Software APIs
usbdev_suspend.c
1 // Copyright lowRISC contributors (OpenTitan project).
2 // Licensed under the Apache License, Version 2.0, see LICENSE for details.
3 // SPDX-License-Identifier: Apache-2.0
4 
5 // USB suspend/resume test
6 //
7 // Basic test of suspend/resume signaling and disconnect/reconnect behavior.
8 // The DPI model sets up the device and reads the test descriptor. Having
9 // ascertained the specific testing behavior that is required, it proceeds to
10 // run through the appropriate states, time delays and bus activity as
11 // illustrated below.
12 //
13 //-----------------------------------------------------------------------------
14 // Test state flow
15 //-----------------------------------------------------------------------------
16 //
17 // [PhaseSuspend]
18 //
19 // Power On Reset -> Configuration -> DPI drops SOF -> Suspend -> Resume ->
20 // -> DPI performs Bus Reset ...
21 //
22 // Three 'Normal Sleep' phases may be started from Power On Reset (to aid dev),
23 // or a Bus Reset if a Bus Reset or Disconnect was the most recent wake
24 // stimulus. If the wake stimulus was Resume Signaling, then configuration does
25 // not occur again and we arrive via NextPhase
26 //
27 // [PhaseSleepResume]
28 // [PhaseSleepReset]
29 // [PhaseSleepDisconnect]
30 //
31 // ... Bus Reset ->
32 // Power On Reset -> Configuration ->
33 // [from prev phase] ... -> DPI drops SOF -> Suspend -> Activate AON
34 // -> Normal Sleep -> DPI produces wake stimulus -> Wakeup
35 // -> Deactivate AON ... [to next]
36 //
37 // [PhaseDeepResume]
38 // [PhaseDeepReset]
39 // [PhaseDeepDisconnect]
40 //
41 // ... Bus Reset ->
42 // Power On Reset -> Configuration ->
43 // [from prev phase] ... -> DPI drops SOF -> Suspend -> Activate AON
44 // -> Deep Sleep -> DPI produces wake stimulus -> Wakeup
45 // -> Deactivate AON .. [to next]
46 //
47 // [PhaseShutdown] Test Complete
48 //
49 //-----------------------------------------------------------------------------
50 
51 //-----------------------------------------------------------------------------
52 // Summary notes from USB 2.0 Specification to aid apprehension (see the spec.
53 // itself for details):
54 //
55 // Device starts transitioning to the Suspend state after observing a constant
56 // Idle state on bus for more than 3.0ms, and must be in Suspend state after no
57 // more than 10ms of bus inactivity. Pull-up resistor must remain asserted.
58 //
59 // Resuming from Suspend state is achieved by the host at any time by any non-
60 // signaling, for at leasat 20ms. This is followed by a standard, low-speed EOP
61 // (two low-speed bit times of SE0 followed by a J). Traffic, even if only SOF,
62 // must be resumed within 3ms after entering the Idle state (J), to prevent
63 // the device re-entering Suspend.
64 // Additionally, the host must provide a 10ms resume recovery time during which
65 // it will not attempt to access the device.
66 //
67 // Suspending/Resuming may occur from any Device State (Powered, Default,
68 // Address or Configured), and the device returns to its pre-Suspend state.
69 //-----------------------------------------------------------------------------
70 
71 #include "sw/device/tests/usbdev_suspend.h"
72 
73 #include <stdint.h>
74 #include <string.h>
75 
81 #include "sw/device/lib/runtime/irq.h"
84 #include "sw/device/lib/testing/pinmux_testutils.h"
85 #include "sw/device/lib/testing/pwrmgr_testutils.h"
86 #include "sw/device/lib/testing/rstmgr_testutils.h"
87 #include "sw/device/lib/testing/rv_plic_testutils.h"
88 #include "sw/device/lib/testing/sram_ctrl_testutils.h"
89 #include "sw/device/lib/testing/test_framework/check.h"
91 #include "sw/device/lib/testing/usb_testutils.h"
92 #include "sw/device/lib/testing/usb_testutils_controlep.h"
93 #include "sw/device/lib/testing/usb_testutils_streams.h"
94 #include "sw/device/silicon_creator/lib/drivers/retention_sram.h"
95 
96 #define MODULE_ID MAKE_MODULE_ID('u', 'd', 'u')
97 
98 // Set up the recording of function points for this module
99 #define USBUTILS_FUNCPT_FILE USBUTILS_FUNCPT_FILE_USBDEV_SUSP_TEST
100 
101 // Are we using purely Isochronous streams for testing?
102 #define USE_ISO_STREAMS 0
103 // Are we using purely Bulk streams for testing?
104 #define USE_BULK_STREAMS 1
105 // Otherwise, we'll use a mixture
106 
107 // The number of streams to be employed if testing with traffic
108 #if USB_ISO_STREAMS
109 #define NUM_STREAMS 4U
110 #else
111 #define NUM_STREAMS USBUTILS_STREAMS_MAX
112 #endif
113 
114 // Are we expecting a full frame interval?
115 // Note: this must match the setting in the DPI model, but we do not have the
116 // ability to share header files.
117 #ifndef USBDPI_FULL_FRAME
118 // By default we shorten the test duration.
119 #define USBDPI_FULL_FRAME 0
120 #endif
121 
122 // TODO: these are now set appropriately for automated testing on FPGA/ES.
123 // We need three sets of parameters:
124 // - chip simulation
125 // - FPGA/Silicon with automated host code
126 // - FPGA/Silicon with manual test stimulus
127 
128 /**
129  * Timeout constants in microseconds;
130  */
131 enum {
132  TimeoutResumeMissed = 40U * 1000U,
133  TimeoutResetMissed = 60U * 1000U,
134  TimeoutWakeupResume = 30000u,
135  TimeoutFinishMissed = 2000u,
136  TimeoutAonResponse = 5000u,
137  TimeoutSleepFailed = 5000u,
138 
139  // How long should we wait for configuration to occur if observing physical
140  // timings? (Real USB host or physically-accurate timings in simulation.)
141  TimeoutPhysConfig = 10U * 1000U * 1000U,
142 
143  /**
144  * Durations that are specified in terms of bus frames, however long those
145  * simulated bus frames happen to be (ie. these intervals are determined by
146  * the DPI host behavior rather than the USB protocol specification)
147  */
148  FramesConfigDelay = 2000u,
149  FramesSuspendMissed = 2000u,
150  FramesInitiateResume = 2u,
151 
152  /**
153  * Number of frame delays to wait after device signals Suspend, before we
154  * initiate sleeping.
155  */
156  FramesWaitEnterSleep = 10u,
157 };
158 
159 /**
160  * Maximum size of the client state stored within the Retention SRAM;
161  * we leave the usb_testutils_streams/other code to specify and manage its own
162  * state.
163  */
164 #define MAX_CLIENT_STATE 0x400U
165 
166 /**
167  * Test states
168  */
169 typedef enum {
170  /**
171  * Power On Reset (start of first phase of test sequence).
172  */
173  kSuspendStatePowerOnReset = 0u,
174  /**
175  * Bus Reset from DPI/Host has occurred.
176  */
177  kSuspendStateBusReset,
178  /**
179  * Waiting for the DPI/Host to suspend the device, for normal Suspend/Resume
180  * behavior, not involving AON/Wakeup functionality.
181  */
182  kSuspendStateWaitSuspend,
183  /**
184  * Waiting for the DPI/Host to suspend the device, expecting a longer suspend
185  * period, during which we put the device into Normal/Deep Sleep using the
186  * AON/Wakeup functionality.
187  */
188  kSuspendStateWaitLongSuspend,
189  /**
190  * Waiting for the DPI/Host to initiate a Resume from Suspended.
191  */
192  kSuspendStateWaitResume,
193  /**
194  * Waiting for the DPI/Host to provide the Bus Reset stimulus.
195  */
196  kSuspendStateWaitBusReset,
197  /**
198  * Waiting whilst Suspended, until we decide to enter Normal/Deep Sleep.
199  * The DPI/Host is not expected to resume communication during this time.
200  */
201  kSuspendStateWaitSuspendTimeout,
202  /**
203  * We have instructed the AON/Wakeup module to wake over control of the USB
204  * signals. It does not do so immediately because it lives in a slower clock
205  * domain, but the delay should be very short.
206  */
207  kSuspendStateActivatedAON,
208  /**
209  * We are expecting to fall into a Normal Sleep.
210  */
211  kSuspendStateNormalSleep,
212  /**
213  * We are expecting to fall into a Deep Sleep.
214  */
215  kSuspendStateDeepSleep,
216  /**
217  * We have just returned from a Normal Sleep.
218  */
219  kSuspendStateNormalWaking,
220  /**
221  * We have just returned from a Deep Sleep.
222  */
223  kSuspendStateDeepWaking,
224  /**
225  * We've instructed the AON/Wakeup module to relinquish its control of the
226  * USB and deactivate.
227  */
228  kSuspendStateAONWakeup,
229  /**
230  * TODO: Resume Signaling still needs completing...
231  */
232  kSuspendStateWaitResumeTimeout,
233  /**
234  * Waiting for the DPI/Host to decide that the test phase is complete.
235  */
236  kSuspendStateWaitFinish,
237  /**
238  * Transition to next test phase, with the device still connected and
239  * operational, ie. Resume Signaling has occurred.
240  */
241  kSuspendStateNextPhase,
242  /**
243  * Disconnecting from the bus.
244  */
245  kSuspendStateWaitDisconnect,
246  /**
247  * Test completed successfully.
248  */
249  kSuspendStateComplete,
250  /**
251  * Test failed.
252  */
253  kSuspendStateFailed,
254 } usbdev_suspend_state_t;
255 
256 /**
257  * Retained state; to be held in the Retention SRAM during Deep Sleep
258  */
259 typedef struct {
260  /**
261  * Host-suppplied device address on the USB.
262  */
263  uint8_t dev_address;
264  /**
265  * Selected device configuration number.
266  */
267  uint8_t dev_config;
268  /**
269  * Test phase.
270  */
271  uint8_t test_phase;
272  /**
273  * Unused padding.
274  */
275  uint8_t pad0;
276  /**
277  * Number of remaining test iterations.
278  */
279  uint32_t num_iters;
280  /**
281  * Data Toggle bits.
282  */
283  uint32_t data_toggles;
284  /**
285  * Used bytes of client state.
286  */
287  uint32_t client_used;
288  /**
289  * Client state; allow, for example, the usb_testutils_streams code to specify
290  * its own per-stream retention state rather than constraining it here.
291  */
292  alignas(uint32_t) uint8_t client_state[MAX_CLIENT_STATE];
294 
295 /**
296  * Test context
297  */
298 typedef struct usbdev_suspend_ctx {
299  /**
300  * Access to usb_testutils context
301  */
303  /**
304  * Current test state
305  */
306  usbdev_suspend_state_t test_state;
307  /**
308  * Current test phase
309  */
310  usbdev_suspend_phase_t test_phase;
311  /**
312  * Initial test phase (inclusive)
313  */
314  usbdev_suspend_phase_t init_phase;
315  /**
316  * Final test phase (inclusive)
317  */
318  usbdev_suspend_phase_t fin_phase;
319  /**
320  * Number of iterations remaining (including the present iteration).
321  */
322  uint32_t num_iters;
323  /**
324  * Streaming traffic throughout test?
325  */
327  /**
328  * Timeout catching any failure of test to advance as expected
329  */
331  /**
332  * Most recent status of wakeup monitor
333  */
335  /**
336  * Test descriptor for current test phase
337  */
338  uint8_t test_dscr[USB_TESTUTILS_TEST_DSCR_LEN];
339  /**
340  * Our retained state; transferred to and from Retention SRAM over Sleep
341  */
344 
345 enum {
346  /**
347  * Retention SRAM start address
348  */
350  /**
351  * Retention SRAM address at which we may store some state.
352  */
353  kRetSramOwnerAddr = kRetSramBaseAddr + offsetof(retention_sram_t, owner),
354 };
355 
356 // Total length of the configuration descriptor.
357 #define CFG_DSCR_TOTAL_LEN \
358  (USB_CFG_DSCR_LEN + \
359  NUM_STREAMS * (USB_INTERFACE_DSCR_LEN + 2 * USB_EP_DSCR_LEN))
360 
361 // This Configuration Descriptor must be capable of describing the maximal
362 // number of interfaces (= number of streams). It is overwritten dynamically
363 // when streaming with traffic.
364 static uint8_t config_descriptors[CFG_DSCR_TOTAL_LEN] = {
365  // Default configuration, for use if we're not testing with traffic too;
366  // we still need configuration for the host to recognize and configure us.
367  USB_CFG_DSCR_HEAD(
368  USB_CFG_DSCR_LEN + 2 * (USB_INTERFACE_DSCR_LEN + 2 * USB_EP_DSCR_LEN),
369  2),
370  VEND_INTERFACE_DSCR(0, 2, 0x50, 1),
371  USB_BULK_EP_DSCR(0, 1, 32, 0),
372  USB_BULK_EP_DSCR(1, 1, 32, 4),
373  VEND_INTERFACE_DSCR(1, 2, 0x50, 1),
374  USB_BULK_EP_DSCR(0, 2, 32, 0),
375  USB_BULK_EP_DSCR(1, 2, 32, 4),
376 };
377 
378 /**
379  * USB Bus Frame duration, in microseconds; may be reduced when communicating
380  * with the USBDPI module to reduce the simulation time.
381  */
382 static uint32_t frame_interval = 1000u;
383 
384 /**
385  * USB device context types.
386  */
387 static usb_testutils_ctx_t usbdev;
388 static usb_testutils_controlep_ctx_t usbdev_control;
389 static usb_testutils_streams_ctx_t usbdev_streams;
390 
391 static const dt_pinmux_t kPinmuxDt = 0;
392 static_assert(kDtPinmuxCount == 1, "this library expects exactly one pinmux");
393 static const dt_pwrmgr_t kPwrmgrDt = 0;
394 static_assert(kDtPwrmgrCount == 1, "this library expects exactly one pwrmgr");
395 static const dt_rstmgr_t kRstmgrDt = 0;
396 static_assert(kDtRstmgrCount == 1, "this library expects exactly one rstmgr");
397 static const dt_rv_plic_t kRvPlicDt = 0;
398 static_assert(kDtRvPlicCount == 1, "this library expects exactly one rv_plic");
399 
400 enum {
401  kPlicTarget = 0,
402 };
403 
404 /**
405  * Pinmux handle
406  */
407 static dif_pinmux_t pinmux;
408 /**
409  * Rstmgr handle
410  */
411 static dif_rstmgr_t rstmgr;
412 /**
413  * Pwrmgr handle
414  */
415 static dif_pwrmgr_t pwrmgr;
416 /**
417  * Interrupt controller handle
418  */
419 static dif_rv_plic_t rv_plic;
420 /**
421  * Wakeup sources for USB.
422  */
423 static dif_pwrmgr_request_sources_t wakeup_sources;
424 /**
425  * Do we expect this host to put the device into suspend?
426  */
427 static bool host_suspends = true;
428 /**
429  * Do we expect this host to perform Resume Signaling and awaken the device from
430  * a Suspended state?
431  */
432 static bool host_resumes = true;
433 /**
434  * Do we expect this host to perform Bus Resets to awaken the device from sleep?
435  */
436 static bool host_resets = true;
437 /**
438  * Do we expect this host to Disconnect the device to awaken it from sleep?
439  */
440 static bool host_disconnects = true;
441 /**
442  * Verbose logging? Mostly useful on FPGA; be warned that it can affect
443  * timing in simulation, and in particular will likely break Verilator sims.
444  *
445  * It can also cause timeouts on the host side with automated regression
446  * tests on FPGA/Silicon because the CPU is stalled waiting for UART FIFO
447  * space.
448  *
449  * TODO: perhaps we want a uart_flush() at carefully selected moments, eg.
450  * when setting a timeout?
451  */
452 static bool verbose = true;
453 /**
454  * Verbose logging from the streaming code?
455  *
456  * Note: this makes the test a lot slower because the CPU is stalled awaiting
457  * UART FIFO space.
458  */
459 static bool s_verbose = false;
460 
461 // Configuration for streaming layer. This specifies the transfer type of each
462 // of the streams being used and checked if we're testing with traffic enabled.
463 static const unsigned nstreams = NUM_STREAMS;
464 #if USE_ISO_STREAMS
465 static const usb_testutils_transfer_type_t xfr_types[] = {
466  kUsbTransferTypeIsochronous, kUsbTransferTypeIsochronous,
467  kUsbTransferTypeIsochronous, kUsbTransferTypeIsochronous,
468  kUsbTransferTypeIsochronous, kUsbTransferTypeIsochronous,
469  kUsbTransferTypeIsochronous, kUsbTransferTypeIsochronous,
470  kUsbTransferTypeIsochronous, kUsbTransferTypeIsochronous,
471  kUsbTransferTypeIsochronous};
472 #elif USE_BULK_STREAMS
473 static const usb_testutils_transfer_type_t xfr_types[] = {
474  kUsbTransferTypeBulk, kUsbTransferTypeBulk, kUsbTransferTypeBulk,
475  kUsbTransferTypeBulk, kUsbTransferTypeBulk, kUsbTransferTypeBulk,
476  kUsbTransferTypeBulk, kUsbTransferTypeBulk, kUsbTransferTypeBulk,
477  kUsbTransferTypeBulk, kUsbTransferTypeBulk};
478 #else
479 static const usb_testutils_transfer_type_t xfr_types[] = {
480  kUsbTransferTypeIsochronous, kUsbTransferTypeInterrupt,
481  kUsbTransferTypeBulk, kUsbTransferTypeBulk,
482 
483  kUsbTransferTypeIsochronous, kUsbTransferTypeInterrupt,
484  kUsbTransferTypeBulk, kUsbTransferTypeIsochronous,
485 
486  kUsbTransferTypeInterrupt, kUsbTransferTypeBulk,
487  kUsbTransferTypeBulk,
488 };
489 #endif
490 
491 // Full traffic and checking
492 static const usbdev_stream_flags_t test_flags =
493  kUsbdevStreamFlagRetrieve | kUsbdevStreamFlagCheck |
494  kUsbdevStreamFlagRetry | kUsbdevStreamFlagSend;
495 // We don't expect it to complete; data transfer is exercised and checked in
496 // other tests.
497 static const uint32_t transfer_bytes = 0x80 << 20;
498 
499 /**
500  * Context information for suspend/resume test
501  */
502 static usbdev_suspend_ctx_t suspend_ctx;
503 
504 /**
505  * Report progress; these messages are obligatory for automated testing in order
506  * that the host-side test harness may synchronize with this device-side code.
507  */
508 // Implement as a varargs function if it becomes more complicated.
509 // static inline void report_progress(const char *msg);
510 #define report_progress(...) LOG_INFO(__VA_ARGS__)
511 
512 /**
513  * Are we observing physically-accurate timings?
514  */
515 static inline bool physical_timings(void) {
516  switch (kDeviceType) {
517  case kDeviceFpgaCw310:
518  case kDeviceFpgaCw340:
519  case kDeviceSilicon:
520  break;
521  default:
522  return false;
523  }
524  return true;
525 }
526 
527 // Return a timeout in microseconds, scaled for the test target; longer timeout
528 // periods are more appropriate for FPGA tests and decidedly undesirable for
529 // Verilator top-level simulations
530 static uint32_t time_frames(unsigned n) {
531  uint32_t scale = 1u;
532  if (physical_timings()) {
533  // scale = 500u;
534  }
535  return scale * n * frame_interval;
536 }
537 
538 // Return the name of a test phase
539 static const char *phase_name(usbdev_suspend_phase_t phase) {
540  switch (phase) {
541  case kSuspendPhaseSuspend:
542  return "Suspend";
543  case kSuspendPhaseSleepResume:
544  return "SleepResume";
545  case kSuspendPhaseSleepReset:
546  return "SleepReset";
547  case kSuspendPhaseSleepDisconnect:
548  return "SleepDisconnect";
549  case kSuspendPhaseDeepResume:
550  return "DeepResume";
551  case kSuspendPhaseDeepReset:
552  return "DeepReset";
553  case kSuspendPhaseDeepDisconnect:
554  return "DeepDisconnect";
555  case kSuspendPhaseShutdown:
556  return "Shutdown";
557  default:
558  return "<Unknown>";
559  }
560 }
561 
562 // Return the name of a test state
563 static const char *state_name(usbdev_suspend_state_t state) {
564  switch (state) {
565  case kSuspendStatePowerOnReset:
566  return "PowerOnReset";
567  case kSuspendStateBusReset:
568  return "BusReset";
569  case kSuspendStateWaitSuspend:
570  return "WaitSuspend";
571  case kSuspendStateWaitResume:
572  return "WaitResume";
573  case kSuspendStateWaitBusReset:
574  return "WaitBusReset";
575  case kSuspendStateWaitLongSuspend:
576  return "WaitLongSuspend";
577  case kSuspendStateWaitSuspendTimeout:
578  return "WaitSuspendTimeout";
579  case kSuspendStateActivatedAON:
580  return "ActivatedAON";
581  case kSuspendStateNormalSleep:
582  return "NormalSleep";
583  case kSuspendStateDeepSleep:
584  return "DeepSleep";
585  case kSuspendStateNormalWaking:
586  return "NormalWaking";
587  case kSuspendStateDeepWaking:
588  return "DeepWaking";
589  case kSuspendStateAONWakeup:
590  return "AONWakeup";
591  case kSuspendStateWaitResumeTimeout:
592  return "WaitResumeTimeout";
593  case kSuspendStateWaitDisconnect:
594  return "WaitDisconnect";
595  case kSuspendStateWaitFinish:
596  return "WaitFinish";
597  case kSuspendStateNextPhase:
598  return "NextPhase";
599  case kSuspendStateComplete:
600  return "Complete";
601  case kSuspendStateFailed:
602  return "Failed";
603  default:
604  return "<Unknown>";
605  }
606 }
607 
608 // Report any link event(s)
609 static void events_report(usbdev_suspend_ctx_t *ctx, uint32_t snapshot,
610  dif_usbdev_link_state_t link_state) {
611  // Report connection/reset events
612  if (snapshot & (1u << kDifUsbdevIrqPowered)) {
613  LOG_INFO("VBUS Connected");
614  }
615  if (snapshot & (1u << kDifUsbdevIrqDisconnected)) {
616  LOG_INFO("VBUS Disconnected");
617  }
618  if (snapshot & (1u << kDifUsbdevIrqLinkReset)) {
619  LOG_INFO("Link reset");
620  }
621  if (snapshot & (1u << kDifUsbdevIrqHostLost)) {
622  LOG_INFO("Host lost");
623  }
624 
625  // Report suspend/resume status changes
626  if (snapshot &
627  ((1u << kDifUsbdevIrqLinkSuspend) | (1u << kDifUsbdevIrqLinkResume))) {
628  switch (link_state) {
629  case kDifUsbdevLinkStatePoweredSuspended:
630  case kDifUsbdevLinkStateSuspended:
631  LOG_INFO("Suspended");
632  break;
633 
634  case kDifUsbdevLinkStateResuming:
635  LOG_INFO("Resuming");
636  break;
637 
638  case kDifUsbdevLinkStateActiveNoSof:
639  LOG_INFO("Resuming no SOF");
640  break;
641 
642  case kDifUsbdevLinkStateActive:
643  LOG_INFO("Resumed");
644  break;
645 
646  default:
647  break;
648  }
649  }
650 }
651 
652 // Transition to a (new) test state
653 static inline void state_enter(usbdev_suspend_ctx_t *ctx,
654  usbdev_suspend_state_t state) {
655  if (verbose) {
656  LOG_INFO("entering state %s", state_name(state));
657  }
658  ctx->test_state = state;
659 }
660 
661 // Set a time out for the current test state, in microseconds
662 static inline void timeout_set(usbdev_suspend_ctx_t *ctx,
663  uint32_t interval_us) {
664  if (verbose) {
665  LOG_INFO("timeout_set %uus\n", interval_us);
666  if (false) {
667  uint64_t now = ibex_mcycle_read();
668  uint64_t then = now + interval_us;
669  LOG_INFO(" setting timeout to 0x%x%x (at 0x%x%x)",
670  (uint32_t)(then >> 32), (uint32_t)then, (uint32_t)(now >> 32),
671  (uint32_t)now);
672  }
673  }
674  ctx->timeout = ibex_timeout_init(interval_us);
675 }
676 
677 // Set a time out, in frames, for the current test state
678 static void timeout_frames_set(usbdev_suspend_ctx_t *ctx,
679  uint32_t interval_frames) {
680  timeout_set(ctx, time_frames(interval_frames));
681 }
682 
683 ////////////////////////////////////////////////////////////////////////////////
684 // Report the state of the phy pins
685 ////////////////////////////////////////////////////////////////////////////////
686 void sense_report(usbdev_suspend_ctx_t *ctx, uint32_t niters) {
687  while (niters-- > 0u) {
689  CHECK_DIF_OK(dif_usbdev_get_phy_pins_status(ctx->usbdev->dev, &sense));
690 #if USBUTILS_FUNCTION_POINTS
691  uint32_t data = (sense.rx_dp ? 1U : 0) | (sense.rx_dn ? 2U : 0) |
692  (sense.rx_d ? 4U : 0) | (sense.output_enable ? 8U : 0) |
693  (sense.vbus_sense ? 0x100U : 0);
694  USBUTILS_FUNCPT(0x515, data);
695 #endif
696  LOG_INFO(
697  "sense %u : rx_dp %u rx_dn %u rx_d %u : tx_dp %u tx_dn %u tx_d %u "
698  "tx_se0 %u : oe %u",
699  sense.vbus_sense, sense.rx_dp, sense.rx_dn, sense.rx_d, sense.tx_dp,
700  sense.tx_dn, sense.tx_d, sense.tx_se0, sense.output_enable);
701  }
702 }
703 
704 /**
705  * Report the status information from the AON/Wake module.
706  */
707 void report_wake_status(usbdev_suspend_ctx_t *ctx) {
708  LOG_INFO("wake status active %u disconnected %u bus_reset %u",
710  ctx->wake_status.bus_reset);
711  LOG_INFO(" bus_not_idle %u", ctx->wake_status.bus_not_idle);
712  LOG_INFO(" (host_resumes %u host_resets %u host_disconnects %u)",
713  host_resumes, host_resets, host_disconnects);
714 }
715 
716 /**
717  * Collect and optionally report the current 'wake status' reported by the
718  * AON/Wake module. This indicates why sleep was interrupted.
719  */
720 status_t collect_wake_status(usbdev_suspend_ctx_t *ctx) {
721  TRY(dif_usbdev_get_wake_status(ctx->usbdev->dev, &ctx->wake_status));
722  if (verbose) {
723  report_wake_status(ctx);
724  }
725  return OK_STATUS();
726 }
727 
728 /**
729  * External interrupt handler.
730  */
731 bool ottf_handle_irq(uint32_t *exc_info, dt_instance_id_t devid,
732  dif_rv_plic_irq_id_t irq_id) {
733  if (devid != dt_pwrmgr_instance_id(kPwrmgrDt) ||
734  irq_id != dt_pwrmgr_irq_to_plic_id(kPwrmgrDt, kDtPwrmgrIrqWakeup)) {
735  return false;
736  }
737  CHECK_DIF_OK(dif_pwrmgr_irq_acknowledge(&pwrmgr, kDtPwrmgrIrqWakeup));
738 
739  if (false) {
740  const bool debug = false;
741  usbdev_suspend_ctx_t *ctx = &suspend_ctx;
742  if (debug) {
743  sense_report(ctx, 2);
744  LOG_INFO("Received Wakeup IRQ in sleep");
745  if (debug) {
746  // Report wake status immediately, to see what ES captured.
747  (void)collect_wake_status(ctx);
748  sense_report(ctx, 10u);
749  }
750  } else {
751  LOG_INFO("Received Wakeup IRQ in sleep");
752  }
753  }
754  return true;
755 }
756 
757 /**
758  * Simple Retention SRAM writing (from sram_ctrl_sleep_sram_ret_contents_test.c)
759  */
760 static void retention_sram_store(const usbdev_retn_state_t *state) {
761  sram_ctrl_testutils_write(kRetSramOwnerAddr, (sram_ctrl_testutils_data_t){
762  .words = (uint32_t *)state,
763  .len = sizeof(*state) / 4});
764 }
765 
766 /**
767  * Simple Retention SRAM reading (from sram_ctrl_sleep_sram_ret_contents_test.c)
768  */
769 static void retention_sram_load(usbdev_retn_state_t *state) {
770  memcpy(state, (uint8_t *)kRetSramOwnerAddr, sizeof(*state));
771 }
772 
773 static void phase_set(usbdev_suspend_ctx_t *ctx, usbdev_suspend_phase_t phase) {
774  if (verbose) {
775  LOG_INFO("phase_set %u (%s)", phase, phase_name(phase));
776  }
777  /**
778  * Test descriptor; indicates to the DPI model that we're interested in
779  * testing bus Suspend/Resume signaling, Reset signaling and Remote Wakeup
780  * behavior.
781  */
782  uint8_t test_descriptor[] = {
783  USB_TESTUTILS_TEST_DSCR(kUsbTestNumberSuspend,
784  (uint8_t)phase, // Test phase
785  0, 0, 0)};
786 
787  memcpy(ctx->test_dscr, test_descriptor, sizeof(ctx->test_dscr));
788 
789  // Remember the new test phase
790  ctx->test_phase = phase;
791 }
792 
793 // Callback handler for link events
794 static status_t link_callback(void *ctx_v,
795  dif_usbdev_irq_state_snapshot_t snapshot,
796  dif_usbdev_link_state_t link_state) {
798 
799  if (snapshot & (1u << kDifUsbdevIrqFrame)) {
800  if (verbose) {
801  // For FPGA testing, we deliberately extend all of the timeout periods to
802  // make the activity viewable. This is therefore just an indication of
803  // activity/progress.
804  static int hb = 0;
805  if (++hb > 1000) {
806  LOG_INFO("SOF");
807  hb = 0;
808  }
809  }
810 
811  // We are supplied with the SOF interrupts to help inform our decision
812  // but these are normally much too frequent to be reporting them
813  snapshot &= ~(1u << kDifUsbdevIrqFrame);
814  if (!snapshot) {
815  // If only a Frame interrupt has called, return without further reporting
816  return OK_STATUS();
817  }
818  }
819 
820  if (false) { // verbose && snapshot) {
821  // LOG_INFO("State %u (%s) - Link events:", ctx->test_state,
822  // state_name(ctx->test_state));
823  events_report(ctx, snapshot, link_state);
824  // LOG_INFO(" events: 0x%x link 0x%x", snapshot, link_state);
825  }
826 
827  // State machine anticipates the behavior of the host/DPI model, checking that
828  // the expected events are reported within the expected time intervals, and
829  // advances accordingly through the test states.
830 
831  switch (ctx->test_state) {
832  // We're expecting the host to drop the SOF heartbeat indicating that we
833  // should suspend... (STEP_IDLE_)
834  case kSuspendStateWaitSuspend:
835  if (snapshot & (1u << kDifUsbdevIrqLinkSuspend)) {
836  state_enter(ctx, kSuspendStateWaitResume);
837  timeout_set(ctx, TimeoutResumeMissed);
838  }
839  break;
840 
841  // After a short delay, the host should resume automatically...
842  // (STEP_ACTIVE_)
843  case kSuspendStateWaitResume:
844  if (snapshot & (1u << kDifUsbdevIrqLinkResume)) {
845  state_enter(ctx, kSuspendStateNextPhase);
846  }
847  break;
848 
849  // The first test phase (Suspend/Resume without AON/Wakeup involvement)
850  // is terminated by a deliberate Bus Reset, advancing us to the next
851  // phase.
852  case kSuspendStateWaitBusReset:
853  if (snapshot & (1u << kDifUsbdevIrqLinkReset)) {
854  state_enter(ctx, kSuspendStateBusReset);
855  }
856  break;
857 
858  // This time we're expecting a much longer Suspend...
859  case kSuspendStateWaitLongSuspend:
860  if (snapshot & (1u << kDifUsbdevIrqLinkSuspend)) {
861  state_enter(ctx, kSuspendStateWaitSuspendTimeout);
862  timeout_frames_set(ctx, FramesWaitEnterSleep);
863  }
864  break;
865 
866  // We're _waiting for a timeout_ to occur, so we're not expecting any
867  // events at this point...
868  case kSuspendStateWaitSuspendTimeout:
869  if (snapshot) {
870  state_enter(ctx, kSuspendStateFailed);
871  }
872  break;
873 
874  case kSuspendStateWaitDisconnect:
875  if (snapshot & (1u << kDifUsbdevIrqDisconnected)) {
876  state_enter(ctx, kSuspendStateComplete);
877  }
878  break;
879 
880  case kSuspendStateActivatedAON:
881  // TODO: should respond to a resume event, and seize back control!
882  break;
883  case kSuspendStateNormalSleep:
884  case kSuspendStateDeepSleep:
885  break;
886  case kSuspendStateAONWakeup:
887  break;
888 
889  case kSuspendStateWaitResumeTimeout:
890  break;
891 
892  case kSuspendStateWaitFinish:
893  // We've resumed, we're just waiting for the host to perform some simple
894  // traffic and then disconnect to signal test completion
895  if (snapshot & (1u << kDifUsbdevLinkStateDisconnected)) {
896  state_enter(ctx, kSuspendStateComplete);
897  }
898  break;
899 
900  case kSuspendStatePowerOnReset:
901  case kSuspendStateBusReset:
902  case kSuspendStateNextPhase:
903  break;
904 
905  case kSuspendStateNormalWaking:
906  case kSuspendStateDeepWaking:
907  break;
908 
909  // Ignore link events if we already have a verdict.
910  case kSuspendStateFailed:
911  case kSuspendStateComplete:
912  break;
913 
914  default:
915  LOG_INFO("Unknown/invalid test state %u (%s)", ctx->test_state,
916  state_name(ctx->test_state));
917  state_enter(ctx, kSuspendStateFailed);
918  break;
919  }
920 
921  if (verbose && ctx->test_state == kSuspendStateFailed) {
922  LOG_INFO(" -> failed handling snapshot 0x%x with link state 0x%x\n",
923  snapshot, link_state);
924  }
925 
926  return OK_STATUS();
927 }
928 
929 // TODO: redirect logging information in Verilator t-l sim because any attempt
930 // to use the UART will introduce long delays and break the test.
931 static size_t base_dev_uart(void *data, const char *buf, size_t len) {
933  for (size_t i = 0; i < len; ++i) {
934  *(uint32_t *)0x411f0084 = ((uint8_t *)buf)[i];
935  }
936  }
937  return len;
938 }
939 static buffer_sink_t base_stdout = {
940  .data = NULL,
941  // Note: Using `&base_dev_null` causes this variable to be placed in the
942  // .data section and triggers the assertion in rom.ld.
943  .sink = base_dev_uart,
944 };
945 
946 ////////////////////////////////////////////////////////////////////////////////
947 // Timeout handling
948 //
949 // Timeouts generally occur if an expected event has not happened as expected,
950 // indicating a failure. Some timeouts, however, simply indicate that the test
951 // should advance - ie. a necessary delay interval has elapsed - and others are
952 // necessary with a physical host (FPGA runs) because the requisite behavior
953 // cannot be generated by the host.
954 ////////////////////////////////////////////////////////////////////////////////
955 static status_t timeout_handle(usbdev_suspend_ctx_t *ctx) {
956  // Timeouts typically indicate failure.
957  bool failed = true;
958 
959  switch (ctx->test_state) {
960  case kSuspendStateWaitSuspend:
961  if (!host_suspends) {
962  LOG_INFO("auto-suspending (FPGA)");
963  state_enter(ctx, kSuspendStateWaitResume);
964  timeout_frames_set(ctx, FramesInitiateResume);
965  failed = false;
966  }
967  break;
968 
969  case kSuspendStateWaitLongSuspend:
970  if (!host_suspends) {
971  LOG_INFO("auto-long-suspending (FPGA)");
972  state_enter(ctx, kSuspendStateWaitSuspendTimeout);
973  timeout_frames_set(ctx, FramesWaitEnterSleep);
974  failed = false;
975  }
976  break;
977 
978  // Timeout is required to advance from the longer suspend state
979  // because we're not expecting any host activity in this case, but
980  // must initiate sleep/powerdown
981  case kSuspendStateWaitSuspendTimeout:
982  if (verbose) {
983  LOG_INFO("set_wake_enable...");
984  }
986 
987  state_enter(ctx, kSuspendStateActivatedAON);
988  timeout_frames_set(ctx, TimeoutAonResponse);
989  failed = false;
990  break;
991 
992  case kSuspendStateWaitResume:
993  if (!host_resumes) {
994  LOG_INFO("auto-resuming (host does not support Resume Signaling)");
995  state_enter(ctx, kSuspendStateWaitBusReset);
996  timeout_frames_set(ctx, 10000u);
997  failed = false;
998  }
999  break;
1000 
1001  // Timeout
1002  case kSuspendStateWaitResumeTimeout:
1003  // TODO:
1004  // timeout_frames_set(ctx, TimeoutFinishMissed);
1005  state_enter(ctx, kSuspendStateNextPhase);
1006  failed = false;
1007  break;
1008 
1009  // Timeout may also be required to advance from Wait(Long)Suspend if
1010  // the host does not attempt to suspend the device, in which case we
1011  // shall also need to transition from WaitResume automatically...
1012  case kSuspendStateWaitBusReset:
1013  if (!host_resets) {
1014  LOG_INFO("auto-resetting (host does not support Bus Resets)");
1015  // Since we don't have an actual Bus Reset we must NOT wait around
1016  // to be reconfigured.
1017  state_enter(ctx, kSuspendStateNextPhase);
1018  failed = false;
1019  }
1020  break;
1021 
1022  // Any other timeout implies that we did not receive the expected link
1023  // event promptly and the test has failed
1024  default:
1025  break;
1026  }
1027 
1028  if (failed) {
1029  LOG_INFO("Timed out in test state %u (%s)", ctx->test_state,
1030  state_name(ctx->test_state));
1031  state_enter(ctx, kSuspendStateFailed);
1032  }
1033 
1034  return OK_STATUS();
1035 }
1036 
1037 ////////////////////////////////////////////////////////////////////////////////
1038 // (Re)initialize the software stack
1039 ////////////////////////////////////////////////////////////////////////////////
1040 
1041 static status_t software_init(usbdev_suspend_ctx_t *ctx) {
1042  if (verbose) {
1043  LOG_INFO("Init testutils layer in state %u (%s)", ctx->test_state,
1044  state_name(ctx->test_state));
1045  }
1046 
1047  // Initialize the usb_testutils layer
1048  // Note: when we exit a Deep Sleep via Resume Signaling we are relying
1049  // upon being able to set up the state of the endpoints and device
1050  // registers again, rather than retaining the full software state in SRAM
1051  TRY(usb_testutils_init(ctx->usbdev, /*pinflip=*/false,
1052  /*en_diff_rcvr=*/true,
1053  /*tx_use_d_se0=*/false));
1054 
1055  // Register our interest in link events
1056  TRY(usb_testutils_link_callback_register(ctx->usbdev, link_callback, ctx));
1057 
1058  if (ctx->with_traffic) {
1059  // Supply usb_testutils context to streaming library
1060  usbdev_streams.usbdev = ctx->usbdev;
1061 
1062 #if 0
1063  // Initialize the state of the streams; do this before resuming.
1064  TRY(usb_testutils_streams_init(&usbdev_streams, nstreams, xfr_types,
1065  transfer_bytes, test_flags, s_verbose));
1066 #else
1067  // TODO: we do nothing with this at the moment, but perhaps in time we'll
1068  // present it to the host via the test descriptor a la the regular
1069  // streaming tests (usbdev_stream/iso/mixed_test).
1070  uint32_t dpi_types;
1071 
1072  // Initialize the state of the streams; do this before resuming.
1073  TRY(usb_testutils_streams_typed_init(&usbdev_streams, config_descriptors,
1074  sizeof(config_descriptors), nstreams,
1075  xfr_types, transfer_bytes, test_flags,
1076  s_verbose, &dpi_types));
1077 #endif
1078  }
1079 
1080  // Set up Endpoint Zero for Control Transfers, at which point the
1081  // interface becomes enabled and we must be responsive to USB traffic.
1082  TRY(usb_testutils_controlep_init(
1083  &usbdev_control, ctx->usbdev, 0, config_descriptors,
1084  sizeof(config_descriptors), ctx->test_dscr, sizeof(ctx->test_dscr)));
1085 
1086  return OK_STATUS();
1087 }
1088 
1089 ////////////////////////////////////////////////////////////////////////////////
1090 // Handle the initial state of a new phase, and the first state after waking
1091 // from Deep Sleep.
1092 ////////////////////////////////////////////////////////////////////////////////
1093 
1094 static status_t phase_start_resume(usbdev_suspend_ctx_t *ctx) {
1095  uint32_t timeout = FramesSuspendMissed;
1096 
1097  TRY_CHECK(ctx->test_state == kSuspendStateNextPhase ||
1098  ctx->test_state == kSuspendStateBusReset ||
1099  ctx->test_state == kSuspendStatePowerOnReset ||
1100  ctx->test_state == kSuspendStateDeepSleep);
1101 
1102  // If we can reuse the existing software state and device configuration for
1103  // this phase then we avoid reinitialization...
1104  if (ctx->test_state != kSuspendStateNextPhase) {
1105  TRY(software_init(ctx));
1106  }
1107 
1108  switch (ctx->test_state) {
1109  case kSuspendStatePowerOnReset:
1110  case kSuspendStateBusReset:
1111  // In this case, since we have no retention RAM, we must wait until the
1112  // host has reconfigured us; do not wait indefinitely, in case something
1113  // has gone wrong.
1114  if (physical_timings()) {
1115  timeout_set(ctx, TimeoutPhysConfig);
1116  } else {
1117  // It should take only a few bus frames even with the older, slower DPI
1118  // behavior.
1119  timeout_frames_set(ctx, 8u);
1120  }
1121 
1122  if (verbose) {
1123  LOG_INFO("waiting to be configured");
1124  }
1125 
1126  while (usbdev_control.device_state != kUsbTestutilsDeviceConfigured &&
1127  !ibex_timeout_check(&ctx->timeout)) {
1128  TRY(usb_testutils_poll(ctx->usbdev));
1129  }
1130 
1131  // If we're out of step with the DPI model/host, stop the test.
1132  TRY_CHECK(usbdev_control.device_state == kUsbTestutilsDeviceConfigured);
1133 
1134  // The DPI model still needs to complete the 'SET_DEVICE_CONFIG' bus frame
1135  // and then devote another bus frame to reading the test configuration.
1136  // (GET_TEST_CONFIG), so we must expect to wait longer before seeing the
1137  // Suspend signaling.
1138  timeout += FramesConfigDelay;
1139  break;
1140 
1141  case kSuspendStateNextPhase:
1142  // Software and device should already be up and running.
1143  break;
1144 
1145  default:
1146  TRY_CHECK(ctx->test_state == kSuspendStateDeepSleep);
1147 
1148  if (ctx->with_traffic) {
1149  // Reinstate the stream information, now that we've set up the basic
1150  // software structures for streaming.
1151  TRY_CHECK(ctx->retn_state.client_used <=
1152  sizeof(ctx->retn_state.client_state));
1153  TRY(usb_testutils_streams_resume(&usbdev_streams,
1154  ctx->retn_state.client_state,
1155  ctx->retn_state.client_used));
1156  }
1157 
1158  // Collect the device address and configuration previously used.
1159  const uint8_t dev_address = ctx->retn_state.dev_address;
1160  const uint8_t dev_config = ctx->retn_state.dev_config;
1161 
1162  // NOTE: We have run through the usb_testutils/controlep_init sequence as
1163  // normal because this sets up our endpoints as they were before, whilst
1164  // requiring less information to be stored in the retention RAM, but we
1165  // must still reinstate the Data Toggle bits and the Device Address
1166 #if USBDEV_HAVE_TOGGLE_STATE
1167  uint16_t out_toggles = (uint16_t)ctx->retn_state.data_toggles;
1168  uint16_t in_toggles = (uint16_t)(ctx->retn_state.data_toggles >> 16);
1169  const uint16_t mask = (uint16_t)((1u << USBDEV_NUM_ENDPOINTS) - 1u);
1170  CHECK_DIF_OK(dif_usbdev_data_toggle_out_write(ctx->usbdev->dev, mask,
1171  out_toggles));
1172  CHECK_DIF_OK(
1173  dif_usbdev_data_toggle_in_write(ctx->usbdev->dev, mask, in_toggles));
1174 #endif
1175  CHECK_DIF_OK(dif_usbdev_address_set(ctx->usbdev->dev, dev_address));
1176 
1177  // TODO: the controlep state needs to be forced to configured.
1178  // TODO: introduce an API call to set/restore the state information for
1179  // the control endpoint, to keep things a little cleaner/more contained?
1180  usbdev_control.device_state = kUsbTestutilsDeviceConfigured;
1181  usbdev_control.usb_config = dev_config;
1182  usbdev_control.new_dev = dev_address;
1183 
1184  // At this point we expected the device to be in the Powered state, and
1185  // since it won't see a Bus Reset, we nudge it into the ActiveNoSOF state.
1186  dif_usbdev_link_state_t link_state;
1187  TRY(dif_usbdev_status_get_link_state(ctx->usbdev->dev, &link_state));
1188  TRY_CHECK(link_state == kDifUsbdevLinkStatePowered ||
1189  link_state == kDifUsbdevLinkStateDisconnected);
1190 
1191  if (link_state == kDifUsbdevLinkStatePowered) {
1192  TRY(dif_usbdev_resume_link_to_active(ctx->usbdev->dev));
1193  }
1194 
1195 #if USBDEV_HAVE_TOGGLE_STATE
1196  if (verbose) {
1197  LOG_INFO("in_toggles 0x%03x out_toggles 0x%03x", in_toggles,
1198  out_toggles);
1199  }
1200 #else
1201  if (ctx->with_traffic) {
1202  LOG_INFO("Warning: Unable to reinstate Data Toggle bits");
1203  }
1204 #endif
1205  break;
1206  }
1207 
1208  // Indication that we've started.
1209  if (ctx->test_state != kSuspendStateNextPhase) {
1210  if (ctx->with_traffic) {
1211  if (ctx->test_state == kSuspendStateDeepSleep) {
1212  if (verbose) {
1213  LOG_INFO("Resuming streaming...");
1214  }
1215  } else {
1216  if (verbose) {
1217  LOG_INFO("Configured; starting streaming...");
1218  }
1219  }
1220  } else {
1221  if (verbose) {
1222  LOG_INFO("Configured; not trying to stream...");
1223  }
1224  }
1225  }
1226 
1227  // Enter the appropriate starting state based upon the test phase
1228  switch (ctx->test_phase) {
1229  case kSuspendPhaseShutdown:
1230  // Just disconnect from the bus and await notification via the link
1231  // callback handler.
1233  state_enter(ctx, kSuspendStateWaitDisconnect);
1234  break;
1235 
1236  case kSuspendPhaseSuspend:
1237  state_enter(ctx, kSuspendStateWaitSuspend);
1238  break;
1239 
1240  default:
1241  CHECK(ctx->test_phase == kSuspendPhaseDeepDisconnect);
1243  case kSuspendPhaseDeepReset:
1244  case kSuspendPhaseDeepResume:
1245  if (ctx->test_state == kSuspendStateDeepSleep) {
1246  state_enter(ctx, kSuspendStateDeepWaking);
1247  break;
1248  }
1249  // If we're starting one of the Deep phases rather than waking from
1250  // DeepSleep then it's the same as starting a normal Sleep phase.
1252  //
1253  case kSuspendPhaseSleepDisconnect:
1254  case kSuspendPhaseSleepReset:
1255  case kSuspendPhaseSleepResume:
1256  if (host_suspends) {
1257  // TODO: human intervention required presently
1258  // timeout *= 2000;
1259  }
1260  state_enter(ctx, kSuspendStateWaitLongSuspend);
1261  break;
1262  }
1263  // Initialize timeout to catch any failure of the host to suspend the bus
1264  timeout_frames_set(ctx, timeout);
1265 
1266  return OK_STATUS();
1267 }
1268 
1269 ////////////////////////////////////////////////////////////////////////////////
1270 // Foreground event handling
1271 //
1272 // Some monitoring activities must occur in the foreground because the
1273 // monitored event is neither immediate nor will it trigger a link
1274 // event.
1275 ////////////////////////////////////////////////////////////////////////////////
1276 
1277 static status_t state_service(usbdev_suspend_ctx_t *ctx) {
1278  switch (ctx->test_state) {
1279  case kSuspendStateActivatedAON:
1280  // Since the AON/Wakeup operates on a low clock frequency, it may
1281  // take some time for it to become active....await its signal
1282  TRY(collect_wake_status(ctx));
1283  if (ctx->wake_status.active) {
1284  // Retain our state information
1285  TRY(dif_usbdev_address_get(ctx->usbdev->dev,
1286  &ctx->retn_state.dev_address));
1287  ctx->retn_state.dev_config = usbdev_control.usb_config;
1288  ctx->retn_state.test_phase = (uint8_t)ctx->test_phase;
1289  // Remember the number of remaining iterations.
1290  ctx->retn_state.num_iters = ctx->num_iters;
1291 #if USBDEV_HAVE_TOGGLE_STATE
1292  // Capture all current Data Toggle bits
1293  uint16_t out_toggles, in_toggles;
1294  TRY(dif_usbdev_data_toggle_out_read(ctx->usbdev->dev, &out_toggles));
1295  TRY(dif_usbdev_data_toggle_in_read(ctx->usbdev->dev, &in_toggles));
1296  ctx->retn_state.data_toggles =
1297  ((uint32_t)in_toggles << 16) | out_toggles;
1298 #else
1299  ctx->retn_state.data_toggles = 0U;
1300 #endif
1301  if (verbose) {
1302  LOG_INFO(" - retaining address %u config %u phase %u (%s)",
1304  ctx->retn_state.test_phase,
1305  phase_name(ctx->retn_state.test_phase));
1306  }
1307 
1308  if (ctx->with_traffic) {
1309  // Store any state information that is necessary to resume streaming.
1310  unsigned used;
1311  TRY(usb_testutils_streams_suspend(
1312  &usbdev_streams, ctx->retn_state.client_state,
1313  sizeof(ctx->retn_state.client_state), &used));
1314  TRY_CHECK(used <= sizeof(ctx->retn_state.client_state));
1315  ctx->retn_state.client_used = used;
1316  }
1317 
1318  retention_sram_store(&ctx->retn_state);
1319 
1320  // TODO: migrate this into a subfunction
1321  // Enter low power mode; note that on some targets we may be unable to
1322  // produce the appropriate stimuli so we have to skip over the sleep
1323  // state.
1324  bool can_awaken = true;
1325  switch (ctx->test_phase) {
1326  case kSuspendPhaseSleepReset:
1327  case kSuspendPhaseDeepReset:
1328  if (!host_resets) {
1329  if (verbose) {
1330  LOG_INFO("auto-skipping WFI (host does not support Bus Resets");
1331  }
1332  can_awaken = false;
1333  }
1334  break;
1335 
1336  case kSuspendPhaseSleepDisconnect:
1337  case kSuspendPhaseDeepDisconnect:
1338  if (!host_disconnects) {
1339  if (verbose) {
1340  LOG_INFO(
1341  "auto-skipping WFI (host does not support Disconnects");
1342  }
1343  can_awaken = false;
1344  }
1345  break;
1346 
1347  default:
1348  TRY_CHECK(ctx->test_phase == kSuspendPhaseSleepResume ||
1349  ctx->test_phase == kSuspendPhaseDeepResume);
1350  if (!host_resumes) {
1351  if (verbose) {
1352  LOG_INFO(
1353  "auto-skipping WFI (host does not support Resume "
1354  "Signaling");
1355  }
1356  can_awaken = false;
1357  }
1358  break;
1359  }
1360 
1361  if (can_awaken) {
1362  if (ctx->test_phase == kSuspendPhaseDeepResume ||
1363  ctx->test_phase == kSuspendPhaseDeepReset ||
1364  ctx->test_phase == kSuspendPhaseDeepDisconnect) {
1365  if (verbose) {
1366  LOG_INFO("Requesting Deep sleep");
1367  }
1368 
1369  // Deep sleep.
1370  //
1371  // Note: we must keep the 'Active USB clock enable' bit set,
1372  // because otherwise when we return to the active state, the
1373  // usbdev clock will not be restored.
1374  TRY(pwrmgr_testutils_enable_low_power(
1375  &pwrmgr, wakeup_sources,
1376  /*domain_config=*/
1377  kDifPwrmgrDomainOptionUsbClockInActivePower));
1378 
1379  // Record that we've asked to power down; timeout should never
1380  // occur.
1381  state_enter(ctx, kSuspendStateDeepSleep);
1382  timeout_frames_set(ctx, TimeoutSleepFailed);
1383  } else {
1384  LOG_INFO("Requesting Normal sleep");
1385 
1386  // Normal sleep.
1387  TRY(pwrmgr_testutils_enable_low_power(
1388  &pwrmgr, /*wakeups=*/wakeup_sources,
1389  /*domain_config=*/
1391  kDifPwrmgrDomainOptionUsbClockInActivePower |
1392  kDifPwrmgrDomainOptionMainPowerInLowPower));
1393 
1394  // Record that we've asked to enter lower power mode; timeout
1395  // should never occur.
1396  state_enter(ctx, kSuspendStateNormalSleep);
1397  timeout_frames_set(ctx, TimeoutSleepFailed);
1398  }
1399 
1400  // With a physical host (FPGA) some manual intervention is required.
1401  const char *action = "";
1402  if (physical_timings()) {
1403  switch (ctx->test_phase) {
1404  case kSuspendPhaseSleepReset:
1405  case kSuspendPhaseDeepReset:
1406  action = "; please Reset the device.";
1407  break;
1408  case kSuspendPhaseSleepDisconnect:
1409  case kSuspendPhaseDeepDisconnect:
1410  action = "; please disconnect and reconnect the USB cable.";
1411  break;
1412  default:
1413  break;
1414  }
1415  }
1416  // sense_report(ctx, 10);
1417  if (verbose) {
1418  LOG_INFO("Issuing WFI to enter sleep%s", action);
1419  }
1421 
1422  // Check that a DeepSleep request did not somehow run past the
1423  // WFI...
1424  TRY_CHECK(ctx->test_state == kSuspendStateNormalSleep);
1425  }
1426 
1427  //---------------------------------------------------------------
1428  // After a Normal sleep, we resume execution here; after a Deep
1429  // sleep we start again as if from a Power On Reset, but the
1430  // pwrmgr tells us otherwise.
1431  //---------------------------------------------------------------
1432 
1433  // TODO: check the IRQ source in the event of a Normal Sleep and
1434  // proceeding past the WFI
1435 
1436  // ... and we should be in one of these test phases.
1437  TRY_CHECK(ctx->retn_state.test_phase == kSuspendPhaseSleepResume ||
1438  ctx->retn_state.test_phase == kSuspendPhaseSleepReset ||
1439  ctx->retn_state.test_phase == kSuspendPhaseSleepDisconnect ||
1440  (!host_resumes &&
1441  ctx->retn_state.test_phase == kSuspendPhaseDeepResume) ||
1442  (!host_resets &&
1443  ctx->retn_state.test_phase == kSuspendPhaseDeepReset) ||
1444  (!host_disconnects &&
1445  ctx->retn_state.test_phase == kSuspendPhaseDeepDisconnect));
1446 
1447  // Retrieve it and check; just additional testing.
1448  usbdev_retn_state_t stored_state;
1449  retention_sram_load(&stored_state);
1450  if (verbose) {
1451  LOG_INFO(" - retained address %u config %u phase %u (%s)",
1452  stored_state.dev_address, stored_state.dev_config,
1453  stored_state.test_phase,
1454  phase_name(stored_state.test_phase));
1455  }
1456 
1457  // Check that the Retention SRAM did its job over Normal Sleep at least;
1458  // the SRAM should remain powered and clocked so this should not be
1459  // challenging.
1460  TRY_CHECK(stored_state.dev_address == ctx->retn_state.dev_address &&
1461  stored_state.dev_config == ctx->retn_state.dev_config &&
1462  stored_state.test_phase == ctx->retn_state.test_phase &&
1463  stored_state.num_iters == ctx->retn_state.num_iters &&
1464  stored_state.data_toggles == ctx->retn_state.data_toggles);
1465 
1466  dif_pwrmgr_wakeup_reason_t wakeup_reason;
1467  TRY(dif_pwrmgr_wakeup_reason_get(&pwrmgr, &wakeup_reason));
1468 
1469  if (verbose) {
1470  LOG_INFO("wakeup types 0x%x sources 0x%x", wakeup_reason.types,
1471  wakeup_reason.request_sources);
1472  }
1473 
1474  state_enter(ctx, kSuspendStateNormalWaking);
1475  // We just need to previous spurious timeouts at this point.
1476  timeout_frames_set(ctx, TimeoutSleepFailed);
1477  }
1478  break;
1479 
1480  case kSuspendStateNormalWaking:
1481  case kSuspendStateDeepWaking:
1482  // We've returned from sleeping; enquire of the USB AON Wake module
1483  // what happened...
1484  TRY(collect_wake_status(ctx));
1485 
1486  // There are three ways that we may exit from Deep Sleep in which
1487  // the AON/Wake module has been handling the bus:
1488  // - Disconnecion (loss of VBUS/SENSE)
1489  // - Bus Reset (from host)
1490  // - Non-Idle state detected (Resume Signaling; this is inferred by
1491  // neither of the other two conditions having occurred.)
1492  // Resume signaling shall last at last 20ms, but the AON/Wake
1493  // module alerts us long before that time has elapsed.
1494 
1495  // Check the report from the AON/Wakeup module
1496  if (ctx->wake_status.active) {
1497  bool got_signal = false;
1498 
1499  switch (ctx->test_phase) {
1500  case kSuspendPhaseSleepResume:
1501  case kSuspendPhaseDeepResume:
1502  got_signal = !host_resumes || (ctx->wake_status.bus_not_idle != 0);
1503  break;
1504 
1505  case kSuspendPhaseSleepReset:
1506  case kSuspendPhaseDeepReset:
1507  got_signal = !host_resets || (ctx->wake_status.bus_reset != 0);
1508  break;
1509 
1510  default:
1511  TRY_CHECK(ctx->test_phase == kSuspendPhaseDeepDisconnect);
1513  case kSuspendPhaseSleepDisconnect:
1514  got_signal =
1515  !host_disconnects || (ctx->wake_status.disconnected != 0);
1516  break;
1517  }
1518 
1519  if (got_signal) {
1520  // TODO: Issue #18562 VBUS Disconnection leaves pull ups asserted
1521  // by the USB AON Wake module, so disconnect them here before
1522  // potential confusion results.
1523  if (ctx->wake_status.disconnected) {
1524  bool sense;
1525 
1526  TRY(dif_usbdev_status_get_sense(ctx->usbdev->dev, &sense));
1527  if (verbose) {
1528  LOG_INFO("Handling Disconnection when VBUS %sasserted",
1529  sense ? "" : "de-");
1530  }
1531 
1532  // TODO: experimental test code! DO NOT MERGE
1533  if (false) {
1534  static uint8_t buf[4096];
1535  extern void usbutils_gather(dif_usbdev_t * dev, uint8_t * buf,
1536  size_t n);
1537 
1538  while (!sense) {
1539  TRY(dif_usbdev_status_get_sense(ctx->usbdev->dev, &sense));
1540  }
1541 
1542  usbutils_gather(ctx->usbdev->dev, buf, sizeof(buf));
1543  }
1544 
1545  // If VBUS/SENSE is not asserted, then the pull up will be removed
1546  // as soon as the AON Wake module is deactivated, because usbdev
1547  // qualifies its own pull up assertions with VBUS/SENSE presence.
1548  if (sense) {
1549  TRY(dif_usbdev_interface_enable(ctx->usbdev->dev, false));
1550  }
1551  }
1552 
1553  // Signal to the AON wakeup module that it should deactivate and
1554  // relinquish control of the bus
1556 
1557  // Although it operates at only 200kHz, it should't take long
1558  state_enter(ctx, kSuspendStateAONWakeup);
1559  timeout_frames_set(ctx, TimeoutAonResponse);
1560  } else {
1561  LOG_INFO("Unexpected report from USB AON Wake module");
1562  report_wake_status(ctx);
1563  state_enter(ctx, kSuspendStateFailed);
1564  }
1565  } else {
1566  LOG_INFO("AON/Wake module not active when expected");
1567  state_enter(ctx, kSuspendStateFailed);
1568  }
1569  break;
1570 
1571  case kSuspendStateAONWakeup:
1572  // Since the AON wakeup module operates on a much lower clock
1573  // frequency it may take some time for it to stop monitoring and to
1574  // report becoming inactive...
1575  TRY(collect_wake_status(ctx));
1576  if (!ctx->wake_status.active) {
1577  // If we've been awoken by a Disconnection event or by a Bus Reset
1578  // event rather than by Resume Signaling, then we must advance to
1579  // the next test phase and expect to be reconfigured.
1580  //
1581  // Note: at this point we may assume that we _did_ get the
1582  // expected wakeup stimulus/report, because it was checked above.
1583  switch (ctx->test_phase) {
1584  case kSuspendPhaseSleepDisconnect:
1585  case kSuspendPhaseDeepDisconnect:
1586  state_enter(ctx, host_disconnects ? kSuspendStatePowerOnReset
1587  : kSuspendStateNextPhase);
1588  break;
1589 
1590  case kSuspendPhaseSleepReset:
1591  case kSuspendPhaseDeepReset:
1592  // TODO: Check! Reset Signaling is still ongoing at this point?
1593  // state_enter(ctx, kSuspendStateWaitBusReset);
1594  state_enter(ctx, kSuspendStateBusReset);
1595  break;
1596 
1597  default:
1598  TRY_CHECK(ctx->test_phase == kSuspendPhaseDeepResume);
1600  case kSuspendPhaseSleepResume:
1601  state_enter(ctx, kSuspendStateWaitResumeTimeout);
1602  timeout_set(ctx, TimeoutWakeupResume);
1603  break;
1604  }
1605  } else {
1606  LOG_INFO("AON Wake module not active when expected");
1607  state_enter(ctx, kSuspendStateFailed);
1608  }
1609  break;
1610 
1611  // TODO: do we still want this state?
1612  case kSuspendStateWaitFinish:
1613  break;
1614 
1615  // Phase-initial/-final states in which we don't need to do anything here.
1616  case kSuspendStatePowerOnReset:
1617  case kSuspendStateBusReset:
1618  case kSuspendStateNextPhase:
1619  case kSuspendStateComplete:
1620  case kSuspendStateFailed:
1621  break;
1622 
1623  // Verdict already decided.
1624 
1625  // States in which we sit waiting - with a timeout - for something
1626  // significant to happen...
1627  default:
1628  TRY_CHECK(ctx->test_state == kSuspendStateWaitResumeTimeout);
1630  case kSuspendStateWaitSuspend:
1631  case kSuspendStateWaitResume:
1632  case kSuspendStateWaitBusReset:
1633  case kSuspendStateWaitLongSuspend:
1634  case kSuspendStateWaitSuspendTimeout:
1635  case kSuspendStateWaitDisconnect:
1636  break;
1637  }
1638 
1639  return OK_STATUS();
1640 }
1641 
1642 /**
1643  * Run a single test phase to completion
1644  */
1645 static status_t phase_run(usbdev_suspend_ctx_t *ctx) {
1646  bool send_progress = (ctx->test_state != kSuspendStateDeepSleep);
1647  bool phase_done = false;
1648 
1649  // Handle the phase-initial state or resuming from Deep Sleep and continuing
1650  // in the present phase.
1651  TRY(phase_start_resume(ctx));
1652 
1653  if (send_progress) {
1654  report_progress("Phase awaiting stimulus (%s)",
1655  phase_name(ctx->test_phase));
1656  }
1657 
1658  switch (ctx->test_state) {
1659  case kSuspendStateBusReset:
1660  case kSuspendStateNextPhase:
1661  case kSuspendStatePowerOnReset:
1662  case kSuspendStateComplete:
1663  case kSuspendStateFailed:
1664  LOG_INFO(
1665  "Phase-initial state %u (%s) should have been handled in "
1666  "phase_start()",
1667  ctx->test_state, state_name(ctx->test_state));
1668  return FAILED_PRECONDITION();
1669  default:
1670  break;
1671  }
1672 
1673  // The DPI model and our callback handler for USB link events do most of the
1674  // work of walking through the test states until completion
1675  do {
1676  if (ibex_timeout_check(&ctx->timeout)) {
1677  TRY(timeout_handle(ctx));
1678  } else {
1679  TRY(state_service(ctx));
1680  }
1681 
1682  switch (ctx->test_state) {
1683  // These states terminate the phase, either advancing to the next phase
1684  // or terminating the test sequence.
1685  case kSuspendStateBusReset:
1686  case kSuspendStateNextPhase:
1687  case kSuspendStatePowerOnReset:
1688  case kSuspendStateComplete: // from PhaseShutdown only
1689  case kSuspendStateFailed: // from any phase
1690  phase_done = true;
1691  break;
1692 
1693  // Do not poll the USB device or perform traffic in these states.
1694  case kSuspendStateActivatedAON:
1695  case kSuspendStateAONWakeup:
1696  case kSuspendStateDeepSleep:
1697  case kSuspendStateNormalSleep:
1698  break;
1699 
1700  // TODO:
1701  case kSuspendStateWaitResume:
1702  // No traffic, but we must still poll the usb_testutils layer to
1703  // handle hardware events and callbacks.
1704  TRY(usb_testutils_poll(ctx->usbdev));
1705  break;
1706 
1707  default:
1708  if (ctx->with_traffic) {
1709  // Servicing streams handles usbdev/testutils events for us.
1710  //
1711  // TODO: streaming code has been integrated, but it would probably be
1712  // quite useful to be able to see the device streaming activity too,
1713  // not just that of the host side?
1714  TRY(usb_testutils_streams_service(&usbdev_streams));
1715  } else {
1716  // No traffic, but we must still poll the usb_testutils layer to
1717  // handle hardware events and callbacks.
1718  TRY(usb_testutils_poll(ctx->usbdev));
1719  }
1720  break;
1721  }
1722  } while (!phase_done);
1723 
1724  // Advance to next phase, unless we have just completed the final phase or
1725  // the test has failed.
1726  switch (ctx->test_state) {
1727  case kSuspendStatePowerOnReset:
1728  case kSuspendStateBusReset:
1729  case kSuspendStateNextPhase: {
1730  // Was this the final phase of the test?
1731  usbdev_suspend_phase_t next_phase =
1732  (usbdev_suspend_phase_t)(ctx->test_phase + 1u);
1733  bool completed = false;
1734  if (ctx->test_phase == ctx->fin_phase) {
1735  if (ctx->num_iters == USBDEV_SUSPEND_ETERNAL || --ctx->num_iters > 0u) {
1736  LOG_INFO("Rewinding to initial phase");
1737  if (ctx->num_iters > 0u) {
1738  LOG_INFO(" - %u iteration(s) remaining", ctx->num_iters);
1739  }
1740  next_phase = ctx->init_phase;
1741  } else {
1742  completed = true;
1743  }
1744  }
1745  // Have we completed the entire test?
1746  if (completed) {
1747  state_enter(ctx, kSuspendStateComplete);
1748  } else {
1749  // Advance to the next test phase, or rewind for the next iteration.
1750  phase_set(ctx, next_phase);
1751  }
1752  } break;
1753 
1754  default:
1755  TRY_CHECK(ctx->test_state == kSuspendStateComplete ||
1756  ctx->test_state == kSuspendStateFailed);
1757  break;
1758  }
1759 
1760  return OK_STATUS();
1761 }
1762 
1763 bool usbdev_suspend_test(usbdev_suspend_phase_t init_phase,
1764  usbdev_suspend_phase_t fin_phase, uint32_t num_iters,
1765  bool with_traffic) {
1766  usbdev_suspend_ctx_t *ctx = &suspend_ctx;
1767 
1768  // Wipe out any memory from the previous test phase, just to be more confident
1769  // that we really are resuming from Deep Sleep and using only the Retention
1770  // SRAM contents to resume.
1771  //
1772  // This also means that the data we subsequently store in the Retention SRAM
1773  // has defined values for the unused padding fields.
1774  memset(ctx, 0, sizeof(*ctx));
1775 
1776  // Enable global and external IRQ at Ibex.
1777  irq_global_ctrl(true);
1778  irq_external_ctrl(true);
1779 
1780  // Remember the phase in which we are to stop.
1781  CHECK(fin_phase >= init_phase);
1782  ctx->init_phase = init_phase;
1783  ctx->fin_phase = fin_phase;
1784 
1785  // Default behavior - for simulation with the DPI - is that all types of
1786  // signaling can be performed, in response to reading the test description.
1787  host_suspends = true;
1788  host_resumes = true;
1789  host_resets = true;
1790  host_disconnects = true;
1791 
1792  // DPI model can perform traffic and will deliberately avoid performing
1793  // traffic during the periods when it stops sending the bus frames
1794 
1795  // Override any of the above switches according to the build target.
1796  switch (kDeviceType) {
1797  case kDeviceSimVerilator:
1798  // steal the UART output and send it via a faster mechanism
1799  base_set_stdout(base_stdout);
1800  verbose = true;
1801 
1802 #if !USBDPI_FULL_FRAME
1803  frame_interval = 500u; // Reduce to 0.5ms to shorten simulation time.
1804 #endif
1805  break;
1806 
1807  // Do NOT steal the UART output in this case because DVsim has a back door
1808  // for rapid logging.
1809  case kDeviceSimDV:
1810  verbose = true;
1811  break;
1812 
1813  case kDeviceSilicon:
1814  // Silicon targets are presently tested with the use of the HyperDebug
1815  // board for control over the VBUS connection.
1816  // Suspend, Resume and Reset operations all rely upon control of the
1817  // parent USB hub.
1818  host_suspends = true;
1819  host_resumes = true;
1820  host_resets = true;
1821  host_disconnects = true;
1822  verbose = false;
1823  break;
1824 
1825  default:
1826  CHECK(kDeviceType == kDeviceFpgaCw310);
1828  case kDeviceFpgaCw340:
1829  // FPGA host can be used to perform Bus Resets and (with hoop-jumping)
1830  // Suspend and Resume. With physical intervention or perhaps a capable
1831  // hub it can perform VBUS Disconnects; such hubs are a rare minority,
1832  // however.
1833  host_suspends = true;
1834  host_resumes = true;
1835  host_resets = true;
1836  // this must still be exercised manually with FPGA boards.
1837  host_disconnects = false;
1838 
1839  // Presently, the FPGA build is expected to be observed/monitored by a
1840  // developer, so verbose reporting is appropriate.
1841  verbose = false; // true;
1842  break;
1843  }
1844 
1845  ctx->with_traffic = with_traffic;
1846 
1847  // Initialize pinmux.
1848  CHECK_DIF_OK(dif_pinmux_init_from_dt(kPinmuxDt, &pinmux));
1849  pinmux_testutils_init(&pinmux);
1850  CHECK_DIF_OK(dif_pinmux_input_select(
1853 
1854  // Initialize pwrmgr.
1855  CHECK_DIF_OK(dif_pwrmgr_init_from_dt(kPwrmgrDt, &pwrmgr));
1856 
1857  // Initialize the PLIC.
1858  CHECK_DIF_OK(dif_rv_plic_init_from_dt(kRvPlicDt, &rv_plic));
1859 
1860  // Initialize rstmgr
1861  CHECK_DIF_OK(dif_rstmgr_init_from_dt(kRstmgrDt, &rstmgr));
1862 
1863  // Enable all the AON interrupts used in this test.
1864  dif_rv_plic_irq_id_t irq_id =
1865  dt_pwrmgr_irq_to_plic_id(kPwrmgrDt, kDtPwrmgrIrqWakeup);
1866  rv_plic_testutils_irq_range_enable(&rv_plic, kPlicTarget, irq_id, irq_id);
1867 
1868  // The USB wakeup signal comes from the pinmux.
1869  CHECK_DIF_OK(dif_pwrmgr_find_request_source(
1870  &pwrmgr, kDifPwrmgrReqTypeWakeup, dt_pinmux_instance_id(kPinmuxDt),
1871  kDtPinmuxWakeupUsbWkupReq, &wakeup_sources));
1872 
1873  // Enable pwrmgr interrupt.
1874  CHECK_DIF_OK(dif_pwrmgr_irq_set_enabled(&pwrmgr, 0, kDifToggleEnabled));
1875 
1876  // Check if there was a HW reset caused by the wdog bite.
1877  dif_rstmgr_reset_info_bitfield_t rst_info = rstmgr_testutils_reason_get();
1878  rstmgr_testutils_reason_clear();
1879 
1880  // Initialize testing context and state machine
1881  ctx->usbdev = &usbdev;
1882 
1883  if (rst_info == kDifRstmgrResetInfoPor) {
1884  const char *iters = "eternally";
1885  static char buf[20];
1886 
1887  report_progress("Running USBDEV_SUSPEND test");
1888 
1889  // Remember the requested iteration count.
1890  ctx->num_iters = num_iters;
1891 
1892  // Report the iteration count
1893  if (num_iters != USBDEV_SUSPEND_ETERNAL) {
1894  base_snprintf(buf, sizeof(buf), "%u times", num_iters);
1895  iters = buf;
1896  }
1897  LOG_INFO(" (seq: %s to %s %s with%s traffic)", phase_name(init_phase),
1898  phase_name(ctx->fin_phase), iters, ctx->with_traffic ? "" : "out");
1899 
1900  // Power On Reset
1901  LOG_INFO("Booting for the first time");
1902 
1903  phase_set(ctx, init_phase);
1904  state_enter(ctx, kSuspendStatePowerOnReset);
1905  } else {
1906  if (verbose) {
1907  // Avoid UART-based logging as much as possible because producing UART
1908  // traffic will stall the CPU waiting on FIFO space, and that can lead to
1909  // USB timeouts when attempting to Resume from Deep Sleep.
1910  LOG_INFO("Resuming from power down!");
1911  }
1912 
1913  // Recover state from the retention RAM
1914  retention_sram_load(&ctx->retn_state);
1915  if (verbose) {
1916  LOG_INFO(" - retained address %u config %u phase %u (%s)",
1918  ctx->retn_state.test_phase,
1919  phase_name(ctx->retn_state.test_phase));
1920  }
1921 
1922  // To have arrived we should be in one of these test phases and we should
1923  // have been in kSuspendStateDeepSleep, so we have not retained that.
1924  CHECK(ctx->retn_state.test_phase == kSuspendPhaseDeepResume ||
1925  ctx->retn_state.test_phase == kSuspendPhaseDeepReset ||
1926  ctx->retn_state.test_phase == kSuspendPhaseDeepDisconnect);
1927 
1928  // We can - presently - check the other parameters; revise/remove this code
1929  // if the configuration becomes more variable.
1930  CHECK(ctx->retn_state.dev_config == 1u);
1931 
1932  // Reinstate the remaining test iteration count from the retained state.
1933  ctx->num_iters = ctx->retn_state.num_iters;
1934 
1935  // We must remain in the DeepSleep state in order to reinitialize the
1936  // software, run through AON Wake deactivation and then check the reason
1937  // for waking.
1938  phase_set(ctx, ctx->retn_state.test_phase);
1939  state_enter(ctx, kSuspendStateDeepSleep);
1940  }
1941 
1942  do {
1943  // Run this test phase
1944  CHECK_STATUS_OK(phase_run(ctx));
1945 
1946  // Keep going if we're advancing to the next phase.
1947  // (NextPhase means that we advance whilst still active and can thus skip
1948  // device setup and configuratinon)
1949  } while (ctx->test_state == kSuspendStateNextPhase || // from Resume
1950  ctx->test_state == kSuspendStateBusReset || // after Bus Reset
1951  ctx->test_state == kSuspendStatePowerOnReset); // after Disconnect
1952 
1953  if (verbose) {
1954  LOG_INFO("Test concluding (%s)", state_name(ctx->test_state));
1955  }
1956 
1957  // Wait enough for a SOF (>1ms) and tear down the software stack.
1958  // Note: there is no finalization code for the streaming at present, because
1959  // it has no resources to release.
1960  busy_spin_micros(1000);
1961  CHECK_STATUS_OK(usb_testutils_fin(ctx->usbdev));
1962 
1963 #if USBUTILS_FUNCTION_POINTS && USBUTILS_FUNCPT_USE_BUFFER
1964  if (false) {
1965  usbutils_funcpt_report();
1966  }
1967 #endif
1968 
1969  return (ctx->test_state == kSuspendStateComplete);
1970 }