efuse_table_gen.py 21 KB

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