efuse_table_gen.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  1. #!/usr/bin/env python
  2. #
  3. # ESP32 efuse table generation tool
  4. #
  5. # Converts efuse table to header file efuse_table.h.
  6. #
  7. # Copyright 2017-2018 Espressif Systems (Shanghai) PTE LTD
  8. #
  9. # Licensed under the Apache License, Version 2.0 (the "License");
  10. # you may not use this file except in compliance with the License.
  11. # You may obtain a copy of the License at
  12. #
  13. # http:#www.apache.org/licenses/LICENSE-2.0
  14. #
  15. # Unless required by applicable law or agreed to in writing, software
  16. # distributed under the License is distributed on an "AS IS" BASIS,
  17. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18. # See the License for the specific language governing permissions and
  19. # limitations under the License.
  20. from __future__ import print_function, division
  21. import argparse
  22. import os
  23. import re
  24. import sys
  25. import hashlib
  26. __version__ = '1.0'
  27. quiet = False
  28. max_blk_len = 256
  29. idf_target = "esp32"
  30. copyright = '''// Copyright 2017-2018 Espressif Systems (Shanghai) PTE LTD
  31. //
  32. // Licensed under the Apache License, Version 2.0 (the "License");
  33. // you may not use this file except in compliance with the License.
  34. // You may obtain a copy of the License at",
  35. //
  36. // http://www.apache.org/licenses/LICENSE-2.0
  37. //
  38. // Unless required by applicable law or agreed to in writing, software
  39. // distributed under the License is distributed on an "AS IS" BASIS,
  40. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  41. // See the License for the specific language governing permissions and
  42. // limitations under the License
  43. '''
  44. def status(msg):
  45. """ Print status message to stderr """
  46. if not quiet:
  47. critical(msg)
  48. def critical(msg):
  49. """ Print critical message to stderr """
  50. sys.stderr.write(msg)
  51. sys.stderr.write('\n')
  52. class FuseTable(list):
  53. def __init__(self):
  54. super(FuseTable, self).__init__(self)
  55. self.md5_digest_table = ""
  56. @classmethod
  57. def from_csv(cls, csv_contents):
  58. res = FuseTable()
  59. lines = csv_contents.splitlines()
  60. def expand_vars(f):
  61. f = os.path.expandvars(f)
  62. m = re.match(r'(?<!\\)\$([A-Za-z_][A-Za-z0-9_]*)', f)
  63. if m:
  64. raise InputError("unknown variable '%s'" % (m.group(1)))
  65. return f
  66. for line_no in range(len(lines)):
  67. line = expand_vars(lines[line_no]).strip()
  68. if line.startswith("#") or len(line) == 0:
  69. continue
  70. try:
  71. res.append(FuseDefinition.from_csv(line))
  72. except InputError as e:
  73. raise InputError("Error at line %d: %s" % (line_no + 1, e))
  74. except Exception:
  75. critical("Unexpected error parsing line %d: %s" % (line_no + 1, line))
  76. raise
  77. # fix up missing bit_start
  78. last_efuse_block = None
  79. for e in res:
  80. if last_efuse_block != e.efuse_block:
  81. last_end = 0
  82. if e.bit_start is None:
  83. e.bit_start = last_end
  84. last_end = e.bit_start + e.bit_count
  85. last_efuse_block = e.efuse_block
  86. res.verify_duplicate_name()
  87. # fix up missing field_name
  88. last_field = None
  89. for e in res:
  90. if e.field_name == "" and last_field is None:
  91. raise InputError("Error at line %d: %s missing field name" % (line_no + 1, e))
  92. elif e.field_name == "" and last_field is not None:
  93. e.field_name = last_field.field_name
  94. last_field = e
  95. # fill group
  96. names = [p.field_name for p in res]
  97. duplicates = set(n for n in names if names.count(n) > 1)
  98. for dname in duplicates:
  99. i_count = 0
  100. for p in res:
  101. if p.field_name != dname:
  102. continue
  103. if len(duplicates.intersection([p.field_name])) != 0:
  104. p.group = str(i_count)
  105. i_count += 1
  106. else:
  107. i_count = 0
  108. res.verify_duplicate_name()
  109. # clac md5 for table
  110. res.calc_md5()
  111. return res
  112. def verify_duplicate_name(self):
  113. # check on duplicate name
  114. names = [p.field_name for p in self]
  115. duplicates = set(n for n in names if names.count(n) > 1)
  116. # print sorted duplicate partitions by name
  117. if len(duplicates) != 0:
  118. fl_error = False
  119. for p in self:
  120. field_name = p.field_name + p.group
  121. if field_name != "" and len(duplicates.intersection([field_name])) != 0:
  122. fl_error = True
  123. print("Field at %s, %s, %s, %s have dublicate field_name" %
  124. (p.field_name, p.efuse_block, p.bit_start, p.bit_count))
  125. if fl_error is True:
  126. raise InputError("Field names must be unique")
  127. def verify(self, type_table=None):
  128. for p in self:
  129. p.verify(type_table)
  130. self.verify_duplicate_name()
  131. # check for overlaps
  132. last = None
  133. for p in sorted(self, key=lambda x:(x.efuse_block, x.bit_start)):
  134. if last is not None and last.efuse_block == p.efuse_block and p.bit_start < last.bit_start + last.bit_count:
  135. raise InputError("Field at %s, %s, %s, %s overlaps %s, %s, %s, %s" %
  136. (p.field_name, p.efuse_block, p.bit_start, p.bit_count,
  137. last.field_name, last.efuse_block, last.bit_start, last.bit_count))
  138. last = p
  139. def calc_md5(self):
  140. txt_table = ''
  141. for p in self:
  142. txt_table += "%s %s %d %s %s" % (p.field_name, p.efuse_block, p.bit_start, str(p.get_bit_count()), p.comment) + "\n"
  143. self.md5_digest_table = hashlib.md5(txt_table.encode('utf-8')).hexdigest()
  144. def show_range_used_bits(self):
  145. # print used and free bits
  146. rows = ''
  147. rows += 'Sorted efuse table:\n'
  148. num = 1
  149. rows += "{0} \t{1:<30} \t{2} \t{3} \t{4}".format("#", "field_name", "efuse_block", "bit_start", "bit_count") + "\n"
  150. for p in sorted(self, key=lambda x:(x.efuse_block, x.bit_start)):
  151. rows += "{0} \t{1:<30} \t{2} \t{3:^8} \t{4:^8}".format(num, p.field_name, p.efuse_block, p.bit_start, p.bit_count) + "\n"
  152. num += 1
  153. rows += '\nUsed bits in efuse table:\n'
  154. last = None
  155. for p in sorted(self, key=lambda x:(x.efuse_block, x.bit_start)):
  156. if last is None:
  157. rows += '%s \n[%d ' % (p.efuse_block, p.bit_start)
  158. if last is not None:
  159. if last.efuse_block != p.efuse_block:
  160. rows += '%d] \n\n%s \n[%d ' % (last.bit_start + last.bit_count - 1, p.efuse_block, p.bit_start)
  161. elif last.bit_start + last.bit_count != p.bit_start:
  162. rows += '%d] [%d ' % (last.bit_start + last.bit_count - 1, p.bit_start)
  163. last = p
  164. rows += '%d] \n' % (last.bit_start + last.bit_count - 1)
  165. rows += '\nNote: Not printed ranges are free for using. (bits in EFUSE_BLK0 are reserved for Espressif)\n'
  166. return rows
  167. def get_str_position_last_free_bit_in_blk(self, blk):
  168. last_used_bit = 0
  169. for p in self:
  170. if p.efuse_block == blk:
  171. if p.define is not None:
  172. return p.get_bit_count()
  173. else:
  174. if last_used_bit < p.bit_start + p.bit_count:
  175. last_used_bit = p.bit_start + p.bit_count
  176. if last_used_bit == 0:
  177. return None
  178. return str(last_used_bit)
  179. def to_header(self, file_name):
  180. rows = [copyright]
  181. rows += ["#ifdef __cplusplus",
  182. 'extern "C" {',
  183. "#endif",
  184. "",
  185. "",
  186. "// md5_digest_table " + self.md5_digest_table,
  187. "// This file was generated from the file " + file_name + ".csv. DO NOT CHANGE THIS FILE MANUALLY.",
  188. "// If you want to change some fields, you need to change " + file_name + ".csv file",
  189. "// then run `efuse_common_table` or `efuse_custom_table` command it will generate this file.",
  190. "// To show efuse_table run the command 'show_efuse_table'.",
  191. "",
  192. ""]
  193. last_field_name = ''
  194. for p in self:
  195. if (p.field_name != last_field_name):
  196. rows += ["extern const esp_efuse_desc_t* " + "ESP_EFUSE_" + p.field_name + "[];"]
  197. last_field_name = p.field_name
  198. rows += ["",
  199. "#ifdef __cplusplus",
  200. "}",
  201. "#endif",
  202. ""]
  203. return '\n'.join(rows) + "\n"
  204. def to_c_file(self, file_name, debug):
  205. rows = [copyright]
  206. rows += ['#include "sdkconfig.h"',
  207. '#include "esp_efuse.h"',
  208. '#include <assert.h>',
  209. '#include "' + file_name + '.h"',
  210. "",
  211. "// md5_digest_table " + self.md5_digest_table,
  212. "// This file was generated from the file " + file_name + ".csv. DO NOT CHANGE THIS FILE MANUALLY.",
  213. "// If you want to change some fields, you need to change " + file_name + ".csv file",
  214. "// then run `efuse_common_table` or `efuse_custom_table` command it will generate this file.",
  215. "// To show efuse_table run the command 'show_efuse_table'."]
  216. rows += [""]
  217. if idf_target == "esp32":
  218. rows += ["#define MAX_BLK_LEN CONFIG_EFUSE_MAX_BLK_LEN"]
  219. rows += [""]
  220. last_free_bit_blk1 = self.get_str_position_last_free_bit_in_blk("EFUSE_BLK1")
  221. last_free_bit_blk2 = self.get_str_position_last_free_bit_in_blk("EFUSE_BLK2")
  222. last_free_bit_blk3 = self.get_str_position_last_free_bit_in_blk("EFUSE_BLK3")
  223. rows += ["// The last free bit in the block is counted over the entire file."]
  224. if last_free_bit_blk1 is not None:
  225. rows += ["#define LAST_FREE_BIT_BLK1 " + last_free_bit_blk1]
  226. if last_free_bit_blk2 is not None:
  227. rows += ["#define LAST_FREE_BIT_BLK2 " + last_free_bit_blk2]
  228. if last_free_bit_blk3 is not None:
  229. rows += ["#define LAST_FREE_BIT_BLK3 " + last_free_bit_blk3]
  230. rows += [""]
  231. if last_free_bit_blk1 is not None:
  232. rows += ['_Static_assert(LAST_FREE_BIT_BLK1 <= MAX_BLK_LEN, "The eFuse table does not match the coding scheme. '
  233. 'Edit the table and restart the efuse_common_table or efuse_custom_table command to regenerate the new files.");']
  234. if last_free_bit_blk2 is not None:
  235. rows += ['_Static_assert(LAST_FREE_BIT_BLK2 <= MAX_BLK_LEN, "The eFuse table does not match the coding scheme. '
  236. 'Edit the table and restart the efuse_common_table or efuse_custom_table command to regenerate the new files.");']
  237. if last_free_bit_blk3 is not None:
  238. rows += ['_Static_assert(LAST_FREE_BIT_BLK3 <= MAX_BLK_LEN, "The eFuse table does not match the coding scheme. '
  239. 'Edit the table and restart the efuse_common_table or efuse_custom_table command to regenerate the new files.");']
  240. rows += [""]
  241. last_name = ''
  242. for p in self:
  243. if (p.field_name != last_name):
  244. if last_name != '':
  245. rows += ["};\n"]
  246. rows += ["static const esp_efuse_desc_t " + p.field_name + "[] = {"]
  247. last_name = p.field_name
  248. rows += [p.to_struct(debug) + ","]
  249. rows += ["};\n"]
  250. rows += ["\n\n\n"]
  251. last_name = ''
  252. for p in self:
  253. if (p.field_name != last_name):
  254. if last_name != '':
  255. rows += [" NULL",
  256. "};\n"]
  257. rows += ["const esp_efuse_desc_t* " + "ESP_EFUSE_" + p.field_name + "[] = {"]
  258. last_name = p.field_name
  259. index = str(0) if str(p.group) == "" else str(p.group)
  260. rows += [" &" + p.field_name + "[" + index + "], \t\t// " + p.comment]
  261. rows += [" NULL",
  262. "};\n"]
  263. return '\n'.join(rows) + "\n"
  264. class FuseDefinition(object):
  265. def __init__(self):
  266. self.field_name = ""
  267. self.group = ""
  268. self.efuse_block = ""
  269. self.bit_start = None
  270. self.bit_count = None
  271. self.define = None
  272. self.comment = ""
  273. @classmethod
  274. def from_csv(cls, line):
  275. """ Parse a line from the CSV """
  276. line_w_defaults = line + ",,,," # lazy way to support default fields
  277. fields = [f.strip() for f in line_w_defaults.split(",")]
  278. res = FuseDefinition()
  279. res.field_name = fields[0]
  280. res.efuse_block = res.parse_block(fields[1])
  281. res.bit_start = res.parse_num(fields[2])
  282. res.bit_count = res.parse_bit_count(fields[3])
  283. if res.bit_count is None or res.bit_count == 0:
  284. raise InputError("Field bit_count can't be empty")
  285. res.comment = fields[4]
  286. return res
  287. def parse_num(self, strval):
  288. if strval == "":
  289. return None # Field will fill in default
  290. return self.parse_int(strval)
  291. def parse_bit_count(self, strval):
  292. if strval == "MAX_BLK_LEN":
  293. self.define = strval
  294. return self.get_max_bits_of_block()
  295. else:
  296. return self.parse_num(strval)
  297. def parse_int(self, v):
  298. try:
  299. return int(v, 0)
  300. except ValueError:
  301. raise InputError("Invalid field value %s" % v)
  302. def parse_block(self, strval):
  303. if strval == "":
  304. raise InputError("Field 'efuse_block' can't be left empty.")
  305. if idf_target == "esp32":
  306. if strval not in ["EFUSE_BLK0", "EFUSE_BLK1", "EFUSE_BLK2", "EFUSE_BLK3"]:
  307. raise InputError("Field 'efuse_block' should be one of EFUSE_BLK0..EFUSE_BLK3")
  308. if idf_target == "esp32s2":
  309. if strval not in ["EFUSE_BLK0", "EFUSE_BLK1", "EFUSE_BLK2", "EFUSE_BLK3", "EFUSE_BLK4",
  310. "EFUSE_BLK5", "EFUSE_BLK6", "EFUSE_BLK7", "EFUSE_BLK8", "EFUSE_BLK9",
  311. "EFUSE_BLK10"]:
  312. raise InputError("Field 'efuse_block' should be one of EFUSE_BLK0..EFUSE_BLK10")
  313. return strval
  314. def get_max_bits_of_block(self):
  315. '''common_table: EFUSE_BLK0, EFUSE_BLK1, EFUSE_BLK2, EFUSE_BLK3
  316. custom_table: ----------, ----------, ----------, EFUSE_BLK3(some reserved in common_table)
  317. '''
  318. if self.efuse_block == "EFUSE_BLK0":
  319. return 256
  320. else:
  321. return max_blk_len
  322. def verify(self, type_table):
  323. if self.efuse_block is None:
  324. raise ValidationError(self, "efuse_block field is not set")
  325. if self.bit_count is None:
  326. raise ValidationError(self, "bit_count field is not set")
  327. if type_table is not None:
  328. if type_table == "custom_table":
  329. if self.efuse_block != "EFUSE_BLK3":
  330. raise ValidationError(self, "custom_table should use only EFUSE_BLK3")
  331. max_bits = self.get_max_bits_of_block()
  332. if self.bit_start + self.bit_count > max_bits:
  333. raise ValidationError(self, "The field is outside the boundaries(max_bits = %d) of the %s block" % (max_bits, self.efuse_block))
  334. def get_full_name(self):
  335. def get_postfix(group):
  336. postfix = ""
  337. if group != "":
  338. postfix = "_PART_" + group
  339. return postfix
  340. return self.field_name + get_postfix(self.group)
  341. def get_bit_count(self, check_define=True):
  342. if check_define is True and self.define is not None:
  343. return self.define
  344. else:
  345. return self.bit_count
  346. def to_struct(self, debug):
  347. start = " {"
  348. if debug is True:
  349. start = " {" + '"' + self.field_name + '" ,'
  350. return ", ".join([start + self.efuse_block,
  351. str(self.bit_start),
  352. str(self.get_bit_count()) + "}, \t // " + self.comment])
  353. def process_input_file(file, type_table):
  354. status("Parsing efuse CSV input file " + file.name + " ...")
  355. input = file.read()
  356. table = FuseTable.from_csv(input)
  357. status("Verifying efuse table...")
  358. table.verify(type_table)
  359. return table
  360. def ckeck_md5_in_file(md5, filename):
  361. if os.path.exists(filename):
  362. with open(filename, 'r') as f:
  363. for line in f:
  364. if md5 in line:
  365. return True
  366. return False
  367. def create_output_files(name, output_table, debug):
  368. file_name = os.path.splitext(os.path.basename(name))[0]
  369. gen_dir = os.path.dirname(name)
  370. dir_for_file_h = gen_dir + "/include"
  371. try:
  372. os.stat(dir_for_file_h)
  373. except Exception:
  374. os.mkdir(dir_for_file_h)
  375. file_h_path = os.path.join(dir_for_file_h, file_name + ".h")
  376. file_c_path = os.path.join(gen_dir, file_name + ".c")
  377. # src files are the same
  378. if ckeck_md5_in_file(output_table.md5_digest_table, file_c_path) is False:
  379. status("Creating efuse *.h file " + file_h_path + " ...")
  380. output = output_table.to_header(file_name)
  381. with open(file_h_path, 'w') as f:
  382. f.write(output)
  383. status("Creating efuse *.c file " + file_c_path + " ...")
  384. output = output_table.to_c_file(file_name, debug)
  385. with open(file_c_path, 'w') as f:
  386. f.write(output)
  387. else:
  388. print("Source files do not require updating correspond to csv file.")
  389. def main():
  390. if sys.version_info[0] < 3:
  391. print("WARNING: Support for Python 2 is deprecated and will be removed in future versions.", file=sys.stderr)
  392. elif sys.version_info[0] == 3 and sys.version_info[1] < 6:
  393. print("WARNING: Python 3 versions older than 3.6 are not supported.", file=sys.stderr)
  394. global quiet
  395. global max_blk_len
  396. global idf_target
  397. parser = argparse.ArgumentParser(description='ESP32 eFuse Manager')
  398. parser.add_argument('--idf_target', '-t', help='Target chip type', choices=['esp32','esp32s2'], default='esp32')
  399. parser.add_argument('--quiet', '-q', help="Don't print non-critical status messages to stderr", action='store_true')
  400. parser.add_argument('--debug', help='Create header file with debug info', default=False, action="store_false")
  401. parser.add_argument('--info', help='Print info about range of used bits', default=False, action="store_true")
  402. parser.add_argument('--max_blk_len', help='Max number of bits in BLOCKs', type=int, default=256)
  403. parser.add_argument('common_input', help='Path to common CSV file to parse.', type=argparse.FileType('r'))
  404. parser.add_argument('custom_input', help='Path to custom CSV file to parse.', type=argparse.FileType('r'), nargs='?', default=None)
  405. args = parser.parse_args()
  406. idf_target = args.idf_target
  407. max_blk_len = args.max_blk_len
  408. print("Max number of bits in BLK %d" % (max_blk_len))
  409. if max_blk_len not in [256, 192, 128]:
  410. raise InputError("Unsupported block length = %d" % (max_blk_len))
  411. quiet = args.quiet
  412. debug = args.debug
  413. info = args.info
  414. common_table = process_input_file(args.common_input, "common_table")
  415. two_table = common_table
  416. if args.custom_input is not None:
  417. custom_table = process_input_file(args.custom_input, "custom_table")
  418. two_table += custom_table
  419. two_table.verify()
  420. # save files.
  421. if info is False:
  422. if args.custom_input is None:
  423. create_output_files(args.common_input.name, common_table, debug)
  424. else:
  425. create_output_files(args.custom_input.name, custom_table, debug)
  426. else:
  427. print(two_table.show_range_used_bits())
  428. return 0
  429. class InputError(RuntimeError):
  430. def __init__(self, e):
  431. super(InputError, self).__init__(e)
  432. class ValidationError(InputError):
  433. def __init__(self, p, message):
  434. super(ValidationError, self).__init__("Entry %s invalid: %s" % (p.field_name, message))
  435. if __name__ == '__main__':
  436. try:
  437. main()
  438. except InputError as e:
  439. print(e, file=sys.stderr)
  440. sys.exit(2)