libfdt.i_shipped 31 KB

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