blob: ff3ab409e4b04e2cfc8efbe85dc7f67ebe6275d6 [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
92class Scanner:
93 """Scanning of the U-Boot source tree
94
95 Properties:
96 _basedir (str): Base directory of U-Boot source code. Defaults to the
97 grandparent of this file's directory
98 _drivers: Dict of valid driver names found in drivers/
99 key: Driver name
100 value: Driver for that driver
101 _driver_aliases: Dict that holds aliases for driver names
102 key: Driver alias declared with
103 DM_DRIVER_ALIAS(driver_alias, driver_name)
104 value: Driver name declared with U_BOOT_DRIVER(driver_name)
Simon Glass10ea9c02020-12-28 20:35:07 -0700105 _warning_disabled: true to disable warnings about driver names not found
Simon Glassa542a702020-12-28 20:35:06 -0700106 _drivers_additional (list or str): List of additional drivers to use
107 during scanning
Simon Glassc58662f2021-02-03 06:00:50 -0700108 _of_match: Dict holding information about compatible strings
109 key: Name of struct udevice_id variable
110 value: Dict of compatible info in that variable:
111 key: Compatible string, e.g. 'rockchip,rk3288-grf'
112 value: Driver data, e,g, 'ROCKCHIP_SYSCON_GRF', or None
113 _compat_to_driver: Maps compatible strings to Driver
Simon Glassa542a702020-12-28 20:35:06 -0700114 """
Simon Glass10ea9c02020-12-28 20:35:07 -0700115 def __init__(self, basedir, warning_disabled, drivers_additional):
Simon Glassa542a702020-12-28 20:35:06 -0700116 """Set up a new Scanner
117 """
118 if not basedir:
119 basedir = sys.argv[0].replace('tools/dtoc/dtoc', '')
120 if basedir == '':
121 basedir = './'
122 self._basedir = basedir
123 self._drivers = {}
124 self._driver_aliases = {}
125 self._drivers_additional = drivers_additional or []
126 self._warning_disabled = warning_disabled
Simon Glassc58662f2021-02-03 06:00:50 -0700127 self._of_match = {}
128 self._compat_to_driver = {}
Simon Glassa542a702020-12-28 20:35:06 -0700129
130 def get_normalized_compat_name(self, node):
131 """Get a node's normalized compat name
132
133 Returns a valid driver name by retrieving node's list of compatible
134 string as a C identifier and performing a check against _drivers
135 and a lookup in driver_aliases printing a warning in case of failure.
136
137 Args:
138 node (Node): Node object to check
139 Return:
140 Tuple:
141 Driver name associated with the first compatible string
142 List of C identifiers for all the other compatible strings
143 (possibly empty)
144 In case of no match found, the return will be the same as
145 get_compat_name()
146 """
147 compat_list_c = get_compat_name(node)
148
149 for compat_c in compat_list_c:
150 if not compat_c in self._drivers.keys():
151 compat_c = self._driver_aliases.get(compat_c)
152 if not compat_c:
153 continue
154
155 aliases_c = compat_list_c
156 if compat_c in aliases_c:
157 aliases_c.remove(compat_c)
158 return compat_c, aliases_c
159
160 if not self._warning_disabled:
161 print('WARNING: the driver %s was not found in the driver list'
162 % (compat_list_c[0]))
163
164 return compat_list_c[0], compat_list_c[1:]
165
Simon Glassc58662f2021-02-03 06:00:50 -0700166 @classmethod
167 def _get_re_for_member(cls, member):
168 """_get_re_for_member: Get a compiled regular expression
169
170 Args:
171 member (str): Struct member name, e.g. 'priv_auto'
172
173 Returns:
174 re.Pattern: Compiled regular expression that parses:
175
176 .member = sizeof(struct fred),
177
178 and returns "fred" as group 1
179 """
180 return re.compile(r'^\s*.%s\s*=\s*sizeof\(struct\s+(.*)\),$' % member)
181
182 def _parse_driver(self, fname, buff):
183 """Parse a C file to extract driver information contained within
184
185 This parses U_BOOT_DRIVER() structs to obtain various pieces of useful
186 information.
187
188 It updates the following members:
189 _drivers - updated with new Driver records for each driver found
190 in the file
191 _of_match - updated with each compatible string found in the file
192 _compat_to_driver - Maps compatible string to Driver
193
194 Args:
195 fname (str): Filename being parsed (used for warnings)
196 buff (str): Contents of file
197
198 Raises:
199 ValueError: Compatible variable is mentioned in .of_match in
200 U_BOOT_DRIVER() but not found in the file
201 """
202 # Dict holding information about compatible strings collected in this
203 # function so far
204 # key: Name of struct udevice_id variable
205 # value: Dict of compatible info in that variable:
206 # key: Compatible string, e.g. 'rockchip,rk3288-grf'
207 # value: Driver data, e,g, 'ROCKCHIP_SYSCON_GRF', or None
208 of_match = {}
209
210 # Dict holding driver information collected in this function so far
211 # key: Driver name (C name as in U_BOOT_DRIVER(xxx))
212 # value: Driver
213 drivers = {}
214
215 # Collect the driver info
216 driver = None
217 re_driver = re.compile(r'U_BOOT_DRIVER\((.*)\)')
218
219 # Collect the uclass ID, e.g. 'UCLASS_SPI'
220 re_id = re.compile(r'\s*\.id\s*=\s*(UCLASS_[A-Z0-9_]+)')
221
222 # Collect the compatible string, e.g. 'rockchip,rk3288-grf'
223 compat = None
224 re_compat = re.compile(r'{\s*.compatible\s*=\s*"(.*)"\s*'
225 r'(,\s*.data\s*=\s*(\S*))?\s*},')
226
227 # This is a dict of compatible strings that were found:
228 # key: Compatible string, e.g. 'rockchip,rk3288-grf'
229 # value: Driver data, e,g, 'ROCKCHIP_SYSCON_GRF', or None
230 compat_dict = {}
231
232 # Holds the var nane of the udevice_id list, e.g.
233 # 'rk3288_syscon_ids_noc' in
234 # static const struct udevice_id rk3288_syscon_ids_noc[] = {
235 ids_name = None
236 re_ids = re.compile(r'struct udevice_id (.*)\[\]\s*=')
237
238 # Matches the references to the udevice_id list
239 re_of_match = re.compile(
240 r'\.of_match\s*=\s*(of_match_ptr\()?([a-z0-9_]+)(\))?,')
241
Simon Glassc8b19b02021-02-03 06:00:53 -0700242 # Matches the struct name for priv, plat
Simon Glassc58662f2021-02-03 06:00:50 -0700243 re_priv = self._get_re_for_member('priv_auto')
Simon Glassc8b19b02021-02-03 06:00:53 -0700244 re_plat = self._get_re_for_member('plat_auto')
245 re_child_priv = self._get_re_for_member('per_child_auto')
246 re_child_plat = self._get_re_for_member('per_child_plat_auto')
Simon Glassc58662f2021-02-03 06:00:50 -0700247
248 prefix = ''
249 for line in buff.splitlines():
250 # Handle line continuation
251 if prefix:
252 line = prefix + line
253 prefix = ''
254 if line.endswith('\\'):
255 prefix = line[:-1]
256 continue
257
258 driver_match = re_driver.search(line)
259
260 # If this line contains U_BOOT_DRIVER()...
261 if driver:
262 m_id = re_id.search(line)
263 m_of_match = re_of_match.search(line)
264 m_priv = re_priv.match(line)
Simon Glassc8b19b02021-02-03 06:00:53 -0700265 m_plat = re_plat.match(line)
266 m_cplat = re_child_plat.match(line)
267 m_cpriv = re_child_priv.match(line)
Simon Glassc58662f2021-02-03 06:00:50 -0700268 if m_priv:
269 driver.priv = m_priv.group(1)
Simon Glassc8b19b02021-02-03 06:00:53 -0700270 elif m_plat:
271 driver.plat = m_plat.group(1)
272 elif m_cplat:
273 driver.child_plat = m_cplat.group(1)
274 elif m_cpriv:
275 driver.child_priv = m_cpriv.group(1)
Simon Glassc58662f2021-02-03 06:00:50 -0700276 elif m_id:
277 driver.uclass_id = m_id.group(1)
278 elif m_of_match:
279 compat = m_of_match.group(2)
280 elif '};' in line:
281 if driver.uclass_id and compat:
282 if compat not in of_match:
283 raise ValueError(
284 "%s: Unknown compatible var '%s' (found: %s)" %
285 (fname, compat, ','.join(of_match.keys())))
286 driver.compat = of_match[compat]
287
288 # This needs to be deterministic, since a driver may
289 # have multiple compatible strings pointing to it.
290 # We record the one earliest in the alphabet so it
291 # will produce the same result on all machines.
292 for compat_id in of_match[compat]:
293 old = self._compat_to_driver.get(compat_id)
294 if not old or driver.name < old.name:
295 self._compat_to_driver[compat_id] = driver
296 drivers[driver.name] = driver
297 else:
298 # The driver does not have a uclass or compat string.
299 # The first is required but the second is not, so just
300 # ignore this.
301 pass
302 driver = None
303 ids_name = None
304 compat = None
305 compat_dict = {}
306
307 elif ids_name:
308 compat_m = re_compat.search(line)
309 if compat_m:
310 compat_dict[compat_m.group(1)] = compat_m.group(3)
311 elif '};' in line:
312 of_match[ids_name] = compat_dict
313 ids_name = None
314 elif driver_match:
315 driver_name = driver_match.group(1)
316 driver = Driver(driver_name, fname)
317 else:
318 ids_m = re_ids.search(line)
319 if ids_m:
320 ids_name = ids_m.group(1)
321
322 # Make the updates based on what we found
323 self._drivers.update(drivers)
324 self._of_match.update(of_match)
325
Simon Glassa542a702020-12-28 20:35:06 -0700326 def scan_driver(self, fname):
327 """Scan a driver file to build a list of driver names and aliases
328
Simon Glassc58662f2021-02-03 06:00:50 -0700329 It updates the following members:
330 _drivers - updated with new Driver records for each driver found
331 in the file
332 _of_match - updated with each compatible string found in the file
333 _compat_to_driver - Maps compatible string to Driver
334 _driver_aliases - Maps alias names to driver name
Simon Glassa542a702020-12-28 20:35:06 -0700335
336 Args
337 fname: Driver filename to scan
338 """
339 with open(fname, encoding='utf-8') as inf:
340 try:
341 buff = inf.read()
342 except UnicodeDecodeError:
343 # This seems to happen on older Python versions
344 print("Skipping file '%s' due to unicode error" % fname)
345 return
346
Simon Glassc58662f2021-02-03 06:00:50 -0700347 # If this file has any U_BOOT_DRIVER() declarations, process it to
348 # obtain driver information
349 if 'U_BOOT_DRIVER' in buff:
350 self._parse_driver(fname, buff)
Simon Glassa542a702020-12-28 20:35:06 -0700351
352 # The following re will search for driver aliases declared as
353 # DM_DRIVER_ALIAS(alias, driver_name)
354 driver_aliases = re.findall(
355 r'DM_DRIVER_ALIAS\(\s*(\w+)\s*,\s*(\w+)\s*\)',
356 buff)
357
358 for alias in driver_aliases: # pragma: no cover
359 if len(alias) != 2:
360 continue
361 self._driver_aliases[alias[1]] = alias[0]
362
363 def scan_drivers(self):
364 """Scan the driver folders to build a list of driver names and aliases
365
366 This procedure will populate self._drivers and self._driver_aliases
367 """
368 for (dirpath, _, filenames) in os.walk(self._basedir):
Simon Glass36b22202021-02-03 06:00:52 -0700369 rel_path = dirpath[len(self._basedir):]
370 if rel_path.startswith('/'):
371 rel_path = rel_path[1:]
372 if rel_path.startswith('build') or rel_path.startswith('.git'):
373 continue
Simon Glassa542a702020-12-28 20:35:06 -0700374 for fname in filenames:
375 if not fname.endswith('.c'):
376 continue
377 self.scan_driver(dirpath + '/' + fname)
378
379 for fname in self._drivers_additional:
380 if not isinstance(fname, str) or len(fname) == 0:
381 continue
382 if fname[0] == '/':
383 self.scan_driver(fname)
384 else:
385 self.scan_driver(self._basedir + '/' + fname)