blob: 3245d02e09bf140800d2fd90e9e3c751196f08c3 [file] [log] [blame]
Simon Glassa542a702020-12-28 20:35:06 -07001#!/usr/bin/python
2# SPDX-License-Identifier: GPL-2.0+
3#
4# Copyright (C) 2017 Google, Inc
5# Written by Simon Glass <sjg@chromium.org>
6#
7
8"""Scanning of U-Boot source for drivers and structs
9
10This scans the source tree to find out things about all instances of
11U_BOOT_DRIVER(), UCLASS_DRIVER and all struct declarations in header files.
12
13See doc/driver-model/of-plat.rst for more informaiton
14"""
15
16import os
17import re
18import sys
19
20
21def conv_name_to_c(name):
22 """Convert a device-tree name to a C identifier
23
24 This uses multiple replace() calls instead of re.sub() since it is faster
25 (400ms for 1m calls versus 1000ms for the 're' version).
26
27 Args:
28 name (str): Name to convert
29 Return:
30 str: String containing the C version of this name
31 """
32 new = name.replace('@', '_at_')
33 new = new.replace('-', '_')
34 new = new.replace(',', '_')
35 new = new.replace('.', '_')
36 return new
37
38def get_compat_name(node):
39 """Get the node's list of compatible string as a C identifiers
40
41 Args:
42 node (fdt.Node): Node object to check
43 Return:
44 list of str: List of C identifiers for all the compatible strings
45 """
46 compat = node.props['compatible'].value
47 if not isinstance(compat, list):
48 compat = [compat]
49 return [conv_name_to_c(c) for c in compat]
50
51
52class Driver:
53 """Information about a driver in U-Boot
54
55 Attributes:
56 name: Name of driver. For U_BOOT_DRIVER(x) this is 'x'
Simon Glassc58662f2021-02-03 06:00:50 -070057 fname: Filename where the driver was found
58 uclass_id: Name of uclass, e.g. 'UCLASS_I2C'
59 compat: Driver data for each compatible string:
60 key: Compatible string, e.g. 'rockchip,rk3288-grf'
61 value: Driver data, e,g, 'ROCKCHIP_SYSCON_GRF', or None
62 fname: Filename where the driver was found
63 priv (str): struct name of the priv_auto member, e.g. 'serial_priv'
Simon Glassc8b19b02021-02-03 06:00:53 -070064 plat (str): struct name of the plat_auto member, e.g. 'serial_plat'
65 child_priv (str): struct name of the per_child_auto member,
66 e.g. 'pci_child_priv'
67 child_plat (str): struct name of the per_child_plat_auto member,
68 e.g. 'pci_child_plat'
Simon Glassa542a702020-12-28 20:35:06 -070069 """
Simon Glassc58662f2021-02-03 06:00:50 -070070 def __init__(self, name, fname):
Simon Glassa542a702020-12-28 20:35:06 -070071 self.name = name
Simon Glassc58662f2021-02-03 06:00:50 -070072 self.fname = fname
73 self.uclass_id = None
74 self.compat = None
75 self.priv = ''
Simon Glassc8b19b02021-02-03 06:00:53 -070076 self.plat = ''
77 self.child_priv = ''
78 self.child_plat = ''
Simon Glassa542a702020-12-28 20:35:06 -070079
80 def __eq__(self, other):
Simon Glassc58662f2021-02-03 06:00:50 -070081 return (self.name == other.name and
82 self.uclass_id == other.uclass_id and
83 self.compat == other.compat and
Simon Glassc8b19b02021-02-03 06:00:53 -070084 self.priv == other.priv and
85 self.plat == other.plat)
Simon Glassa542a702020-12-28 20:35:06 -070086
87 def __repr__(self):
Simon Glassc58662f2021-02-03 06:00:50 -070088 return ("Driver(name='%s', uclass_id='%s', compat=%s, priv=%s)" %
89 (self.name, self.uclass_id, self.compat, self.priv))
Simon Glassa542a702020-12-28 20:35:06 -070090
91
Simon Glass1a8b4b92021-02-03 06:00:54 -070092class UclassDriver:
93 """Holds information about a uclass driver
94
95 Attributes:
96 name: Uclass name, e.g. 'i2c' if the driver is for UCLASS_I2C
97 uclass_id: Uclass ID, e.g. 'UCLASS_I2C'
98 priv: struct name of the private data, e.g. 'i2c_priv'
99 per_dev_priv (str): struct name of the priv_auto member, e.g. 'spi_info'
100 per_dev_plat (str): struct name of the plat_auto member, e.g. 'i2c_chip'
101 per_child_priv (str): struct name of the per_child_auto member,
102 e.g. 'pci_child_priv'
103 per_child_plat (str): struct name of the per_child_plat_auto member,
104 e.g. 'pci_child_plat'
105 """
106 def __init__(self, name):
107 self.name = name
108 self.uclass_id = None
109 self.priv = ''
110 self.per_dev_priv = ''
111 self.per_dev_plat = ''
112 self.per_child_priv = ''
113 self.per_child_plat = ''
114
115 def __eq__(self, other):
116 return (self.name == other.name and
117 self.uclass_id == other.uclass_id and
118 self.priv == other.priv)
119
120 def __repr__(self):
121 return ("UclassDriver(name='%s', uclass_id='%s')" %
122 (self.name, self.uclass_id))
123
124 def __hash__(self):
125 # We can use the uclass ID since it is unique among uclasses
126 return hash(self.uclass_id)
127
128
Simon Glassa542a702020-12-28 20:35:06 -0700129class Scanner:
130 """Scanning of the U-Boot source tree
131
132 Properties:
133 _basedir (str): Base directory of U-Boot source code. Defaults to the
134 grandparent of this file's directory
135 _drivers: Dict of valid driver names found in drivers/
136 key: Driver name
137 value: Driver for that driver
138 _driver_aliases: Dict that holds aliases for driver names
139 key: Driver alias declared with
140 DM_DRIVER_ALIAS(driver_alias, driver_name)
141 value: Driver name declared with U_BOOT_DRIVER(driver_name)
Simon Glass10ea9c02020-12-28 20:35:07 -0700142 _warning_disabled: true to disable warnings about driver names not found
Simon Glassa542a702020-12-28 20:35:06 -0700143 _drivers_additional (list or str): List of additional drivers to use
144 during scanning
Simon Glassc58662f2021-02-03 06:00:50 -0700145 _of_match: Dict holding information about compatible strings
146 key: Name of struct udevice_id variable
147 value: Dict of compatible info in that variable:
148 key: Compatible string, e.g. 'rockchip,rk3288-grf'
149 value: Driver data, e,g, 'ROCKCHIP_SYSCON_GRF', or None
150 _compat_to_driver: Maps compatible strings to Driver
Simon Glass1a8b4b92021-02-03 06:00:54 -0700151 _uclass: Dict of uclass information
152 key: uclass name, e.g. 'UCLASS_I2C'
153 value: UClassDriver
Simon Glassa542a702020-12-28 20:35:06 -0700154 """
Simon Glass10ea9c02020-12-28 20:35:07 -0700155 def __init__(self, basedir, warning_disabled, drivers_additional):
Simon Glassa542a702020-12-28 20:35:06 -0700156 """Set up a new Scanner
157 """
158 if not basedir:
159 basedir = sys.argv[0].replace('tools/dtoc/dtoc', '')
160 if basedir == '':
161 basedir = './'
162 self._basedir = basedir
163 self._drivers = {}
164 self._driver_aliases = {}
165 self._drivers_additional = drivers_additional or []
166 self._warning_disabled = warning_disabled
Simon Glassc58662f2021-02-03 06:00:50 -0700167 self._of_match = {}
168 self._compat_to_driver = {}
Simon Glass1a8b4b92021-02-03 06:00:54 -0700169 self._uclass = {}
Simon Glassa542a702020-12-28 20:35:06 -0700170
171 def get_normalized_compat_name(self, node):
172 """Get a node's normalized compat name
173
174 Returns a valid driver name by retrieving node's list of compatible
175 string as a C identifier and performing a check against _drivers
176 and a lookup in driver_aliases printing a warning in case of failure.
177
178 Args:
179 node (Node): Node object to check
180 Return:
181 Tuple:
182 Driver name associated with the first compatible string
183 List of C identifiers for all the other compatible strings
184 (possibly empty)
185 In case of no match found, the return will be the same as
186 get_compat_name()
187 """
188 compat_list_c = get_compat_name(node)
189
190 for compat_c in compat_list_c:
191 if not compat_c in self._drivers.keys():
192 compat_c = self._driver_aliases.get(compat_c)
193 if not compat_c:
194 continue
195
196 aliases_c = compat_list_c
197 if compat_c in aliases_c:
198 aliases_c.remove(compat_c)
199 return compat_c, aliases_c
200
201 if not self._warning_disabled:
202 print('WARNING: the driver %s was not found in the driver list'
203 % (compat_list_c[0]))
204
205 return compat_list_c[0], compat_list_c[1:]
206
Simon Glassc58662f2021-02-03 06:00:50 -0700207 @classmethod
208 def _get_re_for_member(cls, member):
209 """_get_re_for_member: Get a compiled regular expression
210
211 Args:
212 member (str): Struct member name, e.g. 'priv_auto'
213
214 Returns:
215 re.Pattern: Compiled regular expression that parses:
216
217 .member = sizeof(struct fred),
218
219 and returns "fred" as group 1
220 """
221 return re.compile(r'^\s*.%s\s*=\s*sizeof\(struct\s+(.*)\),$' % member)
222
Simon Glass1a8b4b92021-02-03 06:00:54 -0700223 def _parse_uclass_driver(self, fname, buff):
224 """Parse a C file to extract uclass driver information contained within
225
226 This parses UCLASS_DRIVER() structs to obtain various pieces of useful
227 information.
228
229 It updates the following member:
230 _uclass: Dict of uclass information
231 key: uclass name, e.g. 'UCLASS_I2C'
232 value: UClassDriver
233
234 Args:
235 fname (str): Filename being parsed (used for warnings)
236 buff (str): Contents of file
237 """
238 uc_drivers = {}
239
240 # Collect the driver name and associated Driver
241 driver = None
242 re_driver = re.compile(r'UCLASS_DRIVER\((.*)\)')
243
244 # Collect the uclass ID, e.g. 'UCLASS_SPI'
245 re_id = re.compile(r'\s*\.id\s*=\s*(UCLASS_[A-Z0-9_]+)')
246
247 # Matches the header/size information for uclass-private data
248 re_priv = self._get_re_for_member('priv_auto')
249
250 # Set up parsing for the auto members
251 re_per_device_priv = self._get_re_for_member('per_device_auto')
252 re_per_device_plat = self._get_re_for_member('per_device_plat_auto')
253 re_per_child_priv = self._get_re_for_member('per_child_auto')
254 re_per_child_plat = self._get_re_for_member('per_child_plat_auto')
255
256 prefix = ''
257 for line in buff.splitlines():
258 # Handle line continuation
259 if prefix:
260 line = prefix + line
261 prefix = ''
262 if line.endswith('\\'):
263 prefix = line[:-1]
264 continue
265
266 driver_match = re_driver.search(line)
267
268 # If we have seen UCLASS_DRIVER()...
269 if driver:
270 m_id = re_id.search(line)
271 m_priv = re_priv.match(line)
272 m_per_dev_priv = re_per_device_priv.match(line)
273 m_per_dev_plat = re_per_device_plat.match(line)
274 m_per_child_priv = re_per_child_priv.match(line)
275 m_per_child_plat = re_per_child_plat.match(line)
276 if m_id:
277 driver.uclass_id = m_id.group(1)
278 elif m_priv:
279 driver.priv = m_priv.group(1)
280 elif m_per_dev_priv:
281 driver.per_dev_priv = m_per_dev_priv.group(1)
282 elif m_per_dev_plat:
283 driver.per_dev_plat = m_per_dev_plat.group(1)
284 elif m_per_child_priv:
285 driver.per_child_priv = m_per_child_priv.group(1)
286 elif m_per_child_plat:
287 driver.per_child_plat = m_per_child_plat.group(1)
288 elif '};' in line:
289 if not driver.uclass_id:
290 raise ValueError(
291 "%s: Cannot parse uclass ID in driver '%s'" %
292 (fname, driver.name))
293 uc_drivers[driver.uclass_id] = driver
294 driver = None
295
296 elif driver_match:
297 driver_name = driver_match.group(1)
298 driver = UclassDriver(driver_name)
299
300 self._uclass.update(uc_drivers)
301
Simon Glassc58662f2021-02-03 06:00:50 -0700302 def _parse_driver(self, fname, buff):
303 """Parse a C file to extract driver information contained within
304
305 This parses U_BOOT_DRIVER() structs to obtain various pieces of useful
306 information.
307
308 It updates the following members:
309 _drivers - updated with new Driver records for each driver found
310 in the file
311 _of_match - updated with each compatible string found in the file
312 _compat_to_driver - Maps compatible string to Driver
313
314 Args:
315 fname (str): Filename being parsed (used for warnings)
316 buff (str): Contents of file
317
318 Raises:
319 ValueError: Compatible variable is mentioned in .of_match in
320 U_BOOT_DRIVER() but not found in the file
321 """
322 # Dict holding information about compatible strings collected in this
323 # function so far
324 # key: Name of struct udevice_id variable
325 # value: Dict of compatible info in that variable:
326 # key: Compatible string, e.g. 'rockchip,rk3288-grf'
327 # value: Driver data, e,g, 'ROCKCHIP_SYSCON_GRF', or None
328 of_match = {}
329
330 # Dict holding driver information collected in this function so far
331 # key: Driver name (C name as in U_BOOT_DRIVER(xxx))
332 # value: Driver
333 drivers = {}
334
335 # Collect the driver info
336 driver = None
337 re_driver = re.compile(r'U_BOOT_DRIVER\((.*)\)')
338
339 # Collect the uclass ID, e.g. 'UCLASS_SPI'
340 re_id = re.compile(r'\s*\.id\s*=\s*(UCLASS_[A-Z0-9_]+)')
341
342 # Collect the compatible string, e.g. 'rockchip,rk3288-grf'
343 compat = None
344 re_compat = re.compile(r'{\s*.compatible\s*=\s*"(.*)"\s*'
345 r'(,\s*.data\s*=\s*(\S*))?\s*},')
346
347 # This is a dict of compatible strings that were found:
348 # key: Compatible string, e.g. 'rockchip,rk3288-grf'
349 # value: Driver data, e,g, 'ROCKCHIP_SYSCON_GRF', or None
350 compat_dict = {}
351
352 # Holds the var nane of the udevice_id list, e.g.
353 # 'rk3288_syscon_ids_noc' in
354 # static const struct udevice_id rk3288_syscon_ids_noc[] = {
355 ids_name = None
356 re_ids = re.compile(r'struct udevice_id (.*)\[\]\s*=')
357
358 # Matches the references to the udevice_id list
359 re_of_match = re.compile(
360 r'\.of_match\s*=\s*(of_match_ptr\()?([a-z0-9_]+)(\))?,')
361
Simon Glassc8b19b02021-02-03 06:00:53 -0700362 # Matches the struct name for priv, plat
Simon Glassc58662f2021-02-03 06:00:50 -0700363 re_priv = self._get_re_for_member('priv_auto')
Simon Glassc8b19b02021-02-03 06:00:53 -0700364 re_plat = self._get_re_for_member('plat_auto')
365 re_child_priv = self._get_re_for_member('per_child_auto')
366 re_child_plat = self._get_re_for_member('per_child_plat_auto')
Simon Glassc58662f2021-02-03 06:00:50 -0700367
368 prefix = ''
369 for line in buff.splitlines():
370 # Handle line continuation
371 if prefix:
372 line = prefix + line
373 prefix = ''
374 if line.endswith('\\'):
375 prefix = line[:-1]
376 continue
377
378 driver_match = re_driver.search(line)
379
380 # If this line contains U_BOOT_DRIVER()...
381 if driver:
382 m_id = re_id.search(line)
383 m_of_match = re_of_match.search(line)
384 m_priv = re_priv.match(line)
Simon Glassc8b19b02021-02-03 06:00:53 -0700385 m_plat = re_plat.match(line)
386 m_cplat = re_child_plat.match(line)
387 m_cpriv = re_child_priv.match(line)
Simon Glassc58662f2021-02-03 06:00:50 -0700388 if m_priv:
389 driver.priv = m_priv.group(1)
Simon Glassc8b19b02021-02-03 06:00:53 -0700390 elif m_plat:
391 driver.plat = m_plat.group(1)
392 elif m_cplat:
393 driver.child_plat = m_cplat.group(1)
394 elif m_cpriv:
395 driver.child_priv = m_cpriv.group(1)
Simon Glassc58662f2021-02-03 06:00:50 -0700396 elif m_id:
397 driver.uclass_id = m_id.group(1)
398 elif m_of_match:
399 compat = m_of_match.group(2)
400 elif '};' in line:
401 if driver.uclass_id and compat:
402 if compat not in of_match:
403 raise ValueError(
404 "%s: Unknown compatible var '%s' (found: %s)" %
405 (fname, compat, ','.join(of_match.keys())))
406 driver.compat = of_match[compat]
407
408 # This needs to be deterministic, since a driver may
409 # have multiple compatible strings pointing to it.
410 # We record the one earliest in the alphabet so it
411 # will produce the same result on all machines.
412 for compat_id in of_match[compat]:
413 old = self._compat_to_driver.get(compat_id)
414 if not old or driver.name < old.name:
415 self._compat_to_driver[compat_id] = driver
416 drivers[driver.name] = driver
417 else:
418 # The driver does not have a uclass or compat string.
419 # The first is required but the second is not, so just
420 # ignore this.
421 pass
422 driver = None
423 ids_name = None
424 compat = None
425 compat_dict = {}
426
427 elif ids_name:
428 compat_m = re_compat.search(line)
429 if compat_m:
430 compat_dict[compat_m.group(1)] = compat_m.group(3)
431 elif '};' in line:
432 of_match[ids_name] = compat_dict
433 ids_name = None
434 elif driver_match:
435 driver_name = driver_match.group(1)
436 driver = Driver(driver_name, fname)
437 else:
438 ids_m = re_ids.search(line)
439 if ids_m:
440 ids_name = ids_m.group(1)
441
442 # Make the updates based on what we found
443 self._drivers.update(drivers)
444 self._of_match.update(of_match)
445
Simon Glassa542a702020-12-28 20:35:06 -0700446 def scan_driver(self, fname):
447 """Scan a driver file to build a list of driver names and aliases
448
Simon Glassc58662f2021-02-03 06:00:50 -0700449 It updates the following members:
450 _drivers - updated with new Driver records for each driver found
451 in the file
452 _of_match - updated with each compatible string found in the file
453 _compat_to_driver - Maps compatible string to Driver
454 _driver_aliases - Maps alias names to driver name
Simon Glassa542a702020-12-28 20:35:06 -0700455
456 Args
457 fname: Driver filename to scan
458 """
459 with open(fname, encoding='utf-8') as inf:
460 try:
461 buff = inf.read()
462 except UnicodeDecodeError:
463 # This seems to happen on older Python versions
464 print("Skipping file '%s' due to unicode error" % fname)
465 return
466
Simon Glassc58662f2021-02-03 06:00:50 -0700467 # If this file has any U_BOOT_DRIVER() declarations, process it to
468 # obtain driver information
469 if 'U_BOOT_DRIVER' in buff:
470 self._parse_driver(fname, buff)
Simon Glass1a8b4b92021-02-03 06:00:54 -0700471 if 'UCLASS_DRIVER' in buff:
472 self._parse_uclass_driver(fname, buff)
Simon Glassa542a702020-12-28 20:35:06 -0700473
474 # The following re will search for driver aliases declared as
475 # DM_DRIVER_ALIAS(alias, driver_name)
476 driver_aliases = re.findall(
477 r'DM_DRIVER_ALIAS\(\s*(\w+)\s*,\s*(\w+)\s*\)',
478 buff)
479
480 for alias in driver_aliases: # pragma: no cover
481 if len(alias) != 2:
482 continue
483 self._driver_aliases[alias[1]] = alias[0]
484
485 def scan_drivers(self):
486 """Scan the driver folders to build a list of driver names and aliases
487
488 This procedure will populate self._drivers and self._driver_aliases
489 """
490 for (dirpath, _, filenames) in os.walk(self._basedir):
Simon Glass36b22202021-02-03 06:00:52 -0700491 rel_path = dirpath[len(self._basedir):]
492 if rel_path.startswith('/'):
493 rel_path = rel_path[1:]
494 if rel_path.startswith('build') or rel_path.startswith('.git'):
495 continue
Simon Glassa542a702020-12-28 20:35:06 -0700496 for fname in filenames:
497 if not fname.endswith('.c'):
498 continue
499 self.scan_driver(dirpath + '/' + fname)
500
501 for fname in self._drivers_additional:
502 if not isinstance(fname, str) or len(fname) == 0:
503 continue
504 if fname[0] == '/':
505 self.scan_driver(fname)
506 else:
507 self.scan_driver(self._basedir + '/' + fname)