2 * Copyright (C) 2013 Felix Fietkau <nbd@openwrt.org>
3 * Copyright (C) 2013 John Crispin <blogic@openwrt.org>
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU Lesser General Public License version 2.1
7 * as published by the Free Software Foundation
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
15 #include <sys/types.h>
22 #include <libubox/blobmsg_json.h>
24 #define CONFIG_FILE "/etc/boards.json"
25 #define MODEL_FILE "/proc/devicetree/model"
26 #define CPU_INFO "/proc/cpuinfo"
33 static struct blob_buf b
;
35 static const struct blobmsg_policy board_policy
[__BOARD_MAX
] = {
36 [BOARD_ID
] = { .name
= "id", .type
= BLOBMSG_TYPE_STRING
},
39 static char* detect_mips_machine(void)
45 fp
= fopen(CPU_INFO
, "r");
51 while (fgets(line
, sizeof(line
), fp
)) {
52 if (!strncmp(line
, "machine", 7)) {
53 char *machine
= strstr(line
, ": ");
58 machine
[strlen(machine
) - 1] = '\0';
70 static char* detect_devicetree_model(void)
77 if (stat(MODEL_FILE
, &s
) || !S_ISREG(s
.st_mode
))
80 fp
= fopen(MODEL_FILE
, "r");
86 if (!fgets(line
, sizeof(line
), fp
))
94 static char* board_id(struct blob_attr
*msg
)
96 struct blob_attr
*tb
[__BOARD_MAX
];
98 blobmsg_parse(board_policy
, __BOARD_MAX
, tb
, blobmsg_data(msg
), blobmsg_data_len(msg
));
100 return blobmsg_data(tb
[BOARD_ID
]);
105 static void write_file(char *file
, char *val
)
109 fp
= fopen(file
, "w");
119 static int set_board(char *board
, char *boardid
)
122 fprintf(stderr
, "failed to detect board %s\n", board
);
125 printf("detected %s - %s\n", board
, boardid
);
127 mkdir("/tmp/sysinfo", 0755);
129 write_file("/tmp/sysinfo/model", board
);
130 write_file("/tmp/sysinfo/board_name", boardid
);
135 static int load_json(char *file
)
141 if (stat(file
, &s
) || !S_ISREG(s
.st_mode
)) {
142 fprintf(stderr
, "failed to open %s\n", file
);
146 buf
= malloc(s
.st_size
+ 1);
152 fd
= open(file
, O_RDONLY
);
158 if (read(fd
, buf
, s
.st_size
) != s
.st_size
) {
159 fprintf(stderr
, "failed to read %s - %d bytes\n", file
, (int)s
.st_size
);
164 buf
[s
.st_size
] = '\0';
166 blob_buf_init(&b
, 0);
167 if (!blobmsg_add_json_from_string(&b
, buf
)) {
168 fprintf(stderr
, "Failed to read json\n");
176 int main(int argc
, char **argv
)
178 struct blob_attr
*cur
;
182 board
= detect_mips_machine();
184 detect_devicetree_model();
186 fprintf(stderr
, "failed to detect board\n");
190 if (load_json(CONFIG_FILE
))
193 blob_for_each_attr(cur
, b
.head
, rem
) {
194 if (blobmsg_type(cur
) != BLOBMSG_TYPE_TABLE
)
196 if (!strcmp(blobmsg_name(cur
), board
)) {
197 char *id
= board_id(cur
);
200 return set_board(board
, id
);
204 fprintf(stderr
, "failed to identify %s\n", board
);