libfdt.i_shipped 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097
  1. /* SPDX-License-Identifier: GPL-2.0+ OR BSD-2-Clause */
  2. /*
  3. * pylibfdt - Flat Device Tree manipulation in Python
  4. * Copyright (C) 2017 Google, Inc.
  5. * Written by Simon Glass <sjg@chromium.org>
  6. */
  7. %module libfdt
  8. %include <stdint.i>
  9. %{
  10. #define SWIG_FILE_WITH_INIT
  11. #include "libfdt.h"
  12. /*
  13. * We rename this function here to avoid problems with swig, since we also have
  14. * a struct called fdt_property. That struct causes swig to create a class in
  15. * libfdt.py called fdt_property(), which confuses things.
  16. */
  17. static int fdt_property_stub(void *fdt, const char *name, const char *val,
  18. int len)
  19. {
  20. return fdt_property(fdt, name, val, len);
  21. }
  22. %}
  23. %pythoncode %{
  24. import struct
  25. # Error codes, corresponding to FDT_ERR_... in libfdt.h
  26. (NOTFOUND,
  27. EXISTS,
  28. NOSPACE,
  29. BADOFFSET,
  30. BADPATH,
  31. BADPHANDLE,
  32. BADSTATE,
  33. TRUNCATED,
  34. BADMAGIC,
  35. BADVERSION,
  36. BADSTRUCTURE,
  37. BADLAYOUT,
  38. INTERNAL,
  39. BADNCELLS,
  40. BADVALUE,
  41. BADOVERLAY,
  42. NOPHANDLES) = QUIET_ALL = range(1, 18)
  43. # QUIET_ALL can be passed as the 'quiet' parameter to avoid exceptions
  44. # altogether. All # functions passed this value will return an error instead
  45. # of raising an exception.
  46. # Pass this as the 'quiet' parameter to return -ENOTFOUND on NOTFOUND errors,
  47. # instead of raising an exception.
  48. QUIET_NOTFOUND = (NOTFOUND,)
  49. QUIET_NOSPACE = (NOSPACE,)
  50. class FdtException(Exception):
  51. """An exception caused by an error such as one of the codes above"""
  52. def __init__(self, err):
  53. self.err = err
  54. def __str__(self):
  55. return 'pylibfdt error %d: %s' % (self.err, fdt_strerror(self.err))
  56. def strerror(fdt_err):
  57. """Get the string for an error number
  58. Args:
  59. fdt_err: Error number (-ve)
  60. Returns:
  61. String containing the associated error
  62. """
  63. return fdt_strerror(fdt_err)
  64. def check_err(val, quiet=()):
  65. """Raise an error if the return value is -ve
  66. This is used to check for errors returned by libfdt C functions.
  67. Args:
  68. val: Return value from a libfdt function
  69. quiet: Errors to ignore (empty to raise on all errors)
  70. Returns:
  71. val if val >= 0
  72. Raises
  73. FdtException if val < 0
  74. """
  75. if val < 0:
  76. if -val not in quiet:
  77. raise FdtException(val)
  78. return val
  79. def check_err_null(val, quiet=()):
  80. """Raise an error if the return value is NULL
  81. This is used to check for a NULL return value from certain libfdt C
  82. functions
  83. Args:
  84. val: Return value from a libfdt function
  85. quiet: Errors to ignore (empty to raise on all errors)
  86. Returns:
  87. val if val is a list, None if not
  88. Raises
  89. FdtException if val indicates an error was reported and the error
  90. is not in @quiet.
  91. """
  92. # Normally a list is returned which contains the data and its length.
  93. # If we get just an integer error code, it means the function failed.
  94. if not isinstance(val, list):
  95. if -val not in quiet:
  96. raise FdtException(val)
  97. return val
  98. class FdtRo(object):
  99. """Class for a read-only device-tree
  100. This is a base class used by FdtRw (read-write access) and FdtSw
  101. (sequential-write access). It implements read-only access to the
  102. device tree.
  103. Here are the three classes and when you should use them:
  104. FdtRo - read-only access to an existing FDT
  105. FdtRw - read-write access to an existing FDT (most common case)
  106. FdtSw - for creating a new FDT, as well as allowing read-only access
  107. """
  108. def __init__(self, data):
  109. self._fdt = bytearray(data)
  110. check_err(fdt_check_header(self._fdt));
  111. def as_bytearray(self):
  112. """Get the device tree contents as a bytearray
  113. This can be passed directly to libfdt functions that access a
  114. const void * for the device tree.
  115. Returns:
  116. bytearray containing the device tree
  117. """
  118. return bytearray(self._fdt)
  119. def next_node(self, nodeoffset, depth, quiet=()):
  120. """Find the next subnode
  121. Args:
  122. nodeoffset: Node offset of previous node
  123. depth: The depth of the node at nodeoffset. This is used to
  124. calculate the depth of the returned node
  125. quiet: Errors to ignore (empty to raise on all errors)
  126. Returns:
  127. Typle:
  128. Offset of the next node, if any, else a -ve error
  129. Depth of the returned node, if any, else undefined
  130. Raises:
  131. FdtException if no more nodes found or other error occurs
  132. """
  133. return check_err(fdt_next_node(self._fdt, nodeoffset, depth), quiet)
  134. def first_subnode(self, nodeoffset, quiet=()):
  135. """Find the first subnode of a parent node
  136. Args:
  137. nodeoffset: Node offset of parent node
  138. quiet: Errors to ignore (empty to raise on all errors)
  139. Returns:
  140. The offset of the first subnode, if any
  141. Raises:
  142. FdtException if no subnodes found or other error occurs
  143. """
  144. return check_err(fdt_first_subnode(self._fdt, nodeoffset), quiet)
  145. def next_subnode(self, nodeoffset, quiet=()):
  146. """Find the next subnode
  147. Args:
  148. nodeoffset: Node offset of previous subnode
  149. quiet: Errors to ignore (empty to raise on all errors)
  150. Returns:
  151. The offset of the next subnode, if any
  152. Raises:
  153. FdtException if no more subnodes found or other error occurs
  154. """
  155. return check_err(fdt_next_subnode(self._fdt, nodeoffset), quiet)
  156. def magic(self):
  157. """Return the magic word from the header
  158. Returns:
  159. Magic word
  160. """
  161. return fdt_magic(self._fdt)
  162. def totalsize(self):
  163. """Return the total size of the device tree
  164. Returns:
  165. Total tree size in bytes
  166. """
  167. return fdt_totalsize(self._fdt)
  168. def off_dt_struct(self):
  169. """Return the start of the device-tree struct area
  170. Returns:
  171. Start offset of struct area
  172. """
  173. return fdt_off_dt_struct(self._fdt)
  174. def off_dt_strings(self):
  175. """Return the start of the device-tree string area
  176. Returns:
  177. Start offset of string area
  178. """
  179. return fdt_off_dt_strings(self._fdt)
  180. def off_mem_rsvmap(self):
  181. """Return the start of the memory reserve map
  182. Returns:
  183. Start offset of memory reserve map
  184. """
  185. return fdt_off_mem_rsvmap(self._fdt)
  186. def version(self):
  187. """Return the version of the device tree
  188. Returns:
  189. Version number of the device tree
  190. """
  191. return fdt_version(self._fdt)
  192. def last_comp_version(self):
  193. """Return the last compatible version of the device tree
  194. Returns:
  195. Last compatible version number of the device tree
  196. """
  197. return fdt_last_comp_version(self._fdt)
  198. def boot_cpuid_phys(self):
  199. """Return the physical boot CPU ID
  200. Returns:
  201. Physical boot CPU ID
  202. """
  203. return fdt_boot_cpuid_phys(self._fdt)
  204. def size_dt_strings(self):
  205. """Return the start of the device-tree string area
  206. Returns:
  207. Start offset of string area
  208. """
  209. return fdt_size_dt_strings(self._fdt)
  210. def size_dt_struct(self):
  211. """Return the start of the device-tree struct area
  212. Returns:
  213. Start offset of struct area
  214. """
  215. return fdt_size_dt_struct(self._fdt)
  216. def num_mem_rsv(self, quiet=()):
  217. """Return the number of memory reserve-map records
  218. Returns:
  219. Number of memory reserve-map records
  220. """
  221. return check_err(fdt_num_mem_rsv(self._fdt), quiet)
  222. def get_mem_rsv(self, index, quiet=()):
  223. """Return the indexed memory reserve-map record
  224. Args:
  225. index: Record to return (0=first)
  226. Returns:
  227. Number of memory reserve-map records
  228. """
  229. return check_err(fdt_get_mem_rsv(self._fdt, index), quiet)
  230. def subnode_offset(self, parentoffset, name, quiet=()):
  231. """Get the offset of a named subnode
  232. Args:
  233. parentoffset: Offset of the parent node to check
  234. name: Name of the required subnode, e.g. 'subnode@1'
  235. quiet: Errors to ignore (empty to raise on all errors)
  236. Returns:
  237. The node offset of the found node, if any
  238. Raises
  239. FdtException if there is no node with that name, or other error
  240. """
  241. return check_err(fdt_subnode_offset(self._fdt, parentoffset, name),
  242. quiet)
  243. def path_offset(self, path, quiet=()):
  244. """Get the offset for a given path
  245. Args:
  246. path: Path to the required node, e.g. '/node@3/subnode@1'
  247. quiet: Errors to ignore (empty to raise on all errors)
  248. Returns:
  249. Node offset
  250. Raises
  251. FdtException if the path is not valid or not found
  252. """
  253. return check_err(fdt_path_offset(self._fdt, path), quiet)
  254. def get_name(self, nodeoffset):
  255. """Get the name of a node
  256. Args:
  257. nodeoffset: Offset of node to check
  258. Returns:
  259. Node name
  260. Raises:
  261. FdtException on error (e.g. nodeoffset is invalid)
  262. """
  263. return check_err_null(fdt_get_name(self._fdt, nodeoffset))[0]
  264. def first_property_offset(self, nodeoffset, quiet=()):
  265. """Get the offset of the first property in a node offset
  266. Args:
  267. nodeoffset: Offset to the node to check
  268. quiet: Errors to ignore (empty to raise on all errors)
  269. Returns:
  270. Offset of the first property
  271. Raises
  272. FdtException if the associated node has no properties, or some
  273. other error occurred
  274. """
  275. return check_err(fdt_first_property_offset(self._fdt, nodeoffset),
  276. quiet)
  277. def next_property_offset(self, prop_offset, quiet=()):
  278. """Get the next property in a node
  279. Args:
  280. prop_offset: Offset of the previous property
  281. quiet: Errors to ignore (empty to raise on all errors)
  282. Returns:
  283. Offset of the next property
  284. Raises:
  285. FdtException if the associated node has no more properties, or
  286. some other error occurred
  287. """
  288. return check_err(fdt_next_property_offset(self._fdt, prop_offset),
  289. quiet)
  290. def get_property_by_offset(self, prop_offset, quiet=()):
  291. """Obtains a property that can be examined
  292. Args:
  293. prop_offset: Offset of property (e.g. from first_property_offset())
  294. quiet: Errors to ignore (empty to raise on all errors)
  295. Returns:
  296. Property object, or None if not found
  297. Raises:
  298. FdtException on error (e.g. invalid prop_offset or device
  299. tree format)
  300. """
  301. pdata = check_err_null(
  302. fdt_get_property_by_offset(self._fdt, prop_offset), quiet)
  303. if isinstance(pdata, (int)):
  304. return pdata
  305. return Property(pdata[0], pdata[1])
  306. def getprop(self, nodeoffset, prop_name, quiet=()):
  307. """Get a property from a node
  308. Args:
  309. nodeoffset: Node offset containing property to get
  310. prop_name: Name of property to get
  311. quiet: Errors to ignore (empty to raise on all errors)
  312. Returns:
  313. Value of property as a Property object (which can be used as a
  314. bytearray/string), or -ve error number. On failure, returns an
  315. integer error
  316. Raises:
  317. FdtError if any error occurs (e.g. the property is not found)
  318. """
  319. pdata = check_err_null(fdt_getprop(self._fdt, nodeoffset, prop_name),
  320. quiet)
  321. if isinstance(pdata, (int)):
  322. return pdata
  323. return Property(prop_name, bytearray(pdata[0]))
  324. def get_phandle(self, nodeoffset):
  325. """Get the phandle of a node
  326. Args:
  327. nodeoffset: Node offset to check
  328. Returns:
  329. phandle of node, or 0 if the node has no phandle or another error
  330. occurs
  331. """
  332. return fdt_get_phandle(self._fdt, nodeoffset)
  333. def parent_offset(self, nodeoffset, quiet=()):
  334. """Get the offset of a node's parent
  335. Args:
  336. nodeoffset: Node offset to check
  337. quiet: Errors to ignore (empty to raise on all errors)
  338. Returns:
  339. The offset of the parent node, if any
  340. Raises:
  341. FdtException if no parent found or other error occurs
  342. """
  343. return check_err(fdt_parent_offset(self._fdt, nodeoffset), quiet)
  344. def node_offset_by_phandle(self, phandle, quiet=()):
  345. """Get the offset of a node with the given phandle
  346. Args:
  347. phandle: Phandle to search for
  348. quiet: Errors to ignore (empty to raise on all errors)
  349. Returns:
  350. The offset of node with that phandle, if any
  351. Raises:
  352. FdtException if no node found or other error occurs
  353. """
  354. return check_err(fdt_node_offset_by_phandle(self._fdt, phandle), quiet)
  355. class Fdt(FdtRo):
  356. """Device tree class, supporting all operations
  357. The Fdt object is created is created from a device tree binary file,
  358. e.g. with something like:
  359. fdt = Fdt(open("filename.dtb").read())
  360. Operations can then be performed using the methods in this class. Each
  361. method xxx(args...) corresponds to a libfdt function fdt_xxx(fdt, args...).
  362. All methods raise an FdtException if an error occurs. To avoid this
  363. behaviour a 'quiet' parameter is provided for some functions. This
  364. defaults to empty, but you can pass a list of errors that you expect.
  365. If one of these errors occurs, the function will return an error number
  366. (e.g. -NOTFOUND).
  367. """
  368. def __init__(self, data):
  369. FdtRo.__init__(self, data)
  370. @staticmethod
  371. def create_empty_tree(size, quiet=()):
  372. """Create an empty device tree ready for use
  373. Args:
  374. size: Size of device tree in bytes
  375. Returns:
  376. Fdt object containing the device tree
  377. """
  378. data = bytearray(size)
  379. err = check_err(fdt_create_empty_tree(data, size), quiet)
  380. if err:
  381. return err
  382. return Fdt(data)
  383. def resize(self, size, quiet=()):
  384. """Move the device tree into a larger or smaller space
  385. This creates a new device tree of size @size and moves the existing
  386. device tree contents over to that. It can be used to create more space
  387. in a device tree. Note that the Fdt object remains the same, but it
  388. now has a new bytearray holding the contents.
  389. Args:
  390. size: Required new size of device tree in bytes
  391. """
  392. fdt = bytearray(size)
  393. err = check_err(fdt_open_into(self._fdt, fdt, size), quiet)
  394. if err:
  395. return err
  396. self._fdt = fdt
  397. def pack(self, quiet=()):
  398. """Pack the device tree to remove unused space
  399. This adjusts the tree in place.
  400. Args:
  401. quiet: Errors to ignore (empty to raise on all errors)
  402. Returns:
  403. Error code, or 0 if OK
  404. Raises:
  405. FdtException if any error occurs
  406. """
  407. err = check_err(fdt_pack(self._fdt), quiet)
  408. if err:
  409. return err
  410. del self._fdt[self.totalsize():]
  411. return err
  412. def set_name(self, nodeoffset, name, quiet=()):
  413. """Set the name of a node
  414. Args:
  415. nodeoffset: Node offset of node to update
  416. name: New node name (string without \0)
  417. Returns:
  418. Error code, or 0 if OK
  419. Raises:
  420. FdtException if no parent found or other error occurs
  421. """
  422. if chr(0) in name:
  423. raise ValueError('Property contains embedded nul characters')
  424. return check_err(fdt_set_name(self._fdt, nodeoffset, name), quiet)
  425. def setprop(self, nodeoffset, prop_name, val, quiet=()):
  426. """Set the value of a property
  427. Args:
  428. nodeoffset: Node offset containing the property to create/update
  429. prop_name: Name of property
  430. val: Value to write (string or bytearray)
  431. quiet: Errors to ignore (empty to raise on all errors)
  432. Returns:
  433. Error code, or 0 if OK
  434. Raises:
  435. FdtException if no parent found or other error occurs
  436. """
  437. return check_err(fdt_setprop(self._fdt, nodeoffset, prop_name, val,
  438. len(val)), quiet)
  439. def setprop_u32(self, nodeoffset, prop_name, val, quiet=()):
  440. """Set the value of a property
  441. Args:
  442. nodeoffset: Node offset containing the property to create/update
  443. prop_name: Name of property
  444. val: Value to write (integer)
  445. quiet: Errors to ignore (empty to raise on all errors)
  446. Returns:
  447. Error code, or 0 if OK
  448. Raises:
  449. FdtException if no parent found or other error occurs
  450. """
  451. return check_err(fdt_setprop_u32(self._fdt, nodeoffset, prop_name, val),
  452. quiet)
  453. def setprop_u64(self, nodeoffset, prop_name, val, quiet=()):
  454. """Set the value of a property
  455. Args:
  456. nodeoffset: Node offset containing the property to create/update
  457. prop_name: Name of property
  458. val: Value to write (integer)
  459. quiet: Errors to ignore (empty to raise on all errors)
  460. Returns:
  461. Error code, or 0 if OK
  462. Raises:
  463. FdtException if no parent found or other error occurs
  464. """
  465. return check_err(fdt_setprop_u64(self._fdt, nodeoffset, prop_name, val),
  466. quiet)
  467. def setprop_str(self, nodeoffset, prop_name, val, quiet=()):
  468. """Set the string value of a property
  469. The property is set to the string, with a nul terminator added
  470. Args:
  471. nodeoffset: Node offset containing the property to create/update
  472. prop_name: Name of property
  473. val: Value to write (string without nul terminator). Unicode is
  474. supposed by encoding to UTF-8
  475. quiet: Errors to ignore (empty to raise on all errors)
  476. Returns:
  477. Error code, or 0 if OK
  478. Raises:
  479. FdtException if no parent found or other error occurs
  480. """
  481. val = val.encode('utf-8') + '\0'
  482. return check_err(fdt_setprop(self._fdt, nodeoffset, prop_name,
  483. val, len(val)), quiet)
  484. def delprop(self, nodeoffset, prop_name, quiet=()):
  485. """Delete a property from a node
  486. Args:
  487. nodeoffset: Node offset containing property to delete
  488. prop_name: Name of property to delete
  489. quiet: Errors to ignore (empty to raise on all errors)
  490. Returns:
  491. Error code, or 0 if OK
  492. Raises:
  493. FdtError if the property does not exist, or another error occurs
  494. """
  495. return check_err(fdt_delprop(self._fdt, nodeoffset, prop_name), quiet)
  496. def add_subnode(self, parentoffset, name, quiet=()):
  497. """Add a new subnode to a node
  498. Args:
  499. parentoffset: Parent offset to add the subnode to
  500. name: Name of node to add
  501. Returns:
  502. offset of the node created, or negative error code on failure
  503. Raises:
  504. FdtError if there is not enough space, or another error occurs
  505. """
  506. return check_err(fdt_add_subnode(self._fdt, parentoffset, name), quiet)
  507. def del_node(self, nodeoffset, quiet=()):
  508. """Delete a node
  509. Args:
  510. nodeoffset: Offset of node to delete
  511. Returns:
  512. Error code, or 0 if OK
  513. Raises:
  514. FdtError if an error occurs
  515. """
  516. return check_err(fdt_del_node(self._fdt, nodeoffset), quiet)
  517. class Property(bytearray):
  518. """Holds a device tree property name and value.
  519. This holds a copy of a property taken from the device tree. It does not
  520. reference the device tree, so if anything changes in the device tree,
  521. a Property object will remain valid.
  522. Properties:
  523. name: Property name
  524. value: Property value as a bytearray
  525. """
  526. def __init__(self, name, value):
  527. bytearray.__init__(self, value)
  528. self.name = name
  529. def as_cell(self, fmt):
  530. return struct.unpack('>' + fmt, self)[0]
  531. def as_uint32(self):
  532. return self.as_cell('L')
  533. def as_int32(self):
  534. return self.as_cell('l')
  535. def as_uint64(self):
  536. return self.as_cell('Q')
  537. def as_int64(self):
  538. return self.as_cell('q')
  539. def as_str(self):
  540. """Unicode is supported by decoding from UTF-8"""
  541. if self[-1] != 0:
  542. raise ValueError('Property lacks nul termination')
  543. if 0 in self[:-1]:
  544. raise ValueError('Property contains embedded nul characters')
  545. return self[:-1].decode('utf-8')
  546. class FdtSw(FdtRo):
  547. """Software interface to create a device tree from scratch
  548. The methods in this class work by adding to an existing 'partial' device
  549. tree buffer of a fixed size created by instantiating this class. When the
  550. tree is complete, call as_fdt() to obtain a device tree ready to be used.
  551. Similarly with nodes, a new node is started with begin_node() and finished
  552. with end_node().
  553. The context manager functions can be used to make this a bit easier:
  554. # First create the device tree with a node and property:
  555. sw = FdtSw()
  556. with sw.add_node('node'):
  557. sw.property_u32('reg', 2)
  558. fdt = sw.as_fdt()
  559. # Now we can use it as a real device tree
  560. fdt.setprop_u32(0, 'reg', 3)
  561. The size hint provides a starting size for the space to be used by the
  562. device tree. This will be increased automatically as needed as new items
  563. are added to the tree.
  564. """
  565. INC_SIZE = 1024 # Expand size by this much when out of space
  566. def __init__(self, size_hint=None):
  567. """Create a new FdtSw object
  568. Args:
  569. size_hint: A hint as to the initial size to use
  570. Raises:
  571. ValueError if size_hint is negative
  572. Returns:
  573. FdtSw object on success, else integer error code (if not raising)
  574. """
  575. if not size_hint:
  576. size_hint = self.INC_SIZE
  577. fdtsw = bytearray(size_hint)
  578. err = check_err(fdt_create(fdtsw, size_hint))
  579. if err:
  580. return err
  581. self._fdt = fdtsw
  582. def as_fdt(self):
  583. """Convert a FdtSw into an Fdt so it can be accessed as normal
  584. Creates a new Fdt object from the work-in-progress device tree. This
  585. does not call fdt_finish() on the current object, so it is possible to
  586. add more nodes/properties and call as_fdt() again to get an updated
  587. tree.
  588. Returns:
  589. Fdt object allowing access to the newly created device tree
  590. """
  591. fdtsw = bytearray(self._fdt)
  592. check_err(fdt_finish(fdtsw))
  593. return Fdt(fdtsw)
  594. def check_space(self, val):
  595. """Check if we need to add more space to the FDT
  596. This should be called with the error code from an operation. If this is
  597. -NOSPACE then the FDT will be expanded to have more space, and True will
  598. be returned, indicating that the operation needs to be tried again.
  599. Args:
  600. val: Return value from the operation that was attempted
  601. Returns:
  602. True if the operation must be retried, else False
  603. """
  604. if check_err(val, QUIET_NOSPACE) < 0:
  605. self.resize(len(self._fdt) + self.INC_SIZE)
  606. return True
  607. return False
  608. def resize(self, size):
  609. """Resize the buffer to accommodate a larger tree
  610. Args:
  611. size: New size of tree
  612. Raises:
  613. FdtException on any error
  614. """
  615. fdt = bytearray(size)
  616. err = check_err(fdt_resize(self._fdt, fdt, size))
  617. self._fdt = fdt
  618. def add_reservemap_entry(self, addr, size):
  619. """Add a new memory reserve map entry
  620. Once finished adding, you must call finish_reservemap().
  621. Args:
  622. addr: 64-bit start address
  623. size: 64-bit size
  624. Raises:
  625. FdtException on any error
  626. """
  627. while self.check_space(fdt_add_reservemap_entry(self._fdt, addr,
  628. size)):
  629. pass
  630. def finish_reservemap(self):
  631. """Indicate that there are no more reserve map entries to add
  632. Raises:
  633. FdtException on any error
  634. """
  635. while self.check_space(fdt_finish_reservemap(self._fdt)):
  636. pass
  637. def begin_node(self, name):
  638. """Begin a new node
  639. Use this before adding properties to the node. Then call end_node() to
  640. finish it. You can also use the context manager as shown in the FdtSw
  641. class comment.
  642. Args:
  643. name: Name of node to begin
  644. Raises:
  645. FdtException on any error
  646. """
  647. while self.check_space(fdt_begin_node(self._fdt, name)):
  648. pass
  649. def property_string(self, name, string):
  650. """Add a property with a string value
  651. The string will be nul-terminated when written to the device tree
  652. Args:
  653. name: Name of property to add
  654. string: String value of property
  655. Raises:
  656. FdtException on any error
  657. """
  658. while self.check_space(fdt_property_string(self._fdt, name, string)):
  659. pass
  660. def property_u32(self, name, val):
  661. """Add a property with a 32-bit value
  662. Write a single-cell value to the device tree
  663. Args:
  664. name: Name of property to add
  665. val: Value of property
  666. Raises:
  667. FdtException on any error
  668. """
  669. while self.check_space(fdt_property_u32(self._fdt, name, val)):
  670. pass
  671. def property_u64(self, name, val):
  672. """Add a property with a 64-bit value
  673. Write a double-cell value to the device tree in big-endian format
  674. Args:
  675. name: Name of property to add
  676. val: Value of property
  677. Raises:
  678. FdtException on any error
  679. """
  680. while self.check_space(fdt_property_u64(self._fdt, name, val)):
  681. pass
  682. def property_cell(self, name, val):
  683. """Add a property with a single-cell value
  684. Write a single-cell value to the device tree
  685. Args:
  686. name: Name of property to add
  687. val: Value of property
  688. quiet: Errors to ignore (empty to raise on all errors)
  689. Raises:
  690. FdtException on any error
  691. """
  692. while self.check_space(fdt_property_cell(self._fdt, name, val)):
  693. pass
  694. def property(self, name, val):
  695. """Add a property
  696. Write a new property with the given value to the device tree. The value
  697. is taken as is and is not nul-terminated
  698. Args:
  699. name: Name of property to add
  700. val: Value of property
  701. quiet: Errors to ignore (empty to raise on all errors)
  702. Raises:
  703. FdtException on any error
  704. """
  705. while self.check_space(fdt_property_stub(self._fdt, name, val,
  706. len(val))):
  707. pass
  708. def end_node(self):
  709. """End a node
  710. Use this after adding properties to a node to close it off. You can also
  711. use the context manager as shown in the FdtSw class comment.
  712. Args:
  713. quiet: Errors to ignore (empty to raise on all errors)
  714. Raises:
  715. FdtException on any error
  716. """
  717. while self.check_space(fdt_end_node(self._fdt)):
  718. pass
  719. def add_node(self, name):
  720. """Create a new context for adding a node
  721. When used in a 'with' clause this starts a new node and finishes it
  722. afterward.
  723. Args:
  724. name: Name of node to add
  725. """
  726. return NodeAdder(self, name)
  727. class NodeAdder():
  728. """Class to provide a node context
  729. This allows you to add nodes in a more natural way:
  730. with fdtsw.add_node('name'):
  731. fdtsw.property_string('test', 'value')
  732. The node is automatically completed with a call to end_node() when the
  733. context exits.
  734. """
  735. def __init__(self, fdtsw, name):
  736. self._fdt = fdtsw
  737. self._name = name
  738. def __enter__(self):
  739. self._fdt.begin_node(self._name)
  740. def __exit__(self, type, value, traceback):
  741. self._fdt.end_node()
  742. %}
  743. %rename(fdt_property) fdt_property_func;
  744. /*
  745. * fdt32_t is a big-endian 32-bit value defined to uint32_t in libfdt_env.h
  746. * so use the same type here.
  747. */
  748. typedef uint32_t fdt32_t;
  749. %include "libfdt/fdt.h"
  750. %include "typemaps.i"
  751. /* Most functions don't change the device tree, so use a const void * */
  752. %typemap(in) (const void *)(const void *fdt) {
  753. if (!PyByteArray_Check($input)) {
  754. SWIG_exception_fail(SWIG_TypeError, "in method '" "$symname"
  755. "', argument " "$argnum"" of type '" "$type""'");
  756. }
  757. $1 = (void *)PyByteArray_AsString($input);
  758. fdt = $1;
  759. fdt = fdt; /* avoid unused variable warning */
  760. }
  761. /* Some functions do change the device tree, so use void * */
  762. %typemap(in) (void *)(const void *fdt) {
  763. if (!PyByteArray_Check($input)) {
  764. SWIG_exception_fail(SWIG_TypeError, "in method '" "$symname"
  765. "', argument " "$argnum"" of type '" "$type""'");
  766. }
  767. $1 = PyByteArray_AsString($input);
  768. fdt = $1;
  769. fdt = fdt; /* avoid unused variable warning */
  770. }
  771. /* typemap used for fdt_get_property_by_offset() */
  772. %typemap(out) (struct fdt_property *) {
  773. PyObject *buff;
  774. if ($1) {
  775. resultobj = PyString_FromString(
  776. fdt_string(fdt1, fdt32_to_cpu($1->nameoff)));
  777. buff = PyByteArray_FromStringAndSize(
  778. (const char *)($1 + 1), fdt32_to_cpu($1->len));
  779. resultobj = SWIG_Python_AppendOutput(resultobj, buff);
  780. }
  781. }
  782. %apply int *OUTPUT { int *lenp };
  783. /* typemap used for fdt_getprop() */
  784. %typemap(out) (const void *) {
  785. if (!$1)
  786. $result = Py_None;
  787. else
  788. $result = Py_BuildValue("s#", $1, *arg4);
  789. }
  790. /* typemap used for fdt_setprop() */
  791. %typemap(in) (const void *val) {
  792. $1 = PyString_AsString($input); /* char *str */
  793. }
  794. /* typemap used for fdt_add_reservemap_entry() */
  795. %typemap(in) uint64_t {
  796. $1 = PyLong_AsUnsignedLong($input);
  797. }
  798. /* typemaps used for fdt_next_node() */
  799. %typemap(in, numinputs=1) int *depth (int depth) {
  800. depth = (int) PyInt_AsLong($input);
  801. $1 = &depth;
  802. }
  803. %typemap(argout) int *depth {
  804. PyObject *val = Py_BuildValue("i", *arg$argnum);
  805. resultobj = SWIG_Python_AppendOutput(resultobj, val);
  806. }
  807. %apply int *depth { int *depth };
  808. /* typemaps for fdt_get_mem_rsv */
  809. %typemap(in, numinputs=0) uint64_t * (uint64_t temp) {
  810. $1 = &temp;
  811. }
  812. %typemap(argout) uint64_t * {
  813. PyObject *val = PyLong_FromUnsignedLong(*arg$argnum);
  814. if (!result) {
  815. if (PyTuple_GET_SIZE(resultobj) == 0)
  816. resultobj = val;
  817. else
  818. resultobj = SWIG_Python_AppendOutput(resultobj, val);
  819. }
  820. }
  821. /* We have both struct fdt_property and a function fdt_property() */
  822. %warnfilter(302) fdt_property;
  823. /* These are macros in the header so have to be redefined here */
  824. uint32_t fdt_magic(const void *fdt);
  825. uint32_t fdt_totalsize(const void *fdt);
  826. uint32_t fdt_off_dt_struct(const void *fdt);
  827. uint32_t fdt_off_dt_strings(const void *fdt);
  828. uint32_t fdt_off_mem_rsvmap(const void *fdt);
  829. uint32_t fdt_version(const void *fdt);
  830. uint32_t fdt_last_comp_version(const void *fdt);
  831. uint32_t fdt_boot_cpuid_phys(const void *fdt);
  832. uint32_t fdt_size_dt_strings(const void *fdt);
  833. uint32_t fdt_size_dt_struct(const void *fdt);
  834. int fdt_property_string(void *fdt, const char *name, const char *val);
  835. int fdt_property_cell(void *fdt, const char *name, uint32_t val);
  836. /*
  837. * This function has a stub since the name fdt_property is used for both a
  838. * function and a struct, which confuses SWIG.
  839. */
  840. int fdt_property_stub(void *fdt, const char *name, const char *val, int len);
  841. %include <../libfdt/libfdt.h>