libfdt.i_shipped 30 KB

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