libfdt.i_shipped 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119
  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 void *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 isinstance(val, int) and 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, bytes(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 get_alias(self, name):
  334. """Get the full path referenced by a given alias
  335. Args:
  336. name: name of the alias to lookup
  337. Returns:
  338. Full path to the node for the alias named 'name', if it exists
  339. None, if the given alias or the /aliases node does not exist
  340. """
  341. return fdt_get_alias(self._fdt, name)
  342. def parent_offset(self, nodeoffset, quiet=()):
  343. """Get the offset of a node's parent
  344. Args:
  345. nodeoffset: Node offset to check
  346. quiet: Errors to ignore (empty to raise on all errors)
  347. Returns:
  348. The offset of the parent node, if any
  349. Raises:
  350. FdtException if no parent found or other error occurs
  351. """
  352. return check_err(fdt_parent_offset(self._fdt, nodeoffset), quiet)
  353. def node_offset_by_phandle(self, phandle, quiet=()):
  354. """Get the offset of a node with the given phandle
  355. Args:
  356. phandle: Phandle to search for
  357. quiet: Errors to ignore (empty to raise on all errors)
  358. Returns:
  359. The offset of node with that phandle, if any
  360. Raises:
  361. FdtException if no node found or other error occurs
  362. """
  363. return check_err(fdt_node_offset_by_phandle(self._fdt, phandle), quiet)
  364. class Fdt(FdtRo):
  365. """Device tree class, supporting all operations
  366. The Fdt object is created is created from a device tree binary file,
  367. e.g. with something like:
  368. fdt = Fdt(open("filename.dtb").read())
  369. Operations can then be performed using the methods in this class. Each
  370. method xxx(args...) corresponds to a libfdt function fdt_xxx(fdt, args...).
  371. All methods raise an FdtException if an error occurs. To avoid this
  372. behaviour a 'quiet' parameter is provided for some functions. This
  373. defaults to empty, but you can pass a list of errors that you expect.
  374. If one of these errors occurs, the function will return an error number
  375. (e.g. -NOTFOUND).
  376. """
  377. def __init__(self, data):
  378. FdtRo.__init__(self, data)
  379. @staticmethod
  380. def create_empty_tree(size, quiet=()):
  381. """Create an empty device tree ready for use
  382. Args:
  383. size: Size of device tree in bytes
  384. Returns:
  385. Fdt object containing the device tree
  386. """
  387. data = bytearray(size)
  388. err = check_err(fdt_create_empty_tree(data, size), quiet)
  389. if err:
  390. return err
  391. return Fdt(data)
  392. def resize(self, size, quiet=()):
  393. """Move the device tree into a larger or smaller space
  394. This creates a new device tree of size @size and moves the existing
  395. device tree contents over to that. It can be used to create more space
  396. in a device tree. Note that the Fdt object remains the same, but it
  397. now has a new bytearray holding the contents.
  398. Args:
  399. size: Required new size of device tree in bytes
  400. """
  401. fdt = bytearray(size)
  402. err = check_err(fdt_open_into(self._fdt, fdt, size), quiet)
  403. if err:
  404. return err
  405. self._fdt = fdt
  406. def pack(self, quiet=()):
  407. """Pack the device tree to remove unused space
  408. This adjusts the tree in place.
  409. Args:
  410. quiet: Errors to ignore (empty to raise on all errors)
  411. Returns:
  412. Error code, or 0 if OK
  413. Raises:
  414. FdtException if any error occurs
  415. """
  416. err = check_err(fdt_pack(self._fdt), quiet)
  417. if err:
  418. return err
  419. del self._fdt[self.totalsize():]
  420. return err
  421. def set_name(self, nodeoffset, name, quiet=()):
  422. """Set the name of a node
  423. Args:
  424. nodeoffset: Node offset of node to update
  425. name: New node name (string without \0)
  426. Returns:
  427. Error code, or 0 if OK
  428. Raises:
  429. FdtException if no parent found or other error occurs
  430. """
  431. if chr(0) in name:
  432. raise ValueError('Property contains embedded nul characters')
  433. return check_err(fdt_set_name(self._fdt, nodeoffset, name), quiet)
  434. def setprop(self, nodeoffset, prop_name, val, quiet=()):
  435. """Set the value of a property
  436. Args:
  437. nodeoffset: Node offset containing the property to create/update
  438. prop_name: Name of property
  439. val: Value to write (string or bytearray)
  440. quiet: Errors to ignore (empty to raise on all errors)
  441. Returns:
  442. Error code, or 0 if OK
  443. Raises:
  444. FdtException if no parent found or other error occurs
  445. """
  446. return check_err(fdt_setprop(self._fdt, nodeoffset, prop_name, val,
  447. len(val)), quiet)
  448. def setprop_u32(self, nodeoffset, prop_name, val, quiet=()):
  449. """Set the value of a property
  450. Args:
  451. nodeoffset: Node offset containing the property to create/update
  452. prop_name: Name of property
  453. val: Value to write (integer)
  454. quiet: Errors to ignore (empty to raise on all errors)
  455. Returns:
  456. Error code, or 0 if OK
  457. Raises:
  458. FdtException if no parent found or other error occurs
  459. """
  460. return check_err(fdt_setprop_u32(self._fdt, nodeoffset, prop_name, val),
  461. quiet)
  462. def setprop_u64(self, nodeoffset, prop_name, val, quiet=()):
  463. """Set the value of a property
  464. Args:
  465. nodeoffset: Node offset containing the property to create/update
  466. prop_name: Name of property
  467. val: Value to write (integer)
  468. quiet: Errors to ignore (empty to raise on all errors)
  469. Returns:
  470. Error code, or 0 if OK
  471. Raises:
  472. FdtException if no parent found or other error occurs
  473. """
  474. return check_err(fdt_setprop_u64(self._fdt, nodeoffset, prop_name, val),
  475. quiet)
  476. def setprop_str(self, nodeoffset, prop_name, val, quiet=()):
  477. """Set the string value of a property
  478. The property is set to the string, with a nul terminator added
  479. Args:
  480. nodeoffset: Node offset containing the property to create/update
  481. prop_name: Name of property
  482. val: Value to write (string without nul terminator). Unicode is
  483. supposed by encoding to UTF-8
  484. quiet: Errors to ignore (empty to raise on all errors)
  485. Returns:
  486. Error code, or 0 if OK
  487. Raises:
  488. FdtException if no parent found or other error occurs
  489. """
  490. val = val.encode('utf-8') + b'\0'
  491. return check_err(fdt_setprop(self._fdt, nodeoffset, prop_name,
  492. val, len(val)), quiet)
  493. def delprop(self, nodeoffset, prop_name, quiet=()):
  494. """Delete a property from a node
  495. Args:
  496. nodeoffset: Node offset containing property to delete
  497. prop_name: Name of property to delete
  498. quiet: Errors to ignore (empty to raise on all errors)
  499. Returns:
  500. Error code, or 0 if OK
  501. Raises:
  502. FdtError if the property does not exist, or another error occurs
  503. """
  504. return check_err(fdt_delprop(self._fdt, nodeoffset, prop_name), quiet)
  505. def add_subnode(self, parentoffset, name, quiet=()):
  506. """Add a new subnode to a node
  507. Args:
  508. parentoffset: Parent offset to add the subnode to
  509. name: Name of node to add
  510. Returns:
  511. offset of the node created, or negative error code on failure
  512. Raises:
  513. FdtError if there is not enough space, or another error occurs
  514. """
  515. return check_err(fdt_add_subnode(self._fdt, parentoffset, name), quiet)
  516. def del_node(self, nodeoffset, quiet=()):
  517. """Delete a node
  518. Args:
  519. nodeoffset: Offset of node to delete
  520. Returns:
  521. Error code, or 0 if OK
  522. Raises:
  523. FdtError if an error occurs
  524. """
  525. return check_err(fdt_del_node(self._fdt, nodeoffset), quiet)
  526. class Property(bytearray):
  527. """Holds a device tree property name and value.
  528. This holds a copy of a property taken from the device tree. It does not
  529. reference the device tree, so if anything changes in the device tree,
  530. a Property object will remain valid.
  531. Properties:
  532. name: Property name
  533. value: Property value as a bytearray
  534. """
  535. def __init__(self, name, value):
  536. bytearray.__init__(self, value)
  537. self.name = name
  538. def as_cell(self, fmt):
  539. return struct.unpack('>' + fmt, self)[0]
  540. def as_uint32(self):
  541. return self.as_cell('L')
  542. def as_int32(self):
  543. return self.as_cell('l')
  544. def as_uint64(self):
  545. return self.as_cell('Q')
  546. def as_int64(self):
  547. return self.as_cell('q')
  548. def as_str(self):
  549. """Unicode is supported by decoding from UTF-8"""
  550. if self[-1] != 0:
  551. raise ValueError('Property lacks nul termination')
  552. if 0 in self[:-1]:
  553. raise ValueError('Property contains embedded nul characters')
  554. return self[:-1].decode('utf-8')
  555. class FdtSw(FdtRo):
  556. """Software interface to create a device tree from scratch
  557. The methods in this class work by adding to an existing 'partial' device
  558. tree buffer of a fixed size created by instantiating this class. When the
  559. tree is complete, call as_fdt() to obtain a device tree ready to be used.
  560. Similarly with nodes, a new node is started with begin_node() and finished
  561. with end_node().
  562. The context manager functions can be used to make this a bit easier:
  563. # First create the device tree with a node and property:
  564. sw = FdtSw()
  565. sw.finish_reservemap()
  566. with sw.add_node(''):
  567. with sw.add_node('node'):
  568. sw.property_u32('reg', 2)
  569. fdt = sw.as_fdt()
  570. # Now we can use it as a real device tree
  571. fdt.setprop_u32(0, 'reg', 3)
  572. The size hint provides a starting size for the space to be used by the
  573. device tree. This will be increased automatically as needed as new items
  574. are added to the tree.
  575. """
  576. INC_SIZE = 1024 # Expand size by this much when out of space
  577. def __init__(self, size_hint=None):
  578. """Create a new FdtSw object
  579. Args:
  580. size_hint: A hint as to the initial size to use
  581. Raises:
  582. ValueError if size_hint is negative
  583. Returns:
  584. FdtSw object on success, else integer error code (if not raising)
  585. """
  586. if not size_hint:
  587. size_hint = self.INC_SIZE
  588. fdtsw = bytearray(size_hint)
  589. err = check_err(fdt_create(fdtsw, size_hint))
  590. if err:
  591. return err
  592. self._fdt = fdtsw
  593. def as_fdt(self):
  594. """Convert a FdtSw into an Fdt so it can be accessed as normal
  595. Creates a new Fdt object from the work-in-progress device tree. This
  596. does not call fdt_finish() on the current object, so it is possible to
  597. add more nodes/properties and call as_fdt() again to get an updated
  598. tree.
  599. Returns:
  600. Fdt object allowing access to the newly created device tree
  601. """
  602. fdtsw = bytearray(self._fdt)
  603. while self.check_space(fdt_finish(fdtsw)):
  604. fdtsw = bytearray(self._fdt)
  605. return Fdt(fdtsw)
  606. def check_space(self, val):
  607. """Check if we need to add more space to the FDT
  608. This should be called with the error code from an operation. If this is
  609. -NOSPACE then the FDT will be expanded to have more space, and True will
  610. be returned, indicating that the operation needs to be tried again.
  611. Args:
  612. val: Return value from the operation that was attempted
  613. Returns:
  614. True if the operation must be retried, else False
  615. """
  616. if check_err(val, QUIET_NOSPACE) < 0:
  617. self.resize(len(self._fdt) + self.INC_SIZE)
  618. return True
  619. return False
  620. def resize(self, size):
  621. """Resize the buffer to accommodate a larger tree
  622. Args:
  623. size: New size of tree
  624. Raises:
  625. FdtException on any error
  626. """
  627. fdt = bytearray(size)
  628. err = check_err(fdt_resize(self._fdt, fdt, size))
  629. self._fdt = fdt
  630. def add_reservemap_entry(self, addr, size):
  631. """Add a new memory reserve map entry
  632. Once finished adding, you must call finish_reservemap().
  633. Args:
  634. addr: 64-bit start address
  635. size: 64-bit size
  636. Raises:
  637. FdtException on any error
  638. """
  639. while self.check_space(fdt_add_reservemap_entry(self._fdt, addr,
  640. size)):
  641. pass
  642. def finish_reservemap(self):
  643. """Indicate that there are no more reserve map entries to add
  644. Raises:
  645. FdtException on any error
  646. """
  647. while self.check_space(fdt_finish_reservemap(self._fdt)):
  648. pass
  649. def begin_node(self, name):
  650. """Begin a new node
  651. Use this before adding properties to the node. Then call end_node() to
  652. finish it. You can also use the context manager as shown in the FdtSw
  653. class comment.
  654. Args:
  655. name: Name of node to begin
  656. Raises:
  657. FdtException on any error
  658. """
  659. while self.check_space(fdt_begin_node(self._fdt, name)):
  660. pass
  661. def property_string(self, name, string):
  662. """Add a property with a string value
  663. The string will be nul-terminated when written to the device tree
  664. Args:
  665. name: Name of property to add
  666. string: String value of property
  667. Raises:
  668. FdtException on any error
  669. """
  670. while self.check_space(fdt_property_string(self._fdt, name, string)):
  671. pass
  672. def property_u32(self, name, val):
  673. """Add a property with a 32-bit value
  674. Write a single-cell value to the device tree
  675. Args:
  676. name: Name of property to add
  677. val: Value of property
  678. Raises:
  679. FdtException on any error
  680. """
  681. while self.check_space(fdt_property_u32(self._fdt, name, val)):
  682. pass
  683. def property_u64(self, name, val):
  684. """Add a property with a 64-bit value
  685. Write a double-cell value to the device tree in big-endian format
  686. Args:
  687. name: Name of property to add
  688. val: Value of property
  689. Raises:
  690. FdtException on any error
  691. """
  692. while self.check_space(fdt_property_u64(self._fdt, name, val)):
  693. pass
  694. def property_cell(self, name, val):
  695. """Add a property with a single-cell value
  696. Write a single-cell value to the device tree
  697. Args:
  698. name: Name of property to add
  699. val: Value of property
  700. quiet: Errors to ignore (empty to raise on all errors)
  701. Raises:
  702. FdtException on any error
  703. """
  704. while self.check_space(fdt_property_cell(self._fdt, name, val)):
  705. pass
  706. def property(self, name, val):
  707. """Add a property
  708. Write a new property with the given value to the device tree. The value
  709. is taken as is and is not nul-terminated
  710. Args:
  711. name: Name of property to add
  712. val: Value of property
  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_property_stub(self._fdt, name, val,
  718. len(val))):
  719. pass
  720. def end_node(self):
  721. """End a node
  722. Use this after adding properties to a node to close it off. You can also
  723. use the context manager as shown in the FdtSw class comment.
  724. Args:
  725. quiet: Errors to ignore (empty to raise on all errors)
  726. Raises:
  727. FdtException on any error
  728. """
  729. while self.check_space(fdt_end_node(self._fdt)):
  730. pass
  731. def add_node(self, name):
  732. """Create a new context for adding a node
  733. When used in a 'with' clause this starts a new node and finishes it
  734. afterward.
  735. Args:
  736. name: Name of node to add
  737. """
  738. return NodeAdder(self, name)
  739. class NodeAdder():
  740. """Class to provide a node context
  741. This allows you to add nodes in a more natural way:
  742. with fdtsw.add_node('name'):
  743. fdtsw.property_string('test', 'value')
  744. The node is automatically completed with a call to end_node() when the
  745. context exits.
  746. """
  747. def __init__(self, fdtsw, name):
  748. self._fdt = fdtsw
  749. self._name = name
  750. def __enter__(self):
  751. self._fdt.begin_node(self._name)
  752. def __exit__(self, type, value, traceback):
  753. self._fdt.end_node()
  754. %}
  755. %rename(fdt_property) fdt_property_func;
  756. /*
  757. * fdt32_t is a big-endian 32-bit value defined to uint32_t in libfdt_env.h
  758. * so use the same type here.
  759. */
  760. typedef uint32_t fdt32_t;
  761. %include "libfdt/fdt.h"
  762. %include "typemaps.i"
  763. /* Most functions don't change the device tree, so use a const void * */
  764. %typemap(in) (const void *)(const void *fdt) {
  765. if (!PyByteArray_Check($input)) {
  766. SWIG_exception_fail(SWIG_TypeError, "in method '" "$symname"
  767. "', argument " "$argnum"" of type '" "$type""'");
  768. }
  769. $1 = (void *)PyByteArray_AsString($input);
  770. fdt = $1;
  771. fdt = fdt; /* avoid unused variable warning */
  772. }
  773. /* Some functions do change the device tree, so use void * */
  774. %typemap(in) (void *)(const void *fdt) {
  775. if (!PyByteArray_Check($input)) {
  776. SWIG_exception_fail(SWIG_TypeError, "in method '" "$symname"
  777. "', argument " "$argnum"" of type '" "$type""'");
  778. }
  779. $1 = PyByteArray_AsString($input);
  780. fdt = $1;
  781. fdt = fdt; /* avoid unused variable warning */
  782. }
  783. /* typemap used for fdt_get_property_by_offset() */
  784. %typemap(out) (struct fdt_property *) {
  785. PyObject *buff;
  786. if ($1) {
  787. resultobj = PyString_FromString(
  788. fdt_string(fdt1, fdt32_to_cpu($1->nameoff)));
  789. buff = PyByteArray_FromStringAndSize(
  790. (const char *)($1 + 1), fdt32_to_cpu($1->len));
  791. resultobj = SWIG_Python_AppendOutput(resultobj, buff);
  792. }
  793. }
  794. %apply int *OUTPUT { int *lenp };
  795. /* typemap used for fdt_getprop() */
  796. %typemap(out) (const void *) {
  797. if (!$1)
  798. $result = Py_None;
  799. else
  800. %#if PY_VERSION_HEX >= 0x03000000
  801. $result = Py_BuildValue("y#", $1, *arg4);
  802. %#else
  803. $result = Py_BuildValue("s#", $1, *arg4);
  804. %#endif
  805. }
  806. /* typemap used for fdt_setprop() */
  807. %typemap(in) (const void *val) {
  808. %#if PY_VERSION_HEX >= 0x03000000
  809. if (!PyBytes_Check($input)) {
  810. SWIG_exception_fail(SWIG_TypeError, "bytes expected in method '" "$symname"
  811. "', argument " "$argnum"" of type '" "$type""'");
  812. }
  813. $1 = PyBytes_AsString($input);
  814. %#else
  815. $1 = PyString_AsString($input); /* char *str */
  816. %#endif
  817. }
  818. /* typemaps used for fdt_next_node() */
  819. %typemap(in, numinputs=1) int *depth (int depth) {
  820. depth = (int) PyInt_AsLong($input);
  821. $1 = &depth;
  822. }
  823. %typemap(argout) int *depth {
  824. PyObject *val = Py_BuildValue("i", *arg$argnum);
  825. resultobj = SWIG_Python_AppendOutput(resultobj, val);
  826. }
  827. %apply int *depth { int *depth };
  828. /* typemaps for fdt_get_mem_rsv */
  829. %typemap(in, numinputs=0) uint64_t * (uint64_t temp) {
  830. $1 = &temp;
  831. }
  832. %typemap(argout) uint64_t * {
  833. PyObject *val = PyLong_FromUnsignedLongLong(*arg$argnum);
  834. if (!result) {
  835. if (PyTuple_GET_SIZE(resultobj) == 0)
  836. resultobj = val;
  837. else
  838. resultobj = SWIG_Python_AppendOutput(resultobj, val);
  839. }
  840. }
  841. /* We have both struct fdt_property and a function fdt_property() */
  842. %warnfilter(302) fdt_property;
  843. /* These are macros in the header so have to be redefined here */
  844. uint32_t fdt_magic(const void *fdt);
  845. uint32_t fdt_totalsize(const void *fdt);
  846. uint32_t fdt_off_dt_struct(const void *fdt);
  847. uint32_t fdt_off_dt_strings(const void *fdt);
  848. uint32_t fdt_off_mem_rsvmap(const void *fdt);
  849. uint32_t fdt_version(const void *fdt);
  850. uint32_t fdt_last_comp_version(const void *fdt);
  851. uint32_t fdt_boot_cpuid_phys(const void *fdt);
  852. uint32_t fdt_size_dt_strings(const void *fdt);
  853. uint32_t fdt_size_dt_struct(const void *fdt);
  854. int fdt_property_string(void *fdt, const char *name, const char *val);
  855. int fdt_property_cell(void *fdt, const char *name, uint32_t val);
  856. /*
  857. * This function has a stub since the name fdt_property is used for both a
  858. * function and a struct, which confuses SWIG.
  859. */
  860. int fdt_property_stub(void *fdt, const char *name, const void *val, int len);
  861. %include <../libfdt/libfdt.h>