chip.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575
  1. """
  2. # TOP2049 Open Source programming suite
  3. #
  4. # Chip support
  5. #
  6. # Copyright (c) 2009-2017 Michael Buesch <m@bues.ch>
  7. #
  8. # This program is free software; you can redistribute it and/or modify
  9. # it under the terms of the GNU General Public License as published by
  10. # the Free Software Foundation; either version 2 of the License, or
  11. # (at your option) any later version.
  12. #
  13. # This program is distributed in the hope that it will be useful,
  14. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. # GNU General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU General Public License along
  19. # with this program; if not, write to the Free Software Foundation, Inc.,
  20. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  21. """
  22. from .util import *
  23. from .layout_generator import *
  24. from .user_interface import *
  25. from .generic_algorithms import *
  26. from .ihex import *
  27. class Chip(object):
  28. SUPPORT_ERASE = (1 << 0)
  29. SUPPORT_SIGREAD = (1 << 1)
  30. SUPPORT_PROGMEMREAD = (1 << 2)
  31. SUPPORT_PROGMEMWRITE = (1 << 3)
  32. SUPPORT_EEPROMREAD = (1 << 4)
  33. SUPPORT_EEPROMWRITE = (1 << 5)
  34. SUPPORT_FUSEREAD = (1 << 6)
  35. SUPPORT_FUSEWRITE = (1 << 7)
  36. SUPPORT_LOCKREAD = (1 << 8)
  37. SUPPORT_LOCKWRITE = (1 << 9)
  38. SUPPORT_RAMREAD = (1 << 10)
  39. SUPPORT_RAMWRITE = (1 << 11)
  40. SUPPORT_TEST = (1 << 12)
  41. SUPPORT_UILREAD = (1 << 13)
  42. SUPPORT_UILWRITE = (1 << 14)
  43. @classmethod
  44. def chipSupportsAttr(cls, methodName):
  45. """Check if a chip implementation supports a feature.
  46. 'methodName' is the class member function to check for"""
  47. # This works by checking whether the subclass overloaded
  48. # the member function attribute.
  49. return getattr(cls, methodName) != getattr(Chip, methodName)
  50. @classmethod
  51. def getSupportFlags(cls):
  52. "Get the SUPPORT_... flags for this chip"
  53. flags = 0
  54. for (methodName, flag) in (
  55. ("erase", cls.SUPPORT_ERASE),
  56. ("readSignature", cls.SUPPORT_SIGREAD),
  57. ("readProgmem", cls.SUPPORT_PROGMEMREAD),
  58. ("writeProgmem", cls.SUPPORT_PROGMEMWRITE),
  59. ("readEEPROM", cls.SUPPORT_EEPROMREAD),
  60. ("writeEEPROM", cls.SUPPORT_EEPROMWRITE),
  61. ("readFuse", cls.SUPPORT_FUSEREAD),
  62. ("writeFuse", cls.SUPPORT_FUSEWRITE),
  63. ("readLockbits", cls.SUPPORT_LOCKREAD),
  64. ("writeLockbits", cls.SUPPORT_LOCKWRITE),
  65. ("readRAM", cls.SUPPORT_RAMREAD),
  66. ("writeRAM", cls.SUPPORT_RAMWRITE),
  67. ("test", cls.SUPPORT_TEST),
  68. ("readUserIdLocation", cls.SUPPORT_UILREAD),
  69. ("writeUserIdLocation", cls.SUPPORT_UILWRITE)):
  70. if cls.chipSupportsAttr(methodName):
  71. flags |= flag
  72. return flags
  73. @classmethod
  74. def createInstance(cls, top, chipDescription, assignedChipOptions=()):
  75. instance = cls()
  76. instance.top = top
  77. instance.chipDescription = chipDescription
  78. for acopt in assignedChipOptions:
  79. copt = chipDescription.getChipOption(acopt.name)
  80. if not copt:
  81. raise TOPException("'%s' is not a valid chip option "
  82. "for chip ID '%s'" %\
  83. (acopt.name, chipDescription.chipID))
  84. acopt.detectAndVerifyType(copt)
  85. instance.assignedChipOptions = assignedChipOptions
  86. instance.generateVoltageLayouts()
  87. return instance
  88. def __init__(self, chipPackage=None, chipPinVCC=None, chipPinsVPP=None, chipPinGND=None):
  89. """chipPackage is the ID string for the package.
  90. May be None, if no initial auto-layout is required.
  91. chipPinVCC is the required VCC pin on the package.
  92. chipPinsVPP is the required VPP pin on the package.
  93. chipPinGND is the required GND pin on the package."""
  94. self.__chipPackage = chipPackage
  95. self.__chipPinVCC = chipPinVCC
  96. self.__chipPinsVPP = chipPinsVPP
  97. self.__chipPinGND = chipPinGND
  98. def printWarning(self, message):
  99. self.top.printWarning(self.chipDescription.chipID +\
  100. ": Warning - " + message)
  101. def printInfo(self, message):
  102. self.top.printInfo(self.chipDescription.chipID +\
  103. ": " + message)
  104. def printDebug(self, message):
  105. self.top.printDebug(self.chipDescription.chipID +\
  106. ": Debug - " + message)
  107. def throwError(self, message, always=False):
  108. message = self.chipDescription.chipID + ": " + message
  109. if self.top.getForceLevel() >= 1 and not always:
  110. self.printWarning(message)
  111. else:
  112. raise TOPException(message)
  113. def generateVoltageLayouts(self):
  114. if self.__chipPackage:
  115. self.generator = createLayoutGenerator(self.__chipPackage)
  116. self.generator.setProgrammerType(self.top.getProgrammerType())
  117. self.generator.setPins(vccPin=self.__chipPinVCC,
  118. vppPins=self.__chipPinsVPP,
  119. gndPin=self.__chipPinGND)
  120. self.generator.recalculate()
  121. def getLayoutGenerator(self):
  122. if self.__chipPackage:
  123. return self.generator
  124. return None
  125. def applyVCC(self, turnOn):
  126. "Turn VCC on, using the auto-layout."
  127. if turnOn:
  128. try:
  129. generator = self.generator
  130. except (AttributeError) as e:
  131. self.throwError("BUG: Using auto-layout, but did not initialize it.",
  132. always=True)
  133. generator.applyVCCLayout(self.top)
  134. else:
  135. self.top.vcc.setLayoutMask(0)
  136. def applyVPP(self, turnOn, packagePinsToTurnOn=[]):
  137. """Turn VPP on, using the auto-layout.
  138. packagePinsToTurnOn is a list of pins on the package to drive to VPP.
  139. If it is not passed (or an empty list), all VPP pins of the layout are turned on.
  140. The parameter is unused, if turnOn=False."""
  141. if turnOn:
  142. try:
  143. generator = self.generator
  144. except (AttributeError) as e:
  145. self.throwError("BUG: Using auto-layout, but did not initialize it.",
  146. always=True)
  147. generator.applyVPPLayout(self.top, packagePinsToTurnOn)
  148. else:
  149. self.top.vpp.setLayoutMask(0)
  150. def applyGND(self, turnOn):
  151. "Turn GND on, using the auto-layout."
  152. if turnOn:
  153. try:
  154. generator = self.generator
  155. except (AttributeError) as e:
  156. self.throwError("BUG: Using auto-layout, but did not initialize it.",
  157. always=True)
  158. generator.applyGNDLayout(self.top)
  159. else:
  160. self.top.gnd.setLayoutMask(0)
  161. def progressMeterInit(self, message, nrSteps):
  162. self.top.progressMeterInit(AbstractUserInterface.PROGRESSMETER_CHIPACCESS,
  163. message, nrSteps)
  164. def progressMeterFinish(self):
  165. self.top.progressMeterFinish(AbstractUserInterface.PROGRESSMETER_CHIPACCESS)
  166. def progressMeter(self, step):
  167. self.top.progressMeter(AbstractUserInterface.PROGRESSMETER_CHIPACCESS,
  168. step)
  169. def getChipOptionValue(self, name, default=None):
  170. """Get an AssignedChipOption value that was set by the user.
  171. If no such option is found, it returns 'default'."""
  172. name = name.lower()
  173. for acopt in self.assignedChipOptions:
  174. if acopt.name.lower() == name:
  175. return acopt.value
  176. return default
  177. def shutdownChip(self):
  178. # Override me in the subclass, if required.
  179. self.printDebug("Default chip shutdown")
  180. GenericAlgorithms(self).simpleVoltageShutdown()
  181. def getIHexInterpreter(self):
  182. # Returns the IHEX file interpreter.
  183. # This defaults to the non-section interpreter.
  184. # Override me in the subclass, if required.
  185. return IHexInterpreter()
  186. def readSignature(self):
  187. # Override me in the subclass, if required.
  188. self.throwError("Signature reading not supported",
  189. always=True)
  190. def erase(self):
  191. # Override me in the subclass, if required.
  192. self.throwError("Chip erasing not supported",
  193. always=True)
  194. def test(self):
  195. # Override me in the subclass, if required.
  196. self.throwError("Chip testing not supported",
  197. always=True)
  198. def readProgmem(self):
  199. # Override me in the subclass, if required.
  200. self.throwError("Program memory reading not supported",
  201. always=True)
  202. def writeProgmem(self, image):
  203. # Override me in the subclass, if required.
  204. self.throwError("Program memory writing not supported",
  205. always=True)
  206. def readEEPROM(self):
  207. # Override me in the subclass, if required.
  208. self.throwError("EEPROM reading not supported",
  209. always=True)
  210. def writeEEPROM(self, image):
  211. # Override me in the subclass, if required.
  212. self.throwError("EEPROM writing not supported",
  213. always=True)
  214. def readFuse(self):
  215. # Override me in the subclass, if required.
  216. self.throwError("Fuse reading not supported",
  217. always=True)
  218. def writeFuse(self, image):
  219. # Override me in the subclass, if required.
  220. self.throwError("Fuse writing not supported",
  221. always=True)
  222. def readLockbits(self):
  223. # Override me in the subclass, if required.
  224. self.throwError("Lockbit reading not supported",
  225. always=True)
  226. def writeLockbits(self, image):
  227. # Override me in the subclass, if required.
  228. self.throwError("Lockbit writing not supported",
  229. always=True)
  230. def readRAM(self):
  231. # Override me in the subclass, if required.
  232. self.throwError("RAM reading not supported",
  233. always=True)
  234. def writeRAM(self, image):
  235. # Override me in the subclass, if required.
  236. self.throwError("RAM writing not supported",
  237. always=True)
  238. def readUserIdLocation(self):
  239. # Override me in the subclass, if required.
  240. self.throwError("User ID Location reading not supported",
  241. always=True)
  242. def writeUserIdLocation(self, image):
  243. # Override me in the subclass, if required.
  244. self.throwError("User ID Location writing not supported",
  245. always=True)
  246. __registeredChips = []
  247. def getRegisteredChips():
  248. "Get a list of registered ChipDescriptions"
  249. return __registeredChips
  250. def getRegisteredVendors():
  251. "Returns a dict of 'vendor : [descriptor, ...]' "
  252. vendors = { }
  253. for descriptor in getRegisteredChips():
  254. for vendor in descriptor.chipVendors:
  255. vendors.setdefault(vendor, []).append(descriptor)
  256. return vendors
  257. def _registerChip(chipDesc):
  258. regList = getRegisteredChips()
  259. if chipDesc.chipID in [ cd.chipID for cd in regList ]:
  260. raise TOPException("Chip description registration: "
  261. "The chipID '%s' is not unique." %\
  262. chipDesc.chipID)
  263. regList.append(chipDesc)
  264. class BitDescription:
  265. def __init__(self, bitNr, description):
  266. self.bitNr = bitNr
  267. self.description = description
  268. class ChipOption(object):
  269. TYPE_UNKNOWN = "unknown"
  270. TYPE_BOOL = "bool"
  271. TYPE_INT = "int"
  272. TYPE_FLOAT = "float"
  273. def __init__(self, optType, name, description=""):
  274. self.optType = optType
  275. self.name = name
  276. self.description = description
  277. def __repr__(self):
  278. desc = " / " + self.description if self.description else ""
  279. return "%s (%s%s)" % (self.name, self.optType, desc)
  280. def castValue(self, string):
  281. return None
  282. class ChipOptionBool(ChipOption):
  283. def __init__(self, name, description=""):
  284. ChipOption.__init__(self, ChipOption.TYPE_BOOL,
  285. name, description)
  286. def castValue(self, string):
  287. return str2bool(string)
  288. class ChipOptionInt(ChipOption):
  289. def __init__(self, name, description="", minVal=None, maxVal=None):
  290. ChipOption.__init__(self, ChipOption.TYPE_INT,
  291. name, description)
  292. self.minVal = int(minVal) if minVal is not None else None
  293. self.maxVal = int(maxVal) if minVal is not None else None
  294. def __limitError(self, value):
  295. raise TOPException("%s: Value exceeds limits: %d <= %d <= %d" %\
  296. (self.name, self.minVal, value, self.maxVal))
  297. def castValue(self, string):
  298. try:
  299. value = int(string)
  300. except (ValueError) as e:
  301. return None
  302. if (self.minVal is not None and value < self.minVal) or\
  303. (self.maxVal is not None and value > self.maxVal):
  304. self.__limitError(value)
  305. return value
  306. class ChipOptionFloat(ChipOption):
  307. def __init__(self, name, description="", minVal=None, maxVal=None):
  308. ChipOption.__init__(self, ChipOption.TYPE_FLOAT,
  309. name, description)
  310. self.minVal = float(minVal) if minVal is not None else None
  311. self.maxVal = float(maxVal) if minVal is not None else None
  312. def __limitError(self, value):
  313. raise TOPException("%s: Value exceeds limits: %f <= %f <= %f" %\
  314. (self.name, self.minVal, value, self.maxVal))
  315. def castValue(self, string):
  316. try:
  317. value = float(string)
  318. except (ValueError) as e:
  319. return None
  320. if (self.minVal is not None and value < self.minVal) or\
  321. (self.maxVal is not None and value > self.maxVal):
  322. self.__limitError(value)
  323. return value
  324. class AssignedChipOption(ChipOption):
  325. def __init__(self, name, value):
  326. ChipOption.__init__(self, ChipOption.TYPE_UNKNOWN, name)
  327. self.value = value
  328. def detectAndVerifyType(self, baseOption):
  329. assert(baseOption.optType != self.TYPE_UNKNOWN)
  330. if self.optType != self.TYPE_UNKNOWN:
  331. return
  332. value = baseOption.castValue(self.value)
  333. if value is None:
  334. raise TOPException("Chip option '%s' type mismatch. "
  335. "Must be '%s'." %\
  336. (self.name, baseOption.optType))
  337. self.optType = baseOption.optType
  338. self.value = value
  339. class ChipDescription:
  340. # Possible chip types
  341. TYPE_MCU = 0 # Microcontroller
  342. TYPE_EPROM = 1 # EPROM
  343. TYPE_EEPROM = 2 # EEPROM
  344. TYPE_GAL = 3 # PAL/GAL
  345. TYPE_SRAM = 4 # Static RAM
  346. TYPE_LOGIC = 5 # Logics chip
  347. TYPE_INTERNAL = 999 # For internal use only
  348. def __init__(self, chipImplClass, bitfile, chipID="",
  349. runtimeID=(0,0),
  350. chipType=TYPE_MCU,
  351. chipVendors="Other",
  352. description="", fuseDesc=(), lockbitDesc=(),
  353. packages=None, comment="",
  354. chipOptions=(),
  355. maintainer="Michael Buesch <m@bues.ch>",
  356. broken=False):
  357. """Chip implementation class description.
  358. chipImplClass => The implementation class of the chip.
  359. bitfile => The name of the default bitfile loaded on initialization.
  360. chipID => The chip-ID string. Will default to the bitfile ID string.
  361. runtimeID => The runtime-ID is a tuple of two numbers that uniquely
  362. identifies a loaded FPGA configuration. The first number in the
  363. tuple is an ID number and the second number is a revision number.
  364. chipType => Chip type. Defaults to MCU.
  365. chipVendors => The chip vendor name(s).
  366. description => Human readable chip description string.
  367. fuseDesc => Tuple of fuse bits descriptions (BitDescription(), ...)
  368. lockbitDesc => Tuple of lock bits descriptions (BitDescription(), ...)
  369. packages => List of supported packages.
  370. Each entry is a tuple of two strings: ("PACKAGE", "description")
  371. comment => Additional comment string.
  372. chipOptions => Tuple of ChipOption instances, if any.
  373. maintainer => Maintainer name.
  374. broken => Boolean flag to mark the implementation as broken.
  375. """
  376. if not chipID:
  377. chipID = bitfile
  378. if isinstance(chipVendors, str):
  379. chipVendors = (chipVendors, )
  380. self.chipImplClass = chipImplClass
  381. self.bitfile = bitfile
  382. self.chipID = chipID
  383. self.runtimeID = runtimeID
  384. self.chipType = chipType
  385. self.chipVendors = chipVendors
  386. self.description = description
  387. self.fuseDesc = fuseDesc
  388. self.lockbitDesc = lockbitDesc
  389. self.packages = packages
  390. self.comment = comment
  391. self.chipOptions = chipOptions
  392. self.maintainer = maintainer
  393. self.broken = broken
  394. _registerChip(self)
  395. @classmethod
  396. def findAll(cls, chipID, allowBroken=False):
  397. "Find all ChipDescriptions by fuzzy chipID match."
  398. found = [ chipDesc for chipDesc in getRegisteredChips() if (
  399. (not chipDesc.broken or allowBroken) and\
  400. (chipDesc.chipID.lower().find(chipID.lower()) >= 0)
  401. ) ]
  402. return found
  403. @classmethod
  404. def findOne(cls, chipID, allowBroken=False):
  405. """Find a chip implementation and return the ChipDescriptor.
  406. Raise an exception, if chipID is not unique."""
  407. found = cls.findAll(chipID, allowBroken)
  408. if not found:
  409. raise TOPException("Did not find chipID \"%s\"" % chipID)
  410. if len(found) != 1:
  411. choices = [ desc.chipID for desc in found ]
  412. raise TOPException(
  413. "The chipID \"%s\" is not unique. Choices are: %s" %\
  414. (chipID, ", ".join(choices)))
  415. return found[0]
  416. @classmethod
  417. def dumpAll(cls, fd, verbose=1, showBroken=True):
  418. "Dump all supported chips to file fd."
  419. count = 0
  420. for chip in getRegisteredChips():
  421. if chip.broken and not showBroken:
  422. continue
  423. if chip.chipType == cls.TYPE_INTERNAL:
  424. continue
  425. count = count + 1
  426. if count >= 2:
  427. fd.write("\n")
  428. chip.dump(fd, verbose)
  429. def dump(self, fd, verbose=1):
  430. "Dump information about a registered chip to file fd."
  431. if verbose <= 0:
  432. fd.write(self.chipID)
  433. return
  434. def wrline(prefix, content):
  435. # Write a formatted feature line
  436. fd.write("%15s: %s\n" % (prefix, content))
  437. banner = ""
  438. if self.chipVendors:
  439. banner += ", ".join(self.chipVendors) + " "
  440. if self.description:
  441. banner += self.description
  442. else:
  443. banner += self.bitfile
  444. extraFlags = []
  445. if not self.maintainer:
  446. extraFlags.append("Orphaned")
  447. if self.broken:
  448. extraFlags.append("Broken implementation")
  449. if extraFlags:
  450. banner += " (%s)" % "; ".join(extraFlags)
  451. sep = '+' + '-' * (len(banner) + 4) + '+\n'
  452. fd.write(sep + '| ' + banner + ' |\n' + sep)
  453. if verbose >= 1:
  454. wrline("Chip ID", self.chipID)
  455. if verbose >= 2:
  456. bitfile = self.bitfile
  457. if not bitfile.endswith('.bit'):
  458. bitfile += '.bit'
  459. wrline("BIT file", bitfile)
  460. if verbose >= 1:
  461. for opt in self.chipOptions:
  462. wrline("Chip option", str(opt))
  463. if verbose >= 3 and self.packages:
  464. for (package, description) in self.packages:
  465. if description:
  466. description = " (" + description + ")"
  467. wrline("Chip package", package + description)
  468. if verbose >= 4:
  469. supportedFeatures = (
  470. (Chip.SUPPORT_ERASE, "Full chip erase"),
  471. (Chip.SUPPORT_SIGREAD, "Chip signature reading"),
  472. (Chip.SUPPORT_PROGMEMREAD, "Program memory reading (flash)"),
  473. (Chip.SUPPORT_PROGMEMWRITE, "Program memory writing (flash)"),
  474. (Chip.SUPPORT_EEPROMREAD, "(E)EPROM memory reading"),
  475. (Chip.SUPPORT_EEPROMWRITE, "(E)EPROM memory writing"),
  476. (Chip.SUPPORT_FUSEREAD, "Fuse bits reading"),
  477. (Chip.SUPPORT_FUSEWRITE, "Fuse bits writing"),
  478. (Chip.SUPPORT_LOCKREAD, "Lock bits reading"),
  479. (Chip.SUPPORT_LOCKWRITE, "Lock bits writing"),
  480. (Chip.SUPPORT_RAMREAD, "RAM reading"),
  481. (Chip.SUPPORT_RAMWRITE, "RAM writing"),
  482. (Chip.SUPPORT_TEST, "Unit-testing"),
  483. (Chip.SUPPORT_UILMREAD, "User ID Location reading"),
  484. (Chip.SUPPORT_UILWRITE, "User ID Location writing"),
  485. )
  486. supportFlags = self.chipImplClass.getSupportFlags()
  487. for (flag, description) in supportedFeatures:
  488. if flag & supportFlags:
  489. wrline("Support for", description)
  490. if verbose >= 2 and self.comment:
  491. wrline("Comment", self.comment)
  492. if verbose >= 3:
  493. maintainer = self.maintainer
  494. if not maintainer:
  495. maintainer = "NONE"
  496. wrline("Maintainer", maintainer)
  497. def getChipOption(self, name):
  498. "Get a ChipOption by case insensitive 'name'."
  499. name = name.lower()
  500. for opt in self.chipOptions:
  501. if opt.name.lower() == name:
  502. return opt
  503. return None