libfdt.i_shipped 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025
  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. return check_err(fdt_pack(self._fdt), quiet)
  341. def getprop(self, nodeoffset, prop_name, quiet=()):
  342. """Get a property from a node
  343. Args:
  344. nodeoffset: Node offset containing property to get
  345. prop_name: Name of property to get
  346. quiet: Errors to ignore (empty to raise on all errors)
  347. Returns:
  348. Value of property as a string, or -ve error number
  349. Raises:
  350. FdtError if any error occurs (e.g. the property is not found)
  351. """
  352. pdata = check_err_null(fdt_getprop(self._fdt, nodeoffset, prop_name),
  353. quiet)
  354. if isinstance(pdata, (int)):
  355. return pdata
  356. return str(pdata[0])
  357. def getprop_obj(self, nodeoffset, prop_name, quiet=()):
  358. """Get a property from a node as a Property object
  359. Args:
  360. nodeoffset: Node offset containing property to get
  361. prop_name: Name of property to get
  362. quiet: Errors to ignore (empty to raise on all errors)
  363. Returns:
  364. Property object, or None if not found
  365. Raises:
  366. FdtError if any error occurs (e.g. the property is not found)
  367. """
  368. pdata = check_err_null(fdt_getprop(self._fdt, nodeoffset, prop_name),
  369. quiet)
  370. if isinstance(pdata, (int)):
  371. return None
  372. return Property(prop_name, bytearray(pdata[0]))
  373. def get_phandle(self, nodeoffset):
  374. """Get the phandle of a node
  375. Args:
  376. nodeoffset: Node offset to check
  377. Returns:
  378. phandle of node, or 0 if the node has no phandle or another error
  379. occurs
  380. """
  381. return fdt_get_phandle(self._fdt, nodeoffset)
  382. def parent_offset(self, nodeoffset, quiet=()):
  383. """Get the offset of a node's parent
  384. Args:
  385. nodeoffset: Node offset to check
  386. quiet: Errors to ignore (empty to raise on all errors)
  387. Returns:
  388. The offset of the parent node, if any
  389. Raises:
  390. FdtException if no parent found or other error occurs
  391. """
  392. return check_err(fdt_parent_offset(self._fdt, nodeoffset), quiet)
  393. def set_name(self, nodeoffset, name, quiet=()):
  394. """Set the name of a node
  395. Args:
  396. nodeoffset: Node offset of node to update
  397. name: New node name
  398. Returns:
  399. Error code, or 0 if OK
  400. Raises:
  401. FdtException if no parent found or other error occurs
  402. """
  403. return check_err(fdt_set_name(self._fdt, nodeoffset, name), quiet)
  404. def setprop(self, nodeoffset, prop_name, val, quiet=()):
  405. """Set the value of a property
  406. Args:
  407. nodeoffset: Node offset containing the property to create/update
  408. prop_name: Name of property
  409. val: Value to write (string or bytearray)
  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 no parent found or other error occurs
  415. """
  416. return check_err(fdt_setprop(self._fdt, nodeoffset, prop_name, val,
  417. len(val)), quiet)
  418. def setprop_u32(self, nodeoffset, prop_name, val, quiet=()):
  419. """Set the value of a property
  420. Args:
  421. nodeoffset: Node offset containing the property to create/update
  422. prop_name: Name of property
  423. val: Value to write (integer)
  424. quiet: Errors to ignore (empty to raise on all errors)
  425. Returns:
  426. Error code, or 0 if OK
  427. Raises:
  428. FdtException if no parent found or other error occurs
  429. """
  430. return check_err(fdt_setprop_u32(self._fdt, nodeoffset, prop_name, val),
  431. quiet)
  432. def setprop_u64(self, nodeoffset, prop_name, val, quiet=()):
  433. """Set the value of a property
  434. Args:
  435. nodeoffset: Node offset containing the property to create/update
  436. prop_name: Name of property
  437. val: Value to write (integer)
  438. quiet: Errors to ignore (empty to raise on all errors)
  439. Returns:
  440. Error code, or 0 if OK
  441. Raises:
  442. FdtException if no parent found or other error occurs
  443. """
  444. return check_err(fdt_setprop_u64(self._fdt, nodeoffset, prop_name, val),
  445. quiet)
  446. def setprop_str(self, nodeoffset, prop_name, val, quiet=()):
  447. """Set the string value of a property
  448. The property is set to the string, with a nul terminator added
  449. Args:
  450. nodeoffset: Node offset containing the property to create/update
  451. prop_name: Name of property
  452. val: Value to write (string without nul terminator)
  453. quiet: Errors to ignore (empty to raise on all errors)
  454. Returns:
  455. Error code, or 0 if OK
  456. Raises:
  457. FdtException if no parent found or other error occurs
  458. """
  459. val += '\0'
  460. return check_err(fdt_setprop(self._fdt, nodeoffset, prop_name,
  461. val, len(val)), quiet)
  462. def delprop(self, nodeoffset, prop_name):
  463. """Delete a property from a node
  464. Args:
  465. nodeoffset: Node offset containing property to delete
  466. prop_name: Name of property to delete
  467. Raises:
  468. FdtError if the property does not exist, or another error occurs
  469. """
  470. return check_err(fdt_delprop(self._fdt, nodeoffset, prop_name))
  471. def node_offset_by_phandle(self, phandle, quiet=()):
  472. """Get the offset of a node with the given phandle
  473. Args:
  474. phandle: Phandle to search for
  475. quiet: Errors to ignore (empty to raise on all errors)
  476. Returns:
  477. The offset of node with that phandle, if any
  478. Raises:
  479. FdtException if no node found or other error occurs
  480. """
  481. return check_err(fdt_node_offset_by_phandle(self._fdt, phandle), quiet)
  482. class Property(bytearray):
  483. """Holds a device tree property name and value.
  484. This holds a copy of a property taken from the device tree. It does not
  485. reference the device tree, so if anything changes in the device tree,
  486. a Property object will remain valid.
  487. Properties:
  488. name: Property name
  489. value: Property value as a bytearray
  490. """
  491. def __init__(self, name, value):
  492. bytearray.__init__(self, value)
  493. self.name = name
  494. def as_cell(self, fmt):
  495. return struct.unpack('>' + fmt, self)[0]
  496. def as_uint32(self):
  497. return self.as_cell('L')
  498. def as_int32(self):
  499. return self.as_cell('l')
  500. def as_uint64(self):
  501. return self.as_cell('Q')
  502. def as_int64(self):
  503. return self.as_cell('q')
  504. def as_str(self):
  505. return self[:-1]
  506. class FdtSw(object):
  507. """Software interface to create a device tree from scratch
  508. The methods in this class work by adding to an existing 'partial' device
  509. tree buffer of a fixed size created by instantiating this class. When the
  510. tree is complete, call finish() to complete the device tree so that it can
  511. be used.
  512. Similarly with nodes, a new node is started with begin_node() and finished
  513. with end_node().
  514. The context manager functions can be used to make this a bit easier:
  515. # First create the device tree with a node and property:
  516. with FdtSw(small_size) as sw:
  517. with sw.AddNode('node'):
  518. sw.property_u32('reg', 2)
  519. fdt = sw.AsFdt()
  520. # Now we can use it as a real device tree
  521. fdt.setprop_u32(0, 'reg', 3)
  522. """
  523. def __init__(self, size, quiet=()):
  524. fdtrw = bytearray(size)
  525. err = check_err(fdt_create(fdtrw, size))
  526. if err:
  527. return err
  528. self._fdtrw = fdtrw
  529. def __enter__(self):
  530. """Contact manager to use to create a device tree via software"""
  531. return self
  532. def __exit__(self, type, value, traceback):
  533. check_err(fdt_finish(self._fdtrw))
  534. def AsFdt(self):
  535. """Convert a FdtSw into an Fdt so it can be accessed as normal
  536. Note that finish() must be called before this function will work. If
  537. you are using the context manager (see 'with' code in the FdtSw class
  538. comment) then this will happen automatically.
  539. Returns:
  540. Fdt object allowing access to the newly created device tree
  541. """
  542. return Fdt(self._fdtrw)
  543. def resize(self, size, quiet=()):
  544. """Resize the buffer to accommodate a larger tree
  545. Args:
  546. size: New size of tree
  547. quiet: Errors to ignore (empty to raise on all errors)
  548. Raises:
  549. FdtException if no node found or other error occurs
  550. """
  551. fdt = bytearray(size)
  552. fdt[:len(self._fdtrw)] = self._fdtrw
  553. err = check_err(fdt_resize(self._fdtrw, fdt, size), quiet)
  554. if err:
  555. return err
  556. self._fdtrw = fdt
  557. def add_reservemap_entry(self, addr, size, quiet=()):
  558. """Add a new memory reserve map entry
  559. Once finished adding, you must call finish_reservemap().
  560. Args:
  561. addr: 64-bit start address
  562. size: 64-bit size
  563. quiet: Errors to ignore (empty to raise on all errors)
  564. Raises:
  565. FdtException if no node found or other error occurs
  566. """
  567. return check_err(fdt_add_reservemap_entry(self._fdtrw, addr, size),
  568. quiet)
  569. def finish_reservemap(self, quiet=()):
  570. """Indicate that there are no more reserve map entries to add
  571. Args:
  572. quiet: Errors to ignore (empty to raise on all errors)
  573. Raises:
  574. FdtException if no node found or other error occurs
  575. """
  576. return check_err(fdt_finish_reservemap(self._fdtrw), quiet)
  577. def begin_node(self, name, quiet=()):
  578. """Begin a new node
  579. Use this before adding properties to the node. Then call end_node() to
  580. finish it. You can also use the context manager as shown in the FdtSw
  581. class comment.
  582. Args:
  583. name: Name of node to begin
  584. quiet: Errors to ignore (empty to raise on all errors)
  585. Raises:
  586. FdtException if no node found or other error occurs
  587. """
  588. return check_err(fdt_begin_node(self._fdtrw, name), quiet)
  589. def property_string(self, name, string, quiet=()):
  590. """Add a property with a string value
  591. The string will be nul-terminated when written to the device tree
  592. Args:
  593. name: Name of property to add
  594. string: String value of property
  595. quiet: Errors to ignore (empty to raise on all errors)
  596. Raises:
  597. FdtException if no node found or other error occurs
  598. """
  599. return check_err(fdt_property_string(self._fdtrw, name, string), quiet)
  600. def property_u32(self, name, val, quiet=()):
  601. """Add a property with a 32-bit value
  602. Write a single-cell value to the device tree
  603. Args:
  604. name: Name of property to add
  605. val: Value of property
  606. quiet: Errors to ignore (empty to raise on all errors)
  607. Raises:
  608. FdtException if no node found or other error occurs
  609. """
  610. return check_err(fdt_property_u32(self._fdtrw, name, val), quiet)
  611. def property_u64(self, name, val, quiet=()):
  612. """Add a property with a 64-bit value
  613. Write a double-cell value to the device tree in big-endian format
  614. Args:
  615. name: Name of property to add
  616. val: Value of property
  617. quiet: Errors to ignore (empty to raise on all errors)
  618. Raises:
  619. FdtException if no node found or other error occurs
  620. """
  621. return check_err(fdt_property_u64(self._fdtrw, name, val), quiet)
  622. def property_cell(self, name, val, quiet=()):
  623. """Add a property with a single-cell value
  624. Write a single-cell value to the device tree
  625. Args:
  626. name: Name of property to add
  627. val: Value of property
  628. quiet: Errors to ignore (empty to raise on all errors)
  629. Raises:
  630. FdtException if no node found or other error occurs
  631. """
  632. return check_err(fdt_property_cell(self._fdtrw, name, val), quiet)
  633. def property(self, name, val, quiet=()):
  634. """Add a property
  635. Write a new property with the given value to the device tree. The value
  636. is taken as is and is not nul-terminated
  637. Args:
  638. name: Name of property to add
  639. val: Value of property
  640. quiet: Errors to ignore (empty to raise on all errors)
  641. Raises:
  642. FdtException if no node found or other error occurs
  643. """
  644. return check_err(_fdt_property(self._fdtrw, name, val, len(val)), quiet)
  645. def end_node(self, quiet=()):
  646. """End a node
  647. Use this after adding properties to a node to close it off. You can also
  648. use the context manager as shown in the FdtSw class comment.
  649. Args:
  650. quiet: Errors to ignore (empty to raise on all errors)
  651. Raises:
  652. FdtException if no node found or other error occurs
  653. """
  654. return check_err(fdt_end_node(self._fdtrw), quiet)
  655. def finish(self, quiet=()):
  656. """Finish writing the device tree
  657. This closes off the device tree ready for use
  658. Args:
  659. quiet: Errors to ignore (empty to raise on all errors)
  660. Raises:
  661. FdtException if no node found or other error occurs
  662. """
  663. return check_err(fdt_finish(self._fdtrw), quiet)
  664. def AddNode(self, name):
  665. """Create a new context for adding a node
  666. When used in a 'with' clause this starts a new node and finishes it
  667. afterward.
  668. Args:
  669. name: Name of node to add
  670. """
  671. return NodeAdder(self._fdtrw, name)
  672. class NodeAdder():
  673. """Class to provide a node context
  674. This allows you to add nodes in a more natural way:
  675. with fdtsw.AddNode('name'):
  676. fdtsw.property_string('test', 'value')
  677. The node is automatically completed with a call to end_node() when the
  678. context exits.
  679. """
  680. def __init__(self, fdt, name):
  681. self._fdt = fdt
  682. self._name = name
  683. def __enter__(self):
  684. check_err(fdt_begin_node(self._fdt, self._name))
  685. def __exit__(self, type, value, traceback):
  686. check_err(fdt_end_node(self._fdt))
  687. %}
  688. %rename(fdt_property) fdt_property_func;
  689. typedef int fdt32_t;
  690. %include "libfdt/fdt.h"
  691. %include "typemaps.i"
  692. /* Most functions don't change the device tree, so use a const void * */
  693. %typemap(in) (const void *)(const void *fdt) {
  694. if (!PyByteArray_Check($input)) {
  695. SWIG_exception_fail(SWIG_TypeError, "in method '" "$symname"
  696. "', argument " "$argnum"" of type '" "$type""'");
  697. }
  698. $1 = (void *)PyByteArray_AsString($input);
  699. fdt = $1;
  700. fdt = fdt; /* avoid unused variable warning */
  701. }
  702. /* Some functions do change the device tree, so use void * */
  703. %typemap(in) (void *)(const void *fdt) {
  704. if (!PyByteArray_Check($input)) {
  705. SWIG_exception_fail(SWIG_TypeError, "in method '" "$symname"
  706. "', argument " "$argnum"" of type '" "$type""'");
  707. }
  708. $1 = PyByteArray_AsString($input);
  709. fdt = $1;
  710. fdt = fdt; /* avoid unused variable warning */
  711. }
  712. /* typemap used for fdt_get_property_by_offset() */
  713. %typemap(out) (struct fdt_property *) {
  714. PyObject *buff;
  715. if ($1) {
  716. resultobj = PyString_FromString(
  717. fdt_string(fdt1, fdt32_to_cpu($1->nameoff)));
  718. buff = PyByteArray_FromStringAndSize(
  719. (const char *)($1 + 1), fdt32_to_cpu($1->len));
  720. resultobj = SWIG_Python_AppendOutput(resultobj, buff);
  721. }
  722. }
  723. %apply int *OUTPUT { int *lenp };
  724. /* typemap used for fdt_getprop() */
  725. %typemap(out) (const void *) {
  726. if (!$1)
  727. $result = Py_None;
  728. else
  729. $result = Py_BuildValue("s#", $1, *arg4);
  730. }
  731. /* typemap used for fdt_setprop() */
  732. %typemap(in) (const void *val) {
  733. $1 = PyString_AsString($input); /* char *str */
  734. }
  735. /* typemap used for fdt_add_reservemap_entry() */
  736. %typemap(in) uint64_t {
  737. $1 = PyLong_AsUnsignedLong($input);
  738. }
  739. /* typemaps used for fdt_next_node() */
  740. %typemap(in, numinputs=1) int *depth (int depth) {
  741. depth = (int) PyInt_AsLong($input);
  742. $1 = &depth;
  743. }
  744. %typemap(argout) int *depth {
  745. PyObject *val = Py_BuildValue("i", *arg$argnum);
  746. resultobj = SWIG_Python_AppendOutput(resultobj, val);
  747. }
  748. %apply int *depth { int *depth };
  749. /* typemaps for fdt_get_mem_rsv */
  750. %typemap(in, numinputs=0) uint64_t * (uint64_t temp) {
  751. $1 = &temp;
  752. }
  753. %typemap(argout) uint64_t * {
  754. PyObject *val = PyLong_FromUnsignedLong(*arg$argnum);
  755. if (!result) {
  756. if (PyTuple_GET_SIZE(resultobj) == 0)
  757. resultobj = val;
  758. else
  759. resultobj = SWIG_Python_AppendOutput(resultobj, val);
  760. }
  761. }
  762. /* We have both struct fdt_property and a function fdt_property() */
  763. %warnfilter(302) fdt_property;
  764. /* These are macros in the header so have to be redefined here */
  765. int fdt_magic(const void *fdt);
  766. int fdt_totalsize(const void *fdt);
  767. int fdt_off_dt_struct(const void *fdt);
  768. int fdt_off_dt_strings(const void *fdt);
  769. int fdt_off_mem_rsvmap(const void *fdt);
  770. int fdt_version(const void *fdt);
  771. int fdt_last_comp_version(const void *fdt);
  772. int fdt_boot_cpuid_phys(const void *fdt);
  773. int fdt_size_dt_strings(const void *fdt);
  774. int fdt_size_dt_struct(const void *fdt);
  775. int fdt_property_string(void *fdt, const char *name, const char *val);
  776. int fdt_property_cell(void *fdt, const char *name, uint32_t val);
  777. /*
  778. * This function has a stub since the name fdt_property is used for both a
  779. * function and a struct, which confuses SWIG.
  780. */
  781. int _fdt_property(void *fdt, const char *name, const char *val, int len);
  782. %include <../libfdt/libfdt.h>