Import U-Boot v2026.07 (unmodified upstream source, base for rtwo patches)

This commit is contained in:
2026-09-16 23:15:56 -03:00
commit 391981275c
38022 changed files with 8370285 additions and 0 deletions
+1
View File
@@ -0,0 +1 @@
*.pyc
+15
View File
@@ -0,0 +1,15 @@
.. SPDX-License-Identifier: GPL-2.0+
Devicetree-to-C generator
=========================
This is a Python program and associated utilities, which supports converting
devicetree files into C code. It generates header files containing struct
definitions, as well as C files containing the data. It does not require any
modification of the devicetree files.
Some high-level libraries are provided for working with devicetree. These may
be useful in other projects.
This package also includes some U-Boot-specific features, such as creating
`struct udevice` and `struct uclass` entries for devicetree nodes.
View File
File diff suppressed because it is too large Load Diff
+1
View File
@@ -0,0 +1 @@
main.py
+1006
View File
File diff suppressed because it is too large Load Diff
+334
View File
@@ -0,0 +1,334 @@
#!/usr/bin/python
# SPDX-License-Identifier: GPL-2.0+
#
# Copyright (C) 2016 Google, Inc
# Written by Simon Glass <sjg@chromium.org>
#
# Utility functions for reading from a device tree. Once the upstream pylibfdt
# implementation advances far enough, we should be able to drop these.
import os
import struct
import sys
import tempfile
from u_boot_pylib import command
from u_boot_pylib import tools
def fdt32_to_cpu(val):
"""Convert a device tree cell to an integer
Args:
Value to convert (4-character string representing the cell value)
Return:
A native-endian integer value
"""
return struct.unpack('>I', val)[0]
def fdt64_to_cpu(val):
"""Convert a device tree cell to an integer
Args:
val (list): Value to convert (list of 2 4-character strings representing
the cell value)
Return:
int: A native-endian integer value
"""
return fdt32_to_cpu(val[0]) << 32 | fdt32_to_cpu(val[1])
def fdt_cells_to_cpu(val, cells):
"""Convert one or two cells to a long integer
Args:
Value to convert (array of one or more 4-character strings)
Return:
A native-endian integer value
"""
if not cells:
return 0
out = int(fdt32_to_cpu(val[0]))
if cells == 2:
out = out << 32 | fdt32_to_cpu(val[1])
return out
def EnsureCompiled(fname, tmpdir=None, capture_stderr=False, indir=None):
"""Compile an fdt .dts source file into a .dtb binary blob if needed.
Args:
fname: Filename (if .dts it will be compiled). It not it will be
left alone
tmpdir: Temporary directory for output files, or None to use the
tools-module output directory
indir: List of directories where input files can be found
Returns:
Filename of resulting .dtb file
"""
_, ext = os.path.splitext(fname)
if ext != '.dts':
return fname
if tmpdir:
dts_input = os.path.join(tmpdir, 'source.dts')
dtb_output = os.path.join(tmpdir, 'source.dtb')
else:
dts_input = tools.get_output_filename('source.dts')
dtb_output = tools.get_output_filename('source.dtb')
search_paths = [os.path.join(os.getcwd(), 'include')]
if indir is not None:
search_paths += indir
root, _ = os.path.splitext(fname)
cc, args = tools.get_target_compile_tool('cc')
args += ['-E', '-P', '-x', 'assembler-with-cpp', '-D__ASSEMBLY__']
args += ['-Ulinux']
for path in search_paths:
args.extend(['-I', path])
args += ['-o', dts_input, fname]
command.run(cc, *args)
# If we don't have a directory, put it in the tools tempdir
search_list = []
for path in search_paths:
search_list.extend(['-i', path])
dtc, args = tools.get_target_compile_tool('dtc')
args += ['-I', 'dts', '-o', dtb_output, '-O', 'dtb',
'-W', 'no-unit_address_vs_reg']
args.extend(search_list)
args.append(dts_input)
command.run(dtc, *args, capture_stderr=capture_stderr)
return dtb_output
def GetInt(node, propname, default=None):
"""Get an integer from a property
Args:
node: Node object to read from
propname: property name to read
default: Default value to use if the node/property do not exist
Returns:
Integer value read, or default if none
"""
prop = node.props.get(propname)
if not prop:
return default
if isinstance(prop.value, list):
raise ValueError("Node '%s' property '%s' has list value: expecting "
"a single integer" % (node.name, propname))
value = fdt32_to_cpu(prop.value)
return value
def GetInt64(node, propname, default=None):
"""Get a 64-bit integer from a property
Args:
node (Node): Node object to read from
propname (str): property name to read
default (int): Default value to use if the node/property do not exist
Returns:
int: value read, or default if none
Raises:
ValueError: Property is not of the correct size
"""
prop = node.props.get(propname)
if not prop:
return default
if not isinstance(prop.value, list) or len(prop.value) != 2:
raise ValueError("Node '%s' property '%s' should be a list with 2 items for 64-bit values" %
(node.name, propname))
value = fdt64_to_cpu(prop.value)
return value
def GetString(node, propname, default=None):
"""Get a string from a property
Args:
node: Node object to read from
propname: property name to read
default: Default value to use if the node/property do not exist
Returns:
String value read, or default if none
"""
prop = node.props.get(propname)
if not prop:
return default
value = prop.value
if not prop.bytes:
return ''
if isinstance(value, list):
raise ValueError("Node '%s' property '%s' has list value: expecting "
"a single string" % (node.name, propname))
return value
def GetStringList(node, propname, default=None):
"""Get a string list from a property
Args:
node (Node): Node object to read from
propname (str): property name to read
default (list of str): Default value to use if the node/property do not
exist, or None
Returns:
String value read, or default if none
"""
prop = node.props.get(propname)
if not prop:
return default
value = prop.value
if not prop.bytes:
return []
if not isinstance(value, list):
strval = GetString(node, propname)
return [strval]
return value
def GetArgs(node, propname):
prop = node.props.get(propname)
if not prop:
raise ValueError(f"Node '{node.path}': Expected property '{propname}'")
if prop.bytes:
value = GetStringList(node, propname)
else:
value = []
if not value:
args = []
elif len(value) == 1:
args = value[0].split()
else:
args = value
return args
def GetBool(node, propname, default=False):
"""Get an boolean from a property
Args:
node: Node object to read from
propname: property name to read
default: Default value to use if the node/property do not exist
Returns:
Boolean value read, or default if none (if you set this to True the
function will always return True)
"""
if propname in node.props:
return True
return default
def GetByte(node, propname, default=None):
"""Get an byte from a property
Args:
node: Node object to read from
propname: property name to read
default: Default value to use if the node/property do not exist
Returns:
Byte value read, or default if none
"""
prop = node.props.get(propname)
if not prop:
return default
value = prop.value
if isinstance(value, list):
raise ValueError("Node '%s' property '%s' has list value: expecting "
"a single byte" % (node.name, propname))
if len(value) != 1:
raise ValueError("Node '%s' property '%s' has length %d, expecting %d" %
(node.name, propname, len(value), 1))
return ord(value[0])
def GetBytes(node, propname, size, default=None):
"""Get a set of bytes from a property
Args:
node (Node): Node object to read from
propname (str): property name to read
size (int): Number of bytes to expect
default (bytes): Default value or None
Returns:
bytes: Bytes value read, or default if none
"""
prop = node.props.get(propname)
if not prop:
return default
if len(prop.bytes) != size:
raise ValueError("Node '%s' property '%s' has length %d, expecting %d" %
(node.name, propname, len(prop.bytes), size))
return prop.bytes
def GetPhandleList(node, propname):
"""Get a list of phandles from a property
Args:
node: Node object to read from
propname: property name to read
Returns:
List of phandles read, each an integer
"""
prop = node.props.get(propname)
if not prop:
return None
value = prop.value
if not isinstance(value, list):
value = [value]
return [fdt32_to_cpu(v) for v in value]
def GetPhandleNameOffset(node, propname):
"""Get a <&phandle>, "string", <offset> value from a property
Args:
node: Node object to read from
propname: property name to read
Returns:
tuple:
Node object
str
int
or None if the property does not exist
"""
prop = node.props.get(propname)
if not prop:
return None
value = prop.bytes
phandle = fdt32_to_cpu(value[:4])
node = node.GetFdt().LookupPhandle(phandle)
name = ''
for byte in value[4:]:
if not byte:
break
name += chr(byte)
val = fdt32_to_cpu(value[4 + len(name) + 1:])
return node, name, val
def GetDatatype(node, propname, datatype):
"""Get a value of a given type from a property
Args:
node: Node object to read from
propname: property name to read
datatype: Type to read (str or int)
Returns:
value read, or None if none
Raises:
ValueError if datatype is not str or int
"""
if datatype == str:
return GetString(node, propname)
elif datatype == int:
return GetInt(node, propname)
raise ValueError("fdt_util internal error: Unknown data type '%s'" %
datatype)
+127
View File
@@ -0,0 +1,127 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-2.0+
#
# Copyright (C) 2016 Google, Inc
# Written by Simon Glass <sjg@chromium.org>
#
"""Device tree to C tool
This tool converts a device tree binary file (.dtb) into two C files. The
indent is to allow a C program to access data from the device tree without
having to link against libfdt. By putting the data from the device tree into
C structures, normal C code can be used. This helps to reduce the size of the
compiled program.
Dtoc produces several output files - see OUTPUT_FILES in dtb_platdata.py
This tool is used in U-Boot to provide device tree data to SPL without
increasing the code size of SPL. This supports the CONFIG_SPL_OF_PLATDATA
options. For more information about the use of this options and tool please
see doc/driver-model/of-plat.rst
"""
from argparse import ArgumentParser
import os
import pathlib
import sys
# Bring in the patman libraries
our_path = os.path.dirname(os.path.realpath(__file__))
sys.path.append(os.path.join(our_path, '..'))
# Bring in the libfdt module
sys.path.insert(0, 'scripts/dtc/pylibfdt')
sys.path.insert(0, os.path.join(our_path,
'../../build-sandbox_spl/scripts/dtc/pylibfdt'))
from dtoc import dtb_platdata
from u_boot_pylib import test_util
DTOC_DIR = pathlib.Path(__file__).parent
HAVE_TESTS = (DTOC_DIR / 'test_dtoc.py').exists()
def run_tests(processes, args):
"""Run all the test we have for dtoc
Args:
processes: Number of processes to use to run tests (None=same as #CPUs)
args: List of positional args provided to dtoc. This can hold a test
name to execute (as in 'dtoc -t test_empty_file', for example)
"""
from dtoc import test_src_scan
from dtoc import test_dtoc
sys.argv = [sys.argv[0]]
test_name = args.files and args.files[0] or None
test_dtoc.setup()
result = test_util.run_test_suites(
toolname='dtoc', debug=True, verbosity=1, no_capture=False,
test_preserve_dirs=False, processes=processes, test_name=test_name,
toolpath=[],
class_and_module_list=[test_dtoc.TestDtoc,test_src_scan.TestSrcScan])
return (0 if result.wasSuccessful() else 1)
def RunTestCoverage(build_dir):
"""Run the tests and check that we get 100% coverage"""
sys.argv = [sys.argv[0]]
test_util.run_test_coverage('tools/dtoc/dtoc', '/main.py',
['tools/patman/*.py', 'tools/u_boot_pylib/*','*/fdt*', '*test*'],
build_dir)
def run_dtoc():
epilog = 'Generate C code from devicetree files. See of-plat.rst for details'
parser = ArgumentParser(epilog=epilog)
parser.add_argument('-B', '--build-dir', type=str, default='b',
help='Directory containing the build output')
parser.add_argument('-c', '--c-output-dir', action='store',
help='Select output directory for C files')
parser.add_argument(
'-C', '--h-output-dir', action='store',
help='Select output directory for H files (defaults to --c-output-di)')
parser.add_argument('-d', '--dtb-file', action='store',
help='Specify the .dtb input file')
parser.add_argument(
'-i', '--instantiate', action='store_true', default=False,
help='Instantiate devices to avoid needing device_bind()')
parser.add_argument('--include-disabled', action='store_true',
help='Include disabled nodes')
parser.add_argument('-o', '--output', action='store',
help='Select output filename')
parser.add_argument(
'-p', '--phase', type=str,
help='set phase of U-Boot this invocation is for (spl/tpl)')
parser.add_argument('-P', '--processes', type=int,
help='set number of processes to use for running tests')
if HAVE_TESTS:
parser.add_argument('-t', '--test', action='store_true', dest='test',
default=False, help='run tests')
parser.add_argument(
'-T', '--test-coverage', action='store_true',
default=False, help='run tests and check for 100%% coverage')
parser.add_argument('files', nargs='*')
args = parser.parse_args()
# Run our meagre tests
if HAVE_TESTS and args.test:
ret_code = run_tests(args.processes, args)
sys.exit(ret_code)
elif HAVE_TESTS and args.test_coverage:
RunTestCoverage(args.build_dir)
else:
dtb_platdata.run_steps(args.files, args.dtb_file, args.include_disabled,
args.output,
[args.c_output_dir, args.h_output_dir],
args.phase, instantiate=args.instantiate)
if __name__ == '__main__':
run_dtoc()
+26
View File
@@ -0,0 +1,26 @@
[build-system]
requires = ["setuptools>=78.1.1"]
build-backend = "setuptools.build_meta"
[project]
name = "dtoc"
version = "0.0.6"
authors = [
{ name="Simon Glass", email="sjg@chromium.org" },
]
dependencies = ["pylibfdt", "u_boot_pylib >= 0.0.6"]
description = "Devicetree-to-C generator"
readme = "README.rst"
requires-python = ">=3.7"
classifiers = [
"Programming Language :: Python :: 3",
"License :: OSI Approved :: GNU General Public License v2 or later (GPLv2+)",
"Operating System :: OS Independent",
]
[project.urls]
"Homepage" = "https://docs.u-boot-project.org/en/latest/develop/driver-model/of-plat.html"
"Bug Tracker" = "https://source.denx.de/groups/u-boot/-/issues"
[project.scripts]
dtoc = "dtoc.main:run_dtoc"
+12
View File
@@ -0,0 +1,12 @@
# SPDX-License-Identifier: GPL-2.0+
from setuptools import setup
setup(name='dtoc',
version='1.0',
license='GPL-2.0+',
scripts=['dtoc'],
packages=['dtoc'],
package_dir={'dtoc': ''},
package_data={'dtoc': ['README']},
classifiers=['Environment :: Console',
'Topic :: Software Development :: Embedded Systems'])
+766
View File
@@ -0,0 +1,766 @@
#!/usr/bin/python
# SPDX-License-Identifier: GPL-2.0+
#
# Copyright (C) 2017 Google, Inc
# Written by Simon Glass <sjg@chromium.org>
#
"""Scanning of U-Boot source for drivers and structs
This scans the source tree to find out things about all instances of
U_BOOT_DRIVER(), UCLASS_DRIVER and all struct declarations in header files.
See doc/driver-model/of-plat.rst for more informaiton
"""
import collections
import os
import re
import sys
def conv_name_to_c(name):
"""Convert a device-tree name to a C identifier
This uses multiple replace() calls instead of re.sub() since it is faster
(400ms for 1m calls versus 1000ms for the 're' version).
Args:
name (str): Name to convert
Return:
str: String containing the C version of this name
"""
new = name.replace('@', '_at_')
new = new.replace('-', '_')
new = new.replace(',', '_')
new = new.replace('.', '_')
if new == '/':
return 'root'
return new
def get_compat_name(node):
"""Get the node's list of compatible string as a C identifiers
Args:
node (fdt.Node): Node object to check
Return:
list of str: List of C identifiers for all the compatible strings
"""
compat = node.props['compatible'].value
if not isinstance(compat, list):
compat = [compat]
return [conv_name_to_c(c) for c in compat]
class Driver:
"""Information about a driver in U-Boot
Attributes:
name: Name of driver. For U_BOOT_DRIVER(x) this is 'x'
fname: Filename where the driver was found
uclass_id: Name of uclass, e.g. 'UCLASS_I2C'
compat: Driver data for each compatible string:
key: Compatible string, e.g. 'rockchip,rk3288-grf'
value: Driver data, e,g, 'ROCKCHIP_SYSCON_GRF', or None
fname: Filename where the driver was found
priv (str): struct name of the priv_auto member, e.g. 'serial_priv'
plat (str): struct name of the plat_auto member, e.g. 'serial_plat'
child_priv (str): struct name of the per_child_auto member,
e.g. 'pci_child_priv'
child_plat (str): struct name of the per_child_plat_auto member,
e.g. 'pci_child_plat'
used (bool): True if the driver is used by the structs being output
phase (str): Which phase of U-Boot to use this driver
headers (list): List of header files needed for this driver (each a str)
e.g. ['<asm/cpu.h>']
dups (list): Driver objects with the same name as this one, that were
found after this one
warn_dups (bool): True if the duplicates are not distinguisble using
the phase
uclass (Uclass): uclass for this driver
"""
def __init__(self, name, fname):
self.name = name
self.fname = fname
self.uclass_id = None
self.compat = None
self.priv = ''
self.plat = ''
self.child_priv = ''
self.child_plat = ''
self.used = False
self.phase = ''
self.headers = []
self.dups = []
self.warn_dups = False
self.uclass = None
def __eq__(self, other):
return (self.name == other.name and
self.uclass_id == other.uclass_id and
self.compat == other.compat and
self.priv == other.priv and
self.plat == other.plat and
self.used == other.used)
def __repr__(self):
return ("Driver(name='%s', used=%s, uclass_id='%s', compat=%s, priv=%s)" %
(self.name, self.used, self.uclass_id, self.compat, self.priv))
class UclassDriver:
"""Holds information about a uclass driver
Attributes:
name: Uclass name, e.g. 'i2c' if the driver is for UCLASS_I2C
uclass_id: Uclass ID, e.g. 'UCLASS_I2C'
priv: struct name of the private data, e.g. 'i2c_priv'
per_dev_priv (str): struct name of the priv_auto member, e.g. 'spi_info'
per_dev_plat (str): struct name of the plat_auto member, e.g. 'i2c_chip'
per_child_priv (str): struct name of the per_child_auto member,
e.g. 'pci_child_priv'
per_child_plat (str): struct name of the per_child_plat_auto member,
e.g. 'pci_child_plat'
alias_num_to_node (dict): Aliases for this uclasses (for sequence
numbers)
key (int): Alias number, e.g. 2 for "pci2"
value (str): Node the alias points to
alias_path_to_num (dict): Convert a path to an alias number
key (str): Full path to node (e.g. '/soc/pci')
seq (int): Alias number, e.g. 2 for "pci2"
devs (list): List of devices in this uclass, each a Node
node_refs (dict): References in the linked list of devices:
key (int): Sequence number (0=first, n-1=last, -1=head, n=tail)
value (str): Reference to the device at that position
"""
def __init__(self, name):
self.name = name
self.uclass_id = None
self.priv = ''
self.per_dev_priv = ''
self.per_dev_plat = ''
self.per_child_priv = ''
self.per_child_plat = ''
self.alias_num_to_node = {}
self.alias_path_to_num = {}
self.devs = []
self.node_refs = {}
def __eq__(self, other):
return (self.name == other.name and
self.uclass_id == other.uclass_id and
self.priv == other.priv)
def __repr__(self):
return ("UclassDriver(name='%s', uclass_id='%s')" %
(self.name, self.uclass_id))
def __hash__(self):
# We can use the uclass ID since it is unique among uclasses
return hash(self.uclass_id)
class Struct:
"""Holds information about a struct definition
Attributes:
name: Struct name, e.g. 'fred' if the struct is 'struct fred'
fname: Filename containing the struct, in a format that C files can
include, e.g. 'asm/clk.h'
"""
def __init__(self, name, fname):
self.name = name
self.fname =fname
def __repr__(self):
return ("Struct(name='%s', fname='%s')" % (self.name, self.fname))
class Scanner:
"""Scanning of the U-Boot source tree
Properties:
_basedir (str): Base directory of U-Boot source code. Defaults to the
grandparent of this file's directory
_drivers: Dict of valid driver names found in drivers/
key: Driver name
value: Driver for that driver
_driver_aliases: Dict that holds aliases for driver names
key: Driver alias declared with
DM_DRIVER_ALIAS(driver_alias, driver_name)
value: Driver name declared with U_BOOT_DRIVER(driver_name)
_drivers_additional (list or str): List of additional drivers to use
during scanning
_warnings: Dict of warnings found:
key: Driver name
value: Set of warnings
_of_match: Dict holding information about compatible strings
key: Name of struct udevice_id variable
value: Dict of compatible info in that variable:
key: Compatible string, e.g. 'rockchip,rk3288-grf'
value: Driver data, e,g, 'ROCKCHIP_SYSCON_GRF', or None
_compat_to_driver: Maps compatible strings to Driver
_uclass: Dict of uclass information
key: uclass name, e.g. 'UCLASS_I2C'
value: UClassDriver
_structs: Dict of all structs found in U-Boot:
key: Name of struct
value: Struct object
_phase: The phase of U-Boot that we are generating data for, e.g. 'spl'
or 'tpl'. None if not known
"""
def __init__(self, basedir, drivers_additional, phase=''):
"""Set up a new Scanner
"""
if not basedir:
basedir = sys.argv[0].replace('tools/dtoc/dtoc', '')
if basedir == '':
basedir = './'
self._basedir = basedir
self._drivers = {}
self._driver_aliases = {}
self._drivers_additional = drivers_additional or []
self._missing_drivers = set()
self._warnings = collections.defaultdict(set)
self._of_match = {}
self._compat_to_driver = {}
self._uclass = {}
self._structs = {}
self._phase = phase
def get_driver(self, name):
"""Get a driver given its name
Args:
name (str): Driver name
Returns:
Driver: Driver or None if not found
"""
return self._drivers.get(name)
def get_normalized_compat_name(self, node):
"""Get a node's normalized compat name
Returns a valid driver name by retrieving node's list of compatible
string as a C identifier and performing a check against _drivers
and a lookup in driver_aliases printing a warning in case of failure.
Args:
node (Node): Node object to check
Return:
Tuple:
Driver name associated with the first compatible string
List of C identifiers for all the other compatible strings
(possibly empty)
In case of no match found, the return will be the same as
get_compat_name()
"""
if not node.parent:
compat_list_c = ['root_driver']
else:
compat_list_c = get_compat_name(node)
for compat_c in compat_list_c:
if not compat_c in self._drivers.keys():
compat_c = self._driver_aliases.get(compat_c)
if not compat_c:
continue
aliases_c = compat_list_c
if compat_c in aliases_c:
aliases_c.remove(compat_c)
return compat_c, aliases_c
name = compat_list_c[0]
self._missing_drivers.add(name)
self._warnings[name].add(
'WARNING: the driver %s was not found in the driver list' % name)
return compat_list_c[0], compat_list_c[1:]
def _parse_structs(self, fname, buff):
"""Parse a H file to extract struct definitions contained within
This parses 'struct xx {' definitions to figure out what structs this
header defines.
Args:
buff (str): Contents of file
fname (str): Filename (to use when printing errors)
"""
structs = {}
re_struct = re.compile(r'^struct ([a-z0-9_]+) {$')
re_asm = re.compile(r'../arch/[a-z0-9]+/include/asm/(.*)')
prefix = ''
for line in buff.splitlines():
# Handle line continuation
if prefix:
line = prefix + line
prefix = ''
if line.endswith('\\'):
prefix = line[:-1]
continue
m_struct = re_struct.match(line)
if m_struct:
name = m_struct.group(1)
include_dir = os.path.join(self._basedir, 'include')
rel_fname = os.path.relpath(fname, include_dir)
m_asm = re_asm.match(rel_fname)
if m_asm:
rel_fname = 'asm/' + m_asm.group(1)
structs[name] = Struct(name, rel_fname)
self._structs.update(structs)
@classmethod
def _get_re_for_member(cls, member):
"""_get_re_for_member: Get a compiled regular expression
Args:
member (str): Struct member name, e.g. 'priv_auto'
Returns:
re.Pattern: Compiled regular expression that parses:
.member = sizeof(struct fred),
and returns "fred" as group 1
"""
return re.compile(r'^\s*.%s\s*=\s*sizeof\(struct\s+(.*)\),$' % member)
def _parse_uclass_driver(self, fname, buff):
"""Parse a C file to extract uclass driver information contained within
This parses UCLASS_DRIVER() structs to obtain various pieces of useful
information.
It updates the following member:
_uclass: Dict of uclass information
key: uclass name, e.g. 'UCLASS_I2C'
value: UClassDriver
Args:
fname (str): Filename being parsed (used for warnings)
buff (str): Contents of file
"""
uc_drivers = {}
# Collect the driver name and associated Driver
driver = None
re_driver = re.compile(r'^UCLASS_DRIVER\((.*)\)')
# Collect the uclass ID, e.g. 'UCLASS_SPI'
re_id = re.compile(r'\s*\.id\s*=\s*(UCLASS_[A-Z0-9_]+)')
# Matches the header/size information for uclass-private data
re_priv = self._get_re_for_member('priv_auto')
# Set up parsing for the auto members
re_per_device_priv = self._get_re_for_member('per_device_auto')
re_per_device_plat = self._get_re_for_member('per_device_plat_auto')
re_per_child_priv = self._get_re_for_member('per_child_auto')
re_per_child_plat = self._get_re_for_member('per_child_plat_auto')
prefix = ''
for line in buff.splitlines():
# Handle line continuation
if prefix:
line = prefix + line
prefix = ''
if line.endswith('\\'):
prefix = line[:-1]
continue
driver_match = re_driver.search(line)
# If we have seen UCLASS_DRIVER()...
if driver:
m_id = re_id.search(line)
m_priv = re_priv.match(line)
m_per_dev_priv = re_per_device_priv.match(line)
m_per_dev_plat = re_per_device_plat.match(line)
m_per_child_priv = re_per_child_priv.match(line)
m_per_child_plat = re_per_child_plat.match(line)
if m_id:
driver.uclass_id = m_id.group(1)
elif m_priv:
driver.priv = m_priv.group(1)
elif m_per_dev_priv:
driver.per_dev_priv = m_per_dev_priv.group(1)
elif m_per_dev_plat:
driver.per_dev_plat = m_per_dev_plat.group(1)
elif m_per_child_priv:
driver.per_child_priv = m_per_child_priv.group(1)
elif m_per_child_plat:
driver.per_child_plat = m_per_child_plat.group(1)
elif '};' in line:
if not driver.uclass_id:
raise ValueError(
"%s: Cannot parse uclass ID in driver '%s'" %
(fname, driver.name))
uc_drivers[driver.uclass_id] = driver
driver = None
elif driver_match:
driver_name = driver_match.group(1)
driver = UclassDriver(driver_name)
self._uclass.update(uc_drivers)
def _parse_driver(self, fname, buff):
"""Parse a C file to extract driver information contained within
This parses U_BOOT_DRIVER() structs to obtain various pieces of useful
information.
It updates the following members:
_drivers - updated with new Driver records for each driver found
in the file
_of_match - updated with each compatible string found in the file
_compat_to_driver - Maps compatible string to Driver
_driver_aliases - Maps alias names to driver name
Args:
fname (str): Filename being parsed (used for warnings)
buff (str): Contents of file
Raises:
ValueError: Compatible variable is mentioned in .of_match in
U_BOOT_DRIVER() but not found in the file
"""
# Dict holding information about compatible strings collected in this
# function so far
# key: Name of struct udevice_id variable
# value: Dict of compatible info in that variable:
# key: Compatible string, e.g. 'rockchip,rk3288-grf'
# value: Driver data, e,g, 'ROCKCHIP_SYSCON_GRF', or None
of_match = {}
# Dict holding driver information collected in this function so far
# key: Driver name (C name as in U_BOOT_DRIVER(xxx))
# value: Driver
drivers = {}
# Collect the driver info
driver = None
re_driver = re.compile(r'^U_BOOT_DRIVER\((.*)\)')
# Collect the uclass ID, e.g. 'UCLASS_SPI'
re_id = re.compile(r'\s*\.id\s*=\s*(UCLASS_[A-Z0-9_]+)')
# Collect the compatible string, e.g. 'rockchip,rk3288-grf'
compat = None
re_compat = re.compile(r'{\s*\.compatible\s*=\s*"(.*)"\s*'
r'(,\s*\.data\s*=\s*(\S*))?\s*},')
# This is a dict of compatible strings that were found:
# key: Compatible string, e.g. 'rockchip,rk3288-grf'
# value: Driver data, e,g, 'ROCKCHIP_SYSCON_GRF', or None
compat_dict = {}
# Holds the var nane of the udevice_id list, e.g.
# 'rk3288_syscon_ids_noc' in
# static const struct udevice_id rk3288_syscon_ids_noc[] = {
ids_name = None
re_ids = re.compile(r'struct udevice_id (.*)\[\]\s*=')
# Matches the references to the udevice_id list
re_of_match = re.compile(
r'\.of_match\s*=\s*(of_match_ptr\()?([a-z0-9_]+)([^,]*),')
re_phase = re.compile(r'^\s*DM_PHASE\((.*)\).*$')
re_hdr = re.compile(r'^\s*DM_HEADER\((.*)\).*$')
re_alias = re.compile(r'DM_DRIVER_ALIAS\(\s*(\w+)\s*,\s*(\w+)\s*\)')
# Matches the struct name for priv, plat
re_priv = self._get_re_for_member('priv_auto')
re_plat = self._get_re_for_member('plat_auto')
re_child_priv = self._get_re_for_member('per_child_auto')
re_child_plat = self._get_re_for_member('per_child_plat_auto')
prefix = ''
for line in buff.splitlines():
# Handle line continuation
if prefix:
line = prefix + line
prefix = ''
if line.endswith('\\'):
prefix = line[:-1]
continue
driver_match = re_driver.search(line)
# If this line contains U_BOOT_DRIVER()...
if driver:
m_id = re_id.search(line)
m_of_match = re_of_match.search(line)
m_priv = re_priv.match(line)
m_plat = re_plat.match(line)
m_cplat = re_child_plat.match(line)
m_cpriv = re_child_priv.match(line)
m_phase = re_phase.match(line)
m_hdr = re_hdr.match(line)
if m_priv:
driver.priv = m_priv.group(1)
elif m_plat:
driver.plat = m_plat.group(1)
elif m_cplat:
driver.child_plat = m_cplat.group(1)
elif m_cpriv:
driver.child_priv = m_cpriv.group(1)
elif m_id:
driver.uclass_id = m_id.group(1)
elif m_of_match:
compat = m_of_match.group(2)
suffix = m_of_match.group(3)
if suffix and suffix != ')':
self._warnings[driver.name].add(
"%s: Warning: unexpected suffix '%s' on .of_match line for compat '%s'" %
(fname, suffix, compat))
elif m_phase:
driver.phase = m_phase.group(1)
elif m_hdr:
driver.headers.append(m_hdr.group(1))
elif '};' in line:
is_root = driver.name == 'root_driver'
if driver.uclass_id and (compat or is_root):
if not is_root:
if compat not in of_match:
raise ValueError(
"%s: Unknown compatible var '%s' (found: %s)" %
(fname, compat, ','.join(of_match.keys())))
driver.compat = of_match[compat]
# This needs to be deterministic, since a driver may
# have multiple compatible strings pointing to it.
# We record the one earliest in the alphabet so it
# will produce the same result on all machines.
for compat_id in of_match[compat]:
old = self._compat_to_driver.get(compat_id)
if not old or driver.name < old.name:
self._compat_to_driver[compat_id] = driver
drivers[driver.name] = driver
else:
# The driver does not have a uclass or compat string.
# The first is required but the second is not, so just
# ignore this.
if not driver.uclass_id:
warn = 'Missing .uclass'
else:
warn = 'Missing .compatible'
self._warnings[driver.name].add('%s in %s' %
(warn, fname))
driver = None
ids_name = None
compat = None
compat_dict = {}
elif ids_name:
compat_m = re_compat.search(line)
if compat_m:
compat_dict[compat_m.group(1)] = compat_m.group(3)
elif '};' in line:
of_match[ids_name] = compat_dict
ids_name = None
elif driver_match:
driver_name = driver_match.group(1)
driver = Driver(driver_name, fname)
else:
ids_m = re_ids.search(line)
m_alias = re_alias.match(line)
if ids_m:
ids_name = ids_m.group(1)
elif m_alias:
self._driver_aliases[m_alias.group(2)] = m_alias.group(1)
# Make the updates based on what we found
for driver in drivers.values():
if driver.name in self._drivers:
orig = self._drivers[driver.name]
if self._phase:
# If the original driver matches our phase, use it
if orig.phase == self._phase:
orig.dups.append(driver)
continue
# Otherwise use the new driver, which is assumed to match
else:
# We have no way of distinguishing them
driver.warn_dups = True
driver.dups.append(orig)
self._drivers[driver.name] = driver
self._of_match.update(of_match)
def show_warnings(self):
"""Show any warnings that have been collected"""
used_drivers = [drv.name for drv in self._drivers.values() if drv.used]
missing = self._missing_drivers.copy()
for name in sorted(self._warnings.keys()):
if name in missing or name in used_drivers:
warns = sorted(list(self._warnings[name]))
print('%s: %s' % (name, warns[0]))
indent = ' ' * len(name)
for warn in warns[1:]:
print('%-s: %s' % (indent, warn))
if name in missing:
missing.remove(name)
print()
def scan_driver(self, fname):
"""Scan a driver file to build a list of driver names and aliases
It updates the following members:
_drivers - updated with new Driver records for each driver found
in the file
_of_match - updated with each compatible string found in the file
_compat_to_driver - Maps compatible string to Driver
_driver_aliases - Maps alias names to driver name
Args
fname: Driver filename to scan
"""
with open(fname, encoding='utf-8') as inf:
try:
buff = inf.read()
except UnicodeDecodeError:
# This seems to happen on older Python versions
print("Skipping file '%s' due to unicode error" % fname)
return
# If this file has any U_BOOT_DRIVER() declarations, process it to
# obtain driver information
if 'U_BOOT_DRIVER' in buff:
self._parse_driver(fname, buff)
if 'UCLASS_DRIVER' in buff:
self._parse_uclass_driver(fname, buff)
def scan_header(self, fname):
"""Scan a header file to build a list of struct definitions
It updates the following members:
_structs - updated with new Struct records for each struct found
in the file
Args
fname: header filename to scan
"""
with open(fname, encoding='utf-8') as inf:
try:
buff = inf.read()
except UnicodeDecodeError:
# This seems to happen on older Python versions
print("Skipping file '%s' due to unicode error" % fname)
return
# If this file has any U_BOOT_DRIVER() declarations, process it to
# obtain driver information
if 'struct' in buff:
self._parse_structs(fname, buff)
def scan_drivers(self):
"""Scan the driver folders to build a list of driver names and aliases
This procedure will populate self._drivers and self._driver_aliases
"""
for (dirpath, _, filenames) in os.walk(self._basedir):
rel_path = dirpath[len(self._basedir):]
if rel_path.startswith('/'):
rel_path = rel_path[1:]
if rel_path.startswith('build') or rel_path.startswith('.git'):
continue
for fname in filenames:
pathname = dirpath + '/' + fname
if fname.endswith('.c'):
self.scan_driver(pathname)
elif fname.endswith('.h'):
self.scan_header(pathname)
for fname in self._drivers_additional:
if not isinstance(fname, str) or len(fname) == 0:
continue
if fname[0] == '/':
self.scan_driver(fname)
else:
self.scan_driver(self._basedir + '/' + fname)
# Get the uclass for each driver
# TODO: Can we just get the uclass for the ones we use, e.g. in
# mark_used()?
for driver in self._drivers.values():
driver.uclass = self._uclass.get(driver.uclass_id)
def mark_used(self, nodes):
"""Mark the drivers associated with a list of nodes as 'used'
This takes a list of nodes, finds the driver for each one and marks it
as used.
If two used drivers have the same name, issue a warning.
Args:
nodes (list of None): Nodes that are in use
"""
# Figure out which drivers we actually use
for node in nodes:
struct_name, _ = self.get_normalized_compat_name(node)
driver = self._drivers.get(struct_name)
if driver:
driver.used = True
if driver.dups and driver.warn_dups:
print("Warning: Duplicate driver name '%s' (orig=%s, dups=%s)" %
(driver.name, driver.fname,
', '.join([drv.fname for drv in driver.dups])))
def add_uclass_alias(self, name, num, node):
"""Add an alias to a uclass
Args:
name: Name of uclass, e.g. 'i2c'
num: Alias number, e.g. 2 for alias 'i2c2'
node: Node the alias points to, or None if None
Returns:
True if the node was added
False if the node was not added (uclass of that name not found)
None if the node could not be added because it was None
"""
for uclass in self._uclass.values():
if uclass.name == name:
if node is None:
return None
uclass.alias_num_to_node[int(num)] = node
uclass.alias_path_to_num[node.path] = int(num)
return True
return False
def assign_seq(self, node):
"""Figure out the sequence number for a node
This looks in the node's uclass and assigns a sequence number if needed,
based on the aliases and other nodes in that uclass.
It updates the uclass alias_path_to_num and alias_num_to_node
Args:
node (Node): Node object to look up
"""
if node.driver and node.seq == -1 and node.uclass:
uclass = node.uclass
num = uclass.alias_path_to_num.get(node.path)
if num is not None:
return num
else:
# Dynamically allocate the next available value after all
# existing ones
if uclass.alias_num_to_node:
start = max(uclass.alias_num_to_node.keys())
else:
start = -1
for seq in range(start + 1, 1000):
if seq not in uclass.alias_num_to_node:
break
uclass.alias_path_to_num[node.path] = seq
uclass.alias_num_to_node[seq] = node
return seq
return None
+11
View File
@@ -0,0 +1,11 @@
// SPDX-License-Identifier: GPL-2.0+
/*
* Test device tree file for dtoc
*
* Copyright 2017 Google, Inc
*/
/dts-v1/;
/ {
};
+24
View File
@@ -0,0 +1,24 @@
// SPDX-License-Identifier: GPL-2.0+
/*
* Test device tree file for dtoc
*
* Copyright 2018 Google, Inc
*/
/dts-v1/;
/ {
#address-cells = <1>;
#size-cells = <1>;
spl-test {
bootph-all;
compatible = "sandbox,spl-test";
intval = <1>;
};
spl-test2 {
bootph-all;
compatible = "sandbox,spl-test";
intarray = <5>;
};
};
+26
View File
@@ -0,0 +1,26 @@
// SPDX-License-Identifier: GPL-2.0+
/*
* Test device tree file for dtoc
*
* Copyright 2017 Google, Inc
*/
/dts-v1/;
/ {
#address-cells = <1>;
#size-cells = <1>;
test1 {
bootph-all;
compatible = "test1";
reg = <0x1234 0x5678>;
};
test2 {
bootph-all;
compatible = "test2";
reg = <0x12345678 0x98765432 2 3>;
};
};
+32
View File
@@ -0,0 +1,32 @@
// SPDX-License-Identifier: GPL-2.0+
/*
* Test device tree file for dtoc
*
* Copyright 2017 Google, Inc
*/
/dts-v1/;
/ {
#address-cells = <1>;
#size-cells = <2>;
test1 {
bootph-all;
compatible = "test1";
reg = <0x1234 0x5678 0x0>;
};
test2 {
bootph-all;
compatible = "test2";
reg = <0x12345678 0x98765432 0x10987654>;
};
test3 {
bootph-all;
compatible = "test3";
reg = <0x12345678 0x98765432 0x10987654 2 0 3>;
};
};
+32
View File
@@ -0,0 +1,32 @@
// SPDX-License-Identifier: GPL-2.0+
/*
* Test device tree file for dtoc
*
* Copyright 2017 Google, Inc
*/
/dts-v1/;
/ {
#address-cells = <2>;
#size-cells = <2>;
test1 {
bootph-all;
compatible = "test1";
reg = /bits/ 64 <0x1234 0x5678>;
};
test2 {
bootph-all;
compatible = "test2";
reg = /bits/ 64 <0x1234567890123456 0x9876543210987654>;
};
test3 {
bootph-all;
compatible = "test3";
reg = /bits/ 64 <0x1234567890123456 0x9876543210987654 2 3>;
};
};
+32
View File
@@ -0,0 +1,32 @@
// SPDX-License-Identifier: GPL-2.0+
/*
* Test device tree file for dtoc
*
* Copyright 2017 Google, Inc
*/
/dts-v1/;
/ {
#address-cells = <2>;
#size-cells = <1>;
test1 {
bootph-all;
compatible = "test1";
reg = <0x1234 0x0 0x5678>;
};
test2 {
bootph-all;
compatible = "test2";
reg = <0x12345678 0x90123456 0x98765432>;
};
test3 {
bootph-all;
compatible = "test3";
reg = <0x12345678 0x90123456 0x98765432 0 2 3>;
};
};
+58
View File
@@ -0,0 +1,58 @@
// SPDX-License-Identifier: GPL-2.0+
/*
* Test device tree file for dtoc
*
* Copyright 2017 Google, Inc
*/
/dts-v1/;
/ {
#address-cells = <1>;
#size-cells = <1>;
aliases {
testbus2 = &bus2;
testfdt1 = &testfdt_1;
i2c4- = &i2c;
};
spl-test {
bootph-all;
compatible = "sandbox,spl-test";
boolval;
intval = <1>;
};
i2c: i2c {
bootph-all;
compatible = "sandbox,i2c";
intval = <3>;
};
spl-test3 {
bootph-all;
compatible = "sandbox,spl-test";
stringarray = "one";
longbytearray = [09 0a 0b 0c 0d 0e 0f 10];
};
bus2: some-bus {
#address-cells = <1>;
#size-cells = <0>;
compatible = "denx,u-boot-test-bus";
reg = <3 1>;
ping-expect = <4>;
ping-add = <4>;
testfdt_1: test {
compatible = "denx,u-boot-fdt-test", "google,another-fdt-test";
reg = <5>;
ping-expect = <5>;
ping-add = <5>;
};
test0 {
compatible = "google,another-fdt-test";
};
};
};
@@ -0,0 +1,58 @@
// SPDX-License-Identifier: GPL-2.0+
/*
* Test device tree file for dtoc
*
* Copyright 2017 Google, Inc
*/
/dts-v1/;
/ {
#address-cells = <1>;
#size-cells = <1>;
aliases {
testbus2 = &bus2;
testfdt1 = &testfdt_1;
i2c4 = "/does/not/exist";
};
spl-test {
bootph-all;
compatible = "sandbox,spl-test";
boolval;
intval = <1>;
};
i2c: i2c {
bootph-all;
compatible = "sandbox,i2c";
intval = <3>;
};
spl-test3 {
bootph-all;
compatible = "sandbox,spl-test";
stringarray = "one";
longbytearray = [09 0a 0b 0c 0d 0e 0f 10];
};
bus2: some-bus {
#address-cells = <1>;
#size-cells = <0>;
compatible = "denx,u-boot-test-bus";
reg = <3 1>;
ping-expect = <4>;
ping-add = <4>;
testfdt_1: test {
compatible = "denx,u-boot-fdt-test", "google,another-fdt-test";
reg = <5>;
ping-expect = <5>;
ping-add = <5>;
};
test0 {
compatible = "google,another-fdt-test";
};
};
};
@@ -0,0 +1,58 @@
// SPDX-License-Identifier: GPL-2.0+
/*
* Test device tree file for dtoc
*
* Copyright 2017 Google, Inc
*/
/dts-v1/;
/ {
#address-cells = <1>;
#size-cells = <1>;
aliases {
testbus2 = &bus2;
testfdt1 = &testfdt_1;
other1 = &testfdt_1;
};
spl-test {
bootph-all;
compatible = "sandbox,spl-test";
boolval;
intval = <1>;
};
i2c: i2c {
bootph-all;
compatible = "sandbox,i2c";
intval = <3>;
};
spl-test3 {
bootph-all;
compatible = "sandbox,spl-test";
stringarray = "one";
longbytearray = [09 0a 0b 0c 0d 0e 0f 10];
};
bus2: some-bus {
#address-cells = <1>;
#size-cells = <0>;
compatible = "denx,u-boot-test-bus";
reg = <3 1>;
ping-expect = <4>;
ping-add = <4>;
testfdt_1: test {
compatible = "denx,u-boot-fdt-test", "google,another-fdt-test";
reg = <5>;
ping-expect = <5>;
ping-add = <5>;
};
test0 {
compatible = "google,another-fdt-test";
};
};
};
+22
View File
@@ -0,0 +1,22 @@
// SPDX-License-Identifier: GPL-2.0+
/*
* Test device tree file for dtoc
*
* Copyright 2017 Google, Inc
*/
/dts-v1/;
/ {
spl-test {
bootph-all;
compatible = "compat1", "compat2.1-fred", "compat3";
intval = <1>;
};
spl-test2 {
bootph-all;
compatible = "compat1", "simple_bus";
intval = <1>;
};
};
+17
View File
@@ -0,0 +1,17 @@
// SPDX-License-Identifier: GPL-2.0+
/*
* Test device tree file for dtoc
*
* Copyright 2018 Google, Inc
*/
/dts-v1/;
/ {
#address-cells = <1>;
#size-cells = <1>;
spl-test {
compatible = "test";
reg = "fre";
};
};
+17
View File
@@ -0,0 +1,17 @@
// SPDX-License-Identifier: GPL-2.0+
/*
* Test device tree file for dtoc
*
* Copyright 2018 Google, Inc
*/
/dts-v1/;
/ {
#address-cells = <1>;
#size-cells = <1>;
spl-test {
compatible = "test";
reg = <1 2 3>;
};
};
+90
View File
@@ -0,0 +1,90 @@
// SPDX-License-Identifier: GPL-2.0+
/*
* Test device tree file for dtoc
*
* Copyright 2017 Google, Inc
*/
/dts-v1/;
/ {
#address-cells = <1>;
#size-cells = <1>;
reference = <&over>; /* nake sure that the 'over' phandle exists */
copy-list = <&another &base>;
dest {
bootph-all;
compatible = "sandbox,spl-test";
stringarray = "one";
longbytearray = [09 0a 0b 0c 0d 0e 0f 10];
maybe-empty-int = <1>;
first@0 {
a-prop = <456>;
b-prop = <1>;
};
existing {
};
base {
second {
second3 {
};
second2 {
new-prop;
};
second1: second1 {
new-prop;
};
second4 {
use_second1 = <&second1>;
};
};
};
};
base: base {
compatible = "sandbox,i2c";
bootph-all;
#address-cells = <1>;
#size-cells = <0>;
over: over {
compatible = "sandbox,pmic";
bootph-all;
reg = <9>;
low-power;
};
first@0 {
reg = <0>;
a-prop = <123>;
};
second: second {
second_1_bad: second1 {
some-prop;
};
second2 {
some-prop;
use_second1_bad = <&second_1_bad>;
};
};
};
another: another {
new-prop = "hello";
earlier {
wibble = <2>;
};
later {
fibble = <3>;
};
};
};
@@ -0,0 +1,20 @@
// SPDX-License-Identifier: GPL-2.0+
/*
* Test device tree file for dtoc
*
* Copyright 2020 Collabora Ltd.
*/
/dts-v1/;
/ {
gpio_a: gpios@0 {
bootph-all;
gpio-controller;
compatible = "sandbox_gpio_alias";
#gpio-cells = <1>;
gpio-bank-name = "a";
sandbox,gpio-count = <20>;
};
};
+11
View File
@@ -0,0 +1,11 @@
// SPDX-License-Identifier: GPL-2.0+
/*
* Test device tree file for dtoc
*
* Copyright 2017 Google, Inc
*/
/dts-v1/;
/ {
};
+58
View File
@@ -0,0 +1,58 @@
// SPDX-License-Identifier: GPL-2.0+
/*
* Test device tree file for dtoc
*
* Copyright 2017 Google, Inc
*/
/dts-v1/;
/ {
#address-cells = <1>;
#size-cells = <1>;
aliases {
testbus2 = &bus2;
testfdt1 = &testfdt_1;
i2c4 = &i2c;
};
spl-test {
bootph-all;
compatible = "sandbox,spl-test";
boolval;
intval = <1>;
};
i2c: i2c {
bootph-all;
compatible = "sandbox,i2c";
intval = <3>;
};
spl-test3 {
bootph-all;
compatible = "sandbox,spl-test";
stringarray = "one";
longbytearray = [09 0a 0b 0c 0d 0e 0f 10];
};
bus2: some-bus {
#address-cells = <1>;
#size-cells = <0>;
compatible = "denx,u-boot-test-bus";
reg = <3 1>;
ping-expect = <4>;
ping-add = <4>;
testfdt_1: test {
compatible = "denx,u-boot-fdt-test", "google,another-fdt-test";
reg = <5>;
ping-expect = <5>;
ping-add = <5>;
};
test0 {
compatible = "google,another-fdt-test";
};
};
};
@@ -0,0 +1,15 @@
// SPDX-License-Identifier: GPL-2.0+
/*
* Test device tree file for dtoc
*
* Copyright 2017 Google, Inc
*/
/dts-v1/;
/ {
spl-test {
bootph-all;
compatible = "invalid";
};
};
+32
View File
@@ -0,0 +1,32 @@
// SPDX-License-Identifier: GPL-2.0+
/*
* Test device tree file for dtoc
*
* Copyright 2017 Google, Inc
*/
/dts-v1/;
/ {
#address-cells = <1>;
#size-cells = <1>;
i2c@0 {
compatible = "sandbox,i2c";
bootph-pre-sram;
#address-cells = <1>;
#size-cells = <0>;
spl-test {
bootph-all;
compatible = "sandbox,spl-test";
#address-cells = <1>;
#size-cells = <0>;
status = "disabled";
pmic@9 {
compatible = "sandbox,pmic";
bootph-all;
reg = <9>;
low-power;
};
};
};
};
+21
View File
@@ -0,0 +1,21 @@
// SPDX-License-Identifier: GPL-2.0+
/*
* Test device tree file for dtoc
*
* Copyright 2017 Google, Inc
*/
/dts-v1/;
/ {
#address-cells = <1>;
#size-cells = <1>;
i2c@0 {
pmic@9 {
compatible = "sandbox,pmic";
bootph-all;
reg = <9>;
low-power;
};
};
};
+43
View File
@@ -0,0 +1,43 @@
// SPDX-License-Identifier: GPL-2.0+
/*
* Test device tree file for dtoc
*
* Copyright 2017 Google, Inc
*/
/dts-v1/;
/ {
phandle: phandle-target {
bootph-all;
compatible = "target";
intval = <0>;
#clock-cells = <0>;
};
phandle_1: phandle2-target {
bootph-all;
compatible = "target";
intval = <1>;
#clock-cells = <1>;
};
phandle_2: phandle3-target {
bootph-all;
compatible = "target";
intval = <2>;
#clock-cells = <2>;
};
phandle-source {
bootph-all;
compatible = "source";
clocks = <&phandle &phandle_1 11 &phandle_2 12 13 &phandle>;
phandle-name-offset = <&phandle_2>, "fred", <123>;
};
phandle-source2 {
bootph-all;
compatible = "source";
clocks = <&phandle>;
};
};
+16
View File
@@ -0,0 +1,16 @@
// SPDX-License-Identifier: GPL-2.0+
/*
* Test device tree file for dtoc
*
* Copyright 2018 Google, Inc
*/
/dts-v1/;
/ {
phandle-source {
bootph-all;
compatible = "source";
clocks = <20>; /* Invalid phandle */
};
};
@@ -0,0 +1,22 @@
// SPDX-License-Identifier: GPL-2.0+
/*
* Test device tree file for dtoc
*
* Copyright 2018 Google, Inc
*/
/dts-v1/;
/ {
phandle: phandle-target {
bootph-all;
compatible = "target";
intval = <0>;
};
phandle-source2 {
bootph-all;
compatible = "source";
clocks = <&phandle>;
};
};
@@ -0,0 +1,42 @@
// SPDX-License-Identifier: GPL-2.0+
/*
* Test device tree file for dtoc
*
* Copyright 2020 Collabora Ltd.
*/
/dts-v1/;
/ {
phandle: phandle-target {
bootph-all;
compatible = "target";
intval = <0>;
#gpio-cells = <0>;
};
phandle_1: phandle2-target {
bootph-all;
compatible = "target";
intval = <1>;
#gpio-cells = <1>;
};
phandle_2: phandle3-target {
bootph-all;
compatible = "target";
intval = <2>;
#gpio-cells = <2>;
};
phandle-source {
bootph-all;
compatible = "source";
cd-gpios = <&phandle &phandle_1 11 &phandle_2 12 13 &phandle>;
};
phandle-source2 {
bootph-all;
compatible = "source";
cd-gpios = <&phandle>;
};
};
@@ -0,0 +1,23 @@
// SPDX-License-Identifier: GPL-2.0+
/*
* Test device tree file for dtoc
*
* Copyright 2018 Google, Inc
*/
/dts-v1/;
/ {
phandle-source2 {
bootph-all;
compatible = "source";
clocks = <&phandle>;
};
phandle: phandle-target {
bootph-all;
compatible = "target";
#clock-cells = <0>;
};
};
@@ -0,0 +1,23 @@
// SPDX-License-Identifier: GPL-2.0+
/*
* Test device tree file for dtoc
*
* Copyright 2018 Google, Inc
*/
/dts-v1/;
/ {
phandle: phandle-target {
bootph-all;
compatible = "target";
intval = <0>;
#clock-cells = <0>;
};
phandle-source2 {
bootph-all;
compatible = "source";
clocks = <&phandle>;
};
};
@@ -0,0 +1,5 @@
/* Aliases must be in driver files */
U_BOOT_DRIVER(sandbox_gpio) {
};
DM_DRIVER_ALIAS(sandbox_gpio, sandbox_gpio_alias2)
+69
View File
@@ -0,0 +1,69 @@
// SPDX-License-Identifier: GPL-2.0+
/*
* Test device tree file for dtoc
*
* Copyright 2017 Google, Inc
*/
/dts-v1/;
/ {
#address-cells = <1>;
#size-cells = <1>;
spl-test {
bootph-all;
compatible = "sandbox,spl-test";
boolval;
maybe-empty-int = <>;
intval = <1>;
int64val = /bits/ 64 <0x123456789abcdef0>;
intarray = <2 3 4>;
byteval = [05];
bytearray = [06];
longbytearray = [09 0a 0b 0c 0d 0e 0f 10 11];
stringval = "message";
stringarray = "multi-word", "message";
notstring = [20 21 22 10 00];
};
spl-test2 {
bootph-all;
compatible = "sandbox,spl-test";
intval = <3>;
intarray = <5>;
byteval = [08];
bytearray = [01 23 34];
longbytearray = [09 0a 0b 0c];
stringval = "message2";
stringarray = "another", "multi-word", "message";
acpi-name = "\\_SB.GPO0";
};
spl-test3 {
bootph-all;
compatible = "sandbox,spl-test";
stringarray = "one";
longbytearray = [09 0a 0b 0c 0d 0e 0f 10];
maybe-empty-int = <1>;
};
i2c@0 {
compatible = "sandbox,i2c";
bootph-all;
#address-cells = <1>;
#size-cells = <0>;
pmic@9 {
compatible = "sandbox,pmic";
bootph-all;
reg = <9>;
low-power;
};
};
orig-node {
orig = <1 23 4>;
args = "-n first", "second", "-p", "123,456", "-x";
args2 = "a space", "there";
args3 = "-n first second -p 123,456 -x";
};
};
+30
View File
@@ -0,0 +1,30 @@
// SPDX-License-Identifier: GPL-2.0+
/*
* Test device tree file for dtoc
*
* Copyright 2017 Google, Inc
*/
/dts-v1/;
/ {
#address-cells = <1>;
#size-cells = <1>;
i2c@0 {
compatible = "sandbox,i2c";
bootph-all;
#address-cells = <1>;
#size-cells = <0>;
pmic@9 {
compatible = "sandbox,pmic";
bootph-all;
reg = <9>;
low-power;
gpio {
compatible = "sandbox,gpio";
};
};
};
};
+1854
View File
File diff suppressed because it is too large Load Diff
+1
View File
@@ -0,0 +1 @@
test_fdt.py
+1002
View File
File diff suppressed because it is too large Load Diff
+623
View File
@@ -0,0 +1,623 @@
# SPDX-License-Identifier: GPL-2.0+
# Copyright 2020 Google LLC
#
"""Tests for the src_scan module
This includes unit tests for scanning of the source code
"""
import copy
import os
import shutil
import tempfile
import unittest
from unittest import mock
from dtoc import src_scan
from u_boot_pylib import terminal
from u_boot_pylib import test_util
from u_boot_pylib import tools
OUR_PATH = os.path.dirname(os.path.realpath(__file__))
EXPECT_WARN = {'rockchip_rk3288_grf':
{'WARNING: the driver rockchip_rk3288_grf was not found in the driver list'}}
class FakeNode:
"""Fake Node object for testing"""
def __init__(self):
self.name = None
self.props = {}
class FakeProp:
"""Fake Prop object for testing"""
def __init__(self):
self.name = None
self.value = None
# This is a test so is allowed to access private things in the module it is
# testing
# pylint: disable=W0212
class TestSrcScan(unittest.TestCase):
"""Tests for src_scan"""
@classmethod
def setUpClass(cls):
tools.prepare_output_dir(None)
@classmethod
def tearDownClass(cls):
tools.finalise_output_dir()
def test_simple(self):
"""Simple test of scanning drivers"""
scan = src_scan.Scanner(None, None)
scan.scan_drivers()
self.assertIn('sandbox_gpio', scan._drivers)
self.assertIn('sandbox_gpio_alias', scan._driver_aliases)
self.assertEqual('sandbox_gpio',
scan._driver_aliases['sandbox_gpio_alias'])
self.assertNotIn('sandbox_gpio_alias2', scan._driver_aliases)
def test_additional(self):
"""Test with additional drivers to scan"""
scan = src_scan.Scanner(
None, [None, '', 'tools/dtoc/test/dtoc_test_scan_drivers.cxx'])
scan.scan_drivers()
self.assertIn('sandbox_gpio_alias2', scan._driver_aliases)
self.assertEqual('sandbox_gpio',
scan._driver_aliases['sandbox_gpio_alias2'])
def test_unicode_error(self):
"""Test running dtoc with an invalid unicode file
To be able to perform this test without adding a weird text file which
would produce issues when using checkpatch.pl or patman, generate the
file at runtime and then process it.
"""
driver_fn = '/tmp/' + next(tempfile._get_candidate_names())
with open(driver_fn, 'wb+') as fout:
fout.write(b'\x81')
scan = src_scan.Scanner(None, [driver_fn])
with terminal.capture() as (stdout, _):
scan.scan_drivers()
self.assertRegex(stdout.getvalue(),
r"Skipping file '.*' due to unicode error\s*")
def test_driver(self):
"""Test the Driver class"""
i2c = 'I2C_UCLASS'
compat = {'rockchip,rk3288-grf': 'ROCKCHIP_SYSCON_GRF',
'rockchip,rk3288-srf': None}
drv1 = src_scan.Driver('fred', 'fred.c')
drv2 = src_scan.Driver('mary', 'mary.c')
drv3 = src_scan.Driver('fred', 'fred.c')
drv1.uclass_id = i2c
drv1.compat = compat
drv2.uclass_id = i2c
drv2.compat = compat
drv3.uclass_id = i2c
drv3.compat = compat
self.assertEqual(
"Driver(name='fred', used=False, uclass_id='I2C_UCLASS', "
"compat={'rockchip,rk3288-grf': 'ROCKCHIP_SYSCON_GRF', "
"'rockchip,rk3288-srf': None}, priv=)", str(drv1))
self.assertEqual(drv1, drv3)
self.assertNotEqual(drv1, drv2)
self.assertNotEqual(drv2, drv3)
def test_scan_dirs(self):
"""Test scanning of source directories"""
def add_file(fname):
pathname = os.path.join(indir, fname)
dirname = os.path.dirname(pathname)
os.makedirs(dirname, exist_ok=True)
tools.write_file(pathname, '', binary=False)
fname_list.append(pathname)
try:
indir = tempfile.mkdtemp(prefix='dtoc.')
fname_list = []
add_file('fname.c')
add_file('.git/ignoreme.c')
add_file('dir/fname2.c')
add_file('build-sandbox/ignoreme2.c')
# Mock out scan_driver and check that it is called with the
# expected files
with mock.patch.object(src_scan.Scanner, "scan_driver") as mocked:
scan = src_scan.Scanner(indir, None)
scan.scan_drivers()
self.assertEqual(2, len(mocked.mock_calls))
self.assertEqual(mock.call(fname_list[0]),
mocked.mock_calls[0])
# .git file should be ignored
self.assertEqual(mock.call(fname_list[2]),
mocked.mock_calls[1])
finally:
shutil.rmtree(indir)
def test_scan(self):
"""Test scanning of a driver"""
fname = os.path.join(OUR_PATH, '..', '..', 'drivers/i2c/tegra_i2c.c')
buff = tools.read_file(fname, False)
scan = src_scan.Scanner(None, None)
scan._parse_driver(fname, buff)
self.assertIn('i2c_tegra', scan._drivers)
drv = scan._drivers['i2c_tegra']
self.assertEqual('i2c_tegra', drv.name)
self.assertEqual('UCLASS_I2C', drv.uclass_id)
self.assertEqual(
{'nvidia,tegra114-i2c': 'TYPE_114',
'nvidia,tegra124-i2c': 'TYPE_114',
'nvidia,tegra20-i2c': 'TYPE_STD',
'nvidia,tegra20-i2c-dvc': 'TYPE_DVC'}, drv.compat)
self.assertEqual('i2c_bus', drv.priv)
self.assertEqual(1, len(scan._drivers))
self.assertEqual({}, scan._warnings)
def test_normalized_name(self):
"""Test operation of get_normalized_compat_name()"""
prop = FakeProp()
prop.name = 'compatible'
prop.value = 'rockchip,rk3288-grf'
node = FakeNode()
node.props = {'compatible': prop}
# get_normalized_compat_name() uses this to check for root node
node.parent = FakeNode()
scan = src_scan.Scanner(None, None)
with terminal.capture() as (stdout, _):
name, aliases = scan.get_normalized_compat_name(node)
self.assertEqual('rockchip_rk3288_grf', name)
self.assertEqual([], aliases)
self.assertEqual(1, len(scan._missing_drivers))
self.assertEqual({'rockchip_rk3288_grf'}, scan._missing_drivers)
self.assertEqual('', stdout.getvalue().strip())
self.assertEqual(EXPECT_WARN, scan._warnings)
i2c = 'I2C_UCLASS'
compat = {'rockchip,rk3288-grf': 'ROCKCHIP_SYSCON_GRF',
'rockchip,rk3288-srf': None}
drv = src_scan.Driver('fred', 'fred.c')
drv.uclass_id = i2c
drv.compat = compat
scan._drivers['rockchip_rk3288_grf'] = drv
scan._driver_aliases['rockchip_rk3288_srf'] = 'rockchip_rk3288_grf'
with terminal.capture() as (stdout, _):
name, aliases = scan.get_normalized_compat_name(node)
self.assertEqual('', stdout.getvalue().strip())
self.assertEqual('rockchip_rk3288_grf', name)
self.assertEqual([], aliases)
self.assertEqual(EXPECT_WARN, scan._warnings)
prop.value = 'rockchip,rk3288-srf'
with terminal.capture() as (stdout, _):
name, aliases = scan.get_normalized_compat_name(node)
self.assertEqual('', stdout.getvalue().strip())
self.assertEqual('rockchip_rk3288_grf', name)
self.assertEqual(['rockchip_rk3288_srf'], aliases)
self.assertEqual(EXPECT_WARN, scan._warnings)
def test_scan_errors(self):
"""Test detection of scanning errors"""
buff = '''
static const struct udevice_id tegra_i2c_ids2[] = {
{ .compatible = "nvidia,tegra114-i2c", .data = TYPE_114 },
{ }
};
U_BOOT_DRIVER(i2c_tegra) = {
.name = "i2c_tegra",
.id = UCLASS_I2C,
.of_match = tegra_i2c_ids,
};
'''
scan = src_scan.Scanner(None, None)
with self.assertRaises(ValueError) as exc:
scan._parse_driver('file.c', buff)
self.assertIn(
"file.c: Unknown compatible var 'tegra_i2c_ids' (found: tegra_i2c_ids2)",
str(exc.exception))
def test_of_match(self):
"""Test detection of of_match_ptr() member"""
buff = '''
static const struct udevice_id tegra_i2c_ids[] = {
{ .compatible = "nvidia,tegra114-i2c", .data = TYPE_114 },
{ }
};
U_BOOT_DRIVER(i2c_tegra) = {
.name = "i2c_tegra",
.id = UCLASS_I2C,
.of_match = of_match_ptr(tegra_i2c_ids),
};
'''
scan = src_scan.Scanner(None, None)
scan._parse_driver('file.c', buff)
self.assertIn('i2c_tegra', scan._drivers)
drv = scan._drivers['i2c_tegra']
self.assertEqual('i2c_tegra', drv.name)
self.assertEqual('', drv.phase)
self.assertEqual([], drv.headers)
def test_priv(self):
"""Test collection of struct info from drivers"""
buff = '''
static const struct udevice_id test_ids[] = {
{ .compatible = "nvidia,tegra114-i2c", .data = TYPE_114 },
{ }
};
U_BOOT_DRIVER(testing) = {
.name = "testing",
.id = UCLASS_I2C,
.of_match = test_ids,
.priv_auto = sizeof(struct some_priv),
.plat_auto = sizeof(struct some_plat),
.per_child_auto = sizeof(struct some_cpriv),
.per_child_plat_auto = sizeof(struct some_cplat),
DM_PHASE(tpl)
DM_HEADER(<i2c.h>)
DM_HEADER(<asm/clk.h>)
};
'''
scan = src_scan.Scanner(None, None)
scan._parse_driver('file.c', buff)
self.assertIn('testing', scan._drivers)
drv = scan._drivers['testing']
self.assertEqual('testing', drv.name)
self.assertEqual('UCLASS_I2C', drv.uclass_id)
self.assertEqual(
{'nvidia,tegra114-i2c': 'TYPE_114'}, drv.compat)
self.assertEqual('some_priv', drv.priv)
self.assertEqual('some_plat', drv.plat)
self.assertEqual('some_cpriv', drv.child_priv)
self.assertEqual('some_cplat', drv.child_plat)
self.assertEqual('tpl', drv.phase)
self.assertEqual(['<i2c.h>', '<asm/clk.h>'], drv.headers)
self.assertEqual(1, len(scan._drivers))
def test_uclass_scan(self):
"""Test collection of uclass-driver info"""
buff = '''
UCLASS_DRIVER(i2c) = {
.id = UCLASS_I2C,
.name = "i2c",
.flags = DM_UC_FLAG_SEQ_ALIAS,
.priv_auto = sizeof(struct some_priv),
.per_device_auto = sizeof(struct per_dev_priv),
.per_device_plat_auto = sizeof(struct per_dev_plat),
.per_child_auto = sizeof(struct per_child_priv),
.per_child_plat_auto = sizeof(struct per_child_plat),
.child_post_bind = i2c_child_post_bind,
};
'''
scan = src_scan.Scanner(None, None)
scan._parse_uclass_driver('file.c', buff)
self.assertIn('UCLASS_I2C', scan._uclass)
drv = scan._uclass['UCLASS_I2C']
self.assertEqual('i2c', drv.name)
self.assertEqual('UCLASS_I2C', drv.uclass_id)
self.assertEqual('some_priv', drv.priv)
self.assertEqual('per_dev_priv', drv.per_dev_priv)
self.assertEqual('per_dev_plat', drv.per_dev_plat)
self.assertEqual('per_child_priv', drv.per_child_priv)
self.assertEqual('per_child_plat', drv.per_child_plat)
self.assertEqual(1, len(scan._uclass))
drv2 = copy.deepcopy(drv)
self.assertEqual(drv, drv2)
drv2.priv = 'other_priv'
self.assertNotEqual(drv, drv2)
# The hashes only depend on the uclass ID, so should be equal
self.assertEqual(drv.__hash__(), drv2.__hash__())
self.assertEqual("UclassDriver(name='i2c', uclass_id='UCLASS_I2C')",
str(drv))
def test_uclass_scan_errors(self):
"""Test detection of uclass scanning errors"""
buff = '''
UCLASS_DRIVER(i2c) = {
.name = "i2c",
};
'''
scan = src_scan.Scanner(None, None)
with self.assertRaises(ValueError) as exc:
scan._parse_uclass_driver('file.c', buff)
self.assertIn("file.c: Cannot parse uclass ID in driver 'i2c'",
str(exc.exception))
def test_struct_scan(self):
"""Test collection of struct info"""
buff = '''
/* some comment */
struct some_struct1 {
struct i2c_msg *msgs;
uint nmsgs;
};
'''
scan = src_scan.Scanner(None, None)
scan._basedir = os.path.join(OUR_PATH, '..', '..')
scan._parse_structs('arch/arm/include/asm/file.h', buff)
self.assertIn('some_struct1', scan._structs)
struc = scan._structs['some_struct1']
self.assertEqual('some_struct1', struc.name)
self.assertEqual('asm/file.h', struc.fname)
buff = '''
/* another comment */
struct another_struct {
int speed_hz;
int max_transaction_bytes;
};
'''
scan._parse_structs('include/file2.h', buff)
self.assertIn('another_struct', scan._structs)
struc = scan._structs['another_struct']
self.assertEqual('another_struct', struc.name)
self.assertEqual('file2.h', struc.fname)
self.assertEqual(2, len(scan._structs))
self.assertEqual("Struct(name='another_struct', fname='file2.h')",
str(struc))
def test_struct_scan_errors(self):
"""Test scanning a header file with an invalid unicode file"""
output = tools.get_output_filename('output.h')
tools.write_file(output, b'struct this is a test \x81 of bad unicode')
scan = src_scan.Scanner(None, None)
with terminal.capture() as (stdout, _):
scan.scan_header(output)
self.assertIn('due to unicode error', stdout.getvalue())
def setup_dup_drivers(self, name, phase=''):
"""Set up for a duplcate test
Returns:
tuple:
Scanner to use
Driver record for first driver
Text of second driver declaration
Node for driver 1
"""
driver1 = '''
static const struct udevice_id test_ids[] = {
{ .compatible = "nvidia,tegra114-i2c", .data = TYPE_114 },
{ }
};
U_BOOT_DRIVER(%s) = {
.name = "testing",
.id = UCLASS_I2C,
.of_match = test_ids,
%s
};
''' % (name, 'DM_PHASE(%s)' % phase if phase else '')
driver2 = '''
static const struct udevice_id test_ids[] = {
{ .compatible = "nvidia,tegra114-dvc" },
{ }
};
U_BOOT_DRIVER(%s) = {
.name = "testing",
.id = UCLASS_RAM,
.of_match = test_ids,
};
''' % name
scan = src_scan.Scanner(None, None, phase)
scan._parse_driver('file1.c', driver1)
self.assertIn(name, scan._drivers)
drv1 = scan._drivers[name]
prop = FakeProp()
prop.name = 'compatible'
prop.value = 'nvidia,tegra114-i2c'
node = FakeNode()
node.name = 'testing'
node.props = {'compatible': prop}
# get_normalized_compat_name() uses this to check for root node
node.parent = FakeNode()
return scan, drv1, driver2, node
def test_dup_drivers(self):
"""Test handling of duplicate drivers"""
name = 'nvidia_tegra114_i2c'
scan, drv1, driver2, node = self.setup_dup_drivers(name)
self.assertEqual('', drv1.phase)
# The driver should not have a duplicate yet
self.assertEqual([], drv1.dups)
scan._parse_driver('file2.c', driver2)
# The first driver should now be a duplicate of the second
drv2 = scan._drivers[name]
self.assertEqual('', drv2.phase)
self.assertEqual(1, len(drv2.dups))
self.assertEqual([drv1], drv2.dups)
# There is no way to distinguish them, so we should expect a warning
self.assertTrue(drv2.warn_dups)
# We should see a warning
with terminal.capture() as (stdout, _):
scan.mark_used([node])
self.assertEqual(
"Warning: Duplicate driver name 'nvidia_tegra114_i2c' (orig=file2.c, dups=file1.c)",
stdout.getvalue().strip())
def test_dup_drivers_phase(self):
"""Test handling of duplicate drivers but with different phases"""
name = 'nvidia_tegra114_i2c'
scan, drv1, driver2, node = self.setup_dup_drivers(name, 'spl')
scan._parse_driver('file2.c', driver2)
self.assertEqual('spl', drv1.phase)
# The second driver should now be a duplicate of the second
self.assertEqual(1, len(drv1.dups))
drv2 = drv1.dups[0]
# The phase is different, so we should not warn of dups
self.assertFalse(drv1.warn_dups)
# We should not see a warning
with terminal.capture() as (stdout, _):
scan.mark_used([node])
self.assertEqual('', stdout.getvalue().strip())
def test_sequence(self):
"""Test assignment of sequence numnbers"""
scan = src_scan.Scanner(None, None, '')
node = FakeNode()
uc = src_scan.UclassDriver('UCLASS_I2C')
node.uclass = uc
node.driver = True
node.seq = -1
node.path = 'mypath'
uc.alias_num_to_node[2] = node
# This should assign 3 (after the 2 that exists)
seq = scan.assign_seq(node)
self.assertEqual(3, seq)
self.assertEqual({'mypath': 3}, uc.alias_path_to_num)
self.assertEqual({2: node, 3: node}, uc.alias_num_to_node)
def test_scan_warnings(self):
"""Test detection of scanning warnings"""
buff = '''
static const struct udevice_id tegra_i2c_ids[] = {
{ .compatible = "nvidia,tegra114-i2c", .data = TYPE_114 },
{ }
};
U_BOOT_DRIVER(i2c_tegra) = {
.name = "i2c_tegra",
.id = UCLASS_I2C,
.of_match = tegra_i2c_ids + 1,
};
'''
# The '+ 1' above should generate a warning
prop = FakeProp()
prop.name = 'compatible'
prop.value = 'rockchip,rk3288-grf'
node = FakeNode()
node.props = {'compatible': prop}
# get_normalized_compat_name() uses this to check for root node
node.parent = FakeNode()
scan = src_scan.Scanner(None, None)
scan._parse_driver('file.c', buff)
self.assertEqual(
{'i2c_tegra':
{"file.c: Warning: unexpected suffix ' + 1' on .of_match line for compat 'tegra_i2c_ids'"}},
scan._warnings)
tprop = FakeProp()
tprop.name = 'compatible'
tprop.value = 'nvidia,tegra114-i2c'
tnode = FakeNode()
tnode.props = {'compatible': tprop}
# get_normalized_compat_name() uses this to check for root node
tnode.parent = FakeNode()
with terminal.capture() as (stdout, _):
scan.get_normalized_compat_name(node)
scan.get_normalized_compat_name(tnode)
self.assertEqual('', stdout.getvalue().strip())
self.assertEqual(2, len(scan._missing_drivers))
self.assertEqual({'rockchip_rk3288_grf', 'nvidia_tegra114_i2c'},
scan._missing_drivers)
with terminal.capture() as (stdout, _):
scan.show_warnings()
self.assertIn('rockchip_rk3288_grf', stdout.getvalue())
# This should show just the rockchip warning, since the tegra driver
# is not in self._missing_drivers
scan._missing_drivers.remove('nvidia_tegra114_i2c')
with terminal.capture() as (stdout, _):
scan.show_warnings()
self.assertIn('rockchip_rk3288_grf', stdout.getvalue())
self.assertNotIn('tegra_i2c_ids', stdout.getvalue())
# Do a similar thing with used drivers. By marking the tegra driver as
# used, the warning related to that driver will be shown
drv = scan._drivers['i2c_tegra']
drv.used = True
with terminal.capture() as (stdout, _):
scan.show_warnings()
self.assertIn('rockchip_rk3288_grf', stdout.getvalue())
self.assertIn('tegra_i2c_ids', stdout.getvalue())
# Add a warning to make sure multiple warnings are shown
scan._warnings['i2c_tegra'].update(
scan._warnings['nvidia_tegra114_i2c'])
del scan._warnings['nvidia_tegra114_i2c']
with terminal.capture() as (stdout, _):
scan.show_warnings()
self.assertEqual('''i2c_tegra: WARNING: the driver nvidia_tegra114_i2c was not found in the driver list
: file.c: Warning: unexpected suffix ' + 1' on .of_match line for compat 'tegra_i2c_ids'
rockchip_rk3288_grf: WARNING: the driver rockchip_rk3288_grf was not found in the driver list
''',
stdout.getvalue())
self.assertIn('tegra_i2c_ids', stdout.getvalue())
def scan_uclass_warning(self):
"""Test a missing .uclass in the driver"""
buff = '''
static const struct udevice_id tegra_i2c_ids[] = {
{ .compatible = "nvidia,tegra114-i2c", .data = TYPE_114 },
{ }
};
U_BOOT_DRIVER(i2c_tegra) = {
.name = "i2c_tegra",
.of_match = tegra_i2c_ids,
};
'''
scan = src_scan.Scanner(None, None)
scan._parse_driver('file.c', buff)
self.assertEqual(
{'i2c_tegra': {'Missing .uclass in file.c'}},
scan._warnings)
def scan_compat_warning(self):
"""Test a missing .compatible in the driver"""
buff = '''
static const struct udevice_id tegra_i2c_ids[] = {
{ .compatible = "nvidia,tegra114-i2c", .data = TYPE_114 },
{ }
};
U_BOOT_DRIVER(i2c_tegra) = {
.name = "i2c_tegra",
.id = UCLASS_I2C,
};
'''
scan = src_scan.Scanner(None, None)
scan._parse_driver('file.c', buff)
self.assertEqual(
{'i2c_tegra': {'Missing .compatible in file.c'}},
scan._warnings)