microcode-tool.py 11 KB

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