1 # SPDX-License-Identifier: GPL-2.0
2 # Copyright (c) 2016, NVIDIA CORPORATION. All rights reserved.
12 # pylint: disable=E0611
13 from tests import fs_helper
15 def mkdir_cond(dirname):
16 """Create a directory if it doesn't already exist
19 dirname (str): Name of directory to create
21 if not os.path.exists(dirname):
24 def setup_image(cons, mmc_dev, part_type, second_part=False):
25 """Create a 20MB disk image with a single partition
28 cons (ConsoleBase): Console to use
29 mmc_dev (int): MMC device number to use, e.g. 1
30 part_type (int): Partition type, e.g. 0xc for FAT32
31 second_part (bool): True to contain a small second partition
35 str: Filename of MMC image
36 str: Directory name of 'mnt' directory
38 fname = os.path.join(cons.config.source_dir, f'mmc{mmc_dev}.img')
39 mnt = os.path.join(cons.config.persistent_data_dir, 'mnt')
42 spec = f'type={part_type:x}, size=18M, bootable'
46 u_boot_utils.run_and_log(cons, 'qemu-img create %s 20M' % fname)
47 u_boot_utils.run_and_log(cons, 'sudo sfdisk %s' % fname,
48 stdin=spec.encode('utf-8'))
51 def mount_image(cons, fname, mnt, fstype):
52 """Create a filesystem and mount it on partition 1
55 cons (ConsoleBase): Console to use
56 fname (str): Filename of MMC image
57 mnt (str): Directory name of 'mnt' directory
58 fstype (str): Filesystem type ('vfat' or 'ext4')
61 str: Name of loop device used
63 out = u_boot_utils.run_and_log(cons, 'sudo losetup --show -f -P %s' % fname)
66 u_boot_utils.run_and_log(cons, f'sudo mkfs.{fstype} {part}')
69 opts += f' -o uid={os.getuid()},gid={os.getgid()}'
70 u_boot_utils.run_and_log(cons, f'sudo mount -o loop {part} {mnt}{opts}')
71 u_boot_utils.run_and_log(cons, f'sudo chown {getpass.getuser()} {mnt}')
74 def copy_prepared_image(cons, mmc_dev, fname):
75 """Use a prepared image since we cannot create one
78 cons (ConsoleBase): Console touse
79 mmc_dev (int): MMC device number
80 fname (str): Filename of MMC image
82 infname = os.path.join(cons.config.source_dir,
83 f'test/py/tests/bootstd/mmc{mmc_dev}.img.xz')
84 u_boot_utils.run_and_log(
86 ['sh', '-c', 'xz -dc %s >%s' % (infname, fname)])
88 def setup_bootmenu_image(cons):
89 """Create a 20MB disk image with a single ext4 partition
91 This is modelled on Armbian 22.08 Jammy
94 fname, mnt = setup_image(cons, mmc_dev, 0x83)
100 loop = mount_image(cons, fname, mnt, 'ext4')
106 script = '''# DO NOT EDIT THIS FILE
108 # Please edit /boot/armbianEnv.txt to set supported parameters
111 setenv load_addr "0x9000000"
112 setenv overlay_error "false"
114 setenv rootdev "/dev/mmcblk%dp1"
116 setenv console "both"
117 setenv bootlogo "false"
118 setenv rootfstype "ext4"
119 setenv docker_optimizations "on"
120 setenv earlycon "off"
122 echo "Boot script loaded from ${devtype} ${devnum}"
124 if test -e ${devtype} ${devnum} ${prefix}armbianEnv.txt; then
125 load ${devtype} ${devnum} ${load_addr} ${prefix}armbianEnv.txt
126 env import -t ${load_addr} ${filesize}
129 if test "${logo}" = "disabled"; then setenv logo "logo.nologo"; fi
131 if test "${console}" = "display" || test "${console}" = "both"; then setenv consoleargs "console=tty1"; fi
132 if test "${console}" = "serial" || test "${console}" = "both"; then setenv consoleargs "console=ttyS2,1500000 ${consoleargs}"; fi
133 if test "${earlycon}" = "on"; then setenv consoleargs "earlycon ${consoleargs}"; fi
134 if test "${bootlogo}" = "true"; then setenv consoleargs "bootsplash.bootfile=bootsplash.armbian ${consoleargs}"; fi
136 # get PARTUUID of first partition on SD/eMMC the boot script was loaded from
137 if test "${devtype}" = "mmc"; then part uuid mmc ${devnum}:1 partuuid; fi
139 setenv bootargs "root=${rootdev} rootwait rootfstype=${rootfstype} ${consoleargs} consoleblank=0 loglevel=${verbosity} ubootpart=${partuuid} usb-storage.quirks=${usbstoragequirks} ${extraargs} ${extraboardargs}"
141 if test "${docker_optimizations}" = "on"; then setenv bootargs "${bootargs} cgroup_enable=cpuset cgroup_memory=1 cgroup_enable=memory swapaccount=1"; fi
143 load ${devtype} ${devnum} ${ramdisk_addr_r} ${prefix}uInitrd
144 load ${devtype} ${devnum} ${kernel_addr_r} ${prefix}Image
146 load ${devtype} ${devnum} ${fdt_addr_r} ${prefix}dtb/${fdtfile}
147 fdt addr ${fdt_addr_r}
149 for overlay_file in ${overlays}; do
150 if load ${devtype} ${devnum} ${load_addr} ${prefix}dtb/rockchip/overlay/${overlay_prefix}-${overlay_file}.dtbo; then
151 echo "Applying kernel provided DT overlay ${overlay_prefix}-${overlay_file}.dtbo"
152 fdt apply ${load_addr} || setenv overlay_error "true"
155 for overlay_file in ${user_overlays}; do
156 if load ${devtype} ${devnum} ${load_addr} ${prefix}overlay-user/${overlay_file}.dtbo; then
157 echo "Applying user provided DT overlay ${overlay_file}.dtbo"
158 fdt apply ${load_addr} || setenv overlay_error "true"
161 if test "${overlay_error}" = "true"; then
162 echo "Error applying DT overlays, restoring original DT"
163 load ${devtype} ${devnum} ${fdt_addr_r} ${prefix}dtb/${fdtfile}
165 if load ${devtype} ${devnum} ${load_addr} ${prefix}dtb/rockchip/overlay/${overlay_prefix}-fixup.scr; then
166 echo "Applying kernel provided DT fixup script (${overlay_prefix}-fixup.scr)"
169 if test -e ${devtype} ${devnum} ${prefix}fixup.scr; then
170 load ${devtype} ${devnum} ${load_addr} ${prefix}fixup.scr
171 echo "Applying user provided fixup script (fixup.scr)"
175 booti ${kernel_addr_r} ${ramdisk_addr_r} ${fdt_addr_r}
178 # mkimage -C none -A arm -T script -d /boot/boot.cmd /boot/boot.scr
180 bootdir = os.path.join(mnt, 'boot')
182 cmd_fname = os.path.join(bootdir, 'boot.cmd')
183 scr_fname = os.path.join(bootdir, 'boot.scr')
184 with open(cmd_fname, 'w') as outf:
185 print(script, file=outf)
187 infname = os.path.join(cons.config.source_dir,
188 'test/py/tests/bootstd/armbian.bmp.xz')
189 bmp_file = os.path.join(bootdir, 'boot.bmp')
190 u_boot_utils.run_and_log(
192 ['sh', '-c', f'xz -dc {infname} >{bmp_file}'])
194 u_boot_utils.run_and_log(
195 cons, f'mkimage -C none -A arm -T script -d {cmd_fname} {scr_fname}')
197 kernel = 'vmlinuz-5.15.63-rockchip64'
198 target = os.path.join(bootdir, kernel)
199 with open(target, 'wb') as outf:
200 print('kernel', outf)
202 symlink = os.path.join(bootdir, 'Image')
203 if os.path.exists(symlink):
205 u_boot_utils.run_and_log(
206 cons, f'echo here {kernel} {symlink}')
207 os.symlink(kernel, symlink)
209 u_boot_utils.run_and_log(
210 cons, f'mkimage -C none -A arm -T script -d {cmd_fname} {scr_fname}')
213 except ValueError as exc:
214 print('Falled to create image, failing back to prepared copy: %s',
218 u_boot_utils.run_and_log(cons, 'sudo umount --lazy %s' % mnt)
220 u_boot_utils.run_and_log(cons, 'sudo losetup -d %s' % loop)
223 copy_prepared_image(cons, mmc_dev, fname)
225 def setup_bootflow_image(cons):
226 """Create a 20MB disk image with a single FAT partition"""
228 fname, mnt = setup_image(cons, mmc_dev, 0xc, second_part=True)
234 loop = mount_image(cons, fname, mnt, 'vfat')
237 vmlinux = 'vmlinuz-5.3.7-301.fc31.armv7hl'
238 initrd = 'initramfs-5.3.7-301.fc31.armv7hl.img'
239 dtbdir = 'dtb-5.3.7-301.fc31.armv7hl'
240 script = '''# extlinux.conf generated by appliance-creator
242 menu autoboot Welcome to Fedora-Workstation-armhfp-31-1.9. Automatic boot in # second{,s}. Press a key for options.
243 menu title Fedora-Workstation-armhfp-31-1.9 Boot Options.
248 label Fedora-Workstation-armhfp-31-1.9 (5.3.7-301.fc31.armv7hl)
250 append ro root=UUID=9732b35b-4cd5-458b-9b91-80f7047e0b8a rhgb quiet LANG=en_US.UTF-8 cma=192MB cma=256MB
252 initrd /%s''' % (vmlinux, dtbdir, initrd)
253 ext = os.path.join(mnt, 'extlinux')
256 with open(os.path.join(ext, 'extlinux.conf'), 'w') as fd:
257 print(script, file=fd)
259 inf = os.path.join(cons.config.persistent_data_dir, 'inf')
260 with open(inf, 'wb') as fd:
261 fd.write(gzip.compress(b'vmlinux'))
262 u_boot_utils.run_and_log(cons, 'mkimage -f auto -d %s %s' %
263 (inf, os.path.join(mnt, vmlinux)))
265 with open(os.path.join(mnt, initrd), 'w') as fd:
266 print('initrd', file=fd)
268 mkdir_cond(os.path.join(mnt, dtbdir))
270 dtb_file = os.path.join(mnt, '%s/sandbox.dtb' % dtbdir)
271 u_boot_utils.run_and_log(
272 cons, 'dtc -o %s' % dtb_file, stdin=b'/dts-v1/; / {};')
274 except ValueError as exc:
275 print('Falled to create image, failing back to prepared copy: %s',
279 u_boot_utils.run_and_log(cons, 'sudo umount --lazy %s' % mnt)
281 u_boot_utils.run_and_log(cons, 'sudo losetup -d %s' % loop)
284 copy_prepared_image(cons, mmc_dev, fname)
287 def setup_cros_image(cons):
288 """Create a 20MB disk image with ChromiumOS partitions"""
289 Partition = collections.namedtuple('part', 'start,size,name')
293 def pack_kernel(cons, arch, kern, dummy):
294 """Pack a kernel containing some fake data
297 cons (ConsoleBase): Console to use
298 arch (str): Architecture to use ('x86' or 'arm')
299 kern (str): Filename containing kernel
300 dummy (str): Dummy filename to use for config and bootloader
303 bytes: Packed-kernel data
305 kern_part = os.path.join(cons.config.result_dir, 'kern-part-{arch}.bin')
306 u_boot_utils.run_and_log(
308 f'futility vbutil_kernel --pack {kern_part} '
309 '--keyblock doc/chromium/files/devkeys/kernel.keyblock '
310 '--signprivate doc/chromium/files/devkeys/kernel_data_key.vbprivk '
311 f'--version 1 --config {dummy} --bootloader {dummy} '
314 with open(kern_part, 'rb') as inf:
315 kern_part_data = inf.read()
316 return kern_part_data
318 def set_part_data(partnum, data):
319 """Set the contents of a disk partition
321 This updates disk_data by putting data in the right place
324 partnum (int): Partition number to set
325 data (bytes): Data for that partition
329 start = parts[partnum].start * sect_size
330 disk_data = disk_data[:start] + data + disk_data[start + len(data):]
333 fname = os.path.join(cons.config.source_dir, f'mmc{mmc_dev}.img')
334 u_boot_utils.run_and_log(cons, 'qemu-img create %s 20M' % fname)
335 #mnt = os.path.join(cons.config.persistent_data_dir, 'mnt')
337 u_boot_utils.run_and_log(cons, f'cgpt create {fname}')
339 uuid_state = 'ebd0a0a2-b9e5-4433-87c0-68b6b72699c7'
340 uuid_kern = 'fe3a2a5d-4f32-41a7-b725-accc3285a309'
341 uuid_root = '3cb8e202-3b7e-47dd-8a3c-7ff2a13cfcec'
342 uuid_rwfw = 'cab6e88e-abf3-4102-a07a-d4bb9be3c1d3'
343 uuid_reserved = '2e0a753d-9e48-43b0-8337-b15192cb1b5e'
344 uuid_efi = 'c12a7328-f81f-11d2-ba4b-00a0c93ec93b'
348 # Number of sectors in 1MB
350 sect_1mb = (1 << 20) // sect_size
353 {'num': 0xb, 'label':'RWFW', 'type': uuid_rwfw, 'size': '1'},
354 {'num': 6, 'label':'KERN_C', 'type': uuid_kern, 'size': '1'},
355 {'num': 7, 'label':'ROOT_C', 'type': uuid_root, 'size': '1'},
356 {'num': 9, 'label':'reserved', 'type': uuid_reserved, 'size': '1'},
357 {'num': 0xa, 'label':'reserved', 'type': uuid_reserved, 'size': '1'},
359 {'num': 2, 'label':'KERN_A', 'type': uuid_kern, 'size': '1M'},
360 {'num': 4, 'label':'KERN_B', 'type': uuid_kern, 'size': '1M'},
362 {'num': 8, 'label':'OEM', 'type': uuid_state, 'size': '1M'},
363 {'num': 0xc, 'label':'EFI-SYSTEM', 'type': uuid_efi, 'size': '1M'},
365 {'num': 5, 'label':'ROOT_B', 'type': uuid_root, 'size': '1'},
366 {'num': 3, 'label':'ROOT_A', 'type': uuid_root, 'size': '1'},
367 {'num': 1, 'label':'STATE', 'type': uuid_state, 'size': '1M'},
370 for part in required_parts:
371 size_str = part['size']
373 size = int(size_str[:-1]) * sect_1mb
376 u_boot_utils.run_and_log(
378 f"cgpt add -i {part['num']} -b {ptr} -s {size} -t {part['type']} {fname}")
381 u_boot_utils.run_and_log(cons, f'cgpt boot -p {fname}')
382 out = u_boot_utils.run_and_log(cons, f'cgpt show -q {fname}')
383 '''We expect something like this:
384 8239 2048 1 Basic data
385 45 2048 2 ChromeOS kernel
386 8238 1 3 ChromeOS rootfs
387 2093 2048 4 ChromeOS kernel
388 8237 1 5 ChromeOS rootfs
389 41 1 6 ChromeOS kernel
390 42 1 7 ChromeOS rootfs
391 4141 2048 8 Basic data
392 43 1 9 ChromeOS reserved
393 44 1 10 ChromeOS reserved
394 40 1 11 ChromeOS firmware
395 6189 2048 12 EFI System Partition
398 # Create a dict (indexed by partition number) containing the above info
399 for line in out.splitlines():
400 start, size, num, name = line.split(maxsplit=3)
401 parts[int(num)] = Partition(int(start), int(size), name)
403 dummy = os.path.join(cons.config.result_dir, 'dummy.txt')
404 with open(dummy, 'wb') as outf:
405 outf.write(b'dummy\n')
407 # For now we just use dummy kernels. This limits testing to just detecting
408 # a signed kernel. We could add support for the x86 data structures so that
409 # testing could cover getting the cmdline, setup.bin and other pieces.
410 kern = os.path.join(cons.config.result_dir, 'kern.bin')
411 with open(kern, 'wb') as outf:
412 outf.write(b'kernel\n')
414 with open(fname, 'rb') as inf:
415 disk_data = inf.read()
417 # put x86 kernel in partition 2 and arm one in partition 4
418 set_part_data(2, pack_kernel(cons, 'x86', kern, dummy))
419 set_part_data(4, pack_kernel(cons, 'arm', kern, dummy))
421 with open(fname, 'wb') as outf:
422 outf.write(disk_data)
427 def setup_cedit_file(cons):
428 infname = os.path.join(cons.config.source_dir,
429 'test/boot/files/expo_layout.dts')
430 inhname = os.path.join(cons.config.source_dir,
431 'test/boot/files/expo_ids.h')
432 expo_tool = os.path.join(cons.config.source_dir, 'tools/expo.py')
433 outfname = 'cedit.dtb'
434 u_boot_utils.run_and_log(
435 cons, f'{expo_tool} -e {inhname} -l {infname} -o {outfname}')
437 @pytest.mark.buildconfigspec('ut_dm')
438 def test_ut_dm_init(u_boot_console):
439 """Initialize data for ut dm tests."""
441 fn = u_boot_console.config.source_dir + '/testflash.bin'
442 if not os.path.exists(fn):
443 data = b'this is a test'
444 data += b'\x00' * ((4 * 1024 * 1024) - len(data))
445 with open(fn, 'wb') as fh:
448 fn = u_boot_console.config.source_dir + '/spi.bin'
449 if not os.path.exists(fn):
450 data = b'\x00' * (2 * 1024 * 1024)
451 with open(fn, 'wb') as fh:
454 # Create a file with a single partition
455 fn = u_boot_console.config.source_dir + '/scsi.img'
456 if not os.path.exists(fn):
457 data = b'\x00' * (2 * 1024 * 1024)
458 with open(fn, 'wb') as fh:
460 u_boot_utils.run_and_log(
461 u_boot_console, f'sfdisk {fn}', stdin=b'type=83')
463 fs_helper.mk_fs(u_boot_console.config, 'ext2', 0x200000, '2MB')
464 fs_helper.mk_fs(u_boot_console.config, 'fat32', 0x100000, '1MB')
467 fn = os.path.join(u_boot_console.config.source_dir, f'mmc{mmc_dev}.img')
468 data = b'\x00' * (12 * 1024 * 1024)
469 with open(fn, 'wb') as fh:
472 @pytest.mark.buildconfigspec('cmd_bootflow')
473 @pytest.mark.buildconfigspec('sandbox')
474 def test_ut_dm_init_bootstd(u_boot_console):
475 """Initialise data for bootflow tests"""
477 setup_bootflow_image(u_boot_console)
478 setup_bootmenu_image(u_boot_console)
479 setup_cedit_file(u_boot_console)
480 setup_cros_image(u_boot_console)
482 # Restart so that the new mmc1.img is picked up
483 u_boot_console.restart_uboot()
486 def test_ut(u_boot_console, ut_subtest):
487 """Execute a "ut" subtest.
489 The subtests are collected in function generate_ut_subtest() from linker
490 generated lists by applying a regular expression to the lines of file
491 u-boot.sym. The list entries are created using the C macro UNIT_TEST().
493 Strict naming conventions have to be followed to match the regular
494 expression. Use UNIT_TEST(foo_test_bar, _flags, foo_test) for a test bar in
495 test suite foo that can be executed via command 'ut foo bar' and is
496 implemented in C function foo_test_bar().
499 u_boot_console (ConsoleBase): U-Boot console
500 ut_subtest (str): test to be executed via command ut, e.g 'foo bar' to
501 execute command 'ut foo bar'
504 if ut_subtest == 'hush hush_test_simple_dollar':
505 # ut hush hush_test_simple_dollar prints "Unknown command" on purpose.
506 with u_boot_console.disable_check('unknown_command'):
507 output = u_boot_console.run_command('ut ' + ut_subtest)
508 assert('Unknown command \'quux\' - try \'help\'' in output)
510 output = u_boot_console.run_command('ut ' + ut_subtest)
511 assert output.endswith('Failures: 0')