microcode-tool.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  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. for line in fd:
  90. line = line.rstrip()
  91. # Omit anything after the last comma
  92. words = line.split(',')[:-1]
  93. data += [word + ',' for word in words]
  94. microcodes[name] = Microcode(name, data)
  95. return date, license_text, microcodes
  96. def List(date, microcodes, model):
  97. """List the available microcode chunks
  98. Args:
  99. date: Date of the microcode file
  100. microcodes: Dict of Microcode objects indexed by name
  101. model: Model string to search for, or None
  102. """
  103. print 'Date: %s' % date
  104. if model:
  105. mcode_list, tried = FindMicrocode(microcodes, model.lower())
  106. print 'Matching models %s:' % (', '.join(tried))
  107. else:
  108. print 'All models:'
  109. mcode_list = [microcodes[m] for m in microcodes.keys()]
  110. for mcode in mcode_list:
  111. print '%-20s: model %s' % (mcode.name, mcode.model)
  112. def FindMicrocode(microcodes, model):
  113. """Find all the microcode chunks which match the given model.
  114. This model is something like 306a9 (the value returned in eax from
  115. cpuid(1) when running on Intel CPUs). But we allow a partial match,
  116. omitting the last 1 or two characters to allow many families to have the
  117. same microcode.
  118. If the model name is ambiguous we return a list of matches.
  119. Args:
  120. microcodes: Dict of Microcode objects indexed by name
  121. model: String containing model name to find
  122. Returns:
  123. Tuple:
  124. List of matching Microcode objects
  125. List of abbreviations we tried
  126. """
  127. # Allow a full name to be used
  128. mcode = microcodes.get(model)
  129. if mcode:
  130. return [mcode], []
  131. tried = []
  132. found = []
  133. for i in range(3):
  134. abbrev = model[:-i] if i else model
  135. tried.append(abbrev)
  136. for mcode in microcodes.values():
  137. if mcode.model.startswith(abbrev):
  138. found.append(mcode)
  139. if found:
  140. break
  141. return found, tried
  142. def CreateFile(date, license_text, mcodes, outfile):
  143. """Create a microcode file in U-Boot's .dtsi format
  144. Args:
  145. date: String containing date of original microcode file
  146. license: List of text lines for the license file
  147. mcodes: Microcode objects to write (normally only 1)
  148. outfile: Filename to write to ('-' for stdout)
  149. """
  150. out = '''/*%s
  151. * ---
  152. * This is a device tree fragment. Use #include to add these properties to a
  153. * node.
  154. *
  155. * Date: %s
  156. */
  157. compatible = "intel,microcode";
  158. intel,header-version = <%d>;
  159. intel,update-revision = <%#x>;
  160. intel,date-code = <%#x>;
  161. intel,processor-signature = <%#x>;
  162. intel,checksum = <%#x>;
  163. intel,loader-revision = <%d>;
  164. intel,processor-flags = <%#x>;
  165. /* The first 48-bytes are the public header which repeats the above data */
  166. data = <%s
  167. \t>;'''
  168. words = ''
  169. add_comments = len(mcodes) > 1
  170. for mcode in mcodes:
  171. if add_comments:
  172. words += '\n/* %s */' % mcode.name
  173. for i in range(len(mcode.words)):
  174. if not (i & 3):
  175. words += '\n'
  176. val = mcode.words[i]
  177. # Change each word so it will be little-endian in the FDT
  178. # This data is needed before RAM is available on some platforms so
  179. # we cannot do an endianness swap on boot.
  180. val = struct.unpack("<I", struct.pack(">I", val))[0]
  181. words += '\t%#010x' % val
  182. # Use the first microcode for the headers
  183. mcode = mcodes[0]
  184. # Take care to avoid adding a space before a tab
  185. text = ''
  186. for line in license_text:
  187. if line[0] == '\t':
  188. text += '\n *' + line
  189. else:
  190. text += '\n * ' + line
  191. args = [text, date]
  192. args += [mcode.words[i] for i in range(7)]
  193. args.append(words)
  194. if outfile == '-':
  195. print out % tuple(args)
  196. else:
  197. if not outfile:
  198. if not os.path.exists(MICROCODE_DIR):
  199. print >> sys.stderr, "Creating directory '%s'" % MICROCODE_DIR
  200. os.makedirs(MICROCODE_DIR)
  201. outfile = os.path.join(MICROCODE_DIR, mcode.name + '.dtsi')
  202. print >> sys.stderr, "Writing microcode for '%s' to '%s'" % (
  203. ', '.join([mcode.name for mcode in mcodes]), outfile)
  204. with open(outfile, 'w') as fd:
  205. print >> fd, out % tuple(args)
  206. def MicrocodeTool():
  207. """Run the microcode tool"""
  208. commands = 'create,license,list'.split(',')
  209. parser = OptionParser()
  210. parser.add_option('-d', '--mcfile', type='string', action='store',
  211. help='Name of microcode.dat file')
  212. parser.add_option('-H', '--headerfile', type='string', action='append',
  213. help='Name of .h file containing microcode')
  214. parser.add_option('-m', '--model', type='string', action='store',
  215. help="Model name to extract ('all' for all)")
  216. parser.add_option('-M', '--multiple', type='string', action='store',
  217. help="Allow output of multiple models")
  218. parser.add_option('-o', '--outfile', type='string', action='store',
  219. help='Filename to use for output (- for stdout), default is'
  220. ' %s/<name>.dtsi' % MICROCODE_DIR)
  221. parser.usage += """ command
  222. Process an Intel microcode file (use -h for help). Commands:
  223. create Create microcode .dtsi file for a model
  224. list List available models in microcode file
  225. license Print the license
  226. Typical usage:
  227. ./tools/microcode-tool -d microcode.dat -m 306a create
  228. This will find the appropriate file and write it to %s.""" % MICROCODE_DIR
  229. (options, args) = parser.parse_args()
  230. if not args:
  231. parser.error('Please specify a command')
  232. cmd = args[0]
  233. if cmd not in commands:
  234. parser.error("Unknown command '%s'" % cmd)
  235. if (not not options.mcfile) != (not not options.mcfile):
  236. parser.error("You must specify either header files or a microcode file, not both")
  237. if options.headerfile:
  238. date, license_text, microcodes = ParseHeaderFiles(options.headerfile)
  239. elif options.mcfile:
  240. date, license_text, microcodes = ParseFile(options.mcfile)
  241. else:
  242. parser.error('You must specify a microcode file (or header files)')
  243. if cmd == 'list':
  244. List(date, microcodes, options.model)
  245. elif cmd == 'license':
  246. print '\n'.join(license_text)
  247. elif cmd == 'create':
  248. if not options.model:
  249. parser.error('You must specify a model to create')
  250. model = options.model.lower()
  251. if options.model == 'all':
  252. options.multiple = True
  253. mcode_list = microcodes.values()
  254. tried = []
  255. else:
  256. mcode_list, tried = FindMicrocode(microcodes, model)
  257. if not mcode_list:
  258. parser.error("Unknown model '%s' (%s) - try 'list' to list" %
  259. (model, ', '.join(tried)))
  260. if not options.multiple and len(mcode_list) > 1:
  261. parser.error("Ambiguous model '%s' (%s) matched %s - try 'list' "
  262. "to list or specify a particular file" %
  263. (model, ', '.join(tried),
  264. ', '.join([m.name for m in mcode_list])))
  265. CreateFile(date, license_text, mcode_list, options.outfile)
  266. else:
  267. parser.error("Unknown command '%s'" % cmd)
  268. if __name__ == "__main__":
  269. MicrocodeTool()