test_dfu.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. # Copyright (c) 2016, NVIDIA CORPORATION. All rights reserved.
  2. #
  3. # SPDX-License-Identifier: GPL-2.0
  4. # Test U-Boot's "dfu" command. The test starts DFU in U-Boot, waits for USB
  5. # device enumeration on the host, executes dfu-util multiple times to test
  6. # various transfer sizes, many of which trigger USB driver edge cases, and
  7. # finally aborts the "dfu" command in U-Boot.
  8. import os
  9. import os.path
  10. import pytest
  11. import u_boot_utils
  12. """
  13. Note: This test relies on:
  14. a) boardenv_* to contain configuration values to define which USB ports are
  15. available for testing. Without this, this test will be automatically skipped.
  16. For example:
  17. env__usb_dev_ports = (
  18. {
  19. "fixture_id": "micro_b",
  20. "tgt_usb_ctlr": "0",
  21. "host_usb_dev_node": "/dev/usbdev-p2371-2180",
  22. # This parameter is optional /if/ you only have a single board
  23. # attached to your host at a time.
  24. "host_usb_port_path": "3-13",
  25. },
  26. )
  27. # Optional entries (required only when "alt_id_test_file" and
  28. # "alt_id_dummy_file" are specified).
  29. test_file_name = "/dfu_test.bin"
  30. dummy_file_name = "/dfu_dummy.bin"
  31. # Above files are used to generate proper "alt_info" entry
  32. "alt_info": "/%s ext4 0 2;/%s ext4 0 2" % (test_file_name, dummy_file_name),
  33. env__dfu_configs = (
  34. # eMMC, partition 1
  35. {
  36. "fixture_id": "emmc",
  37. "alt_info": "/dfu_test.bin ext4 0 1;/dfu_dummy.bin ext4 0 1",
  38. "cmd_params": "mmc 0",
  39. # This value is optional.
  40. # If present, it specified the set of transfer sizes tested.
  41. # If missing, a default list of sizes will be used, which covers
  42. # various useful corner cases.
  43. # Manually specifying test sizes is useful if you wish to test 4 DFU
  44. # configurations, but don't want to test every single transfer size
  45. # on each, to avoid bloating the overall time taken by testing.
  46. "test_sizes": (63, 64, 65),
  47. # This value is optional.
  48. # The name of the environment variable that the the dfu command reads
  49. # alt info from. If unspecified, this defaults to dfu_alt_info, which is
  50. # valid for most systems. Some systems use a different variable name.
  51. # One example is the Odroid XU3, which automatically generates
  52. # $dfu_alt_info, each time the dfu command is run, by concatenating
  53. # $dfu_alt_boot and $dfu_alt_system.
  54. "alt_info_env_name": "dfu_alt_system",
  55. # This value is optional.
  56. # For boards which require the "test file" alt setting number other than
  57. # default (0) it is possible to specify exact file name to be used as
  58. # this parameter.
  59. "alt_id_test_file": test_file_name,
  60. # This value is optional.
  61. # For boards which require the "dummy file" alt setting number other
  62. # than default (1) it is possible to specify exact file name to be used
  63. # as this parameter.
  64. "alt_id_dummy_file": dummy_file_name,
  65. },
  66. )
  67. b) udev rules to set permissions on devices nodes, so that sudo is not
  68. required. For example:
  69. ACTION=="add", SUBSYSTEM=="block", SUBSYSTEMS=="usb", KERNELS=="3-13", MODE:="666"
  70. (You may wish to change the group ID instead of setting the permissions wide
  71. open. All that matters is that the user ID running the test can access the
  72. device.)
  73. c) An optional udev rule to give you a persistent value to use in
  74. host_usb_dev_node. For example:
  75. IMPORT{builtin}="path_id"
  76. ENV{ID_PATH}=="?*", ENV{.ID_PORT}=="", SYMLINK+="bus/usb/by-path/$env{ID_PATH}"
  77. ENV{ID_PATH}=="?*", ENV{.ID_PORT}=="?*", SYMLINK+="bus/usb/by-path/$env{ID_PATH}-port$env{.ID_PORT}"
  78. """
  79. # The set of file sizes to test. These values trigger various edge-cases such
  80. # as one less than, equal to, and one greater than typical USB max packet
  81. # sizes, and similar boundary conditions.
  82. test_sizes_default = (
  83. 64 - 1,
  84. 64,
  85. 64 + 1,
  86. 128 - 1,
  87. 128,
  88. 128 + 1,
  89. 960 - 1,
  90. 960,
  91. 960 + 1,
  92. 4096 - 1,
  93. 4096,
  94. 4096 + 1,
  95. 1024 * 1024 - 1,
  96. 1024 * 1024,
  97. 8 * 1024 * 1024,
  98. )
  99. first_usb_dev_port = None
  100. @pytest.mark.buildconfigspec('cmd_dfu')
  101. @pytest.mark.requiredtool('dfu-util')
  102. def test_dfu(u_boot_console, env__usb_dev_port, env__dfu_config):
  103. """Test the "dfu" command; the host system must be able to enumerate a USB
  104. device when "dfu" is running, various DFU transfers are tested, and the
  105. USB device must disappear when "dfu" is aborted.
  106. Args:
  107. u_boot_console: A U-Boot console connection.
  108. env__usb_dev_port: The single USB device-mode port specification on
  109. which to run the test. See the file-level comment above for
  110. details of the format.
  111. env__dfu_config: The single DFU (memory region) configuration on which
  112. to run the test. See the file-level comment above for details
  113. of the format.
  114. Returns:
  115. Nothing.
  116. """
  117. def start_dfu():
  118. """Start U-Boot's dfu shell command.
  119. This also waits for the host-side USB enumeration process to complete.
  120. Args:
  121. None.
  122. Returns:
  123. Nothing.
  124. """
  125. u_boot_utils.wait_until_file_open_fails(
  126. env__usb_dev_port['host_usb_dev_node'], True)
  127. fh = u_boot_utils.attempt_to_open_file(
  128. env__usb_dev_port['host_usb_dev_node'])
  129. if fh:
  130. fh.close()
  131. raise Exception('USB device present before dfu command invoked')
  132. u_boot_console.log.action(
  133. 'Starting long-running U-Boot dfu shell command')
  134. dfu_alt_info_env = env__dfu_config.get('alt_info_env_name', \
  135. 'dfu_alt_info')
  136. cmd = 'setenv "%s" "%s"' % (dfu_alt_info_env,
  137. env__dfu_config['alt_info'])
  138. u_boot_console.run_command(cmd)
  139. cmd = 'dfu 0 ' + env__dfu_config['cmd_params']
  140. u_boot_console.run_command(cmd, wait_for_prompt=False)
  141. u_boot_console.log.action('Waiting for DFU USB device to appear')
  142. fh = u_boot_utils.wait_until_open_succeeds(
  143. env__usb_dev_port['host_usb_dev_node'])
  144. fh.close()
  145. def stop_dfu(ignore_errors):
  146. """Stop U-Boot's dfu shell command from executing.
  147. This also waits for the host-side USB de-enumeration process to
  148. complete.
  149. Args:
  150. ignore_errors: Ignore any errors. This is useful if an error has
  151. already been detected, and the code is performing best-effort
  152. cleanup. In this case, we do not want to mask the original
  153. error by "honoring" any new errors.
  154. Returns:
  155. Nothing.
  156. """
  157. try:
  158. u_boot_console.log.action(
  159. 'Stopping long-running U-Boot dfu shell command')
  160. u_boot_console.ctrlc()
  161. u_boot_console.log.action(
  162. 'Waiting for DFU USB device to disappear')
  163. u_boot_utils.wait_until_file_open_fails(
  164. env__usb_dev_port['host_usb_dev_node'], ignore_errors)
  165. except:
  166. if not ignore_errors:
  167. raise
  168. def run_dfu_util(alt_setting, fn, up_dn_load_arg):
  169. """Invoke dfu-util on the host.
  170. Args:
  171. alt_setting: The DFU "alternate setting" identifier to interact
  172. with.
  173. fn: The host-side file name to transfer.
  174. up_dn_load_arg: '-U' or '-D' depending on whether a DFU upload or
  175. download operation should be performed.
  176. Returns:
  177. Nothing.
  178. """
  179. cmd = ['dfu-util', '-a', alt_setting, up_dn_load_arg, fn]
  180. if 'host_usb_port_path' in env__usb_dev_port:
  181. cmd += ['-p', env__usb_dev_port['host_usb_port_path']]
  182. u_boot_utils.run_and_log(u_boot_console, cmd)
  183. u_boot_console.wait_for('Ctrl+C to exit ...')
  184. def dfu_write(alt_setting, fn):
  185. """Write a file to the target board using DFU.
  186. Args:
  187. alt_setting: The DFU "alternate setting" identifier to interact
  188. with.
  189. fn: The host-side file name to transfer.
  190. Returns:
  191. Nothing.
  192. """
  193. run_dfu_util(alt_setting, fn, '-D')
  194. def dfu_read(alt_setting, fn):
  195. """Read a file from the target board using DFU.
  196. Args:
  197. alt_setting: The DFU "alternate setting" identifier to interact
  198. with.
  199. fn: The host-side file name to transfer.
  200. Returns:
  201. Nothing.
  202. """
  203. # dfu-util fails reads/uploads if the host file already exists
  204. if os.path.exists(fn):
  205. os.remove(fn)
  206. run_dfu_util(alt_setting, fn, '-U')
  207. def dfu_write_read_check(size):
  208. """Test DFU transfers of a specific size of data
  209. This function first writes data to the board then reads it back and
  210. compares the written and read back data. Measures are taken to avoid
  211. certain types of false positives.
  212. Args:
  213. size: The data size to test.
  214. Returns:
  215. Nothing.
  216. """
  217. test_f = u_boot_utils.PersistentRandomFile(u_boot_console,
  218. 'dfu_%d.bin' % size, size)
  219. readback_fn = u_boot_console.config.result_dir + '/dfu_readback.bin'
  220. u_boot_console.log.action('Writing test data to DFU primary ' +
  221. 'altsetting')
  222. dfu_write(alt_setting_test_file, test_f.abs_fn)
  223. u_boot_console.log.action('Writing dummy data to DFU secondary ' +
  224. 'altsetting to clear DFU buffers')
  225. dfu_write(alt_setting_dummy_file, dummy_f.abs_fn)
  226. u_boot_console.log.action('Reading DFU primary altsetting for ' +
  227. 'comparison')
  228. dfu_read(alt_setting_test_file, readback_fn)
  229. u_boot_console.log.action('Comparing written and read data')
  230. written_hash = test_f.content_hash
  231. read_back_hash = u_boot_utils.md5sum_file(readback_fn, size)
  232. assert(written_hash == read_back_hash)
  233. # This test may be executed against multiple USB ports. The test takes a
  234. # long time, so we don't want to do the whole thing each time. Instead,
  235. # execute the full test on the first USB port, and perform a very limited
  236. # test on other ports. In the limited case, we solely validate that the
  237. # host PC can enumerate the U-Boot USB device.
  238. global first_usb_dev_port
  239. if not first_usb_dev_port:
  240. first_usb_dev_port = env__usb_dev_port
  241. if env__usb_dev_port == first_usb_dev_port:
  242. sizes = env__dfu_config.get('test_sizes', test_sizes_default)
  243. else:
  244. sizes = []
  245. dummy_f = u_boot_utils.PersistentRandomFile(u_boot_console,
  246. 'dfu_dummy.bin', 1024)
  247. alt_setting_test_file = env__dfu_config.get('alt_id_test_file', '0')
  248. alt_setting_dummy_file = env__dfu_config.get('alt_id_dummy_file', '1')
  249. ignore_cleanup_errors = True
  250. try:
  251. start_dfu()
  252. u_boot_console.log.action(
  253. 'Overwriting DFU primary altsetting with dummy data')
  254. dfu_write(alt_setting_test_file, dummy_f.abs_fn)
  255. for size in sizes:
  256. with u_boot_console.log.section('Data size %d' % size):
  257. dfu_write_read_check(size)
  258. # Make the status of each sub-test obvious. If the test didn't
  259. # pass, an exception was thrown so this code isn't executed.
  260. u_boot_console.log.status_pass('OK')
  261. ignore_cleanup_errors = False
  262. finally:
  263. stop_dfu(ignore_cleanup_errors)