PageRenderTime 60ms CodeModel.GetById 34ms RepoModel.GetById 0ms app.codeStats 0ms

/tools/microcode-tool.py

https://gitlab.com/gmbnomis/u-boot
Python | 317 lines | 260 code | 12 blank | 45 comment | 29 complexity | 92778a74bc4dd53fce0cfcce6302670f MD5 | raw file
  1. #!/usr/bin/env python
  2. #
  3. # Copyright (c) 2014 Google, Inc
  4. #
  5. # SPDX-License-Identifier: GPL-2.0+
  6. #
  7. # Intel microcode update tool
  8. from optparse import OptionParser
  9. import os
  10. import re
  11. import struct
  12. import sys
  13. MICROCODE_DIR = 'arch/x86/dts/microcode'
  14. class Microcode:
  15. """Holds information about the microcode for a particular model of CPU.
  16. Attributes:
  17. name: Name of the CPU this microcode is for, including any version
  18. information (e.g. 'm12206a7_00000029')
  19. model: Model code string (this is cpuid(1).eax, e.g. '206a7')
  20. words: List of hex words containing the microcode. The first 16 words
  21. are the public header.
  22. """
  23. def __init__(self, name, data):
  24. self.name = name
  25. # Convert data into a list of hex words
  26. self.words = []
  27. for value in ''.join(data).split(','):
  28. hexval = value.strip()
  29. if hexval:
  30. self.words.append(int(hexval, 0))
  31. # The model is in the 4rd hex word
  32. self.model = '%x' % self.words[3]
  33. def ParseFile(fname):
  34. """Parse a micrcode.dat file and return the component parts
  35. Args:
  36. fname: Filename to parse
  37. Returns:
  38. 3-Tuple:
  39. date: String containing date from the file's header
  40. license_text: List of text lines for the license file
  41. microcodes: List of Microcode objects from the file
  42. """
  43. re_date = re.compile('/\* *(.* [0-9]{4}) *\*/$')
  44. re_license = re.compile('/[^-*+] *(.*)$')
  45. re_name = re.compile('/\* *(.*)\.inc *\*/', re.IGNORECASE)
  46. microcodes = {}
  47. license_text = []
  48. date = ''
  49. data = []
  50. name = None
  51. with open(fname) as fd:
  52. for line in fd:
  53. line = line.rstrip()
  54. m_date = re_date.match(line)
  55. m_license = re_license.match(line)
  56. m_name = re_name.match(line)
  57. if m_name:
  58. if name:
  59. microcodes[name] = Microcode(name, data)
  60. name = m_name.group(1).lower()
  61. data = []
  62. elif m_license:
  63. license_text.append(m_license.group(1))
  64. elif m_date:
  65. date = m_date.group(1)
  66. else:
  67. data.append(line)
  68. if name:
  69. microcodes[name] = Microcode(name, data)
  70. return date, license_text, microcodes
  71. def ParseHeaderFiles(fname_list):
  72. """Parse a list of header files and return the component parts
  73. Args:
  74. fname_list: List of files to parse
  75. Returns:
  76. date: String containing date from the file's header
  77. license_text: List of text lines for the license file
  78. microcodes: List of Microcode objects from the file
  79. """
  80. microcodes = {}
  81. license_text = []
  82. date = ''
  83. name = None
  84. for fname in fname_list:
  85. name = os.path.basename(fname).lower()
  86. name = os.path.splitext(name)[0]
  87. data = []
  88. with open(fname) as fd:
  89. license_start = False
  90. license_end = False
  91. for line in fd:
  92. line = line.rstrip()
  93. if len(line) >= 2:
  94. if line[0] == '/' and line[1] == '*':
  95. license_start = True
  96. continue
  97. if line[0] == '*' and line[1] == '/':
  98. license_end = True
  99. continue
  100. if license_start and not license_end:
  101. # Ignore blank line
  102. if len(line) > 0:
  103. license_text.append(line)
  104. continue
  105. # Omit anything after the last comma
  106. words = line.split(',')[:-1]
  107. data += [word + ',' for word in words]
  108. microcodes[name] = Microcode(name, data)
  109. return date, license_text, microcodes
  110. def List(date, microcodes, model):
  111. """List the available microcode chunks
  112. Args:
  113. date: Date of the microcode file
  114. microcodes: Dict of Microcode objects indexed by name
  115. model: Model string to search for, or None
  116. """
  117. print 'Date: %s' % date
  118. if model:
  119. mcode_list, tried = FindMicrocode(microcodes, model.lower())
  120. print 'Matching models %s:' % (', '.join(tried))
  121. else:
  122. print 'All models:'
  123. mcode_list = [microcodes[m] for m in microcodes.keys()]
  124. for mcode in mcode_list:
  125. print '%-20s: model %s' % (mcode.name, mcode.model)
  126. def FindMicrocode(microcodes, model):
  127. """Find all the microcode chunks which match the given model.
  128. This model is something like 306a9 (the value returned in eax from
  129. cpuid(1) when running on Intel CPUs). But we allow a partial match,
  130. omitting the last 1 or two characters to allow many families to have the
  131. same microcode.
  132. If the model name is ambiguous we return a list of matches.
  133. Args:
  134. microcodes: Dict of Microcode objects indexed by name
  135. model: String containing model name to find
  136. Returns:
  137. Tuple:
  138. List of matching Microcode objects
  139. List of abbreviations we tried
  140. """
  141. # Allow a full name to be used
  142. mcode = microcodes.get(model)
  143. if mcode:
  144. return [mcode], []
  145. tried = []
  146. found = []
  147. for i in range(3):
  148. abbrev = model[:-i] if i else model
  149. tried.append(abbrev)
  150. for mcode in microcodes.values():
  151. if mcode.model.startswith(abbrev):
  152. found.append(mcode)
  153. if found:
  154. break
  155. return found, tried
  156. def CreateFile(date, license_text, mcodes, outfile):
  157. """Create a microcode file in U-Boot's .dtsi format
  158. Args:
  159. date: String containing date of original microcode file
  160. license: List of text lines for the license file
  161. mcodes: Microcode objects to write (normally only 1)
  162. outfile: Filename to write to ('-' for stdout)
  163. """
  164. out = '''/*%s
  165. * ---
  166. * This is a device tree fragment. Use #include to add these properties to a
  167. * node.
  168. *
  169. * Date: %s
  170. */
  171. compatible = "intel,microcode";
  172. intel,header-version = <%d>;
  173. intel,update-revision = <%#x>;
  174. intel,date-code = <%#x>;
  175. intel,processor-signature = <%#x>;
  176. intel,checksum = <%#x>;
  177. intel,loader-revision = <%d>;
  178. intel,processor-flags = <%#x>;
  179. /* The first 48-bytes are the public header which repeats the above data */
  180. data = <%s
  181. \t>;'''
  182. words = ''
  183. add_comments = len(mcodes) > 1
  184. for mcode in mcodes:
  185. if add_comments:
  186. words += '\n/* %s */' % mcode.name
  187. for i in range(len(mcode.words)):
  188. if not (i & 3):
  189. words += '\n'
  190. val = mcode.words[i]
  191. # Change each word so it will be little-endian in the FDT
  192. # This data is needed before RAM is available on some platforms so
  193. # we cannot do an endianness swap on boot.
  194. val = struct.unpack("<I", struct.pack(">I", val))[0]
  195. words += '\t%#010x' % val
  196. # Use the first microcode for the headers
  197. mcode = mcodes[0]
  198. # Take care to avoid adding a space before a tab
  199. text = ''
  200. for line in license_text:
  201. if line[0] == '\t':
  202. text += '\n *' + line
  203. else:
  204. text += '\n * ' + line
  205. args = [text, date]
  206. args += [mcode.words[i] for i in range(7)]
  207. args.append(words)
  208. if outfile == '-':
  209. print out % tuple(args)
  210. else:
  211. if not outfile:
  212. if not os.path.exists(MICROCODE_DIR):
  213. print >> sys.stderr, "Creating directory '%s'" % MICROCODE_DIR
  214. os.makedirs(MICROCODE_DIR)
  215. outfile = os.path.join(MICROCODE_DIR, mcode.name + '.dtsi')
  216. print >> sys.stderr, "Writing microcode for '%s' to '%s'" % (
  217. ', '.join([mcode.name for mcode in mcodes]), outfile)
  218. with open(outfile, 'w') as fd:
  219. print >> fd, out % tuple(args)
  220. def MicrocodeTool():
  221. """Run the microcode tool"""
  222. commands = 'create,license,list'.split(',')
  223. parser = OptionParser()
  224. parser.add_option('-d', '--mcfile', type='string', action='store',
  225. help='Name of microcode.dat file')
  226. parser.add_option('-H', '--headerfile', type='string', action='append',
  227. help='Name of .h file containing microcode')
  228. parser.add_option('-m', '--model', type='string', action='store',
  229. help="Model name to extract ('all' for all)")
  230. parser.add_option('-M', '--multiple', type='string', action='store',
  231. help="Allow output of multiple models")
  232. parser.add_option('-o', '--outfile', type='string', action='store',
  233. help='Filename to use for output (- for stdout), default is'
  234. ' %s/<name>.dtsi' % MICROCODE_DIR)
  235. parser.usage += """ command
  236. Process an Intel microcode file (use -h for help). Commands:
  237. create Create microcode .dtsi file for a model
  238. list List available models in microcode file
  239. license Print the license
  240. Typical usage:
  241. ./tools/microcode-tool -d microcode.dat -m 306a create
  242. This will find the appropriate file and write it to %s.""" % MICROCODE_DIR
  243. (options, args) = parser.parse_args()
  244. if not args:
  245. parser.error('Please specify a command')
  246. cmd = args[0]
  247. if cmd not in commands:
  248. parser.error("Unknown command '%s'" % cmd)
  249. if (not not options.mcfile) != (not not options.mcfile):
  250. parser.error("You must specify either header files or a microcode file, not both")
  251. if options.headerfile:
  252. date, license_text, microcodes = ParseHeaderFiles(options.headerfile)
  253. elif options.mcfile:
  254. date, license_text, microcodes = ParseFile(options.mcfile)
  255. else:
  256. parser.error('You must specify a microcode file (or header files)')
  257. if cmd == 'list':
  258. List(date, microcodes, options.model)
  259. elif cmd == 'license':
  260. print '\n'.join(license_text)
  261. elif cmd == 'create':
  262. if not options.model:
  263. parser.error('You must specify a model to create')
  264. model = options.model.lower()
  265. if options.model == 'all':
  266. options.multiple = True
  267. mcode_list = microcodes.values()
  268. tried = []
  269. else:
  270. mcode_list, tried = FindMicrocode(microcodes, model)
  271. if not mcode_list:
  272. parser.error("Unknown model '%s' (%s) - try 'list' to list" %
  273. (model, ', '.join(tried)))
  274. if not options.multiple and len(mcode_list) > 1:
  275. parser.error("Ambiguous model '%s' (%s) matched %s - try 'list' "
  276. "to list or specify a particular file" %
  277. (model, ', '.join(tried),
  278. ', '.join([m.name for m in mcode_list])))
  279. CreateFile(date, license_text, mcode_list, options.outfile)
  280. else:
  281. parser.error("Unknown command '%s'" % cmd)
  282. if __name__ == "__main__":
  283. MicrocodeTool()