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