1.. SPDX-License-Identifier: GPL-2.0+ */
2.. Copyright (c) 2014 The Chromium OS Authors.
3.. sectionauthor:: Simon Glass <sjg@chromium.org>
4
5Sandbox
6=======
7
8Native Execution of U-Boot
9--------------------------
10
11The 'sandbox' architecture is designed to allow U-Boot to run under Linux on
12almost any hardware. To achieve this it builds U-Boot (so far as possible)
13as a normal C application with a main() and normal C libraries.
14
15All of U-Boot's architecture-specific code therefore cannot be built as part
16of the sandbox U-Boot. The purpose of running U-Boot under Linux is to test
17all the generic code, not specific to any one architecture. The idea is to
18create unit tests which we can run to test this upper level code.
19
20CONFIG_SANDBOX is defined when building a native board.
21
22The board name is 'sandbox' but the vendor name is unset, so there is a
23single board in board/sandbox.
24
25CONFIG_SANDBOX_BIG_ENDIAN should be defined when running on big-endian
26machines.
27
28There are two versions of the sandbox: One using 32-bit-wide integers, and one
29using 64-bit-wide integers. The 32-bit version can be build and run on either
3032 or 64-bit hosts by either selecting or deselecting CONFIG_SANDBOX_32BIT; by
31default, the sandbox it built for a 32-bit host. The sandbox using 64-bit-wide
32integers can only be built on 64-bit hosts.
33
34Note that standalone/API support is not available at present.
35
36
37Prerequisites
38-------------
39
40Here are some packages that are worth installing if you are doing sandbox or
41tools development in U-Boot:
42
43   python3-pytest lzma lzma-alone lz4 python3 python3-virtualenv
44   libssl1.0-dev
45
46
47Basic Operation
48---------------
49
50To run sandbox U-Boot use something like::
51
52   make sandbox_defconfig all
53   ./u-boot
54
55Note: If you get errors about 'sdl-config: Command not found' you may need to
56install libsdl2.0-dev or similar to get SDL support. Alternatively you can
57build sandbox without SDL (i.e. no display/keyboard support) by removing
58the CONFIG_SANDBOX_SDL line in include/configs/sandbox.h or using::
59
60   make sandbox_defconfig all NO_SDL=1
61   ./u-boot
62
63U-Boot will start on your computer, showing a sandbox emulation of the serial
64console::
65
66   U-Boot 2014.04 (Mar 20 2014 - 19:06:00)
67
68   DRAM:  128 MiB
69   Using default environment
70
71   In:    serial
72   Out:   lcd
73   Err:   lcd
74   =>
75
76You can issue commands as your would normally. If the command you want is
77not supported you can add it to include/configs/sandbox.h.
78
79To exit, type 'reset' or press Ctrl-C.
80
81
82Console / LCD support
83---------------------
84
85Assuming that CONFIG_SANDBOX_SDL is defined when building, you can run the
86sandbox with LCD and keyboard emulation, using something like::
87
88   ./u-boot -d u-boot.dtb -l
89
90This will start U-Boot with a window showing the contents of the LCD. If
91that window has the focus then you will be able to type commands as you
92would on the console. You can adjust the display settings in the device
93tree file - see arch/sandbox/dts/sandbox.dts.
94
95
96Command-line Options
97--------------------
98
99Various options are available, mostly for test purposes. Use -h to see
100available options. Some of these are described below:
101
102-t, --terminal <arg>
103  The terminal is normally in what is called 'raw-with-sigs' mode. This means
104  that you can use arrow keys for command editing and history, but if you
105  press Ctrl-C, U-Boot will exit instead of handling this as a keypress.
106  Other options are 'raw' (so Ctrl-C is handled within U-Boot) and 'cooked'
107  (where the terminal is in cooked mode and cursor keys will not work, Ctrl-C
108  will exit).
109
110-l
111  Show the LCD emulation window.
112
113-d <device_tree>
114  A device tree binary file can be provided with -d. If you edit the source
115  (it is stored at arch/sandbox/dts/sandbox.dts) you must rebuild U-Boot to
116  recreate the binary file.
117
118-D
119  To use the default device tree, use -D.
120
121-T
122  To use the test device tree, use -T.
123
124-c [<cmd>;]<cmd>
125  To execute commands directly, use the -c option. You can specify a single
126  command, or multiple commands separated by a semicolon, as is normal in
127  U-Boot. Be careful with quoting as the shell will normally process and
128  swallow quotes. When -c is used, U-Boot exits after the command is complete,
129  but you can force it to go to interactive mode instead with -i.
130
131-i
132  Go to interactive mode after executing the commands specified by -c.
133
134Environment Variables
135---------------------
136
137UBOOT_SB_TIME_OFFSET
138    This environment variable stores the offset of the emulated real time clock
139    to the host's real time clock in seconds. The offset defaults to zero.
140
141Memory Emulation
142----------------
143
144Memory emulation is supported, with the size set by CONFIG_SYS_SDRAM_SIZE.
145The -m option can be used to read memory from a file on start-up and write
146it when shutting down. This allows preserving of memory contents across
147test runs. You can tell U-Boot to remove the memory file after it is read
148(on start-up) with the --rm_memory option.
149
150To access U-Boot's emulated memory within the code, use map_sysmem(). This
151function is used throughout U-Boot to ensure that emulated memory is used
152rather than the U-Boot application memory. This provides memory starting
153at 0 and extending to the size of the emulation.
154
155
156Storing State
157-------------
158
159With sandbox you can write drivers which emulate the operation of drivers on
160real devices. Some of these drivers may want to record state which is
161preserved across U-Boot runs. This is particularly useful for testing. For
162example, the contents of a SPI flash chip should not disappear just because
163U-Boot exits.
164
165State is stored in a device tree file in a simple format which is driver-
166specific. You then use the -s option to specify the state file. Use -r to
167make U-Boot read the state on start-up (otherwise it starts empty) and -w
168to write it on exit (otherwise the stored state is left unchanged and any
169changes U-Boot made will be lost). You can also use -n to tell U-Boot to
170ignore any problems with missing state. This is useful when first running
171since the state file will be empty.
172
173The device tree file has one node for each driver - the driver can store
174whatever properties it likes in there. See 'Writing Sandbox Drivers' below
175for more details on how to get drivers to read and write their state.
176
177
178Running and Booting
179-------------------
180
181Since there is no machine architecture, sandbox U-Boot cannot actually boot
182a kernel, but it does support the bootm command. Filesystems, memory
183commands, hashing, FIT images, verified boot and many other features are
184supported.
185
186When 'bootm' runs a kernel, sandbox will exit, as U-Boot does on a real
187machine. Of course in this case, no kernel is run.
188
189It is also possible to tell U-Boot that it has jumped from a temporary
190previous U-Boot binary, with the -j option. That binary is automatically
191removed by the U-Boot that gets the -j option. This allows you to write
192tests which emulate the action of chain-loading U-Boot, typically used in
193a situation where a second 'updatable' U-Boot is stored on your board. It
194is very risky to overwrite or upgrade the only U-Boot on a board, since a
195power or other failure will brick the board and require return to the
196manufacturer in the case of a consumer device.
197
198
199Supported Drivers
200-----------------
201
202U-Boot sandbox supports these emulations:
203
204- Block devices
205- Chrome OS EC
206- GPIO
207- Host filesystem (access files on the host from within U-Boot)
208- I2C
209- Keyboard (Chrome OS)
210- LCD
211- Network
212- Serial (for console only)
213- Sound (incomplete - see sandbox_sdl_sound_init() for details)
214- SPI
215- SPI flash
216- TPM (Trusted Platform Module)
217
218A wide range of commands are implemented. Filesystems which use a block
219device are supported.
220
221Also sandbox supports driver model (CONFIG_DM) and associated commands.
222
223
224Sandbox Variants
225----------------
226
227There are unfortunately quite a few variants at present:
228
229sandbox:
230  should be used for most tests
231sandbox64:
232  special build that forces a 64-bit host
233sandbox_flattree:
234  builds with dev_read\_...() functions defined as inline.
235  We need this build so that we can test those inline functions, and we
236  cannot build with both the inline functions and the non-inline functions
237  since they are named the same.
238sandbox_spl:
239  builds sandbox with SPL support, so you can run spl/u-boot-spl
240  and it will start up and then load ./u-boot. It is also possible to
241  run ./u-boot directly.
242
243Of these sandbox_spl can probably be removed since it is a superset of sandbox.
244
245Most of the config options should be identical between these variants.
246
247
248Linux RAW Networking Bridge
249---------------------------
250
251The sandbox_eth_raw driver bridges traffic between the bottom of the network
252stack and the RAW sockets API in Linux. This allows much of the U-Boot network
253functionality to be tested in sandbox against real network traffic.
254
255For Ethernet network adapters, the bridge utilizes the RAW AF_PACKET API.  This
256is needed to get access to the lowest level of the network stack in Linux. This
257means that all of the Ethernet frame is included. This allows the U-Boot network
258stack to be fully used. In other words, nothing about the Linux network stack is
259involved in forming the packets that end up on the wire. To receive the
260responses to packets sent from U-Boot the network interface has to be set to
261promiscuous mode so that the network card won't filter out packets not destined
262for its configured (on Linux) MAC address.
263
264The RAW sockets Ethernet API requires elevated privileges in Linux. You can
265either run as root, or you can add the capability needed like so::
266
267   sudo /sbin/setcap "CAP_NET_RAW+ep" /path/to/u-boot
268
269The default device tree for sandbox includes an entry for eth0 on the sandbox
270host machine whose alias is "eth1". The following are a few examples of network
271operations being tested on the eth0 interface.
272
273.. code-block:: none
274
275   sudo /path/to/u-boot -D
276
277   DHCP
278   ....
279
280   setenv autoload no
281   setenv ethrotate no
282   setenv ethact eth1
283   dhcp
284
285   PING
286   ....
287
288   setenv autoload no
289   setenv ethrotate no
290   setenv ethact eth1
291   dhcp
292   ping $gatewayip
293
294   TFTP
295   ....
296
297   setenv autoload no
298   setenv ethrotate no
299   setenv ethact eth1
300   dhcp
301   setenv serverip WWW.XXX.YYY.ZZZ
302   tftpboot u-boot.bin
303
304The bridge also supports (to a lesser extent) the localhost interface, 'lo'.
305
306The 'lo' interface cannot use the RAW AF_PACKET API because the lo interface
307doesn't support Ethernet-level traffic. It is a higher-level interface that is
308expected only to be used at the AF_INET level of the API. As such, the most raw
309we can get on that interface is the RAW AF_INET API on UDP. This allows us to
310set the IP_HDRINCL option to include everything except the Ethernet header in
311the packets we send and receive.
312
313Because only UDP is supported, ICMP traffic will not work, so expect that ping
314commands will time out.
315
316The default device tree for sandbox includes an entry for lo on the sandbox
317host machine whose alias is "eth5". The following is an example of a network
318operation being tested on the lo interface.
319
320.. code-block:: none
321
322   TFTP
323   ....
324
325   setenv ethrotate no
326   setenv ethact eth5
327   tftpboot u-boot.bin
328
329
330SPI Emulation
331-------------
332
333Sandbox supports SPI and SPI flash emulation.
334
335The device can be enabled via a device tree, for example::
336
337    spi@0 {
338            #address-cells = <1>;
339            #size-cells = <0>;
340            reg = <0 1>;
341            compatible = "sandbox,spi";
342            cs-gpios = <0>, <&gpio_a 0>;
343            spi.bin@0 {
344                    reg = <0>;
345                    compatible = "spansion,m25p16", "jedec,spi-nor";
346                    spi-max-frequency = <40000000>;
347                    sandbox,filename = "spi.bin";
348            };
349    };
350
351The file must be created in advance::
352
353   $ dd if=/dev/zero of=spi.bin bs=1M count=2
354   $ u-boot -T
355
356Here, you can use "-T" or "-D" option to specify test.dtb or u-boot.dtb,
357respectively, or "-d <file>" for your own dtb.
358
359With this setup you can issue SPI flash commands as normal::
360
361   =>sf probe
362   SF: Detected M25P16 with page size 64 KiB, total 2 MiB
363   =>sf read 0 0 10000
364   SF: 65536 bytes @ 0x0 Read: OK
365
366Since this is a full SPI emulation (rather than just flash), you can
367also use low-level SPI commands::
368
369   =>sspi 0:0 32 9f
370   FF202015
371
372This is issuing a READ_ID command and getting back 20 (ST Micro) part
3730x2015 (the M25P16).
374
375
376Block Device Emulation
377----------------------
378
379U-Boot can use raw disk images for block device emulation. To e.g. list
380the contents of the root directory on the second partion of the image
381"disk.raw", you can use the following commands::
382
383   =>host bind 0 ./disk.raw
384   =>ls host 0:2
385
386A disk image can be created using the following commands::
387
388   $> truncate -s 1200M ./disk.raw
389   $> echo -e "label: gpt\n,64M,U\n,,L" | /usr/sbin/sgdisk  ./disk.raw
390   $> lodev=`sudo losetup -P -f --show ./disk.raw`
391   $> sudo mkfs.vfat -n EFI -v ${lodev}p1
392   $> sudo mkfs.ext4 -L ROOT -v ${lodev}p2
393
394or utilize the device described in test/py/make_test_disk.py::
395
396   #!/usr/bin/python
397   import make_test_disk
398   make_test_disk.makeDisk()
399
400Writing Sandbox Drivers
401-----------------------
402
403Generally you should put your driver in a file containing the word 'sandbox'
404and put it in the same directory as other drivers of its type. You can then
405implement the same hooks as the other drivers.
406
407To access U-Boot's emulated memory, use map_sysmem() as mentioned above.
408
409If your driver needs to store configuration or state (such as SPI flash
410contents or emulated chip registers), you can use the device tree as
411described above. Define handlers for this with the SANDBOX_STATE_IO macro.
412See arch/sandbox/include/asm/state.h for documentation. In short you provide
413a node name, compatible string and functions to read and write the state.
414Since writing the state can expand the device tree, you may need to use
415state_setprop() which does this automatically and avoids running out of
416space. See existing code for examples.
417
418
419Debugging the init sequence
420---------------------------
421
422If you get a failure in the initcall sequence, like this::
423
424   initcall sequence 0000560775957c80 failed at call 0000000000048134 (err=-96)
425
426Then you use can use grep to see which init call failed, e.g.::
427
428   $ grep 0000000000048134 u-boot.map
429   stdio_add_devices
430
431Of course another option is to run it with a debugger such as gdb::
432
433   $ gdb u-boot
434   ...
435   (gdb) br initcall.h:41
436   Breakpoint 1 at 0x4db9d: initcall.h:41. (2 locations)
437
438Note that two locations are reported, since this function is used in both
439board_init_f() and board_init_r().
440
441.. code-block:: none
442
443   (gdb) r
444   Starting program: /tmp/b/sandbox/u-boot
445   [Thread debugging using libthread_db enabled]
446   Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".
447
448   U-Boot 2018.09-00264-ge0c2ba9814-dirty (Sep 22 2018 - 12:21:46 -0600)
449
450   DRAM:  128 MiB
451   MMC:
452
453   Breakpoint 1, initcall_run_list (init_sequence=0x5555559619e0 <init_sequence_f>)
454       at /scratch/sglass/cosarm/src/third_party/u-boot/files/include/initcall.h:41
455   41                              printf("initcall sequence %p failed at call %p (err=%d)\n",
456   (gdb) print *init_fnc_ptr
457   $1 = (const init_fnc_t) 0x55555559c114 <stdio_add_devices>
458   (gdb)
459
460
461This approach can be used on normal boards as well as sandbox.
462
463
464SDL_CONFIG
465----------
466
467If sdl-config is on a different path from the default, set the SDL_CONFIG
468environment variable to the correct pathname before building U-Boot.
469
470
471Using valgrind / memcheck
472-------------------------
473
474It is possible to run U-Boot under valgrind to check memory allocations::
475
476   valgrind u-boot
477
478If you are running sandbox SPL or TPL, then valgrind will not by default
479notice when U-Boot jumps from TPL to SPL, or from SPL to U-Boot proper. To
480fix this, use::
481
482   valgrind --trace-children=yes u-boot
483
484
485Testing
486-------
487
488U-Boot sandbox can be used to run various tests, mostly in the test/
489directory. These include:
490
491command_ut:
492  Unit tests for command parsing and handling
493compression:
494  Unit tests for U-Boot's compression algorithms, useful for
495  security checking. It supports gzip, bzip2, lzma and lzo.
496driver model:
497  Run this pytest::
498
499   ./test/py/test.py --bd sandbox --build -k ut_dm -v
500
501image:
502  Unit tests for images:
503  test/image/test-imagetools.sh - multi-file images
504  test/image/test-fit.py        - FIT images
505tracing:
506  test/trace/test-trace.sh tests the tracing system (see README.trace)
507verified boot:
508  See test/vboot/vboot_test.sh for this
509
510If you change or enhance any of the above subsystems, you shold write or
511expand a test and include it with your patch series submission. Test
512coverage in U-Boot is limited, as we need to work to improve it.
513
514Note that many of these tests are implemented as commands which you can
515run natively on your board if desired (and enabled).
516
517To run all tests use "make check".
518
519To run a single test in an existing sandbox build, you can use -T to use the
520test device tree, and -c to select the test:
521
522  /tmp/b/sandbox/u-boot -T -c "ut dm pci_busdev"
523
524This runs dm_test_pci_busdev() which is in test/dm/pci.c
525
526
527Memory Map
528----------
529
530Sandbox has its own emulated memory starting at 0. Here are some of the things
531that are mapped into that memory:
532
533=======   ========================   ===============================
534Addr      Config                     Usage
535=======   ========================   ===============================
536      0   CONFIG_SYS_FDT_LOAD_ADDR   Device tree
537   e000   CONFIG_BLOBLIST_ADDR       Blob list
538  10000   CONFIG_MALLOC_F_ADDR       Early memory allocation
539  f0000   CONFIG_PRE_CON_BUF_ADDR    Pre-console buffer
540 100000   CONFIG_TRACE_EARLY_ADDR    Early trace buffer (if enabled)
541=======   ========================   ===============================
542