blob: 4f1c2beaa3f7836fe5a35d47423ce56418a5fce3 [file] [log] [blame]
b.liu3a41a312024-02-28 09:57:39 +08001/*
2* mbtk_mtd.c
3*
4* MBTK mtd partition utils API.
5*
6*/
7/******************************************************************************
8
9 EDIT HISTORY FOR FILE
10
11 WHEN WHO WHAT,WHERE,WHY
12-------- -------- -------------------------------------------------------
132024/2/26 LiuBin Initial version
14
15******************************************************************************/
16#include <stdio.h>
17#include <stdlib.h>
18#include <unistd.h>
19#include <errno.h>
20
21#include "mbtk_mtd.h"
22#include "mbtk_log.h"
23#include "mbtk_str.h"
24
25static mbtk_partition_info_t partition_list[MBTK_PARTITION_NUM_MAX];
26static bool partition_inited = FALSE;
27
28mbtk_partition_info_t* mbtk_partition_get()
29{
30 if(partition_inited) {
31 return partition_list;
32 }
33
34 memset(partition_list, 0x0, sizeof(partition_list));
35 FILE *fp = fopen("/proc/mtd", "r");
36 if(fp == NULL) {
37 LOGE("fopen(/proc/mtd) fail:%d", errno);
38 return NULL;
39 }
40
41 char buff[64];
42 int index = 0;
43 char size_str[16];
44 char name[32];
45 memset(buff, 0x0, 64);
46 while(fgets(buff, 64, fp)) {
47 if(str_startwith(buff, "mtd")) {
48 memset(size_str, 0x0, 16);
49 memset(name, 0x0, 32);
50 if(3 == sscanf(buff, "%s %s %*s %s", partition_list[index].dev, size_str, name)) {
51 if(name[0] == '\"' && name[strlen(name) - 1] == '\"') {
52 memcpy(partition_list[index].name, name + 1, strlen(name) - 2); // No copy ""
53 } else {
54 LOGE("partition(%s) name error.", buff);
55 return NULL;
56 }
57
58 if(partition_list[index].dev[strlen(partition_list[index].dev) - 1] == ':') {
59 partition_list[index].dev[strlen(partition_list[index].dev) - 1] = '\0';
60 }
61
62 partition_list[index].partition_size = (uint32)strtoul(size_str, NULL, 16);
63 if(index > 0) {
64 partition_list[index].partition_start = partition_list[index - 1].partition_start + partition_list[index - 1].partition_size;
65 }
66 partition_list[index].used = TRUE;
67 } else {
68 LOGE("sscanf(%s) fail:%d", buff, errno);
69 return NULL;
70 }
71 index++;
72 }
73 memset(buff, 0x0, 64);
74 }
75 fclose(fp);
76
77 int i = 0;
78 while(i < MBTK_PARTITION_NUM_MAX) {
79 if(partition_list[i].used) {
80 LOGD("%s(%s) : %08x %08x", partition_list[i].name, partition_list[i].dev,
81 partition_list[i].partition_start, partition_list[i].partition_size);
82 }
83 i++;
84 }
85
86 partition_inited = TRUE;
87 return partition_list;
88}
89
90