VirtualBox

source: vbox/trunk/src/VBox/Devices/USB/DevXHCI.cpp@ 107924

Last change on this file since 107924 was 107924, checked in by vboxsync, 2 weeks ago

DevXHCI: Removed some Parfait warnings.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 323.5 KB
Line 
1/* $Id: DevXHCI.cpp 107924 2025-01-23 16:42:56Z vboxsync $ */
2/** @file
3 * DevXHCI - eXtensible Host Controller Interface for USB.
4 */
5
6/*
7 * Copyright (C) 2012-2024 Oracle and/or its affiliates.
8 *
9 * This file is part of VirtualBox base platform packages, as
10 * available from https://www.virtualbox.org.
11 *
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation, in version 3 of the
15 * License.
16 *
17 * This program is distributed in the hope that it will be useful, but
18 * WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * General Public License for more details.
21 *
22 * You should have received a copy of the GNU General Public License
23 * along with this program; if not, see <https://www.gnu.org/licenses>.
24 *
25 * SPDX-License-Identifier: GPL-3.0-only
26 */
27
28/** @page pg_dev_xhci xHCI - eXtensible Host Controller Interface Emulation.
29 *
30 * This component implements an xHCI USB controller.
31 *
32 * The xHCI device is significantly different from the EHCI and OHCI
33 * controllers in that it is not timer driven. A worker thread is responsible
34 * for transferring data between xHCI and VUSB.
35 *
36 * Since there can be dozens or even hundreds of USB devices, and because USB
37 * transfers must share the same bus, only one worker thread is created (per
38 * host controller).
39 *
40 *
41 * The xHCI operational model is heavily based around a producer/consumer
42 * model utilizing rings -- Command, Event, and Transfer rings. The Event ring
43 * is only written by the xHC and is read-only for the HCD (Host Controller
44 * Driver). The Command/Transfer rings are only written by the HCD and are
45 * read-only for the xHC.
46 *
47 * The rings contain TRBs (Transfer Request Blocks). The TRBs represent not
48 * only data transfers but also commands and status information. Each type of
49 * ring only produces/consumes specific TRB types.
50 *
51 * When processing a ring, the xHC simply keeps advancing an internal pointer.
52 * For the Command/Transfer rings, the HCD uses Link TRBs to manage the ring
53 * storage in a fairly arbitrary manner. Since the HCD cannot write to the
54 * Event ring, the Event Ring Segment Table (ERST) is used to manage the ring
55 * storage instead.
56 *
57 * The Cycle bit is used to manage the ring buffer full/empty condition. The
58 * Producer and Consumer both have their own Cycle State (PCS/CCS). The Cycle
59 * bit of each TRB determines who owns it. The consumer only processes TRBs
60 * whose Cycle bit matches the CCS. HCD software typically toggles the Cycle
61 * bit on each pass through the ring. The Link TRB can be used to toggle the
62 * CCS accordingly.
63 *
64 * Multiple Transfer TRBs can be chained together (via the Chain bit) into a
65 * single Transfer Descriptor (TD). This provides a convenient capability for
66 * the HCD to turn a URB into a single TD regardless of how the URB is laid
67 * out in physical memory. If a transfer encounters an error or is terminated
68 * by a short packet, the entire TD (i.e. chain of TRBs) is retired.
69 *
70 * Note that the xHC detects and handles short packets on its own. Backends
71 * are always asked not to consider a short packet to be an error condition.
72 *
73 * Command and Event TRBs cannot be chained, thus an ED (Event Descriptor)
74 * or a Command Descriptor (CD) always consists of a single TRB.
75 *
76 * There is one Command ring per xHC, one Event ring per interrupter (one or
77 * more), and a potentially very large number of Transfer rings. There is a
78 * 1:1 mapping between Transfer Rings and USB pipes, hence each USB device
79 * uses 1-31 Transfer rings (at least one for the default control endpoint,
80 * up to 31 if all IN/OUT endpoints are used). USB 3.0 devices may also use
81 * up to 64K streams per endpoint, each with its Transfer ring, massively
82 * increasing the potential number of Transfer rings in use.
83 *
84 * When building a Transfer ring, it's possible to queue up a large number
85 * of TDs and as soon as the oldest ones are retired, queue up new TDs. The
86 * Transfer ring might thus never be empty.
87 *
88 * For tracking ring buffer position, the TRDP and TREP fields in an endpoint
89 * context are used. The TRDP is the 'TR Dequeue Pointer', i.e. the position
90 * of the next TRB to be completed. This field is visible by the HCD when the
91 * endpoint isn't running. It reflects TRBs completely processed by the xHC
92 * and hence no longer owned by the xHC.
93 *
94 * The TREP field is the 'TR Enqueue Pointer' and tracks the position of the
95 * next TRB to start processing (submit). This is purely internal to the
96 * xHC. The TREP can potentially get far ahead of the TRDP, but only in the
97 * part of the ring owned by the xHC (i.e. with matching DCS bit).
98 *
99 * Unlike most other xHCI data structures, transfer TRBs may describe memory
100 * buffers with no alignment restrictions (both starting position and size).
101 * In addition, there is no relationship between TRB boundaries and USB
102 * packet boundaries.
103 *
104 *
105 * Typically an event would be generated via the IOC bit (Interrupt On
106 * Completion) when the last TRB of a TD is completed. However, multiple IOC
107 * bits may be set per TD. This may be required when a TD equal or larger
108 * than 16MB is used, since transfer events utilize a 24-bit length field.
109 *
110 * There is also the option of using Transfer Event TRBs to report TRB
111 * completion. Transfer Event TRBs may be freely intermixed with transfer
112 * TRBs. Note that an event TRB will produce an event reporting the size of
113 * data transferred since the last event TRB or since the beginning of a TD.
114 * The xHC submits URBs such that they either comprise the entire TD or end
115 * at a Transfer Event TRB, thus there is no need to track the EDTLA
116 * separately.
117 *
118 * Transfer errors always generate events, irrespective of IOC settings. The
119 * xHC has always the option to generate events at implementation-specific
120 * points so that the HCD does not fall too far behind.
121 *
122 * Control transfers use special TDs. A Setup Stage TD consists of only a
123 * single Setup Stage TRB (there's no Chain bit). The optional Data Stage
124 * TD consists of a Data Stage TRB chained to zero or more Normal TRBs
125 * and/or Event Data TRBs. The Status Stage TD then consists of a Status
126 * Stage TRB optionally chained to an Event Data TRB. The HCD is responsible
127 * for building the TDs correctly.
128 *
129 * For isochronous transfers, only the first TRB of a TD is actually an
130 * isochronous TRB. If the TD is chained, it will contain Normal TRBs (and
131 * possibly Event Data TRBs).
132 *
133 *
134 * Isochronous transfers require multiple TDs/URBs to be in flight at a
135 * time. This complicates dealing with non-data TRBs (such as link or event
136 * data TRBs). These TRBs cannot be completed while a previous TRB is still
137 * in flight. They are completed either: a) when submitting URBs and there
138 * are no in-flight URBs, or b) just prior to completing an URB.
139 *
140 * This approach works because URBs must be completed strictly in-order. The
141 * TRDP and TREP determine whether there are in-flight TRBs (TREP equals
142 * TRDP if and only if there are no in-flight TRBs).
143 *
144 * When submitting TRBs and there is in-flight traffic, non-data TRBs must
145 * be examined and skipped over. Link TRBs need to be taken into account.
146 *
147 * Unfortunately, certain HCDs (looking at you, Microsoft!) violate the xHCI
148 * specification and make assumptions about how far ahead of the TRDP the
149 * xHC can get. We have to artificially limit the number of in-flight TDs
150 * for this reason.
151 *
152 * Non-isochronous TRBs do not require this treatment for correct function
153 * but are likely to benefit performance-wise from the pipelining.
154 *
155 * With high-speed and faster transfers, there is an added complication for
156 * endpoints with more than one transfer per frame, i.e. short intervals. At
157 * least some host USB stacks require URBs to cover an entire frame, which
158 * means we may have to glue together several TDs into a single URB.
159 *
160 *
161 * A buggy or malicious guest can create a transfer or command ring that
162 * loops in on itself (in the simplest case using a sequence of one or more
163 * link TRBs where the last TRB points to the beginning of the sequence).
164 * Such a loop would effectively hang the processing thread. Since we cannot
165 * easily detect a generic loop, and because even non-looped TRB/command
166 * rings might contain extremely large number of items, we limit the number
167 * of entries that we are willing to process at once. If the limit is
168 * crossed, the xHC reports a host controller error and shuts itself down
169 * until it's reset.
170 *
171 * Note that for TRB lists, both URB submission and completion must protect
172 * against loops because the lists in guest memory are not guaranteed to stay
173 * unchanged between submitting and completing URBs.
174 *
175 * The event ring is not susceptible to loops because the xHC is the producer,
176 * not consumer. The event ring can run out of space but that is not a fatal
177 * problem.
178 *
179 *
180 * The interrupt logic uses an internal IPE (Interrupt Pending Enable) bit
181 * which controls whether the register-visible IP (Interrupt Pending) bit
182 * can be set. The IPE bit is set when a non-blocking event (BEI bit clear)
183 * is enqueued. The IPE bit is cleared when the event ring is initialized or
184 * transitions to empty (i.e. ERDP == EREP). When IPE transtitions to set,
185 * it will set IP unless the EHB (Event Handler Busy) bit is set or IMODC
186 * (Interrupt Moderation Counter) is non-zero. When IMODC counts down to
187 * zero, it sets the IP bit if IPE is set and EHB is not. Setting the IP bit
188 * triggers interrupt delivery. Note that clearing the IPE bit does not
189 * change the IP bit state.
190 *
191 * Interrupt delivery depends on whether MSI/MSI-X is in use or not. With MSI,
192 * an interrupter's IP (Interrupt Pending) bit is cleared as soon as the MSI
193 * message is written; with classic PCI interrupt delivery, the HCD must clear
194 * the IP bit. However, the EHB (Event Handler Busy) bit is always set, which
195 * causes further interrupts to be blocked on the interrupter until the HCD
196 * processes pending events and clears the EHB bit.
197 *
198 * Note that clearing the EHB bit may immediately trigger an interrupt if
199 * additional event TRBs were queued up while the HCD was processing previous
200 * ones.
201 *
202 *
203 * Each enabled USB device has a corresponding slot ID, a doorbell, as well as
204 * a device context which can be accessed through the DCBAA (Device Context
205 * Base Address Array). Valid slot IDs are in the 1-255 range; the first entry
206 * (i.e. index 0) in the DCBAA may optionally point to the Scratchpad Buffer
207 * Array, while doorbell 0 is associated with the Command Ring.
208 *
209 * While 255 valid slot IDs is an xHCI architectural limit, existing xHC
210 * implementations usually set a considerably lower limit, such as 32. See
211 * the XHCI_NDS constant.
212 *
213 * It would be tempting to use the DCBAA to determine which slots are free.
214 * Unfortunately the xHC is not allowed to access DCBAA entries which map to
215 * disabled slots (see section 6.1). A parallel aSlotState array is hence used
216 * to internally track the slot state and find available slots. Once a slot
217 * is enabled, the slot context entry in the DCBAA is used to track the
218 * slot state.
219 *
220 *
221 * Unlike OHCI/UHCI/EHCI, the xHC much more closely tracks USB device state.
222 * HCDs are not allowed to issue SET_ADDRESS requests at all and must use
223 * the Address Device xHCI command instead.
224 *
225 * HCDs can use SET_CONFIGURATION and SET_INTERFACE requests normally, but
226 * must inform the xHC of the changes via Configure Endpoint and Evaluate
227 * Context commands. Similarly there are Reset Endpoint and Stop Endpoint
228 * commands to manage endpoint state.
229 *
230 * A corollary of the above is that unlike OHCI/UHCI/EHCI, with xHCI there
231 * are very clear rules and a straightforward protocol for managing
232 * ownership of structures in physical memory. During normal operation, the
233 * xHC owns all device context memory and the HCD must explicitly ask the xHC
234 * to relinquish the ownership.
235 *
236 * The xHCI architecture offers an interesting feature in that it reserves
237 * opaque fields for xHCI use in certain data structures (slot and endpoint
238 * contexts) and gives the xHC an option to request scratchpad buffers that
239 * a HCD must provide. The xHC may use the opaque storage and/or scratchpad
240 * buffers for saving internal state.
241 *
242 * For implementation reasons, the xHCI device creates two root hubs on the
243 * VUSB level; one for USB2 devices (USB 1.x and 2.0), one for USB3. The
244 * behavior of USB2 vs. USB3 ports is different, and a device can only be
245 * attached to either one or the other hub. However, there is a single array
246 * of ports to avoid overly complicating the code, given that port numbering
247 * is linear and encompasses both USB2 and USB3 ports.
248 *
249 *
250 * The default emulated device is an Intel 7-Series xHC aka Panther Point.
251 * This was Intel's first xHC and is widely supported. It is also possible
252 * to select an Intel 8-Series xHC aka Lynx Point; this is only useful for
253 * debugging and requires the 'other' set of Windows 7 drivers.
254 *
255 * For Windows XP guest support, it is possible to emulate a Renesas
256 * (formerly NEC) uPD720201 xHC. It would be possible to emulate the earlier
257 * NEC chips but those a) only support xHCI 0.96, and b) their drivers
258 * require a reboot during installation. Renesas' drivers also support
259 * Windows Vista and 7.
260 *
261 *
262 * NB: Endpoints are addressed differently in xHCI and USB. In USB,
263 * endpoint addresses are 8-bit values with the low four bits identifying
264 * the endpoint number and the high bit indicating the direction (0=OUT,
265 * 1=IN); see e.g. 9.3.4 in USB 2.0 spec. In xHCI, endpoint addresses are
266 * used as DCIs (Device Context Index) and for that reason, they're
267 * compressed into 5 bits where the lowest bit(!) indicates direction (again
268 * 1=IN) and bits 1-4 designate the endpoint number. Endpoint 0 is somewhat
269 * special and uses DCI 1. See 4.8.1 in xHCI spec.
270 *
271 *
272 * NB: A variable named iPort is a zero-based index into the port array.
273 * On the other hand, a variable named uPort is a one-based port number!
274 * The implementation (obviously) uses zero-based indexing, but USB ports
275 * are numbered starting with 1. The same is true of xHCI slot numbering.
276 * The macros IDX_TO_ID() and ID_TO_IDX(a) should be used to convert between
277 * the two numbering conventions to make the intent clear.
278 *
279 */
280
281
282/*********************************************************************************************************************************
283* Header Files *
284*********************************************************************************************************************************/
285#define LOG_GROUP LOG_GROUP_DEV_XHCI
286#include <VBox/pci.h>
287#include <VBox/msi.h>
288#include <VBox/vmm/pdm.h>
289#include <VBox/err.h>
290#include <VBox/log.h>
291#include <iprt/assert.h>
292#ifdef IN_RING3
293# include <iprt/uuid.h>
294# include <iprt/critsect.h>
295#endif
296#include <VBox/vusb.h>
297#ifdef VBOX_IN_EXTPACK_R3
298# include <VBox/version.h>
299#endif
300#ifndef VBOX_IN_EXTPACK
301# include "VBoxDD.h"
302#endif
303
304
305/*********************************************************************************************************************************
306* (Most of the) Defined Constants, Macros and Structures *
307*********************************************************************************************************************************/
308
309/* Optional error injection support via DBGF. */
310//#define XHCI_ERROR_INJECTION
311
312/** The saved state version. */
313#define XHCI_SAVED_STATE_VERSION 1
314
315
316/** Convert a zero-based index to a 1-based ID. */
317#define IDX_TO_ID(a) (uint8_t)(a + 1)
318/** Convert a 1-based ID to a zero-based index. */
319#define ID_TO_IDX(a) (uint8_t)(a - 1)
320
321/** PCI device related constants. */
322#define XHCI_PCI_MSI_CAP_OFS 0x80
323
324/** Number of LUNs/root hubs. One each for USB2/USB3. */
325#define XHCI_NUM_LUNS 2
326
327/** @name The following two constants were determined experimentally.
328 * They determine the maximum number of TDs allowed to be in flight.
329 * NB: For isochronous TDs, the number *must* be limited because
330 * Windows 8+ violates the xHCI specification and does not keep
331 * the transfer rings consistent.
332 * @{
333 */
334//#define XHCI_MAX_ISOC_IN_FLIGHT 3 /* Scarlett needs 3; was 12 */
335#define XHCI_MAX_ISOC_IN_FLIGHT 12
336#define XHCI_MAX_BULK_IN_FLIGHT 8
337/** @} */
338
339/** @name Implementation limit on the number of TRBs and commands
340 * the xHC is willing to process at once. A larger number is taken
341 * to indicate a broken or malicious guest, and causes a HC error.
342 * @{
343 */
344#define XHCI_MAX_NUM_CMDS 128
345#define XHCI_MAX_NUM_TRBS 1024
346/** @} */
347
348/** Implementation TD size limit. Prevents EDTLA wrap-around. */
349#define XHCI_MAX_TD_SIZE (16 * _1M - 1)
350
351/** Special value to prevent further queuing. */
352#define XHCI_NO_QUEUING_IN_FLIGHT (XHCI_MAX_BULK_IN_FLIGHT * 2)
353
354/* Structural Parameters #1 (HCSPARAMS1) values. */
355
356/** Maximum allowed Number of Downstream Ports on the root hub. Careful
357 * when changing -- other structures may need adjusting!
358 */
359#define XHCI_NDP_MAX 32
360
361/** Default number of USB 2.0 ports.
362 *
363 * @note AppleUSBXHCI does not handle more than 15 ports. At least OS X
364 * 10.8.2 crashes if we report more than 15 ports! Hence the default
365 * is 8 USB2 + 6 USB3 ports for a total of 14 so that OS X is happy.
366 */
367#define XHCI_NDP_20_DEFAULT 8
368
369/** Default number of USB 3.0 ports. */
370#define XHCI_NDP_30_DEFAULT 6
371
372/** Number of interrupters. */
373#define XHCI_NINTR 8
374
375/** Mask for interrupter indexing. */
376#define XHCI_INTR_MASK (XHCI_NINTR - 1)
377
378/* The following is only true if XHCI_NINTR is a (non-zero) power of two. */
379AssertCompile((XHCI_NINTR & XHCI_INTR_MASK) == 0);
380
381/** Number of Device Slots. Determines the number of doorbell
382 * registers and device slots, among other things. */
383#define XHCI_NDS 32
384
385/* Enforce xHCI architectural limits on HCSPARAMS1. */
386AssertCompile(XHCI_NDP_MAX < 255 && XHCI_NINTR < 1024 && XHCI_NDS < 255);
387AssertCompile(XHCI_NDP_20_DEFAULT + XHCI_NDP_30_DEFAULT <= XHCI_NDP_MAX);
388AssertCompile(XHCI_NDP_MAX <= XHCI_NDS);
389
390/* Structural Parameters #2 (HCSPARAMS2) values. */
391
392/** Isochronous Scheduling Threshold. */
393#define XHCI_IST (RT_BIT(3) | 1) /* One frame. */
394
395/** Max number of Event Ring Segment Table entries as a power of two. */
396#define XHCI_ERSTMAX_LOG2 5
397/** Max number of Event Ring Segment Table entries. */
398#define XHCI_ERSTMAX RT_BIT(XHCI_ERSTMAX_LOG2)
399
400/* Enforce xHCI architectural limits on HCSPARAMS2. */
401AssertCompile(XHCI_ERSTMAX_LOG2 < 16);
402
403
404/** Size of the xHCI memory-mapped I/O region. */
405#define XHCI_MMIO_SIZE _64K
406
407/** Size of the capability part of the MMIO region. */
408#define XHCI_CAPS_REG_SIZE 0x80
409
410/** Offset of the port registers in operational register space. */
411#define XHCI_PORT_REG_OFFSET 0x400
412
413/** Offset of xHCI extended capabilities in MMIO region. */
414#define XHCI_XECP_OFFSET 0x1000
415
416/** Offset of the run-time registers in MMIO region. */
417#define XHCI_RTREG_OFFSET 0x2000
418
419/** Offset of the doorbell registers in MMIO region. */
420#define XHCI_DOORBELL_OFFSET 0x3000
421
422/** Size of the extended capability area. */
423#define XHCI_EXT_CAP_SIZE 1024
424
425/* Make sure we can identify MMIO register accesses properly. */
426AssertCompile(XHCI_DOORBELL_OFFSET > XHCI_RTREG_OFFSET);
427AssertCompile(XHCI_XECP_OFFSET > XHCI_PORT_REG_OFFSET + XHCI_CAPS_REG_SIZE);
428AssertCompile(XHCI_RTREG_OFFSET > XHCI_XECP_OFFSET + XHCI_EXT_CAP_SIZE);
429
430
431/** Maximum size of a single extended capability. */
432#define MAX_XCAP_SIZE 256
433
434/** @name xHCI Extended capability types.
435 * @{ */
436#define XHCI_XCP_USB_LEGACY 1u /**< USB legacy support. */
437#define XHCI_XCP_PROTOCOL 2u /**< Protocols supported by ports. */
438#define XHCI_XCP_EXT_PM 3u /**< Extended power management (non-PCI). */
439#define XHCI_XCP_IOVIRT 4u /**< Hardware xHCI virtualization support. */
440#define XHCI_XCP_MSI 5u /**< Message interrupts (non-PCI). */
441#define XHCI_XCP_LOCAL_MEM 6u /**< Local memory (for debug support). */
442#define XHCI_XCP_USB_DEBUG 10u /**< USB debug capability. */
443#define XHCI_XCP_EXT_MSI 17u /**< MSI-X (non-PCI). */
444/** @} */
445
446
447/* xHCI Register Bits. */
448
449
450/** @name Capability Parameters (HCCPARAMS) bits
451 * @{ */
452#define XHCI_HCC_AC64 RT_BIT(0) /**< RO */
453#define XHCI_HCC_BNC RT_BIT(1) /**< RO */
454#define XHCI_HCC_CSZ RT_BIT(2) /**< RO */
455#define XHCI_HCC_PPC RT_BIT(3) /**< RO */
456#define XHCI_HCC_PIND RT_BIT(4) /**< RO */
457#define XHCI_HCC_LHRC RT_BIT(5) /**< RO */
458#define XHCI_HCC_LTC RT_BIT(6) /**< RO */
459#define XHCI_HCC_NSS RT_BIT(7) /**< RO */
460#define XHCI_HCC_MAXPSA_MASK (RT_BIT(12)|RT_BIT(13)|RT_BIT(14)| RT_BIT(15)) /**< RO */
461#define XHCI_HCC_MAXPSA_SHIFT 12
462#define XHCI_HCC_XECP_MASK 0xFFFF0000 /**< RO */
463#define XHCI_HCC_XECP_SHIFT 16
464/** @} */
465
466
467/** @name Command Register (USBCMD) bits
468 * @{ */
469#define XHCI_CMD_RS RT_BIT(0) /**< RW - Run/Stop */
470#define XHCI_CMD_HCRST RT_BIT(1) /**< RW - Host Controller Reset */
471#define XHCI_CMD_INTE RT_BIT(2) /**< RW - Interrupter Enable */
472#define XHCI_CMD_HSEE RT_BIT(3) /**< RW - Host System Error Enable */
473#define XHCI_CMD_LCRST RT_BIT(7) /**< RW - Light HC Reset */
474#define XHCI_CMD_CSS RT_BIT(8) /**< RW - Controller Save State */
475#define XHCI_CMD_CRS RT_BIT(9) /**< RW - Controller Restore State */
476#define XHCI_CMD_EWE RT_BIT(10) /**< RW - Enable Wrap Event */
477#define XHCI_CMD_EU3S RT_BIT(11) /**< RW - Enable U3 MFINDEX Stop */
478
479#define XHCI_CMD_MASK ( XHCI_CMD_RS | XHCI_CMD_HCRST | XHCI_CMD_INTE | XHCI_CMD_HSEE | XHCI_CMD_LCRST \
480 | XHCI_CMD_CSS | XHCI_CMD_CRS | XHCI_CMD_EWE | XHCI_CMD_EU3S)
481/** @} */
482
483
484/** @name Status Register (USBSTS) bits
485 * @{ */
486#define XHCI_STATUS_HCH RT_BIT(0) /**< RO - HC Halted */
487#define XHCI_STATUS_HSE RT_BIT(2) /**< RW1C - Host System Error */
488#define XHCI_STATUS_EINT RT_BIT(3) /**< RW1C - Event Interrupt */
489#define XHCI_STATUS_PCD RT_BIT(4) /**< RW1C - Port Change Detect */
490#define XHCI_STATUS_SSS RT_BIT(8) /**< RO - Save State Status */
491#define XHCI_STATUS_RSS RT_BIT(9) /**< RO - Resture State Status */
492#define XHCI_STATUS_SRE RT_BIT(10) /**< RW1C - Save/Restore Error */
493#define XHCI_STATUS_CNR RT_BIT(11) /**< RO - Controller Not Ready */
494#define XHCI_STATUS_HCE RT_BIT(12) /**< RO - Host Controller Error */
495
496#define XHCI_STATUS_WRMASK (XHCI_STATUS_HSE | XHCI_STATUS_EINT | XHCI_STATUS_PCD | XHCI_STATUS_SRE)
497/** @} */
498
499
500/** @name Default xHCI speed definitions (7.2.2.1.1)
501 * @{ */
502#define XHCI_SPD_FULL 1
503#define XHCI_SPD_LOW 2
504#define XHCI_SPD_HIGH 3
505#define XHCI_SPD_SUPER 4
506/** @} */
507
508/** @name Port Status and Control Register bits (PORTSCUSB2/PORTSCUSB3)
509 * @{ */
510#define XHCI_PORT_CCS RT_BIT(0) /**< ROS - Current Connection Status */
511#define XHCI_PORT_PED RT_BIT(1) /**< RW1S - Port Enabled/Disabled */
512#define XHCI_PORT_OCA RT_BIT(3) /**< RO - Over-current Active */
513#define XHCI_PORT_PR RT_BIT(4) /**< RW1S - Port Reset */
514#define XHCI_PORT_PLS_MASK (RT_BIT(5) | RT_BIT(6) | RT_BIT(7) | RT_BIT(8)) /**< RWS */
515#define XHCI_PORT_PLS_SHIFT 5
516#define XHCI_PORT_PP RT_BIT(9) /**< RWS - Port Power */
517#define XHCI_PORT_SPD_MASK (RT_BIT(10) | RT_BIT(11) | RT_BIT(12) | RT_BIT(13)) /**< ROS */
518#define XHCI_PORT_SPD_SHIFT 10
519#define XHCI_PORT_LWS RT_BIT(16) /**< RW - Link State Write Strobe */
520#define XHCI_PORT_CSC RT_BIT(17) /**< RW1CS - Connect Status Change */
521#define XHCI_PORT_PEC RT_BIT(18) /**< RW1CS - Port Enabled/Disabled Change */
522#define XHCI_PORT_WRC RT_BIT(19) /**< RW1CS - Warm Port Reset Change */
523#define XHCI_PORT_OCC RT_BIT(20) /**< RW1CS - Over-current Change */
524#define XHCI_PORT_PRC RT_BIT(21) /**< RW1CS - Port Reset Change */
525#define XHCI_PORT_PLC RT_BIT(22) /**< RW1CS - Port Link State Change */
526#define XHCI_PORT_CEC RT_BIT(23) /**< RW1CS - Port Config Error Change */
527#define XHCI_PORT_CAS RT_BIT(24) /**< RO - Cold Attach Status */
528#define XHCI_PORT_WCE RT_BIT(25) /**< RWS - Wake on Connect Enable */
529#define XHCI_PORT_WDE RT_BIT(26) /**< RWS - Wake on Disconnect Enable */
530#define XHCI_PORT_WOE RT_BIT(27) /**< RWS - Wake on Over-current Enable */
531#define XHCI_PORT_DR RT_BIT(30) /**< RO - Device (Not) Removable */
532#define XHCI_PORT_WPR RT_BIT(31) /**< RW1S - Warm Port Reset */
533
534#define XHCI_PORT_RESERVED (RT_BIT(2) | RT_BIT(14) | RT_BIT(15) | RT_BIT(28) | RT_BIT(29))
535
536#define XHCI_PORT_WAKE_MASK (XHCI_PORT_WCE|XHCI_PORT_WDE|XHCI_PORT_WOE)
537#define XHCI_PORT_CHANGE_MASK (XHCI_PORT_CSC|XHCI_PORT_PEC|XHCI_PORT_WRC|XHCI_PORT_OCC|XHCI_PORT_PRC|XHCI_PORT_PLC|XHCI_PORT_CEC)
538#define XHCI_PORT_CTL_RW_MASK (XHCI_PORT_PP|XHCI_PORT_LWS)
539#define XHCI_PORT_CTL_W1_MASK (XHCI_PORT_PED|XHCI_PORT_PR|XHCI_PORT_WPR)
540#define XHCI_PORT_RO_MASK (XHCI_PORT_CCS|XHCI_PORT_OCA|XHCI_PORT_SPD_MASK|XHCI_PORT_CAS|XHCI_PORT_DR)
541/** @} */
542
543/** @name Port Link State values
544 * @{ */
545#define XHCI_PLS_U0 0 /**< U0 State. */
546#define XHCI_PLS_U1 1 /**< U1 State. */
547#define XHCI_PLS_U2 2 /**< U2 State. */
548#define XHCI_PLS_U3 3 /**< U3 State (Suspended). */
549#define XHCI_PLS_DISABLED 4 /**< Disabled. */
550#define XHCI_PLS_RXDETECT 5 /**< RxDetect. */
551#define XHCI_PLS_INACTIVE 6 /**< Inactive. */
552#define XHCI_PLS_POLLING 7 /**< Polling. */
553#define XHCI_PLS_RECOVERY 8 /**< Recovery. */
554#define XHCI_PLS_HOTRST 9 /**< Hot Reset. */
555#define XHCI_PLS_CMPLMODE 10 /**< Compliance Mode. */
556#define XHCI_PLS_TSTMODE 11 /**< Test Mode. */
557/* Values 12-14 are reserved. */
558#define XHCI_PLS_RESUME 15 /**< Resume. */
559/** @} */
560
561
562/** @name Command Ring Control Register (CRCR) bits
563 * @{ */
564#define XHCI_CRCR_RCS RT_BIT(0) /**< RW - Ring Cycle State */
565#define XHCI_CRCR_CS RT_BIT(1) /**< RW1S - Command Stop */
566#define XHCI_CRCR_CA RT_BIT(2) /**< RW1S - Command Abort */
567#define XHCI_CRCR_CRR RT_BIT(3) /**< RO - Command Ring Running */
568
569#define XHCI_CRCR_RD_MASK UINT64_C(0xFFFFFFFFFFFFFFF8) /* Mask off bits always read as zero. */
570#define XHCI_CRCR_ADDR_MASK UINT64_C(0xFFFFFFFFFFFFFFC0)
571#define XHCI_CRCR_UPD_MASK (XHCI_CRCR_ADDR_MASK | XHCI_CRCR_RCS)
572/** @} */
573
574
575/** @name Interrupter Management Register (IMAN) bits
576 * @{ */
577#define XHCI_IMAN_IP RT_BIT(0) /**< RW1C - Interrupt Pending */
578#define XHCI_IMAN_IE RT_BIT(1) /**< RW - Interrupt Enable */
579
580#define XHCI_IMAN_VALID_MASK (XHCI_IMAN_IP | XHCI_IMAN_IE)
581/** @} */
582
583
584/** @name Interrupter Moderation Register (IMOD) bits
585 * @{ */
586#define XHCI_IMOD_IMODC_MASK 0xFFFF0000 /**< RW */
587#define XHCI_IMOD_IMODC_SHIFT 16
588#define XHCI_IMOD_IMODI_MASK 0x0000FFFF /**< RW */
589/** @} */
590
591
592/** @name Event Ring Segment Table Size Register (ERSTSZ) bits
593 * @{ */
594#define XHCI_ERSTSZ_MASK 0x0000FFFF /**< RW */
595/** @} */
596
597/** @name Event Ring Segment Table Base Address Register (ERSTBA) bits
598 * @{ */
599#define XHCI_ERST_ADDR_MASK UINT64_C(0xFFFFFFFFFFFFFFC0)
600/** @} */
601
602/** For reasons that are not obvious, NEC/Renesas xHCs only require 16-bit
603 * alignment for the ERST base. This is not in line with the xHCI spec
604 * (which requires 64-bit alignment) but is clearly documented by NEC.
605 */
606#define NEC_ERST_ADDR_MASK UINT64_C(0xFFFFFFFFFFFFFFF0)
607
608/** Firmware revision reported in NEC/Renesas mode. Value chosen based on
609 * OS X driver check (OS X supports these chips since they're commonly
610 * found in ExpressCards).
611 */
612#define NEC_FW_REV 0x3028
613
614/** @name Event Ring Deqeue Pointer Register (ERDP) bits
615 * @{ */
616#define XHCI_ERDP_DESI_MASK UINT64_C(7) /**< RW - Dequeue ERST Segment Index */
617#define XHCI_ERDP_EHB RT_BIT_64(3) /**< RW1C - Event Handler Busy */
618#define XHCI_ERDP_ADDR_MASK UINT64_C(0xFFFFFFFFFFFFFFF0) /**< RW - ERDP address mask */
619/** @} */
620
621/** @name Device Context Base Address Array (DCBAA) definitions
622 * @{ */
623#define XHCI_DCBAA_ADDR_MASK UINT64_C(0xFFFFFFFFFFFFFFC0) /**< Applies to DCBAAP and its entries. */
624/** @} */
625
626/** @name Doorbell Register bits
627 * @{ */
628#define XHCI_DB_TGT_MASK 0x000000FF /**< DB Target mask. */
629#define XHCI_DB_STRMID_SHIFT 16 /**< DB Stream ID shift. */
630#define XHCI_DB_STRMID_MASK 0xFFFF0000 /**< DB Stream ID mask. */
631/** @} */
632
633/** Address mask for device/endpoint/input contexts. */
634#define XHCI_CTX_ADDR_MASK UINT64_C(0xFFFFFFFFFFFFFFF0)
635
636/** @name TRB Completion Codes
637 * @{ */
638#define XHCI_TCC_INVALID 0 /**< CC field not updated. */
639#define XHCI_TCC_SUCCESS 1 /**< Successful TRB completion. */
640#define XHCI_TCC_DATA_BUF_ERR 2 /**< Overrun/underrun. */
641#define XHCI_TCC_BABBLE 3 /**< Babble detected. */
642#define XHCI_TCC_USB_XACT_ERR 4 /**< USB transaction error. */
643#define XHCI_TCC_TRB_ERR 5 /**< TRB error detected. */
644#define XHCI_TCC_STALL 6 /**< USB Stall detected. */
645#define XHCI_TCC_RSRC_ERR 7 /**< Inadequate xHC resources. */
646#define XHCI_TCC_BWIDTH_ERR 8 /**< Unable to allocate bandwidth. */
647#define XHCI_TCC_NO_SLOTS 9 /**< MaxSlots (NDS) exceeded. */
648#define XHCI_TCC_INV_STRM_TYP 10 /**< Invalid stream context type. */
649#define XHCI_TCC_SLOT_NOT_ENB 11 /**< Slot not enabled. */
650#define XHCI_TCC_EP_NOT_ENB 12 /**< Endpoint not enabled. */
651#define XHCI_TCC_SHORT_PKT 13 /**< Short packet detected. */
652#define XHCI_TCC_RING_UNDERRUN 14 /**< Transfer ring underrun. */
653#define XHCI_TCC_RING_OVERRUN 15 /**< Transfer ring overrun. */
654#define XHCI_TCC_VF_RING_FULL 16 /**< VF event ring full. */
655#define XHCI_TCC_PARM_ERR 17 /**< Invalid context parameter. */
656#define XHCI_TCC_BWIDTH_OVER 18 /**< Isoc bandwidth overrun. */
657#define XHCI_TCC_CTX_STATE_ERR 19 /**< Transition from illegal context state. */
658#define XHCI_TCC_NO_PING 20 /**< No ping response in time. */
659#define XHCI_TCC_EVT_RING_FULL 21 /**< Event Ring full. */
660#define XHCI_TCC_DEVICE_COMPAT 22 /**< Incompatible device detected. */
661#define XHCI_TCC_MISS_SVC 23 /**< Missed isoc service. */
662#define XHCI_TCC_CMDR_STOPPED 24 /**< Command ring stopped. */
663#define XHCI_TCC_CMD_ABORTED 25 /**< Command aborted. */
664#define XHCI_TCC_STOPPED 26 /**< Endpoint stopped. */
665#define XHCI_TCC_STP_INV_LEN 27 /**< EP stopped, invalid transfer length. */
666 /* 28 Reserved. */
667#define XHCI_TCC_MAX_EXIT_LAT 29 /**< Max exit latency too large. */
668 /* 30 Reserved. */
669#define XHCI_TCC_ISOC_OVERRUN 31 /**< Isochronous buffer overrun. */
670#define XHCI_TCC_EVT_LOST 32 /**< Event lost due to overrun. */
671#define XHCI_TCC_ERR_OTHER 33 /**< Implementation specific error. */
672#define XHCI_TCC_INV_STRM_ID 34 /**< Invalid stream ID. */
673#define XHCI_TCC_SEC_BWIDTH_ERR 35 /**< Secondary bandwidth error. */
674#define XHCI_TCC_SPLIT_ERR 36 /**< Split transaction error. */
675/** @} */
676
677#if defined(IN_RING3) && defined(LOG_ENABLED)
678/** Human-readable completion code descriptions for debugging. */
679static const char * const g_apszCmplCodes[] = {
680 "CC field not updated", "Successful TRB completion", "Overrun/underrun", "Babble detected", /* 0-3 */
681 "USB transaction error", "TRB error detected", "USB Stall detected", "Inadequate xHC resources", /* 4-7 */
682 "Unable to allocate bandwidth", "MaxSlots (NDS) exceeded", "Invalid stream context type", "Slot not enabled", /* 8-11 */
683 "Endpoint not enabled", "Short packet detected", "Transfer ring underrun", "Transfer ring overrun", /* 12-15 */
684 "VF event ring full", "Invalid context param", "Isoc bandwidth overrun", "Transition from illegal ctx state", /* 16-19 */
685 "No ping response in time", "Event Ring full", "Incompatible device detected", "Missed isoc service", /* 20-23 */
686 "Command ring stopped", "Command aborted", "Endpoint stopped", "EP stopped, invalid transfer length", /* 24-27 */
687 "Reserved", "Max exit latency too large", "Reserved", "Isochronous buffer overrun", /* 28-31 */
688 "Event lost due to overrun", "Implementation specific error", "Invalid stream ID", "Secondary bandwidth error", /* 32-35 */
689 "Split transaction error" /* 36 */
690};
691#endif
692
693
694/* TRBs marked as 'TRB' are only valid in the transfer ring. TRBs marked
695 * as 'Command' are only valid in the command ring. TRBs marked as 'Event'
696 * are the only ones generated in the event ring. The Link TRB is valid
697 * in both the transfer and command rings.
698 */
699
700/** @name TRB Types
701 * @{ */
702#define XHCI_TRB_INVALID 0 /**< Reserved/unused TRB type. */
703#define XHCI_TRB_NORMAL 1 /**< Normal TRB. */
704#define XHCI_TRB_SETUP_STG 2 /**< Setup Stage TRB. */
705#define XHCI_TRB_DATA_STG 3 /**< Data Stage TRB. */
706#define XHCI_TRB_STATUS_STG 4 /**< Status Stage TRB. */
707#define XHCI_TRB_ISOCH 5 /**< Isochronous TRB. */
708#define XHCI_TRB_LINK 6 /**< Link. */
709#define XHCI_TRB_EVT_DATA 7 /**< Event Data TRB. */
710#define XHCI_TRB_NOOP_XFER 8 /**< No-op transfer TRB. */
711#define XHCI_TRB_ENB_SLOT 9 /**< Enable Slot Command. */
712#define XHCI_TRB_DIS_SLOT 10 /**< Disable Slot Command. */
713#define XHCI_TRB_ADDR_DEV 11 /**< Address Device Command. */
714#define XHCI_TRB_CFG_EP 12 /**< Configure Endpoint Command. */
715#define XHCI_TRB_EVAL_CTX 13 /**< Evaluate Context Command. */
716#define XHCI_TRB_RESET_EP 14 /**< Reset Endpoint Command. */
717#define XHCI_TRB_STOP_EP 15 /**< Stop Endpoint Command. */
718#define XHCI_TRB_SET_DEQ_PTR 16 /**< Set TR Dequeue Pointer Command. */
719#define XHCI_TRB_RESET_DEV 17 /**< Reset Device Command. */
720#define XHCI_TRB_FORCE_EVT 18 /**< Force Event Command. */
721#define XHCI_TRB_NEG_BWIDTH 19 /**< Negotiate Bandwidth Command. */
722#define XHCI_TRB_SET_LTV 20 /**< Set Latency Tolerate Value Command. */
723#define XHCI_TRB_GET_PORT_BW 21 /**< Get Port Bandwidth Command. */
724#define XHCI_TRB_FORCE_HDR 22 /**< Force Header Command. */
725#define XHCI_TRB_NOOP_CMD 23 /**< No-op Command. */
726 /* 24-31 Reserved. */
727#define XHCI_TRB_XFER 32 /**< Transfer Event. */
728#define XHCI_TRB_CMD_CMPL 33 /**< Command Completion Event. */
729#define XHCI_TRB_PORT_SC 34 /**< Port Status Change Event. */
730#define XHCI_TRB_BW_REQ 35 /**< Bandwidth Request Event. */
731#define XHCI_TRB_DBELL 36 /**< Doorbell Event. */
732#define XHCI_TRB_HC_EVT 37 /**< Host Controller Event. */
733#define XHCI_TRB_DEV_NOTIFY 38 /**< Device Notification Event. */
734#define XHCI_TRB_MFIDX_WRAP 39 /**< MFINDEX Wrap Event. */
735 /* 40-47 Reserved. */
736#define NEC_TRB_CMD_CMPL 48 /**< Command Completion Event, NEC specific. */
737#define NEC_TRB_GET_FW_VER 49 /**< Get Firmware Version Command, NEC specific. */
738#define NEC_TRB_AUTHENTICATE 50 /**< Authenticate Command, NEC specific. */
739/** @} */
740
741#if defined(IN_RING3) && defined(LOG_ENABLED)
742/** Human-readable TRB names for debugging. */
743static const char * const g_apszTrbNames[] = {
744 "Reserved/unused TRB!!", "Normal TRB", "Setup Stage TRB", "Data Stage TRB", /* 0-3 */
745 "Status Stage TRB", "Isochronous TRB", "Link", "Event Data TRB", /* 4-7 */
746 "No-op transfer TRB", "Enable Slot", "Disable Slot", "Address Device", /* 8-11 */
747 "Configure Endpoint", "Evaluate Context", "Reset Endpoint", "Stop Endpoint", /* 12-15 */
748 "Set TR Dequeue Pointer", "Reset Device", "Force Event", "Negotiate Bandwidth", /* 16-19 */
749 "Set Latency Tolerate Value", "Get Port Bandwidth", "Force Header", "No-op", /* 20-23 */
750 "UNDEF", "UNDEF", "UNDEF", "UNDEF", "UNDEF", "UNDEF", "UNDEF", "UNDEF", /* 24-31 */
751 "Transfer", "Command Completion", "Port Status Change", "BW Request", /* 32-35 */
752 "Doorbell", "Host Controller", "Device Notification", "MFINDEX Wrap", /* 36-39 */
753 "UNDEF", "UNDEF", "UNDEF", "UNDEF", "UNDEF", "UNDEF", "UNDEF", "UNDEF", /* 40-47 */
754 "NEC FW Version Completion", "NEC Get FW Version", "NEC Authenticate" /* 48-50 */
755};
756#endif
757
758/** Generic TRB template. */
759typedef struct sXHCI_TRB_G {
760 uint32_t resvd0;
761 uint32_t resvd1;
762 uint32_t resvd2 : 24;
763 uint32_t cc : 8; /**< Completion Code. */
764 uint32_t cycle : 1; /**< Cycle bit. */
765 uint32_t resvd3 : 9;
766 uint32_t type : 6; /**< TRB Type. */
767 uint32_t resvd4 : 16;
768} XHCI_TRB_G;
769AssertCompile(sizeof(XHCI_TRB_G) == 0x10);
770
771/** Generic transfer TRB template. */
772typedef struct sXHCI_TRB_GX {
773 uint32_t resvd0;
774 uint32_t resvd1;
775 uint32_t xfr_len : 17; /**< Transfer length. */
776 uint32_t resvd2 : 5;
777 uint32_t int_tgt : 10; /**< Interrupter target. */
778 uint32_t cycle : 1; /**< Cycle bit. */
779 uint32_t ent : 1; /**< Evaluate Next TRB. */
780 uint32_t isp : 1; /**< Interrupt on Short Packet. */
781 uint32_t ns : 1; /**< No Snoop. */
782 uint32_t ch : 1; /**< Chain bit. */
783 uint32_t ioc : 1; /**< Interrupt On Completion. */
784 uint32_t idt : 1; /**< Immediate Data. */
785 uint32_t resvd3 : 3;
786 uint32_t type : 6; /**< TRB Type. */
787 uint32_t resvd4 : 16;
788} XHCI_TRB_GX;
789AssertCompile(sizeof(XHCI_TRB_GX) == 0x10);
790
791
792/* -= Transfer TRB types =- */
793
794
795/** Normal Transfer TRB. */
796typedef struct sXHCI_TRB_NORM {
797 uint64_t data_ptr; /**< Pointer or data. */
798 uint32_t xfr_len : 17; /**< Transfer length. */
799 uint32_t td_size : 5; /**< Remaining packets. */
800 uint32_t int_tgt : 10; /**< Interrupter target. */
801 uint32_t cycle : 1; /**< Cycle bit. */
802 uint32_t ent : 1; /**< Evaluate Next TRB. */
803 uint32_t isp : 1; /**< Interrupt on Short Packet. */
804 uint32_t ns : 1; /**< No Snoop. */
805 uint32_t ch : 1; /**< Chain bit. */
806 uint32_t ioc : 1; /**< Interrupt On Completion. */
807 uint32_t idt : 1; /**< Immediate Data. */
808 uint32_t resvd0 : 2;
809 uint32_t bei : 1; /**< Block Event Interrupt. */
810 uint32_t type : 6; /**< TRB Type. */
811 uint32_t resvd1 : 16;
812} XHCI_TRB_NORM;
813AssertCompile(sizeof(XHCI_TRB_NORM) == 0x10);
814
815/** Control Transfer - Setup Stage TRB. */
816typedef struct sXHCI_TRB_CTSP {
817 uint8_t bmRequestType; /**< See the USB spec. */
818 uint8_t bRequest;
819 uint16_t wValue;
820 uint16_t wIndex;
821 uint16_t wLength;
822 uint32_t xfr_len : 17; /**< Transfer length (8). */
823 uint32_t resvd0 : 5;
824 uint32_t int_tgt : 10; /**< Interrupter target. */
825 uint32_t cycle : 1; /**< Cycle bit. */
826 uint32_t resvd1 : 4;
827 uint32_t ioc : 1; /**< Interrupt On Completion. */
828 uint32_t idt : 1; /**< Immediate Data. */
829 uint32_t resvd2 : 2;
830 uint32_t bei : 1; /**< Block Event Interrupt. */
831 uint32_t type : 6; /**< TRB Type. */
832 uint32_t trt : 2; /**< Transfer Type. */
833 uint32_t resvd3 : 14;
834} XHCI_TRB_CTSP;
835AssertCompile(sizeof(XHCI_TRB_CTSP) == 0x10);
836
837/** Control Transfer - Data Stage TRB. */
838typedef struct sXHCI_TRB_CTDT {
839 uint64_t data_ptr; /**< Pointer or data. */
840 uint32_t xfr_len : 17; /**< Transfer length. */
841 uint32_t td_size : 5; /**< Remaining packets. */
842 uint32_t int_tgt : 10; /**< Interrupter target. */
843 uint32_t cycle : 1; /**< Cycle bit. */
844 uint32_t ent : 1; /**< Evaluate Next TRB. */
845 uint32_t isp : 1; /**< Interrupt on Short Packet. */
846 uint32_t ns : 1; /**< No Snoop. */
847 uint32_t ch : 1; /**< Chain bit. */
848 uint32_t ioc : 1; /**< Interrupt On Completion. */
849 uint32_t idt : 1; /**< Immediate Data. */
850 uint32_t resvd0 : 3;
851 uint32_t type : 6; /**< TRB Type. */
852 uint32_t dir : 1; /**< Direction (1=IN). */
853 uint32_t resvd1 : 15;
854} XHCI_TRB_CTDT;
855AssertCompile(sizeof(XHCI_TRB_CTDT) == 0x10);
856
857/** Control Transfer - Status Stage TRB. */
858typedef struct sXHCI_TRB_CTSS {
859 uint64_t resvd0;
860 uint32_t resvd1 : 22;
861 uint32_t int_tgt : 10; /**< Interrupter target. */
862 uint32_t cycle : 1; /**< Cycle bit. */
863 uint32_t ent : 1; /**< Evaluate Next TRB. */
864 uint32_t resvd2 : 2;
865 uint32_t ch : 1; /**< Chain bit. */
866 uint32_t ioc : 1; /**< Interrupt On Completion. */
867 uint32_t resvd3 : 4;
868 uint32_t type : 6; /**< TRB Type. */
869 uint32_t dir : 1; /**< Direction (1=IN). */
870 uint32_t resvd4 : 15;
871} XHCI_TRB_CTSS;
872AssertCompile(sizeof(XHCI_TRB_CTSS) == 0x10);
873
874/** Isochronous Transfer TRB. */
875typedef struct sXHCI_TRB_ISOC {
876 uint64_t data_ptr; /**< Pointer or data. */
877 uint32_t xfr_len : 17; /**< Transfer length. */
878 uint32_t td_size : 5; /**< Remaining packets. */
879 uint32_t int_tgt : 10; /**< Interrupter target. */
880 uint32_t cycle : 1; /**< Cycle bit. */
881 uint32_t ent : 1; /**< Evaluate Next TRB. */
882 uint32_t isp : 1; /**< Interrupt on Short Packet. */
883 uint32_t ns : 1; /**< No Snoop. */
884 uint32_t ch : 1; /**< Chain bit. */
885 uint32_t ioc : 1; /**< Interrupt On Completion. */
886 uint32_t idt : 1; /**< Immediate Data. */
887 uint32_t tbc : 2; /**< Transfer Burst Count. */
888 uint32_t bei : 1; /**< Block Event Interrupt. */
889 uint32_t type : 6; /**< TRB Type. */
890 uint32_t tlbpc : 4; /**< Transfer Last Burst Packet Count. */
891 uint32_t frm_id : 11; /**< Frame ID. */
892 uint32_t sia : 1; /**< Start Isoch ASAP. */
893} XHCI_TRB_ISOC;
894AssertCompile(sizeof(XHCI_TRB_ISOC) == 0x10);
895
896/* Number of bits in the frame ID. */
897#define XHCI_FRAME_ID_BITS 11
898
899/** No Op Transfer TRB. */
900typedef struct sXHCI_TRB_NOPT {
901 uint64_t resvd0;
902 uint32_t resvd1 : 22;
903 uint32_t int_tgt : 10; /**< Interrupter target. */
904 uint32_t cycle : 1; /**< Cycle bit. */
905 uint32_t ent : 1; /**< Evaluate Next TRB. */
906 uint32_t resvd2 : 2;
907 uint32_t ch : 1; /**< Chain bit. */
908 uint32_t ioc : 1; /**< Interrupt On Completion. */
909 uint32_t resvd3 : 4;
910 uint32_t type : 6; /**< TRB Type. */
911 uint32_t resvd4 : 16;
912} XHCI_TRB_NOPT;
913AssertCompile(sizeof(XHCI_TRB_NOPT) == 0x10);
914
915
916/* -= Event TRB types =- */
917
918
919/** Transfer Event TRB. */
920typedef struct sXHCI_TRB_TE {
921 uint64_t trb_ptr; /**< TRB pointer. */
922 uint32_t xfr_len : 24; /**< Transfer length. */
923 uint32_t cc : 8; /**< Completion Code. */
924 uint32_t cycle : 1; /**< Cycle bit. */
925 uint32_t resvd0 : 1;
926 uint32_t ed : 1; /**< Event Data flag. */
927 uint32_t resvd1 : 7;
928 uint32_t type : 6; /**< TRB Type. */
929 uint32_t ep_id : 5; /**< Endpoint ID. */
930 uint32_t resvd2 : 3;
931 uint32_t slot_id : 8; /**< Slot ID. */
932} XHCI_TRB_TE;
933AssertCompile(sizeof(XHCI_TRB_TE) == 0x10);
934
935/** Command Completion Event TRB. */
936typedef struct sXHCI_TRB_CCE {
937 uint64_t trb_ptr; /**< Command TRB pointer. */
938 uint32_t resvd0 : 24;
939 uint32_t cc : 8; /**< Completion Code. */
940 uint32_t cycle : 1; /**< Cycle bit. */
941 uint32_t resvd1 : 9;
942 uint32_t type : 6; /**< TRB Type. */
943 uint32_t vf_id : 8; /**< Virtual Function ID. */
944 uint32_t slot_id : 8; /**< Slot ID. */
945} XHCI_TRB_CCE;
946AssertCompile(sizeof(XHCI_TRB_CCE) == 0x10);
947
948/** Port Staus Change Event TRB. */
949typedef struct sXHCI_TRB_PSCE {
950 uint32_t resvd0 : 24;
951 uint32_t port_id : 8; /**< Port ID. */
952 uint32_t resvd1;
953 uint32_t resvd2 : 24;
954 uint32_t cc : 8; /**< Completion Code. */
955 uint32_t cycle : 1; /**< Cycle bit. */
956 uint32_t resvd3 : 9;
957 uint32_t type : 6; /**< TRB Type. */
958 uint32_t resvd4 : 16;
959} XHCI_TRB_PSCE;
960AssertCompile(sizeof(XHCI_TRB_PSCE) == 0x10);
961
962/** Bandwidth Request Event TRB. */
963typedef struct sXHCI_TRB_BRE {
964 uint32_t resvd0;
965 uint32_t resvd1;
966 uint32_t resvd2 : 24;
967 uint32_t cc : 8; /**< Completion Code. */
968 uint32_t cycle : 1; /**< Cycle bit. */
969 uint32_t resvd3 : 9;
970 uint32_t type : 6; /**< TRB Type. */
971 uint32_t resvd4 : 8;
972 uint32_t slot_id : 8; /**< Slot ID. */
973} XHCI_TRB_BRE;
974AssertCompile(sizeof(XHCI_TRB_BRE) == 0x10);
975
976/** Doorbell Event TRB. */
977typedef struct sXHCI_TRB_DBE {
978 uint32_t reason : 5; /**< DB Reason/target. */
979 uint32_t resvd0 : 27;
980 uint32_t resvd1;
981 uint32_t resvd2 : 24;
982 uint32_t cc : 8; /**< Completion Code. */
983 uint32_t cycle : 1; /**< Cycle bit. */
984 uint32_t resvd3 : 9;
985 uint32_t type : 6; /**< TRB Type. */
986 uint32_t vf_id : 8; /**< Virtual Function ID. */
987 uint32_t slot_id : 8; /**< Slot ID. */
988} XHCI_TRB_DBE;
989AssertCompile(sizeof(XHCI_TRB_DBE) == 0x10);
990
991/** Host Controller Event TRB. */
992typedef struct sXHCI_TRB_HCE {
993 uint32_t resvd0;
994 uint32_t resvd1;
995 uint32_t resvd2 : 24;
996 uint32_t cc : 8; /**< Completion Code. */
997 uint32_t cycle : 1; /**< Cycle bit. */
998 uint32_t resvd3 : 9;
999 uint32_t type : 6; /**< TRB Type. */
1000 uint32_t resvd4 : 16;
1001} XHCI_TRB_HCE;
1002AssertCompile(sizeof(XHCI_TRB_HCE) == 0x10);
1003
1004/** Device Notification Event TRB. */
1005typedef struct sXHCI_TRB_DNE {
1006 uint32_t resvd0 : 4;
1007 uint32_t dn_type : 4; /**< Device Notification Type. */
1008 uint32_t dnd_lo : 5; /**< Device Notification Data Lo. */
1009 uint32_t dnd_hi; /**< Device Notification Data Hi. */
1010 uint32_t resvd1 : 24;
1011 uint32_t cc : 8; /**< Completion Code. */
1012 uint32_t cycle : 1; /**< Cycle bit. */
1013 uint32_t resvd2 : 9;
1014 uint32_t type : 6; /**< TRB Type. */
1015 uint32_t resvd3 : 8;
1016 uint32_t slot_id : 8; /**< Slot ID. */
1017} XHCI_TRB_DNE;
1018AssertCompile(sizeof(XHCI_TRB_DNE) == 0x10);
1019
1020/** MFINDEX Wrap Event TRB. */
1021typedef struct sXHCI_TRB_MWE {
1022 uint32_t resvd0;
1023 uint32_t resvd1;
1024 uint32_t resvd2 : 24;
1025 uint32_t cc : 8; /**< Completion Code. */
1026 uint32_t cycle : 1; /**< Cycle bit. */
1027 uint32_t resvd3 : 9;
1028 uint32_t type : 6; /**< TRB Type. */
1029 uint32_t resvd4 : 16;
1030} XHCI_TRB_MWE;
1031AssertCompile(sizeof(XHCI_TRB_MWE) == 0x10);
1032
1033/** NEC Specific Command Completion Event TRB. */
1034typedef struct sXHCI_TRB_NCE {
1035 uint64_t trb_ptr; /**< Command TRB pointer. */
1036 uint32_t word1 : 16; /**< First result word. */
1037 uint32_t resvd0 : 8;
1038 uint32_t cc : 8; /**< Completion Code. */
1039 uint32_t cycle : 1; /**< Cycle bit. */
1040 uint32_t resvd1 : 9;
1041 uint32_t type : 6; /**< TRB Type. */
1042 uint32_t word2 : 16; /**< Second result word. */
1043} XHCI_TRB_NCE;
1044AssertCompile(sizeof(XHCI_TRB_NCE) == 0x10);
1045
1046
1047
1048/* -= Command TRB types =- */
1049
1050
1051/** No Op Command TRB. */
1052typedef struct sXHCI_TRB_NOPC {
1053 uint32_t resvd0;
1054 uint32_t resvd1;
1055 uint32_t resvd2;
1056 uint32_t cycle : 1; /**< Cycle bit. */
1057 uint32_t resvd3 : 9;
1058 uint32_t type : 6; /**< TRB Type. */
1059 uint32_t resvd4 : 16;
1060} XHCI_TRB_NOPC;
1061AssertCompile(sizeof(XHCI_TRB_NOPC) == 0x10);
1062
1063/** Enable Slot Command TRB. */
1064typedef struct sXHCI_TRB_ESL {
1065 uint32_t resvd0;
1066 uint32_t resvd1;
1067 uint32_t resvd2;
1068 uint32_t cycle : 1; /**< Cycle bit. */
1069 uint32_t resvd3 : 9;
1070 uint32_t type : 6; /**< TRB Type. */
1071 uint32_t resvd4 : 16;
1072} XHCI_TRB_ESL;
1073AssertCompile(sizeof(XHCI_TRB_ESL) == 0x10);
1074
1075/** Disable Slot Command TRB. */
1076typedef struct sXHCI_TRB_DSL {
1077 uint32_t resvd0;
1078 uint32_t resvd1;
1079 uint32_t resvd2;
1080 uint32_t cycle : 1; /**< Cycle bit. */
1081 uint32_t resvd3 : 9;
1082 uint32_t type : 6; /**< TRB Type. */
1083 uint32_t resvd4 : 8;
1084 uint32_t slot_id : 8; /**< Slot ID. */
1085} XHCI_TRB_DSL;
1086AssertCompile(sizeof(XHCI_TRB_DSL) == 0x10);
1087
1088/** Address Device Command TRB. */
1089typedef struct sXHCI_TRB_ADR {
1090 uint64_t ctx_ptr; /**< Input Context pointer. */
1091 uint32_t resvd0;
1092 uint32_t cycle : 1; /**< Cycle bit. */
1093 uint32_t resvd1 : 8;
1094 uint32_t bsr : 1; /**< Block Set Address Request. */
1095 uint32_t type : 6; /**< TRB Type. */
1096 uint32_t resvd2 : 8;
1097 uint32_t slot_id : 8; /**< Slot ID. */
1098} XHCI_TRB_ADR;
1099AssertCompile(sizeof(XHCI_TRB_ADR) == 0x10);
1100
1101/** Configure Endpoint Command TRB. */
1102typedef struct sXHCI_TRB_CFG {
1103 uint64_t ctx_ptr; /**< Input Context pointer. */
1104 uint32_t resvd0;
1105 uint32_t cycle : 1; /**< Cycle bit. */
1106 uint32_t resvd1 : 8;
1107 uint32_t dc : 1; /**< Deconfigure. */
1108 uint32_t type : 6; /**< TRB Type. */
1109 uint32_t resvd2 : 8;
1110 uint32_t slot_id : 8; /**< Slot ID. */
1111} XHCI_TRB_CFG;
1112AssertCompile(sizeof(XHCI_TRB_CFG) == 0x10);
1113
1114/** Evaluate Context Command TRB. */
1115typedef struct sXHCI_TRB_EVC {
1116 uint64_t ctx_ptr; /**< Input Context pointer. */
1117 uint32_t resvd0;
1118 uint32_t cycle : 1; /**< Cycle bit. */
1119 uint32_t resvd1 : 9;
1120 uint32_t type : 6; /**< TRB Type. */
1121 uint32_t resvd2 : 8;
1122 uint32_t slot_id : 8; /**< Slot ID. */
1123} XHCI_TRB_EVC;
1124AssertCompile(sizeof(XHCI_TRB_EVC) == 0x10);
1125
1126/** Reset Endpoint Command TRB. */
1127typedef struct sXHCI_TRB_RSE {
1128 uint32_t resvd0;
1129 uint32_t resvd1;
1130 uint32_t resvd2;
1131 uint32_t cycle : 1; /**< Cycle bit. */
1132 uint32_t resvd3 : 8;
1133 uint32_t tsp : 1; /**< Transfer State Preserve. */
1134 uint32_t type : 6; /**< TRB Type. */
1135 uint32_t ep_id : 5; /**< Endpoint ID. */
1136 uint32_t resvd4 : 3;
1137 uint32_t slot_id : 8; /**< Slot ID. */
1138} XHCI_TRB_RSE;
1139AssertCompile(sizeof(XHCI_TRB_RSE) == 0x10);
1140
1141/** Stop Endpoint Command TRB. */
1142typedef struct sXHCI_TRB_STP {
1143 uint32_t resvd0;
1144 uint32_t resvd1;
1145 uint32_t resvd2;
1146 uint32_t cycle : 1; /**< Cycle bit. */
1147 uint32_t resvd3 : 9;
1148 uint32_t type : 6; /**< TRB Type. */
1149 uint32_t ep_id : 5; /**< Endpoint ID. */
1150 uint32_t resvd4 : 2;
1151 uint32_t sp : 1; /**< Suspend. */
1152 uint32_t slot_id : 8; /**< Slot ID. */
1153} XHCI_TRB_STP;
1154AssertCompile(sizeof(XHCI_TRB_STP) == 0x10);
1155
1156/** Set TR Dequeue Pointer Command TRB. */
1157typedef struct sXHCI_TRB_STDP {
1158#if 0
1159 uint64_t dcs : 1; /**< Dequeue Cycle State. */
1160 uint64_t sct : 3; /**< Stream Context Type. */
1161 uint64_t tr_dqp : 60; /**< New TR Dequeue Pointer (63:4). */
1162#else
1163 uint64_t tr_dqp;
1164#endif
1165 uint16_t resvd0;
1166 uint16_t strm_id; /**< Stream ID. */
1167 uint32_t cycle : 1; /**< Cycle bit. */
1168 uint32_t resvd1 : 9;
1169 uint32_t type : 6; /**< TRB Type. */
1170 uint32_t ep_id : 5; /**< Endpoint ID. */
1171 uint32_t resvd2 : 3;
1172 uint32_t slot_id : 8; /**< Slot ID. */
1173} XHCI_TRB_STDP;
1174AssertCompile(sizeof(XHCI_TRB_STDP) == 0x10);
1175
1176/** Reset Device Command TRB. */
1177typedef struct sXHCI_TRB_RSD {
1178 uint32_t resvd0;
1179 uint32_t resvd1;
1180 uint32_t resvd2;
1181 uint32_t cycle : 1; /**< Cycle bit. */
1182 uint32_t resvd3 : 9;
1183 uint32_t type : 6; /**< TRB Type. */
1184 uint32_t resvd4 : 8;
1185 uint32_t slot_id : 8; /**< Slot ID. */
1186} XHCI_TRB_RSD;
1187AssertCompile(sizeof(XHCI_TRB_RSD) == 0x10);
1188
1189/** Get Port Bandwidth Command TRB. */
1190typedef struct sXHCI_TRB_GPBW {
1191 uint64_t pbctx_ptr; /**< Port Bandwidth Context pointer. */
1192 uint32_t resvd0;
1193 uint32_t cycle : 1; /**< Cycle bit. */
1194 uint32_t resvd1 : 9;
1195 uint32_t type : 6; /**< TRB Type. */
1196 uint32_t spd : 4; /**< Dev Speed. */
1197 uint32_t resvd2 : 4;
1198 uint32_t slot_id : 8; /**< Slot ID. */
1199} XHCI_TRB_GPBW;
1200AssertCompile(sizeof(XHCI_TRB_GPBW) == 0x10);
1201
1202/** Force Header Command TRB. */
1203typedef struct sXHCI_TRB_FHD {
1204 uint32_t pkt_typ : 5; /**< Packet Type. */
1205 uint32_t hdr_lo : 27; /**< Header Info Lo. */
1206 uint32_t hdr_mid; /**< Header Info Mid. */
1207 uint32_t hdr_hi; /**< Header Info Hi. */
1208 uint32_t cycle : 1; /**< Cycle bit. */
1209 uint32_t resvd0 : 9;
1210 uint32_t type : 6; /**< TRB Type. */
1211 uint32_t resvd1 : 8;
1212 uint32_t slot_id : 8; /**< Slot ID. */
1213} XHCI_TRB_FHD;
1214AssertCompile(sizeof(XHCI_TRB_FHD) == 0x10);
1215
1216/** NEC Specific Authenticate Command TRB. */
1217typedef struct sXHCI_TRB_NAC {
1218 uint64_t cookie; /**< Cookie to munge. */
1219 uint32_t resvd0;
1220 uint32_t cycle : 1; /**< Cycle bit. */
1221 uint32_t resvd1 : 9;
1222 uint32_t type : 6; /**< TRB Type. */
1223 uint32_t resvd2 : 8;
1224 uint32_t slot_id : 8; /**< Slot ID. */
1225} XHCI_TRB_NAC;
1226AssertCompile(sizeof(XHCI_TRB_NAC) == 0x10);
1227
1228
1229/* -= Other TRB types =- */
1230
1231
1232/** Link TRB. */
1233typedef struct sXHCI_TRB_LNK {
1234 uint64_t rseg_ptr; /**< Ring Segment Pointer. */
1235 uint32_t resvd0 : 22;
1236 uint32_t int_tgt : 10; /**< Interrupter target. */
1237 uint32_t cycle : 1; /**< Cycle bit. */
1238 uint32_t toggle : 1; /**< Toggle Cycle flag. */
1239 uint32_t resvd1 : 2;
1240 uint32_t chain : 1; /**< Chain flag. */
1241 uint32_t ioc : 1; /**< Interrupt On Completion flag. */
1242 uint32_t resvd2 : 4;
1243 uint32_t type : 6; /**< TRB Type. */
1244 uint32_t resvd3 : 16;
1245} XHCI_TRB_LNK;
1246AssertCompile(sizeof(XHCI_TRB_LNK) == 0x10);
1247
1248/** Event Data TRB. */
1249typedef struct sXHCI_TRB_EVTD {
1250 uint64_t evt_data; /**< Event Data. */
1251 uint32_t resvd0 : 22;
1252 uint32_t int_tgt : 10; /**< Interrupter target. */
1253 uint32_t cycle : 1; /**< Cycle bit. */
1254 uint32_t ent : 1; /**< Evaluate Next Target flag. */
1255 uint32_t resvd1 : 2;
1256 uint32_t chain : 1; /**< Chain flag. */
1257 uint32_t ioc : 1; /**< Interrupt On Completion flag. */
1258 uint32_t resvd2 : 3;
1259 uint32_t bei : 1; /**< Block Event Interrupt flag. */
1260 uint32_t type : 6; /**< TRB Type. */
1261 uint32_t resvd3 : 16;
1262} XHCI_TRB_EVTD;
1263AssertCompile(sizeof(XHCI_TRB_EVTD) == 0x10);
1264
1265
1266/* -= Union TRB types for the three rings =- */
1267
1268
1269typedef union sXHCI_XFER_TRB {
1270 XHCI_TRB_NORM norm;
1271 XHCI_TRB_CTSP setup;
1272 XHCI_TRB_CTDT data;
1273 XHCI_TRB_CTSS status;
1274 XHCI_TRB_ISOC isoc;
1275 XHCI_TRB_EVTD evtd;
1276 XHCI_TRB_NOPT nop;
1277 XHCI_TRB_LNK link;
1278 XHCI_TRB_GX gen;
1279} XHCI_XFER_TRB;
1280AssertCompile(sizeof(XHCI_XFER_TRB) == 0x10);
1281
1282typedef union sXHCI_COMMAND_TRB {
1283 XHCI_TRB_ESL esl;
1284 XHCI_TRB_DSL dsl;
1285 XHCI_TRB_ADR adr;
1286 XHCI_TRB_CFG cfg;
1287 XHCI_TRB_EVC evc;
1288 XHCI_TRB_RSE rse;
1289 XHCI_TRB_STP stp;
1290 XHCI_TRB_STDP stdp;
1291 XHCI_TRB_RSD rsd;
1292 XHCI_TRB_GPBW gpbw;
1293 XHCI_TRB_FHD fhd;
1294 XHCI_TRB_NAC nac;
1295 XHCI_TRB_NOPC nopc;
1296 XHCI_TRB_LNK link;
1297 XHCI_TRB_G gen;
1298} XHCI_COMMAND_TRB;
1299AssertCompile(sizeof(XHCI_COMMAND_TRB) == 0x10);
1300
1301typedef union sXHCI_EVENT_TRB {
1302 XHCI_TRB_TE te;
1303 XHCI_TRB_CCE cce;
1304 XHCI_TRB_PSCE psce;
1305 XHCI_TRB_BRE bre;
1306 XHCI_TRB_DBE dbe;
1307 XHCI_TRB_HCE hce;
1308 XHCI_TRB_DNE dne;
1309 XHCI_TRB_MWE mwe;
1310 XHCI_TRB_NCE nce;
1311 XHCI_TRB_G gen;
1312} XHCI_EVENT_TRB;
1313AssertCompile(sizeof(XHCI_EVENT_TRB) == 0x10);
1314
1315
1316
1317/* -=-=-= Contexts =-=-=- */
1318
1319/** Slot Context. */
1320typedef struct sXHCI_SLOT_CTX {
1321 uint32_t route_str : 20; /**< Route String. */
1322 uint32_t speed : 4; /**< Device speed. */
1323 uint32_t resvd0 : 1;
1324 uint32_t mtt : 1; /**< Multi-TT flag. */
1325 uint32_t hub : 1; /**< Hub flag. */
1326 uint32_t ctx_ent : 5; /**< Context entries. */
1327 uint32_t max_lat : 16; /**< Max exit latency in usec. */
1328 uint32_t rh_port : 8; /**< Root hub port number (1-based). */
1329 uint32_t n_ports : 8; /**< No. of ports for hubs. */
1330 uint32_t tt_slot : 8; /**< TT hub slot ID. */
1331 uint32_t tt_port : 8; /**< TT port number. */
1332 uint32_t ttt : 2; /**< TT Think Time. */
1333 uint32_t resvd1 : 4;
1334 uint32_t intr_tgt : 10; /**< Interrupter Target. */
1335 uint32_t dev_addr : 8; /**< Device Address. */
1336 uint32_t resvd2 : 19;
1337 uint32_t slot_state : 5; /**< Slot State. */
1338 uint32_t opaque[4]; /**< For xHC (i.e. our own) use. */
1339} XHCI_SLOT_CTX;
1340AssertCompile(sizeof(XHCI_SLOT_CTX) == 0x20);
1341
1342/** @name Slot Context states
1343 * @{ */
1344#define XHCI_SLTST_ENDIS 0 /**< Enabled/Disabled. */
1345#define XHCI_SLTST_DEFAULT 1 /**< Default. */
1346#define XHCI_SLTST_ADDRESSED 2 /**< Addressed. */
1347#define XHCI_SLTST_CONFIGURED 3 /**< Configured. */
1348/** @} */
1349
1350#ifdef IN_RING3
1351/** Human-readable slot state descriptions for debugging. */
1352static const char * const g_apszSltStates[] = {
1353 "Enabled/Disabled", "Default", "Addressed", "Configured" /* 0-3 */
1354};
1355#endif
1356
1357/** Endpoint Context. */
1358typedef struct sXHCI_EP_CTX {
1359 uint32_t ep_state : 3; /**< Endpoint state. */
1360 uint32_t resvd0 : 5;
1361 uint32_t mult : 2; /**< SS isoc burst count. */
1362 uint32_t maxps : 5; /**< Max Primary Streams. */
1363 uint32_t lsa : 1; /**< Linear Stream Array. */
1364 uint32_t interval : 8; /**< USB request interval. */
1365 uint32_t resvd1 : 8;
1366 uint32_t resvd2 : 1;
1367 uint32_t c_err : 2; /**< Error count. */
1368 uint32_t ep_type : 3; /**< Endpoint type. */
1369 uint32_t resvd3 : 1;
1370 uint32_t hid : 1; /**< Host Initiate Disable. */
1371 uint32_t max_brs_sz : 8; /**< Max Burst Size. */
1372 uint32_t max_pkt_sz : 16; /**< Max Packet Size. */
1373 uint64_t trdp; /**< TR Dequeue Pointer. */
1374 uint32_t avg_trb_len : 16; /**< Average TRB Length. */
1375 uint32_t max_esit : 16; /**< Max EP Service Interval Time Payload. */
1376 /**< The rest for xHC (i.e. our own) use. */
1377 uint32_t last_frm : 16; /**< Last isochronous frame used (opaque). */
1378 uint32_t ifc : 8; /**< isoch in-flight TD count (opaque). */
1379 uint32_t last_cc : 8; /**< Last TRB completion code (opaque). */
1380 uint64_t trep; /**< TR Enqueue Pointer (opaque). */
1381} XHCI_EP_CTX;
1382AssertCompile(sizeof(XHCI_EP_CTX) == 0x20);
1383
1384/** @name Endpoint Context states
1385 * @{ */
1386#define XHCI_EPST_DISABLED 0 /**< Disabled. */
1387#define XHCI_EPST_RUNNING 1 /**< Running. */
1388#define XHCI_EPST_HALTED 2 /**< Halted. */
1389#define XHCI_EPST_STOPPED 3 /**< Not running/stopped. */
1390#define XHCI_EPST_ERROR 4 /**< Not running/error. */
1391/** @} */
1392
1393/** @name Endpoint Type values
1394 * @{ */
1395#define XHCI_EPTYPE_INVALID 0 /**< Not valid. */
1396#define XHCI_EPTYPE_ISOCH_OUT 1 /**< Isochronous Out. */
1397#define XHCI_EPTYPE_BULK_OUT 2 /**< Bulk Out. */
1398#define XHCI_EPTYPE_INTR_OUT 3 /**< Interrupt Out. */
1399#define XHCI_EPTYPE_CONTROL 4 /**< Control Bidi. */
1400#define XHCI_EPTYPE_ISOCH_IN 5 /**< Isochronous In. */
1401#define XHCI_EPTYPE_BULK_IN 6 /**< Bulk In. */
1402#define XHCI_EPTYPE_INTR_IN 7 /**< Interrupt In. */
1403/** @} */
1404
1405/* Pick out transfer type from endpoint. */
1406#define XHCI_EP_XTYPE(a) (a & 3)
1407
1408/* Endpoint transfer types. */
1409#define XHCI_XFTYPE_CONTROL 0
1410#define XHCI_XFTYPE_ISOCH XHCI_EPTYPE_ISOCH_OUT
1411#define XHCI_XFTYPE_BULK XHCI_EPTYPE_BULK_OUT
1412#define XHCI_XFTYPE_INTR XHCI_EPTYPE_INTR_OUT
1413
1414/* Transfer Ring Dequeue Pointer address mask. */
1415#define XHCI_TRDP_ADDR_MASK UINT64_C(0xFFFFFFFFFFFFFFF0)
1416#define XHCI_TRDP_DCS_MASK RT_BIT(0) /* Dequeue Cycle State bit. */
1417
1418
1419#ifdef IN_RING3
1420
1421/* Human-readable endpoint state descriptions for debugging. */
1422static const char * const g_apszEpStates[] = {
1423 "Disabled", "Running", "Halted", "Stopped", "Error" /* 0-4 */
1424};
1425
1426/* Human-readable endpoint type descriptions for debugging. */
1427static const char * const g_apszEpTypes[] = {
1428 "Not Valid", "Isoch Out", "Bulk Out", "Interrupt Out", /* 0-3 */
1429 "Control", "Isoch In", "Bulk In", "Interrupt In" /* 4-7 */
1430};
1431
1432#endif /* IN_RING3 */
1433
1434/* Input Control Context. */
1435typedef struct sXHCI_INPC_CTX {
1436 uint32_t drop_flags; /* Drop Context flags (2-31). */
1437 uint32_t add_flags; /* Add Context flags (0-31). */
1438 uint32_t resvd[6];
1439} XHCI_INPC_CTX;
1440AssertCompile(sizeof(XHCI_INPC_CTX) == 0x20);
1441
1442/* Make sure all contexts are the same size. */
1443AssertCompile(sizeof(XHCI_EP_CTX) == sizeof(XHCI_SLOT_CTX));
1444AssertCompile(sizeof(XHCI_EP_CTX) == sizeof(XHCI_INPC_CTX));
1445
1446/* -= Event Ring Segment Table =- */
1447
1448/** Event Ring Segment Table Entry. */
1449typedef struct sXHCI_ERSTE {
1450 uint64_t addr;
1451 uint16_t size;
1452 uint16_t resvd0;
1453 uint32_t resvd1;
1454} XHCI_ERSTE;
1455AssertCompile(sizeof(XHCI_ERSTE) == 0x10);
1456
1457
1458/* -=-= Internal data structures not defined by xHCI =-=- */
1459
1460
1461/** Device slot entry -- either slot context or endpoint context. */
1462typedef union sXHCI_DS_ENTRY {
1463 XHCI_SLOT_CTX sc; /**< Slot context. */
1464 XHCI_EP_CTX ep; /**< Endpoint context. */
1465} XHCI_DS_ENTRY;
1466
1467/** Full device context (slot context + 31 endpoint contexts). */
1468typedef struct sXHCI_DEV_CTX {
1469 XHCI_DS_ENTRY entry[32];
1470} XHCI_DEV_CTX;
1471AssertCompile(sizeof(XHCI_DEV_CTX) == 32 * sizeof(XHCI_EP_CTX));
1472AssertCompile(sizeof(XHCI_DEV_CTX) == 32 * sizeof(XHCI_SLOT_CTX));
1473
1474/** Pointer to the xHCI device state. */
1475typedef struct XHCI *PXHCI;
1476
1477#ifndef VBOX_DEVICE_STRUCT_TESTCASE
1478/**
1479 * The xHCI controller data associated with each URB.
1480 */
1481typedef struct VUSBURBHCIINT
1482{
1483 /** The slot index. */
1484 uint8_t uSlotID;
1485 /** Number of Tds in the array. */
1486 uint32_t cTRB;
1487} VUSBURBHCIINT;
1488#endif
1489
1490/**
1491 * An xHCI root hub port, shared.
1492 */
1493typedef struct XHCIHUBPORT
1494{
1495 /** PORTSC: Port status/control register (R/W). */
1496 uint32_t portsc;
1497 /** PORTPM: Power management status/control register (R/W). */
1498 uint32_t portpm;
1499 /** PORTLI: USB3 port link information (R/O). */
1500 uint32_t portli;
1501} XHCIHUBPORT;
1502/** Pointer to a shared xHCI root hub port. */
1503typedef XHCIHUBPORT *PXHCIHUBPORT;
1504
1505/**
1506 * An xHCI root hub port, ring-3.
1507 */
1508typedef struct XHCIHUBPORTR3
1509{
1510 /** Flag whether there is a device attached to the port. */
1511 bool fAttached;
1512} XHCIHUBPORTR3;
1513/** Pointer to a ring-3 xHCI root hub port. */
1514typedef XHCIHUBPORTR3 *PXHCIHUBPORTR3;
1515
1516/**
1517 * The xHCI root hub, ring-3 only.
1518 *
1519 * @implements PDMIBASE
1520 * @implements VUSBIROOTHUBPORT
1521 */
1522typedef struct XHCIROOTHUBR3
1523{
1524 /** Pointer to the parent xHC. */
1525 R3PTRTYPE(struct XHCIR3 *) pXhciR3;
1526 /** Pointer to the base interface of the VUSB RootHub. */
1527 R3PTRTYPE(PPDMIBASE) pIBase;
1528 /** Pointer to the connector interface of the VUSB RootHub. */
1529 R3PTRTYPE(PVUSBIROOTHUBCONNECTOR) pIRhConn;
1530 /** The base interface exposed to the roothub driver. */
1531 PDMIBASE IBase;
1532 /** The roothub port interface exposed to the roothub driver. */
1533 VUSBIROOTHUBPORT IRhPort;
1534
1535 /** The LED for this hub. */
1536 PDMLED Led;
1537
1538 /** Number of actually implemented ports. */
1539 uint8_t cPortsImpl;
1540 /** Index of first port for this hub. */
1541 uint8_t uPortBase;
1542
1543 uint16_t Alignment0; /**< Force alignment. */
1544#if HC_ARCH_BITS == 64
1545 uint32_t Alignment1;
1546#endif
1547} XHCIROOTHUBR3;
1548/** Pointer to a xHCI root hub (ring-3 only). */
1549typedef XHCIROOTHUBR3 *PXHCIROOTHUBR3;
1550
1551/**
1552 * An xHCI interrupter.
1553 */
1554typedef struct sXHCIINTRPTR
1555{
1556 /* Registers defined by xHCI. */
1557 /** IMAN: Interrupt Management Register (R/W). */
1558 uint32_t iman;
1559 /** IMOD: Interrupt Moderation Register (R/W). */
1560 uint32_t imod;
1561 /** ERSTSZ: Event Ring Segment Table Size (R/W). */
1562 uint32_t erstsz;
1563 /* Reserved/padding. */
1564 uint32_t reserved;
1565 /** ERSTBA: Event Ring Segment Table Base Address (R/W). */
1566 uint64_t erstba;
1567 /** ERDP: Event Ring Dequeue Pointer (R/W). */
1568 uint64_t erdp;
1569 /* Interrupter lock. */
1570 PDMCRITSECT lock;
1571 /* Internal xHCI non-register state. */
1572 /** Internal Event Ring enqueue pointer. */
1573 uint64_t erep;
1574 /** Internal ERDP re-write counter. */
1575 uint32_t erdp_rewrites;
1576 /** This interrupter's index (for logging). */
1577 uint32_t index;
1578 /** Internal index into Event Ring Segment Table. */
1579 uint16_t erst_idx;
1580 /** Internal index into Event Ring Segment. */
1581 uint16_t trb_count;
1582 /** Internal Event Ring Producer Cycle State. */
1583 bool evtr_pcs;
1584 /** Internal Interrupt Pending Enable flag. */
1585 bool ipe;
1586} XHCIINTRPTR, *PXHCIINTRPTR;
1587
1588/**
1589 * xHCI device state.
1590 * @implements PDMILEDPORTS
1591 */
1592typedef struct XHCI
1593{
1594 /** MFINDEX wraparound timer. */
1595 TMTIMERHANDLE hWrapTimer;
1596
1597#ifdef XHCI_ERROR_INJECTION
1598 bool fDropIntrHw;
1599 bool fDropIntrIpe;
1600 bool fDropUrb;
1601 uint8_t Alignment00[1];
1602#else
1603 uint32_t Alignment00; /**< Force alignment. */
1604#endif
1605
1606 /** Flag indicating a pending worker thread notification. */
1607 volatile bool fNotificationSent;
1608 volatile bool afPadding[3];
1609
1610 /** The event semaphore the worker thread waits on. */
1611 SUPSEMEVENT hEvtProcess;
1612
1613 /** Bitmap for finished tasks (R3 -> Guest). */
1614 volatile uint32_t u32TasksFinished;
1615 /** Bitmap for finished queued tasks (R3 -> Guest). */
1616 volatile uint32_t u32QueuedTasksFinished;
1617 /** Bitmap for new queued tasks (Guest -> R3). */
1618 volatile uint32_t u32TasksNew;
1619
1620 /** Copy of XHCIR3::RootHub2::cPortsImpl. */
1621 uint8_t cUsb2Ports;
1622 /** Copy of XHCIR3::RootHub3::cPortsImpl. */
1623 uint8_t cUsb3Ports;
1624 /** Sum of cUsb2Ports and cUsb3Ports. */
1625 uint8_t cTotalPorts;
1626 /** Explicit padding. */
1627 uint8_t bPadding;
1628
1629 /** Start of current frame. */
1630 uint64_t SofTime;
1631 /** State of the individual ports. */
1632 XHCIHUBPORT aPorts[XHCI_NDP_MAX];
1633 /** Interrupters array. */
1634 XHCIINTRPTR aInterrupters[XHCI_NINTR];
1635
1636 /** @name Host Controller Capability Registers
1637 * @{ */
1638 /** CAPLENGTH: base + CAPLENGTH = operational register start (R/O). */
1639 uint32_t cap_length;
1640 /** HCIVERSION: host controller interface version (R/O). */
1641 uint32_t hci_version;
1642 /** HCSPARAMS: Structural parameters 1 (R/O). */
1643 uint32_t hcs_params1;
1644 /** HCSPARAMS: Structural parameters 2 (R/O). */
1645 uint32_t hcs_params2;
1646 /** HCSPARAMS: Structural parameters 3 (R/O). */
1647 uint32_t hcs_params3;
1648 /** HCCPARAMS: Capability parameters (R/O). */
1649 uint32_t hcc_params;
1650 /** DBOFF: Doorbell offset (R/O). */
1651 uint32_t dbell_off;
1652 /** RTSOFF: Run-time register space offset (R/O). */
1653 uint32_t rts_off;
1654 /** @} */
1655
1656 /** @name Host Controller Operational Registers
1657 * @{ */
1658 /** USB command register - USBCMD (R/W). */
1659 uint32_t cmd;
1660 /** USB status register - USBSTS (R/W).*/
1661 uint32_t status;
1662 /** Device Control Notification register - DNCTRL (R/W). */
1663 uint32_t dnctrl;
1664 /** Configure Register (R/W). */
1665 uint32_t config;
1666 /** Command Ring Control Register - CRCR (R/W). */
1667 uint64_t crcr;
1668 /** Device Context Base Address Array Pointer (R/W). */
1669 uint64_t dcbaap;
1670 /** @} */
1671
1672 /** Extended Capabilities storage. */
1673 uint8_t abExtCap[XHCI_EXT_CAP_SIZE];
1674 /** Size of valid extended capabilities. */
1675 uint32_t cbExtCap;
1676
1677 uint32_t Alignment1; /**< Align cmdr_dqp. */
1678
1679 /** @name Internal xHCI non-register state
1680 * @{ */
1681 /** Internal Command Ring dequeue pointer. */
1682 uint64_t cmdr_dqp;
1683 /** Internal Command Ring Consumer Cycle State. */
1684 bool cmdr_ccs;
1685 uint8_t aAlignment2[7]; /**< Force alignment. */
1686 /** Internal Device Slot states. */
1687 uint8_t aSlotState[XHCI_NDS];
1688 /** Internal doorbell states. Each bit corresponds to an endpoint. */
1689 uint32_t aBellsRung[XHCI_NDS];
1690 /** @} */
1691
1692 /** @name Model specific configuration
1693 * @{ */
1694 /** ERST address mask. */
1695 uint64_t erst_addr_mask;
1696 /** @} */
1697
1698 /** The MMIO region. */
1699 IOMMMIOHANDLE hMmio;
1700
1701 /** Detected isochronous URBs completed with error. */
1702 STAMCOUNTER StatErrorIsocUrbs;
1703 /** Detected isochronous packets (not URBs!) with error. */
1704 STAMCOUNTER StatErrorIsocPkts;
1705
1706 /** Event TRBs written to event ring(s). */
1707 STAMCOUNTER StatEventsWritten;
1708 /** Event TRBs not written to event ring(s) due to HC being stopped. */
1709 STAMCOUNTER StatEventsDropped;
1710 /** Requests to set the IP bit. */
1711 STAMCOUNTER StatIntrsPending;
1712 /** Actual interrupt deliveries. */
1713 STAMCOUNTER StatIntrsSet;
1714 /** Interrupts not raised because they were disabled. */
1715 STAMCOUNTER StatIntrsNotSet;
1716 /** A pending interrupt was cleared. */
1717 STAMCOUNTER StatIntrsCleared;
1718 /** Number of TRBs that formed a single control URB. */
1719 STAMCOUNTER StatTRBsPerCtlUrb;
1720 /** Number of TRBs that formed a single data (bulk/interrupt) URB. */
1721 STAMCOUNTER StatTRBsPerDtaUrb;
1722 /** Number of TRBs that formed a single isochronous URB. */
1723 STAMCOUNTER StatTRBsPerIsoUrb;
1724 /** Size of a control URB in bytes. */
1725 STAMCOUNTER StatUrbSizeCtrl;
1726 /** Size of a data URB in bytes. */
1727 STAMCOUNTER StatUrbSizeData;
1728 /** Size of an isochronous URB in bytes. */
1729 STAMCOUNTER StatUrbSizeIsoc;
1730
1731#ifdef VBOX_WITH_STATISTICS
1732 /** @name Register access counters.
1733 * @{ */
1734 STAMCOUNTER StatRdCaps;
1735 STAMCOUNTER StatRdCmdRingCtlHi;
1736 STAMCOUNTER StatRdCmdRingCtlLo;
1737 STAMCOUNTER StatRdConfig;
1738 STAMCOUNTER StatRdDevCtxBaapHi;
1739 STAMCOUNTER StatRdDevCtxBaapLo;
1740 STAMCOUNTER StatRdDevNotifyCtrl;
1741 STAMCOUNTER StatRdDoorBell;
1742 STAMCOUNTER StatRdEvtRingDeqPtrHi;
1743 STAMCOUNTER StatRdEvtRingDeqPtrLo;
1744 STAMCOUNTER StatRdEvtRsTblBaseHi;
1745 STAMCOUNTER StatRdEvtRsTblBaseLo;
1746 STAMCOUNTER StatRdEvtRstblSize;
1747 STAMCOUNTER StatRdEvtRsvd;
1748 STAMCOUNTER StatRdIntrMgmt;
1749 STAMCOUNTER StatRdIntrMod;
1750 STAMCOUNTER StatRdMfIndex;
1751 STAMCOUNTER StatRdPageSize;
1752 STAMCOUNTER StatRdPortLinkInfo;
1753 STAMCOUNTER StatRdPortPowerMgmt;
1754 STAMCOUNTER StatRdPortRsvd;
1755 STAMCOUNTER StatRdPortStatusCtrl;
1756 STAMCOUNTER StatRdUsbCmd;
1757 STAMCOUNTER StatRdUsbSts;
1758 STAMCOUNTER StatRdUnknown;
1759
1760 STAMCOUNTER StatWrCmdRingCtlHi;
1761 STAMCOUNTER StatWrCmdRingCtlLo;
1762 STAMCOUNTER StatWrConfig;
1763 STAMCOUNTER StatWrDevCtxBaapHi;
1764 STAMCOUNTER StatWrDevCtxBaapLo;
1765 STAMCOUNTER StatWrDevNotifyCtrl;
1766 STAMCOUNTER StatWrDoorBell0;
1767 STAMCOUNTER StatWrDoorBellN;
1768 STAMCOUNTER StatWrEvtRingDeqPtrHi;
1769 STAMCOUNTER StatWrEvtRingDeqPtrLo;
1770 STAMCOUNTER StatWrEvtRsTblBaseHi;
1771 STAMCOUNTER StatWrEvtRsTblBaseLo;
1772 STAMCOUNTER StatWrEvtRstblSize;
1773 STAMCOUNTER StatWrIntrMgmt;
1774 STAMCOUNTER StatWrIntrMod;
1775 STAMCOUNTER StatWrPortPowerMgmt;
1776 STAMCOUNTER StatWrPortStatusCtrl;
1777 STAMCOUNTER StatWrUsbCmd;
1778 STAMCOUNTER StatWrUsbSts;
1779 STAMCOUNTER StatWrUnknown;
1780 /** @} */
1781#endif
1782} XHCI;
1783
1784/**
1785 * xHCI device state, ring-3 edition.
1786 * @implements PDMILEDPORTS
1787 */
1788typedef struct XHCIR3
1789{
1790 /** The async worker thread. */
1791 R3PTRTYPE(PPDMTHREAD) pWorkerThread;
1792 /** The device instance.
1793 * @note This is only so interface functions can get their bearings. */
1794 PPDMDEVINSR3 pDevIns;
1795
1796 /** Status LUN: The base interface. */
1797 PDMIBASE IBase;
1798 /** Status LUN: Leds interface. */
1799 PDMILEDPORTS ILeds;
1800 /** Status LUN: Partner of ILeds. */
1801 R3PTRTYPE(PPDMILEDCONNECTORS) pLedsConnector;
1802
1803 /** USB 2.0 Root hub device. */
1804 XHCIROOTHUBR3 RootHub2;
1805 /** USB 3.0 Root hub device. */
1806 XHCIROOTHUBR3 RootHub3;
1807
1808 /** State of the individual ports. */
1809 XHCIHUBPORTR3 aPorts[XHCI_NDP_MAX];
1810
1811 /** Critsect to synchronize worker and I/O completion threads. */
1812 RTCRITSECT CritSectThrd;
1813} XHCIR3;
1814/** Pointer to ring-3 xHCI device state. */
1815typedef XHCIR3 *PXHCIR3;
1816
1817/**
1818 * xHCI device data, ring-0 edition.
1819 */
1820typedef struct XHCIR0
1821{
1822 uint32_t uUnused;
1823} XHCIR0;
1824/** Pointer to ring-0 xHCI device data. */
1825typedef struct XHCIR0 *PXHCIR0;
1826
1827
1828/**
1829 * xHCI device data, raw-mode edition.
1830 */
1831typedef struct XHCIRC
1832{
1833 uint32_t uUnused;
1834} XHCIRC;
1835/** Pointer to raw-mode xHCI device data. */
1836typedef struct XHCIRC *PXHCIRC;
1837
1838
1839/** @typedef XHCICC
1840 * The xHCI device data for the current context. */
1841typedef CTX_SUFF(XHCI) XHCICC;
1842/** @typedef PXHCICC
1843 * Pointer to the xHCI device for the current context. */
1844typedef CTX_SUFF(PXHCI) PXHCICC;
1845
1846
1847/* -=-= Local implementation details =-=- */
1848
1849typedef enum sXHCI_JOB {
1850 XHCI_JOB_PROCESS_CMDRING, /**< Process the command ring. */
1851 XHCI_JOB_DOORBELL, /**< A doorbell (other than DB0) was rung. */
1852 XHCI_JOB_XFER_DONE, /**< Transfer completed, look for more work. */
1853 XHCI_JOB_MAX
1854} XHCI_JOB;
1855
1856/* -=-=- Local xHCI definitions -=-=- */
1857
1858/** @name USB states.
1859 * @{ */
1860#define XHCI_USB_RESET 0x00
1861#define XHCI_USB_RESUME 0x40
1862#define XHCI_USB_OPERATIONAL 0x80
1863#define XHCI_USB_SUSPEND 0xc0
1864/** @} */
1865
1866/* Primary interrupter (for readability). */
1867#define XHCI_PRIMARY_INTERRUPTER 0
1868
1869/** @name Device Slot states.
1870 * @{ */
1871#define XHCI_DEVSLOT_EMPTY 0
1872#define XHCI_DEVSLOT_ENABLED 1
1873#define XHCI_DEVSLOT_DEFAULT 2
1874#define XHCI_DEVSLOT_ADDRESSED 3
1875#define XHCI_DEVSLOT_CONFIGURED 4
1876/** @} */
1877
1878/** Get the pointer to a root hub corresponding to given port index. */
1879#define GET_PORT_PRH(a_pThisCC, a_uPort) \
1880 ((a_uPort) >= (a_pThisCC)->RootHub2.cPortsImpl ? &(a_pThisCC)->RootHub3 : &(a_pThisCC)->RootHub2)
1881#define GET_VUSB_PORT_FROM_XHCI_PORT(a_pRh, a_iPort) \
1882 (((a_iPort) - (a_pRh)->uPortBase) + 1)
1883#define GET_XHCI_PORT_FROM_VUSB_PORT(a_pRh, a_uPort) \
1884 ((a_pRh)->uPortBase + (a_uPort) - 1)
1885
1886/** Check if port corresponding to index is USB3, using shared data. */
1887#define IS_USB3_PORT_IDX_SHR(a_pThis, a_uPort) ((a_uPort) >= (a_pThis)->cUsb2Ports)
1888
1889/** Check if port corresponding to index is USB3, using ring-3 data. */
1890#define IS_USB3_PORT_IDX_R3(a_pThisCC, a_uPort) ((a_uPort) >= (a_pThisCC)->RootHub2.cPortsImpl)
1891
1892/** Query the number of configured USB2 ports. */
1893#define XHCI_NDP_USB2(a_pThisCC) ((a_pThisCC)->RootHub2.cPortsImpl)
1894
1895/** Query the number of configured USB3 ports. */
1896#define XHCI_NDP_USB3(a_pThisCC) ((a_pThisCC)->RootHub3.cPortsImpl)
1897
1898/** Query the total number of configured ports. */
1899#define XHCI_NDP_CFG(a_pThis) ((unsigned)RT_MIN((a_pThis)->cTotalPorts, XHCI_NDP_MAX))
1900
1901
1902#ifndef VBOX_DEVICE_STRUCT_TESTCASE
1903
1904
1905/*********************************************************************************************************************************
1906* Internal Functions *
1907*********************************************************************************************************************************/
1908
1909#ifdef IN_RING3
1910
1911/** Build a Protocol extended capability. */
1912static uint32_t xhciR3BuildProtocolCaps(uint8_t *pbCap, uint32_t cbMax, unsigned cPorts, unsigned nPortOfs, int ver)
1913{
1914 uint32_t *pu32Cap = (uint32_t *)pbCap;
1915 unsigned cPsi;
1916
1917 Assert(nPortOfs + cPorts < 255);
1918 Assert(ver == 2 || ver == 3);
1919
1920 cPsi = 0; /* Currently only implied port speed IDs. */
1921
1922 /* Make sure there's enough room. */
1923 if (cPsi * 4 + 16 > cbMax)
1924 return 0;
1925
1926 /* Header - includes (USB) specification version. */
1927 *pu32Cap++ = (ver << 24) | (0 << 16) | XHCI_XCP_PROTOCOL;
1928 /* Specification - 'USB ' */
1929 *pu32Cap++ = 0x20425355;
1930 /* Port offsets and counts. 1-based! */
1931 *pu32Cap++ = (cPsi << 28) | (cPorts << 8) | (nPortOfs + 1);
1932 /* Reserved dword. */
1933 *pu32Cap++ = 0;
1934
1935 return (uint8_t *)pu32Cap - pbCap;
1936}
1937
1938
1939/** Add an extended capability and link it into the chain. */
1940static int xhciR3AddExtCap(PXHCI pThis, const uint8_t *pCap, uint32_t cbCap, uint32_t *puPrevOfs)
1941{
1942 Assert(*puPrevOfs <= pThis->cbExtCap);
1943 Assert(!(cbCap & 3));
1944
1945 /* Check that the extended capability is sane. */
1946 if (cbCap == 0)
1947 return VERR_BUFFER_UNDERFLOW;
1948 if (pThis->cbExtCap + cbCap > XHCI_EXT_CAP_SIZE)
1949 return VERR_BUFFER_OVERFLOW;
1950 if (cbCap > 255 * 4) /* Size must fit into 8-bit dword count. */
1951 return VERR_BUFFER_OVERFLOW;
1952
1953 /* Copy over the capability data and update offsets. */
1954 memcpy(pThis->abExtCap + pThis->cbExtCap, pCap, cbCap);
1955 pThis->abExtCap[*puPrevOfs + 1] = cbCap >> 2;
1956 pThis->abExtCap[pThis->cbExtCap + 1] = 0;
1957 *puPrevOfs = pThis->cbExtCap;
1958 pThis->cbExtCap += cbCap;
1959 return VINF_SUCCESS;
1960}
1961
1962/** Build the xHCI Extended Capabilities region. */
1963static int xhciR3BuildExtCaps(PXHCI pThis, PXHCICC pThisCC)
1964{
1965 int rc;
1966 uint8_t abXcp[MAX_XCAP_SIZE];
1967 uint32_t cbXcp;
1968 uint32_t uPrevOfs = 0;
1969
1970 Assert(XHCI_NDP_USB2(pThisCC));
1971 Assert(XHCI_NDP_USB3(pThisCC));
1972
1973 /* Most of the extended capabilities are optional or not relevant for PCI
1974 * implementations. However, the Supported Protocol caps are required.
1975 */
1976 cbXcp = xhciR3BuildProtocolCaps(abXcp, sizeof(abXcp), XHCI_NDP_USB2(pThisCC), 0, 2);
1977 rc = xhciR3AddExtCap(pThis, abXcp, cbXcp, &uPrevOfs);
1978 AssertReturn(RT_SUCCESS(rc), rc);
1979
1980 cbXcp = xhciR3BuildProtocolCaps(abXcp, sizeof(abXcp), XHCI_NDP_USB3(pThisCC), XHCI_NDP_USB2(pThisCC), 3);
1981 rc = xhciR3AddExtCap(pThis, abXcp, cbXcp, &uPrevOfs);
1982 AssertReturn(RT_SUCCESS(rc), rc);
1983
1984 return VINF_SUCCESS;
1985}
1986
1987
1988/**
1989 * Select an unused device address. Note that this may fail in the unlikely
1990 * case where all possible addresses are exhausted.
1991 */
1992static uint8_t xhciR3SelectNewAddress(PXHCI pThis, uint8_t uSlotID)
1993{
1994 RT_NOREF(pThis, uSlotID);
1995
1996 /*
1997 * Since there is a 1:1 mapping between USB devices and device slots, we
1998 * should be able to assign a USB address which equals slot ID to any USB
1999 * device. However, the address selection algorithm could be completely
2000 * different (it is not defined by the xHCI spec).
2001 */
2002 return uSlotID;
2003}
2004
2005
2006/**
2007 * Read the address of a device context for a slot from the DCBAA.
2008 *
2009 * @returns Given slot's device context base address.
2010 * @param pDevIns The device instance.
2011 * @param pThis Pointer to the xHCI state.
2012 * @param uSlotID Slot ID to get the context address of.
2013 */
2014static uint64_t xhciR3FetchDevCtxAddr(PPDMDEVINS pDevIns, PXHCI pThis, uint8_t uSlotID)
2015{
2016 uint64_t uCtxAddr;
2017 RTGCPHYS GCPhysDCBAAE;
2018
2019 Assert(uSlotID > 0);
2020 Assert(uSlotID < XHCI_NDS);
2021
2022 /* Fetch the address of the output slot context from the DCBAA. */
2023 GCPhysDCBAAE = pThis->dcbaap + uSlotID * sizeof(uint64_t);
2024 PDMDevHlpPCIPhysReadMeta(pDevIns, GCPhysDCBAAE, &uCtxAddr, sizeof(uCtxAddr));
2025 LogFlowFunc(("Slot ID %u, device context @ %RGp\n", uSlotID, uCtxAddr));
2026 Assert(uCtxAddr);
2027
2028 return uCtxAddr & XHCI_CTX_ADDR_MASK;
2029}
2030
2031
2032/**
2033 * Fetch a device's slot or endpoint context from memory.
2034 *
2035 * @param pDevIns The device instance.
2036 * @param pThis The xHCI device state.
2037 * @param uSlotID Slot ID to access.
2038 * @param uDCI Device Context Index.
2039 * @param pCtx Pointer to storage for the context.
2040 */
2041static int xhciR3FetchDevCtx(PPDMDEVINS pDevIns, PXHCI pThis, uint8_t uSlotID, uint8_t uDCI, void *pCtx)
2042{
2043 RTGCPHYS GCPhysCtx;
2044
2045 GCPhysCtx = xhciR3FetchDevCtxAddr(pDevIns, pThis, uSlotID);
2046 LogFlowFunc(("Reading device context @ %RGp, DCI %u\n", GCPhysCtx, uDCI));
2047 GCPhysCtx += uDCI * sizeof(XHCI_SLOT_CTX);
2048 PDMDevHlpPCIPhysReadMeta(pDevIns, GCPhysCtx, pCtx, sizeof(XHCI_SLOT_CTX));
2049 return VINF_SUCCESS;
2050}
2051
2052
2053/**
2054 * Fetch a device's slot and endpoint contexts from guest memory.
2055 *
2056 * @param pDevIns The device instance.
2057 * @param pThis The xHCI device state.
2058 * @param uSlotID Slot ID to access.
2059 * @param uDCI Endpoint Device Context Index.
2060 * @param pSlot Pointer to storage for the slot context.
2061 * @param pEp Pointer to storage for the endpoint context.
2062 */
2063static int xhciR3FetchCtxAndEp(PPDMDEVINS pDevIns, PXHCI pThis, uint8_t uSlotID, uint8_t uDCI, XHCI_SLOT_CTX *pSlot, XHCI_EP_CTX *pEp)
2064{
2065 AssertPtr(pSlot);
2066 AssertPtr(pEp);
2067 Assert(uDCI); /* Can't be 0 -- that's the device context. */
2068
2069 /* Load the slot context. */
2070 xhciR3FetchDevCtx(pDevIns, pThis, uSlotID, 0, pSlot);
2071 /// @todo sanity check the slot context here?
2072 Assert(pSlot->ctx_ent >= uDCI);
2073
2074 /* Load the endpoint context. */
2075 xhciR3FetchDevCtx(pDevIns, pThis, uSlotID, uDCI, pEp);
2076 /// @todo sanity check the endpoint context here?
2077
2078 return VINF_SUCCESS;
2079}
2080
2081
2082/**
2083 * Update an endpoint context in guest memory.
2084 *
2085 * @param pDevIns The device instance.
2086 * @param pThis The xHCI device state.
2087 * @param uSlotID Slot ID to access.
2088 * @param uDCI Endpoint Device Context Index.
2089 * @param pEp Pointer to storage of the endpoint context.
2090 */
2091static int xhciR3WriteBackEp(PPDMDEVINS pDevIns, PXHCI pThis, uint8_t uSlotID, uint8_t uDCI, XHCI_EP_CTX *pEp)
2092{
2093 RTGCPHYS GCPhysCtx;
2094
2095 AssertPtr(pEp);
2096 Assert(uDCI); /* Can't be 0 -- that's the device context. */
2097
2098 /// @todo sanity check the endpoint context here?
2099 /* Find the physical address. */
2100 GCPhysCtx = xhciR3FetchDevCtxAddr(pDevIns, pThis, uSlotID);
2101 LogFlowFunc(("Writing device context @ %RGp, DCI %u\n", GCPhysCtx, uDCI));
2102 GCPhysCtx += uDCI * sizeof(XHCI_SLOT_CTX);
2103 /* Write the updated context. */
2104 PDMDevHlpPCIPhysWriteMeta(pDevIns, GCPhysCtx, pEp, sizeof(XHCI_EP_CTX));
2105
2106 return VINF_SUCCESS;
2107}
2108
2109
2110/**
2111 * Modify an endpoint context such that it enters the running state.
2112 *
2113 * @param pEpCtx Pointer to the endpoint context.
2114 */
2115static void xhciR3EnableEP(XHCI_EP_CTX *pEpCtx)
2116{
2117 LogFlow(("Enabling EP, TRDP @ %RGp, DCS=%u\n", pEpCtx->trdp & XHCI_TRDP_ADDR_MASK, pEpCtx->trdp & XHCI_TRDP_DCS_MASK));
2118 pEpCtx->ep_state = XHCI_EPST_RUNNING;
2119 pEpCtx->trep = pEpCtx->trdp;
2120}
2121
2122#endif /* IN_RING3 */
2123
2124#define MFIND_PERIOD_NS (UINT64_C(2048) * 1000000)
2125
2126/**
2127 * Set up the MFINDEX wrap timer.
2128 */
2129static void xhciSetWrapTimer(PPDMDEVINS pDevIns, PXHCI pThis)
2130{
2131 uint64_t u64Now;
2132 uint64_t u64LastWrap;
2133 uint64_t u64Expire;
2134 int rc;
2135
2136 /* Try to avoid drift. */
2137 u64Now = PDMDevHlpTimerGet(pDevIns, pThis->hWrapTimer);
2138// u64LastWrap = u64Now - (u64Now % (0x3FFF * 125000));
2139 u64LastWrap = u64Now / MFIND_PERIOD_NS * MFIND_PERIOD_NS;
2140 /* The MFINDEX counter wraps around every 2048 milliseconds. */
2141 u64Expire = u64LastWrap + (uint64_t)2048 * 1000000;
2142 rc = PDMDevHlpTimerSet(pDevIns, pThis->hWrapTimer, u64Expire);
2143 AssertRC(rc);
2144}
2145
2146/**
2147 * Determine whether MSI/MSI-X is enabled for this PCI device.
2148 *
2149 * This influences interrupt handling in xHCI. NB: There should be a PCIDevXxx
2150 * function for this.
2151 */
2152static bool xhciIsMSIEnabled(PPDMPCIDEV pDevIns)
2153{
2154 uint16_t uMsgCtl;
2155
2156 uMsgCtl = PDMPciDevGetWord(pDevIns, XHCI_PCI_MSI_CAP_OFS + VBOX_MSI_CAP_MESSAGE_CONTROL);
2157 return !!(uMsgCtl & VBOX_PCI_MSI_FLAGS_ENABLE);
2158}
2159
2160/**
2161 * Get the worker thread going -- there's something to do.
2162 */
2163static void xhciKickWorker(PPDMDEVINS pDevIns, PXHCI pThis, XHCI_JOB enmJob, uint32_t uWorkDesc)
2164{
2165 RT_NOREF(enmJob, uWorkDesc);
2166
2167 /* Tell the worker thread there's something to do. */
2168 if (!ASMAtomicXchgBool(&pThis->fNotificationSent, true))
2169 {
2170 LogFlowFunc(("Signal event semaphore\n"));
2171 int rc = PDMDevHlpSUPSemEventSignal(pDevIns, pThis->hEvtProcess);
2172 AssertRC(rc);
2173 }
2174}
2175
2176/**
2177 * Fetch the current ERST entry from guest memory.
2178 */
2179static void xhciFetchErstEntry(PPDMDEVINS pDevIns, PXHCI pThis, PXHCIINTRPTR ip)
2180{
2181 RTGCPHYS GCPhysErste;
2182 XHCI_ERSTE entry;
2183
2184 Assert(ip->erst_idx < ip->erstsz);
2185 GCPhysErste = ip->erstba + ip->erst_idx * sizeof(XHCI_ERSTE);
2186 PDMDevHlpPCIPhysReadMeta(pDevIns, GCPhysErste, &entry, sizeof(entry));
2187
2188 /*
2189 * 6.5 claims values in 16-4096 range are valid, but does not say what
2190 * happens for values outside of that range...
2191 */
2192 Assert((pThis->status & XHCI_STATUS_HCH) || (entry.size >= 16 && entry.size <= 4096));
2193
2194 /* Cache the entry data internally. */
2195 ip->erep = entry.addr & pThis->erst_addr_mask;
2196 ip->trb_count = entry.size;
2197 Log(("Fetched ERST Entry at %RGp: %u entries at %RGp\n", GCPhysErste, ip->trb_count, ip->erep));
2198}
2199
2200/**
2201 * Set the interrupter's IP and EHB bits and trigger an interrupt if required.
2202 *
2203 * @param pDevIns The PDM device instance.
2204 * @param pThis Pointer to the xHCI state.
2205 * @param ip Pointer to the interrupter structure.
2206 *
2207 */
2208static void xhciSetIntr(PPDMDEVINS pDevIns, PXHCI pThis, PXHCIINTRPTR ip)
2209{
2210 Assert(pThis && ip);
2211 LogFlowFunc(("old IP: %u\n", !!(ip->iman & XHCI_IMAN_IP)));
2212
2213 if (!(ip->iman & XHCI_IMAN_IP))
2214 {
2215 /// @todo assert that we own the interrupter lock
2216 ASMAtomicOrU32(&pThis->status, XHCI_STATUS_EINT);
2217 ASMAtomicOrU64(&ip->erdp, XHCI_ERDP_EHB);
2218 ASMAtomicOrU32(&ip->iman, XHCI_IMAN_IP);
2219 if ((ip->iman & XHCI_IMAN_IE) && (pThis->cmd & XHCI_CMD_INTE))
2220 {
2221#ifdef XHCI_ERROR_INJECTION
2222 if (pThis->fDropIntrHw)
2223 {
2224 pThis->fDropIntrHw = false;
2225 ASMAtomicAndU32(&ip->iman, ~XHCI_IMAN_IP);
2226 }
2227 else
2228#endif
2229 {
2230 Log2(("Triggering interrupt on interrupter %u\n", ip->index));
2231 PDMDevHlpPCISetIrq(pDevIns, 0, PDM_IRQ_LEVEL_HIGH);
2232 STAM_COUNTER_INC(&pThis->StatIntrsSet);
2233 }
2234 }
2235 else
2236 {
2237 Log2(("Not triggering interrupt on interrupter %u (interrupts disabled)\n", ip->index));
2238 STAM_COUNTER_INC(&pThis->StatIntrsNotSet);
2239 }
2240
2241 /* If MSI/MSI-X is in use, the IP bit is immediately cleared again. */
2242 if (xhciIsMSIEnabled(pDevIns->apPciDevs[0]))
2243 ASMAtomicAndU32(&ip->iman, ~XHCI_IMAN_IP);
2244 }
2245}
2246
2247#ifdef IN_RING3
2248
2249/**
2250 * Set the interrupter's IPE bit. If this causes a 0->1 transition, an
2251 * interrupt may be triggered.
2252 *
2253 * @param pDevIns The PDM device instance.
2254 * @param pThis Pointer to the xHCI state.
2255 * @param ip Pointer to the interrupter structure.
2256 */
2257static void xhciR3SetIntrPending(PPDMDEVINS pDevIns, PXHCI pThis, PXHCIINTRPTR ip)
2258{
2259 uint16_t imodc = (ip->imod >> XHCI_IMOD_IMODC_SHIFT) & XHCI_IMOD_IMODC_MASK;
2260
2261 Assert(pThis && ip);
2262 LogFlowFunc(("old IPE: %u, IMODC: %u, EREP: %RGp, EHB: %u\n", ip->ipe, imodc, (RTGCPHYS)ip->erep, !!(ip->erdp & XHCI_ERDP_EHB)));
2263 STAM_COUNTER_INC(&pThis->StatIntrsPending);
2264
2265 if (!ip->ipe)
2266 {
2267#ifdef XHCI_ERROR_INJECTION
2268 if (pThis->fDropIntrIpe)
2269 {
2270 pThis->fDropIntrIpe = false;
2271 }
2272 else
2273#endif
2274 {
2275 ip->ipe = true;
2276 if (!(ip->erdp & XHCI_ERDP_EHB) && (imodc == 0))
2277 xhciSetIntr(pDevIns, pThis, ip);
2278 }
2279 }
2280}
2281
2282
2283/**
2284 * Check if there is space available for writing at least two events on the
2285 * event ring. See 4.9.4 for the state machine (right hand side of diagram).
2286 * If there's only room for one event, the Event Ring Full TRB will need to
2287 * be written out, hence the ring is considered full.
2288 *
2289 * @returns True if space is available, false otherwise.
2290 * @param pDevIns The PDM device instance.
2291 * @param pThis Pointer to the xHCI state.
2292 * @param pIntr Pointer to the interrupter structure.
2293 */
2294static bool xhciR3IsEvtRingFull(PPDMDEVINS pDevIns, PXHCI pThis, PXHCIINTRPTR pIntr)
2295{
2296 uint64_t next_ptr;
2297 uint64_t erdp = pIntr->erdp & XHCI_ERDP_ADDR_MASK;
2298
2299 if (pIntr->trb_count > 1)
2300 {
2301 /* Check the current segment. */
2302 next_ptr = pIntr->erep + sizeof(XHCI_EVENT_TRB);
2303 }
2304 else
2305 {
2306 uint16_t erst_idx;
2307 XHCI_ERSTE entry;
2308 RTGCPHYS GCPhysErste;
2309
2310 /* Need to check the next segment. */
2311 erst_idx = pIntr->erst_idx + 1;
2312 if (erst_idx == pIntr->erstsz)
2313 erst_idx = 0;
2314 GCPhysErste = pIntr->erstba + erst_idx * sizeof(XHCI_ERSTE);
2315 PDMDevHlpPCIPhysReadMeta(pDevIns, GCPhysErste, &entry, sizeof(entry));
2316 next_ptr = entry.addr & pThis->erst_addr_mask;
2317 }
2318
2319 /// @todo We'll have to remember somewhere that the ring is full
2320 return erdp == next_ptr;
2321}
2322
2323/**
2324 * Write an event to the given Event Ring. This implements a good chunk of
2325 * the event ring state machine in section 4.9.4 of the xHCI spec.
2326 *
2327 * @returns VBox status code. Error if event could not be enqueued.
2328 * @param pDevIns The PDM device instance.
2329 * @param pThis Pointer to the xHCI state.
2330 * @param pEvent Pointer to the Event TRB to be enqueued.
2331 * @param iIntr Index of the interrupter to write to.
2332 * @param fBlockInt Set if interrupt should be blocked (BEI bit).
2333 */
2334static int xhciR3WriteEvent(PPDMDEVINS pDevIns, PXHCI pThis, XHCI_EVENT_TRB *pEvent, unsigned iIntr, bool fBlockInt)
2335{
2336 PXHCIINTRPTR pIntr;
2337 int rc = VINF_SUCCESS;
2338
2339 LogFlowFunc(("Interrupter: %u\n", iIntr));
2340
2341 /* If the HC isn't running, events can not be generated. However,
2342 * especially port change events can be triggered at any time. We just
2343 * drop them here -- it's often not an error condition.
2344 */
2345 if (pThis->cmd & XHCI_CMD_RS)
2346 {
2347 STAM_COUNTER_INC(&pThis->StatEventsWritten);
2348 Assert(iIntr < XHCI_NINTR); /* Supplied by guest, potentially invalid. */
2349 pIntr = &pThis->aInterrupters[iIntr & XHCI_INTR_MASK];
2350
2351 /*
2352 * If the interrupter/event ring isn't in a sane state, just
2353 * give up and report Host Controller Error (HCE).
2354 */
2355 // pIntr->erst_idx
2356
2357 int const rcLock = PDMDevHlpCritSectEnter(pDevIns, &pIntr->lock, VERR_IGNORED); /* R3 only, no rcBusy. */
2358 PDM_CRITSECT_RELEASE_ASSERT_RC_DEV(pDevIns, &pIntr->lock, rcLock); /* eventually, most call chains ignore the status. */
2359
2360 if (xhciR3IsEvtRingFull(pDevIns, pThis, pIntr))
2361 {
2362 LogRel(("xHCI: Event ring full!\n"));
2363 }
2364
2365 /* Set the TRB's Cycle bit as appropriate. */
2366 pEvent->gen.cycle = pIntr->evtr_pcs;
2367
2368 /* Write out the TRB and advance the EREP. */
2369 /// @todo This either has to be atomic from the guest's POV or the cycle bit needs to be toggled last!!
2370 PDMDevHlpPCIPhysWriteMeta(pDevIns, pIntr->erep, pEvent, sizeof(*pEvent));
2371 pIntr->erep += sizeof(*pEvent);
2372 --pIntr->trb_count;
2373
2374 /* Advance to the next ERST entry if necessary. */
2375 if (pIntr->trb_count == 0)
2376 {
2377 ++pIntr->erst_idx;
2378 /* If necessary, roll over back to the beginning. */
2379 if (pIntr->erst_idx == pIntr->erstsz)
2380 {
2381 pIntr->erst_idx = 0;
2382 pIntr->evtr_pcs = !pIntr->evtr_pcs;
2383 }
2384 xhciFetchErstEntry(pDevIns, pThis, pIntr);
2385 }
2386
2387 /* Set the IPE bit unless interrupts are blocked. */
2388 if (!fBlockInt)
2389 xhciR3SetIntrPending(pDevIns, pThis, pIntr);
2390
2391 PDMDevHlpCritSectLeave(pDevIns, &pIntr->lock);
2392 }
2393 else
2394 {
2395 STAM_COUNTER_INC(&pThis->StatEventsDropped);
2396 Log(("Event dropped because HC is not running.\n"));
2397 }
2398
2399 return rc;
2400}
2401
2402
2403/**
2404 * Post a port change TRB to an Event Ring.
2405 */
2406static int xhciR3GenPortChgEvent(PPDMDEVINS pDevIns, PXHCI pThis, uint8_t uPort)
2407{
2408 XHCI_EVENT_TRB ed; /* Event Descriptor */
2409 LogFlowFunc(("Port ID: %u\n", uPort));
2410
2411 /*
2412 * Devices can be "physically" attached/detached regardless of whether
2413 * the HC is running or not, but the port status change events can only
2414 * be generated when R/S is set; xhciR3WriteEvent() takes care of that.
2415 */
2416 RT_ZERO(ed);
2417 ed.psce.cc = XHCI_TCC_SUCCESS;
2418 ed.psce.port_id = uPort;
2419 ed.psce.type = XHCI_TRB_PORT_SC;
2420 return xhciR3WriteEvent(pDevIns, pThis, &ed, XHCI_PRIMARY_INTERRUPTER, false);
2421}
2422
2423
2424/**
2425 * Post a command completion TRB to an Event Ring.
2426 */
2427static int xhciR3PostCmdCompletion(PPDMDEVINS pDevIns, PXHCI pThis, unsigned cc, unsigned uSlotID)
2428{
2429 XHCI_EVENT_TRB ed; /* Event Descriptor */
2430 LogFlowFunc(("Cmd @ %RGp, Completion Code: %u (%s), Slot ID: %u\n", (RTGCPHYS)pThis->cmdr_dqp, cc,
2431 cc < RT_ELEMENTS(g_apszCmplCodes) ? g_apszCmplCodes[cc] : "WHAT?!!", uSlotID));
2432
2433 /* The Command Ring dequeue pointer still holds the address of the current
2434 * command TRB. It is written to the completion event TRB as the command
2435 * TRB pointer.
2436 */
2437 RT_ZERO(ed);
2438 ed.cce.trb_ptr = pThis->cmdr_dqp;
2439 ed.cce.cc = cc;
2440 ed.cce.type = XHCI_TRB_CMD_CMPL;
2441 ed.cce.slot_id = uSlotID;
2442 return xhciR3WriteEvent(pDevIns, pThis, &ed, XHCI_PRIMARY_INTERRUPTER, false);
2443}
2444
2445
2446/**
2447 * Post a transfer event TRB to an Event Ring.
2448 */
2449static int xhciR3PostXferEvent(PPDMDEVINS pDevIns, PXHCI pThis, unsigned uIntTgt, unsigned uXferLen, unsigned cc,
2450 unsigned uSlotID, unsigned uEpDCI, uint64_t uEvtData, bool fBlockInt, bool fEvent)
2451{
2452 XHCI_EVENT_TRB ed; /* Event Descriptor */
2453 LogFlowFunc(("Xfer @ %RGp, Completion Code: %u (%s), Slot ID=%u DCI=%u Target=%u EvtData=%RX64 XfrLen=%u BEI=%u ED=%u\n",
2454 (RTGCPHYS)pThis->cmdr_dqp, cc, cc < RT_ELEMENTS(g_apszCmplCodes) ? g_apszCmplCodes[cc] : "WHAT?!!",
2455 uSlotID, uEpDCI, uIntTgt, uEvtData, uXferLen, fBlockInt, fEvent));
2456
2457 /* A transfer event may be either generated by TRB completion (in case
2458 * fEvent=false) or by a special transfer event TRB (fEvent=true). In
2459 * either case, interrupts may be suppressed.
2460 */
2461 RT_ZERO(ed);
2462 ed.te.trb_ptr = uEvtData;
2463 ed.te.xfr_len = uXferLen;
2464 ed.te.cc = cc;
2465 ed.te.ed = fEvent;
2466 ed.te.type = XHCI_TRB_XFER;
2467 ed.te.ep_id = uEpDCI;
2468 ed.te.slot_id = uSlotID;
2469 return xhciR3WriteEvent(pDevIns, pThis, &ed, uIntTgt, fBlockInt); /* Sets the cycle bit, too. */
2470}
2471
2472
2473static int xhciR3FindRhDevBySlot(PPDMDEVINS pDevIns, PXHCI pThis, PXHCICC pThisCC, uint8_t uSlotID, PXHCIROOTHUBR3 *ppRh, uint32_t *puPort)
2474{
2475 XHCI_SLOT_CTX slot_ctx;
2476 PXHCIROOTHUBR3 pRh;
2477 unsigned iPort;
2478 int rc;
2479
2480 /// @todo Do any of these need to be release assertions?
2481 Assert(uSlotID <= RT_ELEMENTS(pThis->aSlotState));
2482 Assert(pThis->aSlotState[ID_TO_IDX(uSlotID)] > XHCI_DEVSLOT_EMPTY);
2483
2484 /* Load the slot context. */
2485 xhciR3FetchDevCtx(pDevIns, pThis, uSlotID, 0, &slot_ctx);
2486
2487 /* The port ID is stored in the slot context. */
2488 iPort = ID_TO_IDX(slot_ctx.rh_port);
2489 if (iPort < XHCI_NDP_CFG(pThis))
2490 {
2491 /* Find the corresponding root hub. */
2492 pRh = GET_PORT_PRH(pThisCC, iPort);
2493 Assert(pRh);
2494
2495 /* And the device; if the device was ripped out fAttached will be false. */
2496 if (pThisCC->aPorts[iPort].fAttached)
2497 {
2498 /* Provide the information the caller asked for. */
2499 if (ppRh)
2500 *ppRh = pRh;
2501 if (puPort)
2502 *puPort = GET_VUSB_PORT_FROM_XHCI_PORT(pRh, iPort);
2503 rc = VINF_SUCCESS;
2504 }
2505 else
2506 {
2507 LogFunc(("No device attached (port index %u)!\n", iPort));
2508 rc = VERR_VUSB_DEVICE_NOT_ATTACHED;
2509 }
2510 }
2511 else
2512 {
2513 LogFunc(("Port out of range (index %u)!\n", iPort));
2514 rc = VERR_INVALID_PARAMETER;
2515 }
2516 return rc;
2517}
2518
2519
2520static void xhciR3EndlessTrbError(PPDMDEVINS pDevIns, PXHCI pThis)
2521{
2522 /* Clear the R/S bit and indicate controller error. */
2523 ASMAtomicAndU32(&pThis->cmd, ~XHCI_CMD_RS);
2524 ASMAtomicOrU32(&pThis->status, XHCI_STATUS_HCE);
2525
2526 /* Ensure that XHCI_STATUS_HCH gets set by the worker thread. */
2527 xhciKickWorker(pDevIns, pThis, XHCI_JOB_XFER_DONE, 0);
2528
2529 LogRelMax(10, ("xHCI: Attempted to process too many TRBs, stopping xHC!\n"));
2530}
2531
2532/**
2533 * TRB walker callback prototype.
2534 *
2535 * @returns true if walking should continue.
2536 * @returns false if walking should be terminated.
2537 * @param pDevIns The device instance.
2538 * @param pThis The xHCI device state.
2539 * @param pXferTRB Pointer to the transfer TRB to handle.
2540 * @param GCPhysXfrTRB Physical address of the TRB.
2541 * @param pvContext User-defined walk context.
2542 * @remarks We don't need to use DECLCALLBACKPTR here, since all users are in
2543 * the same source file, but having the functions marked with
2544 * DECLCALLBACK helps readability.
2545 */
2546typedef DECLCALLBACKPTR(bool, PFNTRBWALKCB,(PPDMDEVINS pDevIns, PXHCI pThis, const XHCI_XFER_TRB *pXferTRB,
2547 RTGCPHYS GCPhysXfrTRB, void *pvContext));
2548
2549
2550/**
2551 * Walk a chain of TRBs which comprise a single TD.
2552 *
2553 * This is something we need to do potentially more than once when submitting a
2554 * URB and then often again when completing the URB. Note that the walker does
2555 * not update the endpoint state (TRDP/TREP/DCS) so that it can be re-run
2556 * multiple times.
2557 *
2558 * @param pDevIns The device instance.
2559 * @param pThis The xHCI device state.
2560 * @param uTRP Initial TR pointer and DCS.
2561 * @param pfnCbk Callback routine.
2562 * @param pvContext User-defined walk context.
2563 * @param pTREP Pointer to storage for final TR Enqueue Pointer/DCS.
2564 */
2565static int xhciR3WalkXferTrbChain(PPDMDEVINS pDevIns, PXHCI pThis, uint64_t uTRP,
2566 PFNTRBWALKCB pfnCbk, void *pvContext, uint64_t *pTREP)
2567{
2568 RTGCPHYS GCPhysXfrTRB;
2569 uint64_t uTREP;
2570 XHCI_XFER_TRB XferTRB;
2571 bool fContinue = true;
2572 bool dcs;
2573 int rc = VINF_SUCCESS;
2574 unsigned cTrbs = 0;
2575
2576 AssertPtr(pvContext);
2577 AssertPtr(pTREP);
2578 Assert(uTRP);
2579
2580 /* Find the transfer TRB address and the DCS. */
2581 GCPhysXfrTRB = uTRP & XHCI_TRDP_ADDR_MASK;
2582 dcs = !!(uTRP & XHCI_TRDP_DCS_MASK); /* MSC upgrades bool to signed something when comparing with a uint8_t:1. */
2583 LogFlowFunc(("Walking Transfer Ring, TREP:%RGp DCS=%u\n", GCPhysXfrTRB, dcs));
2584
2585 do {
2586 /* Fetch the transfer TRB. */
2587 PDMDevHlpPCIPhysReadMeta(pDevIns, GCPhysXfrTRB, &XferTRB, sizeof(XferTRB));
2588
2589 if ((bool)XferTRB.gen.cycle == dcs)
2590 {
2591 Log2(("Walking TRB@%RGp, type %u (%s) %u bytes ENT=%u ISP=%u NS=%u CH=%u IOC=%u IDT=%u\n", GCPhysXfrTRB, XferTRB.gen.type,
2592 XferTRB.gen.type < RT_ELEMENTS(g_apszTrbNames) ? g_apszTrbNames[XferTRB.gen.type] : "WHAT?!!",
2593 XferTRB.gen.xfr_len, XferTRB.gen.ent, XferTRB.gen.isp, XferTRB.gen.ns, XferTRB.gen.ch, XferTRB.gen.ioc, XferTRB.gen.idt));
2594
2595 /* DCS matches, the TRB is ours to process. */
2596 switch (XferTRB.gen.type) {
2597 case XHCI_TRB_LINK:
2598 Log2(("Link intra-TD: Ptr=%RGp IOC=%u TC=%u CH=%u\n", XferTRB.link.rseg_ptr, XferTRB.link.ioc, XferTRB.link.toggle, XferTRB.link.chain));
2599 Assert(XferTRB.link.chain);
2600 /* Do not update the actual TRDP/TREP and DCS yet, just the temporary images. */
2601 GCPhysXfrTRB = XferTRB.link.rseg_ptr & XHCI_TRDP_ADDR_MASK;
2602 if (XferTRB.link.toggle)
2603 dcs = !dcs;
2604 Assert(!XferTRB.link.ioc); /// @todo Needs to be reported.
2605 break;
2606 case XHCI_TRB_NORMAL:
2607 case XHCI_TRB_ISOCH:
2608 case XHCI_TRB_SETUP_STG:
2609 case XHCI_TRB_DATA_STG:
2610 case XHCI_TRB_STATUS_STG:
2611 case XHCI_TRB_EVT_DATA:
2612 fContinue = pfnCbk(pDevIns, pThis, &XferTRB, GCPhysXfrTRB, pvContext);
2613 GCPhysXfrTRB += sizeof(XferTRB);
2614 break;
2615 default:
2616 /* NB: No-op TRBs are not allowed within TDs (4.11.7). */
2617 Log(("Bad TRB type %u found within TD!!\n", XferTRB.gen.type));
2618 fContinue = false;
2619 /// @todo Stop EP etc.?
2620 }
2621 }
2622 else
2623 {
2624 /* We don't have a complete TD. Interesting times. */
2625 Log2(("DCS mismatch, no more TRBs available.\n"));
2626 fContinue = false;
2627 rc = VERR_TRY_AGAIN;
2628 }
2629
2630 /* Kill the xHC if the TRB list has no end in sight. */
2631 if (++cTrbs > XHCI_MAX_NUM_TRBS)
2632 {
2633 /* Stop the xHC with an error. */
2634 xhciR3EndlessTrbError(pDevIns, pThis);
2635
2636 /* Get out of the loop. */
2637 fContinue = false;
2638 rc = VERR_NOT_SUPPORTED; /* No good error code really... */
2639 }
2640 } while (fContinue);
2641
2642 /* Inform caller of the new TR Enqueue Pointer/DCS (not necessarily changed). */
2643 Assert(!(GCPhysXfrTRB & ~XHCI_TRDP_ADDR_MASK));
2644 uTREP = GCPhysXfrTRB | (unsigned)dcs;
2645 Log2(("Final TRP after walk: %RGp\n", uTREP));
2646 *pTREP = uTREP;
2647
2648 return rc;
2649}
2650
2651
2652/** Context for probing TD size. */
2653typedef struct {
2654 uint32_t uXferLen;
2655 uint32_t cTRB;
2656 uint32_t uXfrLenLastED;
2657 uint32_t cTRBLastED;
2658} XHCI_CTX_XFER_PROBE;
2659
2660
2661/** Context for submitting 'out' TDs. */
2662typedef struct {
2663 PVUSBURB pUrb;
2664 uint32_t uXferPos;
2665 unsigned cTRB;
2666} XHCI_CTX_XFER_SUBMIT;
2667
2668
2669/** Context for completing TDs. */
2670typedef struct {
2671 PVUSBURB pUrb;
2672 uint32_t uXferPos;
2673 uint32_t uXferLeft;
2674 unsigned cTRB;
2675 uint32_t uEDTLA : 24;
2676 uint32_t uLastCC : 8;
2677 uint8_t uSlotID;
2678 uint8_t uEpDCI;
2679 bool fMaxCount;
2680} XHCI_CTX_XFER_COMPLETE;
2681
2682
2683/** Context for building isochronous URBs. */
2684typedef struct {
2685 PVUSBURB pUrb;
2686 unsigned iPkt;
2687 uint32_t offCur;
2688 uint64_t uInitTREP;
2689 bool fSubmitFailed;
2690} XHCI_CTX_ISOCH;
2691
2692
2693/**
2694 * @callback_method_impl{PFNTRBWALKCB,
2695 * Probe a TD and figure out how big it is so that a URB can be allocated to back it.}
2696 */
2697static DECLCALLBACK(bool)
2698xhciR3WalkDataTRBsProbe(PPDMDEVINS pDevIns, PXHCI pThis, const XHCI_XFER_TRB *pXferTRB, RTGCPHYS GCPhysXfrTRB, void *pvContext)
2699{
2700 RT_NOREF(pDevIns, pThis, GCPhysXfrTRB);
2701 XHCI_CTX_XFER_PROBE *pCtx = (XHCI_CTX_XFER_PROBE *)pvContext;
2702
2703 pCtx->cTRB++;
2704
2705 /* Only consider TRBs which transfer data. */
2706 switch (pXferTRB->gen.type)
2707 {
2708 case XHCI_TRB_NORMAL:
2709 case XHCI_TRB_ISOCH:
2710 case XHCI_TRB_SETUP_STG:
2711 case XHCI_TRB_DATA_STG:
2712 case XHCI_TRB_STATUS_STG:
2713 pCtx->uXferLen += pXferTRB->norm.xfr_len;
2714 if (RT_UNLIKELY(pCtx->uXferLen > XHCI_MAX_TD_SIZE))
2715 {
2716 /* NB: We let the TD size get a bit past the max so that we don't lose anything,
2717 * but the EDTLA will wrap around.
2718 */
2719 LogRelMax(10, ("xHCI: TD size (%u) too big, not continuing!\n", pCtx->uXferLen));
2720 return false;
2721 }
2722 break;
2723 case XHCI_TRB_EVT_DATA:
2724 /* Remember where the last seen Event Data TRB was. */
2725 pCtx->cTRBLastED = pCtx->cTRB;
2726 pCtx->uXfrLenLastED = pCtx->uXferLen;
2727 break;
2728 default: /* Could be a link TRB, too. */
2729 break;
2730 }
2731
2732 return pXferTRB->gen.ch;
2733}
2734
2735
2736/**
2737 * @callback_method_impl{PFNTRBWALKCB,
2738 * Copy data from a TD (TRB chain) into the corresponding TD. OUT direction only.}
2739 */
2740static DECLCALLBACK(bool)
2741xhciR3WalkDataTRBsSubmit(PPDMDEVINS pDevIns, PXHCI pThis, const XHCI_XFER_TRB *pXferTRB, RTGCPHYS GCPhysXfrTRB, void *pvContext)
2742{
2743 RT_NOREF(pThis, GCPhysXfrTRB);
2744 XHCI_CTX_XFER_SUBMIT *pCtx = (XHCI_CTX_XFER_SUBMIT *)pvContext;
2745 uint32_t uXferLen = pXferTRB->norm.xfr_len;
2746
2747
2748 /* Only consider TRBs which transfer data. */
2749 switch (pXferTRB->gen.type)
2750 {
2751 case XHCI_TRB_NORMAL:
2752 case XHCI_TRB_ISOCH:
2753 case XHCI_TRB_SETUP_STG:
2754 case XHCI_TRB_DATA_STG:
2755 case XHCI_TRB_STATUS_STG:
2756 /* NB: Transfer length may be zero! */
2757 /// @todo explain/verify abuse of various TRB types here (data stage mapped to normal etc.).
2758 if (uXferLen)
2759 {
2760 /* Sanity check for broken guests (TRBs may have changed since probing). */
2761 if (pCtx->uXferPos + uXferLen <= pCtx->pUrb->cbData)
2762 {
2763 /* Data might be immediate or elsewhere in memory. */
2764 if (pXferTRB->norm.idt)
2765 {
2766 /* If an immediate data TRB claims there's more than 8 bytes, we have a problem. */
2767 if (uXferLen > 8)
2768 {
2769 LogRelMax(10, ("xHCI: Immediate data TRB length %u bytes, ignoring!\n", uXferLen));
2770 return false; /* Stop walking the chain immediately. */
2771 }
2772
2773 Assert(uXferLen >= 1 && uXferLen <= 8);
2774 Log2(("Copying %u bytes to URB offset %u (immediate data)\n", uXferLen, pCtx->uXferPos));
2775 memcpy(pCtx->pUrb->abData + pCtx->uXferPos, pXferTRB, uXferLen);
2776 }
2777 else
2778 {
2779 PDMDevHlpPCIPhysReadUser(pDevIns, pXferTRB->norm.data_ptr, pCtx->pUrb->abData + pCtx->uXferPos, uXferLen);
2780 Log2(("Copying %u bytes to URB offset %u (from %RGp)\n", uXferLen, pCtx->uXferPos, pXferTRB->norm.data_ptr));
2781 }
2782 pCtx->uXferPos += uXferLen;
2783 }
2784 else
2785 {
2786 LogRelMax(10, ("xHCI: Attempted to submit too much data, ignoring!\n"));
2787 return false; /* Stop walking the chain immediately. */
2788 }
2789
2790 }
2791 break;
2792 default: /* Could be an event or status stage TRB, too. */
2793 break;
2794 }
2795 pCtx->cTRB++;
2796
2797 /// @todo Maybe have to make certain that the number of probed TRBs matches? Potentially
2798 /// by the time TRBs get submitted, there might be more of them available if the TD was
2799 /// initially not fully written by HCD.
2800
2801 return pXferTRB->gen.ch;
2802}
2803
2804
2805/**
2806 * Perform URB completion processing.
2807 *
2808 * Figure out how much data was really transferred, post events if required, and
2809 * for IN transfers, copy data from the URB.
2810 *
2811 * @callback_method_impl{PFNTRBWALKCB}
2812 */
2813static DECLCALLBACK(bool)
2814xhciR3WalkDataTRBsComplete(PPDMDEVINS pDevIns, PXHCI pThis, const XHCI_XFER_TRB *pXferTRB, RTGCPHYS GCPhysXfrTRB, void *pvContext)
2815{
2816 XHCI_CTX_XFER_COMPLETE *pCtx = (XHCI_CTX_XFER_COMPLETE *)pvContext;
2817 unsigned uXferLen;
2818 unsigned uResidue;
2819 uint8_t cc;
2820 bool fKeepGoing = true;
2821
2822 switch (pXferTRB->gen.type)
2823 {
2824 case XHCI_TRB_NORMAL:
2825 case XHCI_TRB_ISOCH:
2826 case XHCI_TRB_SETUP_STG:
2827 case XHCI_TRB_DATA_STG: /// @todo document abuse; esp. check BEI bit
2828 case XHCI_TRB_STATUS_STG:
2829 /* Assume successful transfer. */
2830 uXferLen = pXferTRB->norm.xfr_len;
2831 cc = XHCI_TCC_SUCCESS;
2832
2833 /* If there was a short packet, handle it accordingly. */
2834 if (pCtx->uXferLeft < uXferLen)
2835 {
2836 /* The completion code is set regardless of IOC/ISP. It may be
2837 * reported later via an Event Data TRB (4.10.1.1)
2838 */
2839 uXferLen = pCtx->uXferLeft;
2840 cc = XHCI_TCC_SHORT_PKT;
2841 }
2842
2843 if (pCtx->pUrb->enmDir == VUSBDIRECTION_IN)
2844 {
2845 Assert(!pXferTRB->norm.idt);
2846
2847 /* NB: Transfer length may be zero! */
2848 if (uXferLen)
2849 {
2850 if (uXferLen <= pCtx->uXferLeft)
2851 {
2852 Log2(("Writing %u bytes to %RGp from URB offset %u (TRB@%RGp)\n", uXferLen, pXferTRB->norm.data_ptr, pCtx->uXferPos, GCPhysXfrTRB));
2853 PDMDevHlpPCIPhysWriteUser(pDevIns, pXferTRB->norm.data_ptr, pCtx->pUrb->abData + pCtx->uXferPos, uXferLen);
2854 }
2855 else
2856 {
2857 LogRelMax(10, ("xHCI: Attempted to read too much data, ignoring!\n"));
2858 }
2859 }
2860 }
2861
2862 /* Update position within TD. */
2863 pCtx->uXferLeft -= uXferLen;
2864 pCtx->uXferPos += uXferLen;
2865 Log2(("Current uXferLeft=%u, uXferPos=%u (length was %u)\n", pCtx->uXferLeft, pCtx->uXferPos, uXferLen));
2866
2867 /* Keep track of the EDTLA and last completion status. */
2868 pCtx->uEDTLA += uXferLen; /* May wrap around! */
2869 pCtx->uLastCC = cc;
2870
2871 /* Report events as required. */
2872 uResidue = pXferTRB->norm.xfr_len - uXferLen;
2873 if (pXferTRB->norm.ioc || (pXferTRB->norm.isp && uResidue))
2874 {
2875 xhciR3PostXferEvent(pDevIns, pThis, pXferTRB->norm.int_tgt, uResidue, cc,
2876 pCtx->uSlotID, pCtx->uEpDCI, GCPhysXfrTRB, pXferTRB->norm.bei, false);
2877 }
2878 break;
2879 case XHCI_TRB_EVT_DATA:
2880 if (pXferTRB->evtd.ioc)
2881 {
2882 xhciR3PostXferEvent(pDevIns, pThis, pXferTRB->evtd.int_tgt, pCtx->uEDTLA, pCtx->uLastCC,
2883 pCtx->uSlotID, pCtx->uEpDCI, pXferTRB->evtd.evt_data, pXferTRB->evtd.bei, true);
2884 }
2885 /* Clear the EDTLA. */
2886 pCtx->uEDTLA = 0;
2887 break;
2888 default:
2889 AssertMsgFailed(("%#x\n", pXferTRB->gen.type));
2890 break;
2891 }
2892
2893 pCtx->cTRB--;
2894 /* For TD fragments, enforce the maximum count, but only as long as the transfer
2895 * is successful. In case of error we have to complete the entire TD! */
2896 if (!pCtx->cTRB && pCtx->fMaxCount && pCtx->uLastCC == XHCI_TCC_SUCCESS)
2897 {
2898 Log2(("Stopping at the end of TD Fragment.\n"));
2899 fKeepGoing = false;
2900 }
2901
2902 /* NB: We currently do not enforce that the number of TRBs can't change between
2903 * submission and completion. If we do, we'll have to store it somewhere for
2904 * isochronous URBs.
2905 */
2906 return pXferTRB->gen.ch && fKeepGoing;
2907}
2908
2909/**
2910 * Process (consume) non-data TRBs on a transfer ring. This function
2911 * completes TRBs which do not have any URB associated with them. Only
2912 * used with running endpoints. Usable regardless of whether there are
2913 * in-flight TRBs or not. Returns the next TRB and its address to the
2914 * caller. May modify the endpoint context!
2915 *
2916 * @param pDevIns The device instance.
2917 * @param pThis The xHCI device state.
2918 * @param uSlotID The slot corresponding to this USB device.
2919 * @param uEpDCI The DCI of this endpoint.
2920 * @param pEpCtx Endpoint context. May be modified.
2921 * @param pXfer Storage for returning the next TRB to caller.
2922 * @param pGCPhys Storage for returning the physical address of TRB.
2923 */
2924static int xhciR3ConsumeNonXferTRBs(PPDMDEVINS pDevIns, PXHCI pThis, uint8_t uSlotID, uint8_t uEpDCI,
2925 XHCI_EP_CTX *pEpCtx, XHCI_XFER_TRB *pXfer, RTGCPHYS *pGCPhys)
2926{
2927 XHCI_XFER_TRB xfer;
2928 RTGCPHYS GCPhysXfrTRB = 0;
2929 bool dcs;
2930 bool fInFlight;
2931 bool fContinue = true;
2932 unsigned cTrbs = 0;
2933
2934 LogFlowFunc(("Slot ID: %u, EP DCI %u\n", uSlotID, uEpDCI));
2935 Assert(uSlotID > 0);
2936 Assert(uSlotID <= XHCI_NDS);
2937
2938 Assert(pEpCtx->ep_state == XHCI_EPST_RUNNING);
2939 do
2940 {
2941 /* Find the transfer TRB address. */
2942 GCPhysXfrTRB = pEpCtx->trdp & XHCI_TRDP_ADDR_MASK;
2943 dcs = !!(pEpCtx->trdp & XHCI_TRDP_DCS_MASK);
2944
2945 /* Determine whether there are any in-flight TRBs or not. This affects TREP
2946 * processing -- when nothing is in flight, we have to move both TREP and TRDP;
2947 * otherwise only the TRDP must be updated.
2948 */
2949 fInFlight = pEpCtx->trep != pEpCtx->trdp;
2950 LogFlowFunc(("Skipping non-data TRBs, TREP:%RGp, TRDP:%RGp, in-flight: %RTbool\n", pEpCtx->trep, pEpCtx->trdp, fInFlight));
2951
2952 /* Fetch the transfer TRB. */
2953 PDMDevHlpPCIPhysReadMeta(pDevIns, GCPhysXfrTRB, &xfer, sizeof(xfer));
2954
2955 /* Make sure the Cycle State matches. */
2956 if ((bool)xfer.gen.cycle == dcs)
2957 {
2958 Log2(("TRB @ %RGp, type %u (%s) %u bytes ENT=%u ISP=%u NS=%u CH=%u IOC=%u IDT=%u\n", GCPhysXfrTRB, xfer.gen.type,
2959 xfer.gen.type < RT_ELEMENTS(g_apszTrbNames) ? g_apszTrbNames[xfer.gen.type] : "WHAT?!!",
2960 xfer.gen.xfr_len, xfer.gen.ent, xfer.gen.isp, xfer.gen.ns, xfer.gen.ch, xfer.gen.ioc, xfer.gen.idt));
2961
2962 switch (xfer.gen.type) {
2963 case XHCI_TRB_LINK:
2964 Log2(("Link extra-TD: Ptr=%RGp IOC=%u TC=%u CH=%u\n", xfer.link.rseg_ptr, xfer.link.ioc, xfer.link.toggle, xfer.link.chain));
2965 Assert(!xfer.link.chain);
2966 AssertCompile(XHCI_TRDP_DCS_MASK == 1); /* link.toggle is 0 or 1, can be used as XHCI_TRDP_DCS_MASK */
2967 /* Set new TRDP but leave DCS bit alone... */
2968 pEpCtx->trdp = (xfer.link.rseg_ptr & XHCI_TRDP_ADDR_MASK) | (pEpCtx->trdp & XHCI_TRDP_DCS_MASK);
2969 /* ...and flip the DCS bit if required. Then update the TREP. */
2970 pEpCtx->trdp = pEpCtx->trdp ^ xfer.link.toggle;
2971 if (!fInFlight)
2972 pEpCtx->trep = pEpCtx->trdp;
2973 if (xfer.link.ioc)
2974 xhciR3PostXferEvent(pDevIns, pThis, xfer.link.int_tgt, 0, XHCI_TCC_SUCCESS, uSlotID, uEpDCI,
2975 GCPhysXfrTRB, false, false);
2976 break;
2977 case XHCI_TRB_NOOP_XFER:
2978 Log2(("No op xfer: IOC=%u CH=%u ENT=%u\n", xfer.nop.ioc, xfer.nop.ch, xfer.nop.ent));
2979 /* A no-op transfer TRB must not be part of a chain. See 4.11.7. */
2980 Assert(!xfer.link.chain);
2981 /* Update enqueue/dequeue pointers. */
2982 pEpCtx->trdp += sizeof(XHCI_XFER_TRB);
2983 if (!fInFlight)
2984 pEpCtx->trep += sizeof(XHCI_XFER_TRB);
2985 if (xfer.nop.ioc)
2986 xhciR3PostXferEvent(pDevIns, pThis, xfer.nop.int_tgt, 0, XHCI_TCC_SUCCESS, uSlotID, uEpDCI,
2987 GCPhysXfrTRB, false, false);
2988 break;
2989 default:
2990 fContinue = false;
2991 break;
2992 }
2993 }
2994 else
2995 {
2996 LogFunc(("Transfer Ring empty\n"));
2997 fContinue = false;
2998 }
2999
3000 /* Kill the xHC if the TRB list has no end in sight. */
3001 /* NB: The limit here could perhaps be much lower because a sequence of Link
3002 * and No-op TRBs with no real work to be done would be highly suspect.
3003 */
3004 if (++cTrbs > XHCI_MAX_NUM_TRBS)
3005 {
3006 /* Stop the xHC with an error. */
3007 xhciR3EndlessTrbError(pDevIns, pThis);
3008
3009 /* Get out of the loop. */
3010 fContinue = false;
3011 }
3012 } while (fContinue);
3013
3014 /* The caller will need the next TRB. Hand it over. */
3015 Assert(GCPhysXfrTRB);
3016 *pGCPhys = GCPhysXfrTRB;
3017 *pXfer = xfer;
3018 LogFlowFunc(("Final TREP:%RGp, TRDP:%RGp GCPhysXfrTRB:%RGp\n", pEpCtx->trep, pEpCtx->trdp, GCPhysXfrTRB));
3019
3020 return VINF_SUCCESS;
3021}
3022
3023/**
3024 * Transfer completion callback routine.
3025 *
3026 * VUSB will call this when a transfer have been completed
3027 * in a one or another way.
3028 *
3029 * @param pInterface Pointer to XHCI::ROOTHUB::IRhPort.
3030 * @param pUrb Pointer to the URB in question.
3031 */
3032static DECLCALLBACK(void) xhciR3RhXferCompletion(PVUSBIROOTHUBPORT pInterface, PVUSBURB pUrb)
3033{
3034 PXHCIROOTHUBR3 pRh = RT_FROM_MEMBER(pInterface, XHCIROOTHUBR3, IRhPort);
3035 PXHCICC pThisCC = pRh->pXhciR3;
3036 PPDMDEVINS pDevIns = pThisCC->pDevIns;
3037 PXHCI pThis = PDMDEVINS_2_DATA(pDevIns, PXHCI);
3038 XHCI_SLOT_CTX slot_ctx;
3039 XHCI_EP_CTX ep_ctx;
3040 XHCI_XFER_TRB xfer;
3041 RTGCPHYS GCPhysXfrTRB;
3042 unsigned uResidue = 0;
3043 uint8_t uSlotID = pUrb->pHci->uSlotID;
3044 uint8_t cc = XHCI_TCC_SUCCESS;
3045 uint8_t uEpDCI;
3046
3047 /* Check for URBs completed synchronously as part of xHCI command execution.
3048 * The URB will have zero cTRB as it's not associated with a TD.
3049 */
3050 if (!pUrb->pHci->cTRB)
3051 {
3052 LogFlow(("%s: xhciR3RhXferCompletion: uSlotID=%u EP=%u cTRB=%d cbData=%u status=%u\n",
3053 pUrb->pszDesc, uSlotID, pUrb->EndPt, pUrb->pHci->cTRB, pUrb->cbData, pUrb->enmStatus));
3054 LogFlow(("%s: xhciR3RhXferCompletion: Completing xHCI-generated request\n", pUrb->pszDesc));
3055 return;
3056 }
3057
3058 /* If the xHC isn't running, just drop the URB right here. */
3059 if (pThis->status & XHCI_STATUS_HCH)
3060 {
3061 LogFlow(("%s: xhciR3RhXferCompletion: uSlotID=%u EP=%u cTRB=%d cbData=%u status=%u\n",
3062 pUrb->pszDesc, uSlotID, pUrb->EndPt, pUrb->pHci->cTRB, pUrb->cbData, pUrb->enmStatus));
3063 LogFlow(("%s: xhciR3RhXferCompletion: xHC halted, skipping URB completion\n", pUrb->pszDesc));
3064 return;
3065 }
3066
3067#ifdef XHCI_ERROR_INJECTION
3068 if (pThis->fDropUrb)
3069 {
3070 LogFlow(("%s: xhciR3RhXferCompletion: Error injection, dropping URB!\n", pUrb->pszDesc));
3071 pThis->fDropUrb = false;
3072 return;
3073 }
3074#endif
3075
3076 RTCritSectEnter(&pThisCC->CritSectThrd);
3077
3078 /* Convert USB endpoint address to xHCI format. */
3079 if (pUrb->EndPt)
3080 uEpDCI = pUrb->EndPt * 2 + (pUrb->enmDir == VUSBDIRECTION_IN ? 1 : 0);
3081 else
3082 uEpDCI = 1; /* EP 0 */
3083
3084 LogFlow(("%s: xhciR3RhXferCompletion: uSlotID=%u EP=%u cTRB=%d\n",
3085 pUrb->pszDesc, uSlotID, pUrb->EndPt, pUrb->pHci->cTRB));
3086 LogFlow(("%s: xhciR3RhXferCompletion: EP DCI=%u, cbData=%u status=%u\n", pUrb->pszDesc, uEpDCI, pUrb->cbData, pUrb->enmStatus));
3087
3088 /* Load the slot/endpoint contexts from guest memory. */
3089 xhciR3FetchCtxAndEp(pDevIns, pThis, uSlotID, uEpDCI, &slot_ctx, &ep_ctx);
3090
3091 /* If the EP is disabled, we don't own it so we can't complete the URB.
3092 * Leave this EP alone and drop the URB.
3093 */
3094 if (ep_ctx.ep_state != XHCI_EPST_RUNNING)
3095 {
3096 Log(("EP DCI %u not running (state %u), skipping URB completion\n", uEpDCI, ep_ctx.ep_state));
3097 RTCritSectLeave(&pThisCC->CritSectThrd);
3098 return;
3099 }
3100
3101 /* Now complete any non-transfer TRBs that might be on the transfer ring before
3102 * the TRB(s) corresponding to this URB. Preloads the TRB as a side effect.
3103 * Endpoint state now must be written back in case it was modified!
3104 */
3105 xhciR3ConsumeNonXferTRBs(pDevIns, pThis, uSlotID, uEpDCI, &ep_ctx, &xfer, &GCPhysXfrTRB);
3106
3107 /* Deal with failures which halt the EP first. */
3108 if (RT_UNLIKELY(pUrb->enmStatus != VUSBSTATUS_OK))
3109 {
3110 switch(pUrb->enmStatus)
3111 {
3112 case VUSBSTATUS_STALL:
3113 /* Halt the endpoint and inform the HCD.
3114 * NB: The TRDP is NOT advanced in case of error.
3115 */
3116 ep_ctx.ep_state = XHCI_EPST_HALTED;
3117 cc = XHCI_TCC_STALL;
3118 xhciR3PostXferEvent(pDevIns, pThis, xfer.gen.int_tgt, uResidue, cc,
3119 uSlotID, uEpDCI, GCPhysXfrTRB, false, false);
3120 break;
3121 case VUSBSTATUS_DNR:
3122 /* Halt the endpoint and inform the HCD.
3123 * NB: The TRDP is NOT advanced in case of error.
3124 */
3125 ep_ctx.ep_state = XHCI_EPST_HALTED;
3126 cc = XHCI_TCC_USB_XACT_ERR;
3127 xhciR3PostXferEvent(pDevIns, pThis, xfer.gen.int_tgt, uResidue, cc,
3128 uSlotID, uEpDCI, GCPhysXfrTRB, false, false);
3129 break;
3130 case VUSBSTATUS_CRC: /// @todo Separate status for canceling?!
3131 ep_ctx.ep_state = XHCI_EPST_HALTED;
3132 cc = XHCI_TCC_USB_XACT_ERR;
3133 xhciR3PostXferEvent(pDevIns, pThis, xfer.gen.int_tgt, uResidue, cc,
3134 uSlotID, uEpDCI, GCPhysXfrTRB, false, false);
3135
3136 /* NB: The TRDP is *not* advanced and TREP is reset. */
3137 ep_ctx.trep = ep_ctx.trdp;
3138 break;
3139 case VUSBSTATUS_DATA_OVERRUN:
3140 case VUSBSTATUS_DATA_UNDERRUN:
3141 /* Halt the endpoint and inform the HCD.
3142 * NB: The TRDP is NOT advanced in case of error.
3143 */
3144 ep_ctx.ep_state = XHCI_EPST_HALTED;
3145 cc = XHCI_TCC_DATA_BUF_ERR;
3146 xhciR3PostXferEvent(pDevIns, pThis, xfer.gen.int_tgt, uResidue, cc,
3147 uSlotID, uEpDCI, GCPhysXfrTRB, false, false);
3148 break;
3149 default:
3150 AssertMsgFailed(("Unexpected URB status %u\n", pUrb->enmStatus));
3151 }
3152
3153 if (pUrb->enmType == VUSBXFERTYPE_ISOC)
3154 STAM_COUNTER_INC(&pThis->StatErrorIsocUrbs);
3155 }
3156 else if (xfer.gen.type == XHCI_TRB_NORMAL)
3157 {
3158 XHCI_CTX_XFER_COMPLETE ctxComplete;
3159 uint64_t uTRDP;
3160
3161 ctxComplete.pUrb = pUrb;
3162 ctxComplete.uXferPos = 0;
3163 ctxComplete.uXferLeft = pUrb->cbData;
3164 ctxComplete.cTRB = pUrb->pHci->cTRB;
3165 ctxComplete.uSlotID = uSlotID;
3166 ctxComplete.uEpDCI = uEpDCI;
3167 ctxComplete.uEDTLA = 0; // Always zero at the beginning of a new TD.
3168 ctxComplete.uLastCC = cc;
3169 ctxComplete.fMaxCount = ep_ctx.ifc >= XHCI_NO_QUEUING_IN_FLIGHT;
3170 xhciR3WalkXferTrbChain(pDevIns, pThis, ep_ctx.trdp, xhciR3WalkDataTRBsComplete, &ctxComplete, &uTRDP);
3171 ep_ctx.last_cc = ctxComplete.uLastCC;
3172 ep_ctx.trdp = uTRDP;
3173
3174 if (ep_ctx.ifc >= XHCI_NO_QUEUING_IN_FLIGHT)
3175 ep_ctx.ifc -= XHCI_NO_QUEUING_IN_FLIGHT; /* TD fragment done, allow further queuing. */
3176 else
3177 ep_ctx.ifc--; /* TD done, decrement in-flight counter. */
3178 }
3179 else if (xfer.gen.type == XHCI_TRB_ISOCH)
3180 {
3181 XHCI_CTX_XFER_COMPLETE ctxComplete;
3182 uint64_t uTRDP;
3183 unsigned iPkt;
3184
3185 ctxComplete.pUrb = pUrb;
3186 ctxComplete.uSlotID = uSlotID;
3187 ctxComplete.uEpDCI = uEpDCI;
3188
3189 for (iPkt = 0; iPkt < pUrb->cIsocPkts; ++iPkt) {
3190 ctxComplete.uXferPos = pUrb->aIsocPkts[iPkt].off;
3191 ctxComplete.uXferLeft = pUrb->aIsocPkts[iPkt].cb;
3192 ctxComplete.cTRB = pUrb->pHci->cTRB;
3193 ctxComplete.uEDTLA = 0; // Zero at TD start.
3194 ctxComplete.uLastCC = cc;
3195 ctxComplete.fMaxCount = false;
3196 if (pUrb->aIsocPkts[iPkt].enmStatus != VUSBSTATUS_OK)
3197 STAM_COUNTER_INC(&pThis->StatErrorIsocPkts);
3198 xhciR3WalkXferTrbChain(pDevIns, pThis, ep_ctx.trdp, xhciR3WalkDataTRBsComplete, &ctxComplete, &uTRDP);
3199 ep_ctx.last_cc = ctxComplete.uLastCC;
3200 ep_ctx.trdp = uTRDP;
3201 xhciR3ConsumeNonXferTRBs(pDevIns, pThis, uSlotID, uEpDCI, &ep_ctx, &xfer, &GCPhysXfrTRB);
3202 }
3203 ep_ctx.ifc--; /* TD done, decrement in-flight counter. */
3204 }
3205 else if (xfer.gen.type == XHCI_TRB_SETUP_STG || xfer.gen.type == XHCI_TRB_DATA_STG || xfer.gen.type == XHCI_TRB_STATUS_STG)
3206 {
3207 XHCI_CTX_XFER_COMPLETE ctxComplete;
3208 uint64_t uTRDP;
3209
3210 ctxComplete.pUrb = pUrb;
3211 ctxComplete.uXferPos = 0;
3212 ctxComplete.uXferLeft = pUrb->cbData;
3213 ctxComplete.cTRB = pUrb->pHci->cTRB;
3214 ctxComplete.uSlotID = uSlotID;
3215 ctxComplete.uEpDCI = uEpDCI;
3216 ctxComplete.uEDTLA = 0; // Always zero at the beginning of a new TD.
3217 ctxComplete.uLastCC = cc;
3218 ctxComplete.fMaxCount = ep_ctx.ifc >= XHCI_NO_QUEUING_IN_FLIGHT;
3219 xhciR3WalkXferTrbChain(pDevIns, pThis, ep_ctx.trdp, xhciR3WalkDataTRBsComplete, &ctxComplete, &uTRDP);
3220 ep_ctx.last_cc = ctxComplete.uLastCC;
3221 ep_ctx.trdp = uTRDP;
3222 }
3223 else
3224 {
3225 AssertMsgFailed(("Unexpected TRB type %u\n", xfer.gen.type));
3226 Log2(("TRB @ %RGp, type %u unexpected!\n", GCPhysXfrTRB, xfer.gen.type));
3227 /* Advance the TRDP anyway so that the endpoint isn't completely stuck. */
3228 ep_ctx.trdp += sizeof(XHCI_XFER_TRB);
3229 }
3230
3231 /* Update the endpoint state. */
3232 xhciR3WriteBackEp(pDevIns, pThis, uSlotID, uEpDCI, &ep_ctx);
3233
3234 RTCritSectLeave(&pThisCC->CritSectThrd);
3235
3236 if (pUrb->enmStatus == VUSBSTATUS_OK)
3237 {
3238 /* Completion callback usually runs on a separate thread. Let the worker do more. */
3239 Log2(("Ring bell for slot %u, DCI %u\n", uSlotID, uEpDCI));
3240 ASMAtomicOrU32(&pThis->aBellsRung[ID_TO_IDX(uSlotID)], 1 << uEpDCI);
3241 xhciKickWorker(pDevIns, pThis, XHCI_JOB_XFER_DONE, 0);
3242 }
3243}
3244
3245
3246/**
3247 * Handle transfer errors.
3248 *
3249 * VUSB calls this when a transfer attempt failed. This function will respond
3250 * indicating whether to retry or complete the URB with failure.
3251 *
3252 * @returns true if the URB should be retired.
3253 * @returns false if the URB should be re-tried.
3254 * @param pInterface Pointer to XHCI::ROOTHUB::IRhPort.
3255 * @param pUrb Pointer to the URB in question.
3256 */
3257static DECLCALLBACK(bool) xhciR3RhXferError(PVUSBIROOTHUBPORT pInterface, PVUSBURB pUrb)
3258{
3259 PXHCIROOTHUBR3 pRh = RT_FROM_MEMBER(pInterface, XHCIROOTHUBR3, IRhPort);
3260 PXHCICC pThisCC = pRh->pXhciR3;
3261 PXHCI pThis = PDMDEVINS_2_DATA(pThisCC->pDevIns, PXHCI);
3262 bool fRetire = true;
3263
3264 /* If the xHC isn't running, get out of here immediately. */
3265 if (pThis->status & XHCI_STATUS_HCH)
3266 {
3267 Log(("xHC halted, skipping URB error handling\n"));
3268 return fRetire;
3269 }
3270
3271 RTCritSectEnter(&pThisCC->CritSectThrd);
3272
3273 Assert(pUrb->pHci->cTRB); /* xHCI-generated URBs should not fail! */
3274 if (!pUrb->pHci->cTRB)
3275 {
3276 Log(("%s: Failing xHCI-generated request!\n", pUrb->pszDesc));
3277 }
3278 else if (pUrb->enmStatus == VUSBSTATUS_STALL)
3279 {
3280 /* Don't retry on stall. */
3281 Log2(("%s: xhciR3RhXferError: STALL, giving up.\n", pUrb->pszDesc));
3282 } else if (pUrb->enmStatus == VUSBSTATUS_CRC) {
3283 /* Don't retry on CRC errors either. These indicate canceled URBs, among others. */
3284 Log2(("%s: xhciR3RhXferError: CRC, giving up.\n", pUrb->pszDesc));
3285 } else if (pUrb->enmStatus == VUSBSTATUS_DNR) {
3286 /* Don't retry on DNR errors. These indicate the device vanished. */
3287 Log2(("%s: xhciR3RhXferError: DNR, giving up.\n", pUrb->pszDesc));
3288 } else if (pUrb->enmStatus == VUSBSTATUS_DATA_OVERRUN) {
3289 /* Don't retry on OVERRUN errors. These indicate a fatal error. */
3290 Log2(("%s: xhciR3RhXferError: OVERRUN, giving up.\n", pUrb->pszDesc));
3291 } else if (pUrb->enmStatus == VUSBSTATUS_DATA_UNDERRUN) {
3292 /* Don't retry on UNDERRUN errors. These indicate a fatal error. */
3293 Log2(("%s: xhciR3RhXferError: UNDERRUN, giving up.\n", pUrb->pszDesc));
3294 } else {
3295 /// @todo
3296 AssertMsgFailed(("%#x\n", pUrb->enmStatus));
3297 }
3298
3299 RTCritSectLeave(&pThisCC->CritSectThrd);
3300 return fRetire;
3301}
3302
3303
3304/**
3305 * Queue a TD composed of normal TRBs, event data TRBs, and suchlike.
3306 *
3307 * @returns VBox status code.
3308 * @param pDevIns The device instance.
3309 * @param pThis The xHCI device state, shared edition.
3310 * @param pThisCC The xHCI device state, ring-3 edition.
3311 * @param pRh Root hub for the device.
3312 * @param GCPhysTRB Physical gues address of the TRB.
3313 * @param pTrb Pointer to the contents of the first TRB.
3314 * @param pEpCtx Pointer to the cached EP context.
3315 * @param uSlotID ID of the associated slot context.
3316 * @param uAddr The device address.
3317 * @param uEpDCI The DCI(!) of the endpoint.
3318 */
3319static int xhciR3QueueDataTD(PPDMDEVINS pDevIns, PXHCI pThis, PXHCICC pThisCC, PXHCIROOTHUBR3 pRh, RTGCPHYS GCPhysTRB,
3320 XHCI_XFER_TRB *pTrb, XHCI_EP_CTX *pEpCtx, uint8_t uSlotID, uint8_t uAddr, uint8_t uEpDCI)
3321{
3322 RT_NOREF(GCPhysTRB);
3323 XHCI_CTX_XFER_PROBE ctxProbe;
3324 XHCI_CTX_XFER_SUBMIT ctxSubmit;
3325 uint64_t uTREP;
3326 bool fFragOnly = false;
3327 int rc;
3328 VUSBXFERTYPE enmType;
3329 VUSBDIRECTION enmDir;
3330
3331 /* Discover how big this TD is. */
3332 RT_ZERO(ctxProbe);
3333 rc = xhciR3WalkXferTrbChain(pDevIns, pThis, pEpCtx->trep, xhciR3WalkDataTRBsProbe, &ctxProbe, &uTREP);
3334 if (RT_SUCCESS(rc))
3335 LogFlowFunc(("Probed %u TRBs, %u bytes total, TREP@%RX64\n", ctxProbe.cTRB, ctxProbe.uXferLen, uTREP));
3336 else
3337 {
3338 LogFlowFunc(("Probing failed after %u TRBs, %u bytes total (last ED after %u TRBs and %u bytes), TREP@%RX64\n", ctxProbe.cTRB, ctxProbe.uXferLen, ctxProbe.cTRBLastED, ctxProbe.uXfrLenLastED, uTREP));
3339 if (rc == VERR_TRY_AGAIN && pTrb->gen.type == XHCI_TRB_NORMAL && ctxProbe.cTRBLastED)
3340 {
3341 /* The TD is incomplete, but we have at least one TD fragment. We can create a URB for
3342 * what we have but we can't safely queue any more because if any error occurs, the
3343 * TD needs to fail as a whole.
3344 * OS X Mavericks and Yosemite tend to trigger this case when reading from USB 3.0
3345 * MSDs (transfers up to 1MB).
3346 */
3347 fFragOnly = true;
3348
3349 /* Because we currently do not maintain the EDTLA across URBs, we have to only submit
3350 * TD fragments up to where we last saw an Event Data TRB. If there was no Event Data
3351 * TRB, we'll just try waiting a bit longer for the TD to be complete or an Event Data
3352 * TRB to show up. The guest is extremely likely to do one or the other, since otherwise
3353 * it has no way to tell when the transfer completed.
3354 */
3355 ctxProbe.cTRB = ctxProbe.cTRBLastED;
3356 ctxProbe.uXferLen = ctxProbe.uXfrLenLastED;
3357 }
3358 else
3359 return rc;
3360 }
3361
3362 /* Determine the transfer kind based on endpoint type. */
3363 switch (pEpCtx->ep_type)
3364 {
3365 case XHCI_EPTYPE_BULK_IN:
3366 case XHCI_EPTYPE_BULK_OUT:
3367 enmType = VUSBXFERTYPE_BULK;
3368 break;
3369 case XHCI_EPTYPE_INTR_IN:
3370 case XHCI_EPTYPE_INTR_OUT:
3371 enmType = VUSBXFERTYPE_INTR;
3372 break;
3373 case XHCI_EPTYPE_CONTROL:
3374 enmType = VUSBXFERTYPE_CTRL;
3375 break;
3376 case XHCI_EPTYPE_ISOCH_IN:
3377 case XHCI_EPTYPE_ISOCH_OUT:
3378 default:
3379 enmType = VUSBXFERTYPE_INVALID;
3380 AssertMsgFailed(("%#x\n", pEpCtx->ep_type));
3381 }
3382
3383 /* Determine the direction based on endpoint type. */
3384 switch (pEpCtx->ep_type)
3385 {
3386 case XHCI_EPTYPE_BULK_IN:
3387 case XHCI_EPTYPE_INTR_IN:
3388 enmDir = VUSBDIRECTION_IN;
3389 break;
3390 case XHCI_EPTYPE_BULK_OUT:
3391 case XHCI_EPTYPE_INTR_OUT:
3392 enmDir = VUSBDIRECTION_OUT;
3393 break;
3394 default:
3395 enmDir = VUSBDIRECTION_INVALID;
3396 AssertMsgFailed(("%#x\n", pEpCtx->ep_type));
3397 }
3398
3399 /* Allocate and initialize a URB. */
3400 PVUSBURB pUrb = VUSBIRhNewUrb(pRh->pIRhConn, uAddr, VUSB_DEVICE_PORT_INVALID, enmType, enmDir, ctxProbe.uXferLen, ctxProbe.cTRB, NULL);
3401 if (!pUrb)
3402 return VERR_OUT_OF_RESOURCES; /// @todo handle error!
3403
3404 STAM_COUNTER_ADD(&pThis->StatTRBsPerDtaUrb, ctxProbe.cTRB);
3405
3406 /* See 4.5.1 about xHCI vs. USB endpoint addressing. */
3407 Assert(uEpDCI);
3408
3409 pUrb->EndPt = uEpDCI / 2; /* DCI = EP * 2 + direction */
3410 pUrb->fShortNotOk = false; /* We detect short packets ourselves. */
3411 pUrb->enmStatus = VUSBSTATUS_OK;
3412
3413 /// @todo Cross check that the EP type corresponds to direction. Probably
3414 //should check when configuring device?
3415 pUrb->pHci->uSlotID = uSlotID;
3416
3417 /* For OUT transfers, copy the TD data into the URB. */
3418 if (pUrb->enmDir == VUSBDIRECTION_OUT)
3419 {
3420 ctxSubmit.pUrb = pUrb;
3421 ctxSubmit.uXferPos = 0;
3422 ctxSubmit.cTRB = 0;
3423 xhciR3WalkXferTrbChain(pDevIns, pThis, pEpCtx->trep, xhciR3WalkDataTRBsSubmit, &ctxSubmit, &uTREP);
3424 Assert(ctxProbe.cTRB == ctxSubmit.cTRB);
3425 ctxProbe.cTRB = ctxSubmit.cTRB;
3426 }
3427
3428 /* If only completing a fragment, remember the TRB count and increase
3429 * the in-flight count past the limit so we won't queue any more.
3430 */
3431 pUrb->pHci->cTRB = ctxProbe.cTRB;
3432 if (fFragOnly)
3433 /* Bit of a hack -- prevent further queuing. */
3434 pEpCtx->ifc += XHCI_NO_QUEUING_IN_FLIGHT;
3435 else
3436 /* Increment the in-flight counter before queuing more. */
3437 pEpCtx->ifc++;
3438
3439 /* Commit the updated TREP; submitting the URB may already invoke completion callbacks. */
3440 pEpCtx->trep = uTREP;
3441 xhciR3WriteBackEp(pDevIns, pThis, uSlotID, uEpDCI, pEpCtx);
3442
3443 /*
3444 * Submit the URB.
3445 */
3446 STAM_COUNTER_ADD(&pThis->StatUrbSizeData, pUrb->cbData);
3447 Log(("%s: xhciR3QueueDataTD: Addr=%u, EndPt=%u, enmDir=%u cbData=%u\n",
3448 pUrb->pszDesc, pUrb->DstAddress, pUrb->EndPt, pUrb->enmDir, pUrb->cbData));
3449 RTCritSectLeave(&pThisCC->CritSectThrd);
3450 rc = VUSBIRhSubmitUrb(pRh->pIRhConn, pUrb, &pRh->Led);
3451 RTCritSectEnter(&pThisCC->CritSectThrd);
3452 if (RT_SUCCESS(rc))
3453 return VINF_SUCCESS;
3454
3455 /* Failure cleanup. Can happen if we're still resetting the device or out of resources,
3456 * or the user just ripped out the device.
3457 */
3458 /// @todo Mark the EP as halted and inactive and write back the changes.
3459
3460 return VERR_OUT_OF_RESOURCES;
3461}
3462
3463
3464/**
3465 * Queue an isochronous TD composed of isochronous and normal TRBs, event
3466 * data TRBs, and suchlike. This TD may either correspond to a single URB or
3467 * form one packet of an isochronous URB.
3468 *
3469 * @returns VBox status code.
3470 * @param pDevIns The device instance.
3471 * @param pThis The xHCI device state, shared edition.
3472 * @param pThisCC The xHCI device state, ring-3 edition.
3473 * @param pRh Root hub for the device.
3474 * @param GCPhysTRB Physical guest address of the TRB.
3475 * @param pTrb Pointer to the contents of the first TRB.
3476 * @param pEpCtx Pointer to the cached EP context.
3477 * @param uSlotID ID of the associated slot context.
3478 * @param uAddr The device address.
3479 * @param uEpDCI The DCI(!) of the endpoint.
3480 * @param pCtxIso Additional isochronous URB context.
3481 */
3482static int xhciR3QueueIsochTD(PPDMDEVINS pDevIns, PXHCI pThis, PXHCICC pThisCC, PXHCIROOTHUBR3 pRh, RTGCPHYS GCPhysTRB,
3483 XHCI_XFER_TRB *pTrb, XHCI_EP_CTX *pEpCtx, uint8_t uSlotID, uint8_t uAddr, uint8_t uEpDCI,
3484 XHCI_CTX_ISOCH *pCtxIso)
3485{
3486 RT_NOREF(GCPhysTRB, pTrb);
3487 XHCI_CTX_XFER_PROBE ctxProbe;
3488 XHCI_CTX_XFER_SUBMIT ctxSubmit;
3489 uint64_t uTREP;
3490 PVUSBURB pUrb;
3491 uint8_t cIsoPackets;
3492 uint32_t cbPktMax;
3493
3494 /* Discover how big this TD is. */
3495 RT_ZERO(ctxProbe);
3496 xhciR3WalkXferTrbChain(pDevIns, pThis, pEpCtx->trep, xhciR3WalkDataTRBsProbe, &ctxProbe, &uTREP);
3497 LogFlowFunc(("Probed %u TRBs, %u bytes total, TREP@%RX64\n", ctxProbe.cTRB, ctxProbe.uXferLen, uTREP));
3498
3499 /* See 4.5.1 about xHCI vs. USB endpoint addressing. */
3500 Assert(uEpDCI);
3501
3502 /* For isochronous transfers, there's a bit of extra work to do. The interval
3503 * is key and determines whether the TD will directly correspond to a URB or
3504 * if it will only form part of a larger URB. In any case, one TD equals one
3505 * 'packet' of an isochronous URB.
3506 */
3507 switch (pEpCtx->interval)
3508 {
3509 case 0: /* Every 2^0 * 125us, i.e. 8 per frame. */
3510 cIsoPackets = 8;
3511 break;
3512 case 1: /* Every 2^1 * 125us, i.e. 4 per frame. */
3513 cIsoPackets = 4;
3514 break;
3515 case 2: /* Every 2^2 * 125us, i.e. 2 per frame. */
3516 cIsoPackets = 2;
3517 break;
3518 case 3: /* Every 2^3 * 125us, i.e. 1 per frame. */
3519 default:/* Or any larger interval (every n frames).*/
3520 cIsoPackets = 1;
3521 break;
3522 }
3523
3524 /* We do not know exactly how much data might be transferred until we
3525 * look at all TDs/packets that constitute the URB. However, we do know
3526 * the maximum possible size even without probing any TDs at all.
3527 * The actual size is expected to be the same or at most slightly smaller,
3528 * hence it makes sense to allocate the URB right away and copy data into
3529 * it as we go, rather than doing complicated probing first.
3530 * The Max Endpoint Service Interval Time (ESIT) Payload defines the
3531 * maximum number of bytes that can be transferred per interval (4.14.2).
3532 * Unfortunately Apple was lazy and their driver leaves the Max ESIT
3533 * Payload as zero, so we have to do the math ourselves.
3534 */
3535
3536 /* Calculate the maximum transfer size per (micro)frame. */
3537 /// @todo This ought to be stored within the URB somewhere.
3538 cbPktMax = pEpCtx->max_pkt_sz * (pEpCtx->max_brs_sz + 1) * (pEpCtx->mult + 1);
3539 if (!pCtxIso->pUrb)
3540 {
3541 uint32_t cbUrbMax = cIsoPackets * cbPktMax;
3542
3543 /* Validate endpoint type. */
3544 AssertMsg(pEpCtx->ep_type == XHCI_EPTYPE_ISOCH_IN || pEpCtx->ep_type == XHCI_EPTYPE_ISOCH_OUT,
3545 ("%#x\n", pEpCtx->ep_type));
3546
3547 /* Allocate and initialize a new URB. */
3548 pUrb = VUSBIRhNewUrb(pRh->pIRhConn, uAddr, VUSB_DEVICE_PORT_INVALID, VUSBXFERTYPE_ISOC,
3549 (pEpCtx->ep_type == XHCI_EPTYPE_ISOCH_IN) ? VUSBDIRECTION_IN : VUSBDIRECTION_OUT,
3550 cbUrbMax, ctxProbe.cTRB, NULL);
3551 if (!pUrb)
3552 return VERR_OUT_OF_RESOURCES; /// @todo handle error!
3553
3554 STAM_COUNTER_ADD(&pThis->StatTRBsPerIsoUrb, ctxProbe.cTRB);
3555
3556 LogFlowFunc(("Allocated URB with %u packets, %u bytes total (ESIT payload %u)\n", cIsoPackets, cbUrbMax, cbPktMax));
3557
3558 pUrb->EndPt = uEpDCI / 2; /* DCI = EP * 2 + direction */
3559 pUrb->fShortNotOk = false; /* We detect short packets ourselves. */
3560 pUrb->enmStatus = VUSBSTATUS_OK;
3561 pUrb->cIsocPkts = cIsoPackets;
3562 pUrb->pHci->uSlotID = uSlotID;
3563 pUrb->pHci->cTRB = ctxProbe.cTRB;
3564
3565 /* If TRB says so or if there are multiple packets per interval, don't even
3566 * bother with frame counting and schedule everything ASAP.
3567 */
3568 if (pTrb->isoc.sia || cIsoPackets != 1)
3569 pUrb->uStartFrameDelta = 0;
3570 else
3571 {
3572 uint16_t uFrameDelta;
3573 uint32_t uPort;
3574
3575 /* Abort the endpoint, i.e. cancel any outstanding URBs. This needs to be done after
3576 * writing back the EP state so that the completion callback can operate.
3577 */
3578 if (RT_SUCCESS(xhciR3FindRhDevBySlot(pDevIns, pThis, pThisCC, uSlotID, NULL, &uPort)))
3579 {
3580
3581 uFrameDelta = pRh->pIRhConn->pfnUpdateIsocFrameDelta(pRh->pIRhConn, uPort, uEpDCI / 2,
3582 uEpDCI & 1 ? VUSBDIRECTION_IN : VUSBDIRECTION_OUT,
3583 pTrb->isoc.frm_id, XHCI_FRAME_ID_BITS);
3584 pUrb->uStartFrameDelta = uFrameDelta;
3585 Log(("%s: Isoch frame delta set to %u\n", pUrb->pszDesc, uFrameDelta));
3586 }
3587 else
3588 {
3589 Log(("%s: Failed to find device for slot! Setting frame delta to zero.\n", pUrb->pszDesc));
3590 pUrb->uStartFrameDelta = 0;
3591 }
3592 }
3593
3594 Log(("%s: Addr=%u, EndPt=%u, enmDir=%u cIsocPkts=%u cbData=%u FrmID=%u Isoch URB created\n",
3595 pUrb->pszDesc, pUrb->DstAddress, pUrb->EndPt, pUrb->enmDir, pUrb->cIsocPkts, pUrb->cbData, pTrb->isoc.frm_id));
3596
3597 /* Set up the context for later use. */
3598 pCtxIso->pUrb = pUrb;
3599 /* Save the current TREP in case we need to rewind. */
3600 pCtxIso->uInitTREP = pEpCtx->trep;
3601 }
3602 else
3603 {
3604 Assert(cIsoPackets > 1);
3605 /* Grab the URB we initialized earlier. */
3606 pUrb = pCtxIso->pUrb;
3607 }
3608
3609 /* Set up the packet corresponding to this TD. */
3610 pUrb->aIsocPkts[pCtxIso->iPkt].cb = RT_MIN(ctxProbe.uXferLen, cbPktMax);
3611 pUrb->aIsocPkts[pCtxIso->iPkt].off = pCtxIso->offCur;
3612 pUrb->aIsocPkts[pCtxIso->iPkt].enmStatus = VUSBSTATUS_NOT_ACCESSED;
3613
3614 /* For OUT transfers, copy the TD data into the URB. */
3615 if (pUrb->enmDir == VUSBDIRECTION_OUT)
3616 {
3617 ctxSubmit.pUrb = pUrb;
3618 ctxSubmit.uXferPos = pCtxIso->offCur;
3619 ctxSubmit.cTRB = 0;
3620 xhciR3WalkXferTrbChain(pDevIns, pThis, pEpCtx->trep, xhciR3WalkDataTRBsSubmit, &ctxSubmit, &uTREP);
3621 Assert(ctxProbe.cTRB == ctxSubmit.cTRB);
3622 }
3623
3624 /* Done preparing this packet. */
3625 Assert(pCtxIso->iPkt < 8);
3626 pCtxIso->iPkt++;
3627 pCtxIso->offCur += ctxProbe.uXferLen;
3628 Assert(pCtxIso->offCur <= pUrb->cbData);
3629
3630 /* Increment the in-flight counter before queuing more. */
3631 if (pCtxIso->iPkt == pUrb->cIsocPkts)
3632 pEpCtx->ifc++;
3633
3634 /* Commit the updated TREP; submitting the URB may already invoke completion callbacks. */
3635 pEpCtx->trep = uTREP;
3636 xhciR3WriteBackEp(pDevIns, pThis, uSlotID, uEpDCI, pEpCtx);
3637
3638 /* If the URB is complete, submit it. */
3639 if (pCtxIso->iPkt == pUrb->cIsocPkts)
3640 {
3641 /* Change cbData to reflect how much data should be transferred. This can differ
3642 * from how much data was allocated for the URB.
3643 */
3644 pUrb->cbData = pCtxIso->offCur;
3645 STAM_COUNTER_ADD(&pThis->StatUrbSizeIsoc, pUrb->cbData);
3646 Log(("%s: Addr=%u, EndPt=%u, enmDir=%u cIsocPkts=%u cbData=%u Isoch URB being submitted\n",
3647 pUrb->pszDesc, pUrb->DstAddress, pUrb->EndPt, pUrb->enmDir, pUrb->cIsocPkts, pUrb->cbData));
3648 RTCritSectLeave(&pThisCC->CritSectThrd);
3649 int rc = VUSBIRhSubmitUrb(pRh->pIRhConn, pUrb, &pRh->Led);
3650 RTCritSectEnter(&pThisCC->CritSectThrd);
3651 if (RT_FAILURE(rc))
3652 {
3653 /* Failure cleanup. Can happen if we're still resetting the device or out of resources,
3654 * or the user just ripped out the device.
3655 */
3656 pCtxIso->fSubmitFailed = true;
3657 /// @todo Mark the EP as halted and inactive and write back the changes.
3658 return VERR_OUT_OF_RESOURCES;
3659 }
3660 /* Clear the isochronous URB context. */
3661 RT_ZERO(*pCtxIso);
3662 }
3663
3664 return VINF_SUCCESS;
3665}
3666
3667
3668/**
3669 * Queue a control TD composed of setup/data/status stage TRBs, event data
3670 * TRBs, and suchlike.
3671 *
3672 * @returns VBox status code.
3673 * @param pDevIns The device instance.
3674 * @param pThis The xHCI device state, shared edition.
3675 * @param pThisCC The xHCI device state, ring-3 edition.
3676 * @param pRh Root hub for the device.
3677 * @param GCPhysTRB Physical guest address of th TRB.
3678 * @param pTrb Pointer to the contents of the first TRB.
3679 * @param pEpCtx Pointer to the cached EP context.
3680 * @param uSlotID ID of the associated slot context.
3681 * @param uAddr The device address.
3682 * @param uEpDCI The DCI(!) of the endpoint.
3683 */
3684static int xhciR3QueueControlTD(PPDMDEVINS pDevIns, PXHCI pThis, PXHCICC pThisCC, PXHCIROOTHUBR3 pRh, RTGCPHYS GCPhysTRB,
3685 XHCI_XFER_TRB *pTrb, XHCI_EP_CTX *pEpCtx, uint8_t uSlotID, uint8_t uAddr, uint8_t uEpDCI)
3686{
3687 RT_NOREF(GCPhysTRB);
3688 XHCI_CTX_XFER_PROBE ctxProbe;
3689 XHCI_CTX_XFER_SUBMIT ctxSubmit;
3690 uint64_t uTREP;
3691 int rc;
3692 VUSBDIRECTION enmDir;
3693
3694 /* Discover how big this TD is. */
3695 RT_ZERO(ctxProbe);
3696 rc = xhciR3WalkXferTrbChain(pDevIns, pThis, pEpCtx->trep, xhciR3WalkDataTRBsProbe, &ctxProbe, &uTREP);
3697 if (RT_SUCCESS(rc))
3698 LogFlowFunc(("Probed %u TRBs, %u bytes total, TREP@%RX64\n", ctxProbe.cTRB, ctxProbe.uXferLen, uTREP));
3699 else
3700 {
3701 LogFlowFunc(("Probing failed after %u TRBs, %u bytes total (last ED after %u TRBs and %u bytes), TREP@%RX64\n", ctxProbe.cTRB, ctxProbe.uXferLen, ctxProbe.cTRBLastED, ctxProbe.uXfrLenLastED, uTREP));
3702 return rc;
3703 }
3704
3705 /* Determine the transfer direction. */
3706 switch (pTrb->gen.type)
3707 {
3708 case XHCI_TRB_SETUP_STG:
3709 enmDir = VUSBDIRECTION_SETUP;
3710 /* For setup TRBs, there is always 8 bytes of immediate data. */
3711 Assert(sizeof(VUSBSETUP) == 8);
3712 Assert(ctxProbe.uXferLen == 8);
3713 Log2(("bmRequestType:%02X bRequest:%02X wValue:%04X wIndex:%04X wLength:%04X\n", pTrb->setup.bmRequestType,
3714 pTrb->setup.bRequest, pTrb->setup.wValue, pTrb->setup.wIndex, pTrb->setup.wLength));
3715 break;
3716 case XHCI_TRB_STATUS_STG:
3717 enmDir = pTrb->status.dir ? VUSBDIRECTION_IN : VUSBDIRECTION_OUT;
3718 break;
3719 case XHCI_TRB_DATA_STG:
3720 enmDir = pTrb->data.dir ? VUSBDIRECTION_IN : VUSBDIRECTION_OUT;
3721 break;
3722 default:
3723 AssertMsgFailed(("%#x\n", pTrb->gen.type)); /* Can't happen unless caller messed up. */
3724 return VERR_INTERNAL_ERROR;
3725 }
3726
3727 /* Allocate and initialize a URB. */
3728 PVUSBURB pUrb = VUSBIRhNewUrb(pRh->pIRhConn, uAddr, VUSB_DEVICE_PORT_INVALID, VUSBXFERTYPE_CTRL, enmDir, ctxProbe.uXferLen, ctxProbe.cTRB,
3729 NULL);
3730 if (!pUrb)
3731 return VERR_OUT_OF_RESOURCES; /// @todo handle error!
3732
3733 STAM_COUNTER_ADD(&pThis->StatTRBsPerCtlUrb, ctxProbe.cTRB);
3734
3735 /* See 4.5.1 about xHCI vs. USB endpoint addressing. */
3736 Assert(uEpDCI);
3737
3738 /* This had better be a control endpoint. */
3739 AssertMsg(pEpCtx->ep_type == XHCI_EPTYPE_CONTROL, ("%#x\n", pEpCtx->ep_type));
3740
3741 pUrb->EndPt = uEpDCI / 2; /* DCI = EP * 2 + direction */
3742 pUrb->fShortNotOk = false; /* We detect short packets ourselves. */
3743 pUrb->enmStatus = VUSBSTATUS_OK;
3744 pUrb->pHci->uSlotID = uSlotID;
3745
3746 /* For OUT/SETUP transfers, copy the TD data into the URB. */
3747 if (pUrb->enmDir == VUSBDIRECTION_OUT || pUrb->enmDir == VUSBDIRECTION_SETUP)
3748 {
3749 ctxSubmit.pUrb = pUrb;
3750 ctxSubmit.uXferPos = 0;
3751 ctxSubmit.cTRB = 0;
3752 xhciR3WalkXferTrbChain(pDevIns, pThis, pEpCtx->trep, xhciR3WalkDataTRBsSubmit, &ctxSubmit, &uTREP);
3753 Assert(ctxProbe.cTRB == ctxSubmit.cTRB);
3754 ctxProbe.cTRB = ctxSubmit.cTRB;
3755 }
3756
3757 pUrb->pHci->cTRB = ctxProbe.cTRB;
3758
3759 /* Commit the updated TREP; submitting the URB may already invoke completion callbacks. */
3760 pEpCtx->trep = uTREP;
3761 xhciR3WriteBackEp(pDevIns, pThis, uSlotID, uEpDCI, pEpCtx);
3762
3763 /*
3764 * Submit the URB.
3765 */
3766 STAM_COUNTER_ADD(&pThis->StatUrbSizeCtrl, pUrb->cbData);
3767 Log(("%s: xhciR3QueueControlTD: Addr=%u, EndPt=%u, enmDir=%u cbData=%u\n",
3768 pUrb->pszDesc, pUrb->DstAddress, pUrb->EndPt, pUrb->enmDir, pUrb->cbData));
3769 RTCritSectLeave(&pThisCC->CritSectThrd);
3770 rc = VUSBIRhSubmitUrb(pRh->pIRhConn, pUrb, &pRh->Led);
3771 RTCritSectEnter(&pThisCC->CritSectThrd);
3772 if (RT_SUCCESS(rc))
3773 return VINF_SUCCESS;
3774
3775 /* Failure cleanup. Can happen if we're still resetting the device or out of resources,
3776 * or the user just ripped out the device.
3777 */
3778 /// @todo Mark the EP as halted and inactive and write back the changes.
3779
3780 return VERR_OUT_OF_RESOURCES;
3781}
3782
3783
3784/**
3785 * Process a device context (transfer data).
3786 *
3787 * @param pDevIns The device instance.
3788 * @param pThis The xHCI device state, shared edition.
3789 * @param pThisCC The xHCI device state, ring-3 edition.
3790 * @param uSlotID Slot/doorbell which had been rung.
3791 * @param uDBVal Value written to the doorbell.
3792 */
3793static int xhciR3ProcessDevCtx(PPDMDEVINS pDevIns, PXHCI pThis, PXHCICC pThisCC, uint8_t uSlotID, uint32_t uDBVal)
3794{
3795 uint8_t uDBTarget = uDBVal & XHCI_DB_TGT_MASK;
3796 XHCI_CTX_ISOCH ctxIsoch = {0};
3797 XHCI_SLOT_CTX slot_ctx;
3798 XHCI_EP_CTX ep_ctx;
3799 XHCI_XFER_TRB xfer;
3800 RTGCPHYS GCPhysXfrTRB;
3801 PXHCIROOTHUBR3 pRh;
3802 bool dcs;
3803 bool fContinue = true;
3804 int rc = VINF_SUCCESS;
3805 unsigned cTrbs = 0;
3806
3807 LogFlowFunc(("Slot ID: %u, DB target %u, DB stream ID %u\n", uSlotID, uDBTarget, (uDBVal & XHCI_DB_STRMID_MASK) >> XHCI_DB_STRMID_SHIFT));
3808 Assert(uSlotID > 0);
3809 Assert(uSlotID <= XHCI_NDS);
3810 /// @todo report errors for bogus DB targets
3811 Assert(uDBTarget > 0);
3812 Assert(uDBTarget < 32);
3813
3814 /// @todo Check for aborts and the like?
3815
3816 /* Load the slot and endpoint contexts. */
3817 xhciR3FetchCtxAndEp(pDevIns, pThis, uSlotID, uDBTarget, &slot_ctx, &ep_ctx);
3818 /// @todo sanity check the context in here?
3819
3820 /* Select the root hub corresponding to the port. */
3821 pRh = GET_PORT_PRH(pThisCC, ID_TO_IDX(slot_ctx.rh_port));
3822
3823 /* Stopped endpoints automatically transition to running state. */
3824 if (RT_UNLIKELY(ep_ctx.ep_state == XHCI_EPST_STOPPED))
3825 {
3826 Log(("EP DCI %u stopped -> running\n", uDBTarget));
3827 ep_ctx.ep_state = XHCI_EPST_RUNNING;
3828 /* Update EP right here. Theoretically could be postponed, but we
3829 * must ensure that the EP does get written back even if there is
3830 * no other work to do.
3831 */
3832 xhciR3WriteBackEp(pDevIns, pThis, uSlotID, uDBTarget, &ep_ctx);
3833 }
3834
3835 /* If the EP isn't running, get outta here. */
3836 if (RT_UNLIKELY(ep_ctx.ep_state != XHCI_EPST_RUNNING))
3837 {
3838 Log2(("EP DCI %u not running (state %u), bail!\n", uDBTarget, ep_ctx.ep_state));
3839 return VINF_SUCCESS;
3840 }
3841
3842 /* Get any non-transfer TRBs out of the way. */
3843 xhciR3ConsumeNonXferTRBs(pDevIns, pThis, uSlotID, uDBTarget, &ep_ctx, &xfer, &GCPhysXfrTRB);
3844 /// @todo This is inefficient.
3845 xhciR3WriteBackEp(pDevIns, pThis, uSlotID, uDBTarget, &ep_ctx);
3846
3847 do
3848 {
3849 /* Fetch the contexts again and find the TRB address at enqueue point. */
3850 xhciR3FetchCtxAndEp(pDevIns, pThis, uSlotID, uDBTarget, &slot_ctx, &ep_ctx);
3851 GCPhysXfrTRB = ep_ctx.trep & XHCI_TRDP_ADDR_MASK;
3852 dcs = !!(ep_ctx.trep & XHCI_TRDP_DCS_MASK);
3853 LogFlowFunc(("Processing Transfer Ring, TREP: %RGp\n", GCPhysXfrTRB));
3854
3855 /* Fetch the transfer TRB. */
3856 PDMDevHlpPCIPhysReadMeta(pDevIns, GCPhysXfrTRB, &xfer, sizeof(xfer));
3857
3858 /* Make sure the Cycle State matches. */
3859 if ((bool)xfer.gen.cycle == dcs)
3860 {
3861 Log2(("TRB @ %RGp, type %u (%s) %u bytes ENT=%u ISP=%u NS=%u CH=%u IOC=%u IDT=%u\n", GCPhysXfrTRB, xfer.gen.type,
3862 xfer.gen.type < RT_ELEMENTS(g_apszTrbNames) ? g_apszTrbNames[xfer.gen.type] : "WHAT?!!",
3863 xfer.gen.xfr_len, xfer.gen.ent, xfer.gen.isp, xfer.gen.ns, xfer.gen.ch, xfer.gen.ioc, xfer.gen.idt));
3864
3865 /* If there is an "in-flight" TRDP, check if we need to wait until the transfer completes. */
3866 if ((ep_ctx.trdp & XHCI_TRDP_ADDR_MASK) != GCPhysXfrTRB)
3867 {
3868 switch (xfer.gen.type) {
3869 case XHCI_TRB_ISOCH:
3870 if (ep_ctx.ifc >= XHCI_MAX_ISOC_IN_FLIGHT)
3871 {
3872 Log(("%u isoch URBs in flight, backing off\n", ep_ctx.ifc));
3873 fContinue = false;
3874 break;
3875 }
3876 RT_FALL_THRU();
3877 case XHCI_TRB_LINK:
3878 Log2(("TRB OK, continuing @ %RX64\n", GCPhysXfrTRB));
3879 break;
3880 case XHCI_TRB_NORMAL:
3881 if (XHCI_EP_XTYPE(ep_ctx.ep_type) != XHCI_XFTYPE_BULK)
3882 {
3883 Log2(("Normal TRB not bulk, not continuing @ %RX64\n", GCPhysXfrTRB));
3884 fContinue = false;
3885 break;
3886 }
3887 if (ep_ctx.ifc >= XHCI_MAX_BULK_IN_FLIGHT)
3888 {
3889 Log(("%u normal URBs in flight, backing off\n", ep_ctx.ifc));
3890 fContinue = false;
3891 break;
3892 }
3893 Log2(("Bulk TRB OK, continuing @ %RX64\n", GCPhysXfrTRB));
3894 break;
3895 case XHCI_TRB_EVT_DATA:
3896 case XHCI_TRB_NOOP_XFER:
3897 Log2(("TRB not OK, not continuing @ %RX64\n", GCPhysXfrTRB));
3898 fContinue = false;
3899 break;
3900 default:
3901 Log2(("Some other TRB (type %u), not continuing @ %RX64\n", xfer.gen.type, GCPhysXfrTRB));
3902 fContinue = false;
3903 break;
3904 }
3905 }
3906 if (!fContinue)
3907 break;
3908
3909 switch (xfer.gen.type) {
3910 case XHCI_TRB_NORMAL:
3911 Log(("Normal TRB: Ptr=%RGp IOC=%u CH=%u\n", xfer.norm.data_ptr, xfer.norm.ioc, xfer.norm.ch));
3912 rc = xhciR3QueueDataTD(pDevIns, pThis, pThisCC, pRh, GCPhysXfrTRB, &xfer, &ep_ctx, uSlotID,
3913 slot_ctx.dev_addr, uDBTarget);
3914 break;
3915 case XHCI_TRB_SETUP_STG:
3916 Log(("Setup stage TRB: IOC=%u IDT=%u\n", xfer.setup.ioc, xfer.setup.idt));
3917 rc = xhciR3QueueControlTD(pDevIns, pThis, pThisCC, pRh, GCPhysXfrTRB, &xfer, &ep_ctx, uSlotID,
3918 slot_ctx.dev_addr, uDBTarget);
3919 break;
3920 case XHCI_TRB_DATA_STG:
3921 Log(("Data stage TRB: Ptr=%RGp IOC=%u CH=%u DIR=%u\n", xfer.data.data_ptr, xfer.data.ioc, xfer.data.ch, xfer.data.dir));
3922 rc = xhciR3QueueControlTD(pDevIns, pThis, pThisCC, pRh, GCPhysXfrTRB, &xfer, &ep_ctx, uSlotID,
3923 slot_ctx.dev_addr, uDBTarget);
3924 break;
3925 case XHCI_TRB_STATUS_STG:
3926 Log(("Status stage TRB: IOC=%u CH=%u DIR=%u\n", xfer.status.ioc, xfer.status.ch, xfer.status.dir));
3927 rc = xhciR3QueueControlTD(pDevIns, pThis, pThisCC, pRh, GCPhysXfrTRB, &xfer, &ep_ctx, uSlotID,
3928 slot_ctx.dev_addr, uDBTarget);
3929 break;
3930 case XHCI_TRB_ISOCH:
3931 Log(("Isoch TRB: Ptr=%RGp IOC=%u CH=%u TLBPC=%u TBC=%u SIA=%u FrmID=%u\n", xfer.isoc.data_ptr, xfer.isoc.ioc, xfer.isoc.ch, xfer.isoc.tlbpc, xfer.isoc.tbc, xfer.isoc.sia, xfer.isoc.frm_id));
3932 rc = xhciR3QueueIsochTD(pDevIns, pThis, pThisCC, pRh, GCPhysXfrTRB, &xfer, &ep_ctx, uSlotID,
3933 slot_ctx.dev_addr, uDBTarget, &ctxIsoch);
3934 break;
3935 case XHCI_TRB_LINK:
3936 Log2(("Link extra-TD: Ptr=%RGp IOC=%u TC=%u CH=%u\n", xfer.link.rseg_ptr, xfer.link.ioc, xfer.link.toggle, xfer.link.chain));
3937 Assert(!xfer.link.chain);
3938 /* Set new TREP but leave DCS bit alone... */
3939 ep_ctx.trep = (xfer.link.rseg_ptr & XHCI_TRDP_ADDR_MASK) | (ep_ctx.trep & XHCI_TRDP_DCS_MASK);
3940 /* ...and flip the DCS bit if required. Then update the TREP. */
3941 ep_ctx.trep = ep_ctx.trep ^ xfer.link.toggle;
3942 rc = xhciR3WriteBackEp(pDevIns, pThis, uSlotID, uDBTarget, &ep_ctx);
3943 break;
3944 case XHCI_TRB_NOOP_XFER:
3945 Log2(("No op xfer: IOC=%u CH=%u ENT=%u\n", xfer.nop.ioc, xfer.nop.ch, xfer.nop.ent));
3946 /* A no-op transfer TRB must not be part of a chain. See 4.11.7. */
3947 Assert(!xfer.link.chain);
3948 /* Update enqueue pointer (TRB was not yet completed). */
3949 ep_ctx.trep += sizeof(XHCI_XFER_TRB);
3950 rc = xhciR3WriteBackEp(pDevIns, pThis, uSlotID, uDBTarget, &ep_ctx);
3951 break;
3952 default:
3953 Log(("Unsupported TRB!!\n"));
3954 rc = VERR_NOT_SUPPORTED;
3955 break;
3956 }
3957 /* If queuing failed, stop right here. */
3958 if (RT_FAILURE(rc))
3959 fContinue = false;
3960 }
3961 else
3962 {
3963 LogFunc(("Transfer Ring empty\n"));
3964 fContinue = false;
3965
3966 /* If an isochronous ring is empty, this is an overrun/underrun. At this point
3967 * the ring will no longer be scheduled (until the doorbell is rung again)
3968 * but it remains in the Running state. This error is only reported if someone
3969 * rang the doorbell and there are no TDs available or in-flight.
3970 */
3971 if ( (ep_ctx.trep == ep_ctx.trdp) /* Nothing in-flight? */
3972 && (ep_ctx.ep_type == XHCI_EPTYPE_ISOCH_IN || ep_ctx.ep_type == XHCI_EPTYPE_ISOCH_OUT))
3973 {
3974 /* There is no TRB associated with this error; the slot context
3975 * determines the interrupter.
3976 */
3977 Log(("Isochronous ring %s, TRDP:%RGp\n", ep_ctx.ep_type == XHCI_EPTYPE_ISOCH_IN ? "overrun" : "underrun", ep_ctx.trdp & XHCI_TRDP_ADDR_MASK));
3978 rc = xhciR3PostXferEvent(pDevIns, pThis, slot_ctx.intr_tgt, 0,
3979 ep_ctx.ep_type == XHCI_EPTYPE_ISOCH_IN ? XHCI_TCC_RING_OVERRUN : XHCI_TCC_RING_UNDERRUN,
3980 uSlotID, uDBTarget, 0, false, false);
3981 }
3982
3983 }
3984
3985 /* Kill the xHC if the TRB list has no end in sight. */
3986 if (++cTrbs > XHCI_MAX_NUM_TRBS)
3987 {
3988 /* Stop the xHC with an error. */
3989 xhciR3EndlessTrbError(pDevIns, pThis);
3990
3991 /* Get out of the loop. */
3992 fContinue = false;
3993 rc = VERR_NOT_SUPPORTED; /* No good error code really... */
3994 }
3995 } while (fContinue);
3996
3997 /* It can unfortunately happen that for endpoints with more than one
3998 * transfer per USB frame, there won't be a complete multi-packet URB ready
3999 * when we go looking for it. If that happens, we'll "rewind" the TREP and
4000 * try again later. Since the URB construction is done under a lock, this
4001 * is safe as we won't be accessing the endpoint concurrently.
4002 */
4003 if (ctxIsoch.pUrb)
4004 {
4005 Log(("Unfinished ISOC URB (%u packets out of %u)!\n", ctxIsoch.iPkt, ctxIsoch.pUrb->cIsocPkts));
4006 /* If submitting failed, the URB is already freed. */
4007 if (!ctxIsoch.fSubmitFailed)
4008 VUSBIRhFreeUrb(pRh->pIRhConn, ctxIsoch.pUrb);
4009 ep_ctx.trep = ctxIsoch.uInitTREP;
4010 xhciR3WriteBackEp(pDevIns, pThis, uSlotID, uDBTarget, &ep_ctx);
4011 }
4012 return rc;
4013}
4014
4015
4016/**
4017 * A worker routine for Address Device command. Builds a URB containing
4018 * a SET_ADDRESS requests and (synchronously) submits it to VUSB, then
4019 * follows up with a status stage URB.
4020 *
4021 * @returns true on success.
4022 * @returns false on failure to submit.
4023 * @param pThisCC The xHCI device state, ring-3 edition.
4024 * @param uSlotID Slot ID to assign address to.
4025 * @param uDevAddr New device address.
4026 * @param iPort The xHCI root hub port index.
4027 */
4028static bool xhciR3IssueSetAddress(PXHCICC pThisCC, uint8_t uSlotID, uint8_t uDevAddr, unsigned iPort)
4029{
4030 PXHCIROOTHUBR3 pRh = GET_PORT_PRH(pThisCC, iPort);
4031
4032 Assert(uSlotID);
4033 LogFlowFunc(("Slot %u port idx %u: new address is %u\n", uSlotID, iPort, uDevAddr));
4034
4035 /* For USB3 devices, force the port number. This simulates the fact that USB3 uses directed (unicast) traffic. */
4036 if (!IS_USB3_PORT_IDX_R3(pThisCC, iPort))
4037 iPort = VUSB_DEVICE_PORT_INVALID;
4038 else
4039 iPort = GET_VUSB_PORT_FROM_XHCI_PORT(pRh, iPort);
4040
4041 /* Allocate and initialize a URB. NB: Zero cTds indicates a URB not submitted by guest. */
4042 PVUSBURB pUrb = VUSBIRhNewUrb(pRh->pIRhConn, 0 /* address */, iPort, VUSBXFERTYPE_CTRL, VUSBDIRECTION_SETUP,
4043 sizeof(VUSBSETUP), 0 /* cTds */, NULL);
4044 if (!pUrb)
4045 return false;
4046
4047 pUrb->EndPt = 0;
4048 pUrb->fShortNotOk = true;
4049 pUrb->enmStatus = VUSBSTATUS_OK;
4050 pUrb->pHci->uSlotID = uSlotID;
4051 pUrb->pHci->cTRB = 0;
4052
4053 /* Build the request. */
4054 PVUSBSETUP pSetup = (PVUSBSETUP)pUrb->abData;
4055 pSetup->bmRequestType = VUSB_DIR_TO_DEVICE | VUSB_REQ_STANDARD | VUSB_TO_DEVICE;
4056 pSetup->bRequest = VUSB_REQ_SET_ADDRESS;
4057 pSetup->wValue = uDevAddr;
4058 pSetup->wIndex = 0;
4059 pSetup->wLength = 0;
4060
4061 /* NB: We assume the address assignment is a synchronous operation. */
4062
4063 /* Submit the setup URB. */
4064 Log(("%s: xhciSetAddress setup: cbData=%u\n", pUrb->pszDesc, pUrb->cbData));
4065 RTCritSectLeave(&pThisCC->CritSectThrd);
4066 int rc = VUSBIRhSubmitUrb(pRh->pIRhConn, pUrb, &pRh->Led);
4067 RTCritSectEnter(&pThisCC->CritSectThrd);
4068 if (RT_FAILURE(rc))
4069 {
4070 Log(("xhciSetAddress: setup stage failed pUrb=%p!!\n", pUrb));
4071 return false;
4072 }
4073
4074 /* To complete the SET_ADDRESS request, the status stage must succeed. */
4075 pUrb = VUSBIRhNewUrb(pRh->pIRhConn, 0 /* address */, iPort, VUSBXFERTYPE_CTRL, VUSBDIRECTION_IN, 0 /* cbData */, 0 /* cTds */,
4076 NULL);
4077 if (!pUrb)
4078 return false;
4079
4080 pUrb->EndPt = 0;
4081 pUrb->fShortNotOk = true;
4082 pUrb->enmStatus = VUSBSTATUS_OK;
4083 pUrb->pHci->uSlotID = uSlotID;
4084 pUrb->pHci->cTRB = 0;
4085
4086 /* Submit the setup URB. */
4087 Log(("%s: xhciSetAddress status: cbData=%u\n", pUrb->pszDesc, pUrb->cbData));
4088 RTCritSectLeave(&pThisCC->CritSectThrd);
4089 rc = VUSBIRhSubmitUrb(pRh->pIRhConn, pUrb, &pRh->Led);
4090 RTCritSectEnter(&pThisCC->CritSectThrd);
4091 if (RT_FAILURE(rc))
4092 {
4093 Log(("xhciSetAddress: status stage failed pUrb=%p!!\n", pUrb));
4094 return false;
4095 }
4096
4097 Log(("xhciSetAddress: set address succeeded\n"));
4098 return true;
4099}
4100
4101
4102/**
4103 * Address a device.
4104 *
4105 * @returns TRB completion code.
4106 * @param pDevIns The device instance.
4107 * @param pThis The xHCI device state, shared edition.
4108 * @param pThisCC The xHCI device state, ring-3 edition.
4109 * @param uInpCtxAddr Address of the input context.
4110 * @param uSlotID Slot ID to assign address to.
4111 * @param fBSR Block Set address Request flag.
4112 */
4113static unsigned xhciR3AddressDevice(PPDMDEVINS pDevIns, PXHCI pThis, PXHCICC pThisCC, uint64_t uInpCtxAddr,
4114 uint8_t uSlotID, bool fBSR)
4115{
4116 RTGCPHYS GCPhysInpCtx = uInpCtxAddr & XHCI_CTX_ADDR_MASK;
4117 RTGCPHYS GCPhysInpSlot;
4118 RTGCPHYS GCPhysOutSlot;
4119 XHCI_INPC_CTX icc; /* Input Control Context (ICI=0). */
4120 XHCI_SLOT_CTX inp_slot_ctx; /* Input Slot Context (ICI=1). */
4121 XHCI_EP_CTX ep_ctx; /* Endpoint Context (ICI=2+). */
4122 XHCI_SLOT_CTX out_slot_ctx; /* Output Slot Context. */
4123 uint8_t dev_addr;
4124 unsigned cc = XHCI_TCC_SUCCESS;
4125
4126 Assert(GCPhysInpCtx);
4127 Assert(uSlotID);
4128 LogFlowFunc(("Slot ID %u, input control context @ %RGp\n", uSlotID, GCPhysInpCtx));
4129
4130 /* Determine the address of the output slot context. */
4131 GCPhysOutSlot = xhciR3FetchDevCtxAddr(pDevIns, pThis, uSlotID);
4132
4133 /* Fetch the output slot context. */
4134 PDMDevHlpPCIPhysReadMeta(pDevIns, GCPhysOutSlot, &out_slot_ctx, sizeof(out_slot_ctx));
4135
4136 /// @todo Check for valid context (6.2.2.1, 6.2.3.1)
4137
4138 /* See 4.6.5 */
4139 do {
4140 /* Parameter validation depends on whether the BSR flag is set or not. */
4141 if (fBSR)
4142 {
4143 /* Check that the output slot context state is in Enabled state. */
4144 if (out_slot_ctx.slot_state >= XHCI_SLTST_DEFAULT)
4145 {
4146 Log(("Output slot context state (%u) wrong (BSR)!\n", out_slot_ctx.slot_state));
4147 cc = XHCI_TCC_CTX_STATE_ERR;
4148 break;
4149 }
4150 dev_addr = 0;
4151 }
4152 else
4153 {
4154 /* Check that the output slot context state is in Enabled or Default state. */
4155 if (out_slot_ctx.slot_state > XHCI_SLTST_DEFAULT)
4156 {
4157 Log(("Output slot context state (%u) wrong (no-BSR)!\n", out_slot_ctx.slot_state));
4158 cc = XHCI_TCC_CTX_STATE_ERR;
4159 break;
4160 }
4161 dev_addr = xhciR3SelectNewAddress(pThis, uSlotID);
4162 }
4163
4164 /* Fetch the input control context. */
4165 PDMDevHlpPCIPhysReadMeta(pDevIns, GCPhysInpCtx, &icc, sizeof(icc));
4166 Assert(icc.add_flags == (RT_BIT(0) | RT_BIT(1))); /* Should have been already checked. */
4167 Assert(!icc.drop_flags);
4168
4169 /* Calculate the address of the input slot context (ICI=1/DCI=0). */
4170 GCPhysInpSlot = GCPhysInpCtx + sizeof(XHCI_INPC_CTX);
4171
4172 /* Read the input slot context. */
4173 PDMDevHlpPCIPhysReadMeta(pDevIns, GCPhysInpSlot, &inp_slot_ctx, sizeof(inp_slot_ctx));
4174
4175 /* If BSR isn't set, issue the actual SET_ADDRESS request. */
4176 if (!fBSR) {
4177 unsigned iPort;
4178
4179 /* We have to dig out the port number/index to determine which virtual root hub to use. */
4180 iPort = ID_TO_IDX(inp_slot_ctx.rh_port);
4181 if (iPort >= XHCI_NDP_CFG(pThis))
4182 {
4183 Log(("Port out of range (index %u)!\n", iPort));
4184 cc = XHCI_TCC_USB_XACT_ERR;
4185 break;
4186 }
4187 if (!xhciR3IssueSetAddress(pThisCC, uSlotID, dev_addr, iPort))
4188 {
4189 Log(("SET_ADDRESS failed!\n"));
4190 cc = XHCI_TCC_USB_XACT_ERR;
4191 break;
4192 }
4193 }
4194
4195 /* Copy the slot context with appropriate modifications. */
4196 out_slot_ctx = inp_slot_ctx;
4197 if (fBSR)
4198 out_slot_ctx.slot_state = XHCI_SLTST_DEFAULT;
4199 else
4200 out_slot_ctx.slot_state = XHCI_SLTST_ADDRESSED;
4201 out_slot_ctx.dev_addr = dev_addr;
4202 PDMDevHlpPCIPhysWriteMeta(pDevIns, GCPhysOutSlot, &out_slot_ctx, sizeof(out_slot_ctx));
4203
4204 /* Point at the EP0 contexts. */
4205 GCPhysInpSlot += sizeof(inp_slot_ctx);
4206 GCPhysOutSlot += sizeof(out_slot_ctx);
4207
4208 /* Copy EP0 context with appropriate modifications. */
4209 PDMDevHlpPCIPhysReadMeta(pDevIns, GCPhysInpSlot, &ep_ctx, sizeof(ep_ctx));
4210 xhciR3EnableEP(&ep_ctx);
4211 PDMDevHlpPCIPhysWriteMeta(pDevIns, GCPhysOutSlot, &ep_ctx, sizeof(ep_ctx));
4212 } while (0);
4213
4214 return cc;
4215}
4216
4217
4218/**
4219 * Reset a halted endpoint.
4220 *
4221 * @returns TRB completion code.
4222 * @param pDevIns The device instance.
4223 * @param pThis Pointer to the xHCI state.
4224 * @param uSlotID Slot ID to work with.
4225 * @param uDCI DCI of the endpoint to reset.
4226 * @param fTSP The Transfer State Preserve flag.
4227 */
4228static unsigned xhciR3ResetEndpoint(PPDMDEVINS pDevIns, PXHCI pThis, uint8_t uSlotID, uint8_t uDCI, bool fTSP)
4229{
4230 RT_NOREF(fTSP);
4231 RTGCPHYS GCPhysSlot;
4232 RTGCPHYS GCPhysEndp;
4233 XHCI_SLOT_CTX slot_ctx;
4234 XHCI_EP_CTX endp_ctx;
4235 unsigned cc = XHCI_TCC_SUCCESS;
4236
4237 Assert(uSlotID);
4238
4239 /* Determine the addresses of the contexts. */
4240 GCPhysSlot = xhciR3FetchDevCtxAddr(pDevIns, pThis, uSlotID);
4241 GCPhysEndp = GCPhysSlot + uDCI * sizeof(XHCI_EP_CTX);
4242
4243 /* Fetch the slot context. */
4244 PDMDevHlpPCIPhysReadMeta(pDevIns, GCPhysSlot, &slot_ctx, sizeof(slot_ctx));
4245
4246 /* See 4.6.8 */
4247 do {
4248 /* Check that the slot context state is Default, Addressed, or Configured. */
4249 if (slot_ctx.slot_state < XHCI_SLTST_DEFAULT)
4250 {
4251 Log(("Slot context state wrong (%u)!\n", slot_ctx.slot_state));
4252 cc = XHCI_TCC_CTX_STATE_ERR;
4253 break;
4254 }
4255
4256 /* Fetch the endpoint context. */
4257 PDMDevHlpPCIPhysReadMeta(pDevIns, GCPhysEndp, &endp_ctx, sizeof(endp_ctx));
4258
4259 /* Check that the endpoint context state is Halted. */
4260 if (endp_ctx.ep_state != XHCI_EPST_HALTED)
4261 {
4262 Log(("Endpoint context state wrong (%u)!\n", endp_ctx.ep_state));
4263 cc = XHCI_TCC_CTX_STATE_ERR;
4264 break;
4265 }
4266
4267 /* Transition EP state. */
4268 endp_ctx.ep_state = XHCI_EPST_STOPPED;
4269
4270 /// @todo What can we do with the TSP flag?
4271 /// @todo Anything to do WRT enabling the corresponding doorbell register?
4272
4273 /* Write back the updated endpoint context. */
4274 PDMDevHlpPCIPhysWriteMeta(pDevIns, GCPhysEndp, &endp_ctx, sizeof(endp_ctx));
4275 } while (0);
4276
4277 return cc;
4278}
4279
4280
4281/**
4282 * Stop a running endpoint.
4283 *
4284 * @returns TRB completion code.
4285 * @param pDevIns The device instance.
4286 * @param pThis The xHCI device state, shared edition.
4287 * @param pThisCC The xHCI device state, ring-3 edition.
4288 * @param uSlotID Slot ID to work with.
4289 * @param uDCI DCI of the endpoint to stop.
4290 * @param fTSP The Suspend flag.
4291 */
4292static unsigned xhciR3StopEndpoint(PPDMDEVINS pDevIns, PXHCI pThis, PXHCICC pThisCC, uint8_t uSlotID, uint8_t uDCI, bool fTSP)
4293{
4294 RT_NOREF(fTSP);
4295 RTGCPHYS GCPhysSlot;
4296 RTGCPHYS GCPhysEndp;
4297 XHCI_SLOT_CTX slot_ctx;
4298 XHCI_EP_CTX endp_ctx;
4299 unsigned cc = XHCI_TCC_SUCCESS;
4300
4301 Assert(uSlotID);
4302
4303 /* Determine the addresses of the contexts. */
4304 GCPhysSlot = xhciR3FetchDevCtxAddr(pDevIns, pThis, uSlotID);
4305 GCPhysEndp = GCPhysSlot + uDCI * sizeof(XHCI_EP_CTX);
4306
4307 /* Fetch the slot context. */
4308 PDMDevHlpPCIPhysReadMeta(pDevIns, GCPhysSlot, &slot_ctx, sizeof(slot_ctx));
4309
4310 /* See 4.6.9 */
4311 do {
4312 /* Check that the slot context state is Default, Addressed, or Configured. */
4313 if (slot_ctx.slot_state < XHCI_SLTST_DEFAULT)
4314 {
4315 Log(("Slot context state wrong (%u)!\n", slot_ctx.slot_state));
4316 cc = XHCI_TCC_CTX_STATE_ERR;
4317 break;
4318 }
4319
4320 /* The doorbell could be ringing; stop it if so. */
4321 if (pThis->aBellsRung[ID_TO_IDX(uSlotID)] & (1 << uDCI))
4322 {
4323 Log(("Unring bell for slot ID %u, DCI %u\n", uSlotID, uDCI));
4324 ASMAtomicAndU32(&pThis->aBellsRung[ID_TO_IDX(uSlotID)], ~(1 << uDCI));
4325 }
4326
4327 /* Fetch the endpoint context. */
4328 PDMDevHlpPCIPhysReadMeta(pDevIns, GCPhysEndp, &endp_ctx, sizeof(endp_ctx));
4329
4330 /* Check that the endpoint context state is Running. */
4331 if (endp_ctx.ep_state != XHCI_EPST_RUNNING)
4332 {
4333 Log(("Endpoint context state wrong (%u)!\n", endp_ctx.ep_state));
4334 cc = XHCI_TCC_CTX_STATE_ERR;
4335 break;
4336 }
4337
4338 /* Transition EP state. */
4339 endp_ctx.ep_state = XHCI_EPST_STOPPED;
4340
4341 /* Write back the updated endpoint context *now*, before actually canceling anyhing. */
4342 PDMDevHlpPCIPhysWriteMeta(pDevIns, GCPhysEndp, &endp_ctx, sizeof(endp_ctx));
4343
4344 /// @todo What can we do with the SP flag?
4345
4346 PXHCIROOTHUBR3 pRh;
4347 uint32_t uPort;
4348
4349 /* Abort the endpoint, i.e. cancel any outstanding URBs. This needs to be done after
4350 * writing back the EP state so that the completion callback can operate. Note that
4351 * the completion callback will not modify the TR when it sees that the EP is not in
4352 * the 'running' state.
4353 * NB: If a URB is canceled before it completed, we have no way to tell if any data
4354 * was already (partially) transferred.
4355 */
4356 if (RT_SUCCESS(xhciR3FindRhDevBySlot(pDevIns, pThis, pThisCC, uSlotID, &pRh, &uPort)))
4357 {
4358 /* Temporarily give up the lock so that the completion callbacks can run. */
4359 RTCritSectLeave(&pThisCC->CritSectThrd);
4360 Log(("Aborting DCI %u -> ep=%u d=%u\n", uDCI, uDCI / 2, uDCI & 1 ? VUSBDIRECTION_IN : VUSBDIRECTION_OUT));
4361 pRh->pIRhConn->pfnAbortEpByPort(pRh->pIRhConn, uPort, uDCI / 2, uDCI & 1 ? VUSBDIRECTION_IN : VUSBDIRECTION_OUT);
4362 RTCritSectEnter(&pThisCC->CritSectThrd);
4363 }
4364
4365 /* Once the completion callbacks had a chance to run, we have to adjust
4366 * the endpoint state.
4367 * NB: The guest may just ring the doorbell to continue and not execute
4368 * 'Set TRDP' after stopping the endpoint.
4369 */
4370 PDMDevHlpPCIPhysReadMeta(pDevIns, GCPhysEndp, &endp_ctx, sizeof(endp_ctx));
4371
4372 /* If the enqueue and dequeue pointers are different, a transfer was
4373 * in progress.
4374 */
4375 bool fXferWasInProgress = endp_ctx.trep != endp_ctx.trdp;
4376
4377 /* Reset the TREP, but the EDTLA should be left alone. */
4378 endp_ctx.trep = endp_ctx.trdp;
4379
4380 if (fXferWasInProgress)
4381 {
4382 /* Fetch the transfer TRB to see the length. */
4383 RTGCPHYS GCPhysXfrTRB = endp_ctx.trdp & XHCI_TRDP_ADDR_MASK;
4384 XHCI_XFER_TRB XferTRB;
4385 PDMDevHlpPCIPhysReadMeta(pDevIns, GCPhysXfrTRB, &XferTRB, sizeof(XferTRB));
4386
4387 xhciR3PostXferEvent(pDevIns, pThis, slot_ctx.intr_tgt, XferTRB.gen.xfr_len, XHCI_TCC_STOPPED, uSlotID, uDCI,
4388 GCPhysXfrTRB, false, false);
4389 }
4390 else
4391 {
4392 /* We need to generate a Force Stopped Event or FSE. Note that FSEs were optional
4393 * in xHCI 0.96 but aren't in 1.0.
4394 */
4395 xhciR3PostXferEvent(pDevIns, pThis, slot_ctx.intr_tgt, 0, XHCI_TCC_STP_INV_LEN, uSlotID, uDCI,
4396 endp_ctx.trdp & XHCI_TRDP_ADDR_MASK, false, false);
4397 }
4398
4399 /* Write back the updated endpoint context again. */
4400 PDMDevHlpPCIPhysWriteMeta(pDevIns, GCPhysEndp, &endp_ctx, sizeof(endp_ctx));
4401
4402 } while (0);
4403
4404 return cc;
4405}
4406
4407
4408/**
4409 * Set a new TR Dequeue Pointer for an endpoint.
4410 *
4411 * @returns TRB completion code.
4412 * @param pDevIns The device instance.
4413 * @param pThis Pointer to the xHCI state.
4414 * @param uSlotID Slot ID to work with.
4415 * @param uDCI DCI of the endpoint to reset.
4416 * @param uTRDP The TRDP including DCS/ flag.
4417 */
4418static unsigned xhciR3SetTRDP(PPDMDEVINS pDevIns, PXHCI pThis, uint8_t uSlotID, uint8_t uDCI, uint64_t uTRDP)
4419{
4420 RTGCPHYS GCPhysSlot;
4421 RTGCPHYS GCPhysEndp;
4422 XHCI_SLOT_CTX slot_ctx;
4423 XHCI_EP_CTX endp_ctx;
4424 unsigned cc = XHCI_TCC_SUCCESS;
4425
4426 Assert(uSlotID);
4427
4428 /* Determine the addresses of the contexts. */
4429 GCPhysSlot = xhciR3FetchDevCtxAddr(pDevIns, pThis, uSlotID);
4430 GCPhysEndp = GCPhysSlot + uDCI * sizeof(XHCI_EP_CTX);
4431
4432 /* Fetch the slot context. */
4433 PDMDevHlpPCIPhysReadMeta(pDevIns, GCPhysSlot, &slot_ctx, sizeof(slot_ctx));
4434
4435 /* See 4.6.10 */
4436 do {
4437 /* Check that the slot context state is Default, Addressed, or Configured. */
4438 if (slot_ctx.slot_state < XHCI_SLTST_DEFAULT)
4439 {
4440 Log(("Slot context state wrong (%u)!\n", slot_ctx.slot_state));
4441 cc = XHCI_TCC_CTX_STATE_ERR;
4442 break;
4443 }
4444
4445 /* Fetch the endpoint context. */
4446 PDMDevHlpPCIPhysReadMeta(pDevIns, GCPhysEndp, &endp_ctx, sizeof(endp_ctx));
4447
4448 /* Check that the endpoint context state is Stopped or Error. */
4449 if (endp_ctx.ep_state != XHCI_EPST_STOPPED && endp_ctx.ep_state != XHCI_EPST_ERROR)
4450 {
4451 Log(("Endpoint context state wrong (%u)!\n", endp_ctx.ep_state));
4452 cc = XHCI_TCC_CTX_STATE_ERR;
4453 break;
4454 }
4455
4456 /* Update the TRDP/TREP and DCS. */
4457 endp_ctx.trdp = uTRDP;
4458 endp_ctx.trep = uTRDP;
4459
4460 /* Also clear the in-flight counter! */
4461 endp_ctx.ifc = 0;
4462
4463 /// @todo Handle streams
4464
4465 /* Write back the updated endpoint context. */
4466 PDMDevHlpPCIPhysWriteMeta(pDevIns, GCPhysEndp, &endp_ctx, sizeof(endp_ctx));
4467 } while (0);
4468
4469 return cc;
4470}
4471
4472
4473/**
4474 * Prepare for a device reset.
4475 *
4476 * @returns TRB completion code.
4477 * @param pDevIns The device instance.
4478 * @param pThis Pointer to the xHCI state.
4479 * @param uSlotID Slot ID to work with.
4480 */
4481static unsigned xhciR3ResetDevice(PPDMDEVINS pDevIns, PXHCI pThis, uint8_t uSlotID)
4482{
4483 RTGCPHYS GCPhysSlot;
4484 XHCI_SLOT_CTX slot_ctx;
4485 XHCI_DEV_CTX dc;
4486 unsigned num_ctx;
4487 unsigned i;
4488 unsigned cc = XHCI_TCC_SUCCESS;
4489
4490 Assert(uSlotID);
4491
4492 /* Determine the address of the slot/device context. */
4493 GCPhysSlot = xhciR3FetchDevCtxAddr(pDevIns, pThis, uSlotID);
4494
4495 /* Fetch the slot context. */
4496 PDMDevHlpPCIPhysReadMeta(pDevIns, GCPhysSlot, &slot_ctx, sizeof(slot_ctx));
4497
4498 /* See 4.6.11. */
4499 do {
4500 /* Check that the slot context state is Addressed or Configured. */
4501 if (slot_ctx.slot_state < XHCI_SLTST_ADDRESSED)
4502 {
4503 Log(("Slot context state wrong (%u)!\n", slot_ctx.slot_state));
4504 cc = XHCI_TCC_CTX_STATE_ERR;
4505 break;
4506 }
4507
4508 /* Read the entire Device Context. */
4509 num_ctx = slot_ctx.ctx_ent + 1; /* Slot context plus EPs. */
4510 Assert(num_ctx);
4511 PDMDevHlpPCIPhysReadMeta(pDevIns, GCPhysSlot, &dc, num_ctx * sizeof(XHCI_SLOT_CTX));
4512
4513 /// @todo Abort any outstanding transfers!
4514
4515 /* Set slot state to Default and reset the USB device address. */
4516 dc.entry[0].sc.slot_state = XHCI_SLTST_DEFAULT;
4517 dc.entry[0].sc.dev_addr = 0;
4518
4519 /* Disable all endpoints except for EP 0 (aka DCI 1). */
4520 for (i = 2; i < num_ctx; ++i)
4521 dc.entry[i].ep.ep_state = XHCI_EPST_DISABLED;
4522
4523 /* Write back the updated device context. */
4524 PDMDevHlpPCIPhysWriteMeta(pDevIns, GCPhysSlot, &dc, num_ctx * sizeof(XHCI_SLOT_CTX));
4525 } while (0);
4526
4527 return cc;
4528}
4529
4530
4531/**
4532 * Configure a device (even though the relevant command is called 'Configure
4533 * Endpoint'. This includes adding/dropping endpoint contexts as directed by
4534 * the input control context bits.
4535 *
4536 * @returns TRB completion code.
4537 * @param pDevIns The device instance.
4538 * @param pThis Pointer to the xHCI state.
4539 * @param uInpCtxAddr Address of the input context.
4540 * @param uSlotID Slot ID associated with the context.
4541 * @param fDC Deconfigure flag set (input context unused).
4542 */
4543static unsigned xhciR3ConfigureDevice(PPDMDEVINS pDevIns, PXHCI pThis, uint64_t uInpCtxAddr, uint8_t uSlotID, bool fDC)
4544{
4545 RTGCPHYS GCPhysInpCtx = uInpCtxAddr & XHCI_CTX_ADDR_MASK;
4546 RTGCPHYS GCPhysInpSlot;
4547 RTGCPHYS GCPhysOutSlot;
4548 RTGCPHYS GCPhysOutEndp;
4549 XHCI_INPC_CTX icc; /* Input Control Context (ICI=0). */
4550 XHCI_SLOT_CTX out_slot_ctx; /* Slot context (DCI=0). */
4551 XHCI_EP_CTX out_endp_ctx; /* Endpoint Context (DCI=1). */
4552 unsigned cc = XHCI_TCC_SUCCESS;
4553 uint32_t uAddFlags;
4554 uint32_t uDropFlags;
4555 unsigned num_inp_ctx;
4556 unsigned num_out_ctx;
4557 XHCI_DEV_CTX dc_inp;
4558 XHCI_DEV_CTX dc_out;
4559 unsigned uDCI;
4560
4561 RT_ZERO(dc_inp);
4562
4563 Assert(uSlotID);
4564 LogFlowFunc(("Slot ID %u, input control context @ %RGp\n", uSlotID, GCPhysInpCtx));
4565
4566 /* Determine the address of the output slot context. */
4567 GCPhysOutSlot = xhciR3FetchDevCtxAddr(pDevIns, pThis, uSlotID);
4568 Assert(GCPhysOutSlot);
4569
4570 /* Fetch the output slot context. */
4571 PDMDevHlpPCIPhysReadMeta(pDevIns, GCPhysOutSlot, &out_slot_ctx, sizeof(out_slot_ctx));
4572
4573 /* See 4.6.6 */
4574 do {
4575 /* Check that the output slot context state is Addressed, or Configured. */
4576 if (out_slot_ctx.slot_state < XHCI_SLTST_ADDRESSED)
4577 {
4578 Log(("Output slot context state wrong (%u)!\n", out_slot_ctx.slot_state));
4579 cc = XHCI_TCC_CTX_STATE_ERR;
4580 break;
4581 }
4582
4583 /* Check for deconfiguration request. */
4584 if (fDC) {
4585 if (out_slot_ctx.slot_state == XHCI_SLTST_CONFIGURED) {
4586 /* Disable all enabled endpoints. */
4587 uDropFlags = 0xFFFFFFFC; /** @todo r=bird: Why do you set uDropFlags and uAddFlags in a code path that doesn't use
4588 * them? This is a _very_ difficult function to get the hang of the way it's written.
4589 * Stuff like this looks like there's a control flow flaw (as to the do-break-while-false
4590 * loop which doesn't do any clean up or logging at the end and seems only sever the very
4591 * dubious purpose of making sure ther's only one return statement). The insistance on
4592 * C-style variable declarations (top of function), makes checking state harder, which is
4593 * why it's discouraged. */
4594 uAddFlags = 0;
4595
4596 /* Start with EP1. */
4597 GCPhysOutEndp = GCPhysOutSlot + sizeof(XHCI_SLOT_CTX) + sizeof(XHCI_EP_CTX);
4598
4599 PDMDevHlpPCIPhysReadMeta(pDevIns, GCPhysOutEndp, &out_endp_ctx, sizeof(out_endp_ctx));
4600 out_endp_ctx.ep_state = XHCI_EPST_DISABLED;
4601 PDMDevHlpPCIPhysWriteMeta(pDevIns, GCPhysOutEndp, &out_endp_ctx, sizeof(out_endp_ctx));
4602 GCPhysOutEndp += sizeof(XHCI_EP_CTX); /* Point to the next EP context. */
4603
4604 /* Finally update the output slot context. */
4605 out_slot_ctx.ctx_ent = 1; /* Only EP0 left. */
4606 out_slot_ctx.slot_state = XHCI_SLTST_ADDRESSED;
4607 PDMDevHlpPCIPhysWriteMeta(pDevIns, GCPhysOutSlot, &out_slot_ctx, sizeof(out_slot_ctx));
4608 LogFlow(("Setting Output Slot State to Addressed, Context Entries = %u\n", out_slot_ctx.ctx_ent));
4609 }
4610 else
4611 /* NB: Attempts to deconfigure a slot in Addressed state are ignored. */
4612 Log(("Ignoring attempt to deconfigure slot in Addressed state!\n"));
4613 break;
4614 }
4615
4616 /* Fetch the input control context. */
4617 Assert(GCPhysInpCtx);
4618 PDMDevHlpPCIPhysReadMeta(pDevIns, GCPhysInpCtx, &icc, sizeof(icc));
4619 Assert(icc.add_flags || icc.drop_flags); /* Make sure there's something to do. */
4620
4621 uAddFlags = icc.add_flags;
4622 uDropFlags = icc.drop_flags;
4623 LogFlowFunc(("Add Flags=%08X, Drop Flags=%08X\n", uAddFlags, uDropFlags));
4624
4625 /* If and only if any 'add context' flag is set, fetch the corresponding
4626 * input device context.
4627 */
4628 if (uAddFlags) {
4629 /* Calculate the address of the input slot context (ICI=1/DCI=0). */
4630 GCPhysInpSlot = GCPhysInpCtx + sizeof(XHCI_INPC_CTX);
4631
4632 /* Read the input Slot Context plus all Endpoint Contexts up to and
4633 * including the one with the highest 'add' bit set.
4634 */
4635 num_inp_ctx = ASMBitLastSetU32(uAddFlags);
4636 Assert(num_inp_ctx);
4637 PDMDevHlpPCIPhysReadMeta(pDevIns, GCPhysInpSlot, &dc_inp, num_inp_ctx * sizeof(XHCI_DS_ENTRY));
4638
4639 /// @todo Check that the highest set add flag isn't beyond input slot Context Entries
4640
4641 /// @todo Check input slot context according to 6.2.2.2
4642 /// @todo Check input EP contexts according to 6.2.3.2
4643 }
4644 /* Read the output Slot Context plus all Endpoint Contexts up to and
4645 * including the one with the highest 'add' or 'drop' bit set.
4646 */
4647 num_out_ctx = ASMBitLastSetU32(uAddFlags | uDropFlags);
4648 PDMDevHlpPCIPhysReadMeta(pDevIns, GCPhysOutSlot, &dc_out, num_out_ctx * sizeof(XHCI_DS_ENTRY));
4649
4650 /* Drop contexts as directed by flags. */
4651 for (uDCI = 2; uDCI < 32; ++uDCI)
4652 {
4653 if (!((1 << uDCI) & uDropFlags))
4654 continue;
4655
4656 Log2(("Dropping EP DCI %u\n", uDCI));
4657 dc_out.entry[uDCI].ep.ep_state = XHCI_EPST_DISABLED;
4658 /// @todo Do we need to bother tracking resources/bandwidth?
4659 }
4660
4661 /* Now add contexts as directed by flags. */
4662 for (uDCI = 2; uDCI < 32; ++uDCI)
4663 {
4664 if (!((1 << uDCI) & uAddFlags))
4665 continue;
4666
4667 Assert(!fDC);
4668 /* Copy over EP context, set to running. */
4669 Log2(("Adding EP DCI %u\n", uDCI));
4670 dc_out.entry[uDCI].ep = dc_inp.entry[uDCI].ep;
4671 xhciR3EnableEP(&dc_out.entry[uDCI].ep);
4672 /// @todo Do we need to bother tracking resources/bandwidth?
4673 }
4674
4675 /* Finally update the device context. */
4676 if (fDC || dc_inp.entry[0].sc.ctx_ent == 1)
4677 {
4678 dc_out.entry[0].sc.slot_state = XHCI_SLTST_ADDRESSED;
4679 dc_out.entry[0].sc.ctx_ent = 1;
4680 LogFlow(("Setting Output Slot State to Addressed\n"));
4681 }
4682 else
4683 {
4684 uint32_t uKillFlags = uDropFlags & ~uAddFlags; /* Endpoints going away. */
4685
4686 /* At least one EP enabled. Update Context Entries and state. */
4687 Assert(dc_inp.entry[0].sc.ctx_ent);
4688 dc_out.entry[0].sc.slot_state = XHCI_SLTST_CONFIGURED;
4689 if (ID_TO_IDX(ASMBitLastSetU32(uAddFlags)) > dc_out.entry[0].sc.ctx_ent)
4690 {
4691 /* Adding new endpoints. */
4692 dc_out.entry[0].sc.ctx_ent = ID_TO_IDX(ASMBitLastSetU32(uAddFlags));
4693 }
4694 else if (ID_TO_IDX(ASMBitLastSetU32(uKillFlags)) == dc_out.entry[0].sc.ctx_ent)
4695 {
4696 /* Removing the last endpoint, find the last non-disabled one. */
4697 unsigned num_ctx_ent;
4698
4699 Assert(dc_out.entry[0].sc.ctx_ent + 1u == num_out_ctx);
4700 for (num_ctx_ent = dc_out.entry[0].sc.ctx_ent; num_ctx_ent > 1; --num_ctx_ent)
4701 if (dc_out.entry[num_ctx_ent].ep.ep_state != XHCI_EPST_DISABLED)
4702 break;
4703 dc_out.entry[0].sc.ctx_ent = num_ctx_ent; /* Last valid index to be precise. */
4704 }
4705 LogFlow(("Setting Output Slot State to Configured, Context Entries = %u\n", dc_out.entry[0].sc.ctx_ent));
4706 }
4707
4708 /* If there were no errors, write back the updated output context. */
4709 LogFlow(("Success, updating Output Context @ %RGp\n", GCPhysOutSlot));
4710 PDMDevHlpPCIPhysWriteMeta(pDevIns, GCPhysOutSlot, &dc_out, num_out_ctx * sizeof(XHCI_DS_ENTRY));
4711 } while (0);
4712
4713 return cc;
4714}
4715
4716
4717/**
4718 * Evaluate an input context. This involves modifying device and endpoint
4719 * contexts as directed by the input control context add bits.
4720 *
4721 * @returns TRB completion code.
4722 * @param pDevIns The device instance.
4723 * @param pThis Pointer to the xHCI state.
4724 * @param uInpCtxAddr Address of the input context.
4725 * @param uSlotID Slot ID associated with the context.
4726 */
4727static unsigned xhciR3EvalContext(PPDMDEVINS pDevIns, PXHCI pThis, uint64_t uInpCtxAddr, uint8_t uSlotID)
4728{
4729 RTGCPHYS GCPhysInpCtx = uInpCtxAddr & XHCI_CTX_ADDR_MASK;
4730 RTGCPHYS GCPhysInpSlot;
4731 RTGCPHYS GCPhysOutSlot;
4732 XHCI_INPC_CTX icc; /* Input Control Context (ICI=0). */
4733 XHCI_SLOT_CTX out_slot_ctx; /* Slot context (DCI=0). */
4734 unsigned cc = XHCI_TCC_SUCCESS;
4735 uint32_t uAddFlags;
4736 uint32_t uDropFlags;
4737 unsigned num_inp_ctx;
4738 unsigned num_out_ctx;
4739 XHCI_DEV_CTX dc_inp;
4740 XHCI_DEV_CTX dc_out;
4741 unsigned uDCI;
4742
4743 Assert(GCPhysInpCtx);
4744 Assert(uSlotID);
4745 LogFlowFunc(("Slot ID %u, input control context @ %RGp\n", uSlotID, GCPhysInpCtx));
4746
4747 /* Determine the address of the output slot context. */
4748 GCPhysOutSlot = xhciR3FetchDevCtxAddr(pDevIns, pThis, uSlotID);
4749 Assert(GCPhysOutSlot);
4750
4751 /* Fetch the output slot context. */
4752 PDMDevHlpPCIPhysReadMeta(pDevIns, GCPhysOutSlot, &out_slot_ctx, sizeof(out_slot_ctx));
4753
4754 /* See 4.6.7 */
4755 do {
4756 /* Check that the output slot context state is Default, Addressed, or Configured. */
4757 if (out_slot_ctx.slot_state < XHCI_SLTST_DEFAULT)
4758 {
4759 Log(("Output slot context state wrong (%u)!\n", out_slot_ctx.slot_state));
4760 cc = XHCI_TCC_CTX_STATE_ERR;
4761 break;
4762 }
4763
4764 /* Fetch the input control context. */
4765 PDMDevHlpPCIPhysReadMeta(pDevIns, GCPhysInpCtx, &icc, sizeof(icc));
4766 uAddFlags = icc.add_flags;
4767 uDropFlags = icc.drop_flags;
4768 LogFlowFunc(("Add Flags=%08X, Drop Flags=%08X\n", uAddFlags, uDropFlags));
4769
4770 /* Drop flags "shall be cleared to 0" but also "do not apply" (4.6.7). Log & ignore. */
4771 if (uDropFlags)
4772 Log(("Drop flags set (%X) for evaluating context!\n", uDropFlags));
4773
4774 /* If no add flags are set, nothing will be done but an error is not reported
4775 * according to the logic flow in 4.6.7.
4776 */
4777 if (!uAddFlags)
4778 {
4779 Log(("Warning: no add flags set for evaluating context!\n"));
4780 break;
4781 }
4782
4783 /* Calculate the address of the input slot context (ICI=1/DCI=0). */
4784 GCPhysInpSlot = GCPhysInpCtx + sizeof(XHCI_INPC_CTX);
4785
4786 /* Read the output Slot Context plus all Endpoint Contexts up to and
4787 * including the one with the highest 'add' bit set.
4788 */
4789 num_inp_ctx = ASMBitLastSetU32(uAddFlags);
4790 Assert(num_inp_ctx);
4791 PDMDevHlpPCIPhysReadMeta(pDevIns, GCPhysInpSlot, &dc_inp, num_inp_ctx * sizeof(XHCI_DS_ENTRY));
4792
4793 /* Read the output Slot Context plus all Endpoint Contexts up to and
4794 * including the one with the highest 'add' bit set.
4795 */
4796 num_out_ctx = ASMBitLastSetU32(uAddFlags);
4797 PDMDevHlpPCIPhysReadMeta(pDevIns, GCPhysOutSlot, &dc_out, num_out_ctx * sizeof(XHCI_DS_ENTRY));
4798
4799 /// @todo Check input slot context according to 6.2.2.3
4800 /// @todo Check input EP contexts according to 6.2.3.3
4801 /// @todo Check that the highest set add flag isn't beyond input slot Context Entries
4802
4803 /* Evaluate endpoint contexts as directed by add flags. */
4804 /// @todo 6.2.3.3 suggests only the A1 bit matters? Anything besides A0/A1 is ignored??
4805 for (uDCI = 1; uDCI < 32; ++uDCI)
4806 {
4807 if (!((1 << uDCI) & uAddFlags))
4808 continue;
4809
4810 /* Evaluate Max Packet Size. */
4811 LogFunc(("DCI %u: Max Packet Size: %u -> %u\n", uDCI, dc_out.entry[uDCI].ep.max_pkt_sz, dc_inp.entry[uDCI].ep.max_pkt_sz));
4812 dc_out.entry[uDCI].ep.max_pkt_sz = dc_inp.entry[uDCI].ep.max_pkt_sz;
4813 }
4814
4815 /* Finally update the device context if directed to do so (A0 flag set). */
4816 if (uAddFlags & RT_BIT(0))
4817 {
4818 /* 6.2.2.3 - evaluate Interrupter Target and Max Exit Latency. */
4819 Log(("Interrupter Target: %u -> %u\n", dc_out.entry[0].sc.intr_tgt, dc_inp.entry[0].sc.intr_tgt));
4820 Log(("Max Exit Latency : %u -> %u\n", dc_out.entry[0].sc.max_lat, dc_inp.entry[0].sc.max_lat));
4821
4822 /// @todo Non-zero Max Exit Latency (see 4.6.7)
4823 dc_out.entry[0].sc.intr_tgt = dc_inp.entry[0].sc.intr_tgt;
4824 dc_out.entry[0].sc.max_lat = dc_inp.entry[0].sc.max_lat;
4825 }
4826
4827 /* If there were no errors, write back the updated output context. */
4828 LogFlow(("Success, updating Output Context @ %RGp\n", GCPhysOutSlot));
4829 PDMDevHlpPCIPhysWriteMeta(pDevIns, GCPhysOutSlot, &dc_out, num_out_ctx * sizeof(XHCI_DS_ENTRY));
4830 } while (0);
4831
4832 return cc;
4833}
4834
4835
4836/**
4837 * Query available port bandwidth.
4838 *
4839 * @returns TRB completion code.
4840 * @param pDevIns The device instance.
4841 * @param pThis Pointer to the xHCI state.
4842 * @param uDevSpd Speed of not yet attached devices.
4843 * @param uHubSlotID Hub Slot ID to query (unsupported).
4844 * @param uBwCtx Bandwidth context physical address.
4845 */
4846static unsigned xhciR3GetPortBandwidth(PPDMDEVINS pDevIns, PXHCI pThis, uint8_t uDevSpd, uint8_t uHubSlotID, uint64_t uBwCtx)
4847{
4848 RT_NOREF(uHubSlotID);
4849 RTGCPHYS GCPhysBwCtx;
4850 unsigned cc = XHCI_TCC_SUCCESS;
4851 unsigned ctx_size;
4852 unsigned iPort;
4853 uint8_t bw_ctx[RT_ALIGN_32(XHCI_NDP_MAX + 1, 4)] = {0};
4854 uint8_t dev_spd;
4855 uint8_t avail_bw;
4856
4857 Assert(!uHubSlotID);
4858 Assert(uBwCtx);
4859
4860 /* See 4.6.15. */
4861
4862 /* Hubs are not supported because guests will never see them. The
4863 * reported values are more or less dummy because we have no real
4864 * information about the bandwidth available on the host. The reported
4865 * values are optimistic, as if each port had its own separate Bus
4866 * Instance aka BI.
4867 */
4868
4869 GCPhysBwCtx = uBwCtx & XHCI_CTX_ADDR_MASK;
4870
4871 /* Number of ports + 1, rounded up to DWORDs. */
4872 ctx_size = RT_ALIGN_32(XHCI_NDP_CFG(pThis) + 1, 4);
4873 LogFlowFunc(("BW Context at %RGp, size %u\n", GCPhysBwCtx, ctx_size));
4874 Assert(ctx_size <= sizeof(bw_ctx));
4875
4876 /* Go over all the ports. */
4877 for (iPort = 0; iPort < XHCI_NDP_CFG(pThis); ++iPort)
4878 {
4879 /* Get the device speed from the port... */
4880 dev_spd = (pThis->aPorts[iPort].portsc & XHCI_PORT_PLS_MASK) >> XHCI_PORT_PLS_SHIFT;
4881 /* ...and if nothing is attached, use the provided default. */
4882 if (!dev_spd)
4883 dev_spd = uDevSpd;
4884
4885 /* For USB3 ports, report 90% available for SS devices (see 6.2.6). */
4886 if (IS_USB3_PORT_IDX_SHR(pThis, iPort))
4887 avail_bw = dev_spd == XHCI_SPD_SUPER ? 90 : 0;
4888 else
4889 /* For USB2 ports, report 80% available for HS and 90% for FS/LS. */
4890 switch (dev_spd)
4891 {
4892 case XHCI_SPD_HIGH:
4893 avail_bw = 80;
4894 break;
4895 case XHCI_SPD_FULL:
4896 case XHCI_SPD_LOW:
4897 avail_bw = 90;
4898 break;
4899 default:
4900 avail_bw = 0;
4901 }
4902
4903 /* The first entry in the context is reserved. */
4904 bw_ctx[iPort + 1] = avail_bw;
4905 }
4906
4907 /* Write back the bandwidth context. */
4908 PDMDevHlpPCIPhysWriteMeta(pDevIns, GCPhysBwCtx, &bw_ctx, ctx_size);
4909
4910 return cc;
4911}
4912
4913#define NEC_MAGIC ('x' | ('H' << 8) | ('C' << 16) | ('I' << 24))
4914
4915/**
4916 * Take a 64-bit input, shake well, produce 32-bit token. This mechanism
4917 * prevents NEC/Renesas drivers from running on 3rd party hardware. Mirrors
4918 * code found in vendor's drivers.
4919 */
4920static uint32_t xhciR3NecAuthenticate(uint64_t cookie)
4921{
4922 uint32_t cookie_lo = RT_LODWORD(cookie);
4923 uint32_t cookie_hi = RT_HIDWORD(cookie);
4924 uint32_t shift_cnt;
4925 uint32_t token;
4926
4927 shift_cnt = (cookie_hi >> 8) & 31;
4928 token = ASMRotateRightU32(cookie_lo - NEC_MAGIC, shift_cnt);
4929 shift_cnt = cookie_hi & 31;
4930 token += ASMRotateLeftU32(cookie_lo + NEC_MAGIC, shift_cnt);
4931 shift_cnt = (cookie_lo >> 16) & 31;
4932 token -= ASMRotateLeftU32(cookie_hi ^ NEC_MAGIC, shift_cnt);
4933
4934 return ~token;
4935}
4936
4937/**
4938 * Process a single command TRB and post completion information.
4939 */
4940static int xhciR3ExecuteCommand(PPDMDEVINS pDevIns, PXHCI pThis, PXHCICC pThisCC, XHCI_COMMAND_TRB *pCmd)
4941{
4942 XHCI_EVENT_TRB ed;
4943 uint32_t token;
4944 unsigned slot;
4945 unsigned cc;
4946 int rc = VINF_SUCCESS;
4947 LogFlowFunc(("Executing command %u (%s) @ %RGp\n", pCmd->gen.type,
4948 pCmd->gen.type < RT_ELEMENTS(g_apszTrbNames) ? g_apszTrbNames[pCmd->gen.type] : "WHAT?!!",
4949 (RTGCPHYS)pThis->cmdr_dqp));
4950
4951 switch (pCmd->gen.type)
4952 {
4953 case XHCI_TRB_NOOP_CMD:
4954 /* No-op, slot ID is always zero. */
4955 rc = xhciR3PostCmdCompletion(pDevIns, pThis, XHCI_TCC_SUCCESS, 0);
4956 pThis->cmdr_dqp += sizeof(XHCI_COMMAND_TRB);
4957 break;
4958
4959 case XHCI_TRB_LINK:
4960 /* Link; set the dequeue pointer. CH bit is ignored. */
4961 Log(("Link: Ptr=%RGp IOC=%u TC=%u\n", pCmd->link.rseg_ptr, pCmd->link.ioc, pCmd->link.toggle));
4962 if (pCmd->link.ioc) /* Command completion event is optional! */
4963 rc = xhciR3PostCmdCompletion(pDevIns, pThis, XHCI_TCC_SUCCESS, 0);
4964 /* Update the dequeue pointer and flip DCS if required. */
4965 pThis->cmdr_dqp = pCmd->link.rseg_ptr & XHCI_TRDP_ADDR_MASK;
4966 pThis->cmdr_ccs = pThis->cmdr_ccs ^ pCmd->link.toggle;
4967 break;
4968
4969 case XHCI_TRB_ENB_SLOT:
4970 /* Look for an empty device slot. */
4971 for (slot = 0; slot < RT_ELEMENTS(pThis->aSlotState); ++slot)
4972 {
4973 if (pThis->aSlotState[slot] == XHCI_DEVSLOT_EMPTY)
4974 {
4975 /* Found a slot - transition to enabled state. */
4976 pThis->aSlotState[slot] = XHCI_DEVSLOT_ENABLED;
4977 break;
4978 }
4979 }
4980 Log(("Enable Slot: found slot ID %u\n", IDX_TO_ID(slot)));
4981
4982 /* Post command completion event. */
4983 if (slot == RT_ELEMENTS(pThis->aSlotState))
4984 xhciR3PostCmdCompletion(pDevIns, pThis, XHCI_TCC_NO_SLOTS, 0);
4985 else
4986 xhciR3PostCmdCompletion(pDevIns, pThis, XHCI_TCC_SUCCESS, IDX_TO_ID(slot));
4987
4988 pThis->cmdr_dqp += sizeof(XHCI_COMMAND_TRB);
4989 break;
4990
4991 case XHCI_TRB_DIS_SLOT:
4992 /* Disable the given device slot. */
4993 Log(("Disable Slot: slot ID %u\n", pCmd->dsl.slot_id));
4994 cc = XHCI_TCC_SUCCESS;
4995 slot = ID_TO_IDX(pCmd->dsl.slot_id);
4996 if ((slot >= RT_ELEMENTS(pThis->aSlotState)) || (pThis->aSlotState[slot] == XHCI_DEVSLOT_EMPTY))
4997 cc = XHCI_TCC_SLOT_NOT_ENB;
4998 else
4999 {
5000 /// @todo set slot state of assoc. context to disabled
5001 pThis->aSlotState[slot] = XHCI_DEVSLOT_EMPTY;
5002 }
5003 xhciR3PostCmdCompletion(pDevIns, pThis, cc, pCmd->dsl.slot_id);
5004 pThis->cmdr_dqp += sizeof(XHCI_COMMAND_TRB);
5005 break;
5006
5007 case XHCI_TRB_ADDR_DEV:
5008 /* Address a device. */
5009 Log(("Address Device: slot ID %u, BSR=%u\n", pCmd->adr.slot_id, pCmd->adr.bsr));
5010 slot = ID_TO_IDX(pCmd->cfg.slot_id);
5011 if ((slot >= RT_ELEMENTS(pThis->aSlotState)) || (pThis->aSlotState[slot] == XHCI_DEVSLOT_EMPTY))
5012 cc = XHCI_TCC_SLOT_NOT_ENB;
5013 else
5014 cc = xhciR3AddressDevice(pDevIns, pThis, pThisCC, pCmd->adr.ctx_ptr, pCmd->adr.slot_id, pCmd->adr.bsr);
5015 xhciR3PostCmdCompletion(pDevIns, pThis, cc, pCmd->adr.slot_id);
5016 pThis->cmdr_dqp += sizeof(XHCI_COMMAND_TRB);
5017 break;
5018
5019 case XHCI_TRB_CFG_EP:
5020 /* Configure endpoint. */
5021 Log(("Configure endpoint: slot ID %u, DC=%u, Ctx @ %RGp\n", pCmd->cfg.slot_id, pCmd->cfg.dc, pCmd->cfg.ctx_ptr));
5022 slot = ID_TO_IDX(pCmd->cfg.slot_id);
5023 if ((slot >= RT_ELEMENTS(pThis->aSlotState)) || (pThis->aSlotState[slot] == XHCI_DEVSLOT_EMPTY))
5024 cc = XHCI_TCC_SLOT_NOT_ENB;
5025 else
5026 cc = xhciR3ConfigureDevice(pDevIns, pThis, pCmd->cfg.ctx_ptr, pCmd->cfg.slot_id, pCmd->cfg.dc);
5027 xhciR3PostCmdCompletion(pDevIns, pThis, cc, pCmd->cfg.slot_id);
5028 pThis->cmdr_dqp += sizeof(XHCI_COMMAND_TRB);
5029 break;
5030
5031 case XHCI_TRB_EVAL_CTX:
5032 /* Evaluate context. */
5033 Log(("Evaluate context: slot ID %u, Ctx @ %RGp\n", pCmd->evc.slot_id, pCmd->evc.ctx_ptr));
5034 slot = ID_TO_IDX(pCmd->evc.slot_id);
5035 if ((slot >= RT_ELEMENTS(pThis->aSlotState)) || (pThis->aSlotState[slot] == XHCI_DEVSLOT_EMPTY))
5036 cc = XHCI_TCC_SLOT_NOT_ENB;
5037 else
5038 cc = xhciR3EvalContext(pDevIns, pThis, pCmd->evc.ctx_ptr, pCmd->evc.slot_id);
5039 xhciR3PostCmdCompletion(pDevIns, pThis, cc, pCmd->evc.slot_id);
5040 pThis->cmdr_dqp += sizeof(XHCI_COMMAND_TRB);
5041 break;
5042
5043 case XHCI_TRB_RESET_EP:
5044 /* Reset the given endpoint. */
5045 Log(("Reset Endpoint: slot ID %u, EP ID %u, TSP=%u\n", pCmd->rse.slot_id, pCmd->rse.ep_id, pCmd->rse.tsp));
5046 slot = ID_TO_IDX(pCmd->rse.slot_id);
5047 if ((slot >= RT_ELEMENTS(pThis->aSlotState)) || (pThis->aSlotState[slot] == XHCI_DEVSLOT_EMPTY))
5048 cc = XHCI_TCC_SLOT_NOT_ENB;
5049 else
5050 cc = xhciR3ResetEndpoint(pDevIns, pThis, pCmd->rse.slot_id, pCmd->rse.ep_id, pCmd->rse.tsp);
5051 xhciR3PostCmdCompletion(pDevIns, pThis, cc, pCmd->stp.slot_id);
5052 pThis->cmdr_dqp += sizeof(XHCI_COMMAND_TRB);
5053 break;
5054
5055 case XHCI_TRB_STOP_EP:
5056 /* Stop the given endpoint. */
5057 Log(("Stop Endpoint: slot ID %u, EP ID %u, SP=%u\n", pCmd->stp.slot_id, pCmd->stp.ep_id, pCmd->stp.sp));
5058 slot = ID_TO_IDX(pCmd->stp.slot_id);
5059 if ((slot >= RT_ELEMENTS(pThis->aSlotState)) || (pThis->aSlotState[slot] == XHCI_DEVSLOT_EMPTY))
5060 cc = XHCI_TCC_SLOT_NOT_ENB;
5061 else
5062 cc = xhciR3StopEndpoint(pDevIns, pThis, pThisCC, pCmd->stp.slot_id, pCmd->stp.ep_id, pCmd->stp.sp);
5063 xhciR3PostCmdCompletion(pDevIns, pThis, cc, pCmd->stp.slot_id);
5064 pThis->cmdr_dqp += sizeof(XHCI_COMMAND_TRB);
5065 break;
5066
5067 case XHCI_TRB_SET_DEQ_PTR:
5068 /* Set TR Dequeue Pointer. */
5069 Log(("Set TRDP: slot ID %u, EP ID %u, TRDP=%RX64\n", pCmd->stdp.slot_id, pCmd->stdp.ep_id, pCmd->stdp.tr_dqp));
5070 slot = ID_TO_IDX(pCmd->stdp.slot_id);
5071 if ((slot >= RT_ELEMENTS(pThis->aSlotState)) || (pThis->aSlotState[slot] == XHCI_DEVSLOT_EMPTY))
5072 cc = XHCI_TCC_SLOT_NOT_ENB;
5073 else
5074 cc = xhciR3SetTRDP(pDevIns, pThis, pCmd->stdp.slot_id, pCmd->stdp.ep_id, pCmd->stdp.tr_dqp);
5075 xhciR3PostCmdCompletion(pDevIns, pThis, cc, pCmd->stdp.slot_id);
5076 pThis->cmdr_dqp += sizeof(XHCI_COMMAND_TRB);
5077 break;
5078
5079 case XHCI_TRB_RESET_DEV:
5080 /* Reset a device. */
5081 Log(("Reset Device: slot ID %u\n", pCmd->rsd.slot_id));
5082 slot = ID_TO_IDX(pCmd->rsd.slot_id);
5083 if ((slot >= RT_ELEMENTS(pThis->aSlotState)) || (pThis->aSlotState[slot] == XHCI_DEVSLOT_EMPTY))
5084 cc = XHCI_TCC_SLOT_NOT_ENB;
5085 else
5086 cc = xhciR3ResetDevice(pDevIns, pThis, pCmd->rsd.slot_id);
5087 xhciR3PostCmdCompletion(pDevIns, pThis, cc, pCmd->rsd.slot_id);
5088 pThis->cmdr_dqp += sizeof(XHCI_COMMAND_TRB);
5089 break;
5090
5091 case XHCI_TRB_GET_PORT_BW:
5092 /* Get port bandwidth. */
5093 Log(("Get Port Bandwidth: Dev Speed %u, Hub Slot ID %u, Context=%RX64\n", pCmd->gpbw.spd, pCmd->gpbw.slot_id, pCmd->gpbw.pbctx_ptr));
5094 if (pCmd->gpbw.slot_id)
5095 cc = XHCI_TCC_PARM_ERR; /* Potential undefined behavior, see 4.6.15. */
5096 else
5097 cc = xhciR3GetPortBandwidth(pDevIns, pThis, pCmd->gpbw.spd, pCmd->gpbw.slot_id, pCmd->gpbw.pbctx_ptr);
5098 xhciR3PostCmdCompletion(pDevIns, pThis, cc, 0);
5099 pThis->cmdr_dqp += sizeof(XHCI_COMMAND_TRB);
5100 break;
5101
5102 case NEC_TRB_GET_FW_VER:
5103 /* Get NEC firmware version. */
5104 Log(("Get NEC firmware version\n"));
5105 cc = XHCI_TCC_SUCCESS;
5106
5107 RT_ZERO(ed);
5108 ed.nce.word1 = NEC_FW_REV;
5109 ed.nce.trb_ptr = pThis->cmdr_dqp;
5110 ed.nce.cc = cc;
5111 ed.nce.type = NEC_TRB_CMD_CMPL;
5112
5113 xhciR3WriteEvent(pDevIns, pThis, &ed, XHCI_PRIMARY_INTERRUPTER, false);
5114
5115 pThis->cmdr_dqp += sizeof(XHCI_COMMAND_TRB);
5116 break;
5117
5118 case NEC_TRB_AUTHENTICATE:
5119 /* NEC authentication. */
5120 Log(("NEC authentication, cookie %RX64\n", pCmd->nac.cookie));
5121 cc = XHCI_TCC_SUCCESS;
5122
5123 token = xhciR3NecAuthenticate(pCmd->nac.cookie);
5124 RT_ZERO(ed);
5125 ed.nce.word1 = RT_LOWORD(token);
5126 ed.nce.word2 = RT_HIWORD(token);
5127 ed.nce.trb_ptr = pThis->cmdr_dqp;
5128 ed.nce.cc = cc;
5129 ed.nce.type = NEC_TRB_CMD_CMPL;
5130
5131 xhciR3WriteEvent(pDevIns, pThis, &ed, XHCI_PRIMARY_INTERRUPTER, false);
5132
5133 pThis->cmdr_dqp += sizeof(XHCI_COMMAND_TRB);
5134 break;
5135
5136 default:
5137 Log(("Unsupported command!\n"));
5138 pThis->cmdr_dqp += sizeof(XHCI_COMMAND_TRB);
5139 break;
5140 }
5141
5142 return rc;
5143}
5144
5145
5146/**
5147 * Stop the Command Ring.
5148 */
5149static int xhciR3StopCommandRing(PPDMDEVINS pDevIns, PXHCI pThis)
5150{
5151 LogFlowFunc(("Command Ring stopping\n"));
5152
5153 Assert(pThis->crcr & (XHCI_CRCR_CA | XHCI_CRCR_CS));
5154 Assert(pThis->crcr & XHCI_CRCR_CRR);
5155 ASMAtomicAndU64(&pThis->crcr, ~(XHCI_CRCR_CRR | XHCI_CRCR_CA | XHCI_CRCR_CS));
5156 return xhciR3PostCmdCompletion(pDevIns, pThis, XHCI_TCC_CMDR_STOPPED, 0);
5157}
5158
5159
5160/**
5161 * Process the xHCI command ring.
5162 */
5163static int xhciR3ProcessCommandRing(PPDMDEVINS pDevIns, PXHCI pThis, PXHCICC pThisCC)
5164{
5165 RTGCPHYS GCPhysCmdTRB;
5166 XHCI_COMMAND_TRB cmd; /* Command Descriptor */
5167 unsigned cCmds;
5168
5169 Assert(pThis->crcr & XHCI_CRCR_CRR);
5170 LogFlowFunc(("Processing commands...\n"));
5171
5172 for (cCmds = 0;; cCmds++)
5173 {
5174 /* First check if the xHC is running at all. */
5175 if (!(pThis->cmd & XHCI_CMD_RS))
5176 {
5177 /* Note that this will call xhciR3PostCmdCompletion() which will
5178 * end up doing nothing because R/S is clear.
5179 */
5180 xhciR3StopCommandRing(pDevIns, pThis);
5181 break;
5182 }
5183
5184 /* Check if Command Ring was stopped in the meantime. */
5185 if (pThis->crcr & (XHCI_CRCR_CS | XHCI_CRCR_CA))
5186 {
5187 /* NB: We currently do not abort commands. If we did, we would
5188 * abort the currently running command and complete it with
5189 * the XHCI_TCC_CMD_ABORTED status.
5190 */
5191 xhciR3StopCommandRing(pDevIns, pThis);
5192 break;
5193 }
5194
5195 /* Fetch the command TRB. */
5196 GCPhysCmdTRB = pThis->cmdr_dqp;
5197 PDMDevHlpPCIPhysReadMeta(pDevIns, GCPhysCmdTRB, &cmd, sizeof(cmd));
5198
5199 /* Make sure the Cycle State matches. */
5200 if ((bool)cmd.gen.cycle == pThis->cmdr_ccs)
5201 xhciR3ExecuteCommand(pDevIns, pThis, pThisCC, &cmd);
5202 else
5203 {
5204 Log(("Command Ring empty\n"));
5205 break;
5206 }
5207
5208 /* Check if we're being fed suspiciously many commands. */
5209 if (cCmds > XHCI_MAX_NUM_CMDS)
5210 {
5211 /* Clear the R/S bit and any command ring running bits.
5212 * Note that the caller (xhciR3WorkerLoop) will set XHCI_STATUS_HCH.
5213 */
5214 ASMAtomicAndU32(&pThis->cmd, ~XHCI_CMD_RS);
5215 ASMAtomicAndU64(&pThis->crcr, ~(XHCI_CRCR_CRR | XHCI_CRCR_CA | XHCI_CRCR_CS));
5216 ASMAtomicOrU32(&pThis->status, XHCI_STATUS_HCE);
5217 LogRelMax(10, ("xHCI: Attempted to execute too many commands, stopping xHC!\n"));
5218 break;
5219 }
5220 }
5221 return VINF_SUCCESS;
5222}
5223
5224
5225/**
5226 * The xHCI asynchronous worker thread.
5227 *
5228 * @returns VBox status code.
5229 * @param pDevIns The xHCI device instance.
5230 * @param pThread The worker thread.
5231 */
5232static DECLCALLBACK(int) xhciR3WorkerLoop(PPDMDEVINS pDevIns, PPDMTHREAD pThread)
5233{
5234 PXHCI pThis = PDMDEVINS_2_DATA(pDevIns, PXHCI);
5235 PXHCICC pThisCC = PDMDEVINS_2_DATA_CC(pDevIns, PXHCICC);
5236 int rc;
5237
5238 LogFlow(("xHCI entering worker thread loop.\n"));
5239 if (pThread->enmState == PDMTHREADSTATE_INITIALIZING)
5240 return VINF_SUCCESS;
5241
5242 while (pThread->enmState == PDMTHREADSTATE_RUNNING)
5243 {
5244 uint8_t uSlotID;
5245
5246 bool fNotificationSent = ASMAtomicXchgBool(&pThis->fNotificationSent, false);
5247 if (!fNotificationSent)
5248 {
5249 rc = PDMDevHlpSUPSemEventWaitNoResume(pDevIns, pThis->hEvtProcess, RT_INDEFINITE_WAIT);
5250 AssertLogRelMsgReturn(RT_SUCCESS(rc) || rc == VERR_INTERRUPTED, ("%Rrc\n", rc), rc);
5251 if (RT_UNLIKELY(pThread->enmState != PDMTHREADSTATE_RUNNING))
5252 break;
5253 LogFlowFunc(("Woken up with rc=%Rrc\n", rc));
5254 ASMAtomicWriteBool(&pThis->fNotificationSent, false);
5255 }
5256
5257 RTCritSectEnter(&pThisCC->CritSectThrd);
5258
5259 if (pThis->crcr & XHCI_CRCR_CRR)
5260 xhciR3ProcessCommandRing(pDevIns, pThis, pThisCC);
5261
5262 /* Run down the list of doorbells that are ringing. */
5263 for (uSlotID = 1; uSlotID < XHCI_NDS; ++uSlotID)
5264 {
5265 if (pThis->aSlotState[ID_TO_IDX(uSlotID)] >= XHCI_DEVSLOT_ENABLED)
5266 {
5267 while (pThis->aBellsRung[ID_TO_IDX(uSlotID)])
5268 {
5269 uint8_t bit;
5270 uint32_t uDBVal = 0;
5271
5272 for (bit = 0; bit < 32; ++bit)
5273 if (pThis->aBellsRung[ID_TO_IDX(uSlotID)] & (1 << bit))
5274 {
5275 uDBVal = bit;
5276 break;
5277 }
5278
5279 Log2(("Stop ringing bell for slot %u, DCI %u\n", uSlotID, uDBVal));
5280 ASMAtomicAndU32(&pThis->aBellsRung[ID_TO_IDX(uSlotID)], ~(1 << uDBVal));
5281 xhciR3ProcessDevCtx(pDevIns, pThis, pThisCC, uSlotID, uDBVal);
5282 }
5283 }
5284 }
5285
5286 /* If the R/S bit is no longer set, halt the xHC. */
5287 if (!(pThis->cmd & XHCI_CMD_RS))
5288 {
5289 Log(("R/S clear, halting the xHC.\n"));
5290 ASMAtomicOrU32(&pThis->status, XHCI_STATUS_HCH);
5291 }
5292
5293 RTCritSectLeave(&pThisCC->CritSectThrd);
5294 } /* While running */
5295
5296 LogFlow(("xHCI worker thread exiting.\n"));
5297 return VINF_SUCCESS;
5298}
5299
5300
5301/**
5302 * Unblock the worker thread so it can respond to a state change.
5303 *
5304 * @returns VBox status code.
5305 * @param pDevIns The xHCI device instance.
5306 * @param pThread The worker thread.
5307 */
5308static DECLCALLBACK(int) xhciR3WorkerWakeUp(PPDMDEVINS pDevIns, PPDMTHREAD pThread)
5309{
5310 NOREF(pThread);
5311 PXHCI pThis = PDMDEVINS_2_DATA(pDevIns, PXHCI);
5312
5313 return PDMDevHlpSUPSemEventSignal(pDevIns, pThis->hEvtProcess);
5314}
5315
5316
5317/**
5318 * @interface_method_impl{PDMIBASE,pfnQueryInterface}
5319 */
5320static DECLCALLBACK(void *) xhciR3RhQueryInterface(PPDMIBASE pInterface, const char *pszIID)
5321{
5322 PXHCIROOTHUBR3 pRh = RT_FROM_MEMBER(pInterface, XHCIROOTHUBR3, IBase);
5323 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIBASE, &pRh->IBase);
5324 PDMIBASE_RETURN_INTERFACE(pszIID, VUSBIROOTHUBPORT, &pRh->IRhPort);
5325 return NULL;
5326}
5327
5328/**
5329 * @interface_method_impl{PDMIBASE,pfnQueryInterface}
5330 */
5331static DECLCALLBACK(void *) xhciR3QueryStatusInterface(PPDMIBASE pInterface, const char *pszIID)
5332{
5333 PXHCIR3 pThisCC = RT_FROM_MEMBER(pInterface, XHCIR3, IBase);
5334 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIBASE, &pThisCC->IBase);
5335 PDMIBASE_RETURN_INTERFACE(pszIID, PDMILEDPORTS, &pThisCC->ILeds);
5336 return NULL;
5337}
5338
5339/**
5340 * Gets the pointer to the status LED of a unit.
5341 *
5342 * @returns VBox status code.
5343 * @param pInterface Pointer to the interface structure containing the called function pointer.
5344 * @param iLUN The unit which status LED we desire.
5345 * @param ppLed Where to store the LED pointer.
5346 */
5347static DECLCALLBACK(int) xhciR3QueryStatusLed(PPDMILEDPORTS pInterface, unsigned iLUN, PPDMLED *ppLed)
5348{
5349 PXHCICC pThisCC = RT_FROM_MEMBER(pInterface, XHCIR3, ILeds);
5350
5351 if (iLUN < XHCI_NUM_LUNS)
5352 {
5353 *ppLed = iLUN ? &pThisCC->RootHub3.Led : &pThisCC->RootHub2.Led;
5354 Assert((*ppLed)->u32Magic == PDMLED_MAGIC);
5355 return VINF_SUCCESS;
5356 }
5357 return VERR_PDM_LUN_NOT_FOUND;
5358}
5359
5360
5361/**
5362 * Get the number of ports available in the hub.
5363 *
5364 * @returns The number of ports available.
5365 * @param pInterface Pointer to this structure.
5366 * @param pAvailable Bitmap indicating the available ports. Set bit == available port.
5367 */
5368static DECLCALLBACK(unsigned) xhciR3RhGetAvailablePorts(PVUSBIROOTHUBPORT pInterface, PVUSBPORTBITMAP pAvailable)
5369{
5370 PXHCIROOTHUBR3 pRh = RT_FROM_MEMBER(pInterface, XHCIROOTHUBR3, IRhPort);
5371 PXHCICC pThisCC = pRh->pXhciR3;
5372 PPDMDEVINS pDevIns = pThisCC->pDevIns;
5373 unsigned iPort;
5374 unsigned cPorts = 0;
5375 LogFlow(("xhciR3RhGetAvailablePorts\n"));
5376
5377 memset(pAvailable, 0, sizeof(*pAvailable));
5378
5379 int const rcLock = PDMDevHlpCritSectEnter(pDevIns, pDevIns->pCritSectRoR3, VERR_IGNORED);
5380 PDM_CRITSECT_RELEASE_ASSERT_RC_DEV(pDevIns, pDevIns->pCritSectRoR3, rcLock);
5381
5382 for (iPort = pRh->uPortBase; iPort < (unsigned)pRh->uPortBase + pRh->cPortsImpl; iPort++)
5383 {
5384 Assert(iPort < XHCI_NDP_CFG(PDMDEVINS_2_DATA(pDevIns, PXHCI)));
5385 if (!pThisCC->aPorts[iPort].fAttached)
5386 {
5387 cPorts++;
5388 ASMBitSet(pAvailable, IDX_TO_ID(iPort - pRh->uPortBase));
5389 }
5390 }
5391
5392 PDMDevHlpCritSectLeave(pDevIns, pDevIns->pCritSectRoR3);
5393 return cPorts;
5394}
5395
5396
5397/**
5398 * Get the supported USB versions for USB2 hubs.
5399 *
5400 * @returns The mask of supported USB versions.
5401 * @param pInterface Pointer to this structure.
5402 */
5403static DECLCALLBACK(uint32_t) xhciR3RhGetUSBVersions2(PVUSBIROOTHUBPORT pInterface)
5404{
5405 RT_NOREF(pInterface);
5406 return VUSB_STDVER_11 | VUSB_STDVER_20;
5407}
5408
5409
5410/**
5411 * Get the supported USB versions for USB2 hubs.
5412 *
5413 * @returns The mask of supported USB versions.
5414 * @param pInterface Pointer to this structure.
5415 */
5416static DECLCALLBACK(uint32_t) xhciR3RhGetUSBVersions3(PVUSBIROOTHUBPORT pInterface)
5417{
5418 RT_NOREF(pInterface);
5419 return VUSB_STDVER_30;
5420}
5421
5422
5423/**
5424 * Start sending SOF tokens across the USB bus, lists are processed in the
5425 * next frame.
5426 */
5427static void xhciR3BusStart(PPDMDEVINS pDevIns, PXHCI pThis, PXHCICC pThisCC)
5428{
5429 unsigned iPort;
5430
5431 pThisCC->RootHub2.pIRhConn->pfnPowerOn(pThisCC->RootHub2.pIRhConn);
5432 pThisCC->RootHub3.pIRhConn->pfnPowerOn(pThisCC->RootHub3.pIRhConn);
5433// xhciR3BumpFrameNumber(pThis);
5434
5435 Log(("xHCI: Bus started\n"));
5436
5437 Assert(pThis->status & XHCI_STATUS_HCH);
5438 ASMAtomicAndU32(&pThis->status, ~XHCI_STATUS_HCH);
5439
5440 /* HCH gates PSCEG (4.19.2). When clearing HCH, re-evaluate port changes. */
5441 for (iPort = 0; iPort < XHCI_NDP_CFG(pThis); ++iPort)
5442 {
5443 if (pThis->aPorts[iPort].portsc & XHCI_PORT_CHANGE_MASK)
5444 xhciR3GenPortChgEvent(pDevIns, pThis, IDX_TO_ID(iPort));
5445 }
5446
5447 /// @todo record the starting time?
5448// pThis->SofTime = TMTimerGet(pThis->CTX_SUFF(pEndOfFrameTimer)) - pThis->cTicksPerFrame;
5449}
5450
5451/**
5452 * Stop sending SOF tokens on the bus and processing the data.
5453 */
5454static void xhciR3BusStop(PPDMDEVINS pDevIns, PXHCI pThis, PXHCICC pThisCC)
5455{
5456 LogFlow(("xhciR3BusStop\n"));
5457
5458 /* Stop the controller and Command Ring. */
5459 pThis->cmd &= ~XHCI_CMD_RS;
5460 pThis->crcr |= XHCI_CRCR_CS;
5461
5462 /* Power off the root hubs. */
5463 pThisCC->RootHub2.pIRhConn->pfnPowerOff(pThisCC->RootHub2.pIRhConn);
5464 pThisCC->RootHub3.pIRhConn->pfnPowerOff(pThisCC->RootHub3.pIRhConn);
5465
5466 /* The worker thread will halt the HC (set HCH) when done. */
5467 xhciKickWorker(pDevIns, pThis, XHCI_JOB_PROCESS_CMDRING, 0);
5468}
5469
5470
5471/**
5472 * Power a port up or down
5473 */
5474static void xhciR3PortPower(PXHCI pThis, PXHCICC pThisCC, unsigned iPort, bool fPowerUp)
5475{
5476 PXHCIHUBPORT pPort = &pThis->aPorts[iPort];
5477 PXHCIHUBPORTR3 pPortR3 = &pThisCC->aPorts[iPort];
5478 PXHCIROOTHUBR3 pRh = GET_PORT_PRH(pThisCC, iPort);
5479
5480 bool fOldPPS = !!(pPort->portsc & XHCI_PORT_PP);
5481 LogFlow(("xhciR3PortPower (port %u) %s\n", IDX_TO_ID(iPort), fPowerUp ? "UP" : "DOWN"));
5482
5483 if (fPowerUp)
5484 {
5485 /* Power up a port. */
5486 if (pPortR3->fAttached)
5487 ASMAtomicOrU32(&pPort->portsc, XHCI_PORT_CCS);
5488 if (pPort->portsc & XHCI_PORT_CCS)
5489 ASMAtomicOrU32(&pPort->portsc, XHCI_PORT_PP);
5490 if (pPortR3->fAttached && !fOldPPS)
5491 VUSBIRhDevPowerOn(pRh->pIRhConn, GET_VUSB_PORT_FROM_XHCI_PORT(pRh, iPort));
5492 }
5493 else
5494 {
5495 /* Power down. */
5496 ASMAtomicAndU32(&pPort->portsc, ~(XHCI_PORT_PP | XHCI_PORT_CCS));
5497 if (pPortR3->fAttached && fOldPPS)
5498 VUSBIRhDevPowerOff(pRh->pIRhConn, GET_VUSB_PORT_FROM_XHCI_PORT(pRh, iPort));
5499 }
5500}
5501
5502
5503/**
5504 * Port reset done callback.
5505 *
5506 * @param pDevIns The device instance data.
5507 * @param iPort The XHCI port index of the port being resetted.
5508 */
5509static void xhciR3PortResetDone(PPDMDEVINS pDevIns, unsigned iPort)
5510{
5511 PXHCI pThis = PDMDEVINS_2_DATA(pDevIns, PXHCI);
5512
5513 Log2(("xhciR3PortResetDone\n"));
5514
5515 AssertReturnVoid(iPort < XHCI_NDP_CFG(pThis));
5516
5517 /*
5518 * Successful reset.
5519 */
5520 Log2(("xhciR3PortResetDone: Reset completed.\n"));
5521
5522 uint32_t fChangeMask = XHCI_PORT_PED | XHCI_PORT_PRC;
5523 /* For USB2 ports, transition the link state. */
5524 if (!IS_USB3_PORT_IDX_SHR(pThis, iPort))
5525 {
5526 pThis->aPorts[iPort].portsc &= ~XHCI_PORT_PLS_MASK;
5527 pThis->aPorts[iPort].portsc |= XHCI_PLS_U0 << XHCI_PORT_PLS_SHIFT;
5528 }
5529 else
5530 {
5531 if (pThis->aPorts[iPort].portsc & XHCI_PORT_WPR)
5532 fChangeMask |= XHCI_PORT_WRC;
5533 }
5534
5535 ASMAtomicAndU32(&pThis->aPorts[iPort].portsc, ~(XHCI_PORT_PR | XHCI_PORT_WPR));
5536 ASMAtomicOrU32(&pThis->aPorts[iPort].portsc, fChangeMask);
5537 /// @todo Set USBSTS.PCD and manage PSCEG correctly!
5538 /// @todo just guessing?!
5539// ASMAtomicOrU32(&pThis->aPorts[iPort].portsc, XHCI_PORT_CSC | XHCI_PORT_PLC);
5540
5541 /// @todo Is this the right place?
5542 xhciR3GenPortChgEvent(pDevIns, pThis, IDX_TO_ID(iPort));
5543}
5544
5545
5546/**
5547 * Sets a flag in a port status register, but only if a device is connected;
5548 * if not, set ConnectStatusChange flag to force HCD to reevaluate connect status.
5549 *
5550 * @returns true if device was connected and the flag was cleared.
5551 */
5552static bool xhciR3RhPortSetIfConnected(PXHCI pThis, unsigned iPort, uint32_t fValue)
5553{
5554 /*
5555 * Writing a 0 has no effect
5556 */
5557 if (fValue == 0)
5558 return false;
5559
5560 /*
5561 * The port might be still/already disconnected.
5562 */
5563 if (!(pThis->aPorts[iPort].portsc & XHCI_PORT_CCS))
5564 return false;
5565
5566 bool fRc = !(pThis->aPorts[iPort].portsc & fValue);
5567
5568 /* Set the bit. */
5569 ASMAtomicOrU32(&pThis->aPorts[iPort].portsc, fValue);
5570
5571 return fRc;
5572}
5573
5574
5575/** Translate VUSB speed enum to xHCI definition. */
5576static unsigned xhciR3UsbSpd2XhciSpd(VUSBSPEED enmSpeed)
5577{
5578 unsigned uSpd;
5579
5580 switch (enmSpeed)
5581 {
5582 default: AssertMsgFailed(("%d\n", enmSpeed));
5583 RT_FALL_THRU();
5584 case VUSB_SPEED_LOW: uSpd = XHCI_SPD_LOW; break;
5585 case VUSB_SPEED_FULL: uSpd = XHCI_SPD_FULL; break;
5586 case VUSB_SPEED_HIGH: uSpd = XHCI_SPD_HIGH; break;
5587 case VUSB_SPEED_SUPER: uSpd = XHCI_SPD_SUPER; break;
5588 }
5589 return uSpd;
5590}
5591
5592/** @interface_method_impl{VUSBIROOTHUBPORT,pfnAttach} */
5593static DECLCALLBACK(int) xhciR3RhAttach(PVUSBIROOTHUBPORT pInterface, unsigned uPort, VUSBSPEED enmSpeed)
5594{
5595 PXHCIROOTHUBR3 pRh = RT_FROM_MEMBER(pInterface, XHCIROOTHUBR3, IRhPort);
5596 PXHCICC pThisCC = pRh->pXhciR3;
5597 PPDMDEVINS pDevIns = pThisCC->pDevIns;
5598 PXHCI pThis = PDMDEVINS_2_DATA(pDevIns, PXHCI);
5599 PXHCIHUBPORT pPort;
5600 unsigned iPort;
5601 LogFlow(("xhciR3RhAttach: uPort=%u (iPort=%u)\n", uPort, ID_TO_IDX(uPort) + pRh->uPortBase));
5602
5603 int const rcLock = PDMDevHlpCritSectEnter(pDevIns, pDevIns->pCritSectRoR3, VERR_IGNORED);
5604 AssertRCReturn(rcLock, rcLock);
5605
5606 /*
5607 * Validate and adjust input.
5608 */
5609 Assert(uPort >= 1 && uPort <= pRh->cPortsImpl);
5610 iPort = ID_TO_IDX(uPort) + pRh->uPortBase;
5611 Assert(iPort < XHCI_NDP_CFG(pThis));
5612 pPort = &pThis->aPorts[iPort];
5613 Assert(!pThisCC->aPorts[iPort].fAttached);
5614 Assert(enmSpeed != VUSB_SPEED_UNKNOWN);
5615
5616 /*
5617 * Attach it.
5618 */
5619 ASMAtomicOrU32(&pPort->portsc, XHCI_PORT_CCS | XHCI_PORT_CSC);
5620 pThisCC->aPorts[iPort].fAttached = true;
5621 xhciR3PortPower(pThis, pThisCC, iPort, 1 /* power on */);
5622
5623 /* USB3 ports automatically transition to Enabled state. */
5624 if (IS_USB3_PORT_IDX_R3(pThisCC, iPort))
5625 {
5626 Assert(enmSpeed == VUSB_SPEED_SUPER);
5627 pPort->portsc |= XHCI_PORT_PED;
5628 pPort->portsc &= ~XHCI_PORT_PLS_MASK;
5629 pPort->portsc |= XHCI_PLS_U0 << XHCI_PORT_PLS_SHIFT;
5630 pPort->portsc &= ~XHCI_PORT_SPD_MASK;
5631 pPort->portsc |= XHCI_SPD_SUPER << XHCI_PORT_SPD_SHIFT;
5632 VUSBIRhDevReset(pRh->pIRhConn, GET_VUSB_PORT_FROM_XHCI_PORT(pRh, iPort),
5633 false, NULL /* sync */, NULL, PDMDevHlpGetVM(pDevIns));
5634 }
5635 else
5636 {
5637 Assert(enmSpeed == VUSB_SPEED_LOW || enmSpeed == VUSB_SPEED_FULL || enmSpeed == VUSB_SPEED_HIGH);
5638 pPort->portsc &= ~XHCI_PORT_SPD_MASK;
5639 pPort->portsc |= xhciR3UsbSpd2XhciSpd(enmSpeed) << XHCI_PORT_SPD_SHIFT;
5640 }
5641
5642 xhciR3GenPortChgEvent(pDevIns, pThis, IDX_TO_ID(iPort));
5643
5644 PDMDevHlpCritSectLeave(pDevIns, pDevIns->pCritSectRoR3);
5645 return VINF_SUCCESS;
5646}
5647
5648
5649/**
5650 * A device is being detached from a port in the root hub.
5651 *
5652 * @param pInterface Pointer to this structure.
5653 * @param uPort The 1-based port number assigned to the device.
5654 */
5655static DECLCALLBACK(void) xhciR3RhDetach(PVUSBIROOTHUBPORT pInterface, unsigned uPort)
5656{
5657 PXHCIROOTHUBR3 pRh = RT_FROM_MEMBER(pInterface, XHCIROOTHUBR3, IRhPort);
5658 PXHCICC pThisCC = pRh->pXhciR3;
5659 PPDMDEVINS pDevIns = pThisCC->pDevIns;
5660 PXHCI pThis = PDMDEVINS_2_DATA(pDevIns, PXHCI);
5661 PXHCIHUBPORT pPort;
5662 unsigned iPort;
5663 LogFlow(("xhciR3RhDetach: uPort=%u iPort=%u\n", uPort, ID_TO_IDX(uPort) + pRh->uPortBase));
5664 int const rcLock = PDMDevHlpCritSectEnter(pDevIns, pDevIns->pCritSectRoR3, VERR_IGNORED);
5665 PDM_CRITSECT_RELEASE_ASSERT_RC_DEV(pDevIns, pDevIns->pCritSectRoR3, rcLock);
5666
5667 /*
5668 * Validate and adjust input.
5669 */
5670 Assert(uPort >= 1 && uPort <= pRh->cPortsImpl);
5671 iPort = ID_TO_IDX(uPort) + pRh->uPortBase;
5672 Assert(iPort < XHCI_NDP_CFG(pThis));
5673 pPort = &pThis->aPorts[iPort];
5674 Assert(pThisCC->aPorts[iPort].fAttached);
5675
5676 /*
5677 * Detach it.
5678 */
5679 pThisCC->aPorts[iPort].fAttached = false;
5680 ASMAtomicAndU32(&pPort->portsc, ~(XHCI_PORT_CCS | XHCI_PORT_SPD_MASK | XHCI_PORT_PLS_MASK));
5681 ASMAtomicOrU32(&pPort->portsc, XHCI_PORT_CSC);
5682 /* Link state goes to RxDetect. */
5683 ASMAtomicOrU32(&pPort->portsc, XHCI_PLS_RXDETECT << XHCI_PORT_PLS_SHIFT);
5684 /* Disconnect clears the port enable bit. */
5685 if (pPort->portsc & XHCI_PORT_PED)
5686 ASMAtomicAndU32(&pPort->portsc, ~XHCI_PORT_PED);
5687
5688 xhciR3GenPortChgEvent(pDevIns, pThis, IDX_TO_ID(iPort));
5689
5690 PDMDevHlpCritSectLeave(pDevIns, pDevIns->pCritSectRoR3);
5691}
5692
5693
5694/**
5695 * One of the root hub devices has completed its reset
5696 * operation.
5697 *
5698 * Currently, we don't think anything is required to be done here
5699 * so it's just a stub for forcing async resetting of the devices
5700 * during a root hub reset.
5701 *
5702 * @param pDev The root hub device.
5703 * @param rc The result of the operation.
5704 * @param uPort The port number of the device on the roothub being resetted.
5705 * @param pvUser Pointer to the controller.
5706 */
5707static DECLCALLBACK(void) xhciR3RhResetDoneOneDev(PVUSBIDEVICE pDev, uint32_t uPort, int rc, void *pvUser)
5708{
5709 LogRel(("xHCI: Root hub-attached device reset completed with %Rrc\n", rc));
5710 RT_NOREF(pDev, uPort, rc, pvUser);
5711}
5712
5713
5714/**
5715 * Does a software or hardware reset of the controller.
5716 *
5717 * This is called in response to setting HcCommandStatus.HCR, hardware reset,
5718 * and device construction.
5719 *
5720 * @param pThis The shared XHCI instance data
5721 * @param pThisCC The ring-3 XHCI instance data
5722 * @param fNewMode The new mode of operation. This is UsbSuspend if
5723 * it's a software reset, and UsbReset if it's a
5724 * hardware reset / cold boot.
5725 * @param fTrueReset Set if we can do a real reset of the devices
5726 * attached to the root hub. This is really a just a
5727 * hack for the non-working linux device reset. Linux
5728 * has this feature called 'logical disconnect' if
5729 * device reset fails which prevents us from doing
5730 * resets when the guest asks for it - the guest will
5731 * get confused when the device seems to be
5732 * reconnected everytime it tries to reset it. But if
5733 * we're at hardware reset time, we can allow a device
5734 * to be 'reconnected' without upsetting the guest.
5735 *
5736 * @remark This has nothing to do with software setting the
5737 * mode to UsbReset.
5738 */
5739static void xhciR3DoReset(PXHCI pThis, PXHCICC pThisCC, uint32_t fNewMode, bool fTrueReset)
5740{
5741 LogFunc(("%s reset%s\n", fNewMode == XHCI_USB_RESET ? "Hardware" : "Software",
5742 fTrueReset ? " (really reset devices)" : ""));
5743
5744 /*
5745 * Cancel all outstanding URBs.
5746 *
5747 * We can't, and won't, deal with URBs until we're moved out of the
5748 * suspend/reset state. Also, a real HC isn't going to send anything
5749 * any more when a reset has been signaled.
5750 */
5751 pThisCC->RootHub2.pIRhConn->pfnCancelAllUrbs(pThisCC->RootHub2.pIRhConn);
5752 pThisCC->RootHub3.pIRhConn->pfnCancelAllUrbs(pThisCC->RootHub3.pIRhConn);
5753
5754 /*
5755 * Reset the hardware registers.
5756 */
5757 /** @todo other differences between hardware reset and VM reset? */
5758
5759 pThis->cmd = 0;
5760 pThis->status = XHCI_STATUS_HCH;
5761 pThis->dnctrl = 0;
5762 pThis->crcr = 0;
5763 pThis->dcbaap = 0;
5764 pThis->config = 0;
5765
5766 /*
5767 * Reset the internal state.
5768 */
5769 pThis->cmdr_dqp = 0;
5770 pThis->cmdr_ccs = 0;
5771
5772 RT_ZERO(pThis->aSlotState);
5773 RT_ZERO(pThis->aBellsRung);
5774
5775 /* Zap everything but the lock. */
5776 for (unsigned i = 0; i < RT_ELEMENTS(pThis->aInterrupters); ++i)
5777 {
5778 pThis->aInterrupters[i].iman = 0;
5779 pThis->aInterrupters[i].imod = 0;
5780 pThis->aInterrupters[i].erstsz = 0;
5781 pThis->aInterrupters[i].erstba = 0;
5782 pThis->aInterrupters[i].erdp = 0;
5783 pThis->aInterrupters[i].erep = 0;
5784 pThis->aInterrupters[i].erst_idx = 0;
5785 pThis->aInterrupters[i].trb_count = 0;
5786 pThis->aInterrupters[i].evtr_pcs = false;
5787 pThis->aInterrupters[i].ipe = false;
5788 }
5789
5790 if (fNewMode == XHCI_USB_RESET)
5791 {
5792 /* Only a hardware reset reinits the port registers. */
5793 for (unsigned i = 0; i < XHCI_NDP_CFG(pThis); i++)
5794 {
5795 /* Need to preserve the speed of attached devices. */
5796 pThis->aPorts[i].portsc &= XHCI_PORT_SPD_MASK;
5797 pThis->aPorts[i].portsc |= XHCI_PLS_RXDETECT << XHCI_PORT_PLS_SHIFT;
5798 /* If Port Power Control is not supported, ports are always powered on. */
5799 if (!(pThis->hcc_params & XHCI_HCC_PPC))
5800 pThis->aPorts[i].portsc |= XHCI_PORT_PP;
5801 }
5802 }
5803
5804 /*
5805 * If this is a hardware reset, we will initialize the root hub too.
5806 * Software resets doesn't do this according to the specs.
5807 * (It's not possible to have a device connected at the time of the
5808 * device construction, so nothing to worry about there.)
5809 */
5810 if (fNewMode == XHCI_USB_RESET)
5811 {
5812 pThisCC->RootHub2.pIRhConn->pfnReset(pThisCC->RootHub2.pIRhConn, fTrueReset);
5813 pThisCC->RootHub3.pIRhConn->pfnReset(pThisCC->RootHub3.pIRhConn, fTrueReset);
5814
5815 /*
5816 * Reattach the devices.
5817 */
5818 for (unsigned i = 0; i < XHCI_NDP_CFG(pThis); i++)
5819 {
5820 bool fAttached = pThisCC->aPorts[i].fAttached;
5821 PXHCIROOTHUBR3 pRh = GET_PORT_PRH(pThisCC, i);
5822 pThisCC->aPorts[i].fAttached = false;
5823
5824 if (fAttached)
5825 {
5826 VUSBSPEED enmSpeed = VUSBIRhDevGetSpeed(pRh->pIRhConn, GET_VUSB_PORT_FROM_XHCI_PORT(pRh, i));
5827 xhciR3RhAttach(&pRh->IRhPort, GET_VUSB_PORT_FROM_XHCI_PORT(pRh, i), enmSpeed);
5828 }
5829 }
5830 }
5831}
5832
5833/**
5834 * Reset the root hub.
5835 *
5836 * @returns VBox status code.
5837 * @param pInterface Pointer to this structure.
5838 * @param fTrueReset This is used to indicate whether we're at VM reset
5839 * time and can do real resets or if we're at any other
5840 * time where that isn't such a good idea.
5841 * @remark Do NOT call VUSBIDevReset on the root hub in an async fashion!
5842 * @thread EMT
5843 */
5844static DECLCALLBACK(int) xhciR3RhReset(PVUSBIROOTHUBPORT pInterface, bool fTrueReset)
5845{
5846 PXHCIROOTHUBR3 pRh = RT_FROM_MEMBER(pInterface, XHCIROOTHUBR3, IRhPort);
5847 PXHCICC pThisCC = pRh->pXhciR3;
5848 PPDMDEVINS pDevIns = pThisCC->pDevIns;
5849 PXHCI pThis = PDMDEVINS_2_DATA(pDevIns, PXHCI);
5850
5851 Log(("xhciR3RhReset fTrueReset=%d\n", fTrueReset));
5852 int const rcLock = PDMDevHlpCritSectEnter(pDevIns, pDevIns->pCritSectRoR3, VERR_IGNORED);
5853 AssertRCReturn(rcLock, rcLock);
5854
5855 /* Soft reset first */
5856 xhciR3DoReset(pThis, pThisCC, XHCI_USB_SUSPEND, false /* N/A */);
5857
5858 /*
5859 * We're pretending to _reattach_ the devices without resetting them.
5860 * Except, during VM reset where we use the opportunity to do a proper
5861 * reset before the guest comes along and expects things.
5862 *
5863 * However, it's very very likely that we're not doing the right thing
5864 * here when end up here on request from the guest (USB Reset state).
5865 * The docs talk about root hub resetting, however what exact behaviour
5866 * in terms of root hub status and changed bits, and HC interrupts aren't
5867 * stated clearly. IF we get trouble and see the guest doing "USB Resets"
5868 * we will have to look into this. For the time being we stick with simple.
5869 */
5870 for (unsigned iPort = pRh->uPortBase; iPort < XHCI_NDP_CFG(pThis); iPort++)
5871 {
5872 if (pThisCC->aPorts[iPort].fAttached)
5873 {
5874 ASMAtomicOrU32(&pThis->aPorts[iPort].portsc, XHCI_PORT_CCS | XHCI_PORT_CSC);
5875 if (fTrueReset)
5876 VUSBIRhDevReset(pRh->pIRhConn, GET_VUSB_PORT_FROM_XHCI_PORT(pRh, iPort), fTrueReset,
5877 xhciR3RhResetDoneOneDev, pDevIns, PDMDevHlpGetVM(pDevIns));
5878 }
5879 }
5880
5881 PDMDevHlpCritSectLeave(pDevIns, pDevIns->pCritSectRoR3);
5882 return VINF_SUCCESS;
5883}
5884
5885#endif /* IN_RING3 */
5886
5887
5888
5889/* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- */
5890/* xHCI Operational Register access routines */
5891/* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- */
5892
5893
5894
5895/**
5896 * Read the USBCMD register of the host controller.
5897 */
5898static VBOXSTRICTRC HcUsbcmd_r(PPDMDEVINS pDevIns, PXHCI pThis, uint32_t iReg, uint32_t *pu32Value)
5899{
5900 RT_NOREF(pDevIns, iReg);
5901 STAM_COUNTER_INC(&pThis->StatRdUsbCmd);
5902 *pu32Value = pThis->cmd;
5903 return VINF_SUCCESS;
5904}
5905
5906/**
5907 * Write to the USBCMD register of the host controller.
5908 */
5909static VBOXSTRICTRC HcUsbcmd_w(PPDMDEVINS pDevIns, PXHCI pThis, uint32_t iReg, uint32_t val)
5910{
5911#ifdef IN_RING3
5912 PXHCICC pThisCC = PDMDEVINS_2_DATA_CC(pDevIns, PXHCICC);
5913#endif
5914 RT_NOREF(iReg);
5915 STAM_COUNTER_INC(&pThis->StatWrUsbCmd);
5916#ifdef LOG_ENABLED
5917 Log(("HcUsbcmd_w old=%x new=%x\n", pThis->cmd, val));
5918 if (val & XHCI_CMD_RS)
5919 Log((" XHCI_CMD_RS\n"));
5920 if (val & XHCI_CMD_HCRST)
5921 Log((" XHCI_CMD_HCRST\n"));
5922 if (val & XHCI_CMD_INTE )
5923 Log((" XHCI_CMD_INTE\n"));
5924 if (val & XHCI_CMD_HSEE)
5925 Log((" XHCI_CMD_HSEE\n"));
5926 if (val & XHCI_CMD_LCRST)
5927 Log((" XHCI_CMD_LCRST\n"));
5928 if (val & XHCI_CMD_CSS)
5929 Log((" XHCI_CMD_CSS\n"));
5930 if (val & XHCI_CMD_CRS)
5931 Log((" XHCI_CMD_CRS\n"));
5932 if (val & XHCI_CMD_EWE)
5933 Log((" XHCI_CMD_EWE\n"));
5934 if (val & XHCI_CMD_EU3S)
5935 Log((" XHCI_CMD_EU3S\n"));
5936#endif
5937
5938 if (val & ~XHCI_CMD_MASK)
5939 Log(("Unknown USBCMD bits %#x are set!\n", val & ~XHCI_CMD_MASK));
5940
5941
5942 /* First deal with resets. These must be done in R3 and will initialize
5943 * the USBCMD register.
5944 */
5945 if (val & (XHCI_CMD_HCRST | XHCI_CMD_LCRST))
5946 {
5947#ifdef IN_RING3
5948 /* NB: xhciR3DoReset() overwrites pThis->cmd */
5949 if (val & XHCI_CMD_HCRST)
5950 {
5951 LogRel(("xHCI: Hardware reset\n"));
5952 xhciR3DoReset(pThis, pThisCC, XHCI_USB_RESET, true /* reset devices */);
5953 }
5954 else if (val & XHCI_CMD_LCRST)
5955 {
5956 LogRel(("xHCI: Software reset\n"));
5957 xhciR3DoReset(pThis, pThisCC, XHCI_USB_SUSPEND, false /* N/A */);
5958 }
5959 else
5960 Assert(0);
5961
5962 return VINF_SUCCESS;
5963#else
5964 return VINF_IOM_R3_MMIO_WRITE;
5965#endif
5966 }
5967
5968 /* Not resetting, handle the remaining bits. */
5969 if (pThis->status & XHCI_STATUS_HCE)
5970 {
5971 /* If the HCE (HC Error) status bit is set, don't do anything.
5972 * Only a reset will clear the HCE bit.
5973 */
5974 Log(("xHCI: HCE bit set, ignoring USBCMD register changes!\n"));
5975 return VINF_SUCCESS;
5976 }
5977 else
5978 {
5979 /* See what changed and take action on that. First the R/S bit.
5980 * Note that R/S changes must also be done in R3, so we get them
5981 * out of the way first.
5982 * NB: xhciR3BusStop() modifies USBCMD.
5983 */
5984 uint32_t old_state = pThis->cmd & XHCI_CMD_RS;
5985 uint32_t new_state = val & XHCI_CMD_RS;
5986
5987 if (old_state != new_state)
5988 {
5989#ifdef IN_RING3
5990 switch (new_state)
5991 {
5992 case XHCI_CMD_RS:
5993 LogRel(("xHCI: USB Operational\n"));
5994 xhciR3BusStart(pDevIns, pThis, pThisCC);
5995 break;
5996 case 0:
5997 xhciR3BusStop(pDevIns, pThis, pThisCC);
5998 LogRel(("xHCI: USB Suspended\n"));
5999 break;
6000 }
6001#else
6002 return VINF_IOM_R3_MMIO_WRITE;
6003#endif
6004 }
6005
6006 /* Check EWE (Enable MFINDEX Wraparound Event) changes. */
6007 old_state = pThis->cmd & XHCI_CMD_EWE;
6008 new_state = val & XHCI_CMD_EWE;
6009
6010 if (old_state != new_state)
6011 {
6012 switch (new_state)
6013 {
6014 case XHCI_CMD_EWE:
6015 Log(("xHCI: MFINDEX Wrap timer started\n"));
6016 xhciSetWrapTimer(pDevIns, pThis);
6017 break;
6018 case 0:
6019 PDMDevHlpTimerStop(pDevIns, pThis->hWrapTimer);
6020 Log(("xHCI: MFINDEX Wrap timer stopped\n"));
6021 break;
6022 }
6023 }
6024
6025 /* INTE transitions need to twiddle interrupts. */
6026 old_state = pThis->cmd & XHCI_CMD_INTE;
6027 new_state = val & XHCI_CMD_INTE;
6028 if (old_state != new_state)
6029 {
6030 switch (new_state)
6031 {
6032 case XHCI_CMD_INTE:
6033 /* Check whether the event interrupt bit is set and trigger an interrupt. */
6034 if (pThis->status & XHCI_STATUS_EINT)
6035 PDMDevHlpPCISetIrq(pDevIns, 0, PDM_IRQ_LEVEL_HIGH);
6036 break;
6037 case 0:
6038 PDMDevHlpPCISetIrq(pDevIns, 0, PDM_IRQ_LEVEL_LOW);
6039 break;
6040 }
6041 }
6042
6043 /* We currently do nothing for state save/restore. If we did, the CSS/CRS command bits
6044 * would set the SSS/RSS status bits until the operation is done. The CSS/CRS bits are
6045 * never read as one.
6046 */
6047 /// @todo 4.9.4 describes internal state that needs to be saved/restored:
6048 /// ERSTE, ERST Count, EREP, and TRB Count
6049 /// Command Ring Dequeue Pointer?
6050 if (val & XHCI_CMD_CSS)
6051 {
6052 Log(("xHCI: Save State requested\n"));
6053 val &= ~XHCI_CMD_CSS;
6054 }
6055
6056 if (val & XHCI_CMD_CRS)
6057 {
6058 Log(("xHCI: Restore State requested\n"));
6059 val &= ~XHCI_CMD_CRS;
6060 }
6061 }
6062
6063 /* Finally update the USBCMD register. */
6064 pThis->cmd = val;
6065
6066 return VINF_SUCCESS;
6067}
6068
6069#ifdef LOG_ENABLED
6070static void HcUsbstsLogBits(uint32_t val)
6071{
6072 if (val & XHCI_STATUS_HCH)
6073 Log((" XHCI_STATUS_HCH (HC Halted)\n"));
6074 if (val & XHCI_STATUS_HSE)
6075 Log((" XHCI_STATUS_HSE (Host System Error)\n"));
6076 if (val & XHCI_STATUS_EINT)
6077 Log((" XHCI_STATUS_EINT (Event Interrupt)\n"));
6078 if (val & XHCI_STATUS_PCD)
6079 Log((" XHCI_STATUS_PCD (Port Change Detect)\n"));
6080 if (val & XHCI_STATUS_SSS)
6081 Log((" XHCI_STATUS_SSS (Save State Status)\n"));
6082 if (val & XHCI_STATUS_RSS)
6083 Log((" XHCI_STATUS_RSS (Restore State Status)\n"));
6084 if (val & XHCI_STATUS_SRE)
6085 Log((" XHCI_STATUS_SRE (Save/Restore Error)\n"));
6086 if (val & XHCI_STATUS_CNR)
6087 Log((" XHCI_STATUS_CNR (Controller Not Ready)\n"));
6088 if (val & XHCI_STATUS_HCE)
6089 Log((" XHCI_STATUS_HCE (Host Controller Error)\n"));
6090}
6091#endif
6092
6093/**
6094 * Read the USBSTS register of the host controller.
6095 */
6096static VBOXSTRICTRC HcUsbsts_r(PPDMDEVINS pDevIns, PXHCI pThis, uint32_t iReg, uint32_t *pu32Value)
6097{
6098#ifdef LOG_ENABLED
6099 Log(("HcUsbsts_r current value %x\n", pThis->status));
6100 HcUsbstsLogBits(pThis->status);
6101#endif
6102 RT_NOREF(pDevIns, iReg);
6103 STAM_COUNTER_INC(&pThis->StatRdUsbSts);
6104
6105 *pu32Value = pThis->status;
6106 return VINF_SUCCESS;
6107}
6108
6109/**
6110 * Write to the USBSTS register of the host controller.
6111 */
6112static VBOXSTRICTRC HcUsbsts_w(PPDMDEVINS pDevIns, PXHCI pThis, uint32_t iReg, uint32_t val)
6113{
6114#ifdef LOG_ENABLED
6115 Log(("HcUsbsts_w current value %x; new %x\n", pThis->status, val));
6116 HcUsbstsLogBits(val);
6117#endif
6118 RT_NOREF(pDevIns, iReg);
6119 STAM_COUNTER_INC(&pThis->StatWrUsbSts);
6120
6121 if ( (val & ~XHCI_STATUS_WRMASK)
6122 && val != 0xffffffff /* Ignore clear-all-like requests. */)
6123 Log(("Unknown USBSTS bits %#x are set!\n", val & ~XHCI_STATUS_WRMASK));
6124
6125 /* Most bits are read-only. */
6126 val &= XHCI_STATUS_WRMASK;
6127
6128 /* "The Host Controller Driver may clear specific bits in this
6129 * register by writing '1' to bit positions to be cleared"
6130 */
6131 ASMAtomicAndU32(&pThis->status, ~val);
6132
6133 return VINF_SUCCESS;
6134}
6135
6136/**
6137 * Read the PAGESIZE register of the host controller.
6138 */
6139static VBOXSTRICTRC HcPagesize_r(PPDMDEVINS pDevIns, PXHCI pThis, uint32_t iReg, uint32_t *pu32Value)
6140{
6141 RT_NOREF(pDevIns, pThis, iReg);
6142 STAM_COUNTER_INC(&pThis->StatRdPageSize);
6143 *pu32Value = 1; /* 2^(bit n + 12) -> 4K page size only. */
6144 return VINF_SUCCESS;
6145}
6146
6147/**
6148 * Read the DNCTRL (Device Notification Control) register.
6149 */
6150static VBOXSTRICTRC HcDevNotifyCtrl_r(PPDMDEVINS pDevIns, PXHCI pThis, uint32_t iReg, uint32_t *pu32Value)
6151{
6152 RT_NOREF(pDevIns, iReg);
6153 STAM_COUNTER_INC(&pThis->StatRdDevNotifyCtrl);
6154 *pu32Value = pThis->dnctrl;
6155 return VINF_SUCCESS;
6156}
6157
6158/**
6159 * Write the DNCTRL (Device Notification Control) register.
6160 */
6161static VBOXSTRICTRC HcDevNotifyCtrl_w(PPDMDEVINS pDevIns, PXHCI pThis, uint32_t iReg, uint32_t val)
6162{
6163 RT_NOREF(pDevIns, iReg);
6164 STAM_COUNTER_INC(&pThis->StatWrDevNotifyCtrl);
6165 pThis->dnctrl = val;
6166 return VINF_SUCCESS;
6167}
6168
6169/**
6170 * Read the low dword of CRCR (Command Ring Control) register.
6171 */
6172static VBOXSTRICTRC HcCmdRingCtlLo_r(PPDMDEVINS pDevIns, PXHCI pThis, uint32_t iReg, uint32_t *pu32Value)
6173{
6174 RT_NOREF(pDevIns, iReg);
6175 STAM_COUNTER_INC(&pThis->StatRdCmdRingCtlLo);
6176 *pu32Value = (uint32_t)(pThis->crcr & XHCI_CRCR_RD_MASK);
6177 return VINF_SUCCESS;
6178}
6179
6180/**
6181 * Write the low dword of CRCR (Command Ring Control) register.
6182 */
6183static VBOXSTRICTRC HcCmdRingCtlLo_w(PPDMDEVINS pDevIns, PXHCI pThis, uint32_t iReg, uint32_t val)
6184{
6185 RT_NOREF(iReg);
6186 STAM_COUNTER_INC(&pThis->StatWrCmdRingCtlLo);
6187 /* NB: A dword write to the low half clears the high half. */
6188
6189 /* Sticky Abort/Stop bits - update register and kick the worker thread. */
6190 if (val & (XHCI_CRCR_CA | XHCI_CRCR_CS))
6191 {
6192 pThis->crcr |= val & (XHCI_CRCR_CA | XHCI_CRCR_CS);
6193 xhciKickWorker(pDevIns, pThis, XHCI_JOB_PROCESS_CMDRING, 0);
6194 }
6195
6196 /*
6197 * If the command ring is not running, the internal dequeue pointer
6198 * and the cycle state is updated. Otherwise the update is ignored.
6199 */
6200 if (!(pThis->crcr & XHCI_CRCR_CRR))
6201 {
6202 pThis->crcr = (pThis->crcr & ~XHCI_CRCR_UPD_MASK) | (val & XHCI_CRCR_UPD_MASK);
6203 /// @todo cmdr_dqp: atomic? volatile?
6204 pThis->cmdr_dqp = pThis->crcr & XHCI_CRCR_ADDR_MASK;
6205 pThis->cmdr_ccs = pThis->crcr & XHCI_CRCR_RCS;
6206 }
6207
6208 return VINF_SUCCESS;
6209}
6210
6211/**
6212 * Read the high dword of CRCR (Command Ring Control) register.
6213 */
6214static VBOXSTRICTRC HcCmdRingCtlHi_r(PPDMDEVINS pDevIns, PXHCI pThis, uint32_t iReg, uint32_t *pu32Value)
6215{
6216 RT_NOREF(pDevIns, iReg);
6217 STAM_COUNTER_INC(&pThis->StatRdCmdRingCtlHi);
6218 *pu32Value = pThis->crcr >> 32;
6219 return VINF_SUCCESS;
6220}
6221
6222/**
6223 * Write the high dword of CRCR (Command Ring Control) register.
6224 */
6225static VBOXSTRICTRC HcCmdRingCtlHi_w(PPDMDEVINS pDevIns, PXHCI pThis, uint32_t iReg, uint32_t val)
6226{
6227 RT_NOREF(pDevIns, iReg);
6228 STAM_COUNTER_INC(&pThis->StatWrCmdRingCtlHi);
6229 if (!(pThis->crcr & XHCI_CRCR_CRR))
6230 {
6231 pThis->crcr = ((uint64_t)val << 32) | (uint32_t)pThis->crcr;
6232 pThis->cmdr_dqp = pThis->crcr & XHCI_CRCR_ADDR_MASK;
6233 }
6234 return VINF_SUCCESS;
6235}
6236
6237/**
6238 * Read the low dword of the DCBAAP register.
6239 */
6240static VBOXSTRICTRC HcDevCtxBAAPLo_r(PPDMDEVINS pDevIns, PXHCI pThis, uint32_t iReg, uint32_t *pu32Value)
6241{
6242 RT_NOREF(pDevIns, iReg);
6243 STAM_COUNTER_INC(&pThis->StatRdDevCtxBaapLo);
6244 *pu32Value = (uint32_t)pThis->dcbaap;
6245 return VINF_SUCCESS;
6246}
6247
6248/**
6249 * Write the low dword of the DCBAAP register.
6250 */
6251static VBOXSTRICTRC HcDevCtxBAAPLo_w(PPDMDEVINS pDevIns, PXHCI pThis, uint32_t iReg, uint32_t val)
6252{
6253 RT_NOREF(pDevIns, iReg);
6254 STAM_COUNTER_INC(&pThis->StatWrDevCtxBaapLo);
6255 /* NB: A dword write to the low half clears the high half. */
6256 /// @todo Should this mask off the reserved bits?
6257 pThis->dcbaap = val;
6258 return VINF_SUCCESS;
6259}
6260
6261/**
6262 * Read the high dword of the DCBAAP register.
6263 */
6264static VBOXSTRICTRC HcDevCtxBAAPHi_r(PPDMDEVINS pDevIns, PXHCI pThis, uint32_t iReg, uint32_t *pu32Value)
6265{
6266 RT_NOREF(pDevIns, iReg);
6267 STAM_COUNTER_INC(&pThis->StatRdDevCtxBaapHi);
6268 *pu32Value = pThis->dcbaap >> 32;
6269 return VINF_SUCCESS;
6270}
6271
6272/**
6273 * Write the high dword of the DCBAAP register.
6274 */
6275static VBOXSTRICTRC HcDevCtxBAAPHi_w(PPDMDEVINS pDevIns, PXHCI pThis, uint32_t iReg, uint32_t val)
6276{
6277 RT_NOREF(pDevIns, iReg);
6278 STAM_COUNTER_INC(&pThis->StatWrDevCtxBaapHi);
6279 pThis->dcbaap = ((uint64_t)val << 32) | (uint32_t)pThis->dcbaap;
6280 return VINF_SUCCESS;
6281}
6282
6283/**
6284 * Read the CONFIG register.
6285 */
6286static VBOXSTRICTRC HcConfig_r(PPDMDEVINS pDevIns, PXHCI pThis, uint32_t iReg, uint32_t *pu32Value)
6287{
6288 RT_NOREF(pDevIns, iReg);
6289 STAM_COUNTER_INC(&pThis->StatRdConfig);
6290 *pu32Value = pThis->config;
6291 return VINF_SUCCESS;
6292}
6293
6294/**
6295 * Write the CONFIG register.
6296 */
6297static VBOXSTRICTRC HcConfig_w(PPDMDEVINS pDevIns, PXHCI pThis, uint32_t iReg, uint32_t val)
6298{
6299 RT_NOREF(pDevIns, iReg);
6300 STAM_COUNTER_INC(&pThis->StatWrConfig);
6301 /// @todo side effects?
6302 pThis->config = val;
6303 return VINF_SUCCESS;
6304}
6305
6306
6307
6308/* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- */
6309/* xHCI Port Register access routines */
6310/* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- */
6311
6312
6313
6314/**
6315 * Read the PORTSC register.
6316 */
6317static VBOXSTRICTRC HcPortStatusCtrl_r(PPDMDEVINS pDevIns, PXHCI pThis, uint32_t iPort, uint32_t *pu32Value)
6318{
6319 PXHCIHUBPORT p = &pThis->aPorts[iPort];
6320 RT_NOREF(pDevIns);
6321 STAM_COUNTER_INC(&pThis->StatRdPortStatusCtrl);
6322
6323 Assert(!(pThis->hcc_params & XHCI_HCC_PPC));
6324
6325 if (p->portsc & XHCI_PORT_PR)
6326 {
6327/// @todo Probably not needed?
6328#ifdef IN_RING3
6329 Log2(("HcPortStatusCtrl_r(): port %u: Impatient guest!\n", IDX_TO_ID(iPort)));
6330 RTThreadYield();
6331#else
6332 Log2(("HcPortStatusCtrl_r: yield -> VINF_IOM_R3_MMIO_READ\n"));
6333 return VINF_IOM_R3_MMIO_READ;
6334#endif
6335 }
6336
6337 /* The WPR bit is always read as zero. */
6338 *pu32Value = p->portsc & ~XHCI_PORT_WPR;
6339 return VINF_SUCCESS;
6340}
6341
6342/**
6343 * Write the PORTSC register.
6344 */
6345static VBOXSTRICTRC HcPortStatusCtrl_w(PPDMDEVINS pDevIns, PXHCI pThis, uint32_t iPort, uint32_t val)
6346{
6347 PXHCIHUBPORT p = &pThis->aPorts[iPort];
6348#ifdef IN_RING3
6349 PXHCICC pThisCC = PDMDEVINS_2_DATA_CC(pDevIns, PXHCICC);
6350#endif
6351 STAM_COUNTER_INC(&pThis->StatWrPortStatusCtrl);
6352
6353 /* If no register change results, we're done. */
6354 if ( p->portsc == val
6355 && !(val & XHCI_PORT_CHANGE_MASK))
6356 return VINF_SUCCESS;
6357
6358 /* If port state is not changing (status bits are being cleared etc.), we can do it in any context.
6359 * This case occurs when the R/W control bits are not changing and the W1C bits are not being set.
6360 */
6361 if ( (p->portsc & XHCI_PORT_CTL_RW_MASK) == (val & XHCI_PORT_CTL_RW_MASK)
6362 && !(val & XHCI_PORT_CTL_W1_MASK))
6363 {
6364 Log(("HcPortStatusCtrl_w port %u (status only): old=%x new=%x\n", IDX_TO_ID(iPort), p->portsc, val));
6365
6366 if (val & XHCI_PORT_RESERVED)
6367 Log(("Reserved bits set %x!\n", val & XHCI_PORT_RESERVED));
6368
6369 /* A write to clear any of the change notification bits. */
6370 if (val & XHCI_PORT_CHANGE_MASK)
6371 p->portsc &= ~(val & XHCI_PORT_CHANGE_MASK);
6372
6373 /* Update the wake mask. */
6374 p->portsc &= ~XHCI_PORT_WAKE_MASK;
6375 p->portsc |= val & XHCI_PORT_WAKE_MASK;
6376
6377 /* There may still be differences between 'portsc' and 'val' in
6378 * the R/O bits; that does not count as a register change and is fine.
6379 * The RW1x control bits are not considered either since those only matter
6380 * if set in 'val'. Since the LWS bit was not set, the PLS bits should not
6381 * be compared. The port change bits may differ as well since the guest
6382 * could be clearing only some or none of them.
6383 */
6384 AssertMsg(!(val & XHCI_PORT_CTL_W1_MASK), ("val=%X\n", val));
6385 AssertMsg(!(val & XHCI_PORT_LWS), ("val=%X\n", val));
6386 AssertMsg((val & ~(XHCI_PORT_RO_MASK|XHCI_PORT_CTL_W1_MASK|XHCI_PORT_PLS_MASK|XHCI_PORT_CHANGE_MASK)) == (p->portsc & ~(XHCI_PORT_RO_MASK|XHCI_PORT_CTL_W1_MASK|XHCI_PORT_PLS_MASK|XHCI_PORT_CHANGE_MASK)), ("val=%X vs. portsc=%X\n", val, p->portsc));
6387 return VINF_SUCCESS;
6388 }
6389
6390 /* Actual USB port state changes need to be done in R3. */
6391#ifdef IN_RING3
6392 Log(("HcPortStatusCtrl_w port %u: old=%x new=%x\n", IDX_TO_ID(iPort), p->portsc, val));
6393 Assert(!(pThis->hcc_params & XHCI_HCC_PPC));
6394 Assert(p->portsc & XHCI_PORT_PP);
6395
6396 if (val & XHCI_PORT_RESERVED)
6397 Log(("Reserved bits set %x!\n", val & XHCI_PORT_RESERVED));
6398
6399 /* A write to clear any of the change notification bits. */
6400 if (val & XHCI_PORT_CHANGE_MASK)
6401 p->portsc &= ~(val & XHCI_PORT_CHANGE_MASK);
6402
6403 /* Writing the Port Enable/Disable bit as 1 disables a port; it cannot be
6404 * enabled that way. Writing the bit as zero does does nothing.
6405 */
6406 if ((val & XHCI_PORT_PED) && (p->portsc & XHCI_PORT_PED))
6407 {
6408 p->portsc &= ~XHCI_PORT_PED;
6409 Log(("HcPortStatusCtrl_w(): port %u: DISABLE\n", IDX_TO_ID(iPort)));
6410 }
6411
6412 if (!(val & XHCI_PORT_PP) && (p->portsc & XHCI_PORT_PP))
6413 {
6414 p->portsc &= ~XHCI_PORT_PP;
6415 Log(("HcPortStatusCtrl_w(): port %u: POWER OFF\n", IDX_TO_ID(iPort)));
6416 }
6417
6418 /* Warm Port Reset - USB3 only; see 4.19.5.1. */
6419 if ((val & XHCI_PORT_WPR) && IS_USB3_PORT_IDX_SHR(pThis, iPort))
6420 {
6421 Log(("HcPortStatusCtrl_w(): port %u: WARM RESET\n", IDX_TO_ID(iPort)));
6422 if (xhciR3RhPortSetIfConnected(pThis, iPort, XHCI_PORT_PR | XHCI_PORT_WPR))
6423 {
6424 PXHCIROOTHUBR3 pRh = GET_PORT_PRH(pThisCC, iPort);
6425
6426 VUSBIRhDevReset(pRh->pIRhConn, GET_VUSB_PORT_FROM_XHCI_PORT(pRh, iPort), false /* don't reset on linux */, NULL /* sync */, NULL, PDMDevHlpGetVM(pDevIns));
6427 xhciR3PortResetDone(pDevIns, iPort);
6428 }
6429 }
6430
6431 if (val & XHCI_PORT_PR)
6432 {
6433 Log(("HcPortStatusCtrl_w(): port %u: RESET\n", IDX_TO_ID(iPort)));
6434 if (xhciR3RhPortSetIfConnected(pThis, iPort, XHCI_PORT_PR))
6435 {
6436 PXHCIROOTHUBR3 pRh = GET_PORT_PRH(pThisCC, iPort);
6437
6438 VUSBIRhDevReset(pRh->pIRhConn, GET_VUSB_PORT_FROM_XHCI_PORT(pRh, iPort), false /* don't reset on linux */, NULL /* sync */, NULL, PDMDevHlpGetVM(pDevIns));
6439 xhciR3PortResetDone(pDevIns, iPort);
6440 }
6441 else if (p->portsc & XHCI_PORT_PR)
6442 {
6443 /* the guest is getting impatient. */
6444 Log2(("HcPortStatusCtrl_w(): port %u: Impatient guest!\n", IDX_TO_ID(iPort)));
6445 RTThreadYield();
6446 }
6447 }
6448
6449 /// @todo Do some sanity checking on the new link state?
6450 /* Update the link state if requested. */
6451 if (val & XHCI_PORT_LWS)
6452 {
6453 unsigned old_pls;
6454 unsigned new_pls;
6455
6456 old_pls = (p->portsc & XHCI_PORT_PLS_MASK) >> XHCI_PORT_PLS_SHIFT;
6457 new_pls = (val & XHCI_PORT_PLS_MASK) >> XHCI_PORT_PLS_SHIFT;
6458
6459 p->portsc &= ~XHCI_PORT_PLS_MASK;
6460 p->portsc |= new_pls << XHCI_PORT_PLS_SHIFT;
6461 Log2(("HcPortStatusCtrl_w(): port %u: Updating link state from %u to %u\n", IDX_TO_ID(iPort), old_pls, new_pls));
6462 /* U3->U0 (USB3) and Resume->U0 transitions set the PLC flag. See 4.15.2.2 */
6463 if (new_pls == XHCI_PLS_U0)
6464 if (old_pls == XHCI_PLS_U3 || old_pls == XHCI_PLS_RESUME)
6465 {
6466 p->portsc |= XHCI_PORT_PLC;
6467 xhciR3GenPortChgEvent(pDevIns, pThis, IDX_TO_ID(iPort));
6468 }
6469 }
6470
6471 /// @todo which other bits can we safely ignore?
6472
6473 /* Update the wake mask. */
6474 p->portsc &= ~XHCI_PORT_WAKE_MASK;
6475 p->portsc |= val & XHCI_PORT_WAKE_MASK;
6476
6477 return VINF_SUCCESS;
6478#else /* !IN_RING3 */
6479 RT_NOREF(pDevIns);
6480 return VINF_IOM_R3_MMIO_WRITE;
6481#endif /* !IN_RING3 */
6482}
6483
6484
6485/**
6486 * Read the PORTPMSC register.
6487 */
6488static VBOXSTRICTRC HcPortPowerMgmt_r(PPDMDEVINS pDevIns, PXHCI pThis, uint32_t iPort, uint32_t *pu32Value)
6489{
6490 PXHCIHUBPORT p = &pThis->aPorts[iPort];
6491 RT_NOREF(pDevIns);
6492 STAM_COUNTER_INC(&pThis->StatRdPortPowerMgmt);
6493
6494 *pu32Value = p->portpm;
6495 return VINF_SUCCESS;
6496}
6497
6498
6499/**
6500 * Write the PORTPMSC register.
6501 */
6502static VBOXSTRICTRC HcPortPowerMgmt_w(PPDMDEVINS pDevIns, PXHCI pThis, uint32_t iPort, uint32_t val)
6503{
6504 PXHCIHUBPORT p = &pThis->aPorts[iPort];
6505 RT_NOREF(pDevIns);
6506 STAM_COUNTER_INC(&pThis->StatWrPortPowerMgmt);
6507
6508 /// @todo anything to do here?
6509 p->portpm = val;
6510 return VINF_SUCCESS;
6511}
6512
6513
6514/**
6515 * Read the PORTLI register.
6516 */
6517static VBOXSTRICTRC HcPortLinkInfo_r(PPDMDEVINS pDevIns, PXHCI pThis, uint32_t iPort, uint32_t *pu32Value)
6518{
6519 PXHCIHUBPORT p = &pThis->aPorts[iPort];
6520 RT_NOREF(pDevIns);
6521 STAM_COUNTER_INC(&pThis->StatRdPortLinkInfo);
6522
6523 /* The link information is R/O; we probably can't get it at all. If we
6524 * do maintain it for USB3 ports, we also have to reset it (5.4.10).
6525 */
6526 *pu32Value = p->portli;
6527 return VINF_SUCCESS;
6528}
6529
6530/**
6531 * Read the reserved register. Linux likes to do this.
6532 */
6533static VBOXSTRICTRC HcPortRsvd_r(PPDMDEVINS pDevIns, PXHCI pThis, uint32_t iPort, uint32_t *pu32Value)
6534{
6535 RT_NOREF(pDevIns, pThis, iPort);
6536 STAM_COUNTER_INC(&pThis->StatRdPortRsvd);
6537 *pu32Value = 0;
6538 return VINF_SUCCESS;
6539}
6540
6541
6542
6543/* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- */
6544/* xHCI Interrupter Register access routines */
6545/* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- */
6546
6547
6548
6549/**
6550 * Read the IMAN register.
6551 */
6552static VBOXSTRICTRC HcIntrMgmt_r(PPDMDEVINS pDevIns, PXHCI pThis, PXHCIINTRPTR ip, uint32_t *pu32Value)
6553{
6554 RT_NOREF(pDevIns, pThis);
6555 STAM_COUNTER_INC(&pThis->StatRdIntrMgmt);
6556
6557 *pu32Value = ip->iman;
6558 return VINF_SUCCESS;
6559}
6560
6561/**
6562 * Write the IMAN register.
6563 */
6564static VBOXSTRICTRC HcIntrMgmt_w(PPDMDEVINS pDevIns, PXHCI pThis, PXHCIINTRPTR ip, uint32_t val)
6565{
6566 uint32_t uNew = val & XHCI_IMAN_VALID_MASK;
6567 STAM_COUNTER_INC(&pThis->StatWrIntrMgmt);
6568
6569 if (val & ~XHCI_IMAN_VALID_MASK)
6570 Log(("Reserved bits set %x!\n", val & ~XHCI_IMAN_VALID_MASK));
6571
6572 /* If the Interrupt Pending (IP) bit is set, writing one clears it.
6573 * Note that when MSIs are enabled, the bit auto-clears almost immediately.
6574 */
6575 if (val & ip->iman & XHCI_IMAN_IP)
6576 {
6577 Log2(("clearing interrupt on interrupter %u\n", ip->index));
6578 PDMDevHlpPCISetIrq(pDevIns, 0, PDM_IRQ_LEVEL_LOW);
6579 STAM_COUNTER_INC(&pThis->StatIntrsCleared);
6580 uNew &= ~XHCI_IMAN_IP;
6581 }
6582 else
6583 {
6584 /* Preserve the current IP bit. */
6585 uNew = (uNew & ~XHCI_IMAN_IP) | (ip->iman & XHCI_IMAN_IP);
6586 }
6587
6588 /* Trigger an interrupt if the IP bit is set and IE transitions from 0 to 1. */
6589 if ( (uNew & XHCI_IMAN_IE)
6590 && !(ip->iman & XHCI_IMAN_IE)
6591 && (ip->iman & XHCI_IMAN_IP)
6592 && (pThis->cmd & XHCI_CMD_INTE))
6593 PDMDevHlpPCISetIrq(pDevIns, 0, PDM_IRQ_LEVEL_HIGH);
6594
6595 ip->iman = uNew;
6596 return VINF_SUCCESS;
6597}
6598
6599/**
6600 * Read the IMOD register.
6601 */
6602static VBOXSTRICTRC HcIntrMod_r(PPDMDEVINS pDevIns, PXHCI pThis, PXHCIINTRPTR ip, uint32_t *pu32Value)
6603{
6604 RT_NOREF(pDevIns, pThis);
6605 STAM_COUNTER_INC(&pThis->StatRdIntrMod);
6606
6607 *pu32Value = ip->imod;
6608 return VINF_SUCCESS;
6609}
6610
6611/**
6612 * Write the IMOD register.
6613 */
6614static VBOXSTRICTRC HcIntrMod_w(PPDMDEVINS pDevIns, PXHCI pThis, PXHCIINTRPTR ip, uint32_t val)
6615{
6616 RT_NOREF(pDevIns, pThis);
6617 STAM_COUNTER_INC(&pThis->StatWrIntrMod);
6618
6619 /// @todo Does writing a zero to IMODC/IMODI potentially trigger
6620 /// an interrupt?
6621 ip->imod = val;
6622 return VINF_SUCCESS;
6623}
6624
6625/**
6626 * Read the ERSTSZ register.
6627 */
6628static VBOXSTRICTRC HcEvtRSTblSize_r(PPDMDEVINS pDevIns, PXHCI pThis, PXHCIINTRPTR ip, uint32_t *pu32Value)
6629{
6630 RT_NOREF(pDevIns, pThis);
6631 STAM_COUNTER_INC(&pThis->StatRdEvtRstblSize);
6632
6633 *pu32Value = ip->erstsz;
6634 return VINF_SUCCESS;
6635}
6636
6637/**
6638 * Write the ERSTSZ register.
6639 */
6640static VBOXSTRICTRC HcEvtRSTblSize_w(PPDMDEVINS pDevIns, PXHCI pThis, PXHCIINTRPTR ip, uint32_t val)
6641{
6642 RT_NOREF(pDevIns, pThis);
6643 STAM_COUNTER_INC(&pThis->StatWrEvtRstblSize);
6644
6645 if (val & ~XHCI_ERSTSZ_MASK)
6646 Log(("Reserved bits set %x!\n", val & ~XHCI_ERSTSZ_MASK));
6647 if (val > XHCI_ERSTMAX)
6648 Log(("ERSTSZ (%u) > ERSTMAX (%u)!\n", val, XHCI_ERSTMAX));
6649
6650 /* Enforce the maximum size. */
6651 ip->erstsz = RT_MIN(val, XHCI_ERSTMAX);
6652
6653 if (!ip->index && !ip->erstsz) /* Windows 8 does this temporarily. Thanks guys... */
6654 Log(("ERSTSZ is zero for primary interrupter: undefined behavior!\n"));
6655
6656 return VINF_SUCCESS;
6657}
6658
6659/**
6660 * Read the reserved register. Linux likes to do this.
6661 */
6662static VBOXSTRICTRC HcEvtRsvd_r(PPDMDEVINS pDevIns, PXHCI pThis, PXHCIINTRPTR ip, uint32_t *pu32Value)
6663{
6664 RT_NOREF(pDevIns, pThis, ip);
6665 STAM_COUNTER_INC(&pThis->StatRdEvtRsvd);
6666 *pu32Value = 0;
6667 return VINF_SUCCESS;
6668}
6669
6670/**
6671 * Read the low dword of the ERSTBA register.
6672 */
6673static VBOXSTRICTRC HcEvtRSTblBaseLo_r(PPDMDEVINS pDevIns, PXHCI pThis, PXHCIINTRPTR ip, uint32_t *pu32Value)
6674{
6675 RT_NOREF(pDevIns, pThis);
6676 STAM_COUNTER_INC(&pThis->StatRdEvtRsTblBaseLo);
6677
6678 *pu32Value = (uint32_t)ip->erstba;
6679 return VINF_SUCCESS;
6680}
6681
6682
6683/**
6684 * Write the low dword of the ERSTBA register.
6685 */
6686static VBOXSTRICTRC HcEvtRSTblBaseLo_w(PPDMDEVINS pDevIns, PXHCI pThis, PXHCIINTRPTR ip, uint32_t val)
6687{
6688 STAM_COUNTER_INC(&pThis->StatWrEvtRsTblBaseLo);
6689
6690 if (val & ~pThis->erst_addr_mask)
6691 Log(("Reserved bits set %x!\n", val & ~pThis->erst_addr_mask));
6692
6693 /* NB: A dword write to the low half clears the high half. */
6694 ip->erstba = val & pThis->erst_addr_mask;
6695
6696 /* Initialize the internal event ring state. */
6697 ip->evtr_pcs = 1;
6698 ip->erst_idx = 0;
6699 ip->ipe = false;
6700
6701 /* Fetch the first ERST entry now. Not later! That "sets the Event Ring
6702 * State Machine:EREP Advancement to the Start state"
6703 */
6704 xhciFetchErstEntry(pDevIns, pThis, ip);
6705
6706 return VINF_SUCCESS;
6707}
6708
6709/**
6710 * Read the high dword of the ERSTBA register.
6711 */
6712static VBOXSTRICTRC HcEvtRSTblBaseHi_r(PPDMDEVINS pDevIns, PXHCI pThis, PXHCIINTRPTR ip, uint32_t *pu32Value)
6713{
6714 RT_NOREF(pDevIns, pThis);
6715 STAM_COUNTER_INC(&pThis->StatRdEvtRsTblBaseHi);
6716
6717 *pu32Value = (uint32_t)(ip->erstba >> 32);
6718 return VINF_SUCCESS;
6719}
6720
6721/**
6722 * Write the high dword of the ERSTBA register.
6723 */
6724static VBOXSTRICTRC HcEvtRSTblBaseHi_w(PPDMDEVINS pDevIns, PXHCI pThis, PXHCIINTRPTR ip, uint32_t val)
6725{
6726 STAM_COUNTER_INC(&pThis->StatWrEvtRsTblBaseHi);
6727
6728 /* Update the high dword while preserving the low one. */
6729 ip->erstba = ((uint64_t)val << 32) | (uint32_t)ip->erstba;
6730
6731 /* We shouldn't be doing this when AC64 is set. But High Sierra
6732 * ignores that because it "knows" the xHC handles 64-bit addressing,
6733 * so we're going to assume that OSes are not going to write junk into
6734 * ERSTBAH when they don't see AC64 set.
6735 */
6736 xhciFetchErstEntry(pDevIns, pThis, ip);
6737
6738 return VINF_SUCCESS;
6739}
6740
6741
6742/**
6743 * Read the low dword of the ERDP register.
6744 */
6745static VBOXSTRICTRC HcEvtRingDeqPtrLo_r(PPDMDEVINS pDevIns, PXHCI pThis, PXHCIINTRPTR ip, uint32_t *pu32Value)
6746{
6747 RT_NOREF(pThis);
6748 STAM_COUNTER_INC(&pThis->StatRdEvtRingDeqPtrLo);
6749
6750 /* Lock to avoid incomplete update being seen. */
6751 int rc = PDMDevHlpCritSectEnter(pDevIns, &ip->lock, VINF_IOM_R3_MMIO_READ);
6752 if (rc != VINF_SUCCESS)
6753 return rc;
6754
6755 *pu32Value = (uint32_t)ip->erdp;
6756
6757 PDMDevHlpCritSectLeave(pDevIns, &ip->lock);
6758
6759 return VINF_SUCCESS;
6760}
6761
6762/**
6763 * Write the low dword of the ERDP register.
6764 */
6765static VBOXSTRICTRC HcEvtRingDeqPtrLo_w(PPDMDEVINS pDevIns, PXHCI pThis, PXHCIINTRPTR ip, uint32_t val)
6766{
6767 uint64_t old_erdp;
6768 uint64_t new_erdp;
6769 STAM_COUNTER_INC(&pThis->StatWrEvtRingDeqPtrLo);
6770
6771 /* NB: A dword write to the low half clears the high half.
6772 * The high dword should be ignored when AC64=0, but High Sierra
6773 * does not care what we report. Therefore a write to the low dword
6774 * handles all the control bits and a write to the high dword still
6775 * updates the ERDP address. On a 64-bit host, there must be a
6776 * back-to-back low dword + high dword access. We are going to boldly
6777 * assume that the guest will not place the event ring across the 4G
6778 * boundary (i.e. storing the bottom part in the firmware ROM).
6779 */
6780 int rc = PDMDevHlpCritSectEnter(pDevIns, &ip->lock, VINF_IOM_R3_MMIO_WRITE);
6781 if (rc != VINF_SUCCESS)
6782 return rc;
6783
6784 old_erdp = ip->erdp & XHCI_ERDP_ADDR_MASK; /* Remember old ERDP address. */
6785 new_erdp = ip->erdp & XHCI_ERDP_EHB; /* Preserve EHB */
6786
6787 /* If the Event Handler Busy (EHB) bit is set, writing a one clears it. */
6788 if (val & ip->erdp & XHCI_ERDP_EHB)
6789 {
6790 Log2(("clearing EHB on interrupter %p\n", ip));
6791 new_erdp &= ~XHCI_ERDP_EHB;
6792 }
6793 /// @todo Check if this might inadvertently set EHB!
6794
6795 new_erdp |= val & ~XHCI_ERDP_EHB;
6796 ip->erdp = new_erdp;
6797
6798 /* Check if the ERDP changed. See workaround below. */
6799 if (old_erdp != (new_erdp & XHCI_ERDP_ADDR_MASK))
6800 ip->erdp_rewrites = 0;
6801 else
6802 ++ip->erdp_rewrites;
6803
6804 LogFlowFunc(("ERDP: %RGp, EREP: %RGp\n", (RTGCPHYS)(ip->erdp & XHCI_ERDP_ADDR_MASK), (RTGCPHYS)ip->erep));
6805
6806 if ((ip->erdp & XHCI_ERDP_ADDR_MASK) == ip->erep)
6807 {
6808 Log2(("Event Ring empty, clearing IPE\n"));
6809 ip->ipe = false;
6810 }
6811 else if (ip->ipe && (val & XHCI_ERDP_EHB))
6812 {
6813 /* EHB is being cleared but the ring isn't empty and IPE is still set. */
6814 if (RT_UNLIKELY(old_erdp == (new_erdp & XHCI_ERDP_ADDR_MASK) && ip->erdp_rewrites > 2))
6815 {
6816 /* If guest does not advance the ERDP, do not trigger an interrupt
6817 * again. Workaround for buggy xHCI initialization in Linux 4.6 which
6818 * enables interrupts before setting up internal driver state. That
6819 * leads to the guest IRQ handler not actually handling events and
6820 * infinitely re-triggering interrupts. However, only do this if the
6821 * guest has already written the same ERDP value a few times. The Intel
6822 * xHCI driver always writes the same ERDP twice and we must still
6823 * re-trigger interrupts in that case.
6824 * See @bugref{8546}.
6825 */
6826 Log2(("Event Ring not empty, ERDP not advanced, not re-triggering interrupt!\n"));
6827 ip->ipe = false;
6828 }
6829 else
6830 {
6831 Log2(("Event Ring not empty, re-triggering interrupt\n"));
6832 xhciSetIntr(pDevIns, pThis, ip);
6833 }
6834 }
6835
6836 PDMDevHlpCritSectLeave(pDevIns, &ip->lock);
6837
6838 return VINF_SUCCESS;
6839}
6840
6841/**
6842 * Read the high dword of the ERDP register.
6843 */
6844static VBOXSTRICTRC HcEvtRingDeqPtrHi_r(PPDMDEVINS pDevIns, PXHCI pThis, PXHCIINTRPTR ip, uint32_t *pu32Value)
6845{
6846 RT_NOREF(pDevIns, pThis);
6847 STAM_COUNTER_INC(&pThis->StatRdEvtRingDeqPtrHi);
6848
6849 *pu32Value = (uint32_t)(ip->erdp >> 32);
6850 return VINF_SUCCESS;
6851}
6852
6853/**
6854 * Write the high dword of the ERDP register.
6855 */
6856static VBOXSTRICTRC HcEvtRingDeqPtrHi_w(PPDMDEVINS pDevIns, PXHCI pThis, PXHCIINTRPTR ip, uint32_t val)
6857{
6858 RT_NOREF(pThis);
6859 STAM_COUNTER_INC(&pThis->StatWrEvtRingDeqPtrHi);
6860
6861 /* See HcEvtRingDeqPtrLo_w for semantics. */
6862 int rc = PDMDevHlpCritSectEnter(pDevIns, &ip->lock, VINF_IOM_R3_MMIO_WRITE);
6863 if (rc != VINF_SUCCESS)
6864 return rc;
6865
6866 /* Update the high dword while preserving the low one. */
6867 ip->erdp = ((uint64_t)val << 32) | (uint32_t)ip->erdp;
6868
6869 PDMDevHlpCritSectLeave(pDevIns, &ip->lock);
6870
6871 return VINF_SUCCESS;
6872}
6873
6874
6875/**
6876 * xHCI register access routines.
6877 */
6878typedef struct
6879{
6880 const char *pszName;
6881 VBOXSTRICTRC (*pfnRead )(PPDMDEVINS pDevIns, PXHCI pThis, uint32_t iReg, uint32_t *pu32Value);
6882 VBOXSTRICTRC (*pfnWrite)(PPDMDEVINS pDevIns, PXHCI pThis, uint32_t iReg, uint32_t u32Value);
6883} XHCIREGACC;
6884
6885/**
6886 * xHCI interrupter register access routines.
6887 */
6888typedef struct
6889{
6890 const char *pszName;
6891 VBOXSTRICTRC (*pfnIntrRead )(PPDMDEVINS pDevIns, PXHCI pThis, PXHCIINTRPTR pIntr, uint32_t *pu32Value);
6892 VBOXSTRICTRC (*pfnIntrWrite)(PPDMDEVINS pDevIns, PXHCI pThis, PXHCIINTRPTR pIntr, uint32_t u32Value);
6893} XHCIINTRREGACC;
6894
6895/**
6896 * Operational registers descriptor table.
6897 */
6898static const XHCIREGACC g_aOpRegs[] =
6899{
6900 {"USBCMD" , HcUsbcmd_r, HcUsbcmd_w },
6901 {"USBSTS", HcUsbsts_r, HcUsbsts_w },
6902 {"PAGESIZE", HcPagesize_r, NULL },
6903 {"Unused", NULL, NULL },
6904 {"Unused", NULL, NULL },
6905 {"DNCTRL", HcDevNotifyCtrl_r, HcDevNotifyCtrl_w },
6906 {"CRCRL", HcCmdRingCtlLo_r, HcCmdRingCtlLo_w },
6907 {"CRCRH", HcCmdRingCtlHi_r, HcCmdRingCtlHi_w },
6908 {"Unused", NULL, NULL },
6909 {"Unused", NULL, NULL },
6910 {"Unused", NULL, NULL },
6911 {"Unused", NULL, NULL },
6912 {"DCBAAPL", HcDevCtxBAAPLo_r, HcDevCtxBAAPLo_w },
6913 {"DCBAAPH", HcDevCtxBAAPHi_r, HcDevCtxBAAPHi_w },
6914 {"CONFIG", HcConfig_r, HcConfig_w }
6915};
6916
6917
6918/**
6919 * Port registers descriptor table (for a single port). The number of ports
6920 * and their associated registers depends on the NDP value.
6921 */
6922static const XHCIREGACC g_aPortRegs[] =
6923{
6924 /*
6925 */
6926 {"PORTSC", HcPortStatusCtrl_r, HcPortStatusCtrl_w },
6927 {"PORTPMSC", HcPortPowerMgmt_r, HcPortPowerMgmt_w },
6928 {"PORTLI", HcPortLinkInfo_r, NULL },
6929 {"Reserved", HcPortRsvd_r, NULL }
6930};
6931AssertCompile(RT_ELEMENTS(g_aPortRegs) * sizeof(uint32_t) == 0x10);
6932
6933
6934/**
6935 * Interrupter runtime registers descriptor table (for a single interrupter).
6936 * The number of interrupters depends on the XHCI_NINTR value.
6937 */
6938static const XHCIINTRREGACC g_aIntrRegs[] =
6939{
6940 {"IMAN", HcIntrMgmt_r, HcIntrMgmt_w },
6941 {"IMOD", HcIntrMod_r, HcIntrMod_w },
6942 {"ERSTSZ", HcEvtRSTblSize_r, HcEvtRSTblSize_w },
6943 {"Reserved", HcEvtRsvd_r, NULL },
6944 {"ERSTBAL", HcEvtRSTblBaseLo_r, HcEvtRSTblBaseLo_w },
6945 {"ERSTBAH", HcEvtRSTblBaseHi_r, HcEvtRSTblBaseHi_w },
6946 {"ERDPL", HcEvtRingDeqPtrLo_r, HcEvtRingDeqPtrLo_w },
6947 {"ERDPH", HcEvtRingDeqPtrHi_r, HcEvtRingDeqPtrHi_w }
6948};
6949AssertCompile(RT_ELEMENTS(g_aIntrRegs) * sizeof(uint32_t) == 0x20);
6950
6951
6952/**
6953 * Read the MFINDEX register.
6954 */
6955static int HcMfIndex_r(PPDMDEVINS pDevIns, PXHCI pThis, uint32_t *pu32Value)
6956{
6957 uint64_t uNanoTime;
6958 uint64_t uMfTime;
6959 STAM_COUNTER_INC(&pThis->StatRdMfIndex);
6960
6961 /* MFINDEX increments once per micro-frame, i.e. 8 times per millisecond
6962 * or every 125us. The resolution is only 14 bits, meaning that MFINDEX
6963 * wraps around after it reaches 0x3FFF (16383) or every 2048 milliseconds.
6964 */
6965 /// @todo MFINDEX should only be running when R/S is set. May not matter.
6966 uNanoTime = PDMDevHlpTimerGet(pDevIns, pThis->hWrapTimer);
6967 uMfTime = uNanoTime / 125000;
6968
6969 *pu32Value = uMfTime & 0x3FFF;
6970 Log2(("MFINDEX read: %u\n", *pu32Value));
6971 return VINF_SUCCESS;
6972}
6973
6974/**
6975 * @callback_method_impl{FNIOMMMIONEWREAD, Read a MMIO register.}
6976 *
6977 * @note We only accept 32-bit writes that are 32-bit aligned.
6978 */
6979static DECLCALLBACK(VBOXSTRICTRC) xhciMmioRead(PPDMDEVINS pDevIns, void *pvUser, RTGCPHYS off, void *pv, unsigned cb)
6980{
6981 PXHCI pThis = PDMDEVINS_2_DATA(pDevIns, PXHCI);
6982 const uint32_t offReg = (uint32_t)off;
6983 uint32_t * const pu32 = (uint32_t *)pv;
6984 uint32_t iReg;
6985 RT_NOREF(pvUser);
6986
6987 Log2(("xhciRead %RGp (offset %04X) size=%d\n", off, offReg, cb));
6988
6989 if (offReg < XHCI_CAPS_REG_SIZE)
6990 {
6991 switch (offReg)
6992 {
6993 case 0x0: /* CAPLENGTH + HCIVERSION */
6994 *pu32 = (pThis->hci_version << 16) | pThis->cap_length;
6995 break;
6996
6997 case 0x4: /* HCSPARAMS1 (structural) */
6998 Log2(("HCSPARAMS1 read\n"));
6999 *pu32 = pThis->hcs_params1;
7000 break;
7001
7002 case 0x8: /* HCSPARAMS2 (structural) */
7003 Log2(("HCSPARAMS2 read\n"));
7004 *pu32 = pThis->hcs_params2;
7005 break;
7006
7007 case 0xC: /* HCSPARAMS3 (structural) */
7008 Log2(("HCSPARAMS3 read\n"));
7009 *pu32 = pThis->hcs_params3;
7010 break;
7011
7012 case 0x10: /* HCCPARAMS1 (caps) */
7013 Log2(("HCCPARAMS1 read\n"));
7014 *pu32 = pThis->hcc_params;
7015 break;
7016
7017 case 0x14: /* DBOFF (doorbell offset) */
7018 Log2(("DBOFF read\n"));
7019 *pu32 = pThis->dbell_off;
7020 break;
7021
7022 case 0x18: /* RTSOFF (run-time register offset) */
7023 Log2(("RTSOFF read\n"));
7024 *pu32 = pThis->rts_off;
7025 break;
7026
7027 case 0x1C: /* HCCPARAMS2 (caps) */
7028 Log2(("HCCPARAMS2 read\n"));
7029 *pu32 = 0; /* xHCI 1.1 only */
7030 break;
7031
7032 default:
7033 Log(("xHCI: Trying to read unknown capability register %u!\n", offReg));
7034 STAM_COUNTER_INC(&pThis->StatRdUnknown);
7035 return VINF_IOM_MMIO_UNUSED_FF;
7036 }
7037 STAM_COUNTER_INC(&pThis->StatRdCaps);
7038 Log2(("xhciRead %RGp size=%d -> val=%x\n", off, cb, *pu32));
7039 return VINF_SUCCESS;
7040 }
7041
7042 /*
7043 * Validate the access (in case of IOM bugs or incorrect MMIO registration).
7044 */
7045 AssertMsgReturn(cb == sizeof(uint32_t), ("IOM bug? %RGp LB %d\n", off, cb),
7046 VINF_IOM_MMIO_UNUSED_FF /* No idea what really would happen... */);
7047 /** r=bird: If you don't have an idea what would happen for non-dword reads,
7048 * then the flags passed to IOM when creating the MMIO region are doubtful, right? */
7049 AssertMsgReturn(!(off & 0x3), ("IOM bug? %RGp LB %d\n", off, cb), VINF_IOM_MMIO_UNUSED_FF);
7050
7051 /*
7052 * Validate the register and call the read operator.
7053 */
7054 VBOXSTRICTRC rcStrict = VINF_IOM_MMIO_UNUSED_FF;
7055 if (offReg >= XHCI_DOORBELL_OFFSET)
7056 {
7057 /* The doorbell registers are effectively write-only and return 0 when read. */
7058 iReg = (offReg - XHCI_DOORBELL_OFFSET) >> 2;
7059 if (iReg < XHCI_NDS)
7060 {
7061 STAM_COUNTER_INC(&pThis->StatRdDoorBell);
7062 *pu32 = 0;
7063 rcStrict = VINF_SUCCESS;
7064 Log2(("xhciRead: DBellReg (DB %u) %RGp size=%d -> val=%x (rc=%d)\n", iReg, off, cb, *pu32, VBOXSTRICTRC_VAL(rcStrict)));
7065 }
7066 }
7067 else if (offReg >= XHCI_RTREG_OFFSET)
7068 {
7069 /* Run-time registers. */
7070 Assert(offReg < XHCI_DOORBELL_OFFSET);
7071 /* The MFINDEX register would be interrupter -1... */
7072 if (offReg < XHCI_RTREG_OFFSET + RT_ELEMENTS(g_aIntrRegs) * sizeof(uint32_t))
7073 {
7074 if (offReg == XHCI_RTREG_OFFSET)
7075 rcStrict = HcMfIndex_r(pDevIns, pThis, pu32);
7076 else
7077 {
7078 /* The silly Linux xHCI driver reads the reserved registers. */
7079 STAM_COUNTER_INC(&pThis->StatRdUnknown);
7080 *pu32 = 0;
7081 rcStrict = VINF_SUCCESS;
7082 }
7083 }
7084 else
7085 {
7086 Assert((offReg - XHCI_RTREG_OFFSET) / (RT_ELEMENTS(g_aIntrRegs) * sizeof(uint32_t)) > 0);
7087 const uint32_t iIntr = (offReg - XHCI_RTREG_OFFSET) / (RT_ELEMENTS(g_aIntrRegs) * sizeof(uint32_t)) - 1;
7088
7089 if (iIntr < XHCI_NINTR)
7090 {
7091 iReg = (offReg >> 2) & (RT_ELEMENTS(g_aIntrRegs) - 1);
7092 const XHCIINTRREGACC *pReg = &g_aIntrRegs[iReg];
7093 if (pReg->pfnIntrRead)
7094 {
7095 PXHCIINTRPTR pIntr = &pThis->aInterrupters[iIntr];
7096 rcStrict = pReg->pfnIntrRead(pDevIns, pThis, pIntr, pu32);
7097 Log2(("xhciRead: IntrReg (intr %u): %RGp (%s) size=%d -> val=%x (rc=%d)\n", iIntr, off, pReg->pszName, cb, *pu32, VBOXSTRICTRC_VAL(rcStrict)));
7098 }
7099 }
7100 }
7101 }
7102 else if (offReg >= XHCI_XECP_OFFSET)
7103 {
7104 /* Extended Capability registers. */
7105 Assert(offReg < XHCI_RTREG_OFFSET);
7106 uint32_t offXcp = offReg - XHCI_XECP_OFFSET;
7107
7108 if (offXcp + cb <= RT_MIN(pThis->cbExtCap, sizeof(pThis->abExtCap))) /* can't trust cbExtCap in ring-0. */
7109 {
7110 *pu32 = *(uint32_t *)&pThis->abExtCap[offXcp];
7111 rcStrict = VINF_SUCCESS;
7112 }
7113 Log2(("xhciRead: ExtCapReg %RGp size=%d -> val=%x (rc=%d)\n", off, cb, *pu32, VBOXSTRICTRC_VAL(rcStrict)));
7114 }
7115 else
7116 {
7117 /* Operational registers (incl. port registers). */
7118 Assert(offReg < XHCI_XECP_OFFSET);
7119 iReg = (offReg - XHCI_CAPS_REG_SIZE) >> 2;
7120 if (iReg < RT_ELEMENTS(g_aOpRegs))
7121 {
7122 const XHCIREGACC *pReg = &g_aOpRegs[iReg];
7123 if (pReg->pfnRead)
7124 {
7125 rcStrict = pReg->pfnRead(pDevIns, pThis, iReg, pu32);
7126 Log2(("xhciRead: OpReg %RGp (%s) size=%d -> val=%x (rc=%d)\n", off, pReg->pszName, cb, *pu32, VBOXSTRICTRC_VAL(rcStrict)));
7127 }
7128 }
7129 else if (iReg >= (XHCI_PORT_REG_OFFSET >> 2))
7130 {
7131 iReg -= (XHCI_PORT_REG_OFFSET >> 2);
7132 const uint32_t iPort = iReg / RT_ELEMENTS(g_aPortRegs);
7133 if (iPort < XHCI_NDP_CFG(pThis))
7134 {
7135 iReg = (offReg >> 2) & (RT_ELEMENTS(g_aPortRegs) - 1);
7136 Assert(iReg < RT_ELEMENTS(g_aPortRegs));
7137 const XHCIREGACC *pReg = &g_aPortRegs[iReg];
7138 if (pReg->pfnRead)
7139 {
7140 rcStrict = pReg->pfnRead(pDevIns, pThis, iPort, pu32);
7141 Log2(("xhciRead: PortReg (port %u): %RGp (%s) size=%d -> val=%x (rc=%d)\n", IDX_TO_ID(iPort), off, pReg->pszName, cb, *pu32, VBOXSTRICTRC_VAL(rcStrict)));
7142 }
7143 }
7144 }
7145 }
7146
7147 if (rcStrict != VINF_IOM_MMIO_UNUSED_FF)
7148 { /* likely */ }
7149 else
7150 {
7151 STAM_COUNTER_INC(&pThis->StatRdUnknown);
7152 Log(("xHCI: Trying to read unimplemented register at offset %04X!\n", offReg));
7153 }
7154
7155 return rcStrict;
7156}
7157
7158
7159/**
7160 * @callback_method_impl{FNIOMMMIONEWWRITE, Write to a MMIO register.}
7161 *
7162 * @note We only accept 32-bit writes that are 32-bit aligned.
7163 */
7164static DECLCALLBACK(VBOXSTRICTRC) xhciMmioWrite(PPDMDEVINS pDevIns, void *pvUser, RTGCPHYS off, void const *pv, unsigned cb)
7165{
7166 PXHCI pThis = PDMDEVINS_2_DATA(pDevIns, PXHCI);
7167 const uint32_t offReg = (uint32_t)off;
7168 uint32_t * const pu32 = (uint32_t *)pv;
7169 uint32_t iReg;
7170 RT_NOREF(pvUser);
7171
7172 Log2(("xhciWrite %RGp (offset %04X) %x size=%d\n", off, offReg, *(uint32_t *)pv, cb));
7173
7174 if (offReg < XHCI_CAPS_REG_SIZE)
7175 {
7176 /* These are read-only */
7177 Log(("xHCI: Trying to write to register %u!\n", offReg));
7178 STAM_COUNTER_INC(&pThis->StatWrUnknown);
7179 return VINF_SUCCESS;
7180 }
7181
7182 /*
7183 * Validate the access (in case of IOM bug or incorrect MMIO registration).
7184 */
7185 AssertMsgReturn(cb == sizeof(uint32_t), ("IOM bug? %RGp LB %d\n", off, cb), VINF_SUCCESS);
7186 AssertMsgReturn(!(off & 0x3), ("IOM bug? %RGp LB %d\n", off, cb), VINF_SUCCESS);
7187
7188 /*
7189 * Validate the register and call the write operator.
7190 */
7191 VBOXSTRICTRC rcStrict = VINF_IOM_MMIO_UNUSED_FF;
7192 if (offReg >= XHCI_DOORBELL_OFFSET)
7193 {
7194 /* Let's spring into action... as long as the xHC is running. */
7195 iReg = (offReg - XHCI_DOORBELL_OFFSET) >> 2;
7196 if ((pThis->cmd & XHCI_CMD_RS) && iReg < XHCI_NDS)
7197 {
7198 if (iReg == 0)
7199 {
7200 /* DB0 aka Command Ring. */
7201 STAM_COUNTER_INC(&pThis->StatWrDoorBell0);
7202 if (*pu32 == 0)
7203 {
7204 /* Set the Command Ring state to Running if not already set. */
7205 if (!(pThis->crcr & XHCI_CRCR_CRR))
7206 {
7207 Log(("Command ring entered Running state\n"));
7208 ASMAtomicOrU64(&pThis->crcr, XHCI_CRCR_CRR);
7209 }
7210 xhciKickWorker(pDevIns, pThis, XHCI_JOB_PROCESS_CMDRING, 0);
7211 }
7212 else
7213 Log2(("Ignoring DB0 write with value %X!\n", *pu32));
7214 }
7215 else
7216 {
7217 /* Device context doorbell. Do basic parameter checking to avoid
7218 * waking up the worker thread needlessly.
7219 */
7220 STAM_COUNTER_INC(&pThis->StatWrDoorBellN);
7221 uint8_t uDBTarget = *pu32 & XHCI_DB_TGT_MASK;
7222 Assert(uDBTarget < 32); /// @todo Report an error? Or just ignore?
7223 if (uDBTarget < 32)
7224 {
7225 Log2(("Ring bell for slot %u, DCI %u\n", iReg, uDBTarget));
7226 ASMAtomicOrU32(&pThis->aBellsRung[ID_TO_IDX(iReg)], 1 << uDBTarget);
7227 xhciKickWorker(pDevIns, pThis, XHCI_JOB_DOORBELL, *pu32);
7228 }
7229 else
7230 Log2(("Ignoring DB%u write with bad target %u!\n", iReg, uDBTarget));
7231 }
7232 rcStrict = VINF_SUCCESS;
7233 Log2(("xhciWrite: DBellReg (DB %u) %RGp size=%d <- val=%x (rc=%d)\n", iReg, off, cb, *(uint32_t *)pv, VBOXSTRICTRC_VAL(rcStrict)));
7234 }
7235 }
7236 else if (offReg >= XHCI_RTREG_OFFSET)
7237 {
7238 /* Run-time registers. */
7239 Assert(offReg < XHCI_DOORBELL_OFFSET);
7240 /* NB: The MFINDEX register is R/O. */
7241 if (offReg >= XHCI_RTREG_OFFSET + (RT_ELEMENTS(g_aIntrRegs) * sizeof(uint32_t)))
7242 {
7243 Assert((offReg - XHCI_RTREG_OFFSET) / (RT_ELEMENTS(g_aIntrRegs) * sizeof(uint32_t)) > 0);
7244 const uint32_t iIntr = (offReg - XHCI_RTREG_OFFSET) / (RT_ELEMENTS(g_aIntrRegs) * sizeof(uint32_t)) - 1;
7245
7246 if (iIntr < XHCI_NINTR)
7247 {
7248 iReg = (offReg >> 2) & (RT_ELEMENTS(g_aIntrRegs) - 1);
7249 const XHCIINTRREGACC *pReg = &g_aIntrRegs[iReg];
7250 if (pReg->pfnIntrWrite)
7251 {
7252 PXHCIINTRPTR pIntr = &pThis->aInterrupters[iIntr];
7253 rcStrict = pReg->pfnIntrWrite(pDevIns, pThis, pIntr, *pu32);
7254 Log2(("xhciWrite: IntrReg (intr %u): %RGp (%s) size=%d <- val=%x (rc=%d)\n", iIntr, off, pReg->pszName, cb, *pu32, VBOXSTRICTRC_VAL(rcStrict)));
7255 }
7256 }
7257 }
7258 }
7259 else
7260 {
7261 /* Operational registers (incl. port registers). */
7262 Assert(offReg < XHCI_RTREG_OFFSET);
7263 iReg = (offReg - pThis->cap_length) >> 2;
7264 if (iReg < RT_ELEMENTS(g_aOpRegs))
7265 {
7266 const XHCIREGACC *pReg = &g_aOpRegs[iReg];
7267 if (pReg->pfnWrite)
7268 {
7269 rcStrict = pReg->pfnWrite(pDevIns, pThis, iReg, *(uint32_t *)pv);
7270 Log2(("xhciWrite: OpReg %RGp (%s) size=%d <- val=%x (rc=%d)\n", off, pReg->pszName, cb, *(uint32_t *)pv, VBOXSTRICTRC_VAL(rcStrict)));
7271 }
7272 }
7273 else if (iReg >= (XHCI_PORT_REG_OFFSET >> 2))
7274 {
7275 iReg -= (XHCI_PORT_REG_OFFSET >> 2);
7276 const uint32_t iPort = iReg / RT_ELEMENTS(g_aPortRegs);
7277 if (iPort < XHCI_NDP_CFG(pThis))
7278 {
7279 iReg = (offReg >> 2) & (RT_ELEMENTS(g_aPortRegs) - 1);
7280 Assert(iReg < RT_ELEMENTS(g_aPortRegs));
7281 const XHCIREGACC *pReg = &g_aPortRegs[iReg];
7282 if (pReg->pfnWrite)
7283 {
7284 rcStrict = pReg->pfnWrite(pDevIns, pThis, iPort, *pu32);
7285 Log2(("xhciWrite: PortReg (port %u): %RGp (%s) size=%d <- val=%x (rc=%d)\n", IDX_TO_ID(iPort), off, pReg->pszName, cb, *pu32, VBOXSTRICTRC_VAL(rcStrict)));
7286 }
7287 }
7288 }
7289 }
7290
7291 if (rcStrict != VINF_IOM_MMIO_UNUSED_FF)
7292 { /* likely */ }
7293 else
7294 {
7295 /* Ignore writes to unimplemented or read-only registers. */
7296 STAM_COUNTER_INC(&pThis->StatWrUnknown);
7297 Log(("xHCI: Trying to write unimplemented or R/O register at offset %04X!\n", offReg));
7298 rcStrict = VINF_SUCCESS;
7299 }
7300
7301 return rcStrict;
7302}
7303
7304
7305#ifdef IN_RING3
7306
7307/**
7308 * @callback_method_impl{FNTMTIMERDEV,
7309 * Provides periodic MFINDEX wrap events. See 4.14.2.}
7310 */
7311static DECLCALLBACK(void) xhciR3WrapTimer(PPDMDEVINS pDevIns, TMTIMERHANDLE hTimer, void *pvUser)
7312{
7313 PXHCI pThis = (PXHCI)pvUser;
7314 XHCI_EVENT_TRB ed;
7315 LogFlow(("xhciR3WrapTimer:\n"));
7316 RT_NOREF(hTimer);
7317
7318 /*
7319 * Post the MFINDEX Wrap event and rearm the timer. Only called
7320 * when the EWE bit is set in command register.
7321 */
7322 RT_ZERO(ed);
7323 ed.mwe.cc = XHCI_TCC_SUCCESS;
7324 ed.mwe.type = XHCI_TRB_MFIDX_WRAP;
7325 xhciR3WriteEvent(pDevIns, pThis, &ed, XHCI_PRIMARY_INTERRUPTER, false);
7326
7327 xhciSetWrapTimer(pDevIns, pThis);
7328}
7329
7330
7331/**
7332 * @callback_method_impl{FNSSMDEVSAVEEXEC}
7333 */
7334static DECLCALLBACK(int) xhciR3SaveExec(PPDMDEVINS pDevIns, PSSMHANDLE pSSM)
7335{
7336 PXHCI pThis = PDMDEVINS_2_DATA(pDevIns, PXHCI);
7337 PCPDMDEVHLPR3 pHlp = pDevIns->pHlpR3;
7338 uint32_t iPort;
7339 uint32_t iSlot;
7340 uint32_t iIntr;
7341
7342 LogFlow(("xhciR3SaveExec: \n"));
7343
7344 /* Save HC operational registers. */
7345 pHlp->pfnSSMPutU32(pSSM, pThis->cmd);
7346 pHlp->pfnSSMPutU32(pSSM, pThis->status);
7347 pHlp->pfnSSMPutU32(pSSM, pThis->dnctrl);
7348 pHlp->pfnSSMPutU64(pSSM, pThis->crcr);
7349 pHlp->pfnSSMPutU64(pSSM, pThis->dcbaap);
7350 pHlp->pfnSSMPutU32(pSSM, pThis->config);
7351
7352 /* Save HC non-register state. */
7353 pHlp->pfnSSMPutU64(pSSM, pThis->cmdr_dqp);
7354 pHlp->pfnSSMPutBool(pSSM, pThis->cmdr_ccs);
7355
7356 /* Save per-slot state. */
7357 pHlp->pfnSSMPutU32(pSSM, XHCI_NDS);
7358 for (iSlot = 0; iSlot < XHCI_NDS; ++iSlot)
7359 {
7360 pHlp->pfnSSMPutU8 (pSSM, pThis->aSlotState[iSlot]);
7361 pHlp->pfnSSMPutU32(pSSM, pThis->aBellsRung[iSlot]);
7362 }
7363
7364 /* Save root hub (port) state. */
7365 pHlp->pfnSSMPutU32(pSSM, XHCI_NDP_CFG(pThis));
7366 for (iPort = 0; iPort < XHCI_NDP_CFG(pThis); ++iPort)
7367 {
7368 pHlp->pfnSSMPutU32(pSSM, pThis->aPorts[iPort].portsc);
7369 pHlp->pfnSSMPutU32(pSSM, pThis->aPorts[iPort].portpm);
7370 }
7371
7372 /* Save interrupter state. */
7373 pHlp->pfnSSMPutU32(pSSM, XHCI_NINTR);
7374 for (iIntr = 0; iIntr < XHCI_NINTR; ++iIntr)
7375 {
7376 pHlp->pfnSSMPutU32(pSSM, pThis->aInterrupters[iIntr].iman);
7377 pHlp->pfnSSMPutU32(pSSM, pThis->aInterrupters[iIntr].imod);
7378 pHlp->pfnSSMPutU32(pSSM, pThis->aInterrupters[iIntr].erstsz);
7379 pHlp->pfnSSMPutU64(pSSM, pThis->aInterrupters[iIntr].erstba);
7380 pHlp->pfnSSMPutU64(pSSM, pThis->aInterrupters[iIntr].erdp);
7381 pHlp->pfnSSMPutU64(pSSM, pThis->aInterrupters[iIntr].erep);
7382 pHlp->pfnSSMPutU16(pSSM, pThis->aInterrupters[iIntr].erst_idx);
7383 pHlp->pfnSSMPutU16(pSSM, pThis->aInterrupters[iIntr].trb_count);
7384 pHlp->pfnSSMPutBool(pSSM, pThis->aInterrupters[iIntr].evtr_pcs);
7385 pHlp->pfnSSMPutBool(pSSM, pThis->aInterrupters[iIntr].ipe);
7386 }
7387
7388 /* Terminator marker. */
7389 pHlp->pfnSSMPutU32(pSSM, UINT32_MAX);
7390
7391 /* If not continuing after save, force HC into non-running state to avoid trouble later. */
7392 if (pHlp->pfnSSMHandleGetAfter(pSSM) != SSMAFTER_CONTINUE)
7393 pThis->cmd &= ~XHCI_CMD_RS;
7394
7395 return VINF_SUCCESS;
7396}
7397
7398
7399/**
7400 * @callback_method_impl{FNSSMDEVLOADEXEC}
7401 */
7402static DECLCALLBACK(int) xhciR3LoadExec(PPDMDEVINS pDevIns, PSSMHANDLE pSSM, uint32_t uVersion, uint32_t uPass)
7403{
7404 PXHCI pThis = PDMDEVINS_2_DATA(pDevIns, PXHCI);
7405 PCPDMDEVHLPR3 pHlp = pDevIns->pHlpR3;
7406 int rc;
7407 uint32_t cPorts;
7408 uint32_t iPort;
7409 uint32_t cSlots;
7410 uint32_t iSlot;
7411 uint32_t cIntrs;
7412 uint32_t iIntr;
7413 uint64_t u64Dummy;
7414 uint32_t u32Dummy;
7415 uint16_t u16Dummy;
7416 uint8_t u8Dummy;
7417 bool fDummy;
7418
7419 LogFlow(("xhciR3LoadExec:\n"));
7420
7421 Assert(uPass == SSM_PASS_FINAL); NOREF(uPass);
7422 if (uVersion != XHCI_SAVED_STATE_VERSION)
7423 return VERR_SSM_UNSUPPORTED_DATA_UNIT_VERSION;
7424
7425 /* Load HC operational registers. */
7426 pHlp->pfnSSMGetU32(pSSM, &pThis->cmd);
7427 pHlp->pfnSSMGetU32(pSSM, &pThis->status);
7428 pHlp->pfnSSMGetU32(pSSM, &pThis->dnctrl);
7429 pHlp->pfnSSMGetU64(pSSM, &pThis->crcr);
7430 pHlp->pfnSSMGetU64(pSSM, &pThis->dcbaap);
7431 pHlp->pfnSSMGetU32(pSSM, &pThis->config);
7432
7433 /* Load HC non-register state. */
7434 pHlp->pfnSSMGetU64(pSSM, &pThis->cmdr_dqp);
7435 pHlp->pfnSSMGetBool(pSSM, &pThis->cmdr_ccs);
7436
7437 /* Load per-slot state. */
7438 rc = pHlp->pfnSSMGetU32(pSSM, &cSlots);
7439 AssertRCReturn(rc, rc);
7440 if (cSlots > 256) /* Sanity check. */
7441 return VERR_SSM_INVALID_STATE;
7442 for (iSlot = 0; iSlot < cSlots; ++iSlot)
7443 {
7444 /* Load only as many slots as we have; discard any extras. */
7445 if (iSlot < XHCI_NDS)
7446 {
7447 pHlp->pfnSSMGetU8 (pSSM, &pThis->aSlotState[iSlot]);
7448 pHlp->pfnSSMGetU32(pSSM, &pThis->aBellsRung[iSlot]);
7449 }
7450 else
7451 {
7452 pHlp->pfnSSMGetU8 (pSSM, &u8Dummy);
7453 pHlp->pfnSSMGetU32(pSSM, &u32Dummy);
7454 }
7455 }
7456
7457 /* Load root hub (port) state. */
7458 rc = pHlp->pfnSSMGetU32(pSSM, &cPorts);
7459 AssertRCReturn(rc, rc);
7460 if (cPorts > 256) /* Sanity check. */
7461 return VERR_SSM_INVALID_STATE;
7462
7463 for (iPort = 0; iPort < cPorts; ++iPort)
7464 {
7465 /* Load only as many ports as we have; discard any extras. */
7466 if (iPort < XHCI_NDP_CFG(pThis))
7467 {
7468 pHlp->pfnSSMGetU32(pSSM, &pThis->aPorts[iPort].portsc);
7469 pHlp->pfnSSMGetU32(pSSM, &pThis->aPorts[iPort].portpm);
7470 }
7471 else
7472 {
7473 pHlp->pfnSSMGetU32(pSSM, &u32Dummy);
7474 pHlp->pfnSSMGetU32(pSSM, &u32Dummy);
7475 }
7476 }
7477
7478 /* Load interrupter state. */
7479 rc = pHlp->pfnSSMGetU32(pSSM, &cIntrs);
7480 AssertRCReturn(rc, rc);
7481 if (cIntrs > 256) /* Sanity check. */
7482 return VERR_SSM_INVALID_STATE;
7483 for (iIntr = 0; iIntr < cIntrs; ++iIntr)
7484 {
7485 /* Load only as many interrupters as we have; discard any extras. */
7486 if (iIntr < XHCI_NINTR)
7487 {
7488 pHlp->pfnSSMGetU32(pSSM, &pThis->aInterrupters[iIntr].iman);
7489 pHlp->pfnSSMGetU32(pSSM, &pThis->aInterrupters[iIntr].imod);
7490 pHlp->pfnSSMGetU32(pSSM, &pThis->aInterrupters[iIntr].erstsz);
7491 pHlp->pfnSSMGetU64(pSSM, &pThis->aInterrupters[iIntr].erstba);
7492 pHlp->pfnSSMGetU64(pSSM, &pThis->aInterrupters[iIntr].erdp);
7493 pHlp->pfnSSMGetU64(pSSM, &pThis->aInterrupters[iIntr].erep);
7494 pHlp->pfnSSMGetU16(pSSM, &pThis->aInterrupters[iIntr].erst_idx);
7495 pHlp->pfnSSMGetU16(pSSM, &pThis->aInterrupters[iIntr].trb_count);
7496 pHlp->pfnSSMGetBool(pSSM, &pThis->aInterrupters[iIntr].evtr_pcs);
7497 pHlp->pfnSSMGetBool(pSSM, &pThis->aInterrupters[iIntr].ipe);
7498 }
7499 else
7500 {
7501 pHlp->pfnSSMGetU32(pSSM, &u32Dummy);
7502 pHlp->pfnSSMGetU32(pSSM, &u32Dummy);
7503 pHlp->pfnSSMGetU32(pSSM, &u32Dummy);
7504 pHlp->pfnSSMGetU64(pSSM, &u64Dummy);
7505 pHlp->pfnSSMGetU64(pSSM, &u64Dummy);
7506 pHlp->pfnSSMGetU64(pSSM, &u64Dummy);
7507 pHlp->pfnSSMGetU16(pSSM, &u16Dummy);
7508 pHlp->pfnSSMGetU16(pSSM, &u16Dummy);
7509 pHlp->pfnSSMGetBool(pSSM, &fDummy);
7510 pHlp->pfnSSMGetBool(pSSM, &fDummy);
7511 }
7512 }
7513
7514 /* Terminator marker. */
7515 rc = pHlp->pfnSSMGetU32(pSSM, &u32Dummy);
7516 AssertRCReturn(rc, rc);
7517 AssertReturn(u32Dummy == UINT32_MAX, VERR_SSM_DATA_UNIT_FORMAT_CHANGED);
7518
7519 return rc;
7520}
7521
7522
7523/* -=-=-=-=- DBGF -=-=-=-=- */
7524
7525/**
7526 * @callback_method_impl{FNDBGFHANDLERDEV, Dumps xHCI state.}
7527 */
7528static DECLCALLBACK(void) xhciR3Info(PPDMDEVINS pDevIns, PCDBGFINFOHLP pHlp, const char *pszArgs)
7529{
7530 PXHCI pThis = PDMDEVINS_2_DATA(pDevIns, PXHCI);
7531 RTGCPHYS GPAddr;
7532 bool fVerbose = false;
7533 unsigned i, j;
7534 uint64_t u64Val;
7535
7536 /* Parse arguments. */
7537 if (pszArgs)
7538 fVerbose = strstr(pszArgs, "verbose") != NULL;
7539
7540#ifdef XHCI_ERROR_INJECTION
7541 if (pszArgs && strstr(pszArgs, "dropintrhw"))
7542 {
7543 pHlp->pfnPrintf(pHlp, "Dropping the next interrupt (external)!\n");
7544 pThis->fDropIntrHw = true;
7545 return;
7546 }
7547
7548 if (pszArgs && strstr(pszArgs, "dropintrint"))
7549 {
7550 pHlp->pfnPrintf(pHlp, "Dropping the next interrupt (internal)!\n");
7551 pThis->fDropIntrIpe = true;
7552 return;
7553 }
7554
7555 if (pszArgs && strstr(pszArgs, "dropurb"))
7556 {
7557 pHlp->pfnPrintf(pHlp, "Dropping the next URB!\n");
7558 pThis->fDropUrb = true;
7559 return;
7560 }
7561
7562 if (pszArgs && strstr(pszArgs, "genintrhw"))
7563 {
7564 pHlp->pfnPrintf(pHlp, "Generating hardware interrupt (external)...\n");
7565 int iIntr = 0;
7566 PXHCIINTRPTR pIntr = &pThis->aInterrupters[iIntr & XHCI_INTR_MASK];
7567 xhciSetIntr(pDevIns, pThis, pIntr);
7568 return;
7569 }
7570
7571 if (pszArgs && strstr(pszArgs, "genintrint"))
7572 {
7573 pHlp->pfnPrintf(pHlp, "Generating hardware interrupt (internal)...\n");
7574 int iIntr = 0;
7575 PXHCIINTRPTR pIntr = &pThis->aInterrupters[iIntr & XHCI_INTR_MASK];
7576 xhciR3SetIntrPending(pDevIns, pThis, pIntr);
7577 return;
7578 }
7579
7580 if (pszArgs && strstr(pszArgs, "genintrhw"))
7581 {
7582 pHlp->pfnPrintf(pHlp, "Generating hardware interrupt (external)...\n");
7583 int iIntr = 0;
7584 PXHCIINTRPTR pIntr = &pThis->aInterrupters[iIntr & XHCI_INTR_MASK];
7585 xhciSetIntr(pDevIns, pThis, pIntr);
7586 return;
7587 }
7588
7589 if (pszArgs && strstr(pszArgs, "genintrint"))
7590 {
7591 pHlp->pfnPrintf(pHlp, "Generating hardware interrupt (internal)...\n");
7592 int iIntr = 0;
7593 PXHCIINTRPTR pIntr = &pThis->aInterrupters[iIntr & XHCI_INTR_MASK];
7594 xhciR3SetIntrPending(pDevIns, pThis, pIntr);
7595 return;
7596 }
7597
7598 if (pszArgs && strstr(pszArgs, "genportchgevt"))
7599 {
7600 pHlp->pfnPrintf(pHlp, "Generating port change event...\n");
7601 int iPort = 0;
7602 xhciR3GenPortChgEvent(pDevIns, pThis, IDX_TO_ID(iPort));
7603 return;
7604 }
7605
7606 if (pszArgs && strstr(pszArgs, "genmfiwrapevt"))
7607 {
7608 pHlp->pfnPrintf(pHlp, "Generating MF Index wrap event...\n");
7609 XHCI_EVENT_TRB ed;
7610 RT_ZERO(ed);
7611 ed.mwe.cc = XHCI_TCC_SUCCESS;
7612 ed.mwe.type = XHCI_TRB_MFIDX_WRAP;
7613 xhciR3WriteEvent(pDevIns, pThis, &ed, XHCI_PRIMARY_INTERRUPTER, false);
7614 return;
7615 }
7616
7617 if (pszArgs && strstr(pszArgs, "gendoorbell"))
7618 {
7619 pHlp->pfnPrintf(pHlp, "Generating doorbell ring..\n");
7620 xhciKickWorker(pDevIns, pThis, XHCI_JOB_DOORBELL, 0);
7621 return;
7622 }
7623#endif
7624
7625 /* Show basic information. */
7626 pHlp->pfnPrintf(pHlp,
7627 "%s#%d: PCI MMIO=%RGp IRQ=%u MSI=%s R0=%RTbool RC=%RTbool\n",
7628 pDevIns->pReg->szName,
7629 pDevIns->iInstance,
7630 PDMDevHlpMmioGetMappingAddress(pDevIns, pThis->hMmio),
7631 PCIDevGetInterruptLine(pDevIns->apPciDevs[0]),
7632#ifdef VBOX_WITH_MSI_DEVICES
7633 xhciIsMSIEnabled(pDevIns->apPciDevs[0]) ? "on" : "off",
7634#else
7635 "none",
7636#endif
7637 pDevIns->fR0Enabled, pDevIns->fRCEnabled);
7638
7639 /* Command register. */
7640 pHlp->pfnPrintf(pHlp, "USBCMD: %X:", pThis->cmd);
7641 if (pThis->cmd & XHCI_CMD_EU3S) pHlp->pfnPrintf(pHlp, " EU3S" );
7642 if (pThis->cmd & XHCI_CMD_EWE) pHlp->pfnPrintf(pHlp, " EWE" );
7643 if (pThis->cmd & XHCI_CMD_CRS) pHlp->pfnPrintf(pHlp, " CRS" );
7644 if (pThis->cmd & XHCI_CMD_CSS) pHlp->pfnPrintf(pHlp, " CSS" );
7645 if (pThis->cmd & XHCI_CMD_LCRST) pHlp->pfnPrintf(pHlp, " LCRST" );
7646 if (pThis->cmd & XHCI_CMD_HSEE) pHlp->pfnPrintf(pHlp, " HSEE" );
7647 if (pThis->cmd & XHCI_CMD_INTE) pHlp->pfnPrintf(pHlp, " INTE" );
7648 if (pThis->cmd & XHCI_CMD_HCRST) pHlp->pfnPrintf(pHlp, " HCRST" );
7649 if (pThis->cmd & XHCI_CMD_RS) pHlp->pfnPrintf(pHlp, " RS" );
7650 pHlp->pfnPrintf(pHlp, "\n");
7651
7652 /* Status register. */
7653 pHlp->pfnPrintf(pHlp, "USBSTS: %X:", pThis->status);
7654 if (pThis->status & XHCI_STATUS_HCH) pHlp->pfnPrintf(pHlp, " HCH" );
7655 if (pThis->status & XHCI_STATUS_HSE) pHlp->pfnPrintf(pHlp, " HSE" );
7656 if (pThis->status & XHCI_STATUS_EINT) pHlp->pfnPrintf(pHlp, " EINT" );
7657 if (pThis->status & XHCI_STATUS_PCD) pHlp->pfnPrintf(pHlp, " PCD" );
7658 if (pThis->status & XHCI_STATUS_SSS) pHlp->pfnPrintf(pHlp, " SSS" );
7659 if (pThis->status & XHCI_STATUS_RSS) pHlp->pfnPrintf(pHlp, " RSS" );
7660 if (pThis->status & XHCI_STATUS_SRE) pHlp->pfnPrintf(pHlp, " SRE" );
7661 if (pThis->status & XHCI_STATUS_CNR) pHlp->pfnPrintf(pHlp, " CNR" );
7662 if (pThis->status & XHCI_STATUS_HCE) pHlp->pfnPrintf(pHlp, " HCE" );
7663 pHlp->pfnPrintf(pHlp, "\n");
7664
7665 /* Device Notification Control and Configure registers. */
7666 pHlp->pfnPrintf(pHlp, "DNCTRL: %X CONFIG: %X (%u slots)\n", pThis->dnctrl, pThis->config, pThis->config);
7667
7668 /* Device Context Base Address Array. */
7669 GPAddr = pThis->dcbaap & XHCI_DCBAA_ADDR_MASK;
7670 pHlp->pfnPrintf(pHlp, "DCBAA ptr: %RGp\n", GPAddr);
7671 /* The DCBAA must be valid in 'run' state. */
7672 if (fVerbose && (pThis->cmd & XHCI_CMD_RS))
7673 {
7674 PDMDevHlpPCIPhysRead(pDevIns, GPAddr, &u64Val, sizeof(u64Val));
7675 pHlp->pfnPrintf(pHlp, " Scratchpad buffer: %RX64\n", u64Val);
7676 }
7677
7678 /* Command Ring Control Register. */
7679 pHlp->pfnPrintf(pHlp, "CRCR: %X:", pThis->crcr & ~XHCI_CRCR_ADDR_MASK);
7680 if (pThis->crcr & XHCI_CRCR_RCS) pHlp->pfnPrintf(pHlp, " RCS");
7681 if (pThis->crcr & XHCI_CRCR_CS) pHlp->pfnPrintf(pHlp, " CS" );
7682 if (pThis->crcr & XHCI_CRCR_CA) pHlp->pfnPrintf(pHlp, " CA" );
7683 if (pThis->crcr & XHCI_CRCR_CRR) pHlp->pfnPrintf(pHlp, " CRR");
7684 pHlp->pfnPrintf(pHlp, "\n");
7685 GPAddr = pThis->crcr & XHCI_CRCR_ADDR_MASK;
7686 pHlp->pfnPrintf(pHlp, "CRCR ptr : %RGp\n", GPAddr);
7687
7688 /* Interrupters. */
7689 if (fVerbose)
7690 {
7691 for (i = 0; i < RT_ELEMENTS(pThis->aInterrupters); ++i)
7692 {
7693 if (pThis->aInterrupters[i].erstsz)
7694 {
7695 XHCIINTRPTR *ir = &pThis->aInterrupters[i];
7696
7697 pHlp->pfnPrintf(pHlp, "Interrupter %d (IPE=%u)\n", i, ir->ipe);
7698
7699 /* The Interrupt Management Register. */
7700 pHlp->pfnPrintf(pHlp, " IMAN : %X:", ir->iman);
7701 if (ir->iman & XHCI_IMAN_IP) pHlp->pfnPrintf(pHlp, " IP");
7702 if (ir->iman & XHCI_IMAN_IE) pHlp->pfnPrintf(pHlp, " IE");
7703 pHlp->pfnPrintf(pHlp, "\n");
7704
7705 /* The Interrupt Moderation Register. */
7706 pHlp->pfnPrintf(pHlp, " IMOD : %X:", ir->imod);
7707 pHlp->pfnPrintf(pHlp, " IMODI=%u", ir->imod & XHCI_IMOD_IMODI_MASK);
7708 pHlp->pfnPrintf(pHlp, " IMODC=%u", (ir->imod & XHCI_IMOD_IMODC_MASK) >> XHCI_IMOD_IMODC_SHIFT);
7709 pHlp->pfnPrintf(pHlp, "\n");
7710
7711 pHlp->pfnPrintf(pHlp, " ERSTSZ: %X\n", ir->erstsz);
7712 pHlp->pfnPrintf(pHlp, " ERSTBA: %RGp\n", (RTGCPHYS)ir->erstba);
7713
7714 pHlp->pfnPrintf(pHlp, " ERDP : %RGp:", (RTGCPHYS)ir->erdp);
7715 pHlp->pfnPrintf(pHlp, " EHB=%u", !!(ir->erdp & XHCI_ERDP_EHB));
7716 pHlp->pfnPrintf(pHlp, " DESI=%u", ir->erdp & XHCI_ERDP_DESI_MASK);
7717 pHlp->pfnPrintf(pHlp, " ptr=%RGp", ir->erdp & XHCI_ERDP_ADDR_MASK);
7718 pHlp->pfnPrintf(pHlp, "\n");
7719
7720 pHlp->pfnPrintf(pHlp, " EREP : %RGp", ir->erep);
7721 pHlp->pfnPrintf(pHlp, " Free TRBs in seg=%u", ir->trb_count);
7722 pHlp->pfnPrintf(pHlp, "\n");
7723 }
7724 }
7725 }
7726
7727 /* Port control/status. */
7728 for (i = 0; i < XHCI_NDP_CFG(pThis); ++i)
7729 {
7730 PXHCIHUBPORT p = &pThis->aPorts[i];
7731
7732 pHlp->pfnPrintf(pHlp, "Port %02u (USB%c): ", IDX_TO_ID(i), IS_USB3_PORT_IDX_SHR(pThis, i) ? '3' : '2');
7733
7734 /* Port Status register. */
7735 pHlp->pfnPrintf(pHlp, "PORTSC: %8X:", p->portsc);
7736 if (p->portsc & XHCI_PORT_CCS) pHlp->pfnPrintf(pHlp, " CCS" );
7737 if (p->portsc & XHCI_PORT_PED) pHlp->pfnPrintf(pHlp, " PED" );
7738 if (p->portsc & XHCI_PORT_OCA) pHlp->pfnPrintf(pHlp, " OCA" );
7739 if (p->portsc & XHCI_PORT_PR ) pHlp->pfnPrintf(pHlp, " PR" );
7740 pHlp->pfnPrintf(pHlp, " PLS=%u", (p->portsc & XHCI_PORT_PLS_MASK) >> XHCI_PORT_PLS_SHIFT);
7741 if (p->portsc & XHCI_PORT_PP ) pHlp->pfnPrintf(pHlp, " PP" );
7742 pHlp->pfnPrintf(pHlp, " SPD=%u", (p->portsc & XHCI_PORT_SPD_MASK) >> XHCI_PORT_SPD_SHIFT);
7743 if (p->portsc & XHCI_PORT_LWS) pHlp->pfnPrintf(pHlp, " LWS" );
7744 if (p->portsc & XHCI_PORT_CSC) pHlp->pfnPrintf(pHlp, " CSC" );
7745 if (p->portsc & XHCI_PORT_PEC) pHlp->pfnPrintf(pHlp, " PEC" );
7746 if (p->portsc & XHCI_PORT_WRC) pHlp->pfnPrintf(pHlp, " WRC" );
7747 if (p->portsc & XHCI_PORT_OCC) pHlp->pfnPrintf(pHlp, " OCC" );
7748 if (p->portsc & XHCI_PORT_PRC) pHlp->pfnPrintf(pHlp, " PRC" );
7749 if (p->portsc & XHCI_PORT_PLC) pHlp->pfnPrintf(pHlp, " PLC" );
7750 if (p->portsc & XHCI_PORT_CEC) pHlp->pfnPrintf(pHlp, " CEC" );
7751 if (p->portsc & XHCI_PORT_CAS) pHlp->pfnPrintf(pHlp, " CAS" );
7752 if (p->portsc & XHCI_PORT_WCE) pHlp->pfnPrintf(pHlp, " WCE" );
7753 if (p->portsc & XHCI_PORT_WDE) pHlp->pfnPrintf(pHlp, " WDE" );
7754 if (p->portsc & XHCI_PORT_WOE) pHlp->pfnPrintf(pHlp, " WOE" );
7755 if (p->portsc & XHCI_PORT_DR ) pHlp->pfnPrintf(pHlp, " DR" );
7756 if (p->portsc & XHCI_PORT_WPR) pHlp->pfnPrintf(pHlp, " WPR" );
7757 pHlp->pfnPrintf(pHlp, "\n");
7758 }
7759
7760 /* Device contexts. */
7761 if (fVerbose && (pThis->cmd & XHCI_CMD_RS))
7762 {
7763 for (i = 0; i < XHCI_NDS; ++i)
7764 {
7765 if (pThis->aSlotState[i] > XHCI_DEVSLOT_EMPTY)
7766 {
7767 RTGCPHYS GCPhysSlot;
7768 XHCI_DEV_CTX ctxDevice;
7769 XHCI_SLOT_CTX ctxSlot;
7770 const char *pcszDesc;
7771 uint8_t uSlotID = IDX_TO_ID(i);
7772
7773 /* Find the slot address/ */
7774 GCPhysSlot = xhciR3FetchDevCtxAddr(pDevIns, pThis, uSlotID);
7775 pHlp->pfnPrintf(pHlp, "Slot %d (device context @ %RGp)\n", uSlotID, GCPhysSlot);
7776 if (!GCPhysSlot)
7777 {
7778 pHlp->pfnPrintf(pHlp, "Bad context address, skipping!\n");
7779 continue;
7780 }
7781
7782 /* Just read in the whole lot and sort in which contexts are valid later. */
7783 PDMDevHlpPCIPhysRead(pDevIns, GCPhysSlot, &ctxDevice, sizeof(ctxDevice));
7784
7785 ctxSlot = ctxDevice.entry[0].sc;
7786 pcszDesc = ctxSlot.slot_state < RT_ELEMENTS(g_apszSltStates) ? g_apszSltStates[ctxSlot.slot_state] : "BAD!!!";
7787 pHlp->pfnPrintf(pHlp, " Speed:%u Entries:%u RhPort:%u", ctxSlot.speed, ctxSlot.ctx_ent, ctxSlot.rh_port);
7788 pHlp->pfnPrintf(pHlp, " Address:%u State:%s \n", ctxSlot.dev_addr, pcszDesc);
7789 pHlp->pfnPrintf(pHlp, " Doorbells:%08X\n", pThis->aBellsRung[ID_TO_IDX(uSlotID)]);
7790
7791 /* Endpoint contexts. */
7792 for (j = 1; j <= ctxSlot.ctx_ent; ++j)
7793 {
7794 XHCI_EP_CTX ctxEP = ctxDevice.entry[j].ep;
7795
7796 /* Skip disabled endpoints -- they may be unused and do not
7797 * contain valid data in any case.
7798 */
7799 if (ctxEP.ep_state == XHCI_EPST_DISABLED)
7800 continue;
7801
7802 pcszDesc = ctxEP.ep_state < RT_ELEMENTS(g_apszEpStates) ? g_apszEpStates[ctxEP.ep_state] : "BAD!!!";
7803 pHlp->pfnPrintf(pHlp, " Endpoint DCI %u State:%s", j, pcszDesc);
7804 pcszDesc = ctxEP.ep_type < RT_ELEMENTS(g_apszEpTypes) ? g_apszEpTypes[ctxEP.ep_type] : "BAD!!!";
7805 pHlp->pfnPrintf(pHlp, " Type:%s\n",pcszDesc);
7806
7807 pHlp->pfnPrintf(pHlp, " Mult:%u MaxPStreams:%u LSA:%u Interval:%u\n",
7808 ctxEP.mult, ctxEP.maxps, ctxEP.lsa, ctxEP.interval);
7809 pHlp->pfnPrintf(pHlp, " CErr:%u HID:%u MaxPS:%u MaxBS:%u",
7810 ctxEP.c_err, ctxEP.hid, ctxEP.max_pkt_sz, ctxEP.max_brs_sz);
7811 pHlp->pfnPrintf(pHlp, " AvgTRBLen:%u MaxESIT:%u",
7812 ctxEP.avg_trb_len, ctxEP.max_esit);
7813 pHlp->pfnPrintf(pHlp, " LastFrm:%u IFC:%u LastCC:%u\n",
7814 ctxEP.last_frm, ctxEP.ifc, ctxEP.last_cc);
7815 pHlp->pfnPrintf(pHlp, " TRDP:%RGp DCS:%u\n", (RTGCPHYS)(ctxEP.trdp & XHCI_TRDP_ADDR_MASK),
7816 ctxEP.trdp & XHCI_TRDP_DCS_MASK);
7817 pHlp->pfnPrintf(pHlp, " TREP:%RGp DCS:%u\n", (RTGCPHYS)(ctxEP.trep & XHCI_TRDP_ADDR_MASK),
7818 ctxEP.trep & XHCI_TRDP_DCS_MASK);
7819 }
7820 }
7821 }
7822 }
7823}
7824
7825
7826/**
7827 * @interface_method_impl{PDMDEVREG,pfnReset}
7828 */
7829static DECLCALLBACK(void) xhciR3Reset(PPDMDEVINS pDevIns)
7830{
7831 PXHCI pThis = PDMDEVINS_2_DATA(pDevIns, PXHCI);
7832 PXHCICC pThisCC = PDMDEVINS_2_DATA_CC(pDevIns, PXHCICC);
7833 LogFlow(("xhciR3Reset:\n"));
7834
7835 /*
7836 * There is no distinction between cold boot, warm reboot and software reboots,
7837 * all of these are treated as cold boots. We are also doing the initialization
7838 * job of a BIOS or SMM driver.
7839 *
7840 * Important: Don't confuse UsbReset with hardware reset. Hardware reset is
7841 * just one way of getting into the UsbReset state.
7842 */
7843
7844 /* Set the HC Halted bit now to prevent completion callbacks from running
7845 *(there is really no point when resetting).
7846 */
7847 ASMAtomicOrU32(&pThis->status, XHCI_STATUS_HCH);
7848
7849 xhciR3BusStop(pDevIns, pThis, pThisCC);
7850 xhciR3DoReset(pThis, pThisCC, XHCI_USB_RESET, true /* reset devices */);
7851}
7852
7853
7854/**
7855 * @interface_method_impl{PDMDEVREG,pfnDestruct}
7856 */
7857static DECLCALLBACK(int) xhciR3Destruct(PPDMDEVINS pDevIns)
7858{
7859 PDMDEV_CHECK_VERSIONS_RETURN_QUIET(pDevIns);
7860 PXHCI pThis = PDMDEVINS_2_DATA(pDevIns, PXHCI);
7861 PXHCICC pThisCC = PDMDEVINS_2_DATA_CC(pDevIns, PXHCICC);
7862 LogFlow(("xhciR3Destruct:\n"));
7863
7864 /*
7865 * Destroy interrupter locks.
7866 */
7867 for (unsigned i = 0; i < RT_ELEMENTS(pThis->aInterrupters); ++i)
7868 {
7869 if (PDMDevHlpCritSectIsInitialized(pDevIns, &pThis->aInterrupters[i].lock))
7870 PDMDevHlpCritSectDelete(pDevIns, &pThis->aInterrupters[i].lock);
7871 }
7872
7873 /*
7874 * Clean up the worker thread and associated machinery.
7875 */
7876 if (pThis->hEvtProcess != NIL_SUPSEMEVENT)
7877 {
7878 PDMDevHlpSUPSemEventClose(pDevIns, pThis->hEvtProcess);
7879 pThis->hEvtProcess = NIL_SUPSEMEVENT;
7880 }
7881 if (RTCritSectIsInitialized(&pThisCC->CritSectThrd))
7882 RTCritSectDelete(&pThisCC->CritSectThrd);
7883
7884 return VINF_SUCCESS;
7885}
7886
7887
7888/**
7889 * Worker for xhciR3Construct that registers a LUN (USB root hub).
7890 */
7891static int xhciR3RegisterHub(PPDMDEVINS pDevIns, PXHCIROOTHUBR3 pRh, uint32_t iLun, const char *pszDesc)
7892{
7893 int rc = PDMDevHlpDriverAttach(pDevIns, iLun, &pRh->IBase, &pRh->pIBase, pszDesc);
7894 AssertMsgRCReturn(rc, ("Configuration error: Failed to attach root hub driver to LUN #%u! (%Rrc)\n", iLun, rc), rc);
7895
7896 pRh->pIRhConn = PDMIBASE_QUERY_INTERFACE(pRh->pIBase, VUSBIROOTHUBCONNECTOR);
7897 AssertMsgReturn(pRh->pIRhConn,
7898 ("Configuration error: The driver doesn't provide the VUSBIROOTHUBCONNECTOR interface!\n"),
7899 VERR_PDM_MISSING_INTERFACE);
7900
7901 /* Set URB parameters. */
7902 rc = VUSBIRhSetUrbParams(pRh->pIRhConn, sizeof(VUSBURBHCIINT), 0);
7903 if (RT_FAILURE(rc))
7904 return PDMDevHlpVMSetError(pDevIns, rc, RT_SRC_POS, N_("OHCI: Failed to set URB parameters"));
7905
7906 return rc;
7907}
7908
7909/**
7910 * @interface_method_impl{PDMDEVREG,pfnConstruct,XHCI
7911 * constructor}
7912 */
7913static DECLCALLBACK(int) xhciR3Construct(PPDMDEVINS pDevIns, int iInstance, PCFGMNODE pCfg)
7914{
7915 PDMDEV_CHECK_VERSIONS_RETURN(pDevIns);
7916 PXHCI pThis = PDMDEVINS_2_DATA(pDevIns, PXHCI);
7917 PXHCICC pThisCC = PDMDEVINS_2_DATA_CC(pDevIns, PXHCICC);
7918 PCPDMDEVHLPR3 pHlp = pDevIns->pHlpR3;
7919 uint8_t cUsb2Ports;
7920 uint8_t cUsb3Ports;
7921 int rc;
7922 LogFlow(("xhciR3Construct:\n"));
7923 RT_NOREF(iInstance);
7924
7925 /*
7926 * Initialize data so the destructor runs smoothly.
7927 */
7928 pThis->hEvtProcess = NIL_SUPSEMEVENT;
7929
7930 /*
7931 * Validate and read configuration.
7932 */
7933 PDMDEV_VALIDATE_CONFIG_RETURN(pDevIns, "USB2Ports|USB3Ports|ChipType", "");
7934
7935 /* Number of USB2 ports option. */
7936 rc = pHlp->pfnCFGMQueryU8Def(pCfg, "USB2Ports", &cUsb2Ports, XHCI_NDP_20_DEFAULT);
7937 if (RT_FAILURE(rc))
7938 return PDMDEV_SET_ERROR(pDevIns, rc,
7939 N_("xHCI configuration error: failed to read USB2Ports as integer"));
7940
7941 if (cUsb2Ports == 0 || cUsb2Ports > XHCI_NDP_MAX)
7942 return PDMDevHlpVMSetError(pDevIns, VERR_INVALID_PARAMETER, RT_SRC_POS,
7943 N_("xHCI configuration error: USB2Ports must be in range [%u,%u]"),
7944 1, XHCI_NDP_MAX);
7945
7946 /* Number of USB3 ports option. */
7947 rc = pHlp->pfnCFGMQueryU8Def(pCfg, "USB3Ports", &cUsb3Ports, XHCI_NDP_30_DEFAULT);
7948 if (RT_FAILURE(rc))
7949 return PDMDEV_SET_ERROR(pDevIns, rc,
7950 N_("xHCI configuration error: failed to read USB3Ports as integer"));
7951
7952 if (cUsb3Ports == 0 || cUsb3Ports > XHCI_NDP_MAX)
7953 return PDMDevHlpVMSetError(pDevIns, VERR_INVALID_PARAMETER, RT_SRC_POS,
7954 N_("xHCI configuration error: USB3Ports must be in range [%u,%u]"),
7955 1, XHCI_NDP_MAX);
7956
7957 /* Check that the total number of ports is within limits.*/
7958 if (cUsb2Ports + cUsb3Ports > XHCI_NDP_MAX)
7959 return PDMDevHlpVMSetError(pDevIns, VERR_INVALID_PARAMETER, RT_SRC_POS,
7960 N_("xHCI configuration error: USB2Ports + USB3Ports must be in range [%u,%u]"),
7961 1, XHCI_NDP_MAX);
7962
7963 /* Determine the model. */
7964 char szChipType[16];
7965 rc = pHlp->pfnCFGMQueryStringDef(pCfg, "ChipType", &szChipType[0], sizeof(szChipType), "PantherPoint");
7966 if (RT_FAILURE(rc))
7967 return PDMDEV_SET_ERROR(pDevIns, VERR_PDM_DEVINS_UNKNOWN_CFG_VALUES,
7968 N_("xHCI configuration error: Querying \"ChipType\" as string failed"));
7969
7970 /*
7971 * The default model is Panther Point (8086:1E31), Intel's first and most widely
7972 * supported xHCI implementation. For debugging, the Lynx Point (8086:8C31) model
7973 * can be selected. These two models work with the 7 Series and 8 Series Intel xHCI
7974 * drivers for Windows 7, respectively. There is no functional difference.
7975 * For Windows XP support, it's also possible to present a Renesas uPD720201 xHC;
7976 * this is an evolution of the original NEC xHCI chip.
7977 */
7978 bool fChipLynxPoint = false;
7979 bool fChipRenesas = false;
7980 if (!strcmp(szChipType, "PantherPoint"))
7981 fChipLynxPoint = false;
7982 else if (!strcmp(szChipType, "LynxPoint"))
7983 fChipLynxPoint = true;
7984 else if (!strcmp(szChipType, "uPD720201"))
7985 fChipRenesas = true;
7986 else
7987 return PDMDevHlpVMSetError(pDevIns, VERR_PDM_DEVINS_UNKNOWN_CFG_VALUES, RT_SRC_POS,
7988 N_("xHCI configuration error: The \"ChipType\" value \"%s\" is unsupported"), szChipType);
7989
7990 LogFunc(("cUsb2Ports=%u cUsb3Ports=%u szChipType=%s (%d,%d) fR0Enabled=%d fRCEnabled=%d\n", cUsb2Ports, cUsb3Ports,
7991 szChipType, fChipLynxPoint, fChipRenesas, pDevIns->fR0Enabled, pDevIns->fRCEnabled));
7992
7993 /* Set up interrupter locks. */
7994 for (unsigned i = 0; i < RT_ELEMENTS(pThis->aInterrupters); ++i)
7995 {
7996 rc = PDMDevHlpCritSectInit(pDevIns, &pThis->aInterrupters[i].lock, RT_SRC_POS, "xHCIIntr#%u", i);
7997 if (RT_FAILURE(rc))
7998 return PDMDevHlpVMSetError(pDevIns, rc, RT_SRC_POS,
7999 N_("xHCI: Failed to create critical section for interrupter %u"), i);
8000 pThis->aInterrupters[i].index = i; /* Stash away index, mostly for logging/debugging. */
8001 }
8002
8003
8004 /*
8005 * Init instance data.
8006 */
8007 pThisCC->pDevIns = pDevIns;
8008
8009 PPDMPCIDEV pPciDev = pDevIns->apPciDevs[0];
8010 if (fChipRenesas)
8011 {
8012 pThis->erst_addr_mask = NEC_ERST_ADDR_MASK;
8013 PCIDevSetVendorId(pPciDev, 0x1912);
8014 PCIDevSetDeviceId(pPciDev, 0x0014);
8015 PCIDevSetByte(pPciDev, VBOX_PCI_REVISION_ID, 0x02);
8016 }
8017 else
8018 {
8019 pThis->erst_addr_mask = XHCI_ERST_ADDR_MASK;
8020 PCIDevSetVendorId(pPciDev, 0x8086);
8021 if (fChipLynxPoint)
8022 PCIDevSetDeviceId(pPciDev, 0x8C31); /* Lynx Point / 8 Series */
8023 else
8024 PCIDevSetDeviceId(pPciDev, 0x1E31); /* Panther Point / 7 Series */
8025 }
8026
8027 PCIDevSetClassProg(pPciDev, 0x30); /* xHCI */
8028 PCIDevSetClassSub(pPciDev, 0x03); /* USB 3.0 */
8029 PCIDevSetClassBase(pPciDev, 0x0C);
8030 PCIDevSetInterruptPin(pPciDev, 0x01);
8031#ifdef VBOX_WITH_MSI_DEVICES
8032 PCIDevSetStatus(pPciDev, VBOX_PCI_STATUS_CAP_LIST);
8033 PCIDevSetCapabilityList(pPciDev, 0x80);
8034#endif
8035 PDMPciDevSetByte(pPciDev, 0x60, 0x20); /* serial bus release number register; 0x20 = USB 2.0 */
8036 /** @todo USBLEGSUP & USBLEGCTLSTS? Legacy interface for the BIOS (0xEECP+0 & 0xEECP+4) */
8037
8038 pThis->cTotalPorts = (uint8_t)(cUsb2Ports + cUsb3Ports);
8039
8040 /* Set up the USB2 root hub interface. */
8041 pThis->cUsb2Ports = cUsb2Ports;
8042 pThisCC->RootHub2.pXhciR3 = pThisCC;
8043 pThisCC->RootHub2.cPortsImpl = cUsb2Ports;
8044 pThisCC->RootHub2.uPortBase = 0;
8045 pThisCC->RootHub2.IBase.pfnQueryInterface = xhciR3RhQueryInterface;
8046 pThisCC->RootHub2.IRhPort.pfnGetAvailablePorts = xhciR3RhGetAvailablePorts;
8047 pThisCC->RootHub2.IRhPort.pfnGetUSBVersions = xhciR3RhGetUSBVersions2;
8048 pThisCC->RootHub2.IRhPort.pfnAttach = xhciR3RhAttach;
8049 pThisCC->RootHub2.IRhPort.pfnDetach = xhciR3RhDetach;
8050 pThisCC->RootHub2.IRhPort.pfnReset = xhciR3RhReset;
8051 pThisCC->RootHub2.IRhPort.pfnXferCompletion = xhciR3RhXferCompletion;
8052 pThisCC->RootHub2.IRhPort.pfnXferError = xhciR3RhXferError;
8053
8054 /* Now the USB3 root hub interface. */
8055 pThis->cUsb3Ports = cUsb3Ports;
8056 pThisCC->RootHub3.pXhciR3 = pThisCC;
8057 pThisCC->RootHub3.cPortsImpl = cUsb3Ports;
8058 pThisCC->RootHub3.uPortBase = XHCI_NDP_USB2(pThisCC);
8059 pThisCC->RootHub3.IBase.pfnQueryInterface = xhciR3RhQueryInterface;
8060 pThisCC->RootHub3.IRhPort.pfnGetAvailablePorts = xhciR3RhGetAvailablePorts;
8061 pThisCC->RootHub3.IRhPort.pfnGetUSBVersions = xhciR3RhGetUSBVersions3;
8062 pThisCC->RootHub3.IRhPort.pfnAttach = xhciR3RhAttach;
8063 pThisCC->RootHub3.IRhPort.pfnDetach = xhciR3RhDetach;
8064 pThisCC->RootHub3.IRhPort.pfnReset = xhciR3RhReset;
8065 pThisCC->RootHub3.IRhPort.pfnXferCompletion = xhciR3RhXferCompletion;
8066 pThisCC->RootHub3.IRhPort.pfnXferError = xhciR3RhXferError;
8067
8068 /* USB LED */
8069 pThisCC->RootHub2.Led.u32Magic = PDMLED_MAGIC;
8070 pThisCC->RootHub3.Led.u32Magic = PDMLED_MAGIC;
8071 pThisCC->IBase.pfnQueryInterface = xhciR3QueryStatusInterface;
8072 pThisCC->ILeds.pfnQueryStatusLed = xhciR3QueryStatusLed;
8073
8074 /* Initialize the capability registers */
8075 pThis->cap_length = XHCI_CAPS_REG_SIZE;
8076 pThis->hci_version = 0x100; /* Version 1.0 */
8077 pThis->hcs_params1 = (XHCI_NDP_CFG(pThis) << 24) | (XHCI_NINTR << 8) | XHCI_NDS;
8078 pThis->hcs_params2 = (XHCI_ERSTMAX_LOG2 << 4) | XHCI_IST;
8079 pThis->hcs_params3 = (4 << 16) | 1; /* Matches Intel 7 Series xHCI. */
8080 /* Note: The Intel 7 Series xHCI does not have port power control (XHCI_HCC_PPC). */
8081 pThis->hcc_params = ((XHCI_XECP_OFFSET >> 2) << XHCI_HCC_XECP_SHIFT); /// @todo other fields
8082 pThis->dbell_off = XHCI_DOORBELL_OFFSET;
8083 pThis->rts_off = XHCI_RTREG_OFFSET;
8084
8085 /*
8086 * Set up extended capabilities.
8087 */
8088 rc = xhciR3BuildExtCaps(pThis, pThisCC);
8089 AssertRCReturn(rc, rc);
8090
8091 /*
8092 * Register PCI device and I/O region.
8093 */
8094 rc = PDMDevHlpPCIRegister(pDevIns, pPciDev);
8095 AssertRCReturn(rc, rc);
8096
8097#ifdef VBOX_WITH_MSI_DEVICES
8098 PDMMSIREG MsiReg;
8099 RT_ZERO(MsiReg);
8100 MsiReg.cMsiVectors = 1;
8101 MsiReg.iMsiCapOffset = XHCI_PCI_MSI_CAP_OFS;
8102 MsiReg.iMsiNextOffset = 0x00;
8103 rc = PDMDevHlpPCIRegisterMsi(pDevIns, &MsiReg);
8104 if (RT_FAILURE (rc))
8105 {
8106 PCIDevSetCapabilityList(pPciDev, 0x0);
8107 /* That's OK, we can work without MSI */
8108 }
8109#endif
8110
8111 rc = PDMDevHlpPCIIORegionCreateMmio(pDevIns, 0, XHCI_MMIO_SIZE, PCI_ADDRESS_SPACE_MEM,
8112 xhciMmioWrite, xhciMmioRead, NULL,
8113 IOMMMIO_FLAGS_READ_DWORD | IOMMMIO_FLAGS_WRITE_DWORD_ZEROED
8114 /*| IOMMMIO_FLAGS_DBGSTOP_ON_COMPLICATED_WRITE*/,
8115 "USB xHCI", &pThis->hMmio);
8116 AssertRCReturn(rc, rc);
8117
8118 /*
8119 * Register the saved state data unit.
8120 */
8121 rc = PDMDevHlpSSMRegisterEx(pDevIns, XHCI_SAVED_STATE_VERSION, sizeof(*pThis), NULL,
8122 NULL, NULL, NULL,
8123 NULL, xhciR3SaveExec, NULL,
8124 NULL, xhciR3LoadExec, NULL);
8125 AssertRCReturn(rc, rc);
8126
8127 /*
8128 * Attach to the VBox USB RootHub Driver on LUN #0 (USB3 root hub).
8129 * NB: USB3 must come first so that emulated devices which support both USB2
8130 * and USB3 are attached to the USB3 hub.
8131 */
8132 rc = xhciR3RegisterHub(pDevIns, &pThisCC->RootHub3, 0, "RootHubUSB3");
8133 AssertRCReturn(rc, rc);
8134
8135 /*
8136 * Attach to the VBox USB RootHub Driver on LUN #1 (USB2 root hub).
8137 */
8138 rc = xhciR3RegisterHub(pDevIns, &pThisCC->RootHub2, 1, "RootHubUSB2");
8139 AssertRCReturn(rc, rc);
8140
8141 /*
8142 * Attach the status LED (optional).
8143 */
8144 PPDMIBASE pBase;
8145 rc = PDMDevHlpDriverAttach(pDevIns, PDM_STATUS_LUN, &pThisCC->IBase, &pBase, "Status Port");
8146 if (RT_SUCCESS(rc))
8147 pThisCC->pLedsConnector = PDMIBASE_QUERY_INTERFACE(pBase, PDMILEDCONNECTORS);
8148 else if (rc != VERR_PDM_NO_ATTACHED_DRIVER)
8149 {
8150 AssertMsgFailed(("xHCI: Failed to attach to status driver. rc=%Rrc\n", rc));
8151 return PDMDEV_SET_ERROR(pDevIns, rc, N_("xHCI cannot attach to status driver"));
8152 }
8153
8154 /*
8155 * Create the MFINDEX wrap event timer.
8156 */
8157 rc = PDMDevHlpTimerCreate(pDevIns, TMCLOCK_VIRTUAL, xhciR3WrapTimer, pThis,
8158 TMTIMER_FLAGS_NO_CRIT_SECT | TMTIMER_FLAGS_RING0, "xHCI MFINDEX Wrap", &pThis->hWrapTimer);
8159 AssertRCReturn(rc, rc);
8160
8161 /*
8162 * Set up the worker thread.
8163 */
8164 rc = PDMDevHlpSUPSemEventCreate(pDevIns, &pThis->hEvtProcess);
8165 AssertLogRelRCReturn(rc, rc);
8166
8167 rc = RTCritSectInit(&pThisCC->CritSectThrd);
8168 AssertLogRelRCReturn(rc, rc);
8169
8170 rc = PDMDevHlpThreadCreate(pDevIns, &pThisCC->pWorkerThread, pThis, xhciR3WorkerLoop, xhciR3WorkerWakeUp,
8171 0, RTTHREADTYPE_IO, "xHCI");
8172 AssertLogRelRCReturn(rc, rc);
8173
8174 /*
8175 * Do a hardware reset.
8176 */
8177 xhciR3DoReset(pThis, pThisCC, XHCI_USB_RESET, false /* don't reset devices */);
8178
8179# ifdef VBOX_WITH_STATISTICS
8180 /*
8181 * Register statistics.
8182 */
8183 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatErrorIsocUrbs, STAMTYPE_COUNTER, "IsocUrbsErr", STAMUNIT_OCCURENCES, "Isoch URBs completed w/error.");
8184 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatErrorIsocPkts, STAMTYPE_COUNTER, "IsocPktsErr", STAMUNIT_OCCURENCES, "Isoch packets completed w/error.");
8185 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatEventsWritten, STAMTYPE_COUNTER, "EventsWritten", STAMUNIT_OCCURENCES, "Event TRBs delivered.");
8186 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatEventsDropped, STAMTYPE_COUNTER, "EventsDropped", STAMUNIT_OCCURENCES, "Event TRBs dropped (HC stopped).");
8187 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatIntrsPending, STAMTYPE_COUNTER, "IntrsPending", STAMUNIT_OCCURENCES, "Requests to set the IP bit.");
8188 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatIntrsSet, STAMTYPE_COUNTER, "IntrsSet", STAMUNIT_OCCURENCES, "Actual interrupts delivered.");
8189 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatIntrsNotSet, STAMTYPE_COUNTER, "IntrsNotSet", STAMUNIT_OCCURENCES, "Interrupts not delivered/disabled.");
8190 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatIntrsCleared, STAMTYPE_COUNTER, "IntrsCleared", STAMUNIT_OCCURENCES, "Interrupts cleared by guest.");
8191 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatTRBsPerCtlUrb, STAMTYPE_COUNTER, "UrbTrbsCtl", STAMUNIT_COUNT, "TRBs per one control URB.");
8192 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatTRBsPerDtaUrb, STAMTYPE_COUNTER, "UrbTrbsDta", STAMUNIT_COUNT, "TRBs per one data (bulk/intr) URB.");
8193 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatTRBsPerIsoUrb, STAMTYPE_COUNTER, "UrbTrbsIso", STAMUNIT_COUNT, "TRBs per one isochronous URB.");
8194 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatUrbSizeCtrl, STAMTYPE_COUNTER, "UrbSizeCtl", STAMUNIT_COUNT, "Size of a control URB in bytes.");
8195 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatUrbSizeData, STAMTYPE_COUNTER, "UrbSizeDta", STAMUNIT_COUNT, "Size of a data (bulk/intr) URB in bytes.");
8196 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatUrbSizeIsoc, STAMTYPE_COUNTER, "UrbSizeIso", STAMUNIT_COUNT, "Size of an isochronous URB in bytes.");
8197
8198 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatRdCaps, STAMTYPE_COUNTER, "Regs/RdCaps", STAMUNIT_COUNT, "");
8199 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatRdCmdRingCtlHi, STAMTYPE_COUNTER, "Regs/RdCmdRingCtlHi", STAMUNIT_COUNT, "");
8200 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatRdCmdRingCtlLo, STAMTYPE_COUNTER, "Regs/RdCmdRingCtlLo", STAMUNIT_COUNT, "");
8201 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatRdConfig, STAMTYPE_COUNTER, "Regs/RdConfig", STAMUNIT_COUNT, "");
8202 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatRdDevCtxBaapHi, STAMTYPE_COUNTER, "Regs/RdDevCtxBaapHi", STAMUNIT_COUNT, "");
8203 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatRdDevCtxBaapLo, STAMTYPE_COUNTER, "Regs/RdDevCtxBaapLo", STAMUNIT_COUNT, "");
8204 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatRdDevNotifyCtrl, STAMTYPE_COUNTER, "Regs/RdDevNotifyCtrl", STAMUNIT_COUNT, "");
8205 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatRdDoorBell, STAMTYPE_COUNTER, "Regs/RdDoorBell", STAMUNIT_COUNT, "");
8206 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatRdEvtRingDeqPtrHi, STAMTYPE_COUNTER, "Regs/RdEvtRingDeqPtrHi", STAMUNIT_COUNT, "");
8207 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatRdEvtRingDeqPtrLo, STAMTYPE_COUNTER, "Regs/RdEvtRingDeqPtrLo", STAMUNIT_COUNT, "");
8208 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatRdEvtRsTblBaseHi, STAMTYPE_COUNTER, "Regs/RdEvtRsTblBaseHi", STAMUNIT_COUNT, "");
8209 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatRdEvtRsTblBaseLo, STAMTYPE_COUNTER, "Regs/RdEvtRsTblBaseLo", STAMUNIT_COUNT, "");
8210 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatRdEvtRstblSize, STAMTYPE_COUNTER, "Regs/RdEvtRstblSize", STAMUNIT_COUNT, "");
8211 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatRdEvtRsvd, STAMTYPE_COUNTER, "Regs/RdEvtRsvd", STAMUNIT_COUNT, "");
8212 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatRdIntrMgmt, STAMTYPE_COUNTER, "Regs/RdIntrMgmt", STAMUNIT_COUNT, "");
8213 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatRdIntrMod, STAMTYPE_COUNTER, "Regs/RdIntrMod", STAMUNIT_COUNT, "");
8214 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatRdMfIndex, STAMTYPE_COUNTER, "Regs/RdMfIndex", STAMUNIT_COUNT, "");
8215 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatRdPageSize, STAMTYPE_COUNTER, "Regs/RdPageSize", STAMUNIT_COUNT, "");
8216 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatRdPortLinkInfo, STAMTYPE_COUNTER, "Regs/RdPortLinkInfo", STAMUNIT_COUNT, "");
8217 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatRdPortPowerMgmt, STAMTYPE_COUNTER, "Regs/RdPortPowerMgmt", STAMUNIT_COUNT, "");
8218 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatRdPortRsvd, STAMTYPE_COUNTER, "Regs/RdPortRsvd", STAMUNIT_COUNT, "");
8219 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatRdPortStatusCtrl, STAMTYPE_COUNTER, "Regs/RdPortStatusCtrl", STAMUNIT_COUNT, "");
8220 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatRdUsbCmd, STAMTYPE_COUNTER, "Regs/RdUsbCmd", STAMUNIT_COUNT, "");
8221 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatRdUsbSts, STAMTYPE_COUNTER, "Regs/RdUsbSts", STAMUNIT_COUNT, "");
8222 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatRdUnknown, STAMTYPE_COUNTER, "Regs/RdUnknown", STAMUNIT_COUNT, "");
8223
8224 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatWrCmdRingCtlHi, STAMTYPE_COUNTER, "Regs/WrCmdRingCtlHi", STAMUNIT_COUNT, "");
8225 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatWrCmdRingCtlLo, STAMTYPE_COUNTER, "Regs/WrCmdRingCtlLo", STAMUNIT_COUNT, "");
8226 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatWrConfig, STAMTYPE_COUNTER, "Regs/WrConfig", STAMUNIT_COUNT, "");
8227 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatWrDevCtxBaapHi, STAMTYPE_COUNTER, "Regs/WrDevCtxBaapHi", STAMUNIT_COUNT, "");
8228 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatWrDevCtxBaapLo, STAMTYPE_COUNTER, "Regs/WrDevCtxBaapLo", STAMUNIT_COUNT, "");
8229 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatWrDevNotifyCtrl, STAMTYPE_COUNTER, "Regs/WrDevNotifyCtrl", STAMUNIT_COUNT, "");
8230 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatWrDoorBell0, STAMTYPE_COUNTER, "Regs/WrDoorBell0", STAMUNIT_COUNT, "");
8231 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatWrDoorBellN, STAMTYPE_COUNTER, "Regs/WrDoorBellN", STAMUNIT_COUNT, "");
8232 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatWrEvtRingDeqPtrHi, STAMTYPE_COUNTER, "Regs/WrEvtRingDeqPtrHi", STAMUNIT_COUNT, "");
8233 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatWrEvtRingDeqPtrLo, STAMTYPE_COUNTER, "Regs/WrEvtRingDeqPtrLo", STAMUNIT_COUNT, "");
8234 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatWrEvtRsTblBaseHi, STAMTYPE_COUNTER, "Regs/WrEvtRsTblBaseHi", STAMUNIT_COUNT, "");
8235 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatWrEvtRsTblBaseLo, STAMTYPE_COUNTER, "Regs/WrEvtRsTblBaseLo", STAMUNIT_COUNT, "");
8236 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatWrEvtRstblSize, STAMTYPE_COUNTER, "Regs/WrEvtRstblSize", STAMUNIT_COUNT, "");
8237 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatWrIntrMgmt, STAMTYPE_COUNTER, "Regs/WrIntrMgmt", STAMUNIT_COUNT, "");
8238 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatWrIntrMod, STAMTYPE_COUNTER, "Regs/WrIntrMod", STAMUNIT_COUNT, "");
8239 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatWrPortPowerMgmt, STAMTYPE_COUNTER, "Regs/WrPortPowerMgmt", STAMUNIT_COUNT, "");
8240 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatWrPortStatusCtrl, STAMTYPE_COUNTER, "Regs/WrPortStatusCtrl", STAMUNIT_COUNT, "");
8241 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatWrUsbCmd, STAMTYPE_COUNTER, "Regs/WrUsbCmd", STAMUNIT_COUNT, "");
8242 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatWrUsbSts, STAMTYPE_COUNTER, "Regs/WrUsbSts", STAMUNIT_COUNT, "");
8243 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatWrUnknown, STAMTYPE_COUNTER, "Regs/WrUnknown", STAMUNIT_COUNT, "");
8244# endif /* VBOX_WITH_STATISTICS */
8245
8246 /*
8247 * Register debugger info callbacks.
8248 */
8249 PDMDevHlpDBGFInfoRegister(pDevIns, "xhci", "xHCI registers.", xhciR3Info);
8250
8251 return VINF_SUCCESS;
8252}
8253
8254#else /* !IN_RING3 */
8255
8256/**
8257 * @callback_method_impl{PDMDEVREGR0,pfnConstruct}
8258 */
8259static DECLCALLBACK(int) xhciRZConstruct(PPDMDEVINS pDevIns)
8260{
8261 PDMDEV_CHECK_VERSIONS_RETURN(pDevIns);
8262 PXHCI pThis = PDMDEVINS_2_DATA(pDevIns, PXHCI);
8263
8264 int rc = PDMDevHlpMmioSetUpContext(pDevIns, pThis->hMmio, xhciMmioWrite, xhciMmioRead, NULL /*pvUser*/);
8265 AssertRCReturn(rc, rc);
8266
8267 return VINF_SUCCESS;
8268}
8269
8270#endif /* !IN_RING3 */
8271
8272/* Without this, g_DeviceXHCI won't be visible outside this module! */
8273extern "C" const PDMDEVREG g_DeviceXHCI;
8274
8275const PDMDEVREG g_DeviceXHCI =
8276{
8277 /* .u32version = */ PDM_DEVREG_VERSION,
8278 /* .uReserved0 = */ 0,
8279 /* .szName = */ "usb-xhci",
8280 /* .fFlags = */ PDM_DEVREG_FLAGS_DEFAULT_BITS | PDM_DEVREG_FLAGS_RZ | PDM_DEVREG_FLAGS_NEW_STYLE,
8281 /* .fClass = */ PDM_DEVREG_CLASS_BUS_USB,
8282 /* .cMaxInstances = */ ~0U,
8283 /* .uSharedVersion = */ 42,
8284 /* .cbInstanceShared = */ sizeof(XHCI),
8285 /* .cbInstanceCC = */ sizeof(XHCICC),
8286 /* .cbInstanceRC = */ sizeof(XHCIRC),
8287 /* .cMaxPciDevices = */ 1,
8288 /* .cMaxMsixVectors = */ 0,
8289 /* .pszDescription = */ "xHCI USB controller.\n",
8290#if defined(IN_RING3)
8291# ifdef VBOX_IN_EXTPACK
8292 /* .pszRCMod = */ "VBoxEhciRC.rc",
8293 /* .pszR0Mod = */ "VBoxEhciR0.r0",
8294# else
8295 /* .pszRCMod = */ "VBoxDDRC.rc",
8296 /* .pszR0Mod = */ "VBoxDDR0.r0",
8297# endif
8298 /* .pfnConstruct = */ xhciR3Construct,
8299 /* .pfnDestruct = */ xhciR3Destruct,
8300 /* .pfnRelocate = */ NULL,
8301 /* .pfnMemSetup = */ NULL,
8302 /* .pfnPowerOn = */ NULL,
8303 /* .pfnReset = */ xhciR3Reset,
8304 /* .pfnSuspend = */ NULL,
8305 /* .pfnResume = */ NULL,
8306 /* .pfnAttach = */ NULL,
8307 /* .pfnDetach = */ NULL,
8308 /* .pfnQueryInterface = */ NULL,
8309 /* .pfnInitComplete = */ NULL,
8310 /* .pfnPowerOff = */ NULL,
8311 /* .pfnSoftReset = */ NULL,
8312 /* .pfnReserved0 = */ NULL,
8313 /* .pfnReserved1 = */ NULL,
8314 /* .pfnReserved2 = */ NULL,
8315 /* .pfnReserved3 = */ NULL,
8316 /* .pfnReserved4 = */ NULL,
8317 /* .pfnReserved5 = */ NULL,
8318 /* .pfnReserved6 = */ NULL,
8319 /* .pfnReserved7 = */ NULL,
8320#elif defined(IN_RING0)
8321 /* .pfnEarlyConstruct = */ NULL,
8322 /* .pfnConstruct = */ xhciRZConstruct,
8323 /* .pfnDestruct = */ NULL,
8324 /* .pfnFinalDestruct = */ NULL,
8325 /* .pfnRequest = */ NULL,
8326 /* .pfnReserved0 = */ NULL,
8327 /* .pfnReserved1 = */ NULL,
8328 /* .pfnReserved2 = */ NULL,
8329 /* .pfnReserved3 = */ NULL,
8330 /* .pfnReserved4 = */ NULL,
8331 /* .pfnReserved5 = */ NULL,
8332 /* .pfnReserved6 = */ NULL,
8333 /* .pfnReserved7 = */ NULL,
8334#elif defined(IN_RC)
8335 /* .pfnConstruct = */ xhciRZConstruct,
8336 /* .pfnReserved0 = */ NULL,
8337 /* .pfnReserved1 = */ NULL,
8338 /* .pfnReserved2 = */ NULL,
8339 /* .pfnReserved3 = */ NULL,
8340 /* .pfnReserved4 = */ NULL,
8341 /* .pfnReserved5 = */ NULL,
8342 /* .pfnReserved6 = */ NULL,
8343 /* .pfnReserved7 = */ NULL,
8344#else
8345# error "Not in IN_RING3, IN_RING0 or IN_RC!"
8346#endif
8347 /* .u32VersionEnd = */ PDM_DEVREG_VERSION
8348};
8349
8350#endif /* !VBOX_DEVICE_STRUCT_TESTCASE */
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette