test_dfu.py 11 KB

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