microcode-tool.py 8.3 KB

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