1 # SPDX-License-Identifier: GPL-2.0
2 # Copyright (c) 2016, NVIDIA CORPORATION. All rights reserved.
12 from tests import fs_helper
14 def mkdir_cond(dirname):
15 """Create a directory if it doesn't already exist
18 dirname (str): Name of directory to create
20 if not os.path.exists(dirname):
23 def setup_image(cons, mmc_dev, part_type, second_part=False):
24 """Create a 20MB disk image with a single partition
27 cons (ConsoleBase): Console to use
28 mmc_dev (int): MMC device number to use, e.g. 1
29 part_type (int): Partition type, e.g. 0xc for FAT32
30 second_part (bool): True to contain a small second partition
34 str: Filename of MMC image
35 str: Directory name of 'mnt' directory
37 fname = os.path.join(cons.config.source_dir, f'mmc{mmc_dev}.img')
38 mnt = os.path.join(cons.config.persistent_data_dir, 'mnt')
41 spec = f'type={part_type:x}, size=18M, bootable'
45 u_boot_utils.run_and_log(cons, 'qemu-img create %s 20M' % fname)
46 u_boot_utils.run_and_log(cons, 'sudo sfdisk %s' % fname,
47 stdin=spec.encode('utf-8'))
50 def mount_image(cons, fname, mnt, fstype):
51 """Create a filesystem and mount it on partition 1
54 cons (ConsoleBase): Console to use
55 fname (str): Filename of MMC image
56 mnt (str): Directory name of 'mnt' directory
57 fstype (str): Filesystem type ('vfat' or 'ext4')
60 str: Name of loop device used
62 out = u_boot_utils.run_and_log(cons, 'sudo losetup --show -f -P %s' % fname)
65 u_boot_utils.run_and_log(cons, f'sudo mkfs.{fstype} {part}')
68 opts += f' -o uid={os.getuid()},gid={os.getgid()}'
69 u_boot_utils.run_and_log(cons, f'sudo mount -o loop {part} {mnt}{opts}')
70 u_boot_utils.run_and_log(cons, f'sudo chown {getpass.getuser()} {mnt}')
73 def copy_prepared_image(cons, mmc_dev, fname):
74 """Use a prepared image since we cannot create one
77 cons (ConsoleBase): Console touse
78 mmc_dev (int): MMC device number
79 fname (str): Filename of MMC image
81 infname = os.path.join(cons.config.source_dir,
82 f'test/py/tests/bootstd/mmc{mmc_dev}.img.xz')
83 u_boot_utils.run_and_log(
85 ['sh', '-c', 'xz -dc %s >%s' % (infname, fname)])
87 def setup_bootmenu_image(cons):
88 """Create a 20MB disk image with a single ext4 partition
90 This is modelled on Armbian 22.08 Jammy
93 fname, mnt = setup_image(cons, mmc_dev, 0x83)
99 loop = mount_image(cons, fname, mnt, 'ext4')
105 script = '''# DO NOT EDIT THIS FILE
107 # Please edit /boot/armbianEnv.txt to set supported parameters
110 setenv load_addr "0x9000000"
111 setenv overlay_error "false"
113 setenv rootdev "/dev/mmcblk%dp1"
115 setenv console "both"
116 setenv bootlogo "false"
117 setenv rootfstype "ext4"
118 setenv docker_optimizations "on"
119 setenv earlycon "off"
121 echo "Boot script loaded from ${devtype} ${devnum}"
123 if test -e ${devtype} ${devnum} ${prefix}armbianEnv.txt; then
124 load ${devtype} ${devnum} ${load_addr} ${prefix}armbianEnv.txt
125 env import -t ${load_addr} ${filesize}
128 if test "${logo}" = "disabled"; then setenv logo "logo.nologo"; fi
130 if test "${console}" = "display" || test "${console}" = "both"; then setenv consoleargs "console=tty1"; fi
131 if test "${console}" = "serial" || test "${console}" = "both"; then setenv consoleargs "console=ttyS2,1500000 ${consoleargs}"; fi
132 if test "${earlycon}" = "on"; then setenv consoleargs "earlycon ${consoleargs}"; fi
133 if test "${bootlogo}" = "true"; then setenv consoleargs "bootsplash.bootfile=bootsplash.armbian ${consoleargs}"; fi
135 # get PARTUUID of first partition on SD/eMMC the boot script was loaded from
136 if test "${devtype}" = "mmc"; then part uuid mmc ${devnum}:1 partuuid; fi
138 setenv bootargs "root=${rootdev} rootwait rootfstype=${rootfstype} ${consoleargs} consoleblank=0 loglevel=${verbosity} ubootpart=${partuuid} usb-storage.quirks=${usbstoragequirks} ${extraargs} ${extraboardargs}"
140 if test "${docker_optimizations}" = "on"; then setenv bootargs "${bootargs} cgroup_enable=cpuset cgroup_memory=1 cgroup_enable=memory swapaccount=1"; fi
142 load ${devtype} ${devnum} ${ramdisk_addr_r} ${prefix}uInitrd
143 load ${devtype} ${devnum} ${kernel_addr_r} ${prefix}Image
145 load ${devtype} ${devnum} ${fdt_addr_r} ${prefix}dtb/${fdtfile}
146 fdt addr ${fdt_addr_r}
148 for overlay_file in ${overlays}; do
149 if load ${devtype} ${devnum} ${load_addr} ${prefix}dtb/rockchip/overlay/${overlay_prefix}-${overlay_file}.dtbo; then
150 echo "Applying kernel provided DT overlay ${overlay_prefix}-${overlay_file}.dtbo"
151 fdt apply ${load_addr} || setenv overlay_error "true"
154 for overlay_file in ${user_overlays}; do
155 if load ${devtype} ${devnum} ${load_addr} ${prefix}overlay-user/${overlay_file}.dtbo; then
156 echo "Applying user provided DT overlay ${overlay_file}.dtbo"
157 fdt apply ${load_addr} || setenv overlay_error "true"
160 if test "${overlay_error}" = "true"; then
161 echo "Error applying DT overlays, restoring original DT"
162 load ${devtype} ${devnum} ${fdt_addr_r} ${prefix}dtb/${fdtfile}
164 if load ${devtype} ${devnum} ${load_addr} ${prefix}dtb/rockchip/overlay/${overlay_prefix}-fixup.scr; then
165 echo "Applying kernel provided DT fixup script (${overlay_prefix}-fixup.scr)"
168 if test -e ${devtype} ${devnum} ${prefix}fixup.scr; then
169 load ${devtype} ${devnum} ${load_addr} ${prefix}fixup.scr
170 echo "Applying user provided fixup script (fixup.scr)"
174 booti ${kernel_addr_r} ${ramdisk_addr_r} ${fdt_addr_r}
177 # mkimage -C none -A arm -T script -d /boot/boot.cmd /boot/boot.scr
179 bootdir = os.path.join(mnt, 'boot')
181 cmd_fname = os.path.join(bootdir, 'boot.cmd')
182 scr_fname = os.path.join(bootdir, 'boot.scr')
183 with open(cmd_fname, 'w') as outf:
184 print(script, file=outf)
186 infname = os.path.join(cons.config.source_dir,
187 'test/py/tests/bootstd/armbian.bmp.xz')
188 bmp_file = os.path.join(bootdir, 'boot.bmp')
189 u_boot_utils.run_and_log(
191 ['sh', '-c', f'xz -dc {infname} >{bmp_file}'])
193 u_boot_utils.run_and_log(
194 cons, f'mkimage -C none -A arm -T script -d {cmd_fname} {scr_fname}')
196 kernel = 'vmlinuz-5.15.63-rockchip64'
197 target = os.path.join(bootdir, kernel)
198 with open(target, 'wb') as outf:
199 print('kernel', outf)
201 symlink = os.path.join(bootdir, 'Image')
202 if os.path.exists(symlink):
204 u_boot_utils.run_and_log(
205 cons, f'echo here {kernel} {symlink}')
206 os.symlink(kernel, symlink)
208 u_boot_utils.run_and_log(
209 cons, f'mkimage -C none -A arm -T script -d {cmd_fname} {scr_fname}')
212 except ValueError as exc:
213 print('Falled to create image, failing back to prepared copy: %s',
217 u_boot_utils.run_and_log(cons, 'sudo umount --lazy %s' % mnt)
219 u_boot_utils.run_and_log(cons, 'sudo losetup -d %s' % loop)
222 copy_prepared_image(cons, mmc_dev, fname)
224 def setup_bootflow_image(cons):
225 """Create a 20MB disk image with a single FAT partition"""
227 fname, mnt = setup_image(cons, mmc_dev, 0xc, second_part=True)
233 loop = mount_image(cons, fname, mnt, 'vfat')
236 vmlinux = 'vmlinuz-5.3.7-301.fc31.armv7hl'
237 initrd = 'initramfs-5.3.7-301.fc31.armv7hl.img'
238 dtbdir = 'dtb-5.3.7-301.fc31.armv7hl'
239 script = '''# extlinux.conf generated by appliance-creator
241 menu autoboot Welcome to Fedora-Workstation-armhfp-31-1.9. Automatic boot in # second{,s}. Press a key for options.
242 menu title Fedora-Workstation-armhfp-31-1.9 Boot Options.
247 label Fedora-Workstation-armhfp-31-1.9 (5.3.7-301.fc31.armv7hl)
249 append ro root=UUID=9732b35b-4cd5-458b-9b91-80f7047e0b8a rhgb quiet LANG=en_US.UTF-8 cma=192MB cma=256MB
251 initrd /%s''' % (vmlinux, dtbdir, initrd)
252 ext = os.path.join(mnt, 'extlinux')
255 with open(os.path.join(ext, 'extlinux.conf'), 'w') as fd:
256 print(script, file=fd)
258 inf = os.path.join(cons.config.persistent_data_dir, 'inf')
259 with open(inf, 'wb') as fd:
260 fd.write(gzip.compress(b'vmlinux'))
261 u_boot_utils.run_and_log(cons, 'mkimage -f auto -d %s %s' %
262 (inf, os.path.join(mnt, vmlinux)))
264 with open(os.path.join(mnt, initrd), 'w') as fd:
265 print('initrd', file=fd)
267 mkdir_cond(os.path.join(mnt, dtbdir))
269 dtb_file = os.path.join(mnt, '%s/sandbox.dtb' % dtbdir)
270 u_boot_utils.run_and_log(
271 cons, 'dtc -o %s' % dtb_file, stdin=b'/dts-v1/; / {};')
273 except ValueError as exc:
274 print('Falled to create image, failing back to prepared copy: %s',
278 u_boot_utils.run_and_log(cons, 'sudo umount --lazy %s' % mnt)
280 u_boot_utils.run_and_log(cons, 'sudo losetup -d %s' % loop)
283 copy_prepared_image(cons, mmc_dev, fname)
286 def setup_cros_image(cons):
287 """Create a 20MB disk image with ChromiumOS partitions"""
288 Partition = collections.namedtuple('part', 'start,size,name')
292 def pack_kernel(cons, arch, kern, dummy):
293 """Pack a kernel containing some fake data
296 cons (ConsoleBase): Console to use
297 arch (str): Architecture to use ('x86' or 'arm')
298 kern (str): Filename containing kernel
299 dummy (str): Dummy filename to use for config and bootloader
302 bytes: Packed-kernel data
304 kern_part = os.path.join(cons.config.result_dir, 'kern-part-{arch}.bin')
305 u_boot_utils.run_and_log(
307 f'futility vbutil_kernel --pack {kern_part} '
308 '--keyblock doc/chromium/files/devkeys/kernel.keyblock '
309 '--signprivate doc/chromium/files/devkeys/kernel_data_key.vbprivk '
310 f'--version 1 --config {dummy} --bootloader {dummy} '
313 with open(kern_part, 'rb') as inf:
314 kern_part_data = inf.read()
315 return kern_part_data
317 def set_part_data(partnum, data):
318 """Set the contents of a disk partition
320 This updates disk_data by putting data in the right place
323 partnum (int): Partition number to set
324 data (bytes): Data for that partition
328 start = parts[partnum].start * sect_size
329 disk_data = disk_data[:start] + data + disk_data[start + len(data):]
332 fname = os.path.join(cons.config.source_dir, f'mmc{mmc_dev}.img')
333 u_boot_utils.run_and_log(cons, 'qemu-img create %s 20M' % fname)
334 #mnt = os.path.join(cons.config.persistent_data_dir, 'mnt')
336 u_boot_utils.run_and_log(cons, f'cgpt create {fname}')
338 uuid_state = 'ebd0a0a2-b9e5-4433-87c0-68b6b72699c7'
339 uuid_kern = 'fe3a2a5d-4f32-41a7-b725-accc3285a309'
340 uuid_root = '3cb8e202-3b7e-47dd-8a3c-7ff2a13cfcec'
341 uuid_rwfw = 'cab6e88e-abf3-4102-a07a-d4bb9be3c1d3'
342 uuid_reserved = '2e0a753d-9e48-43b0-8337-b15192cb1b5e'
343 uuid_efi = 'c12a7328-f81f-11d2-ba4b-00a0c93ec93b'
347 # Number of sectors in 1MB
349 sect_1mb = (1 << 20) // sect_size
352 {'num': 0xb, 'label':'RWFW', 'type': uuid_rwfw, 'size': '1'},
353 {'num': 6, 'label':'KERN_C', 'type': uuid_kern, 'size': '1'},
354 {'num': 7, 'label':'ROOT_C', 'type': uuid_root, 'size': '1'},
355 {'num': 9, 'label':'reserved', 'type': uuid_reserved, 'size': '1'},
356 {'num': 0xa, 'label':'reserved', 'type': uuid_reserved, 'size': '1'},
358 {'num': 2, 'label':'KERN_A', 'type': uuid_kern, 'size': '1M'},
359 {'num': 4, 'label':'KERN_B', 'type': uuid_kern, 'size': '1M'},
361 {'num': 8, 'label':'OEM', 'type': uuid_state, 'size': '1M'},
362 {'num': 0xc, 'label':'EFI-SYSTEM', 'type': uuid_efi, 'size': '1M'},
364 {'num': 5, 'label':'ROOT_B', 'type': uuid_root, 'size': '1'},
365 {'num': 3, 'label':'ROOT_A', 'type': uuid_root, 'size': '1'},
366 {'num': 1, 'label':'STATE', 'type': uuid_state, 'size': '1M'},
369 for part in required_parts:
370 size_str = part['size']
372 size = int(size_str[:-1]) * sect_1mb
375 u_boot_utils.run_and_log(
377 f"cgpt add -i {part['num']} -b {ptr} -s {size} -t {part['type']} {fname}")
380 u_boot_utils.run_and_log(cons, f'cgpt boot -p {fname}')
381 out = u_boot_utils.run_and_log(cons, f'cgpt show -q {fname}')
382 '''We expect something like this:
383 8239 2048 1 Basic data
384 45 2048 2 ChromeOS kernel
385 8238 1 3 ChromeOS rootfs
386 2093 2048 4 ChromeOS kernel
387 8237 1 5 ChromeOS rootfs
388 41 1 6 ChromeOS kernel
389 42 1 7 ChromeOS rootfs
390 4141 2048 8 Basic data
391 43 1 9 ChromeOS reserved
392 44 1 10 ChromeOS reserved
393 40 1 11 ChromeOS firmware
394 6189 2048 12 EFI System Partition
397 # Create a dict (indexed by partition number) containing the above info
398 for line in out.splitlines():
399 start, size, num, name = line.split(maxsplit=3)
400 parts[int(num)] = Partition(int(start), int(size), name)
402 dummy = os.path.join(cons.config.result_dir, 'dummy.txt')
403 with open(dummy, 'wb') as outf:
404 outf.write(b'dummy\n')
406 # For now we just use dummy kernels. This limits testing to just detecting
407 # a signed kernel. We could add support for the x86 data structures so that
408 # testing could cover getting the cmdline, setup.bin and other pieces.
409 kern = os.path.join(cons.config.result_dir, 'kern.bin')
410 with open(kern, 'wb') as outf:
411 outf.write(b'kernel\n')
413 with open(fname, 'rb') as inf:
414 disk_data = inf.read()
416 # put x86 kernel in partition 2 and arm one in partition 4
417 set_part_data(2, pack_kernel(cons, 'x86', kern, dummy))
418 set_part_data(4, pack_kernel(cons, 'arm', kern, dummy))
420 with open(fname, 'wb') as outf:
421 outf.write(disk_data)
426 def setup_cedit_file(cons):
427 infname = os.path.join(cons.config.source_dir,
428 'test/boot/files/expo_layout.dts')
429 inhname = os.path.join(cons.config.source_dir,
430 'test/boot/files/expo_ids.h')
431 expo_tool = os.path.join(cons.config.source_dir, 'tools/expo.py')
432 outfname = 'cedit.dtb'
433 u_boot_utils.run_and_log(
434 cons, f'{expo_tool} -e {inhname} -l {infname} -o {outfname}')
436 @pytest.mark.buildconfigspec('ut_dm')
437 def test_ut_dm_init(u_boot_console):
438 """Initialize data for ut dm tests."""
440 fn = u_boot_console.config.source_dir + '/testflash.bin'
441 if not os.path.exists(fn):
442 data = b'this is a test'
443 data += b'\x00' * ((4 * 1024 * 1024) - len(data))
444 with open(fn, 'wb') as fh:
447 fn = u_boot_console.config.source_dir + '/spi.bin'
448 if not os.path.exists(fn):
449 data = b'\x00' * (2 * 1024 * 1024)
450 with open(fn, 'wb') as fh:
453 # Create a file with a single partition
454 fn = u_boot_console.config.source_dir + '/scsi.img'
455 if not os.path.exists(fn):
456 data = b'\x00' * (2 * 1024 * 1024)
457 with open(fn, 'wb') as fh:
459 u_boot_utils.run_and_log(
460 u_boot_console, f'sfdisk {fn}', stdin=b'type=83')
462 fs_helper.mk_fs(u_boot_console.config, 'ext2', 0x200000, '2MB')
463 fs_helper.mk_fs(u_boot_console.config, 'fat32', 0x100000, '1MB')
466 fn = os.path.join(u_boot_console.config.source_dir, f'mmc{mmc_dev}.img')
467 data = b'\x00' * (12 * 1024 * 1024)
468 with open(fn, 'wb') as fh:
471 @pytest.mark.buildconfigspec('cmd_bootflow')
472 def test_ut_dm_init_bootstd(u_boot_console):
473 """Initialise data for bootflow tests"""
475 setup_bootflow_image(u_boot_console)
476 setup_bootmenu_image(u_boot_console)
477 setup_cedit_file(u_boot_console)
478 setup_cros_image(u_boot_console)
480 # Restart so that the new mmc1.img is picked up
481 u_boot_console.restart_uboot()
484 def test_ut(u_boot_console, ut_subtest):
485 """Execute a "ut" subtest.
487 The subtests are collected in function generate_ut_subtest() from linker
488 generated lists by applying a regular expression to the lines of file
489 u-boot.sym. The list entries are created using the C macro UNIT_TEST().
491 Strict naming conventions have to be followed to match the regular
492 expression. Use UNIT_TEST(foo_test_bar, _flags, foo_test) for a test bar in
493 test suite foo that can be executed via command 'ut foo bar' and is
494 implemented in C function foo_test_bar().
497 u_boot_console (ConsoleBase): U-Boot console
498 ut_subtest (str): test to be executed via command ut, e.g 'foo bar' to
499 execute command 'ut foo bar'
502 output = u_boot_console.run_command('ut ' + ut_subtest)
503 assert output.endswith('Failures: 0')