VirtualBox

source: vbox/trunk/src/VBox/Devices/USB/DevOHCI.cpp@ 68080

Last change on this file since 68080 was 67835, checked in by vboxsync, 7 years ago

DevOHCI: warning

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 218.3 KB
Line 
1/* $Id: DevOHCI.cpp 67835 2017-07-06 15:32:14Z vboxsync $ */
2/** @file
3 * DevOHCI - Open Host Controller Interface for USB.
4 */
5
6/*
7 * Copyright (C) 2006-2016 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18/** @page pg_dev_ohci OHCI - Open Host Controller Interface Emulation.
19 *
20 * This component implements an OHCI USB controller. It is split roughly in
21 * to two main parts, the first part implements the register level
22 * specification of USB OHCI and the second part maintains the root hub (which
23 * is an integrated component of the device).
24 *
25 * The OHCI registers are used for the usual stuff like enabling and disabling
26 * interrupts. Since the USB time is divided in to 1ms frames and various
27 * interrupts may need to be triggered at frame boundary time, a timer-based
28 * approach was taken. Whenever the bus is enabled ohci->eof_timer will be set.
29 *
30 * The actual USB transfers are stored in main memory (along with endpoint and
31 * transfer descriptors). The ED's for all the control and bulk endpoints are
32 * found by consulting the HcControlHeadED and HcBulkHeadED registers
33 * respectively. Interrupt ED's are different, they are found by looking
34 * in the HCCA (another communication area in main memory).
35 *
36 * At the start of every frame (in function ohci_sof) we traverse all enabled
37 * ED lists and queue up as many transfers as possible. No attention is paid
38 * to control/bulk service ratios or bandwidth requirements since our USB
39 * could conceivably contain a dozen high speed busses so this would
40 * artificially limit the performance.
41 *
42 * Once we have a transfer ready to go (in function ohciServiceTd) we
43 * allocate an URB on the stack, fill in all the relevant fields and submit
44 * it using the VUSBIRhSubmitUrb function. The roothub device and the virtual
45 * USB core code (vusb.c) coordinates everything else from this point onwards.
46 *
47 * When the URB has been successfully handed to the lower level driver, our
48 * prepare callback gets called and we can remove the TD from the ED transfer
49 * list. This stops us queueing it twice while it completes.
50 * bird: no, we don't remove it because that confuses the guest! (=> crashes)
51 *
52 * Completed URBs are reaped at the end of every frame (in function
53 * ohci_frame_boundary). Our completion routine makes use of the ED and TD
54 * fields in the URB to store the physical addresses of the descriptors so
55 * that they may be modified in the roothub callbacks. Our completion
56 * routine (ohciRhXferComplete) carries out a number of tasks:
57 * -# Retires the TD associated with the transfer, setting the
58 * relevant error code etc.
59 * -# Updates done-queue interrupt timer and potentially causes
60 * a writeback of the done-queue.
61 * -# If the transfer was device-to-host, we copy the data in to
62 * the host memory.
63 *
64 * As for error handling OHCI allows for 3 retries before failing a transfer,
65 * an error count is stored in each transfer descriptor. A halt flag is also
66 * stored in the transfer descriptor. That allows for ED's to be disabled
67 * without stopping the bus and de-queuing them.
68 *
69 * When the bus is started and stopped we call VUSBIDevPowerOn/Off() on our
70 * roothub to indicate it's powering up and powering down. Whenever we power
71 * down, the USB core makes sure to synchronously complete all outstanding
72 * requests so that the OHCI is never seen in an inconsistent state by the
73 * guest OS (Transfers are not meant to be unlinked until they've actually
74 * completed, but we can't do that unless we work synchronously, so we just
75 * have to fake it).
76 * bird: we do work synchronously now, anything causes guest crashes.
77 */
78
79
80/*********************************************************************************************************************************
81* Header Files *
82*********************************************************************************************************************************/
83#define LOG_GROUP LOG_GROUP_DEV_OHCI
84#include <VBox/pci.h>
85#include <VBox/vmm/pdm.h>
86#include <VBox/vmm/mm.h>
87#include <VBox/err.h>
88#include <VBox/log.h>
89#include <iprt/assert.h>
90#include <iprt/string.h>
91#include <iprt/asm.h>
92#include <iprt/asm-math.h>
93#include <iprt/semaphore.h>
94#include <iprt/critsect.h>
95#include <iprt/param.h>
96#ifdef IN_RING3
97# include <iprt/alloca.h>
98# include <iprt/mem.h>
99# include <iprt/thread.h>
100# include <iprt/uuid.h>
101#endif
102#include <VBox/vusb.h>
103#include "VBoxDD.h"
104
105
106#define VBOX_WITH_OHCI_PHYS_READ_CACHE
107//#define VBOX_WITH_OHCI_PHYS_READ_STATS
108
109
110/*********************************************************************************************************************************
111* Structures and Typedefs *
112*********************************************************************************************************************************/
113/** The saved state version. */
114#define OHCI_SAVED_STATE_VERSION 5
115// The saved state with support of 8 ports
116#define OHCI_SAVED_STATE_VERSION_8PORTS 4
117/** The saved state version used in 3.0 and earlier.
118 *
119 * @remarks Because of the SSMR3MemPut/Get laziness we ended up with an
120 * accidental format change between 2.0 and 2.1 that didn't get its own
121 * version number. It is therefore not possible to restore states from
122 * 2.0 and earlier with 2.1 and later. */
123#define OHCI_SAVED_STATE_VERSION_MEM_HELL 3
124
125
126/** Maximum supported number of Downstream Ports on the root hub. 15 ports
127 * is the maximum defined by the OHCI spec.
128 * If you change this you need to add more status register words to the 'opreg'
129 * array.
130 */
131#define OHCI_NDP_MAX 15
132
133/** Default NDP, chosen to be compatible with everything. */
134#define OHCI_NDP_DEFAULT 12
135
136/* Macro to query the number of currently configured ports. */
137#define OHCI_NDP_CFG(pohci) ((pohci)->RootHub.desc_a & OHCI_RHA_NDP)
138
139/** Pointer to OHCI device data. */
140typedef struct OHCI *POHCI;
141/** Read-only pointer to the OHCI device data. */
142typedef struct OHCI const *PCOHCI;
143
144#ifndef VBOX_DEVICE_STRUCT_TESTCASE
145/**
146 * Host controller transfer descriptor data.
147 */
148typedef struct VUSBURBHCITDINT
149{
150 /** Type of TD. */
151 uint32_t TdType;
152 /** The address of the */
153 RTGCPHYS32 TdAddr;
154 /** A copy of the TD. */
155 uint32_t TdCopy[16];
156} VUSBURBHCITDINT;
157
158/**
159 * The host controller data associated with each URB.
160 */
161typedef struct VUSBURBHCIINT
162{
163 /** The endpoint descriptor address. */
164 RTGCPHYS32 EdAddr;
165 /** Number of Tds in the array. */
166 uint32_t cTds;
167 /** When this URB was created.
168 * (Used for isochronous frames and for logging.) */
169 uint32_t u32FrameNo;
170 /** Flag indicating that the TDs have been unlinked. */
171 bool fUnlinked;
172} VUSBURBHCIINT;
173#endif
174
175/**
176 * An OHCI root hub port.
177 */
178typedef struct OHCIHUBPORT
179{
180 /** The port register. */
181 uint32_t fReg;
182#if HC_ARCH_BITS == 64
183 uint32_t Alignment0; /**< Align the pointer correctly. */
184#endif
185 /** The device attached to the port. */
186 R3PTRTYPE(PVUSBIDEVICE) pDev;
187} OHCIHUBPORT;
188#if HC_ARCH_BITS == 64
189AssertCompile(sizeof(OHCIHUBPORT) == 16); /* saved state */
190#endif
191/** Pointer to an OHCI hub port. */
192typedef OHCIHUBPORT *POHCIHUBPORT;
193
194/**
195 * The OHCI root hub.
196 *
197 * @implements PDMIBASE
198 * @implements VUSBIROOTHUBPORT
199 * @implements PDMILEDPORTS
200 */
201typedef struct ohci_roothub
202{
203 /** Pointer to the base interface of the VUSB RootHub. */
204 R3PTRTYPE(PPDMIBASE) pIBase;
205 /** Pointer to the connector interface of the VUSB RootHub. */
206 R3PTRTYPE(PVUSBIROOTHUBCONNECTOR) pIRhConn;
207 /** Pointer to the device interface of the VUSB RootHub. */
208 R3PTRTYPE(PVUSBIDEVICE) pIDev;
209 /** The base interface exposed to the roothub driver. */
210 PDMIBASE IBase;
211 /** The roothub port interface exposed to the roothub driver. */
212 VUSBIROOTHUBPORT IRhPort;
213
214 /** The LED. */
215 PDMLED Led;
216 /** The LED ports. */
217 PDMILEDPORTS ILeds;
218 /** Partner of ILeds. */
219 R3PTRTYPE(PPDMILEDCONNECTORS) pLedsConnector;
220
221 uint32_t status;
222 uint32_t desc_a;
223 uint32_t desc_b;
224#if HC_ARCH_BITS == 64
225 uint32_t Alignment0; /**< Align aPorts on a 8 byte boundary. */
226#endif
227 OHCIHUBPORT aPorts[OHCI_NDP_MAX];
228 R3PTRTYPE(POHCI) pOhci;
229} OHCIROOTHUB;
230/** Pointer to the OHCI root hub. */
231typedef OHCIROOTHUB *POHCIROOTHUB;
232
233
234/**
235 * Data used for reattaching devices on a state load.
236 */
237typedef struct ohci_load {
238 /** Timer used once after state load to inform the guest about new devices.
239 * We do this to be sure the guest get any disconnect / reconnect on the
240 * same port. */
241 PTMTIMERR3 pTimer;
242 /** Number of detached devices. */
243 unsigned cDevs;
244 /** Array of devices which were detached. */
245 PVUSBIDEVICE apDevs[OHCI_NDP_MAX];
246} OHCILOAD;
247/** Pointer to an OHCILOAD structure. */
248typedef OHCILOAD *POHCILOAD;
249
250#ifdef VBOX_WITH_OHCI_PHYS_READ_CACHE
251typedef struct OHCIPAGECACHE
252{
253 /** Last read physical page address. */
254 RTGCPHYS GCPhysReadCacheAddr;
255 /** Copy of last read physical page. */
256 uint8_t au8PhysReadCache[PAGE_SIZE];
257} OHCIPAGECACHE, *POHCIPAGECACHE;
258#endif
259
260/**
261 * OHCI device data.
262 */
263typedef struct OHCI
264{
265 /** The PCI device. */
266 PDMPCIDEV PciDev;
267
268 /** Pointer to the device instance - R3 ptr. */
269 PPDMDEVINSR3 pDevInsR3;
270 /** The End-Of-Frame timer - R3 Ptr. */
271 PTMTIMERR3 pEndOfFrameTimerR3;
272
273 /** Pointer to the device instance - R0 ptr */
274 PPDMDEVINSR0 pDevInsR0;
275 /** The End-Of-Frame timer - R0 Ptr. */
276 PTMTIMERR0 pEndOfFrameTimerR0;
277
278 /** Pointer to the device instance - RC ptr. */
279 PPDMDEVINSRC pDevInsRC;
280 /** The End-Of-Frame timer - RC Ptr. */
281 PTMTIMERRC pEndOfFrameTimerRC;
282
283 /** Start of current frame. */
284 uint64_t SofTime;
285 /* done queue interrupt counter */
286 uint32_t dqic : 3;
287 /** frame number overflow. */
288 uint32_t fno : 1;
289 /** Address of the MMIO region assigned by PCI. */
290 RTGCPHYS32 MMIOBase;
291
292 /* Root hub device */
293 OHCIROOTHUB RootHub;
294
295 /* OHCI registers */
296
297 /** @name Control partition
298 * @{ */
299 /** HcControl. */
300 uint32_t ctl;
301 /** HcCommandStatus. */
302 uint32_t status;
303 /** HcInterruptStatus. */
304 uint32_t intr_status;
305 /** HcInterruptEnabled. */
306 uint32_t intr;
307 /** @} */
308
309 /** @name Memory pointer partition
310 * @{ */
311 /** HcHCCA. */
312 uint32_t hcca;
313 /** HcPeriodCurrentEd. */
314 uint32_t per_cur;
315 /** HcControlCurrentED. */
316 uint32_t ctrl_cur;
317 /** HcControlHeadED. */
318 uint32_t ctrl_head;
319 /** HcBlockCurrendED. */
320 uint32_t bulk_cur;
321 /** HcBlockHeadED. */
322 uint32_t bulk_head;
323 /** HcDoneHead. */
324 uint32_t done;
325 /** @} */
326
327 /** @name Frame counter partition
328 * @{ */
329 /** HcFmInterval.FSMPS - FSLargestDataPacket */
330 uint32_t fsmps : 15;
331 /** HcFmInterval.FIT - FrameItervalToggle */
332 uint32_t fit : 1;
333 /** HcFmInterval.FI - FrameInterval */
334 uint32_t fi : 14;
335 /** HcFmRemaining.FRT - toggle bit. */
336 uint32_t frt : 1;
337 /** HcFmNumber.
338 * @remark The register size is 16-bit, but for debugging and performance
339 * reasons we maintain a 32-bit counter. */
340 uint32_t HcFmNumber;
341 /** HcPeriodicStart */
342 uint32_t pstart;
343 /** @} */
344
345 /** The number of virtual time ticks per frame. */
346 uint64_t cTicksPerFrame;
347 /** The number of virtual time ticks per USB bus tick. */
348 uint64_t cTicksPerUsbTick;
349
350 /** Number of in-flight TDs. */
351 unsigned cInFlight;
352 unsigned Alignment0; /**< Align aInFlight on a 8 byte boundary. */
353 /** Array of in-flight TDs. */
354 struct ohci_td_in_flight
355 {
356 /** Address of the transport descriptor. */
357 uint32_t GCPhysTD;
358 /** Flag indicating an inactive (not-linked) URB. */
359 bool fInactive;
360 /** Pointer to the URB. */
361 R3PTRTYPE(PVUSBURB) pUrb;
362 } aInFlight[257];
363
364#if HC_ARCH_BITS == 32
365 uint32_t Alignment1;
366#endif
367
368 /** Number of in-done-queue TDs. */
369 unsigned cInDoneQueue;
370 /** Array of in-done-queue TDs. */
371 struct ohci_td_in_done_queue
372 {
373 /** Address of the transport descriptor. */
374 uint32_t GCPhysTD;
375 } aInDoneQueue[64];
376 /** When the tail of the done queue was added.
377 * Used to calculate the age of the done queue. */
378 uint32_t u32FmDoneQueueTail;
379#if R3_ARCH_BITS == 32
380 /** Align pLoad, the stats and the struct size correctly. */
381 uint32_t Alignment2;
382#endif
383 /** Pointer to state load data. */
384 R3PTRTYPE(POHCILOAD) pLoad;
385
386 /** Detected canceled isochronous URBs. */
387 STAMCOUNTER StatCanceledIsocUrbs;
388 /** Detected canceled general URBs. */
389 STAMCOUNTER StatCanceledGenUrbs;
390 /** Dropped URBs (endpoint halted, or URB canceled). */
391 STAMCOUNTER StatDroppedUrbs;
392 /** Profiling ohciFrameBoundaryTimer. */
393 STAMPROFILE StatTimer;
394
395 /** This member and all the following are not part of saved state. */
396 uint64_t SavedStateEnd;
397
398 /** VM timer frequency used for frame timer calculations. */
399 uint64_t u64TimerHz;
400 /** Idle detection flag; must be cleared at start of frame */
401 bool fIdle;
402 /** A flag indicating that the bulk list may have in-flight URBs. */
403 bool fBulkNeedsCleaning;
404
405 /** Whether RC/R0 is enabled. */
406 bool fRZEnabled;
407
408 uint32_t Alignment3; /**< Align size on a 8 byte boundary. */
409
410 /** Critical section synchronising interrupt handling. */
411 PDMCRITSECT CsIrq;
412 /** Critical section to synchronize the framer and URB completion handler. */
413 RTCRITSECT CritSect;
414#ifdef VBOX_WITH_OHCI_PHYS_READ_CACHE
415 /** Last read physical page for caching ED reads in the framer thread. */
416 R3PTRTYPE(POHCIPAGECACHE) pCacheED;
417 /** Last read physical page for caching TD reads in the framer thread. */
418 R3PTRTYPE(POHCIPAGECACHE) pCacheTD;
419#endif
420
421} OHCI;
422
423/* Standard OHCI bus speed */
424#define OHCI_DEFAULT_TIMER_FREQ 1000
425
426/* Host Controller Communications Area */
427#define OHCI_HCCA_NUM_INTR 32
428#define OHCI_HCCA_OFS (OHCI_HCCA_NUM_INTR * sizeof(uint32_t))
429struct ohci_hcca
430{
431 uint16_t frame;
432 uint16_t pad;
433 uint32_t done;
434};
435AssertCompileSize(ohci_hcca, 8);
436
437/** @name OHCI Endpoint Descriptor
438 * @{ */
439
440#define ED_PTR_MASK (~(uint32_t)0xf)
441#define ED_HWINFO_MPS 0x07ff0000
442#define ED_HWINFO_ISO RT_BIT(15)
443#define ED_HWINFO_SKIP RT_BIT(14)
444#define ED_HWINFO_LOWSPEED RT_BIT(13)
445#define ED_HWINFO_IN RT_BIT(12)
446#define ED_HWINFO_OUT RT_BIT(11)
447#define ED_HWINFO_DIR (RT_BIT(11) | RT_BIT(12))
448#define ED_HWINFO_ENDPOINT 0x780 /* 4 bits */
449#define ED_HWINFO_ENDPOINT_SHIFT 7
450#define ED_HWINFO_FUNCTION 0x7f /* 7 bits */
451#define ED_HEAD_CARRY RT_BIT(1)
452#define ED_HEAD_HALTED RT_BIT(0)
453
454/**
455 * OHCI Endpoint Descriptor.
456 */
457typedef struct OHCIED
458{
459 /** Flags and stuff. */
460 uint32_t hwinfo;
461 /** TailP - TD Queue Tail pointer. Bits 0-3 ignored / preserved. */
462 uint32_t TailP;
463 /** HeadP - TD Queue head pointer. Bit 0 - Halted, Bit 1 - toggleCarry. Bit 2&3 - 0. */
464 uint32_t HeadP;
465 /** NextED - Next Endpoint Descriptor. Bits 0-3 ignored / preserved. */
466 uint32_t NextED;
467} OHCIED, *POHCIED;
468typedef const OHCIED *PCOHCIED;
469/** @} */
470AssertCompileSize(OHCIED, 16);
471
472
473/** @name Completion Codes
474 * @{ */
475#define OHCI_CC_NO_ERROR (UINT32_C(0x00) << 28)
476#define OHCI_CC_CRC (UINT32_C(0x01) << 28)
477#define OHCI_CC_STALL (UINT32_C(0x04) << 28)
478#define OHCI_CC_DEVICE_NOT_RESPONDING (UINT32_C(0x05) << 28)
479#define OHCI_CC_DNR OHCI_CC_DEVICE_NOT_RESPONDING
480#define OHCI_CC_PID_CHECK_FAILURE (UINT32_C(0x06) << 28)
481#define OHCI_CC_UNEXPECTED_PID (UINT32_C(0x07) << 28)
482#define OHCI_CC_DATA_OVERRUN (UINT32_C(0x08) << 28)
483#define OHCI_CC_DATA_UNDERRUN (UINT32_C(0x09) << 28)
484/* 0x0a..0x0b - reserved */
485#define OHCI_CC_BUFFER_OVERRUN (UINT32_C(0x0c) << 28)
486#define OHCI_CC_BUFFER_UNDERRUN (UINT32_C(0x0d) << 28)
487#define OHCI_CC_NOT_ACCESSED_0 (UINT32_C(0x0e) << 28)
488#define OHCI_CC_NOT_ACCESSED_1 (UINT32_C(0x0f) << 28)
489/** @} */
490
491
492/** @name OHCI General transfer descriptor
493 * @{ */
494
495/** Error count (EC) shift. */
496#define TD_ERRORS_SHIFT 26
497/** Error count max. (One greater than what the EC field can hold.) */
498#define TD_ERRORS_MAX 4
499
500/** CC - Condition code mask. */
501#define TD_HWINFO_CC (UINT32_C(0xf0000000))
502#define TD_HWINFO_CC_SHIFT 28
503/** EC - Error count. */
504#define TD_HWINFO_ERRORS (RT_BIT(26) | RT_BIT(27))
505/** T - Data toggle. */
506#define TD_HWINFO_TOGGLE (RT_BIT(24) | RT_BIT(25))
507#define TD_HWINFO_TOGGLE_HI (RT_BIT(25))
508#define TD_HWINFO_TOGGLE_LO (RT_BIT(24))
509/** DI - Delay interrupt. */
510#define TD_HWINFO_DI (RT_BIT(21) | RT_BIT(22) | RT_BIT(23))
511#define TD_HWINFO_IN (RT_BIT(20))
512#define TD_HWINFO_OUT (RT_BIT(19))
513/** DP - Direction / PID. */
514#define TD_HWINFO_DIR (RT_BIT(19) | RT_BIT(20))
515/** R - Buffer rounding. */
516#define TD_HWINFO_ROUNDING (RT_BIT(18))
517/** Bits that are reserved / unknown. */
518#define TD_HWINFO_UNKNOWN_MASK (UINT32_C(0x0003ffff))
519
520/** SETUP - to endpoint. */
521#define OHCI_TD_DIR_SETUP 0x0
522/** OUT - to endpoint. */
523#define OHCI_TD_DIR_OUT 0x1
524/** IN - from endpoint. */
525#define OHCI_TD_DIR_IN 0x2
526/** Reserved. */
527#define OHCI_TD_DIR_RESERVED 0x3
528
529/**
530 * OHCI general transfer descriptor
531 */
532typedef struct OHCITD
533{
534 uint32_t hwinfo;
535 /** CBP - Current Buffer Pointer. (32-bit physical address) */
536 uint32_t cbp;
537 /** NextTD - Link to the next transfer descriptor. (32-bit physical address, dword aligned) */
538 uint32_t NextTD;
539 /** BE - Buffer End (inclusive). (32-bit physical address) */
540 uint32_t be;
541} OHCITD, *POHCITD;
542typedef const OHCITD *PCOHCITD;
543/** @} */
544AssertCompileSize(OHCIED, 16);
545
546
547/** @name OHCI isochronous transfer descriptor.
548 * @{ */
549/** SF - Start frame number. */
550#define ITD_HWINFO_SF 0xffff
551/** DI - Delay interrupt. (TD_HWINFO_DI) */
552#define ITD_HWINFO_DI (RT_BIT(21) | RT_BIT(22) | RT_BIT(23))
553#define ITD_HWINFO_DI_SHIFT 21
554/** FC - Frame count. */
555#define ITD_HWINFO_FC (RT_BIT(24) | RT_BIT(25) | RT_BIT(26))
556#define ITD_HWINFO_FC_SHIFT 24
557/** CC - Condition code mask. (=TD_HWINFO_CC) */
558#define ITD_HWINFO_CC UINT32_C(0xf0000000)
559#define ITD_HWINFO_CC_SHIFT 28
560/** The buffer page 0 mask (lower 12 bits are ignored). */
561#define ITD_BP0_MASK UINT32_C(0xfffff000)
562
563#define ITD_NUM_PSW 8
564/** OFFSET - offset of the package into the buffer page.
565 * (Only valid when CC set to Not Accessed.)
566 *
567 * Note that the top bit of the OFFSET field is overlapping with the
568 * first bit in the CC field. This is ok because both 0xf and 0xe are
569 * defined as "Not Accessed".
570 */
571#define ITD_PSW_OFFSET 0x1fff
572/** SIZE field mask for IN bound transfers.
573 * (Only valid when CC isn't Not Accessed.)*/
574#define ITD_PSW_SIZE 0x07ff
575/** CC field mask.
576 * USed to indicate the format of SIZE (Not Accessed -> OFFSET). */
577#define ITD_PSW_CC 0xf000
578#define ITD_PSW_CC_SHIFT 12
579
580/**
581 * OHCI isochronous transfer descriptor.
582 */
583typedef struct OHCIITD
584{
585 uint32_t HwInfo;
586 /** BP0 - Buffer Page 0. The lower 12 bits are ignored. */
587 uint32_t BP0;
588 /** NextTD - Link to the next transfer descriptor. (32-bit physical address, dword aligned) */
589 uint32_t NextTD;
590 /** BE - Buffer End (inclusive). (32-bit physical address) */
591 uint32_t BE;
592 /** (OffsetN/)PSWN - package status word array (0..7).
593 * The format varies depending on whether the package has been completed or not. */
594 uint16_t aPSW[ITD_NUM_PSW];
595} OHCIITD, *POHCIITD;
596typedef const OHCIITD *PCOHCIITD;
597/** @} */
598AssertCompileSize(OHCIITD, 32);
599
600/**
601 * OHCI register operator.
602 */
603typedef struct ohci_opreg
604{
605 const char *pszName;
606 int (*pfnRead )(PCOHCI pThis, uint32_t iReg, uint32_t *pu32Value);
607 int (*pfnWrite)(POHCI pThis, uint32_t iReg, uint32_t u32Value);
608} OHCIOPREG;
609
610
611/* OHCI Local stuff */
612#define OHCI_CTL_CBSR ((1<<0)|(1<<1))
613#define OHCI_CTL_PLE (1<<2)
614#define OHCI_CTL_IE (1<<3)
615#define OHCI_CTL_CLE (1<<4)
616#define OHCI_CTL_BLE (1<<5)
617#define OHCI_CTL_HCFS ((1<<6)|(1<<7))
618#define OHCI_USB_RESET 0x00
619#define OHCI_USB_RESUME 0x40
620#define OHCI_USB_OPERATIONAL 0x80
621#define OHCI_USB_SUSPEND 0xc0
622#define OHCI_CTL_IR (1<<8)
623#define OHCI_CTL_RWC (1<<9)
624#define OHCI_CTL_RWE (1<<10)
625
626#define OHCI_STATUS_HCR (1<<0)
627#define OHCI_STATUS_CLF (1<<1)
628#define OHCI_STATUS_BLF (1<<2)
629#define OHCI_STATUS_OCR (1<<3)
630#define OHCI_STATUS_SOC ((1<<6)|(1<<7))
631
632/** @name Interrupt Status and Enabled/Disabled Flags
633 * @{ */
634/** SO - Scheduling overrun. */
635#define OHCI_INTR_SCHEDULEING_OVERRUN RT_BIT(0)
636/** WDH - HcDoneHead writeback. */
637#define OHCI_INTR_WRITE_DONE_HEAD RT_BIT(1)
638/** SF - Start of frame. */
639#define OHCI_INTR_START_OF_FRAME RT_BIT(2)
640/** RD - Resume detect. */
641#define OHCI_INTR_RESUME_DETECT RT_BIT(3)
642/** UE - Unrecoverable error. */
643#define OHCI_INTR_UNRECOVERABLE_ERROR RT_BIT(4)
644/** FNO - Frame number overflow. */
645#define OHCI_INTR_FRAMENUMBER_OVERFLOW RT_BIT(5)
646/** RHSC- Root hub status change. */
647#define OHCI_INTR_ROOT_HUB_STATUS_CHANGE RT_BIT(6)
648/** OC - Ownership change. */
649#define OHCI_INTR_OWNERSHIP_CHANGE RT_BIT(30)
650/** MIE - Master interrupt enable. */
651#define OHCI_INTR_MASTER_INTERRUPT_ENABLED RT_BIT(31)
652/** @} */
653
654#define OHCI_HCCA_SIZE 0x100
655#define OHCI_HCCA_MASK UINT32_C(0xffffff00)
656
657#define OHCI_FMI_FI UINT32_C(0x00003fff)
658#define OHCI_FMI_FSMPS UINT32_C(0x7fff0000)
659#define OHCI_FMI_FSMPS_SHIFT 16
660#define OHCI_FMI_FIT UINT32_C(0x80000000)
661#define OHCI_FMI_FIT_SHIFT 31
662
663#define OHCI_FR_RT RT_BIT_32(31)
664
665#define OHCI_LS_THRESH 0x628
666
667#define OHCI_RHA_NDP (0xff)
668#define OHCI_RHA_PSM RT_BIT_32(8)
669#define OHCI_RHA_NPS RT_BIT_32(9)
670#define OHCI_RHA_DT RT_BIT_32(10)
671#define OHCI_RHA_OCPM RT_BIT_32(11)
672#define OHCI_RHA_NOCP RT_BIT_32(12)
673#define OHCI_RHA_POTPGP UINT32_C(0xff000000)
674
675#define OHCI_RHS_LPS RT_BIT_32(0)
676#define OHCI_RHS_OCI RT_BIT_32(1)
677#define OHCI_RHS_DRWE RT_BIT_32(15)
678#define OHCI_RHS_LPSC RT_BIT_32(16)
679#define OHCI_RHS_OCIC RT_BIT_32(17)
680#define OHCI_RHS_CRWE RT_BIT_32(31)
681
682/** @name HcRhPortStatus[n] - RH Port Status register (read).
683 * @{ */
684/** CCS - CurrentConnectionStatus - 0 = no device, 1 = device. */
685#define OHCI_PORT_CCS RT_BIT(0)
686/** PES - PortEnableStatus. */
687#define OHCI_PORT_PES RT_BIT(1)
688/** PSS - PortSuspendStatus */
689#define OHCI_PORT_PSS RT_BIT(2)
690/** POCI- PortOverCurrentIndicator. */
691#define OHCI_PORT_POCI RT_BIT(3)
692/** PRS - PortResetStatus */
693#define OHCI_PORT_PRS RT_BIT(4)
694/** PPS - PortPowerStatus */
695#define OHCI_PORT_PPS RT_BIT(8)
696/** LSDA - LowSpeedDeviceAttached */
697#define OHCI_PORT_LSDA RT_BIT(9)
698/** CSC - ConnectStatusChange */
699#define OHCI_PORT_CSC RT_BIT(16)
700/** PESC - PortEnableStatusChange */
701#define OHCI_PORT_PESC RT_BIT(17)
702/** PSSC - PortSuspendStatusChange */
703#define OHCI_PORT_PSSC RT_BIT(18)
704/** OCIC - OverCurrentIndicatorChange */
705#define OHCI_PORT_OCIC RT_BIT(19)
706/** PRSC - PortResetStatusChange */
707#define OHCI_PORT_PRSC RT_BIT(20)
708/** @} */
709
710
711/** @name HcRhPortStatus[n] - Root Hub Port Status Registers - read.
712 * @{ */
713/** CCS - CurrentConnectStatus - 0 = no device, 1 = device. */
714#define OHCI_PORT_R_CURRENT_CONNECT_STATUS RT_BIT(0)
715/** PES - PortEnableStatus. */
716#define OHCI_PORT_R_ENABLE_STATUS RT_BIT(1)
717/** PSS - PortSuspendStatus */
718#define OHCI_PORT_R_SUSPEND_STATUS RT_BIT(2)
719/** POCI- PortOverCurrentIndicator. */
720#define OHCI_PORT_R_OVER_CURRENT_INDICATOR RT_BIT(3)
721/** PRS - PortResetStatus */
722#define OHCI_PORT_R_RESET_STATUS RT_BIT(4)
723/** PPS - PortPowerStatus */
724#define OHCI_PORT_R_POWER_STATUS RT_BIT(8)
725/** LSDA - LowSpeedDeviceAttached */
726#define OHCI_PORT_R_LOW_SPEED_DEVICE_ATTACHED RT_BIT(9)
727/** CSC - ConnectStatusChange */
728#define OHCI_PORT_R_CONNECT_STATUS_CHANGE RT_BIT(16)
729/** PESC - PortEnableStatusChange */
730#define OHCI_PORT_R_ENABLE_STATUS_CHANGE RT_BIT(17)
731/** PSSC - PortSuspendStatusChange */
732#define OHCI_PORT_R_SUSPEND_STATUS_CHANGE RT_BIT(18)
733/** OCIC - OverCurrentIndicatorChange */
734#define OHCI_PORT_R_OVER_CURRENT_INDICATOR_CHANGE RT_BIT(19)
735/** PRSC - PortResetStatusChange */
736#define OHCI_PORT_R_RESET_STATUS_CHANGE RT_BIT(20)
737/** @} */
738
739/** @name HcRhPortStatus[n] - Root Hub Port Status Registers - write.
740 * @{ */
741/** CCS - ClearPortEnable. */
742#define OHCI_PORT_W_CLEAR_ENABLE RT_BIT(0)
743/** PES - SetPortEnable. */
744#define OHCI_PORT_W_SET_ENABLE RT_BIT(1)
745/** PSS - SetPortSuspend */
746#define OHCI_PORT_W_SET_SUSPEND RT_BIT(2)
747/** POCI- ClearSuspendStatus. */
748#define OHCI_PORT_W_CLEAR_SUSPEND_STATUS RT_BIT(3)
749/** PRS - SetPortReset */
750#define OHCI_PORT_W_SET_RESET RT_BIT(4)
751/** PPS - SetPortPower */
752#define OHCI_PORT_W_SET_POWER RT_BIT(8)
753/** LSDA - ClearPortPower */
754#define OHCI_PORT_W_CLEAR_POWER RT_BIT(9)
755/** CSC - ClearConnectStatusChange */
756#define OHCI_PORT_W_CLEAR_CSC RT_BIT(16)
757/** PESC - PortEnableStatusChange */
758#define OHCI_PORT_W_CLEAR_PESC RT_BIT(17)
759/** PSSC - PortSuspendStatusChange */
760#define OHCI_PORT_W_CLEAR_PSSC RT_BIT(18)
761/** OCIC - OverCurrentIndicatorChange */
762#define OHCI_PORT_W_CLEAR_OCIC RT_BIT(19)
763/** PRSC - PortResetStatusChange */
764#define OHCI_PORT_W_CLEAR_PRSC RT_BIT(20)
765/** The mask of bit which are used to clear themselves. */
766#define OHCI_PORT_W_CLEAR_CHANGE_MASK ( OHCI_PORT_W_CLEAR_CSC | OHCI_PORT_W_CLEAR_PESC | OHCI_PORT_W_CLEAR_PSSC \
767 | OHCI_PORT_W_CLEAR_OCIC | OHCI_PORT_W_CLEAR_PRSC)
768/** @} */
769
770
771#ifndef VBOX_DEVICE_STRUCT_TESTCASE
772
773#ifdef VBOX_WITH_OHCI_PHYS_READ_STATS
774/*
775 * Explain
776 */
777typedef struct OHCIDESCREADSTATS
778{
779 uint32_t cReads;
780 uint32_t cPageChange;
781 uint32_t cMinReadsPerPage;
782 uint32_t cMaxReadsPerPage;
783
784 uint32_t cReadsLastPage;
785 uint32_t u32LastPageAddr;
786} OHCIDESCREADSTATS;
787typedef OHCIDESCREADSTATS *POHCIDESCREADSTATS;
788
789typedef struct OHCIPHYSREADSTATS
790{
791 OHCIDESCREADSTATS ed;
792 OHCIDESCREADSTATS td;
793 OHCIDESCREADSTATS all;
794
795 uint32_t cCrossReads;
796 uint32_t cCacheReads;
797 uint32_t cPageReads;
798} OHCIPHYSREADSTATS;
799typedef OHCIPHYSREADSTATS *POHCIPHYSREADSTATS;
800typedef OHCIPHYSREADSTATS const *PCOHCIPHYSREADSTATS;
801#endif /* VBOX_WITH_OHCI_PHYS_READ_STATS */
802
803
804/*********************************************************************************************************************************
805* Global Variables *
806*********************************************************************************************************************************/
807#if defined(VBOX_WITH_OHCI_PHYS_READ_STATS) && defined(IN_RING3)
808static OHCIPHYSREADSTATS g_PhysReadState;
809#endif
810
811#if defined(LOG_ENABLED) && defined(IN_RING3)
812static bool g_fLogBulkEPs = false;
813static bool g_fLogControlEPs = false;
814static bool g_fLogInterruptEPs = false;
815#endif
816#ifdef IN_RING3
817/**
818 * SSM descriptor table for the OHCI structure.
819 */
820static SSMFIELD const g_aOhciFields[] =
821{
822 SSMFIELD_ENTRY( OHCI, SofTime),
823 SSMFIELD_ENTRY_CUSTOM( dpic+fno, RT_OFFSETOF(OHCI, SofTime) + RT_SIZEOFMEMB(OHCI, SofTime), 4),
824 SSMFIELD_ENTRY( OHCI, RootHub.status),
825 SSMFIELD_ENTRY( OHCI, RootHub.desc_a),
826 SSMFIELD_ENTRY( OHCI, RootHub.desc_b),
827 SSMFIELD_ENTRY( OHCI, RootHub.aPorts[0].fReg),
828 SSMFIELD_ENTRY( OHCI, RootHub.aPorts[1].fReg),
829 SSMFIELD_ENTRY( OHCI, RootHub.aPorts[2].fReg),
830 SSMFIELD_ENTRY( OHCI, RootHub.aPorts[3].fReg),
831 SSMFIELD_ENTRY( OHCI, RootHub.aPorts[4].fReg),
832 SSMFIELD_ENTRY( OHCI, RootHub.aPorts[5].fReg),
833 SSMFIELD_ENTRY( OHCI, RootHub.aPorts[6].fReg),
834 SSMFIELD_ENTRY( OHCI, RootHub.aPorts[7].fReg),
835 SSMFIELD_ENTRY( OHCI, RootHub.aPorts[8].fReg),
836 SSMFIELD_ENTRY( OHCI, RootHub.aPorts[9].fReg),
837 SSMFIELD_ENTRY( OHCI, RootHub.aPorts[10].fReg),
838 SSMFIELD_ENTRY( OHCI, RootHub.aPorts[11].fReg),
839 SSMFIELD_ENTRY( OHCI, RootHub.aPorts[12].fReg),
840 SSMFIELD_ENTRY( OHCI, RootHub.aPorts[13].fReg),
841 SSMFIELD_ENTRY( OHCI, RootHub.aPorts[14].fReg),
842 SSMFIELD_ENTRY( OHCI, ctl),
843 SSMFIELD_ENTRY( OHCI, status),
844 SSMFIELD_ENTRY( OHCI, intr_status),
845 SSMFIELD_ENTRY( OHCI, intr),
846 SSMFIELD_ENTRY( OHCI, hcca),
847 SSMFIELD_ENTRY( OHCI, per_cur),
848 SSMFIELD_ENTRY( OHCI, ctrl_cur),
849 SSMFIELD_ENTRY( OHCI, ctrl_head),
850 SSMFIELD_ENTRY( OHCI, bulk_cur),
851 SSMFIELD_ENTRY( OHCI, bulk_head),
852 SSMFIELD_ENTRY( OHCI, done),
853 SSMFIELD_ENTRY_CUSTOM( fsmps+fit+fi+frt, RT_OFFSETOF(OHCI, done) + RT_SIZEOFMEMB(OHCI, done), 4),
854 SSMFIELD_ENTRY( OHCI, HcFmNumber),
855 SSMFIELD_ENTRY( OHCI, pstart),
856 SSMFIELD_ENTRY_TERM()
857};
858#endif
859
860
861/*********************************************************************************************************************************
862* Internal Functions *
863*********************************************************************************************************************************/
864RT_C_DECLS_BEGIN
865#ifdef IN_RING3
866/* Update host controller state to reflect a device attach */
867static void rhport_power(POHCIROOTHUB pRh, unsigned iPort, bool fPowerUp);
868static void ohciBusResume(POHCI ohci, bool fHardware);
869static void ohciBusStop(POHCI pThis);
870#ifdef VBOX_WITH_OHCI_PHYS_READ_CACHE
871static void ohciPhysReadCacheClear(POHCIPAGECACHE pPageCache);
872#endif
873
874static DECLCALLBACK(void) ohciRhXferCompletion(PVUSBIROOTHUBPORT pInterface, PVUSBURB pUrb);
875static DECLCALLBACK(bool) ohciRhXferError(PVUSBIROOTHUBPORT pInterface, PVUSBURB pUrb);
876
877static int ohci_in_flight_find(POHCI pThis, uint32_t GCPhysTD);
878# if defined(VBOX_STRICT) || defined(LOG_ENABLED)
879static int ohci_in_done_queue_find(POHCI pThis, uint32_t GCPhysTD);
880# endif
881static DECLCALLBACK(void) ohciR3LoadReattachDevices(PPDMDEVINS pDevIns, PTMTIMER pTimer, void *pvUser);
882#endif /* IN_RING3 */
883RT_C_DECLS_END
884
885
886/**
887 * Update PCI IRQ levels
888 */
889static void ohciUpdateInterruptLocked(POHCI ohci, const char *msg)
890{
891 int level = 0;
892
893 if ( (ohci->intr & OHCI_INTR_MASTER_INTERRUPT_ENABLED)
894 && (ohci->intr_status & ohci->intr)
895 && !(ohci->ctl & OHCI_CTL_IR))
896 level = 1;
897
898 PDMDevHlpPCISetIrq(ohci->CTX_SUFF(pDevIns), 0, level);
899 if (level)
900 {
901 uint32_t val = ohci->intr_status & ohci->intr;
902 Log2(("ohci: Fired off interrupt %#010x - SO=%d WDH=%d SF=%d RD=%d UE=%d FNO=%d RHSC=%d OC=%d - %s\n",
903 val, val & 1, (val >> 1) & 1, (val >> 2) & 1, (val >> 3) & 1, (val >> 4) & 1, (val >> 5) & 1,
904 (val >> 6) & 1, (val >> 30) & 1, msg)); NOREF(val); NOREF(msg);
905 }
906}
907
908#ifdef IN_RING3
909
910/**
911 * Set an interrupt, use the wrapper ohciSetInterrupt.
912 */
913DECLINLINE(int) ohciSetInterruptInt(POHCI ohci, int rcBusy, uint32_t intr, const char *msg)
914{
915 int rc = PDMCritSectEnter(&ohci->CsIrq, rcBusy);
916 if (rc != VINF_SUCCESS)
917 return rc;
918
919 if ( (ohci->intr_status & intr) != intr )
920 {
921 ohci->intr_status |= intr;
922 ohciUpdateInterruptLocked(ohci, msg);
923 }
924
925 PDMCritSectLeave(&ohci->CsIrq);
926 return rc;
927}
928
929/**
930 * Set an interrupt wrapper macro for logging purposes.
931 */
932# define ohciR3SetInterrupt(ohci, intr) ohciSetInterruptInt(ohci, VERR_IGNORED, intr, #intr)
933
934
935/* Carry out a hardware remote wakeup */
936static void ohci_remote_wakeup(POHCI pThis)
937{
938 if ((pThis->ctl & OHCI_CTL_HCFS) != OHCI_USB_SUSPEND)
939 return;
940 if (!(pThis->RootHub.status & OHCI_RHS_DRWE))
941 return;
942 ohciBusResume(pThis, true /* hardware */);
943}
944
945
946/**
947 * Query interface method for the roothub LUN.
948 */
949static DECLCALLBACK(void *) ohciRhQueryInterface(PPDMIBASE pInterface, const char *pszIID)
950{
951 POHCI pThis = RT_FROM_MEMBER(pInterface, OHCI, RootHub.IBase);
952 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIBASE, &pThis->RootHub.IBase);
953 PDMIBASE_RETURN_INTERFACE(pszIID, VUSBIROOTHUBPORT, &pThis->RootHub.IRhPort);
954 PDMIBASE_RETURN_INTERFACE(pszIID, PDMILEDPORTS, &pThis->RootHub.ILeds);
955 return NULL;
956}
957
958/**
959 * Gets the pointer to the status LED of a unit.
960 *
961 * @returns VBox status code.
962 * @param pInterface Pointer to the interface structure containing the called function pointer.
963 * @param iLUN The unit which status LED we desire.
964 * @param ppLed Where to store the LED pointer.
965 */
966static DECLCALLBACK(int) ohciRhQueryStatusLed(PPDMILEDPORTS pInterface, unsigned iLUN, PPDMLED *ppLed)
967{
968 POHCI pThis = (POHCI)((uintptr_t)pInterface - RT_OFFSETOF(OHCI, RootHub.ILeds));
969 if (iLUN == 0)
970 {
971 *ppLed = &pThis->RootHub.Led;
972 return VINF_SUCCESS;
973 }
974 return VERR_PDM_LUN_NOT_FOUND;
975}
976
977
978/** Converts a OHCI.roothub.IRhPort pointer to a POHCI. */
979#define VUSBIROOTHUBPORT_2_OHCI(pInterface) ((POHCI)( (uintptr_t)(pInterface) - RT_OFFSETOF(OHCI, RootHub.IRhPort) ))
980
981
982/**
983 * Get the number of available ports in the hub.
984 *
985 * @returns The number of ports available.
986 * @param pInterface Pointer to this structure.
987 * @param pAvailable Bitmap indicating the available ports. Set bit == available port.
988 */
989static DECLCALLBACK(unsigned) ohciRhGetAvailablePorts(PVUSBIROOTHUBPORT pInterface, PVUSBPORTBITMAP pAvailable)
990{
991 POHCI pThis = VUSBIROOTHUBPORT_2_OHCI(pInterface);
992 unsigned iPort;
993 unsigned cPorts = 0;
994
995 memset(pAvailable, 0, sizeof(*pAvailable));
996
997 PDMCritSectEnter(pThis->pDevInsR3->pCritSectRoR3, VERR_IGNORED);
998 for (iPort = 0; iPort < OHCI_NDP_CFG(pThis); iPort++)
999 {
1000 if (!pThis->RootHub.aPorts[iPort].pDev)
1001 {
1002 cPorts++;
1003 ASMBitSet(pAvailable, iPort + 1);
1004 }
1005 }
1006 PDMCritSectLeave(pThis->pDevInsR3->pCritSectRoR3);
1007
1008 return cPorts;
1009}
1010
1011
1012/**
1013 * Gets the supported USB versions.
1014 *
1015 * @returns The mask of supported USB versions.
1016 * @param pInterface Pointer to this structure.
1017 */
1018static DECLCALLBACK(uint32_t) ohciRhGetUSBVersions(PVUSBIROOTHUBPORT pInterface)
1019{
1020 RT_NOREF(pInterface);
1021 return VUSB_STDVER_11;
1022}
1023
1024
1025/**
1026 * A device is being attached to a port in the roothub.
1027 *
1028 * @param pInterface Pointer to this structure.
1029 * @param pDev Pointer to the device being attached.
1030 * @param uPort The port number assigned to the device.
1031 */
1032static DECLCALLBACK(int) ohciRhAttach(PVUSBIROOTHUBPORT pInterface, PVUSBIDEVICE pDev, unsigned uPort)
1033{
1034 POHCI pThis = VUSBIROOTHUBPORT_2_OHCI(pInterface);
1035 LogFlow(("ohciRhAttach: pDev=%p uPort=%u\n", pDev, uPort));
1036 PDMCritSectEnter(pThis->pDevInsR3->pCritSectRoR3, VERR_IGNORED);
1037
1038 /*
1039 * Validate and adjust input.
1040 */
1041 Assert(uPort >= 1 && uPort <= OHCI_NDP_CFG(pThis));
1042 uPort--;
1043 Assert(!pThis->RootHub.aPorts[uPort].pDev);
1044 /* Only LS/FS devices can end up here. */
1045 Assert(pDev->pfnGetSpeed(pDev) == VUSB_SPEED_LOW || pDev->pfnGetSpeed(pDev) == VUSB_SPEED_FULL);
1046
1047 /*
1048 * Attach it.
1049 */
1050 pThis->RootHub.aPorts[uPort].fReg = OHCI_PORT_R_CURRENT_CONNECT_STATUS | OHCI_PORT_R_CONNECT_STATUS_CHANGE;
1051 pThis->RootHub.aPorts[uPort].pDev = pDev;
1052 rhport_power(&pThis->RootHub, uPort, 1 /* power on */);
1053
1054 ohci_remote_wakeup(pThis);
1055 ohciR3SetInterrupt(pThis, OHCI_INTR_ROOT_HUB_STATUS_CHANGE);
1056
1057 PDMCritSectLeave(pThis->pDevInsR3->pCritSectRoR3);
1058 return VINF_SUCCESS;
1059}
1060
1061
1062/**
1063 * A device is being detached from a port in the roothub.
1064 *
1065 * @param pInterface Pointer to this structure.
1066 * @param pDev Pointer to the device being detached.
1067 * @param uPort The port number assigned to the device.
1068 */
1069static DECLCALLBACK(void) ohciRhDetach(PVUSBIROOTHUBPORT pInterface, PVUSBIDEVICE pDev, unsigned uPort)
1070{
1071 RT_NOREF(pDev);
1072 POHCI pThis = VUSBIROOTHUBPORT_2_OHCI(pInterface);
1073 LogFlow(("ohciRhDetach: pDev=%p uPort=%u\n", pDev, uPort));
1074 PDMCritSectEnter(pThis->pDevInsR3->pCritSectRoR3, VERR_IGNORED);
1075
1076 /*
1077 * Validate and adjust input.
1078 */
1079 Assert(uPort >= 1 && uPort <= OHCI_NDP_CFG(pThis));
1080 uPort--;
1081 Assert(pThis->RootHub.aPorts[uPort].pDev == pDev);
1082
1083 /*
1084 * Detach it.
1085 */
1086 pThis->RootHub.aPorts[uPort].pDev = NULL;
1087 if (pThis->RootHub.aPorts[uPort].fReg & OHCI_PORT_PES)
1088 pThis->RootHub.aPorts[uPort].fReg = OHCI_PORT_R_CONNECT_STATUS_CHANGE | OHCI_PORT_PESC;
1089 else
1090 pThis->RootHub.aPorts[uPort].fReg = OHCI_PORT_R_CONNECT_STATUS_CHANGE;
1091
1092 ohci_remote_wakeup(pThis);
1093 ohciR3SetInterrupt(pThis, OHCI_INTR_ROOT_HUB_STATUS_CHANGE);
1094
1095 PDMCritSectLeave(pThis->pDevInsR3->pCritSectRoR3);
1096}
1097
1098
1099#ifdef IN_RING3
1100/**
1101 * One of the roothub devices has completed its reset operation.
1102 *
1103 * Currently, we don't think anything is required to be done here
1104 * so it's just a stub for forcing async resetting of the devices
1105 * during a root hub reset.
1106 *
1107 * @param pDev The root hub device.
1108 * @param rc The result of the operation.
1109 * @param pvUser Pointer to the controller.
1110 */
1111static DECLCALLBACK(void) ohciRhResetDoneOneDev(PVUSBIDEVICE pDev, int rc, void *pvUser)
1112{
1113 LogRel(("OHCI: root hub reset completed with %Rrc\n", rc));
1114 NOREF(pDev); NOREF(rc); NOREF(pvUser);
1115}
1116#endif
1117
1118
1119/**
1120 * Reset the root hub.
1121 *
1122 * @returns VBox status code.
1123 * @param pInterface Pointer to this structure.
1124 * @param fResetOnLinux This is used to indicate whether we're at VM reset time and
1125 * can do real resets or if we're at any other time where that
1126 * isn't such a good idea.
1127 * @remark Do NOT call VUSBIDevReset on the root hub in an async fashion!
1128 * @thread EMT
1129 */
1130static DECLCALLBACK(int) ohciRhReset(PVUSBIROOTHUBPORT pInterface, bool fResetOnLinux)
1131{
1132 POHCI pThis = VUSBIROOTHUBPORT_2_OHCI(pInterface);
1133 PDMCritSectEnter(pThis->pDevInsR3->pCritSectRoR3, VERR_IGNORED);
1134
1135 pThis->RootHub.status = 0;
1136 pThis->RootHub.desc_a = OHCI_RHA_NPS | OHCI_NDP_CFG(pThis); /* Preserve NDP value. */
1137 pThis->RootHub.desc_b = 0x0; /* Impl. specific */
1138
1139 /*
1140 * We're pending to _reattach_ the device without resetting them.
1141 * Except, during VM reset where we use the opportunity to do a proper
1142 * reset before the guest comes along and expect things.
1143 *
1144 * However, it's very very likely that we're not doing the right thing
1145 * here if coming from the guest (USB Reset state). The docs talks about
1146 * root hub resetting, however what exact behaviour in terms of root hub
1147 * status and changed bits, and HC interrupts aren't stated clearly. IF we
1148 * get trouble and see the guest doing "USB Resets" we will have to look
1149 * into this. For the time being we stick with simple.
1150 */
1151 for (unsigned iPort = 0; iPort < OHCI_NDP_CFG(pThis); iPort++)
1152 {
1153 if (pThis->RootHub.aPorts[iPort].pDev)
1154 {
1155 pThis->RootHub.aPorts[iPort].fReg = OHCI_PORT_R_CURRENT_CONNECT_STATUS | OHCI_PORT_R_CONNECT_STATUS_CHANGE;
1156 if (fResetOnLinux)
1157 {
1158 PVM pVM = PDMDevHlpGetVM(pThis->CTX_SUFF(pDevIns));
1159 VUSBIDevReset(pThis->RootHub.aPorts[iPort].pDev, fResetOnLinux, ohciRhResetDoneOneDev, pThis, pVM);
1160 }
1161 }
1162 else
1163 pThis->RootHub.aPorts[iPort].fReg = 0;
1164 }
1165
1166 PDMCritSectLeave(pThis->pDevInsR3->pCritSectRoR3);
1167 return VINF_SUCCESS;
1168}
1169
1170
1171/**
1172 * Does a software or hardware reset of the controller.
1173 *
1174 * This is called in response to setting HcCommandStatus.HCR, hardware reset,
1175 * and device construction.
1176 *
1177 * @param pThis The ohci instance data.
1178 * @param fNewMode The new mode of operation. This is UsbSuspend if it's a
1179 * software reset, and UsbReset if it's a hardware reset / cold boot.
1180 * @param fResetOnLinux Set if we can do a real reset of the devices attached to the root hub.
1181 * This is really a just a hack for the non-working linux device reset.
1182 * Linux has this feature called 'logical disconnect' if device reset fails
1183 * which prevents us from doing resets when the guest asks for it - the guest
1184 * will get confused when the device seems to be reconnected everytime it tries
1185 * to reset it. But if we're at hardware reset time, we can allow a device to
1186 * be 'reconnected' without upsetting the guest.
1187 *
1188 * @remark This hasn't got anything to do with software setting the mode to UsbReset.
1189 */
1190static void ohciDoReset(POHCI pThis, uint32_t fNewMode, bool fResetOnLinux)
1191{
1192 Log(("ohci: %s reset%s\n", fNewMode == OHCI_USB_RESET ? "hardware" : "software",
1193 fResetOnLinux ? " (reset on linux)" : ""));
1194
1195 /* Stop the bus in any case, disabling walking the lists. */
1196 ohciBusStop(pThis);
1197
1198 /*
1199 * Cancel all outstanding URBs.
1200 *
1201 * We can't, and won't, deal with URBs until we're moved out of the
1202 * suspend/reset state. Also, a real HC isn't going to send anything
1203 * any more when a reset has been signaled.
1204 */
1205 pThis->RootHub.pIRhConn->pfnCancelAllUrbs(pThis->RootHub.pIRhConn);
1206
1207 /*
1208 * Reset the hardware registers.
1209 */
1210 if (fNewMode == OHCI_USB_RESET)
1211 pThis->ctl |= OHCI_CTL_RWC; /* We're the firmware, set RemoteWakeupConnected. */
1212 else
1213 pThis->ctl &= OHCI_CTL_IR | OHCI_CTL_RWC; /* IR and RWC are preserved on software reset. */
1214
1215 /* Clear the HCFS bits first to make setting the new state work. */
1216 pThis->ctl &= ~OHCI_CTL_HCFS;
1217 pThis->ctl |= fNewMode;
1218 pThis->status = 0;
1219 pThis->intr_status = 0;
1220 pThis->intr = 0;
1221
1222 pThis->hcca = 0;
1223 pThis->per_cur = 0;
1224 pThis->ctrl_head = pThis->ctrl_cur = 0;
1225 pThis->bulk_head = pThis->bulk_cur = 0;
1226 pThis->done = 0;
1227
1228 pThis->fsmps = 0x2778; /* To-Be-Defined, use the value linux sets...*/
1229 pThis->fit = 0;
1230 pThis->fi = 11999; /* (12MHz ticks, one frame is 1ms) */
1231 pThis->frt = 0;
1232 pThis->HcFmNumber = 0;
1233 pThis->pstart = 0;
1234
1235 pThis->dqic = 0x7;
1236 pThis->fno = 0;
1237
1238#ifdef VBOX_WITH_OHCI_PHYS_READ_CACHE
1239 ohciPhysReadCacheClear(pThis->pCacheED);
1240 ohciPhysReadCacheClear(pThis->pCacheTD);
1241#endif
1242
1243 /*
1244 * If this is a hardware reset, we will initialize the root hub too.
1245 * Software resets doesn't do this according to the specs.
1246 * (It's not possible to have device connected at the time of the
1247 * device construction, so nothing to worry about there.)
1248 */
1249 if (fNewMode == OHCI_USB_RESET)
1250 VUSBIDevReset(pThis->RootHub.pIDev, fResetOnLinux, NULL, NULL, NULL);
1251}
1252
1253/**
1254 * Reads physical memory.
1255 */
1256DECLINLINE(void) ohciPhysRead(POHCI pThis, uint32_t Addr, void *pvBuf, size_t cbBuf)
1257{
1258 if (cbBuf)
1259 PDMDevHlpPhysRead(pThis->CTX_SUFF(pDevIns), Addr, pvBuf, cbBuf);
1260}
1261
1262/**
1263 * Writes physical memory.
1264 */
1265DECLINLINE(void) ohciPhysWrite(POHCI pThis, uint32_t Addr, const void *pvBuf, size_t cbBuf)
1266{
1267 if (cbBuf)
1268 PDMDevHlpPCIPhysWrite(pThis->CTX_SUFF(pDevIns), Addr, pvBuf, cbBuf);
1269}
1270
1271/**
1272 * Read an array of dwords from physical memory and correct endianness.
1273 */
1274DECLINLINE(void) ohciGetDWords(POHCI pThis, uint32_t Addr, uint32_t *pau32s, int c32s)
1275{
1276 ohciPhysRead(pThis, Addr, pau32s, c32s * sizeof(uint32_t));
1277# ifndef RT_LITTLE_ENDIAN
1278 for(int i = 0; i < c32s; i++)
1279 pau32s[i] = RT_H2LE_U32(pau32s[i]);
1280# endif
1281}
1282
1283/**
1284 * Write an array of dwords from physical memory and correct endianness.
1285 */
1286DECLINLINE(void) ohciPutDWords(POHCI pThis, uint32_t Addr, const uint32_t *pau32s, int cu32s)
1287{
1288# ifdef RT_LITTLE_ENDIAN
1289 ohciPhysWrite(pThis, Addr, pau32s, cu32s << 2);
1290# else
1291 for (int i = 0; i < c32s; i++, pau32s++, Addr += sizeof(*pau32s))
1292 {
1293 uint32_t u32Tmp = RT_H2LE_U32(*pau32s);
1294 ohciPhysWrite(pThis, Addr, (uint8_t *)&u32Tmp, sizeof(u32Tmp));
1295 }
1296# endif
1297}
1298
1299
1300
1301# ifdef VBOX_WITH_OHCI_PHYS_READ_STATS
1302
1303static void descReadStatsReset(POHCIDESCREADSTATS p)
1304{
1305 p->cReads = 0;
1306 p->cPageChange = 0;
1307 p->cMinReadsPerPage = UINT32_MAX;
1308 p->cMaxReadsPerPage = 0;
1309
1310 p->cReadsLastPage = 0;
1311 p->u32LastPageAddr = 0;
1312}
1313
1314static void physReadStatsReset(POHCIPHYSREADSTATS p)
1315{
1316 descReadStatsReset(&p->ed);
1317 descReadStatsReset(&p->td);
1318 descReadStatsReset(&p->all);
1319
1320 p->cCrossReads = 0;
1321 p->cCacheReads = 0;
1322 p->cPageReads = 0;
1323}
1324
1325static void physReadStatsUpdateDesc(POHCIDESCREADSTATS p, uint32_t u32Addr)
1326{
1327 const uint32_t u32PageAddr = u32Addr & ~UINT32_C(0xFFF);
1328
1329 ++p->cReads;
1330
1331 if (p->u32LastPageAddr == 0)
1332 {
1333 /* First call. */
1334 ++p->cReadsLastPage;
1335 p->u32LastPageAddr = u32PageAddr;
1336 }
1337 else if (u32PageAddr != p->u32LastPageAddr)
1338 {
1339 /* New page. */
1340 ++p->cPageChange;
1341
1342 p->cMinReadsPerPage = RT_MIN(p->cMinReadsPerPage, p->cReadsLastPage);
1343 p->cMaxReadsPerPage = RT_MAX(p->cMaxReadsPerPage, p->cReadsLastPage);;
1344
1345 p->cReadsLastPage = 1;
1346 p->u32LastPageAddr = u32PageAddr;
1347 }
1348 else
1349 {
1350 /* Read on the same page. */
1351 ++p->cReadsLastPage;
1352 }
1353}
1354
1355static void physReadStatsPrint(PCOHCIPHYSREADSTATS p)
1356{
1357 p->ed.cMinReadsPerPage = RT_MIN(p->ed.cMinReadsPerPage, p->ed.cReadsLastPage);
1358 p->ed.cMaxReadsPerPage = RT_MAX(p->ed.cMaxReadsPerPage, p->ed.cReadsLastPage);;
1359
1360 p->td.cMinReadsPerPage = RT_MIN(p->td.cMinReadsPerPage, p->td.cReadsLastPage);
1361 p->td.cMaxReadsPerPage = RT_MAX(p->td.cMaxReadsPerPage, p->td.cReadsLastPage);;
1362
1363 p->all.cMinReadsPerPage = RT_MIN(p->all.cMinReadsPerPage, p->all.cReadsLastPage);
1364 p->all.cMaxReadsPerPage = RT_MAX(p->all.cMaxReadsPerPage, p->all.cReadsLastPage);;
1365
1366 LogRel(("PHYSREAD:\n"
1367 " ED: %d, %d, %d/%d\n"
1368 " TD: %d, %d, %d/%d\n"
1369 " ALL: %d, %d, %d/%d\n"
1370 " C: %d, %d, %d\n"
1371 "",
1372 p->ed.cReads, p->ed.cPageChange, p->ed.cMinReadsPerPage, p->ed.cMaxReadsPerPage,
1373 p->td.cReads, p->td.cPageChange, p->td.cMinReadsPerPage, p->td.cMaxReadsPerPage,
1374 p->all.cReads, p->all.cPageChange, p->all.cMinReadsPerPage, p->all.cMaxReadsPerPage,
1375 p->cCrossReads, p->cCacheReads, p->cPageReads
1376 ));
1377
1378 physReadStatsReset(p);
1379}
1380
1381# endif /* VBOX_WITH_OHCI_PHYS_READ_STATS */
1382# ifdef VBOX_WITH_OHCI_PHYS_READ_CACHE
1383
1384static POHCIPAGECACHE ohciPhysReadCacheAlloc(void)
1385{
1386 return (POHCIPAGECACHE)RTMemAlloc(sizeof(OHCIPAGECACHE));
1387}
1388
1389static void ohciPhysReadCacheFree(POHCIPAGECACHE pPageCache)
1390{
1391 RTMemFree(pPageCache);
1392}
1393
1394static void ohciPhysReadCacheClear(POHCIPAGECACHE pPageCache)
1395{
1396 pPageCache->GCPhysReadCacheAddr = NIL_RTGCPHYS;
1397}
1398
1399static void ohciPhysReadCacheRead(POHCI pThis, POHCIPAGECACHE pPageCache, RTGCPHYS GCPhys, void *pvBuf, size_t cbBuf)
1400{
1401 const RTGCPHYS PageAddr = PAGE_ADDRESS(GCPhys);
1402
1403 if (PageAddr == PAGE_ADDRESS(GCPhys + cbBuf))
1404 {
1405 if (PageAddr != pPageCache->GCPhysReadCacheAddr)
1406 {
1407 PDMDevHlpPhysRead(pThis->pDevInsR3, PageAddr,
1408 pPageCache->au8PhysReadCache, sizeof(pPageCache->au8PhysReadCache));
1409 pPageCache->GCPhysReadCacheAddr = PageAddr;
1410# ifdef VBOX_WITH_OHCI_PHYS_READ_STATS
1411 ++g_PhysReadState.cPageReads;
1412# endif
1413 }
1414
1415 memcpy(pvBuf, &pPageCache->au8PhysReadCache[GCPhys & PAGE_OFFSET_MASK], cbBuf);
1416# ifdef VBOX_WITH_OHCI_PHYS_READ_STATS
1417 ++g_PhysReadState.cCacheReads;
1418# endif
1419 }
1420 else
1421 {
1422 PDMDevHlpPhysRead(pThis->pDevInsR3, GCPhys, pvBuf, cbBuf);
1423# ifdef VBOX_WITH_OHCI_PHYS_READ_STATS
1424 ++g_PhysReadState.cCrossReads;
1425# endif
1426 }
1427}
1428
1429static void ohciReadEdCached(POHCI pThis, uint32_t EdAddr, POHCIED pEd)
1430{
1431 ohciPhysReadCacheRead(pThis, pThis->pCacheED, EdAddr, pEd, sizeof(*pEd));
1432}
1433
1434static void ohciReadTdCached(POHCI pThis, uint32_t TdAddr, POHCITD pTd)
1435{
1436 ohciPhysReadCacheRead(pThis, pThis->pCacheTD, TdAddr, pTd, sizeof(*pTd));
1437}
1438
1439# endif /* VBOX_WITH_OHCI_PHYS_READ_CACHE */
1440
1441/**
1442 * Reads an OHCIED.
1443 */
1444DECLINLINE(void) ohciReadEd(POHCI pThis, uint32_t EdAddr, POHCIED pEd)
1445{
1446# ifdef VBOX_WITH_OHCI_PHYS_READ_STATS
1447 physReadStatsUpdateDesc(&g_PhysReadState.ed, EdAddr);
1448 physReadStatsUpdateDesc(&g_PhysReadState.all, EdAddr);
1449# endif
1450 ohciGetDWords(pThis, EdAddr, (uint32_t *)pEd, sizeof(*pEd) >> 2);
1451}
1452
1453/**
1454 * Reads an OHCITD.
1455 */
1456DECLINLINE(void) ohciReadTd(POHCI pThis, uint32_t TdAddr, POHCITD pTd)
1457{
1458# ifdef VBOX_WITH_OHCI_PHYS_READ_STATS
1459 physReadStatsUpdateDesc(&g_PhysReadState.td, TdAddr);
1460 physReadStatsUpdateDesc(&g_PhysReadState.all, TdAddr);
1461# endif
1462 ohciGetDWords(pThis, TdAddr, (uint32_t *)pTd, sizeof(*pTd) >> 2);
1463# ifdef LOG_ENABLED
1464 if (LogIs3Enabled())
1465 {
1466 uint32_t hichg;
1467 hichg = pTd->hwinfo;
1468 Log3(("ohciReadTd(,%#010x,): R=%d DP=%d DI=%d T=%d EC=%d CC=%#x CBP=%#010x NextTD=%#010x BE=%#010x UNK=%#x\n",
1469 TdAddr,
1470 (pTd->hwinfo >> 18) & 1,
1471 (pTd->hwinfo >> 19) & 3,
1472 (pTd->hwinfo >> 21) & 7,
1473 (pTd->hwinfo >> 24) & 3,
1474 (pTd->hwinfo >> 26) & 3,
1475 (pTd->hwinfo >> 28) &15,
1476 pTd->cbp,
1477 pTd->NextTD,
1478 pTd->be,
1479 pTd->hwinfo & TD_HWINFO_UNKNOWN_MASK));
1480# if 0
1481 if (LogIs3Enabled())
1482 {
1483 /*
1484 * usbohci.sys (32-bit XP) allocates 0x80 bytes per TD:
1485 * 0x00-0x0f is the OHCI TD.
1486 * 0x10-0x1f for isochronous TDs
1487 * 0x20 is the physical address of this TD.
1488 * 0x24 is initialized with 0x64745948, probably a magic.
1489 * 0x28 is some kind of flags. the first bit begin the allocated / not allocated indicator.
1490 * 0x30 is a pointer to something. endpoint? interface? device?
1491 * 0x38 is initialized to 0xdeadface. but is changed into a pointer or something.
1492 * 0x40 looks like a pointer.
1493 * The rest is unknown and initialized with zeros.
1494 */
1495 uint8_t abXpTd[0x80];
1496 ohciPhysRead(pThis, TdAddr, abXpTd, sizeof(abXpTd));
1497 Log3(("WinXpTd: alloc=%d PhysSelf=%RX32 s2=%RX32 magic=%RX32 s4=%RX32 s5=%RX32\n"
1498 "%.*Rhxd\n",
1499 abXpTd[28] & RT_BIT(0),
1500 *((uint32_t *)&abXpTd[0x20]), *((uint32_t *)&abXpTd[0x30]),
1501 *((uint32_t *)&abXpTd[0x24]), *((uint32_t *)&abXpTd[0x38]),
1502 *((uint32_t *)&abXpTd[0x40]),
1503 sizeof(abXpTd), &abXpTd[0]));
1504 }
1505# endif
1506 }
1507# endif
1508}
1509
1510/**
1511 * Reads an OHCIITD.
1512 */
1513DECLINLINE(void) ohciReadITd(POHCI pThis, uint32_t ITdAddr, POHCIITD pITd)
1514{
1515 ohciGetDWords(pThis, ITdAddr, (uint32_t *)pITd, sizeof(*pITd) / sizeof(uint32_t));
1516# ifdef LOG_ENABLED
1517 if (LogIs3Enabled())
1518 {
1519 Log3(("ohciReadITd(,%#010x,): SF=%#06x (%#RX32) DI=%#x FC=%d CC=%#x BP0=%#010x NextTD=%#010x BE=%#010x\n",
1520 ITdAddr,
1521 pITd->HwInfo & 0xffff, pThis->HcFmNumber,
1522 (pITd->HwInfo >> 21) & 7,
1523 (pITd->HwInfo >> 24) & 7,
1524 (pITd->HwInfo >> 28) &15,
1525 pITd->BP0,
1526 pITd->NextTD,
1527 pITd->BE));
1528 Log3(("psw0=%x:%03x psw1=%x:%03x psw2=%x:%03x psw3=%x:%03x psw4=%x:%03x psw5=%x:%03x psw6=%x:%03x psw7=%x:%03x\n",
1529 pITd->aPSW[0] >> 12, pITd->aPSW[0] & 0xfff,
1530 pITd->aPSW[1] >> 12, pITd->aPSW[1] & 0xfff,
1531 pITd->aPSW[2] >> 12, pITd->aPSW[2] & 0xfff,
1532 pITd->aPSW[3] >> 12, pITd->aPSW[3] & 0xfff,
1533 pITd->aPSW[4] >> 12, pITd->aPSW[4] & 0xfff,
1534 pITd->aPSW[5] >> 12, pITd->aPSW[5] & 0xfff,
1535 pITd->aPSW[6] >> 12, pITd->aPSW[6] & 0xfff,
1536 pITd->aPSW[7] >> 12, pITd->aPSW[7] & 0xfff));
1537 }
1538# endif
1539}
1540
1541
1542/**
1543 * Writes an OHCIED.
1544 */
1545DECLINLINE(void) ohciWriteEd(POHCI pThis, uint32_t EdAddr, PCOHCIED pEd)
1546{
1547# ifdef LOG_ENABLED
1548 if (LogIs3Enabled())
1549 {
1550 OHCIED EdOld;
1551 uint32_t hichg;
1552
1553 ohciGetDWords(pThis, EdAddr, (uint32_t *)&EdOld, sizeof(EdOld) >> 2);
1554 hichg = EdOld.hwinfo ^ pEd->hwinfo;
1555 Log3(("ohciWriteEd(,%#010x,): %sFA=%#x %sEN=%#x %sD=%#x %sS=%d %sK=%d %sF=%d %sMPS=%#x %sTailP=%#010x %sHeadP=%#010x %sH=%d %sC=%d %sNextED=%#010x\n",
1556 EdAddr,
1557 (hichg >> 0) & 0x7f ? "*" : "", (pEd->hwinfo >> 0) & 0x7f,
1558 (hichg >> 7) & 0xf ? "*" : "", (pEd->hwinfo >> 7) & 0xf,
1559 (hichg >> 11) & 3 ? "*" : "", (pEd->hwinfo >> 11) & 3,
1560 (hichg >> 13) & 1 ? "*" : "", (pEd->hwinfo >> 13) & 1,
1561 (hichg >> 14) & 1 ? "*" : "", (pEd->hwinfo >> 14) & 1,
1562 (hichg >> 15) & 1 ? "*" : "", (pEd->hwinfo >> 15) & 1,
1563 (hichg >> 24) &0x3ff ? "*" : "", (pEd->hwinfo >> 16) &0x3ff,
1564 EdOld.TailP != pEd->TailP ? "*" : "", pEd->TailP,
1565 (EdOld.HeadP & ~3) != (pEd->HeadP & ~3) ? "*" : "", pEd->HeadP & ~3,
1566 (EdOld.HeadP ^ pEd->HeadP) & 1 ? "*" : "", pEd->HeadP & 1,
1567 (EdOld.HeadP ^ pEd->HeadP) & 2 ? "*" : "", (pEd->HeadP >> 1) & 1,
1568 EdOld.NextED != pEd->NextED ? "*" : "", pEd->NextED));
1569 }
1570# endif
1571
1572 ohciPutDWords(pThis, EdAddr, (uint32_t *)pEd, sizeof(*pEd) >> 2);
1573}
1574
1575
1576/**
1577 * Writes an OHCITD.
1578 */
1579DECLINLINE(void) ohciWriteTd(POHCI pThis, uint32_t TdAddr, PCOHCITD pTd, const char *pszLogMsg)
1580{
1581# ifdef LOG_ENABLED
1582 if (LogIs3Enabled())
1583 {
1584 OHCITD TdOld;
1585 ohciGetDWords(pThis, TdAddr, (uint32_t *)&TdOld, sizeof(TdOld) >> 2);
1586 uint32_t hichg = TdOld.hwinfo ^ pTd->hwinfo;
1587 Log3(("ohciWriteTd(,%#010x,): %sR=%d %sDP=%d %sDI=%#x %sT=%d %sEC=%d %sCC=%#x %sCBP=%#010x %sNextTD=%#010x %sBE=%#010x (%s)\n",
1588 TdAddr,
1589 (hichg >> 18) & 1 ? "*" : "", (pTd->hwinfo >> 18) & 1,
1590 (hichg >> 19) & 3 ? "*" : "", (pTd->hwinfo >> 19) & 3,
1591 (hichg >> 21) & 7 ? "*" : "", (pTd->hwinfo >> 21) & 7,
1592 (hichg >> 24) & 3 ? "*" : "", (pTd->hwinfo >> 24) & 3,
1593 (hichg >> 26) & 3 ? "*" : "", (pTd->hwinfo >> 26) & 3,
1594 (hichg >> 28) &15 ? "*" : "", (pTd->hwinfo >> 28) &15,
1595 TdOld.cbp != pTd->cbp ? "*" : "", pTd->cbp,
1596 TdOld.NextTD != pTd->NextTD ? "*" : "", pTd->NextTD,
1597 TdOld.be != pTd->be ? "*" : "", pTd->be,
1598 pszLogMsg));
1599 }
1600# else
1601 RT_NOREF(pszLogMsg);
1602# endif
1603 ohciPutDWords(pThis, TdAddr, (uint32_t *)pTd, sizeof(*pTd) >> 2);
1604}
1605
1606/**
1607 * Writes an OHCIITD.
1608 */
1609DECLINLINE(void) ohciWriteITd(POHCI pThis, uint32_t ITdAddr, PCOHCIITD pITd, const char *pszLogMsg)
1610{
1611# ifdef LOG_ENABLED
1612 if (LogIs3Enabled())
1613 {
1614 OHCIITD ITdOld;
1615 ohciGetDWords(pThis, ITdAddr, (uint32_t *)&ITdOld, sizeof(ITdOld) / sizeof(uint32_t));
1616 uint32_t HIChg = ITdOld.HwInfo ^ pITd->HwInfo;
1617 Log3(("ohciWriteITd(,%#010x,): %sSF=%#x (now=%#RX32) %sDI=%#x %sFC=%d %sCC=%#x %sBP0=%#010x %sNextTD=%#010x %sBE=%#010x (%s)\n",
1618 ITdAddr,
1619 (HIChg & 0xffff) & 1 ? "*" : "", pITd->HwInfo & 0xffff, pThis->HcFmNumber,
1620 (HIChg >> 21) & 7 ? "*" : "", (pITd->HwInfo >> 21) & 7,
1621 (HIChg >> 24) & 7 ? "*" : "", (pITd->HwInfo >> 24) & 7,
1622 (HIChg >> 28) &15 ? "*" : "", (pITd->HwInfo >> 28) &15,
1623 ITdOld.BP0 != pITd->BP0 ? "*" : "", pITd->BP0,
1624 ITdOld.NextTD != pITd->NextTD ? "*" : "", pITd->NextTD,
1625 ITdOld.BE != pITd->BE ? "*" : "", pITd->BE,
1626 pszLogMsg));
1627 Log3(("psw0=%s%x:%s%03x psw1=%s%x:%s%03x psw2=%s%x:%s%03x psw3=%s%x:%s%03x psw4=%s%x:%s%03x psw5=%s%x:%s%03x psw6=%s%x:%s%03x psw7=%s%x:%s%03x\n",
1628 (ITdOld.aPSW[0] >> 12) != (pITd->aPSW[0] >> 12) ? "*" : "", pITd->aPSW[0] >> 12, (ITdOld.aPSW[0] & 0xfff) != (pITd->aPSW[0] & 0xfff) ? "*" : "", pITd->aPSW[0] & 0xfff,
1629 (ITdOld.aPSW[1] >> 12) != (pITd->aPSW[1] >> 12) ? "*" : "", pITd->aPSW[1] >> 12, (ITdOld.aPSW[1] & 0xfff) != (pITd->aPSW[1] & 0xfff) ? "*" : "", pITd->aPSW[1] & 0xfff,
1630 (ITdOld.aPSW[2] >> 12) != (pITd->aPSW[2] >> 12) ? "*" : "", pITd->aPSW[2] >> 12, (ITdOld.aPSW[2] & 0xfff) != (pITd->aPSW[2] & 0xfff) ? "*" : "", pITd->aPSW[2] & 0xfff,
1631 (ITdOld.aPSW[3] >> 12) != (pITd->aPSW[3] >> 12) ? "*" : "", pITd->aPSW[3] >> 12, (ITdOld.aPSW[3] & 0xfff) != (pITd->aPSW[3] & 0xfff) ? "*" : "", pITd->aPSW[3] & 0xfff,
1632 (ITdOld.aPSW[4] >> 12) != (pITd->aPSW[4] >> 12) ? "*" : "", pITd->aPSW[4] >> 12, (ITdOld.aPSW[4] & 0xfff) != (pITd->aPSW[4] & 0xfff) ? "*" : "", pITd->aPSW[4] & 0xfff,
1633 (ITdOld.aPSW[5] >> 12) != (pITd->aPSW[5] >> 12) ? "*" : "", pITd->aPSW[5] >> 12, (ITdOld.aPSW[5] & 0xfff) != (pITd->aPSW[5] & 0xfff) ? "*" : "", pITd->aPSW[5] & 0xfff,
1634 (ITdOld.aPSW[6] >> 12) != (pITd->aPSW[6] >> 12) ? "*" : "", pITd->aPSW[6] >> 12, (ITdOld.aPSW[6] & 0xfff) != (pITd->aPSW[6] & 0xfff) ? "*" : "", pITd->aPSW[6] & 0xfff,
1635 (ITdOld.aPSW[7] >> 12) != (pITd->aPSW[7] >> 12) ? "*" : "", pITd->aPSW[7] >> 12, (ITdOld.aPSW[7] & 0xfff) != (pITd->aPSW[7] & 0xfff) ? "*" : "", pITd->aPSW[7] & 0xfff));
1636 }
1637# else
1638 RT_NOREF(pszLogMsg);
1639# endif
1640 ohciPutDWords(pThis, ITdAddr, (uint32_t *)pITd, sizeof(*pITd) / sizeof(uint32_t));
1641}
1642
1643
1644# ifdef LOG_ENABLED
1645
1646/**
1647 * Core TD queue dumper. LOG_ENABLED builds only.
1648 */
1649DECLINLINE(void) ohciDumpTdQueueCore(POHCI pThis, uint32_t GCPhysHead, uint32_t GCPhysTail, bool fFull)
1650{
1651 uint32_t GCPhys = GCPhysHead;
1652 int cMax = 100;
1653 for (;;)
1654 {
1655 OHCITD Td;
1656 Log4(("%#010x%s%s", GCPhys,
1657 GCPhys && ohci_in_flight_find(pThis, GCPhys) >= 0 ? "~" : "",
1658 GCPhys && ohci_in_done_queue_find(pThis, GCPhys) >= 0 ? "^" : ""));
1659 if (GCPhys == 0 || GCPhys == GCPhysTail)
1660 break;
1661
1662 /* can't use ohciReadTd() because of Log4. */
1663 ohciGetDWords(pThis, GCPhys, (uint32_t *)&Td, sizeof(Td) >> 2);
1664 if (fFull)
1665 Log4((" [R=%d DP=%d DI=%d T=%d EC=%d CC=%#x CBP=%#010x NextTD=%#010x BE=%#010x] -> ",
1666 (Td.hwinfo >> 18) & 1,
1667 (Td.hwinfo >> 19) & 3,
1668 (Td.hwinfo >> 21) & 7,
1669 (Td.hwinfo >> 24) & 3,
1670 (Td.hwinfo >> 26) & 3,
1671 (Td.hwinfo >> 28) &15,
1672 Td.cbp,
1673 Td.NextTD,
1674 Td.be));
1675 else
1676 Log4((" -> "));
1677 GCPhys = Td.NextTD & ED_PTR_MASK;
1678 Assert(GCPhys != GCPhysHead);
1679 Assert(cMax-- > 0); NOREF(cMax);
1680 }
1681}
1682
1683/**
1684 * Dumps a TD queue. LOG_ENABLED builds only.
1685 */
1686DECLINLINE(void) ohciDumpTdQueue(POHCI pThis, uint32_t GCPhysHead, const char *pszMsg)
1687{
1688 if (pszMsg)
1689 Log4(("%s: ", pszMsg));
1690 ohciDumpTdQueueCore(pThis, GCPhysHead, 0, true);
1691 Log4(("\n"));
1692}
1693
1694/**
1695 * Core ITD queue dumper. LOG_ENABLED builds only.
1696 */
1697DECLINLINE(void) ohciDumpITdQueueCore(POHCI pThis, uint32_t GCPhysHead, uint32_t GCPhysTail, bool fFull)
1698{
1699 RT_NOREF(fFull);
1700 uint32_t GCPhys = GCPhysHead;
1701 int cMax = 100;
1702 for (;;)
1703 {
1704 OHCIITD ITd;
1705 Log4(("%#010x%s%s", GCPhys,
1706 GCPhys && ohci_in_flight_find(pThis, GCPhys) >= 0 ? "~" : "",
1707 GCPhys && ohci_in_done_queue_find(pThis, GCPhys) >= 0 ? "^" : ""));
1708 if (GCPhys == 0 || GCPhys == GCPhysTail)
1709 break;
1710
1711 /* can't use ohciReadTd() because of Log4. */
1712 ohciGetDWords(pThis, GCPhys, (uint32_t *)&ITd, sizeof(ITd) / sizeof(uint32_t));
1713 /*if (fFull)
1714 Log4((" [R=%d DP=%d DI=%d T=%d EC=%d CC=%#x CBP=%#010x NextTD=%#010x BE=%#010x] -> ",
1715 (Td.hwinfo >> 18) & 1,
1716 (Td.hwinfo >> 19) & 3,
1717 (Td.hwinfo >> 21) & 7,
1718 (Td.hwinfo >> 24) & 3,
1719 (Td.hwinfo >> 26) & 3,
1720 (Td.hwinfo >> 28) &15,
1721 Td.cbp,
1722 Td.NextTD,
1723 Td.be));
1724 else*/
1725 Log4((" -> "));
1726 GCPhys = ITd.NextTD & ED_PTR_MASK;
1727 Assert(GCPhys != GCPhysHead);
1728 Assert(cMax-- > 0); NOREF(cMax);
1729 }
1730}
1731
1732/**
1733 * Dumps a ED list. LOG_ENABLED builds only.
1734 */
1735DECLINLINE(void) ohciDumpEdList(POHCI pThis, uint32_t GCPhysHead, const char *pszMsg, bool fTDs)
1736{
1737 RT_NOREF(fTDs);
1738 uint32_t GCPhys = GCPhysHead;
1739 if (pszMsg)
1740 Log4(("%s:", pszMsg));
1741 for (;;)
1742 {
1743 OHCIED Ed;
1744
1745 /* ED */
1746 Log4((" %#010x={", GCPhys));
1747 if (!GCPhys)
1748 {
1749 Log4(("END}\n"));
1750 return;
1751 }
1752
1753 /* TDs */
1754 ohciReadEd(pThis, GCPhys, &Ed);
1755 if (Ed.hwinfo & ED_HWINFO_ISO)
1756 Log4(("[I]"));
1757 if ((Ed.HeadP & ED_HEAD_HALTED) || (Ed.hwinfo & ED_HWINFO_SKIP))
1758 {
1759 if ((Ed.HeadP & ED_HEAD_HALTED) && (Ed.hwinfo & ED_HWINFO_SKIP))
1760 Log4(("SH}"));
1761 else if (Ed.hwinfo & ED_HWINFO_SKIP)
1762 Log4(("S-}"));
1763 else
1764 Log4(("-H}"));
1765 }
1766 else
1767 {
1768 if (Ed.hwinfo & ED_HWINFO_ISO)
1769 ohciDumpITdQueueCore(pThis, Ed.HeadP & ED_PTR_MASK, Ed.TailP & ED_PTR_MASK, false);
1770 else
1771 ohciDumpTdQueueCore(pThis, Ed.HeadP & ED_PTR_MASK, Ed.TailP & ED_PTR_MASK, false);
1772 Log4(("}"));
1773 }
1774
1775 /* next */
1776 GCPhys = Ed.NextED & ED_PTR_MASK;
1777 Assert(GCPhys != GCPhysHead);
1778 }
1779 /* not reached */
1780}
1781
1782# endif /* LOG_ENABLED */
1783
1784
1785DECLINLINE(int) ohci_in_flight_find_free(POHCI pThis, const int iStart)
1786{
1787 unsigned i = iStart;
1788 while (i < RT_ELEMENTS(pThis->aInFlight))
1789 {
1790 if (pThis->aInFlight[i].GCPhysTD == 0)
1791 return i;
1792 i++;
1793 }
1794 i = iStart;
1795 while (i-- > 0)
1796 {
1797 if (pThis->aInFlight[i].GCPhysTD == 0)
1798 return i;
1799 }
1800 return -1;
1801}
1802
1803
1804/**
1805 * Record an in-flight TD.
1806 *
1807 * @param pThis OHCI instance data.
1808 * @param GCPhysTD Physical address of the TD.
1809 * @param pUrb The URB.
1810 */
1811static void ohci_in_flight_add(POHCI pThis, uint32_t GCPhysTD, PVUSBURB pUrb)
1812{
1813 int i = ohci_in_flight_find_free(pThis, (GCPhysTD >> 4) % RT_ELEMENTS(pThis->aInFlight));
1814 if (i >= 0)
1815 {
1816# ifdef LOG_ENABLED
1817 pUrb->pHci->u32FrameNo = pThis->HcFmNumber;
1818# endif
1819 pThis->aInFlight[i].GCPhysTD = GCPhysTD;
1820 pThis->aInFlight[i].pUrb = pUrb;
1821 pThis->cInFlight++;
1822 return;
1823 }
1824 AssertMsgFailed(("Out of space cInFlight=%d!\n", pThis->cInFlight));
1825}
1826
1827
1828/**
1829 * Record in-flight TDs for an URB.
1830 *
1831 * @param pThis OHCI instance data.
1832 * @param pUrb The URB.
1833 */
1834static void ohci_in_flight_add_urb(POHCI pThis, PVUSBURB pUrb)
1835{
1836 for (unsigned iTd = 0; iTd < pUrb->pHci->cTds; iTd++)
1837 ohci_in_flight_add(pThis, pUrb->paTds[iTd].TdAddr, pUrb);
1838}
1839
1840
1841/**
1842 * Finds a in-flight TD.
1843 *
1844 * @returns Index of the record.
1845 * @returns -1 if not found.
1846 * @param pThis OHCI instance data.
1847 * @param GCPhysTD Physical address of the TD.
1848 * @remark This has to be fast.
1849 */
1850static int ohci_in_flight_find(POHCI pThis, uint32_t GCPhysTD)
1851{
1852 unsigned cLeft = pThis->cInFlight;
1853 unsigned i = (GCPhysTD >> 4) % RT_ELEMENTS(pThis->aInFlight);
1854 const int iLast = i;
1855 while (i < RT_ELEMENTS(pThis->aInFlight))
1856 {
1857 if (pThis->aInFlight[i].GCPhysTD == GCPhysTD)
1858 return i;
1859 if (pThis->aInFlight[i].GCPhysTD)
1860 if (cLeft-- <= 1)
1861 return -1;
1862 i++;
1863 }
1864 i = iLast;
1865 while (i-- > 0)
1866 {
1867 if (pThis->aInFlight[i].GCPhysTD == GCPhysTD)
1868 return i;
1869 if (pThis->aInFlight[i].GCPhysTD)
1870 if (cLeft-- <= 1)
1871 return -1;
1872 }
1873 return -1;
1874}
1875
1876
1877/**
1878 * Checks if a TD is in-flight.
1879 *
1880 * @returns true if in flight, false if not.
1881 * @param pThis OHCI instance data.
1882 * @param GCPhysTD Physical address of the TD.
1883 */
1884static bool ohciIsTdInFlight(POHCI pThis, uint32_t GCPhysTD)
1885{
1886 return ohci_in_flight_find(pThis, GCPhysTD) >= 0;
1887}
1888
1889/**
1890 * Returns a URB associated with an in-flight TD, if any.
1891 *
1892 * @returns pointer to URB if TD is in flight.
1893 * @returns NULL if not in flight.
1894 * @param pThis OHCI instance data.
1895 * @param GCPhysTD Physical address of the TD.
1896 */
1897static PVUSBURB ohciTdInFlightUrb(POHCI pThis, uint32_t GCPhysTD)
1898{
1899 int i;
1900
1901 i = ohci_in_flight_find(pThis, GCPhysTD);
1902 if ( i >= 0 )
1903 return pThis->aInFlight[i].pUrb;
1904 return NULL;
1905}
1906
1907/**
1908 * Removes a in-flight TD.
1909 *
1910 * @returns 0 if found. For logged builds this is the number of frames the TD has been in-flight.
1911 * @returns -1 if not found.
1912 * @param pThis OHCI instance data.
1913 * @param GCPhysTD Physical address of the TD.
1914 */
1915static int ohci_in_flight_remove(POHCI pThis, uint32_t GCPhysTD)
1916{
1917 int i = ohci_in_flight_find(pThis, GCPhysTD);
1918 if (i >= 0)
1919 {
1920# ifdef LOG_ENABLED
1921 const int cFramesInFlight = pThis->HcFmNumber - pThis->aInFlight[i].pUrb->pHci->u32FrameNo;
1922# else
1923 const int cFramesInFlight = 0;
1924# endif
1925 Log2(("ohci_in_flight_remove: reaping TD=%#010x %d frames (%#010x-%#010x)\n",
1926 GCPhysTD, cFramesInFlight, pThis->aInFlight[i].pUrb->pHci->u32FrameNo, pThis->HcFmNumber));
1927 pThis->aInFlight[i].GCPhysTD = 0;
1928 pThis->aInFlight[i].pUrb = NULL;
1929 pThis->cInFlight--;
1930 return cFramesInFlight;
1931 }
1932 AssertMsgFailed(("TD %#010x is not in flight\n", GCPhysTD));
1933 return -1;
1934}
1935
1936
1937/**
1938 * Removes all TDs associated with a URB from the in-flight tracking.
1939 *
1940 * @returns 0 if found. For logged builds this is the number of frames the TD has been in-flight.
1941 * @returns -1 if not found.
1942 * @param pThis OHCI instance data.
1943 * @param pUrb The URB.
1944 */
1945static int ohci_in_flight_remove_urb(POHCI pThis, PVUSBURB pUrb)
1946{
1947 int cFramesInFlight = ohci_in_flight_remove(pThis, pUrb->paTds[0].TdAddr);
1948 if (pUrb->pHci->cTds > 1)
1949 {
1950 for (unsigned iTd = 1; iTd < pUrb->pHci->cTds; iTd++)
1951 if (ohci_in_flight_remove(pThis, pUrb->paTds[iTd].TdAddr) < 0)
1952 cFramesInFlight = -1;
1953 }
1954 return cFramesInFlight;
1955}
1956
1957
1958# if defined(VBOX_STRICT) || defined(LOG_ENABLED)
1959
1960/**
1961 * Empties the in-done-queue.
1962 * @param pThis OHCI instance data.
1963 */
1964static void ohci_in_done_queue_zap(POHCI pThis)
1965{
1966 pThis->cInDoneQueue = 0;
1967}
1968
1969/**
1970 * Finds a TD in the in-done-queue.
1971 * @returns >= 0 on success.
1972 * @returns -1 if not found.
1973 * @param pThis OHCI instance data.
1974 * @param GCPhysTD Physical address of the TD.
1975 */
1976static int ohci_in_done_queue_find(POHCI pThis, uint32_t GCPhysTD)
1977{
1978 unsigned i = pThis->cInDoneQueue;
1979 while (i-- > 0)
1980 if (pThis->aInDoneQueue[i].GCPhysTD == GCPhysTD)
1981 return i;
1982 return -1;
1983}
1984
1985/**
1986 * Checks that the specified TD is not in the done queue.
1987 * @param pThis OHCI instance data.
1988 * @param GCPhysTD Physical address of the TD.
1989 */
1990static bool ohci_in_done_queue_check(POHCI pThis, uint32_t GCPhysTD)
1991{
1992 int i = ohci_in_done_queue_find(pThis, GCPhysTD);
1993# if 0
1994 /* This condition has been observed with the USB tablet emulation or with
1995 * a real USB mouse and an SMP XP guest. I am also not sure if this is
1996 * really a problem for us. The assertion checks that the guest doesn't
1997 * re-submit a TD which is still in the done queue. It seems to me that
1998 * this should only be a problem if we either keep track of TDs in the done
1999 * queue somewhere else as well (in which case we should also free those
2000 * references in time, and I can't see any code doing that) or if we
2001 * manipulate TDs in the done queue in some way that might fail if they are
2002 * re-submitted (can't see anything like that either).
2003 */
2004 AssertMsg(i < 0, ("TD %#010x (i=%d)\n", GCPhysTD, i));
2005# endif
2006 return i < 0;
2007}
2008
2009
2010# if defined(VBOX_STRICT) && defined(LOG_ENABLED)
2011/**
2012 * Adds a TD to the in-done-queue tracking, checking that it's not there already.
2013 * @param pThis OHCI instance data.
2014 * @param GCPhysTD Physical address of the TD.
2015 */
2016static void ohci_in_done_queue_add(POHCI pThis, uint32_t GCPhysTD)
2017{
2018 Assert(pThis->cInDoneQueue + 1 <= RT_ELEMENTS(pThis->aInDoneQueue));
2019 if (ohci_in_done_queue_check(pThis, GCPhysTD))
2020 pThis->aInDoneQueue[pThis->cInDoneQueue++].GCPhysTD = GCPhysTD;
2021}
2022# endif /* VBOX_STRICT */
2023# endif /* defined(VBOX_STRICT) || defined(LOG_ENABLED) */
2024
2025
2026/**
2027 * OHCI Transport Buffer - represents a OHCI Transport Descriptor (TD).
2028 * A TD may be split over max 2 pages.
2029 */
2030typedef struct OHCIBUF
2031{
2032 /** Pages involved. */
2033 struct OHCIBUFVEC
2034 {
2035 /** The 32-bit physical address of this part. */
2036 uint32_t Addr;
2037 /** The length. */
2038 uint32_t cb;
2039 } aVecs[2];
2040 /** Number of valid entries in aVecs. */
2041 uint32_t cVecs;
2042 /** The total length. */
2043 uint32_t cbTotal;
2044} OHCIBUF, *POHCIBUF;
2045
2046
2047/**
2048 * Sets up a OHCI transport buffer.
2049 *
2050 * @param pBuf Ohci buffer.
2051 * @param cbp Current buffer pointer. 32-bit physical address.
2052 * @param be Last byte in buffer (BufferEnd). 32-bit physical address.
2053 */
2054static void ohciBufInit(POHCIBUF pBuf, uint32_t cbp, uint32_t be)
2055{
2056 if (!cbp || !be)
2057 {
2058 pBuf->cVecs = 0;
2059 pBuf->cbTotal = 0;
2060 Log2(("ohci: cbp=%#010x be=%#010x cbTotal=0 EMPTY\n", cbp, be));
2061 }
2062 else if ((cbp & ~0xfff) == (be & ~0xfff))
2063 {
2064 pBuf->aVecs[0].Addr = cbp;
2065 pBuf->aVecs[0].cb = (be - cbp) + 1;
2066 pBuf->cVecs = 1;
2067 pBuf->cbTotal = pBuf->aVecs[0].cb;
2068 Log2(("ohci: cbp=%#010x be=%#010x cbTotal=%u\n", cbp, be, pBuf->cbTotal));
2069 }
2070 else
2071 {
2072 pBuf->aVecs[0].Addr = cbp;
2073 pBuf->aVecs[0].cb = 0x1000 - (cbp & 0xfff);
2074 pBuf->aVecs[1].Addr = be & ~0xfff;
2075 pBuf->aVecs[1].cb = (be & 0xfff) + 1;
2076 pBuf->cVecs = 2;
2077 pBuf->cbTotal = pBuf->aVecs[0].cb + pBuf->aVecs[1].cb;
2078 Log2(("ohci: cbp=%#010x be=%#010x cbTotal=%u PAGE FLIP\n", cbp, be, pBuf->cbTotal));
2079 }
2080}
2081
2082/**
2083 * Updates a OHCI transport buffer.
2084 *
2085 * This is called upon completion to adjust the sector lengths if
2086 * the total length has changed. (received less then we had space for
2087 * or a partial transfer.)
2088 *
2089 * @param pBuf The buffer to update. cbTotal contains the new total on input.
2090 * While the aVecs[*].cb members is updated upon return.
2091 */
2092static void ohciBufUpdate(POHCIBUF pBuf)
2093{
2094 for (uint32_t i = 0, cbCur = 0; i < pBuf->cVecs; i++)
2095 {
2096 if (cbCur + pBuf->aVecs[i].cb > pBuf->cbTotal)
2097 {
2098 pBuf->aVecs[i].cb = pBuf->cbTotal - cbCur;
2099 pBuf->cVecs = i + 1;
2100 return;
2101 }
2102 cbCur += pBuf->aVecs[i].cb;
2103 }
2104}
2105
2106
2107/** A worker for ohciUnlinkTds(). */
2108static bool ohciUnlinkIsochronousTdInList(POHCI pThis, uint32_t TdAddr, POHCIITD pITd, POHCIED pEd)
2109{
2110 const uint32_t LastTdAddr = pEd->TailP & ED_PTR_MASK;
2111 Log(("ohciUnlinkIsocTdInList: Unlinking non-head ITD! TdAddr=%#010RX32 HeadTdAddr=%#010RX32 LastEdAddr=%#010RX32\n",
2112 TdAddr, pEd->HeadP & ED_PTR_MASK, LastTdAddr));
2113 AssertMsgReturn(LastTdAddr != TdAddr, ("TdAddr=%#010RX32\n", TdAddr), false);
2114
2115 uint32_t cMax = 256;
2116 uint32_t CurTdAddr = pEd->HeadP & ED_PTR_MASK;
2117 while ( CurTdAddr != LastTdAddr
2118 && cMax-- > 0)
2119 {
2120 OHCIITD ITd;
2121 ohciReadITd(pThis, CurTdAddr, &ITd);
2122 if ((ITd.NextTD & ED_PTR_MASK) == TdAddr)
2123 {
2124 ITd.NextTD = (pITd->NextTD & ED_PTR_MASK) | (ITd.NextTD & ~ED_PTR_MASK);
2125 ohciWriteITd(pThis, CurTdAddr, &ITd, "ohciUnlinkIsocTdInList");
2126 pITd->NextTD &= ~ED_PTR_MASK;
2127 return true;
2128 }
2129
2130 /* next */
2131 CurTdAddr = ITd.NextTD & ED_PTR_MASK;
2132 }
2133
2134 Log(("ohciUnlinkIsocTdInList: TdAddr=%#010RX32 wasn't found in the list!!! (cMax=%d)\n", TdAddr, cMax));
2135 return false;
2136}
2137
2138
2139/** A worker for ohciUnlinkTds(). */
2140static bool ohciUnlinkGeneralTdInList(POHCI pThis, uint32_t TdAddr, POHCITD pTd, POHCIED pEd)
2141{
2142 const uint32_t LastTdAddr = pEd->TailP & ED_PTR_MASK;
2143 Log(("ohciUnlinkGeneralTdInList: Unlinking non-head TD! TdAddr=%#010RX32 HeadTdAddr=%#010RX32 LastEdAddr=%#010RX32\n",
2144 TdAddr, pEd->HeadP & ED_PTR_MASK, LastTdAddr));
2145 AssertMsgReturn(LastTdAddr != TdAddr, ("TdAddr=%#010RX32\n", TdAddr), false);
2146
2147 uint32_t cMax = 256;
2148 uint32_t CurTdAddr = pEd->HeadP & ED_PTR_MASK;
2149 while ( CurTdAddr != LastTdAddr
2150 && cMax-- > 0)
2151 {
2152 OHCITD Td;
2153 ohciReadTd(pThis, CurTdAddr, &Td);
2154 if ((Td.NextTD & ED_PTR_MASK) == TdAddr)
2155 {
2156 Td.NextTD = (pTd->NextTD & ED_PTR_MASK) | (Td.NextTD & ~ED_PTR_MASK);
2157 ohciWriteTd(pThis, CurTdAddr, &Td, "ohciUnlinkGeneralTdInList");
2158 pTd->NextTD &= ~ED_PTR_MASK;
2159 return true;
2160 }
2161
2162 /* next */
2163 CurTdAddr = Td.NextTD & ED_PTR_MASK;
2164 }
2165
2166 Log(("ohciUnlinkGeneralTdInList: TdAddr=%#010RX32 wasn't found in the list!!! (cMax=%d)\n", TdAddr, cMax));
2167 return false;
2168}
2169
2170
2171/**
2172 * Unlinks the TDs that makes up the URB from the ED.
2173 *
2174 * @returns success indicator. true if successfully unlinked.
2175 * @returns false if the TD was not found in the list.
2176 */
2177static bool ohciUnlinkTds(POHCI pThis, PVUSBURB pUrb, POHCIED pEd)
2178{
2179 /*
2180 * Don't unlink more than once.
2181 */
2182 if (pUrb->pHci->fUnlinked)
2183 return true;
2184 pUrb->pHci->fUnlinked = true;
2185
2186 if (pUrb->enmType == VUSBXFERTYPE_ISOC)
2187 {
2188 for (unsigned iTd = 0; iTd < pUrb->pHci->cTds; iTd++)
2189 {
2190 POHCIITD pITd = (POHCIITD)&pUrb->paTds[iTd].TdCopy[0];
2191 const uint32_t ITdAddr = pUrb->paTds[iTd].TdAddr;
2192
2193 /*
2194 * Unlink the TD from the ED list.
2195 * The normal case is that it's at the head of the list.
2196 */
2197 Assert((ITdAddr & ED_PTR_MASK) == ITdAddr);
2198 if ((pEd->HeadP & ED_PTR_MASK) == ITdAddr)
2199 {
2200 pEd->HeadP = (pITd->NextTD & ED_PTR_MASK) | (pEd->HeadP & ~ED_PTR_MASK);
2201 pITd->NextTD &= ~ED_PTR_MASK;
2202 }
2203 else
2204 {
2205 /*
2206 * It's probably somewhere in the list, not a unlikely situation with
2207 * the current isochronous code.
2208 */
2209 if (!ohciUnlinkIsochronousTdInList(pThis, ITdAddr, pITd, pEd))
2210 return false;
2211 }
2212 }
2213 }
2214 else
2215 {
2216 for (unsigned iTd = 0; iTd < pUrb->pHci->cTds; iTd++)
2217 {
2218 POHCITD pTd = (POHCITD)&pUrb->paTds[iTd].TdCopy[0];
2219 const uint32_t TdAddr = pUrb->paTds[iTd].TdAddr;
2220
2221 /** @todo r=bird: Messing with the toggle flag in prepare is probably not correct
2222 * when we encounter a STALL error, 4.3.1.3.7.2: ''If an endpoint returns a STALL
2223 * PID, the Host Controller retires the General TD with the ConditionCode set
2224 * to STALL and halts the endpoint. The CurrentBufferPointer, ErrorCount, and
2225 * dataToggle fields retain the values that they had at the start of the
2226 * transaction.'' */
2227
2228 /* update toggle and set data toggle carry */
2229 pTd->hwinfo &= ~TD_HWINFO_TOGGLE;
2230 if ( pTd->hwinfo & TD_HWINFO_TOGGLE_HI )
2231 {
2232 if ( !!(pTd->hwinfo & TD_HWINFO_TOGGLE_LO) ) /** @todo r=bird: is it just me or doesn't this make sense at all? */
2233 pTd->hwinfo |= TD_HWINFO_TOGGLE_LO;
2234 else
2235 pTd->hwinfo &= ~TD_HWINFO_TOGGLE_LO;
2236 }
2237 else
2238 {
2239 if ( !!(pEd->HeadP & ED_HEAD_CARRY) ) /** @todo r=bird: is it just me or doesn't this make sense at all? */
2240 pEd->HeadP |= ED_HEAD_CARRY;
2241 else
2242 pEd->HeadP &= ~ED_HEAD_CARRY;
2243 }
2244
2245 /*
2246 * Unlink the TD from the ED list.
2247 * The normal case is that it's at the head of the list.
2248 */
2249 Assert((TdAddr & ED_PTR_MASK) == TdAddr);
2250 if ((pEd->HeadP & ED_PTR_MASK) == TdAddr)
2251 {
2252 pEd->HeadP = (pTd->NextTD & ED_PTR_MASK) | (pEd->HeadP & ~ED_PTR_MASK);
2253 pTd->NextTD &= ~ED_PTR_MASK;
2254 }
2255 else
2256 {
2257 /*
2258 * The TD is probably somewhere in the list.
2259 *
2260 * This shouldn't ever happen unless there was a failure! Even on failure,
2261 * we can screw up the HCD state by picking out a TD from within the list
2262 * like this! If this turns out to be a problem, we have to find a better
2263 * solution. For now we'll hope the HCD handles it...
2264 */
2265 if (!ohciUnlinkGeneralTdInList(pThis, TdAddr, pTd, pEd))
2266 return false;
2267 }
2268
2269 /*
2270 * Only unlink the first TD on error.
2271 * See comment in ohciRhXferCompleteGeneralURB().
2272 */
2273 if (pUrb->enmStatus != VUSBSTATUS_OK)
2274 break;
2275 }
2276 }
2277
2278 return true;
2279}
2280
2281
2282/**
2283 * Checks that the transport descriptors associated with the URB
2284 * hasn't been changed in any way indicating that they may have been canceled.
2285 *
2286 * This rountine also updates the TD copies contained within the URB.
2287 *
2288 * @returns true if the URB has been canceled, otherwise false.
2289 * @param pThis The OHCI instance.
2290 * @param pUrb The URB in question.
2291 * @param pEd The ED pointer (optional).
2292 */
2293static bool ohciHasUrbBeenCanceled(POHCI pThis, PVUSBURB pUrb, PCOHCIED pEd)
2294{
2295 if (!pUrb)
2296 return true;
2297
2298 /*
2299 * Make sure we've got an endpoint descriptor so we can
2300 * check for tail TDs.
2301 */
2302 OHCIED Ed;
2303 if (!pEd)
2304 {
2305 ohciReadEd(pThis, pUrb->pHci->EdAddr, &Ed);
2306 pEd = &Ed;
2307 }
2308
2309 if (pUrb->enmType == VUSBXFERTYPE_ISOC)
2310 {
2311 for (unsigned iTd = 0; iTd < pUrb->pHci->cTds; iTd++)
2312 {
2313 union
2314 {
2315 OHCIITD ITd;
2316 uint32_t au32[8];
2317 } u;
2318 if ( (pUrb->paTds[iTd].TdAddr & ED_PTR_MASK)
2319 == (pEd->TailP & ED_PTR_MASK))
2320 {
2321 Log(("%s: ohciHasUrbBeenCanceled: iTd=%d cTds=%d TdAddr=%#010RX32 canceled (tail)! [iso]\n",
2322 pUrb->pszDesc, iTd, pUrb->pHci->cTds, pUrb->paTds[iTd].TdAddr));
2323 STAM_COUNTER_INC(&pThis->StatCanceledIsocUrbs);
2324 return true;
2325 }
2326 ohciReadITd(pThis, pUrb->paTds[iTd].TdAddr, &u.ITd);
2327 if ( u.au32[0] != pUrb->paTds[iTd].TdCopy[0] /* hwinfo */
2328 || u.au32[1] != pUrb->paTds[iTd].TdCopy[1] /* bp0 */
2329 || u.au32[3] != pUrb->paTds[iTd].TdCopy[3] /* be */
2330 || ( u.au32[2] != pUrb->paTds[iTd].TdCopy[2] /* NextTD */
2331 && iTd + 1 < pUrb->pHci->cTds /* ignore the last one */)
2332 || u.au32[4] != pUrb->paTds[iTd].TdCopy[4] /* psw0&1 */
2333 || u.au32[5] != pUrb->paTds[iTd].TdCopy[5] /* psw2&3 */
2334 || u.au32[6] != pUrb->paTds[iTd].TdCopy[6] /* psw4&5 */
2335 || u.au32[7] != pUrb->paTds[iTd].TdCopy[7] /* psw6&7 */
2336 )
2337 {
2338 Log(("%s: ohciHasUrbBeenCanceled: iTd=%d cTds=%d TdAddr=%#010RX32 canceled! [iso]\n",
2339 pUrb->pszDesc, iTd, pUrb->pHci->cTds, pUrb->paTds[iTd].TdAddr));
2340 Log2((" %.*Rhxs (cur)\n"
2341 "!= %.*Rhxs (copy)\n",
2342 sizeof(u.ITd), &u.ITd, sizeof(u.ITd), &pUrb->paTds[iTd].TdCopy[0]));
2343 STAM_COUNTER_INC(&pThis->StatCanceledIsocUrbs);
2344 return true;
2345 }
2346 pUrb->paTds[iTd].TdCopy[2] = u.au32[2];
2347 }
2348 }
2349 else
2350 {
2351 for (unsigned iTd = 0; iTd < pUrb->pHci->cTds; iTd++)
2352 {
2353 union
2354 {
2355 OHCITD Td;
2356 uint32_t au32[4];
2357 } u;
2358 if ( (pUrb->paTds[iTd].TdAddr & ED_PTR_MASK)
2359 == (pEd->TailP & ED_PTR_MASK))
2360 {
2361 Log(("%s: ohciHasUrbBeenCanceled: iTd=%d cTds=%d TdAddr=%#010RX32 canceled (tail)!\n",
2362 pUrb->pszDesc, iTd, pUrb->pHci->cTds, pUrb->paTds[iTd].TdAddr));
2363 STAM_COUNTER_INC(&pThis->StatCanceledGenUrbs);
2364 return true;
2365 }
2366 ohciReadTd(pThis, pUrb->paTds[iTd].TdAddr, &u.Td);
2367 if ( u.au32[0] != pUrb->paTds[iTd].TdCopy[0] /* hwinfo */
2368 || u.au32[1] != pUrb->paTds[iTd].TdCopy[1] /* cbp */
2369 || u.au32[3] != pUrb->paTds[iTd].TdCopy[3] /* be */
2370 || ( u.au32[2] != pUrb->paTds[iTd].TdCopy[2] /* NextTD */
2371 && iTd + 1 < pUrb->pHci->cTds /* ignore the last one */)
2372 )
2373 {
2374 Log(("%s: ohciHasUrbBeenCanceled: iTd=%d cTds=%d TdAddr=%#010RX32 canceled!\n",
2375 pUrb->pszDesc, iTd, pUrb->pHci->cTds, pUrb->paTds[iTd].TdAddr));
2376 Log2((" %.*Rhxs (cur)\n"
2377 "!= %.*Rhxs (copy)\n",
2378 sizeof(u.Td), &u.Td, sizeof(u.Td), &pUrb->paTds[iTd].TdCopy[0]));
2379 STAM_COUNTER_INC(&pThis->StatCanceledGenUrbs);
2380 return true;
2381 }
2382 pUrb->paTds[iTd].TdCopy[2] = u.au32[2];
2383 }
2384 }
2385 return false;
2386}
2387
2388
2389/**
2390 * Returns the OHCI_CC_* corresponding to the VUSB status code.
2391 *
2392 * @returns OHCI_CC_* value.
2393 * @param enmStatus The VUSB status code.
2394 */
2395static uint32_t ohciVUsbStatus2OhciStatus(VUSBSTATUS enmStatus)
2396{
2397 switch (enmStatus)
2398 {
2399 case VUSBSTATUS_OK: return OHCI_CC_NO_ERROR;
2400 case VUSBSTATUS_STALL: return OHCI_CC_STALL;
2401 case VUSBSTATUS_CRC: return OHCI_CC_CRC;
2402 case VUSBSTATUS_DATA_UNDERRUN: return OHCI_CC_DATA_UNDERRUN;
2403 case VUSBSTATUS_DATA_OVERRUN: return OHCI_CC_DATA_OVERRUN;
2404 case VUSBSTATUS_DNR: return OHCI_CC_DNR;
2405 case VUSBSTATUS_NOT_ACCESSED: return OHCI_CC_NOT_ACCESSED_1;
2406 default:
2407 Log(("pUrb->enmStatus=%#x!!!\n", enmStatus));
2408 return OHCI_CC_DNR;
2409 }
2410}
2411
2412/**
2413 * Worker for ohciRhXferCompletion that handles the completion of
2414 * a URB made up of isochronous TDs.
2415 *
2416 * In general, all URBs should have status OK.
2417 */
2418static void ohciRhXferCompleteIsochronousURB(POHCI pThis, PVUSBURB pUrb /*, POHCIED pEd , int cFmAge*/)
2419{
2420 /*
2421 * Copy the data back (if IN operation) and update the TDs.
2422 */
2423 for (unsigned iTd = 0; iTd < pUrb->pHci->cTds; iTd++)
2424 {
2425 POHCIITD pITd = (POHCIITD)&pUrb->paTds[iTd].TdCopy[0];
2426 const uint32_t ITdAddr = pUrb->paTds[iTd].TdAddr;
2427 const unsigned cFrames = ((pITd->HwInfo & ITD_HWINFO_FC) >> ITD_HWINFO_FC_SHIFT) + 1;
2428 unsigned R = (pUrb->pHci->u32FrameNo & ITD_HWINFO_SF) - (pITd->HwInfo & ITD_HWINFO_SF);
2429 if (R >= 8)
2430 R = 0; /* submitted ahead of time. */
2431
2432 /*
2433 * Only one case of TD level condition code is document, so
2434 * just set NO_ERROR here to reduce number duplicate code.
2435 */
2436 pITd->HwInfo &= ~TD_HWINFO_CC;
2437 AssertCompile(OHCI_CC_NO_ERROR == 0);
2438
2439 if (pUrb->enmStatus == VUSBSTATUS_OK)
2440 {
2441 /*
2442 * Update the frames and copy back the data.
2443 * We assume that we don't get incorrect lengths here.
2444 */
2445 for (unsigned i = 0; i < cFrames; i++)
2446 {
2447 if ( i < R
2448 || pUrb->aIsocPkts[i - R].enmStatus == VUSBSTATUS_NOT_ACCESSED)
2449 {
2450 /* It should already be NotAccessed. */
2451 pITd->aPSW[i] |= 0xe000; /* (Don't touch the 12th bit.) */
2452 continue;
2453 }
2454
2455 /* Update the PSW (save the offset first in case of a IN). */
2456 uint32_t off = pITd->aPSW[i] & ITD_PSW_OFFSET;
2457 pITd->aPSW[i] = ohciVUsbStatus2OhciStatus(pUrb->aIsocPkts[i - R].enmStatus)
2458 >> (TD_HWINFO_CC_SHIFT - ITD_PSW_CC_SHIFT);
2459
2460 if ( pUrb->enmDir == VUSBDIRECTION_IN
2461 && ( pUrb->aIsocPkts[i - R].enmStatus == VUSBSTATUS_OK
2462 || pUrb->aIsocPkts[i - R].enmStatus == VUSBSTATUS_DATA_UNDERRUN
2463 || pUrb->aIsocPkts[i - R].enmStatus == VUSBSTATUS_DATA_OVERRUN))
2464 {
2465 /* Set the size. */
2466 const unsigned cb = pUrb->aIsocPkts[i - R].cb;
2467 pITd->aPSW[i] |= cb & ITD_PSW_SIZE;
2468 /* Copy data. */
2469 if (cb)
2470 {
2471 uint8_t *pb = &pUrb->abData[pUrb->aIsocPkts[i - R].off];
2472 if (off + cb > 0x1000)
2473 {
2474 if (off < 0x1000)
2475 {
2476 /* both */
2477 const unsigned cb0 = 0x1000 - off;
2478 ohciPhysWrite(pThis, (pITd->BP0 & ITD_BP0_MASK) + off, pb, cb0);
2479 ohciPhysWrite(pThis, pITd->BE & ITD_BP0_MASK, pb + cb0, cb - cb0);
2480 }
2481 else /* only in the 2nd page */
2482 ohciPhysWrite(pThis, (pITd->BE & ITD_BP0_MASK) + (off & ITD_BP0_MASK), pb, cb);
2483 }
2484 else /* only in the 1st page */
2485 ohciPhysWrite(pThis, (pITd->BP0 & ITD_BP0_MASK) + off, pb, cb);
2486 Log5(("packet %d: off=%#x cb=%#x pb=%p (%#x)\n"
2487 "%.*Rhxd\n",
2488 i + R, off, cb, pb, pb - &pUrb->abData[0], cb, pb));
2489 //off += cb;
2490 }
2491 }
2492 }
2493
2494 /*
2495 * If the last package ended with a NotAccessed status, set ITD CC
2496 * to DataOverrun to indicate scheduling overrun.
2497 */
2498 if (pUrb->aIsocPkts[pUrb->cIsocPkts - 1].enmStatus == VUSBSTATUS_NOT_ACCESSED)
2499 pITd->HwInfo |= OHCI_CC_DATA_OVERRUN;
2500 }
2501 else
2502 {
2503 Log(("DevOHCI: Taking untested code path at line %d...\n", __LINE__));
2504 /*
2505 * Most status codes only applies to the individual packets.
2506 *
2507 * If we get a URB level error code of this kind, we'll distribute
2508 * it to all the packages unless some other status is available for
2509 * a package. This is a bit fuzzy, and we will get rid of this code
2510 * before long!
2511 */
2512 //if (pUrb->enmStatus != VUSBSTATUS_DATA_OVERRUN)
2513 {
2514 const unsigned uCC = ohciVUsbStatus2OhciStatus(pUrb->enmStatus)
2515 >> (TD_HWINFO_CC_SHIFT - ITD_PSW_CC_SHIFT);
2516 for (unsigned i = 0; i < cFrames; i++)
2517 pITd->aPSW[i] = uCC;
2518 }
2519 //else
2520 // pITd->HwInfo |= ohciVUsbStatus2OhciStatus(pUrb->enmStatus);
2521 }
2522
2523 /*
2524 * Update the done queue interrupt timer.
2525 */
2526 uint32_t DoneInt = (pITd->HwInfo & ITD_HWINFO_DI) >> ITD_HWINFO_DI_SHIFT;
2527 if ((pITd->HwInfo & TD_HWINFO_CC) != OHCI_CC_NO_ERROR)
2528 DoneInt = 0; /* It's cleared on error. */
2529 if ( DoneInt != 0x7
2530 && DoneInt < pThis->dqic)
2531 pThis->dqic = DoneInt;
2532
2533 /*
2534 * Move on to the done list and write back the modified TD.
2535 */
2536# ifdef LOG_ENABLED
2537 if (!pThis->done)
2538 pThis->u32FmDoneQueueTail = pThis->HcFmNumber;
2539# ifdef VBOX_STRICT
2540 ohci_in_done_queue_add(pThis, ITdAddr);
2541# endif
2542# endif
2543 pITd->NextTD = pThis->done;
2544 pThis->done = ITdAddr;
2545
2546 Log(("%s: ohciRhXferCompleteIsochronousURB: ITdAddr=%#010x EdAddr=%#010x SF=%#x (%#x) CC=%#x FC=%d "
2547 "psw0=%x:%x psw1=%x:%x psw2=%x:%x psw3=%x:%x psw4=%x:%x psw5=%x:%x psw6=%x:%x psw7=%x:%x R=%d\n",
2548 pUrb->pszDesc, ITdAddr,
2549 pUrb->pHci->EdAddr,
2550 pITd->HwInfo & ITD_HWINFO_SF, pThis->HcFmNumber,
2551 (pITd->HwInfo & ITD_HWINFO_CC) >> ITD_HWINFO_CC_SHIFT,
2552 (pITd->HwInfo & ITD_HWINFO_FC) >> ITD_HWINFO_FC_SHIFT,
2553 pITd->aPSW[0] >> ITD_PSW_CC_SHIFT, pITd->aPSW[0] & ITD_PSW_SIZE,
2554 pITd->aPSW[1] >> ITD_PSW_CC_SHIFT, pITd->aPSW[1] & ITD_PSW_SIZE,
2555 pITd->aPSW[2] >> ITD_PSW_CC_SHIFT, pITd->aPSW[2] & ITD_PSW_SIZE,
2556 pITd->aPSW[3] >> ITD_PSW_CC_SHIFT, pITd->aPSW[3] & ITD_PSW_SIZE,
2557 pITd->aPSW[4] >> ITD_PSW_CC_SHIFT, pITd->aPSW[4] & ITD_PSW_SIZE,
2558 pITd->aPSW[5] >> ITD_PSW_CC_SHIFT, pITd->aPSW[5] & ITD_PSW_SIZE,
2559 pITd->aPSW[6] >> ITD_PSW_CC_SHIFT, pITd->aPSW[6] & ITD_PSW_SIZE,
2560 pITd->aPSW[7] >> ITD_PSW_CC_SHIFT, pITd->aPSW[7] & ITD_PSW_SIZE,
2561 R));
2562 ohciWriteITd(pThis, ITdAddr, pITd, "retired");
2563 }
2564}
2565
2566
2567/**
2568 * Worker for ohciRhXferCompletion that handles the completion of
2569 * a URB made up of general TDs.
2570 */
2571static void ohciRhXferCompleteGeneralURB(POHCI pThis, PVUSBURB pUrb, POHCIED pEd, int cFmAge)
2572{
2573 RT_NOREF(cFmAge);
2574
2575 /*
2576 * Copy the data back (if IN operation) and update the TDs.
2577 */
2578 unsigned cbLeft = pUrb->cbData;
2579 uint8_t *pb = &pUrb->abData[0];
2580 for (unsigned iTd = 0; iTd < pUrb->pHci->cTds; iTd++)
2581 {
2582 POHCITD pTd = (POHCITD)&pUrb->paTds[iTd].TdCopy[0];
2583 const uint32_t TdAddr = pUrb->paTds[iTd].TdAddr;
2584
2585 /*
2586 * Setup a ohci transfer buffer and calc the new cbp value.
2587 */
2588 OHCIBUF Buf;
2589 ohciBufInit(&Buf, pTd->cbp, pTd->be);
2590 uint32_t NewCbp;
2591 if (cbLeft >= Buf.cbTotal)
2592 NewCbp = 0;
2593 else
2594 {
2595 /* (len may have changed for short transfers) */
2596 Buf.cbTotal = cbLeft;
2597 ohciBufUpdate(&Buf);
2598 Assert(Buf.cVecs >= 1);
2599 NewCbp = Buf.aVecs[Buf.cVecs-1].Addr + Buf.aVecs[Buf.cVecs-1].cb;
2600 }
2601
2602 /*
2603 * Write back IN buffers.
2604 */
2605 if ( pUrb->enmDir == VUSBDIRECTION_IN
2606 && ( pUrb->enmStatus == VUSBSTATUS_OK
2607 || pUrb->enmStatus == VUSBSTATUS_DATA_OVERRUN
2608 || pUrb->enmStatus == VUSBSTATUS_DATA_UNDERRUN)
2609 && Buf.cbTotal > 0)
2610 {
2611 Assert(Buf.cVecs > 0);
2612 ohciPhysWrite(pThis, Buf.aVecs[0].Addr, pb, Buf.aVecs[0].cb);
2613 if (Buf.cVecs > 1)
2614 ohciPhysWrite(pThis, Buf.aVecs[1].Addr, pb + Buf.aVecs[0].cb, Buf.aVecs[1].cb);
2615 }
2616
2617 /* advance the data buffer. */
2618 cbLeft -= Buf.cbTotal;
2619 pb += Buf.cbTotal;
2620
2621 /*
2622 * Set writeback field.
2623 */
2624 /* zero out writeback fields for retirement */
2625 pTd->hwinfo &= ~TD_HWINFO_CC;
2626 /* always update the CurrentBufferPointer; essential for underrun/overrun errors */
2627 pTd->cbp = NewCbp;
2628
2629 if (pUrb->enmStatus == VUSBSTATUS_OK)
2630 {
2631 pTd->hwinfo &= ~TD_HWINFO_ERRORS;
2632
2633 /* update done queue interrupt timer */
2634 uint32_t DoneInt = (pTd->hwinfo & TD_HWINFO_DI) >> 21;
2635 if ( DoneInt != 0x7
2636 && DoneInt < pThis->dqic)
2637 pThis->dqic = DoneInt;
2638 Log(("%s: ohciRhXferCompleteGeneralURB: ED=%#010x TD=%#010x Age=%d enmStatus=%d cbTotal=%#x NewCbp=%#010RX32 dqic=%d\n",
2639 pUrb->pszDesc, pUrb->pHci->EdAddr, TdAddr, cFmAge, pUrb->enmStatus, Buf.cbTotal, NewCbp, pThis->dqic));
2640 }
2641 else
2642 {
2643 Log(("%s: ohciRhXferCompleteGeneralURB: HALTED ED=%#010x TD=%#010x (age %d) pUrb->enmStatus=%d\n",
2644 pUrb->pszDesc, pUrb->pHci->EdAddr, TdAddr, cFmAge, pUrb->enmStatus));
2645 pEd->HeadP |= ED_HEAD_HALTED;
2646 pThis->dqic = 0; /* "If the Transfer Descriptor is being retired with an error,
2647 * then the Done Queue Interrupt Counter is cleared as if the
2648 * InterruptDelay field were zero."
2649 */
2650 switch (pUrb->enmStatus)
2651 {
2652 case VUSBSTATUS_STALL:
2653 pTd->hwinfo |= OHCI_CC_STALL;
2654 break;
2655 case VUSBSTATUS_CRC:
2656 pTd->hwinfo |= OHCI_CC_CRC;
2657 break;
2658 case VUSBSTATUS_DATA_UNDERRUN:
2659 pTd->hwinfo |= OHCI_CC_DATA_UNDERRUN;
2660 break;
2661 case VUSBSTATUS_DATA_OVERRUN:
2662 pTd->hwinfo |= OHCI_CC_DATA_OVERRUN;
2663 break;
2664 default: /* what the hell */
2665 Log(("pUrb->enmStatus=%#x!!!\n", pUrb->enmStatus));
2666 /* fall thru */
2667 case VUSBSTATUS_DNR:
2668 pTd->hwinfo |= OHCI_CC_DNR;
2669 break;
2670 }
2671 }
2672
2673 /*
2674 * Move on to the done list and write back the modified TD.
2675 */
2676# ifdef LOG_ENABLED
2677 if (!pThis->done)
2678 pThis->u32FmDoneQueueTail = pThis->HcFmNumber;
2679# ifdef VBOX_STRICT
2680 ohci_in_done_queue_add(pThis, TdAddr);
2681# endif
2682# endif
2683 pTd->NextTD = pThis->done;
2684 pThis->done = TdAddr;
2685
2686 ohciWriteTd(pThis, TdAddr, pTd, "retired");
2687
2688 /*
2689 * If we've halted the endpoint, we stop here.
2690 * ohciUnlinkTds() will make sure we've only unliked the first TD.
2691 *
2692 * The reason for this is that while we can have more than one TD in a URB, real
2693 * OHCI hardware will only deal with one TD at the time and it's therefore incorrect
2694 * to retire TDs after the endpoint has been halted. Win2k will crash or enter infinite
2695 * kernel loop if we don't behave correctly. (See @bugref{1646}.)
2696 */
2697 if (pEd->HeadP & ED_HEAD_HALTED)
2698 break;
2699 }
2700}
2701
2702
2703/**
2704 * Transfer completion callback routine.
2705 *
2706 * VUSB will call this when a transfer have been completed
2707 * in a one or another way.
2708 *
2709 * @param pInterface Pointer to OHCI::ROOTHUB::IRhPort.
2710 * @param pUrb Pointer to the URB in question.
2711 */
2712static DECLCALLBACK(void) ohciRhXferCompletion(PVUSBIROOTHUBPORT pInterface, PVUSBURB pUrb)
2713{
2714 POHCI pThis = VUSBIROOTHUBPORT_2_OHCI(pInterface);
2715 LogFlow(("%s: ohciRhXferCompletion: EdAddr=%#010RX32 cTds=%d TdAddr0=%#010RX32\n",
2716 pUrb->pszDesc, pUrb->pHci->EdAddr, pUrb->pHci->cTds, pUrb->paTds[0].TdAddr));
2717
2718 RTCritSectEnter(&pThis->CritSect);
2719 pThis->fIdle = false; /* Mark as active */
2720
2721 /* get the current end point descriptor. */
2722 OHCIED Ed;
2723 ohciReadEd(pThis, pUrb->pHci->EdAddr, &Ed);
2724
2725 /*
2726 * Check that the URB hasn't been canceled and then try unlink the TDs.
2727 *
2728 * We drop the URB if the ED is marked halted/skip ASSUMING that this
2729 * means the HCD has canceled the URB.
2730 *
2731 * If we succeed here (i.e. not dropping the URB), the TdCopy members will
2732 * be updated but not yet written. We will delay the writing till we're done
2733 * with the data copying, buffer pointer advancing and error handling.
2734 */
2735 int cFmAge = ohci_in_flight_remove_urb(pThis, pUrb);
2736 if (pUrb->enmStatus == VUSBSTATUS_UNDO)
2737 {
2738 /* Leave the TD alone - the HCD doesn't want us talking to the device. */
2739 Log(("%s: ohciRhXferCompletion: CANCELED {ED=%#010x cTds=%d TD0=%#010x age %d}\n",
2740 pUrb->pszDesc, pUrb->pHci->EdAddr, pUrb->pHci->cTds, pUrb->paTds[0].TdAddr, cFmAge));
2741 STAM_COUNTER_INC(&pThis->StatDroppedUrbs);
2742 RTCritSectLeave(&pThis->CritSect);
2743 return;
2744 }
2745 bool fHasBeenCanceled = false;
2746 if ( (Ed.HeadP & ED_HEAD_HALTED)
2747 || (Ed.hwinfo & ED_HWINFO_SKIP)
2748 || cFmAge < 0
2749 || (fHasBeenCanceled = ohciHasUrbBeenCanceled(pThis, pUrb, &Ed))
2750 || !ohciUnlinkTds(pThis, pUrb, &Ed)
2751 )
2752 {
2753 Log(("%s: ohciRhXferCompletion: DROPPED {ED=%#010x cTds=%d TD0=%#010x age %d} because:%s%s%s%s%s!!!\n",
2754 pUrb->pszDesc, pUrb->pHci->EdAddr, pUrb->pHci->cTds, pUrb->paTds[0].TdAddr, cFmAge,
2755 (Ed.HeadP & ED_HEAD_HALTED) ? " ep halted" : "",
2756 (Ed.hwinfo & ED_HWINFO_SKIP) ? " ep skip" : "",
2757 (Ed.HeadP & ED_PTR_MASK) != pUrb->paTds[0].TdAddr ? " ep head-changed" : "",
2758 cFmAge < 0 ? " td not-in-flight" : "",
2759 fHasBeenCanceled ? " td canceled" : ""));
2760 NOREF(fHasBeenCanceled);
2761 STAM_COUNTER_INC(&pThis->StatDroppedUrbs);
2762 RTCritSectLeave(&pThis->CritSect);
2763 return;
2764 }
2765
2766 /*
2767 * Complete the TD updating and write the back.
2768 * When appropriate also copy data back to the guest memory.
2769 */
2770 if (pUrb->enmType == VUSBXFERTYPE_ISOC)
2771 ohciRhXferCompleteIsochronousURB(pThis, pUrb /*, &Ed , cFmAge*/);
2772 else
2773 ohciRhXferCompleteGeneralURB(pThis, pUrb, &Ed, cFmAge);
2774
2775 /* finally write back the endpoint descriptor. */
2776 ohciWriteEd(pThis, pUrb->pHci->EdAddr, &Ed);
2777
2778 RTCritSectLeave(&pThis->CritSect);
2779}
2780
2781
2782/**
2783 * Handle transfer errors.
2784 *
2785 * VUSB calls this when a transfer attempt failed. This function will respond
2786 * indicating whether to retry or complete the URB with failure.
2787 *
2788 * @returns true if the URB should be retired.
2789 * @returns false if the URB should be retried.
2790 * @param pInterface Pointer to OHCI::ROOTHUB::IRhPort.
2791 * @param pUrb Pointer to the URB in question.
2792 */
2793static DECLCALLBACK(bool) ohciRhXferError(PVUSBIROOTHUBPORT pInterface, PVUSBURB pUrb)
2794{
2795 POHCI pThis = VUSBIROOTHUBPORT_2_OHCI(pInterface);
2796
2797 /*
2798 * Isochronous URBs can't be retried.
2799 */
2800 if (pUrb->enmType == VUSBXFERTYPE_ISOC)
2801 return true;
2802
2803 /*
2804 * Don't retry on stall.
2805 */
2806 if (pUrb->enmStatus == VUSBSTATUS_STALL)
2807 {
2808 Log2(("%s: ohciRhXferError: STALL, giving up.\n", pUrb->pszDesc));
2809 return true;
2810 }
2811
2812 RTCritSectEnter(&pThis->CritSect);
2813
2814 bool fRetire = false;
2815 /*
2816 * Check if the TDs still are valid.
2817 * This will make sure the TdCopy is up to date.
2818 */
2819 const uint32_t TdAddr = pUrb->paTds[0].TdAddr;
2820/** @todo IMPORTANT! we must check if the ED is still valid at this point!!! */
2821 if (ohciHasUrbBeenCanceled(pThis, pUrb, NULL))
2822 {
2823 Log(("%s: ohciRhXferError: TdAddr0=%#x canceled!\n", pUrb->pszDesc, TdAddr));
2824 fRetire = true;
2825 }
2826 else
2827 {
2828 /*
2829 * Get and update the error counter.
2830 */
2831 POHCITD pTd = (POHCITD)&pUrb->paTds[0].TdCopy[0];
2832 unsigned cErrs = (pTd->hwinfo & TD_HWINFO_ERRORS) >> TD_ERRORS_SHIFT;
2833 pTd->hwinfo &= ~TD_HWINFO_ERRORS;
2834 cErrs++;
2835 pTd->hwinfo |= (cErrs % TD_ERRORS_MAX) << TD_ERRORS_SHIFT;
2836 ohciWriteTd(pThis, TdAddr, pTd, "ohciRhXferError");
2837
2838 if (cErrs >= TD_ERRORS_MAX - 1)
2839 {
2840 Log2(("%s: ohciRhXferError: too many errors, giving up!\n", pUrb->pszDesc));
2841 fRetire = true;
2842 }
2843 else
2844 Log2(("%s: ohciRhXferError: cErrs=%d: retrying...\n", pUrb->pszDesc, cErrs));
2845 }
2846
2847 RTCritSectLeave(&pThis->CritSect);
2848 return fRetire;
2849}
2850
2851
2852/**
2853 * Service a general transport descriptor.
2854 */
2855static bool ohciServiceTd(POHCI pThis, VUSBXFERTYPE enmType, PCOHCIED pEd, uint32_t EdAddr, uint32_t TdAddr,
2856 uint32_t *pNextTdAddr, const char *pszListName)
2857{
2858 RT_NOREF(pszListName);
2859
2860 /*
2861 * Read the TD and setup the buffer data.
2862 */
2863 OHCITD Td;
2864 ohciReadTd(pThis, TdAddr, &Td);
2865 OHCIBUF Buf;
2866 ohciBufInit(&Buf, Td.cbp, Td.be);
2867
2868 *pNextTdAddr = Td.NextTD & ED_PTR_MASK;
2869
2870 /*
2871 * Determine the direction.
2872 */
2873 VUSBDIRECTION enmDir;
2874 switch (pEd->hwinfo & ED_HWINFO_DIR)
2875 {
2876 case ED_HWINFO_OUT: enmDir = VUSBDIRECTION_OUT; break;
2877 case ED_HWINFO_IN: enmDir = VUSBDIRECTION_IN; break;
2878 default:
2879 switch (Td.hwinfo & TD_HWINFO_DIR)
2880 {
2881 case TD_HWINFO_OUT: enmDir = VUSBDIRECTION_OUT; break;
2882 case TD_HWINFO_IN: enmDir = VUSBDIRECTION_IN; break;
2883 case 0: enmDir = VUSBDIRECTION_SETUP; break;
2884 default:
2885 Log(("ohciServiceTd: Invalid direction!!!! Td.hwinfo=%#x Ed.hwdinfo=%#x\n", Td.hwinfo, pEd->hwinfo));
2886 /** @todo Do the correct thing here */
2887 return false;
2888 }
2889 break;
2890 }
2891
2892 pThis->fIdle = false; /* Mark as active */
2893
2894 /*
2895 * Allocate and initialize a new URB.
2896 */
2897 PVUSBURB pUrb = VUSBIRhNewUrb(pThis->RootHub.pIRhConn, pEd->hwinfo & ED_HWINFO_FUNCTION, NULL,
2898 enmType, enmDir, Buf.cbTotal, 1, NULL);
2899 if (!pUrb)
2900 return false; /* retry later... */
2901
2902 pUrb->EndPt = (pEd->hwinfo & ED_HWINFO_ENDPOINT) >> ED_HWINFO_ENDPOINT_SHIFT;
2903 pUrb->fShortNotOk = !(Td.hwinfo & TD_HWINFO_ROUNDING);
2904 pUrb->enmStatus = VUSBSTATUS_OK;
2905 pUrb->pHci->EdAddr = EdAddr;
2906 pUrb->pHci->fUnlinked = false;
2907 pUrb->pHci->cTds = 1;
2908 pUrb->paTds[0].TdAddr = TdAddr;
2909 pUrb->pHci->u32FrameNo = pThis->HcFmNumber;
2910 AssertCompile(sizeof(pUrb->paTds[0].TdCopy) >= sizeof(Td));
2911 memcpy(pUrb->paTds[0].TdCopy, &Td, sizeof(Td));
2912
2913 /* copy data if out bound transfer. */
2914 pUrb->cbData = Buf.cbTotal;
2915 if ( Buf.cbTotal
2916 && Buf.cVecs > 0
2917 && enmDir != VUSBDIRECTION_IN)
2918 {
2919 ohciPhysRead(pThis, Buf.aVecs[0].Addr, pUrb->abData, Buf.aVecs[0].cb);
2920 if (Buf.cVecs > 1)
2921 ohciPhysRead(pThis, Buf.aVecs[1].Addr, &pUrb->abData[Buf.aVecs[0].cb], Buf.aVecs[1].cb);
2922 }
2923
2924 /*
2925 * Submit the URB.
2926 */
2927 ohci_in_flight_add(pThis, TdAddr, pUrb);
2928 Log(("%s: ohciServiceTd: submitting TdAddr=%#010x EdAddr=%#010x cbData=%#x\n",
2929 pUrb->pszDesc, TdAddr, EdAddr, pUrb->cbData));
2930
2931 RTCritSectLeave(&pThis->CritSect);
2932 int rc = VUSBIRhSubmitUrb(pThis->RootHub.pIRhConn, pUrb, &pThis->RootHub.Led);
2933 RTCritSectEnter(&pThis->CritSect);
2934 if (RT_SUCCESS(rc))
2935 return true;
2936
2937 /* Failure cleanup. Can happen if we're still resetting the device or out of resources. */
2938 Log(("ohciServiceTd: failed submitting TdAddr=%#010x EdAddr=%#010x pUrb=%p!!\n",
2939 TdAddr, EdAddr, pUrb));
2940 ohci_in_flight_remove(pThis, TdAddr);
2941 return false;
2942}
2943
2944
2945/**
2946 * Service a the head TD of an endpoint.
2947 */
2948static bool ohciServiceHeadTd(POHCI pThis, VUSBXFERTYPE enmType, PCOHCIED pEd, uint32_t EdAddr, const char *pszListName)
2949{
2950 /*
2951 * Read the TD, after first checking if it's already in-flight.
2952 */
2953 uint32_t TdAddr = pEd->HeadP & ED_PTR_MASK;
2954 if (ohciIsTdInFlight(pThis, TdAddr))
2955 return false;
2956# if defined(VBOX_STRICT) || defined(LOG_ENABLED)
2957 ohci_in_done_queue_check(pThis, TdAddr);
2958# endif
2959 return ohciServiceTd(pThis, enmType, pEd, EdAddr, TdAddr, &TdAddr, pszListName);
2960}
2961
2962
2963/**
2964 * Service one or more general transport descriptors (bulk or interrupt).
2965 */
2966static bool ohciServiceTdMultiple(POHCI pThis, VUSBXFERTYPE enmType, PCOHCIED pEd, uint32_t EdAddr,
2967 uint32_t TdAddr, uint32_t *pNextTdAddr, const char *pszListName)
2968{
2969 RT_NOREF(pszListName);
2970
2971 /*
2972 * Read the TDs involved in this URB.
2973 */
2974 struct OHCITDENTRY
2975 {
2976 /** The TD. */
2977 OHCITD Td;
2978 /** The associated OHCI buffer tracker. */
2979 OHCIBUF Buf;
2980 /** The TD address. */
2981 uint32_t TdAddr;
2982 /** Pointer to the next element in the chain (stack). */
2983 struct OHCITDENTRY *pNext;
2984 } Head;
2985
2986# ifdef VBOX_WITH_OHCI_PHYS_READ_CACHE
2987 ohciPhysReadCacheClear(pThis->pCacheTD);
2988# endif
2989
2990 /* read the head */
2991# ifdef VBOX_WITH_OHCI_PHYS_READ_CACHE
2992 ohciReadTdCached(pThis, TdAddr, &Head.Td);
2993# else
2994 ohciReadTd(pThis, TdAddr, &Head.Td);
2995# endif
2996 ohciBufInit(&Head.Buf, Head.Td.cbp, Head.Td.be);
2997 Head.TdAddr = TdAddr;
2998 Head.pNext = NULL;
2999
3000 /* combine with more TDs. */
3001 struct OHCITDENTRY *pTail = &Head;
3002 unsigned cbTotal = pTail->Buf.cbTotal;
3003 unsigned cTds = 1;
3004 while ( (pTail->Buf.cbTotal == 0x1000 || pTail->Buf.cbTotal == 0x2000)
3005 && !(pTail->Td.hwinfo & TD_HWINFO_ROUNDING) /* This isn't right for *BSD, but let's not . */
3006 && (pTail->Td.NextTD & ED_PTR_MASK) != (pEd->TailP & ED_PTR_MASK)
3007 && cTds < 128)
3008 {
3009 struct OHCITDENTRY *pCur = (struct OHCITDENTRY *)alloca(sizeof(*pCur));
3010
3011 pCur->pNext = NULL;
3012 pCur->TdAddr = pTail->Td.NextTD & ED_PTR_MASK;
3013# ifdef VBOX_WITH_OHCI_PHYS_READ_CACHE
3014 ohciReadTdCached(pThis, pCur->TdAddr, &pCur->Td);
3015# else
3016 ohciReadTd(pThis, pCur->TdAddr, &pCur->Td);
3017# endif
3018 ohciBufInit(&pCur->Buf, pCur->Td.cbp, pCur->Td.be);
3019
3020 /* Don't combine if the direction doesn't match up. There can't actually be
3021 * a mismatch for bulk/interrupt EPs unless the guest is buggy.
3022 */
3023 if ( (pCur->Td.hwinfo & (TD_HWINFO_DIR))
3024 != (Head.Td.hwinfo & (TD_HWINFO_DIR)))
3025 break;
3026
3027 pTail->pNext = pCur;
3028 pTail = pCur;
3029 cbTotal += pCur->Buf.cbTotal;
3030 cTds++;
3031 }
3032
3033 /* calc next TD address */
3034 *pNextTdAddr = pTail->Td.NextTD & ED_PTR_MASK;
3035
3036 /*
3037 * Determine the direction.
3038 */
3039 VUSBDIRECTION enmDir;
3040 switch (pEd->hwinfo & ED_HWINFO_DIR)
3041 {
3042 case ED_HWINFO_OUT: enmDir = VUSBDIRECTION_OUT; break;
3043 case ED_HWINFO_IN: enmDir = VUSBDIRECTION_IN; break;
3044 default:
3045 Log(("ohciServiceTdMultiple: WARNING! Ed.hwdinfo=%#x bulk or interrupt EP shouldn't rely on the TD for direction...\n", pEd->hwinfo));
3046 switch (Head.Td.hwinfo & TD_HWINFO_DIR)
3047 {
3048 case TD_HWINFO_OUT: enmDir = VUSBDIRECTION_OUT; break;
3049 case TD_HWINFO_IN: enmDir = VUSBDIRECTION_IN; break;
3050 default:
3051 Log(("ohciServiceTdMultiple: Invalid direction!!!! Head.Td.hwinfo=%#x Ed.hwdinfo=%#x\n", Head.Td.hwinfo, pEd->hwinfo));
3052 /** @todo Do the correct thing here */
3053 return false;
3054 }
3055 break;
3056 }
3057
3058 pThis->fIdle = false; /* Mark as active */
3059
3060 /*
3061 * Allocate and initialize a new URB.
3062 */
3063 PVUSBURB pUrb = VUSBIRhNewUrb(pThis->RootHub.pIRhConn, pEd->hwinfo & ED_HWINFO_FUNCTION, NULL,
3064 enmType, enmDir, cbTotal, cTds, "ohciServiceTdMultiple");
3065 if (!pUrb)
3066 /* retry later... */
3067 return false;
3068 Assert(pUrb->cbData == cbTotal);
3069
3070 pUrb->enmType = enmType;
3071 pUrb->EndPt = (pEd->hwinfo & ED_HWINFO_ENDPOINT) >> ED_HWINFO_ENDPOINT_SHIFT;
3072 pUrb->enmDir = enmDir;
3073 pUrb->fShortNotOk = !(pTail->Td.hwinfo & TD_HWINFO_ROUNDING);
3074 pUrb->enmStatus = VUSBSTATUS_OK;
3075 pUrb->pHci->cTds = cTds;
3076 pUrb->pHci->EdAddr = EdAddr;
3077 pUrb->pHci->fUnlinked = false;
3078 pUrb->pHci->u32FrameNo = pThis->HcFmNumber;
3079
3080 /* Copy data and TD information. */
3081 unsigned iTd = 0;
3082 uint8_t *pb = &pUrb->abData[0];
3083 for (struct OHCITDENTRY *pCur = &Head; pCur; pCur = pCur->pNext, iTd++)
3084 {
3085 /* data */
3086 if ( cbTotal
3087 && enmDir != VUSBDIRECTION_IN
3088 && pCur->Buf.cVecs > 0)
3089 {
3090 ohciPhysRead(pThis, pCur->Buf.aVecs[0].Addr, pb, pCur->Buf.aVecs[0].cb);
3091 if (pCur->Buf.cVecs > 1)
3092 ohciPhysRead(pThis, pCur->Buf.aVecs[1].Addr, pb + pCur->Buf.aVecs[0].cb, pCur->Buf.aVecs[1].cb);
3093 }
3094 pb += pCur->Buf.cbTotal;
3095
3096 /* TD info */
3097 pUrb->paTds[iTd].TdAddr = pCur->TdAddr;
3098 AssertCompile(sizeof(pUrb->paTds[iTd].TdCopy) >= sizeof(pCur->Td));
3099 memcpy(pUrb->paTds[iTd].TdCopy, &pCur->Td, sizeof(pCur->Td));
3100 }
3101
3102 /*
3103 * Submit the URB.
3104 */
3105 ohci_in_flight_add_urb(pThis, pUrb);
3106 Log(("%s: ohciServiceTdMultiple: submitting cbData=%#x EdAddr=%#010x cTds=%d TdAddr0=%#010x\n",
3107 pUrb->pszDesc, pUrb->cbData, EdAddr, cTds, TdAddr));
3108 RTCritSectLeave(&pThis->CritSect);
3109 int rc = VUSBIRhSubmitUrb(pThis->RootHub.pIRhConn, pUrb, &pThis->RootHub.Led);
3110 RTCritSectEnter(&pThis->CritSect);
3111 if (RT_SUCCESS(rc))
3112 return true;
3113
3114 /* Failure cleanup. Can happen if we're still resetting the device or out of resources. */
3115 Log(("ohciServiceTdMultiple: failed submitting pUrb=%p cbData=%#x EdAddr=%#010x cTds=%d TdAddr0=%#010x - rc=%Rrc\n",
3116 pUrb, cbTotal, EdAddr, cTds, TdAddr, rc));
3117 for (struct OHCITDENTRY *pCur = &Head; pCur; pCur = pCur->pNext, iTd++)
3118 ohci_in_flight_remove(pThis, pCur->TdAddr);
3119 return false;
3120}
3121
3122
3123/**
3124 * Service the head TD of an endpoint.
3125 */
3126static bool ohciServiceHeadTdMultiple(POHCI pThis, VUSBXFERTYPE enmType, PCOHCIED pEd, uint32_t EdAddr, const char *pszListName)
3127{
3128 /*
3129 * First, check that it's not already in-flight.
3130 */
3131 uint32_t TdAddr = pEd->HeadP & ED_PTR_MASK;
3132 if (ohciIsTdInFlight(pThis, TdAddr))
3133 return false;
3134# if defined(VBOX_STRICT) || defined(LOG_ENABLED)
3135 ohci_in_done_queue_check(pThis, TdAddr);
3136# endif
3137 return ohciServiceTdMultiple(pThis, enmType, pEd, EdAddr, TdAddr, &TdAddr, pszListName);
3138}
3139
3140
3141/**
3142 * A worker for ohciServiceIsochronousEndpoint which unlinks a ITD
3143 * that belongs to the past.
3144 */
3145static bool ohciServiceIsochronousTdUnlink(POHCI pThis, POHCIITD pITd, uint32_t ITdAddr, uint32_t ITdAddrPrev,
3146 PVUSBURB pUrb, POHCIED pEd, uint32_t EdAddr)
3147{
3148 LogFlow(("%s%sohciServiceIsochronousTdUnlink: Unlinking ITD: ITdAddr=%#010x EdAddr=%#010x ITdAddrPrev=%#010x\n",
3149 pUrb ? pUrb->pszDesc : "", pUrb ? ": " : "", ITdAddr, EdAddr, ITdAddrPrev));
3150
3151 /*
3152 * Do the unlinking.
3153 */
3154 const uint32_t ITdAddrNext = pITd->NextTD & ED_PTR_MASK;
3155 if (ITdAddrPrev)
3156 {
3157 /* Get validate the previous TD */
3158 int iInFlightPrev = ohci_in_flight_find(pThis, ITdAddrPrev);
3159 AssertMsgReturn(iInFlightPrev >= 0, ("ITdAddr=%#RX32\n", ITdAddrPrev), false);
3160 PVUSBURB pUrbPrev = pThis->aInFlight[iInFlightPrev].pUrb;
3161 if (ohciHasUrbBeenCanceled(pThis, pUrbPrev, pEd)) /* ensures the copy is correct. */
3162 return false;
3163
3164 /* Update the copy and write it back. */
3165 POHCIITD pITdPrev = ((POHCIITD)pUrbPrev->paTds[0].TdCopy);
3166 pITdPrev->NextTD = (pITdPrev->NextTD & ~ED_PTR_MASK) | ITdAddrNext;
3167 ohciWriteITd(pThis, ITdAddrPrev, pITdPrev, "ohciServiceIsochronousEndpoint");
3168 }
3169 else
3170 {
3171 /* It's the head node. update the copy from the caller and write it back. */
3172 pEd->HeadP = (pEd->HeadP & ~ED_PTR_MASK) | ITdAddrNext;
3173 ohciWriteEd(pThis, EdAddr, pEd);
3174 }
3175
3176 /*
3177 * If it's in flight, just mark the URB as unlinked (there is only one ITD per URB atm).
3178 * Otherwise, retire it to the done queue with an error and cause a done line interrupt (?).
3179 */
3180 if (pUrb)
3181 {
3182 pUrb->pHci->fUnlinked = true;
3183 if (ohciHasUrbBeenCanceled(pThis, pUrb, pEd)) /* ensures the copy is correct (paranoia). */
3184 return false;
3185
3186 POHCIITD pITdCopy = ((POHCIITD)pUrb->paTds[0].TdCopy);
3187 pITd->NextTD = pITdCopy->NextTD &= ~ED_PTR_MASK;
3188 }
3189 else
3190 {
3191 pITd->HwInfo &= ~ITD_HWINFO_CC;
3192 pITd->HwInfo |= OHCI_CC_DATA_OVERRUN;
3193
3194 pITd->NextTD = pThis->done;
3195 pThis->done = ITdAddr;
3196
3197 pThis->dqic = 0;
3198 }
3199
3200 ohciWriteITd(pThis, ITdAddr, pITd, "ohciServiceIsochronousTdUnlink");
3201 return true;
3202}
3203
3204
3205/**
3206 * A worker for ohciServiceIsochronousEndpoint which submits the specified TD.
3207 *
3208 * @returns true on success.
3209 * @returns false on failure to submit.
3210 * @param pThis The OHCI controller instance data.
3211 * @param pITd The transfer descriptor to service.
3212 * @param ITdAddr The address of the transfer descriptor in gues memory.
3213 * @param R The start packet (frame) relative to the start of frame in HwInfo.
3214 * @param pEd The OHCI endpoint descriptor.
3215 * @param EdAddr The endpoint descriptor address in guest memory.
3216 */
3217static bool ohciServiceIsochronousTd(POHCI pThis, POHCIITD pITd, uint32_t ITdAddr, const unsigned R, PCOHCIED pEd, uint32_t EdAddr)
3218{
3219 /*
3220 * Determine the endpoint direction.
3221 */
3222 VUSBDIRECTION enmDir;
3223 switch (pEd->hwinfo & ED_HWINFO_DIR)
3224 {
3225 case ED_HWINFO_OUT: enmDir = VUSBDIRECTION_OUT; break;
3226 case ED_HWINFO_IN: enmDir = VUSBDIRECTION_IN; break;
3227 default:
3228 Log(("ohciServiceIsochronousTd: Invalid direction!!!! Ed.hwdinfo=%#x\n", pEd->hwinfo));
3229 /* Should probably raise an unrecoverable HC error here */
3230 return false;
3231 }
3232
3233 /*
3234 * Extract the packet sizes and calc the total URB size.
3235 */
3236 struct
3237 {
3238 uint16_t cb;
3239 uint16_t off;
3240 } aPkts[ITD_NUM_PSW];
3241
3242 /* first entry (R) */
3243 uint32_t cbTotal = 0;
3244 if (((uint32_t)pITd->aPSW[R] >> ITD_PSW_CC_SHIFT) < (OHCI_CC_NOT_ACCESSED_0 >> TD_HWINFO_CC_SHIFT))
3245 Log(("ITdAddr=%RX32 PSW%d.CC=%#x < 'Not Accessed'!\n", ITdAddr, R, pITd->aPSW[R] >> ITD_PSW_CC_SHIFT)); /* => Unrecoverable Error*/
3246 uint16_t offPrev = aPkts[0].off = (pITd->aPSW[R] & ITD_PSW_OFFSET);
3247
3248 /* R+1..cFrames */
3249 const unsigned cFrames = ((pITd->HwInfo & ITD_HWINFO_FC) >> ITD_HWINFO_FC_SHIFT) + 1;
3250 for (unsigned iR = R + 1; iR < cFrames; iR++)
3251 {
3252 const uint16_t PSW = pITd->aPSW[iR];
3253 const uint16_t off = aPkts[iR - R].off = (PSW & ITD_PSW_OFFSET);
3254 cbTotal += aPkts[iR - R - 1].cb = off - offPrev;
3255 if (off < offPrev)
3256 Log(("ITdAddr=%RX32 PSW%d.offset=%#x < offPrev=%#x!\n", ITdAddr, iR, off, offPrev)); /* => Unrecoverable Error*/
3257 if (((uint32_t)PSW >> ITD_PSW_CC_SHIFT) < (OHCI_CC_NOT_ACCESSED_0 >> TD_HWINFO_CC_SHIFT))
3258 Log(("ITdAddr=%RX32 PSW%d.CC=%#x < 'Not Accessed'!\n", ITdAddr, iR, PSW >> ITD_PSW_CC_SHIFT)); /* => Unrecoverable Error*/
3259 offPrev = off;
3260 }
3261
3262 /* calc offEnd and figure out the size of the last packet. */
3263 const uint32_t offEnd = (pITd->BE & 0xfff)
3264 + (((pITd->BE & ITD_BP0_MASK) != (pITd->BP0 & ITD_BP0_MASK)) << 12)
3265 + 1 /* BE is inclusive */;
3266 if (offEnd < offPrev)
3267 Log(("ITdAddr=%RX32 offEnd=%#x < offPrev=%#x!\n", ITdAddr, offEnd, offPrev)); /* => Unrecoverable Error*/
3268 cbTotal += aPkts[cFrames - 1 - R].cb = offEnd - offPrev;
3269 Assert(cbTotal <= 0x2000);
3270
3271 pThis->fIdle = false; /* Mark as active */
3272
3273 /*
3274 * Allocate and initialize a new URB.
3275 */
3276 PVUSBURB pUrb = VUSBIRhNewUrb(pThis->RootHub.pIRhConn, pEd->hwinfo & ED_HWINFO_FUNCTION, NULL,
3277 VUSBXFERTYPE_ISOC, enmDir, cbTotal, 1, NULL);
3278 if (!pUrb)
3279 /* retry later... */
3280 return false;
3281
3282 pUrb->EndPt = (pEd->hwinfo & ED_HWINFO_ENDPOINT) >> ED_HWINFO_ENDPOINT_SHIFT;
3283 pUrb->fShortNotOk = false;
3284 pUrb->enmStatus = VUSBSTATUS_OK;
3285 pUrb->pHci->EdAddr = EdAddr;
3286 pUrb->pHci->cTds = 1;
3287 pUrb->pHci->fUnlinked = false;
3288 pUrb->pHci->u32FrameNo = pThis->HcFmNumber;
3289 pUrb->paTds[0].TdAddr = ITdAddr;
3290 AssertCompile(sizeof(pUrb->paTds[0].TdCopy) >= sizeof(*pITd));
3291 memcpy(pUrb->paTds[0].TdCopy, pITd, sizeof(*pITd));
3292# if 0 /* color the data */
3293 memset(pUrb->abData, 0xfe, cbTotal);
3294# endif
3295
3296 /* copy the data */
3297 if ( cbTotal
3298 && enmDir != VUSBDIRECTION_IN)
3299 {
3300 const uint32_t off0 = pITd->aPSW[R] & ITD_PSW_OFFSET;
3301 if (off0 < 0x1000)
3302 {
3303 if (offEnd > 0x1000)
3304 {
3305 /* both pages. */
3306 const unsigned cb0 = 0x1000 - off0;
3307 ohciPhysRead(pThis, (pITd->BP0 & ITD_BP0_MASK) + off0, &pUrb->abData[0], cb0);
3308 ohciPhysRead(pThis, pITd->BE & ITD_BP0_MASK, &pUrb->abData[cb0], offEnd & 0xfff);
3309 }
3310 else /* a portion of the 1st page. */
3311 ohciPhysRead(pThis, (pITd->BP0 & ITD_BP0_MASK) + off0, pUrb->abData, offEnd - off0);
3312 }
3313 else /* a portion of the 2nd page. */
3314 ohciPhysRead(pThis, (pITd->BE & UINT32_C(0xfffff000)) + (off0 & 0xfff), pUrb->abData, cbTotal);
3315 }
3316
3317 /* setup the packets */
3318 pUrb->cIsocPkts = cFrames - R;
3319 unsigned off = 0;
3320 for (unsigned i = 0; i < pUrb->cIsocPkts; i++)
3321 {
3322 pUrb->aIsocPkts[i].enmStatus = VUSBSTATUS_NOT_ACCESSED;
3323 pUrb->aIsocPkts[i].off = off;
3324 off += pUrb->aIsocPkts[i].cb = aPkts[i].cb;
3325 }
3326 Assert(off == cbTotal);
3327
3328 /*
3329 * Submit the URB.
3330 */
3331 ohci_in_flight_add_urb(pThis, pUrb);
3332 Log(("%s: ohciServiceIsochronousTd: submitting cbData=%#x cIsocPkts=%d EdAddr=%#010x TdAddr=%#010x SF=%#x (%#x)\n",
3333 pUrb->pszDesc, pUrb->cbData, pUrb->cIsocPkts, EdAddr, ITdAddr, pITd->HwInfo & ITD_HWINFO_SF, pThis->HcFmNumber));
3334 RTCritSectLeave(&pThis->CritSect);
3335 int rc = VUSBIRhSubmitUrb(pThis->RootHub.pIRhConn, pUrb, &pThis->RootHub.Led);
3336 RTCritSectEnter(&pThis->CritSect);
3337 if (RT_SUCCESS(rc))
3338 return true;
3339
3340 /* Failure cleanup. Can happen if we're still resetting the device or out of resources. */
3341 Log(("ohciServiceIsochronousTd: failed submitting pUrb=%p cbData=%#x EdAddr=%#010x cTds=%d ITdAddr0=%#010x - rc=%Rrc\n",
3342 pUrb, cbTotal, EdAddr, 1, ITdAddr, rc));
3343 ohci_in_flight_remove(pThis, ITdAddr);
3344 return false;
3345}
3346
3347
3348/**
3349 * Service an isochronous endpoint.
3350 */
3351static void ohciServiceIsochronousEndpoint(POHCI pThis, POHCIED pEd, uint32_t EdAddr)
3352{
3353 /*
3354 * We currently process this as if the guest follows the interrupt end point chaining
3355 * hierarchy described in the documenation. This means that for an isochronous endpoint
3356 * with a 1 ms interval we expect to find in-flight TDs at the head of the list. We will
3357 * skip over all in-flight TDs which timeframe has been exceed. Those which aren't in
3358 * flight but which are too late will be retired (possibly out of order, but, we don't
3359 * care right now).
3360 *
3361 * When we reach a TD which still has a buffer which is due for take off, we will
3362 * stop iterating TDs. If it's in-flight, there isn't anything to be done. Otherwise
3363 * we will push it onto the runway for immediate take off. In this process we
3364 * might have to complete buffers which didn't make it on time, something which
3365 * complicates the kind of status info we need to keep around for the TD.
3366 *
3367 * Note: We're currently not making any attempt at reassembling ITDs into URBs.
3368 * However, this will become necessary because of EMT scheduling and guest
3369 * like linux using one TD for each frame (simple but inefficient for us).
3370 */
3371 OHCIITD ITd;
3372 uint32_t ITdAddr = pEd->HeadP & ED_PTR_MASK;
3373 uint32_t ITdAddrPrev = 0;
3374 uint32_t u32NextFrame = UINT32_MAX;
3375 const uint16_t u16CurFrame = pThis->HcFmNumber;
3376 for (;;)
3377 {
3378 /* check for end-of-chain. */
3379 if ( ITdAddr == (pEd->TailP & ED_PTR_MASK)
3380 || !ITdAddr)
3381 break;
3382
3383 /*
3384 * If isochronous endpoints are around, don't slow down the timer. Getting the timing right
3385 * is difficult enough as it is.
3386 */
3387 pThis->fIdle = false;
3388
3389 /*
3390 * Read the current ITD and check what we're supposed to do about it.
3391 */
3392 ohciReadITd(pThis, ITdAddr, &ITd);
3393 const uint32_t ITdAddrNext = ITd.NextTD & ED_PTR_MASK;
3394 const int16_t R = u16CurFrame - (uint16_t)(ITd.HwInfo & ITD_HWINFO_SF); /* 4.3.2.3 */
3395 const int16_t cFrames = ((ITd.HwInfo & ITD_HWINFO_FC) >> ITD_HWINFO_FC_SHIFT) + 1;
3396
3397 if (R < cFrames)
3398 {
3399 /*
3400 * It's inside the current or a future launch window.
3401 *
3402 * We will try maximize the TD in flight here to deal with EMT scheduling
3403 * issues and similar stuff which will screw up the time. So, we will only
3404 * stop submitting TD when we reach a gap (in time) or end of the list.
3405 */
3406 if ( R < 0 /* (a future frame) */
3407 && (uint16_t)u32NextFrame != (uint16_t)(ITd.HwInfo & ITD_HWINFO_SF))
3408 break;
3409 if (ohci_in_flight_find(pThis, ITdAddr) < 0)
3410 if (!ohciServiceIsochronousTd(pThis, &ITd, ITdAddr, R < 0 ? 0 : R, pEd, EdAddr))
3411 break;
3412
3413 ITdAddrPrev = ITdAddr;
3414 }
3415 else
3416 {
3417# if 1
3418 /*
3419 * Ok, the launch window for this TD has passed.
3420 * If it's not in flight it should be retired with a DataOverrun status (TD).
3421 *
3422 * Don't remove in-flight TDs before they complete.
3423 * Windows will, upon the completion of another ITD it seems, check for if
3424 * any other TDs has been unlinked. If we unlink them before they really
3425 * complete all the packet status codes will be NotAccessed and Windows
3426 * will fail the URB with status USBD_STATUS_ISOCH_REQUEST_FAILED.
3427 *
3428 * I don't know if unlinking TDs out of order could cause similar problems,
3429 * time will show.
3430 */
3431 int iInFlight = ohci_in_flight_find(pThis, ITdAddr);
3432 if (iInFlight >= 0)
3433 ITdAddrPrev = ITdAddr;
3434 else if (!ohciServiceIsochronousTdUnlink(pThis, &ITd, ITdAddr, ITdAddrPrev,
3435 NULL, pEd, EdAddr))
3436 {
3437 Log(("ohciServiceIsochronousEndpoint: Failed unlinking old ITD.\n"));
3438 break;
3439 }
3440# else /* BAD IDEA: */
3441 /*
3442 * Ok, the launch window for this TD has passed.
3443 * If it's not in flight it should be retired with a DataOverrun status (TD).
3444 *
3445 * If it's in flight we will try unlink it from the list prematurely to
3446 * help the guest to move on and shorten the list we have to walk. We currently
3447 * are successful with the first URB but then it goes too slowly...
3448 */
3449 int iInFlight = ohci_in_flight_find(pThis, ITdAddr);
3450 if (!ohciServiceIsochronousTdUnlink(pThis, &ITd, ITdAddr, ITdAddrPrev,
3451 iInFlight < 0 ? NULL : pThis->aInFlight[iInFlight].pUrb,
3452 pEd, EdAddr))
3453 {
3454 Log(("ohciServiceIsochronousEndpoint: Failed unlinking old ITD.\n"));
3455 break;
3456 }
3457# endif
3458 }
3459
3460 /* advance to the next ITD */
3461 ITdAddr = ITdAddrNext;
3462 u32NextFrame = (ITd.HwInfo & ITD_HWINFO_SF) + cFrames;
3463 }
3464}
3465
3466
3467/**
3468 * Checks if a endpoints has TDs queued and is ready to have them processed.
3469 *
3470 * @returns true if it's ok to process TDs.
3471 * @param pEd The endpoint data.
3472 */
3473DECLINLINE(bool) ohciIsEdReady(PCOHCIED pEd)
3474{
3475 return (pEd->HeadP & ED_PTR_MASK) != (pEd->TailP & ED_PTR_MASK)
3476 && !(pEd->HeadP & ED_HEAD_HALTED)
3477 && !(pEd->hwinfo & ED_HWINFO_SKIP);
3478}
3479
3480
3481/**
3482 * Checks if an endpoint has TDs queued (not necessarily ready to have them processed).
3483 *
3484 * @returns true if endpoint may have TDs queued.
3485 * @param pEd The endpoint data.
3486 */
3487DECLINLINE(bool) ohciIsEdPresent(PCOHCIED pEd)
3488{
3489 return (pEd->HeadP & ED_PTR_MASK) != (pEd->TailP & ED_PTR_MASK)
3490 && !(pEd->HeadP & ED_HEAD_HALTED);
3491}
3492
3493
3494/**
3495 * Services the bulk list.
3496 *
3497 * On the bulk list we must reassemble URBs from multiple TDs using heuristics
3498 * derived from USB tracing done in the guests and guest source code (when available).
3499 */
3500static void ohciServiceBulkList(POHCI pThis)
3501{
3502# ifdef LOG_ENABLED
3503 if (g_fLogBulkEPs)
3504 ohciDumpEdList(pThis, pThis->bulk_head, "Bulk before", true);
3505 if (pThis->bulk_cur)
3506 Log(("ohciServiceBulkList: bulk_cur=%#010x before listprocessing!!! HCD have positioned us!!!\n", pThis->bulk_cur));
3507# endif
3508
3509 /*
3510 * ", HC will start processing the Bulk list and will set BF [BulkListFilled] to 0"
3511 * - We've simplified and are always starting at the head of the list and working
3512 * our way thru to the end each time.
3513 */
3514 pThis->status &= ~OHCI_STATUS_BLF;
3515 pThis->fBulkNeedsCleaning = false;
3516 pThis->bulk_cur = 0;
3517
3518 uint32_t EdAddr = pThis->bulk_head;
3519 while (EdAddr)
3520 {
3521 OHCIED Ed;
3522# ifdef VBOX_WITH_OHCI_PHYS_READ_CACHE
3523 ohciReadEdCached(pThis, EdAddr, &Ed);
3524# else
3525 ohciReadEd(pThis, EdAddr, &Ed);
3526# endif
3527 Assert(!(Ed.hwinfo & ED_HWINFO_ISO)); /* the guest is screwing us */
3528 if (ohciIsEdReady(&Ed))
3529 {
3530 pThis->status |= OHCI_STATUS_BLF;
3531 pThis->fBulkNeedsCleaning = true;
3532
3533# if 1
3534 /*
3535
3536 * After we figured out that all the TDs submitted for dealing with MSD
3537 * read/write data really makes up on single URB, and that we must
3538 * reassemble these TDs into an URB before submitting it, there is no
3539 * longer any need for servicing anything other than the head *URB*
3540 * on a bulk endpoint.
3541 */
3542 ohciServiceHeadTdMultiple(pThis, VUSBXFERTYPE_BULK, &Ed, EdAddr, "Bulk");
3543# else
3544 /*
3545 * This alternative code was used before we started reassembling URBs from
3546 * multiple TDs. We keep it handy for debugging.
3547 */
3548 uint32_t TdAddr = Ed.HeadP & ED_PTR_MASK;
3549 if (!ohciIsTdInFlight(pThis, TdAddr))
3550 {
3551 do
3552 {
3553 if (!ohciServiceTdMultiple(pThis, VUSBXFERTYPE_BULK, &Ed, EdAddr, TdAddr, &TdAddr, "Bulk"))
3554 {
3555 LogFlow(("ohciServiceBulkList: ohciServiceTdMultiple -> false\n"));
3556 break;
3557 }
3558 if ( (TdAddr & ED_PTR_MASK) == (Ed.TailP & ED_PTR_MASK)
3559 || !TdAddr /* paranoia */)
3560 {
3561 LogFlow(("ohciServiceBulkList: TdAddr=%#010RX32 Ed.TailP=%#010RX32\n", TdAddr, Ed.TailP));
3562 break;
3563 }
3564
3565 ohciReadEd(pThis, EdAddr, &Ed); /* It might have been updated on URB completion. */
3566 } while (ohciIsEdReady(&Ed));
3567 }
3568# endif
3569 }
3570 else
3571 {
3572 if (Ed.hwinfo & ED_HWINFO_SKIP)
3573 {
3574 LogFlow(("ohciServiceBulkList: Ed=%#010RX32 Ed.TailP=%#010RX32 SKIP\n", EdAddr, Ed.TailP));
3575 /* If the ED is in 'skip' state, no transactions on it are allowed and we must
3576 * cancel outstanding URBs, if any.
3577 */
3578 uint32_t TdAddr = Ed.HeadP & ED_PTR_MASK;
3579 PVUSBURB pUrb = ohciTdInFlightUrb(pThis, TdAddr);
3580 if (pUrb)
3581 pThis->RootHub.pIRhConn->pfnCancelUrbsEp(pThis->RootHub.pIRhConn, pUrb);
3582 }
3583 }
3584
3585 /* next end point */
3586 EdAddr = Ed.NextED & ED_PTR_MASK;
3587
3588 }
3589
3590# ifdef LOG_ENABLED
3591 if (g_fLogBulkEPs)
3592 ohciDumpEdList(pThis, pThis->bulk_head, "Bulk after ", true);
3593# endif
3594}
3595
3596/**
3597 * Abort outstanding transfers on the bulk list.
3598 *
3599 * If the guest disabled bulk list processing, we must abort any outstanding transfers
3600 * (that is, cancel in-flight URBs associated with the list). This is required because
3601 * there may be outstanding read URBs that will never get a response from the device
3602 * and would block further communication.
3603 */
3604static void ohciUndoBulkList(POHCI pThis)
3605{
3606# ifdef LOG_ENABLED
3607 if (g_fLogBulkEPs)
3608 ohciDumpEdList(pThis, pThis->bulk_head, "Bulk before", true);
3609 if (pThis->bulk_cur)
3610 Log(("ohciUndoBulkList: bulk_cur=%#010x before list processing!!! HCD has positioned us!!!\n", pThis->bulk_cur));
3611# endif
3612
3613 /* This flag follows OHCI_STATUS_BLF, but BLF doesn't change when list processing is disabled. */
3614 pThis->fBulkNeedsCleaning = false;
3615
3616 uint32_t EdAddr = pThis->bulk_head;
3617 while (EdAddr)
3618 {
3619 OHCIED Ed;
3620# ifdef VBOX_WITH_OHCI_PHYS_READ_CACHE
3621 ohciReadEdCached(pThis, EdAddr, &Ed);
3622# else
3623 ohciReadEd(pThis, EdAddr, &Ed);
3624# endif
3625 Assert(!(Ed.hwinfo & ED_HWINFO_ISO)); /* the guest is screwing us */
3626 if (ohciIsEdPresent(&Ed))
3627 {
3628 uint32_t TdAddr = Ed.HeadP & ED_PTR_MASK;
3629 if (ohciIsTdInFlight(pThis, TdAddr))
3630 {
3631 LogFlow(("ohciUndoBulkList: Ed=%#010RX32 Ed.TailP=%#010RX32 UNDO\n", EdAddr, Ed.TailP));
3632 PVUSBURB pUrb = ohciTdInFlightUrb(pThis, TdAddr);
3633 if (pUrb)
3634 pThis->RootHub.pIRhConn->pfnCancelUrbsEp(pThis->RootHub.pIRhConn, pUrb);
3635 }
3636 }
3637 /* next endpoint */
3638 EdAddr = Ed.NextED & ED_PTR_MASK;
3639 }
3640}
3641
3642
3643/**
3644 * Services the control list.
3645 *
3646 * The control list has complex URB assembling, but that's taken
3647 * care of at VUSB level (unlike the other transfer types).
3648 */
3649static void ohciServiceCtrlList(POHCI pThis)
3650{
3651# ifdef LOG_ENABLED
3652 if (g_fLogControlEPs)
3653 ohciDumpEdList(pThis, pThis->ctrl_head, "Ctrl before", true);
3654 if (pThis->ctrl_cur)
3655 Log(("ohciServiceCtrlList: ctrl_cur=%010x before list processing!!! HCD have positioned us!!!\n", pThis->ctrl_cur));
3656# endif
3657
3658 /*
3659 * ", HC will start processing the list and will set ControlListFilled to 0"
3660 * - We've simplified and are always starting at the head of the list and working
3661 * our way thru to the end each time.
3662 */
3663 pThis->status &= ~OHCI_STATUS_CLF;
3664 pThis->ctrl_cur = 0;
3665
3666 uint32_t EdAddr = pThis->ctrl_head;
3667 while (EdAddr)
3668 {
3669 OHCIED Ed;
3670 ohciReadEd(pThis, EdAddr, &Ed);
3671 Assert(!(Ed.hwinfo & ED_HWINFO_ISO)); /* the guest is screwing us */
3672 if (ohciIsEdReady(&Ed))
3673 {
3674# if 1
3675 /*
3676 * Control TDs depends on order and stage. Only one can be in-flight
3677 * at any given time. OTOH, some stages are completed immediately,
3678 * so we process the list until we've got a head which is in-flight
3679 * or reach the end of the list.
3680 */
3681 do
3682 {
3683 if ( !ohciServiceHeadTd(pThis, VUSBXFERTYPE_CTRL, &Ed, EdAddr, "Control")
3684 || ohciIsTdInFlight(pThis, Ed.HeadP & ED_PTR_MASK))
3685 {
3686 pThis->status |= OHCI_STATUS_CLF;
3687 break;
3688 }
3689 ohciReadEd(pThis, EdAddr, &Ed); /* It might have been updated on URB completion. */
3690 } while (ohciIsEdReady(&Ed));
3691# else
3692 /* Simplistic, for debugging. */
3693 ohciServiceHeadTd(pThis, VUSBXFERTYPE_CTRL, &Ed, EdAddr, "Control");
3694 pThis->status |= OHCI_STATUS_CLF;
3695# endif
3696 }
3697
3698 /* next end point */
3699 EdAddr = Ed.NextED & ED_PTR_MASK;
3700 }
3701
3702# ifdef LOG_ENABLED
3703 if (g_fLogControlEPs)
3704 ohciDumpEdList(pThis, pThis->ctrl_head, "Ctrl after ", true);
3705# endif
3706}
3707
3708
3709/**
3710 * Services the periodic list.
3711 *
3712 * On the interrupt portion of the periodic list we must reassemble URBs from multiple
3713 * TDs using heuristics derived from USB tracing done in the guests and guest source
3714 * code (when available).
3715 */
3716static void ohciServicePeriodicList(POHCI pThis)
3717{
3718 /*
3719 * Read the list head from the HCCA.
3720 */
3721 const unsigned iList = pThis->HcFmNumber % OHCI_HCCA_NUM_INTR;
3722 uint32_t EdAddr;
3723 ohciGetDWords(pThis, pThis->hcca + iList * sizeof(EdAddr), &EdAddr, 1);
3724
3725# ifdef LOG_ENABLED
3726 const uint32_t EdAddrHead = EdAddr;
3727 if (g_fLogInterruptEPs)
3728 {
3729 char sz[48];
3730 RTStrPrintf(sz, sizeof(sz), "Int%02x before", iList);
3731 ohciDumpEdList(pThis, EdAddrHead, sz, true);
3732 }
3733# endif
3734
3735 /*
3736 * Iterate the endpoint list.
3737 */
3738 while (EdAddr)
3739 {
3740 OHCIED Ed;
3741# ifdef VBOX_WITH_OHCI_PHYS_READ_CACHE
3742 ohciReadEdCached(pThis, EdAddr, &Ed);
3743# else
3744 ohciReadEd(pThis, EdAddr, &Ed);
3745# endif
3746
3747 if (ohciIsEdReady(&Ed))
3748 {
3749 /*
3750 * "There is no separate head pointer of isochronous transfers. The first
3751 * isochronous Endpoint Descriptor simply links to the last interrupt
3752 * Endpoint Descriptor."
3753 */
3754 if (!(Ed.hwinfo & ED_HWINFO_ISO))
3755 {
3756 /*
3757 * Presently we will only process the head URB on an interrupt endpoint.
3758 */
3759 ohciServiceHeadTdMultiple(pThis, VUSBXFERTYPE_INTR, &Ed, EdAddr, "Periodic");
3760 }
3761 else if (pThis->ctl & OHCI_CTL_IE)
3762 {
3763 /*
3764 * Presently only the head ITD.
3765 */
3766 ohciServiceIsochronousEndpoint(pThis, &Ed, EdAddr);
3767 }
3768 else
3769 break;
3770 }
3771 else
3772 {
3773 if (Ed.hwinfo & ED_HWINFO_SKIP)
3774 {
3775 LogFlow(("ohciServicePeriodicList: Ed=%#010RX32 Ed.TailP=%#010RX32 SKIP\n", EdAddr, Ed.TailP));
3776 /* If the ED is in 'skip' state, no transactions on it are allowed and we must
3777 * cancel outstanding URBs, if any.
3778 */
3779 uint32_t TdAddr = Ed.HeadP & ED_PTR_MASK;
3780 PVUSBURB pUrb = ohciTdInFlightUrb(pThis, TdAddr);
3781 if (pUrb)
3782 pThis->RootHub.pIRhConn->pfnCancelUrbsEp(pThis->RootHub.pIRhConn, pUrb);
3783 }
3784 }
3785 /* next end point */
3786 EdAddr = Ed.NextED & ED_PTR_MASK;
3787 }
3788
3789# ifdef LOG_ENABLED
3790 if (g_fLogInterruptEPs)
3791 {
3792 char sz[48];
3793 RTStrPrintf(sz, sizeof(sz), "Int%02x after ", iList);
3794 ohciDumpEdList(pThis, EdAddrHead, sz, true);
3795 }
3796# endif
3797}
3798
3799
3800/**
3801 * Update the HCCA.
3802 *
3803 * @param pThis The OHCI instance data.
3804 */
3805static void ohciUpdateHCCA(POHCI pThis)
3806{
3807 struct ohci_hcca hcca;
3808 ohciPhysRead(pThis, pThis->hcca + OHCI_HCCA_OFS, &hcca, sizeof(hcca));
3809
3810 hcca.frame = RT_H2LE_U16((uint16_t)pThis->HcFmNumber);
3811 hcca.pad = 0;
3812
3813 bool fWriteDoneHeadInterrupt = false;
3814 if ( pThis->dqic == 0
3815 && (pThis->intr_status & OHCI_INTR_WRITE_DONE_HEAD) == 0)
3816 {
3817 uint32_t done = pThis->done;
3818
3819 if (pThis->intr_status & ~( OHCI_INTR_MASTER_INTERRUPT_ENABLED | OHCI_INTR_OWNERSHIP_CHANGE
3820 | OHCI_INTR_WRITE_DONE_HEAD) )
3821 done |= 0x1;
3822
3823 hcca.done = RT_H2LE_U32(done);
3824 pThis->done = 0;
3825 pThis->dqic = 0x7;
3826
3827 Log(("ohci: Writeback Done (%#010x) on frame %#x (age %#x)\n", hcca.done,
3828 pThis->HcFmNumber, pThis->HcFmNumber - pThis->u32FmDoneQueueTail));
3829# ifdef LOG_ENABLED
3830 ohciDumpTdQueue(pThis, hcca.done & ED_PTR_MASK, "DoneQueue");
3831# endif
3832 Assert(RT_OFFSETOF(struct ohci_hcca, done) == 4);
3833# if defined(VBOX_STRICT) || defined(LOG_ENABLED)
3834 ohci_in_done_queue_zap(pThis);
3835# endif
3836 fWriteDoneHeadInterrupt = true;
3837 }
3838
3839 Log(("ohci: Updating HCCA on frame %#x\n", pThis->HcFmNumber));
3840 ohciPhysWrite(pThis, pThis->hcca + OHCI_HCCA_OFS, (uint8_t *)&hcca, sizeof(hcca));
3841 if (fWriteDoneHeadInterrupt)
3842 ohciR3SetInterrupt(pThis, OHCI_INTR_WRITE_DONE_HEAD);
3843}
3844
3845
3846/**
3847 * Go over the in-flight URB list and cancel any URBs that are no longer in use.
3848 * This occurs when the host removes EDs or TDs from the lists and we don't notice
3849 * the sKip bit. Such URBs must be promptly canceled, otherwise there is a risk
3850 * they might "steal" data destined for another URB.
3851 */
3852static void ohciCancelOrphanedURBs(POHCI pThis)
3853{
3854 bool fValidHCCA = !( pThis->hcca >= OHCI_HCCA_MASK
3855 || pThis->hcca < ~OHCI_HCCA_MASK);
3856 unsigned i, cLeft;
3857 int j;
3858 uint32_t EdAddr;
3859 PVUSBURB pUrb;
3860
3861 /* If the HCCA is not currently valid, or there are no in-flight URBs,
3862 * there's nothing to do.
3863 */
3864 if (!fValidHCCA || !pThis->cInFlight)
3865 return;
3866
3867 /* Initially mark all in-flight URBs as inactive. */
3868 for (i = 0, cLeft = pThis->cInFlight; cLeft && i < RT_ELEMENTS(pThis->aInFlight); i++)
3869 {
3870 if (pThis->aInFlight[i].pUrb)
3871 {
3872 pThis->aInFlight[i].fInactive = true;
3873 cLeft--;
3874 }
3875 }
3876 Assert(cLeft == 0);
3877
3878# ifdef VBOX_WITH_OHCI_PHYS_READ_CACHE
3879 /* Get hcca data to minimize calls to ohciGetDWords/PDMDevHlpPhysRead. */
3880 uint32_t au32HCCA[OHCI_HCCA_NUM_INTR];
3881 ohciGetDWords(pThis, pThis->hcca, au32HCCA, OHCI_HCCA_NUM_INTR);
3882# endif
3883
3884 /* Go over all bulk/control/interrupt endpoint lists; any URB found in these lists
3885 * is marked as active again.
3886 */
3887 for (i = 0; i < OHCI_HCCA_NUM_INTR + 2; i++)
3888 {
3889 switch (i)
3890 {
3891 case OHCI_HCCA_NUM_INTR:
3892 EdAddr = pThis->bulk_head;
3893 break;
3894 case OHCI_HCCA_NUM_INTR + 1:
3895 EdAddr = pThis->ctrl_head;
3896 break;
3897 default:
3898# ifdef VBOX_WITH_OHCI_PHYS_READ_CACHE
3899 EdAddr = au32HCCA[i];
3900# else
3901 ohciGetDWords(pThis, pThis->hcca + i * sizeof(EdAddr), &EdAddr, 1);
3902# endif
3903 break;
3904 }
3905 while (EdAddr)
3906 {
3907 OHCIED Ed;
3908 OHCITD Td;
3909# ifdef VBOX_WITH_OHCI_PHYS_READ_CACHE
3910 ohciReadEdCached(pThis, EdAddr, &Ed);
3911# else
3912 ohciReadEd(pThis, EdAddr, &Ed);
3913# endif
3914 uint32_t TdAddr = Ed.HeadP & ED_PTR_MASK;
3915 uint32_t TailP = Ed.TailP & ED_PTR_MASK;
3916 unsigned k = 0;
3917 if ( !(Ed.hwinfo & ED_HWINFO_SKIP)
3918 && (TdAddr != TailP))
3919 {
3920# ifdef VBOX_WITH_OHCI_PHYS_READ_CACHE
3921 ohciPhysReadCacheClear(pThis->pCacheTD);
3922# endif
3923 do
3924 {
3925# ifdef VBOX_WITH_OHCI_PHYS_READ_CACHE
3926 ohciReadTdCached(pThis, TdAddr, &Td);
3927# else
3928 ohciReadTd(pThis, TdAddr, &Td);
3929# endif
3930 j = ohci_in_flight_find(pThis, TdAddr);
3931 if (j > -1)
3932 pThis->aInFlight[j].fInactive = false;
3933 TdAddr = Td.NextTD & ED_PTR_MASK;
3934 /* See #8125.
3935 * Sometimes the ED is changed by the guest between ohciReadEd above and here.
3936 * Then the code reads TD pointed by the new TailP, which is not allowed.
3937 * Luckily Windows guests have Td.NextTD = 0 in the tail TD.
3938 * Also having a real TD at 0 is very unlikely.
3939 * So do not continue.
3940 */
3941 if (TdAddr == 0)
3942 break;
3943 /* Failsafe for temporarily looped lists. */
3944 if (++k == 128)
3945 break;
3946 } while (TdAddr != (Ed.TailP & ED_PTR_MASK));
3947 }
3948 EdAddr = Ed.NextED & ED_PTR_MASK;
3949 }
3950 }
3951
3952 /* In-flight URBs still marked as inactive are not used anymore and need
3953 * to be canceled.
3954 */
3955 for (i = 0, cLeft = pThis->cInFlight; cLeft && i < RT_ELEMENTS(pThis->aInFlight); i++)
3956 {
3957 if (pThis->aInFlight[i].pUrb)
3958 {
3959 cLeft--;
3960 pUrb = pThis->aInFlight[i].pUrb;
3961 if (pThis->aInFlight[i].fInactive
3962 && pUrb->enmState == VUSBURBSTATE_IN_FLIGHT
3963 && pUrb->enmType != VUSBXFERTYPE_CTRL)
3964 pThis->RootHub.pIRhConn->pfnCancelUrbsEp(pThis->RootHub.pIRhConn, pUrb);
3965 }
3966 }
3967 Assert(cLeft == 0);
3968}
3969
3970/**
3971 * Generate a Start-Of-Frame event, and set a timer for End-Of-Frame.
3972 */
3973static void ohciStartOfFrame(POHCI pThis)
3974{
3975# ifdef LOG_ENABLED
3976 const uint32_t status_old = pThis->status;
3977# endif
3978
3979 /*
3980 * Update HcFmRemaining.FRT and update start of frame time.
3981 */
3982 pThis->frt = pThis->fit;
3983 pThis->SofTime += pThis->cTicksPerFrame;
3984
3985 /*
3986 * Check that the HCCA address isn't bogus. Linux 2.4.x is known to start
3987 * the bus with a hcca of 0 to work around problem with a specific controller.
3988 */
3989 bool fValidHCCA = !( pThis->hcca >= OHCI_HCCA_MASK
3990 || pThis->hcca < ~OHCI_HCCA_MASK);
3991
3992# if 1
3993 /*
3994 * Update the HCCA.
3995 * Should be done after SOF but before HC read first ED in this frame.
3996 */
3997 if (fValidHCCA)
3998 ohciUpdateHCCA(pThis);
3999# endif
4000
4001 /* "After writing to HCCA, HC will set SF in HcInterruptStatus" - guest isn't executing, so ignore the order! */
4002 ohciR3SetInterrupt(pThis, OHCI_INTR_START_OF_FRAME);
4003
4004 if (pThis->fno)
4005 {
4006 ohciR3SetInterrupt(pThis, OHCI_INTR_FRAMENUMBER_OVERFLOW);
4007 pThis->fno = 0;
4008 }
4009
4010 /* If the HCCA address is invalid, we're quitting here to avoid doing something which cannot be reported to the HCD. */
4011 if (!fValidHCCA)
4012 {
4013 Log(("ohciStartOfFrame: skipping hcca part because hcca=%RX32 (our 'valid' range: %RX32-%RX32)\n",
4014 pThis->hcca, ~OHCI_HCCA_MASK, OHCI_HCCA_MASK));
4015 return;
4016 }
4017
4018 /*
4019 * Periodic EPs.
4020 */
4021 if (pThis->ctl & OHCI_CTL_PLE)
4022 ohciServicePeriodicList(pThis);
4023
4024 /*
4025 * Control EPs.
4026 */
4027 if ( (pThis->ctl & OHCI_CTL_CLE)
4028 && (pThis->status & OHCI_STATUS_CLF) )
4029 ohciServiceCtrlList(pThis);
4030
4031 /*
4032 * Bulk EPs.
4033 */
4034 if ( (pThis->ctl & OHCI_CTL_BLE)
4035 && (pThis->status & OHCI_STATUS_BLF))
4036 ohciServiceBulkList(pThis);
4037 else if ((pThis->status & OHCI_STATUS_BLF)
4038 && pThis->fBulkNeedsCleaning)
4039 ohciUndoBulkList(pThis); /* If list disabled but not empty, abort endpoints. */
4040
4041# if 0
4042 /*
4043 * Update the HCCA after processing the lists and everything. A bit experimental.
4044 *
4045 * ASSUME the guest won't be very upset if a TD is completed, retired and handed
4046 * back immediately. The idea is to be able to retire the data and/or status stages
4047 * of a control transfer together with the setup stage, thus saving a frame. This
4048 * behaviour is should be perfectly ok, since the setup (and maybe data) stages
4049 * have already taken at least one frame to complete.
4050 *
4051 * But, when implementing the first synchronous virtual USB devices, we'll have to
4052 * verify that the guest doesn't choke when having a TD returned in the same frame
4053 * as it was submitted.
4054 */
4055 ohciUpdateHCCA(pThis);
4056# endif
4057
4058# ifdef LOG_ENABLED
4059 if (pThis->status ^ status_old)
4060 {
4061 uint32_t val = pThis->status;
4062 uint32_t chg = val ^ status_old; NOREF(chg);
4063 Log2(("ohciStartOfFrame: HcCommandStatus=%#010x: %sHCR=%d %sCLF=%d %sBLF=%d %sOCR=%d %sSOC=%d\n",
4064 val,
4065 chg & RT_BIT(0) ? "*" : "", val & 1,
4066 chg & RT_BIT(1) ? "*" : "", (val >> 1) & 1,
4067 chg & RT_BIT(2) ? "*" : "", (val >> 2) & 1,
4068 chg & RT_BIT(3) ? "*" : "", (val >> 3) & 1,
4069 chg & (3<<16)? "*" : "", (val >> 16) & 3));
4070 }
4071# endif
4072}
4073
4074/**
4075 * Updates the HcFmNumber and FNO registers.
4076 */
4077static void bump_frame_number(POHCI pThis)
4078{
4079 const uint16_t u16OldFmNumber = pThis->HcFmNumber++;
4080 if ((u16OldFmNumber ^ pThis->HcFmNumber) & RT_BIT(15))
4081 pThis->fno = 1;
4082}
4083
4084/**
4085 * Callback for periodic frame processing.
4086 */
4087static DECLCALLBACK(bool) ohciR3StartFrame(PVUSBIROOTHUBPORT pInterface, uint32_t u32FrameNo)
4088{
4089 RT_NOREF(u32FrameNo);
4090 POHCI pThis = VUSBIROOTHUBPORT_2_OHCI(pInterface);
4091
4092 RTCritSectEnter(&pThis->CritSect);
4093
4094 /* Reset idle detection flag */
4095 pThis->fIdle = true;
4096
4097# ifdef VBOX_WITH_OHCI_PHYS_READ_STATS
4098 physReadStatsReset(&g_PhysReadState);
4099# endif
4100
4101# ifdef VBOX_WITH_OHCI_PHYS_READ_CACHE
4102 ohciPhysReadCacheClear(pThis->pCacheED);
4103 ohciPhysReadCacheClear(pThis->pCacheTD);
4104# endif
4105
4106 /* Frame boundary, so do EOF stuff here. */
4107 bump_frame_number(pThis);
4108 if ( (pThis->dqic != 0x7) && (pThis->dqic != 0))
4109 pThis->dqic--;
4110
4111 /* Clean up any URBs that have been removed. */
4112 ohciCancelOrphanedURBs(pThis);
4113
4114 /* Start the next frame. */
4115 ohciStartOfFrame(pThis);
4116
4117# ifdef VBOX_WITH_OHCI_PHYS_READ_STATS
4118 physReadStatsPrint(&g_PhysReadState);
4119# endif
4120
4121 RTCritSectLeave(&pThis->CritSect);
4122
4123 return pThis->fIdle;
4124}
4125
4126/** @interface_method_impl{VUSBIROOTHUBPORT,pfnFrameRateChanged} */
4127static DECLCALLBACK(void) ohciR3FrameRateChanged(PVUSBIROOTHUBPORT pInterface, uint32_t u32FrameRate)
4128{
4129 POHCI pThis = VUSBIROOTHUBPORT_2_OHCI(pInterface);
4130
4131 Assert(u32FrameRate <= OHCI_DEFAULT_TIMER_FREQ);
4132
4133 pThis->cTicksPerFrame = pThis->u64TimerHz / u32FrameRate;
4134 if (!pThis->cTicksPerFrame)
4135 pThis->cTicksPerFrame = 1;
4136 pThis->cTicksPerUsbTick = pThis->u64TimerHz >= VUSB_BUS_HZ ? pThis->u64TimerHz / VUSB_BUS_HZ : 1;
4137}
4138
4139/**
4140 * Do frame processing on frame boundary
4141 */
4142static DECLCALLBACK(void) ohciFrameBoundaryTimer(PPDMDEVINS pDevIns, PTMTIMER pTimer, void *pvUser)
4143{
4144 RT_NOREF(pDevIns, pTimer, pvUser);
4145}
4146
4147/**
4148 * Start sending SOF tokens across the USB bus, lists are processed in
4149 * next frame
4150 */
4151static void ohciBusStart(POHCI pThis)
4152{
4153 VUSBIDevPowerOn(pThis->RootHub.pIDev);
4154 pThis->dqic = 0x7;
4155
4156 Log(("ohci: %s: Bus started\n", pThis->PciDev.pszNameR3));
4157
4158 pThis->SofTime = PDMDevHlpTMTimeVirtGet(pThis->CTX_SUFF(pDevIns));
4159 int rc = pThis->RootHub.pIRhConn->pfnSetPeriodicFrameProcessing(pThis->RootHub.pIRhConn, OHCI_DEFAULT_TIMER_FREQ);
4160 AssertRC(rc);
4161}
4162
4163/**
4164 * Stop sending SOF tokens on the bus
4165 */
4166static void ohciBusStop(POHCI pThis)
4167{
4168 int rc = pThis->RootHub.pIRhConn->pfnSetPeriodicFrameProcessing(pThis->RootHub.pIRhConn, 0);
4169 AssertRC(rc);
4170 VUSBIDevPowerOff(pThis->RootHub.pIDev);
4171}
4172
4173/**
4174 * Move in to resume state
4175 */
4176static void ohciBusResume(POHCI pThis, bool fHardware)
4177{
4178 pThis->ctl &= ~OHCI_CTL_HCFS;
4179 pThis->ctl |= OHCI_USB_RESUME;
4180
4181 Log(("pThis: ohciBusResume fHardware=%RTbool RWE=%s\n",
4182 fHardware, (pThis->ctl & OHCI_CTL_RWE) ? "on" : "off"));
4183
4184 if (fHardware && (pThis->ctl & OHCI_CTL_RWE))
4185 ohciR3SetInterrupt(pThis, OHCI_INTR_RESUME_DETECT);
4186
4187 ohciBusStart(pThis);
4188}
4189
4190
4191/* Power a port up or down */
4192static void rhport_power(POHCIROOTHUB pRh, unsigned iPort, bool fPowerUp)
4193{
4194 POHCIHUBPORT pPort = &pRh->aPorts[iPort];
4195 bool fOldPPS = !!(pPort->fReg & OHCI_PORT_PPS);
4196 if (fPowerUp)
4197 {
4198 /* power up */
4199 if (pPort->pDev)
4200 pPort->fReg |= OHCI_PORT_R_CURRENT_CONNECT_STATUS;
4201 if (pPort->fReg & OHCI_PORT_R_CURRENT_CONNECT_STATUS)
4202 pPort->fReg |= OHCI_PORT_R_POWER_STATUS;
4203 if (pPort->pDev && !fOldPPS)
4204 VUSBIDevPowerOn(pPort->pDev);
4205 }
4206 else
4207 {
4208 /* power down */
4209 pPort->fReg &= ~( OHCI_PORT_R_POWER_STATUS
4210 | OHCI_PORT_R_CURRENT_CONNECT_STATUS
4211 | OHCI_PORT_R_SUSPEND_STATUS
4212 | OHCI_PORT_R_RESET_STATUS);
4213 if (pPort->pDev && fOldPPS)
4214 VUSBIDevPowerOff(pPort->pDev);
4215 }
4216}
4217
4218#endif /* IN_RING3 */
4219
4220/**
4221 * Read the HcRevision register.
4222 */
4223static int HcRevision_r(PCOHCI pThis, uint32_t iReg, uint32_t *pu32Value)
4224{
4225 RT_NOREF2(pThis, iReg);
4226 Log2(("HcRevision_r() -> 0x10\n"));
4227 *pu32Value = 0x10; /* OHCI revision 1.0, no emulation. */
4228 return VINF_SUCCESS;
4229}
4230
4231/**
4232 * Write to the HcRevision register.
4233 */
4234static int HcRevision_w(POHCI pThis, uint32_t iReg, uint32_t u32Value)
4235{
4236 RT_NOREF3(pThis, iReg, u32Value);
4237 Log2(("HcRevision_w(%#010x) - denied\n", u32Value));
4238 AssertMsgFailed(("Invalid operation!!! u32Value=%#010x\n", u32Value));
4239 return VINF_SUCCESS;
4240}
4241
4242/**
4243 * Read the HcControl register.
4244 */
4245static int HcControl_r(PCOHCI pThis, uint32_t iReg, uint32_t *pu32Value)
4246{
4247 RT_NOREF1(iReg);
4248 uint32_t ctl = pThis->ctl;
4249 Log2(("HcControl_r -> %#010x - CBSR=%d PLE=%d IE=%d CLE=%d BLE=%d HCFS=%#x IR=%d RWC=%d RWE=%d\n",
4250 ctl, ctl & 3, (ctl >> 2) & 1, (ctl >> 3) & 1, (ctl >> 4) & 1, (ctl >> 5) & 1, (ctl >> 6) & 3, (ctl >> 8) & 1,
4251 (ctl >> 9) & 1, (ctl >> 10) & 1));
4252 *pu32Value = ctl;
4253 return VINF_SUCCESS;
4254}
4255
4256/**
4257 * Write the HcControl register.
4258 */
4259static int HcControl_w(POHCI pThis, uint32_t iReg, uint32_t val)
4260{
4261 RT_NOREF1(iReg);
4262
4263 /* log it. */
4264 uint32_t chg = pThis->ctl ^ val; NOREF(chg);
4265 Log2(("HcControl_w(%#010x) => %sCBSR=%d %sPLE=%d %sIE=%d %sCLE=%d %sBLE=%d %sHCFS=%#x %sIR=%d %sRWC=%d %sRWE=%d\n",
4266 val,
4267 chg & 3 ? "*" : "", val & 3,
4268 chg & RT_BIT(2) ? "*" : "", (val >> 2) & 1,
4269 chg & RT_BIT(3) ? "*" : "", (val >> 3) & 1,
4270 chg & RT_BIT(4) ? "*" : "", (val >> 4) & 1,
4271 chg & RT_BIT(5) ? "*" : "", (val >> 5) & 1,
4272 chg & (3 << 6)? "*" : "", (val >> 6) & 3,
4273 chg & RT_BIT(8) ? "*" : "", (val >> 8) & 1,
4274 chg & RT_BIT(9) ? "*" : "", (val >> 9) & 1,
4275 chg & RT_BIT(10) ? "*" : "", (val >> 10) & 1));
4276 if (val & ~0x07ff)
4277 Log2(("Unknown bits %#x are set!!!\n", val & ~0x07ff));
4278
4279 /* see what changed and take action on that. */
4280 uint32_t old_state = pThis->ctl & OHCI_CTL_HCFS;
4281 uint32_t new_state = val & OHCI_CTL_HCFS;
4282
4283#ifdef IN_RING3
4284 pThis->ctl = val;
4285 if (new_state != old_state)
4286 {
4287 switch (new_state)
4288 {
4289 case OHCI_USB_OPERATIONAL:
4290 LogRel(("OHCI: USB Operational\n"));
4291 ohciBusStart(pThis);
4292 break;
4293 case OHCI_USB_SUSPEND:
4294 ohciBusStop(pThis);
4295 LogRel(("OHCI: USB Suspended\n"));
4296 break;
4297 case OHCI_USB_RESUME:
4298 LogRel(("OHCI: USB Resume\n"));
4299 ohciBusResume(pThis, false /* not hardware */);
4300 break;
4301 case OHCI_USB_RESET:
4302 {
4303 LogRel(("OHCI: USB Reset\n"));
4304 ohciBusStop(pThis);
4305 /** @todo This should probably do a real reset, but we don't implement
4306 * that correctly in the roothub reset callback yet. check it's
4307 * comments and argument for more details. */
4308 VUSBIDevReset(pThis->RootHub.pIDev, false /* don't do a real reset */, NULL, NULL, NULL);
4309 break;
4310 }
4311 }
4312 }
4313#else /* !IN_RING3 */
4314 if ( new_state != old_state )
4315 {
4316 Log2(("HcControl_w: state changed -> VINF_IOM_R3_MMIO_WRITE\n"));
4317 return VINF_IOM_R3_MMIO_WRITE;
4318 }
4319 pThis->ctl = val;
4320#endif /* !IN_RING3 */
4321
4322 return VINF_SUCCESS;
4323}
4324
4325/**
4326 * Read the HcCommandStatus register.
4327 */
4328static int HcCommandStatus_r(PCOHCI pThis, uint32_t iReg, uint32_t *pu32Value)
4329{
4330 uint32_t status = pThis->status;
4331 Log2(("HcCommandStatus_r() -> %#010x - HCR=%d CLF=%d BLF=%d OCR=%d SOC=%d\n",
4332 status, status & 1, (status >> 1) & 1, (status >> 2) & 1, (status >> 3) & 1, (status >> 16) & 3));
4333 *pu32Value = status;
4334 RT_NOREF1(iReg);
4335 return VINF_SUCCESS;
4336}
4337
4338/**
4339 * Write to the HcCommandStatus register.
4340 */
4341static int HcCommandStatus_w(POHCI pThis, uint32_t iReg, uint32_t val)
4342{
4343 RT_NOREF1(iReg);
4344
4345 /* log */
4346 uint32_t chg = pThis->status ^ val; NOREF(chg);
4347 Log2(("HcCommandStatus_w(%#010x) => %sHCR=%d %sCLF=%d %sBLF=%d %sOCR=%d %sSOC=%d\n",
4348 val,
4349 chg & RT_BIT(0) ? "*" : "", val & 1,
4350 chg & RT_BIT(1) ? "*" : "", (val >> 1) & 1,
4351 chg & RT_BIT(2) ? "*" : "", (val >> 2) & 1,
4352 chg & RT_BIT(3) ? "*" : "", (val >> 3) & 1,
4353 chg & (3<<16)? "!!!":"", (pThis->status >> 16) & 3));
4354 if (val & ~0x0003000f)
4355 Log2(("Unknown bits %#x are set!!!\n", val & ~0x0003000f));
4356
4357 /* SOC is read-only */
4358 val = (val & ~OHCI_STATUS_SOC);
4359
4360#ifdef IN_RING3
4361 /* "bits written as '0' remain unchanged in the register" */
4362 pThis->status |= val;
4363 if (pThis->status & OHCI_STATUS_HCR)
4364 {
4365 LogRel(("OHCI: Software reset\n"));
4366 ohciDoReset(pThis, OHCI_USB_SUSPEND, false /* N/A */);
4367 }
4368#else
4369 if ((pThis->status | val) & OHCI_STATUS_HCR)
4370 {
4371 LogFlow(("HcCommandStatus_w: reset -> VINF_IOM_R3_MMIO_WRITE\n"));
4372 return VINF_IOM_R3_MMIO_WRITE;
4373 }
4374 pThis->status |= val;
4375#endif
4376 return VINF_SUCCESS;
4377}
4378
4379/**
4380 * Read the HcInterruptStatus register.
4381 */
4382static int HcInterruptStatus_r(PCOHCI pThis, uint32_t iReg, uint32_t *pu32Value)
4383{
4384 uint32_t val = pThis->intr_status;
4385 Log2(("HcInterruptStatus_r() -> %#010x - SO=%d WDH=%d SF=%d RD=%d UE=%d FNO=%d RHSC=%d OC=%d\n",
4386 val, val & 1, (val >> 1) & 1, (val >> 2) & 1, (val >> 3) & 1, (val >> 4) & 1, (val >> 5) & 1,
4387 (val >> 6) & 1, (val >> 30) & 1));
4388 *pu32Value = val;
4389 RT_NOREF1(iReg);
4390 return VINF_SUCCESS;
4391}
4392
4393/**
4394 * Write to the HcInterruptStatus register.
4395 */
4396static int HcInterruptStatus_w(POHCI pThis, uint32_t iReg, uint32_t val)
4397{
4398 RT_NOREF1(iReg);
4399
4400 uint32_t res = pThis->intr_status & ~val;
4401 uint32_t chg = pThis->intr_status ^ res; NOREF(chg);
4402
4403 int rc = PDMCritSectEnter(&pThis->CsIrq, VINF_IOM_R3_MMIO_WRITE);
4404 if (rc != VINF_SUCCESS)
4405 return rc;
4406
4407 Log2(("HcInterruptStatus_w(%#010x) => %sSO=%d %sWDH=%d %sSF=%d %sRD=%d %sUE=%d %sFNO=%d %sRHSC=%d %sOC=%d\n",
4408 val,
4409 chg & RT_BIT(0) ? "*" : "", res & 1,
4410 chg & RT_BIT(1) ? "*" : "", (res >> 1) & 1,
4411 chg & RT_BIT(2) ? "*" : "", (res >> 2) & 1,
4412 chg & RT_BIT(3) ? "*" : "", (res >> 3) & 1,
4413 chg & RT_BIT(4) ? "*" : "", (res >> 4) & 1,
4414 chg & RT_BIT(5) ? "*" : "", (res >> 5) & 1,
4415 chg & RT_BIT(6) ? "*" : "", (res >> 6) & 1,
4416 chg & RT_BIT(30)? "*" : "", (res >> 30) & 1));
4417 if ( (val & ~0xc000007f)
4418 && val != 0xffffffff /* ignore clear-all-like requests from xp. */)
4419 Log2(("Unknown bits %#x are set!!!\n", val & ~0xc000007f));
4420
4421 /* "The Host Controller Driver may clear specific bits in this
4422 * register by writing '1' to bit positions to be cleared"
4423 */
4424 pThis->intr_status &= ~val;
4425 ohciUpdateInterruptLocked(pThis, "HcInterruptStatus_w");
4426 PDMCritSectLeave(&pThis->CsIrq);
4427 return VINF_SUCCESS;
4428}
4429
4430/**
4431 * Read the HcInterruptEnable register
4432 */
4433static int HcInterruptEnable_r(PCOHCI pThis, uint32_t iReg, uint32_t *pu32Value)
4434{
4435 uint32_t val = pThis->intr;
4436 Log2(("HcInterruptEnable_r() -> %#010x - SO=%d WDH=%d SF=%d RD=%d UE=%d FNO=%d RHSC=%d OC=%d MIE=%d\n",
4437 val, val & 1, (val >> 1) & 1, (val >> 2) & 1, (val >> 3) & 1, (val >> 4) & 1, (val >> 5) & 1,
4438 (val >> 6) & 1, (val >> 30) & 1, (val >> 31) & 1));
4439 *pu32Value = val;
4440 RT_NOREF1(iReg);
4441 return VINF_SUCCESS;
4442}
4443
4444/**
4445 * Writes to the HcInterruptEnable register.
4446 */
4447static int HcInterruptEnable_w(POHCI pThis, uint32_t iReg, uint32_t val)
4448{
4449 RT_NOREF1(iReg);
4450 uint32_t res = pThis->intr | val;
4451 uint32_t chg = pThis->intr ^ res; NOREF(chg);
4452
4453 int rc = PDMCritSectEnter(&pThis->CsIrq, VINF_IOM_R3_MMIO_WRITE);
4454 if (rc != VINF_SUCCESS)
4455 return rc;
4456
4457 Log2(("HcInterruptEnable_w(%#010x) => %sSO=%d %sWDH=%d %sSF=%d %sRD=%d %sUE=%d %sFNO=%d %sRHSC=%d %sOC=%d %sMIE=%d\n",
4458 val,
4459 chg & RT_BIT(0) ? "*" : "", res & 1,
4460 chg & RT_BIT(1) ? "*" : "", (res >> 1) & 1,
4461 chg & RT_BIT(2) ? "*" : "", (res >> 2) & 1,
4462 chg & RT_BIT(3) ? "*" : "", (res >> 3) & 1,
4463 chg & RT_BIT(4) ? "*" : "", (res >> 4) & 1,
4464 chg & RT_BIT(5) ? "*" : "", (res >> 5) & 1,
4465 chg & RT_BIT(6) ? "*" : "", (res >> 6) & 1,
4466 chg & RT_BIT(30) ? "*" : "", (res >> 30) & 1,
4467 chg & RT_BIT(31) ? "*" : "", (res >> 31) & 1));
4468 if (val & ~0xc000007f)
4469 Log2(("Uknown bits %#x are set!!!\n", val & ~0xc000007f));
4470
4471 pThis->intr |= val;
4472 ohciUpdateInterruptLocked(pThis, "HcInterruptEnable_w");
4473 PDMCritSectLeave(&pThis->CsIrq);
4474 return VINF_SUCCESS;
4475}
4476
4477/**
4478 * Reads the HcInterruptDisable register.
4479 */
4480static int HcInterruptDisable_r(PCOHCI pThis, uint32_t iReg, uint32_t *pu32Value)
4481{
4482#if 1 /** @todo r=bird: "On read, the current value of the HcInterruptEnable register is returned." */
4483 uint32_t val = pThis->intr;
4484#else /* old code. */
4485 uint32_t val = ~pThis->intr;
4486#endif
4487 Log2(("HcInterruptDisable_r() -> %#010x - SO=%d WDH=%d SF=%d RD=%d UE=%d FNO=%d RHSC=%d OC=%d MIE=%d\n",
4488 val, val & 1, (val >> 1) & 1, (val >> 2) & 1, (val >> 3) & 1, (val >> 4) & 1, (val >> 5) & 1,
4489 (val >> 6) & 1, (val >> 30) & 1, (val >> 31) & 1));
4490
4491 *pu32Value = val;
4492 RT_NOREF1(iReg);
4493 return VINF_SUCCESS;
4494}
4495
4496/**
4497 * Writes to the HcInterruptDisable register.
4498 */
4499static int HcInterruptDisable_w(POHCI pThis, uint32_t iReg, uint32_t val)
4500{
4501 RT_NOREF1(iReg);
4502 uint32_t res = pThis->intr & ~val;
4503 uint32_t chg = pThis->intr ^ res; NOREF(chg);
4504
4505 int rc = PDMCritSectEnter(&pThis->CsIrq, VINF_IOM_R3_MMIO_WRITE);
4506 if (rc != VINF_SUCCESS)
4507 return rc;
4508
4509 Log2(("HcInterruptDisable_w(%#010x) => %sSO=%d %sWDH=%d %sSF=%d %sRD=%d %sUE=%d %sFNO=%d %sRHSC=%d %sOC=%d %sMIE=%d\n",
4510 val,
4511 chg & RT_BIT(0) ? "*" : "", res & 1,
4512 chg & RT_BIT(1) ? "*" : "", (res >> 1) & 1,
4513 chg & RT_BIT(2) ? "*" : "", (res >> 2) & 1,
4514 chg & RT_BIT(3) ? "*" : "", (res >> 3) & 1,
4515 chg & RT_BIT(4) ? "*" : "", (res >> 4) & 1,
4516 chg & RT_BIT(5) ? "*" : "", (res >> 5) & 1,
4517 chg & RT_BIT(6) ? "*" : "", (res >> 6) & 1,
4518 chg & RT_BIT(30) ? "*" : "", (res >> 30) & 1,
4519 chg & RT_BIT(31) ? "*" : "", (res >> 31) & 1));
4520 /* Don't bitch about invalid bits here since it makes sense to disable
4521 * interrupts you don't know about. */
4522
4523 pThis->intr &= ~val;
4524 ohciUpdateInterruptLocked(pThis, "HcInterruptDisable_w");
4525 PDMCritSectLeave(&pThis->CsIrq);
4526 return VINF_SUCCESS;
4527}
4528
4529/**
4530 * Read the HcHCCA register (Host Controller Communications Area physical address).
4531 */
4532static int HcHCCA_r(PCOHCI pThis, uint32_t iReg, uint32_t *pu32Value)
4533{
4534 Log2(("HcHCCA_r() -> %#010x\n", pThis->hcca));
4535 *pu32Value = pThis->hcca;
4536 RT_NOREF1(iReg);
4537 return VINF_SUCCESS;
4538}
4539
4540/**
4541 * Write to the HcHCCA register (Host Controller Communications Area physical address).
4542 */
4543static int HcHCCA_w(POHCI pThis, uint32_t iReg, uint32_t Value)
4544{
4545 Log2(("HcHCCA_w(%#010x) - old=%#010x new=%#010x\n", Value, pThis->hcca, Value & OHCI_HCCA_MASK));
4546 pThis->hcca = Value & OHCI_HCCA_MASK;
4547 RT_NOREF1(iReg);
4548 return VINF_SUCCESS;
4549}
4550
4551/**
4552 * Read the HcPeriodCurrentED register.
4553 */
4554static int HcPeriodCurrentED_r(PCOHCI pThis, uint32_t iReg, uint32_t *pu32Value)
4555{
4556 Log2(("HcPeriodCurrentED_r() -> %#010x\n", pThis->per_cur));
4557 *pu32Value = pThis->per_cur;
4558 RT_NOREF1(iReg);
4559 return VINF_SUCCESS;
4560}
4561
4562/**
4563 * Write to the HcPeriodCurrentED register.
4564 */
4565static int HcPeriodCurrentED_w(POHCI pThis, uint32_t iReg, uint32_t val)
4566{
4567 Log(("HcPeriodCurrentED_w(%#010x) - old=%#010x new=%#010x (This is a read only register, only the linux guys don't respect that!)\n",
4568 val, pThis->per_cur, val & ~7));
4569 //AssertMsgFailed(("HCD (Host Controller Driver) should not write to HcPeriodCurrentED! val=%#010x (old=%#010x)\n", val, pThis->per_cur));
4570 AssertMsg(!(val & 7), ("Invalid alignment, val=%#010x\n", val));
4571 pThis->per_cur = val & ~7;
4572 RT_NOREF1(iReg);
4573 return VINF_SUCCESS;
4574}
4575
4576/**
4577 * Read the HcControlHeadED register.
4578 */
4579static int HcControlHeadED_r(PCOHCI pThis, uint32_t iReg, uint32_t *pu32Value)
4580{
4581 Log2(("HcControlHeadED_r() -> %#010x\n", pThis->ctrl_head));
4582 *pu32Value = pThis->ctrl_head;
4583 RT_NOREF1(iReg);
4584 return VINF_SUCCESS;
4585}
4586
4587/**
4588 * Write to the HcControlHeadED register.
4589 */
4590static int HcControlHeadED_w(POHCI pThis, uint32_t iReg, uint32_t val)
4591{
4592 Log2(("HcControlHeadED_w(%#010x) - old=%#010x new=%#010x\n", val, pThis->ctrl_head, val & ~7));
4593 AssertMsg(!(val & 7), ("Invalid alignment, val=%#010x\n", val));
4594 pThis->ctrl_head = val & ~7;
4595 RT_NOREF1(iReg);
4596 return VINF_SUCCESS;
4597}
4598
4599/**
4600 * Read the HcControlCurrentED register.
4601 */
4602static int HcControlCurrentED_r(PCOHCI pThis, uint32_t iReg, uint32_t *pu32Value)
4603{
4604 Log2(("HcControlCurrentED_r() -> %#010x\n", pThis->ctrl_cur));
4605 *pu32Value = pThis->ctrl_cur;
4606 RT_NOREF1(iReg);
4607 return VINF_SUCCESS;
4608}
4609
4610/**
4611 * Write to the HcControlCurrentED register.
4612 */
4613static int HcControlCurrentED_w(POHCI pThis, uint32_t iReg, uint32_t val)
4614{
4615 Log2(("HcControlCurrentED_w(%#010x) - old=%#010x new=%#010x\n", val, pThis->ctrl_cur, val & ~7));
4616 AssertMsg(!(pThis->ctl & OHCI_CTL_CLE), ("Illegal write! HcControl.ControlListEnabled is set! val=%#010x\n", val));
4617 AssertMsg(!(val & 7), ("Invalid alignment, val=%#010x\n", val));
4618 pThis->ctrl_cur = val & ~7;
4619 RT_NOREF1(iReg);
4620 return VINF_SUCCESS;
4621}
4622
4623/**
4624 * Read the HcBulkHeadED register.
4625 */
4626static int HcBulkHeadED_r(PCOHCI pThis, uint32_t iReg, uint32_t *pu32Value)
4627{
4628 Log2(("HcBulkHeadED_r() -> %#010x\n", pThis->bulk_head));
4629 *pu32Value = pThis->bulk_head;
4630 RT_NOREF1(iReg);
4631 return VINF_SUCCESS;
4632}
4633
4634/**
4635 * Write to the HcBulkHeadED register.
4636 */
4637static int HcBulkHeadED_w(POHCI pThis, uint32_t iReg, uint32_t val)
4638{
4639 Log2(("HcBulkHeadED_w(%#010x) - old=%#010x new=%#010x\n", val, pThis->bulk_head, val & ~7));
4640 AssertMsg(!(val & 7), ("Invalid alignment, val=%#010x\n", val));
4641 pThis->bulk_head = val & ~7; /** @todo The ATI OHCI controller on my machine enforces 16-byte address alignment. */
4642 RT_NOREF1(iReg);
4643 return VINF_SUCCESS;
4644}
4645
4646/**
4647 * Read the HcBulkCurrentED register.
4648 */
4649static int HcBulkCurrentED_r(PCOHCI pThis, uint32_t iReg, uint32_t *pu32Value)
4650{
4651 Log2(("HcBulkCurrentED_r() -> %#010x\n", pThis->bulk_cur));
4652 *pu32Value = pThis->bulk_cur;
4653 RT_NOREF1(iReg);
4654 return VINF_SUCCESS;
4655}
4656
4657/**
4658 * Write to the HcBulkCurrentED register.
4659 */
4660static int HcBulkCurrentED_w(POHCI pThis, uint32_t iReg, uint32_t val)
4661{
4662 Log2(("HcBulkCurrentED_w(%#010x) - old=%#010x new=%#010x\n", val, pThis->bulk_cur, val & ~7));
4663 AssertMsg(!(pThis->ctl & OHCI_CTL_BLE), ("Illegal write! HcControl.BulkListEnabled is set! val=%#010x\n", val));
4664 AssertMsg(!(val & 7), ("Invalid alignment, val=%#010x\n", val));
4665 pThis->bulk_cur = val & ~7;
4666 RT_NOREF1(iReg);
4667 return VINF_SUCCESS;
4668}
4669
4670
4671/**
4672 * Read the HcDoneHead register.
4673 */
4674static int HcDoneHead_r(PCOHCI pThis, uint32_t iReg, uint32_t *pu32Value)
4675{
4676 Log2(("HcDoneHead_r() -> 0x%#08x\n", pThis->done));
4677 *pu32Value = pThis->done;
4678 RT_NOREF1(iReg);
4679 return VINF_SUCCESS;
4680}
4681
4682/**
4683 * Write to the HcDoneHead register.
4684 */
4685static int HcDoneHead_w(POHCI pThis, uint32_t iReg, uint32_t val)
4686{
4687 RT_NOREF3(pThis, iReg, val);
4688 Log2(("HcDoneHead_w(0x%#08x) - denied!!!\n", val));
4689 /*AssertMsgFailed(("Illegal operation!!! val=%#010x\n", val)); - OS/2 does this */
4690 return VINF_SUCCESS;
4691}
4692
4693
4694/**
4695 * Read the HcFmInterval (Fm=Frame) register.
4696 */
4697static int HcFmInterval_r(PCOHCI pThis, uint32_t iReg, uint32_t *pu32Value)
4698{
4699 uint32_t val = (pThis->fit << 31) | (pThis->fsmps << 16) | (pThis->fi);
4700 Log2(("HcFmInterval_r() -> 0x%#08x - FI=%d FSMPS=%d FIT=%d\n",
4701 val, val & 0x3fff, (val >> 16) & 0x7fff, val >> 31));
4702 *pu32Value = val;
4703 RT_NOREF1(iReg);
4704 return VINF_SUCCESS;
4705}
4706
4707/**
4708 * Write to the HcFmInterval (Fm = Frame) register.
4709 */
4710static int HcFmInterval_w(POHCI pThis, uint32_t iReg, uint32_t val)
4711{
4712 RT_NOREF1(iReg);
4713
4714 /* log */
4715 uint32_t chg = val ^ ((pThis->fit << 31) | (pThis->fsmps << 16) | pThis->fi); NOREF(chg);
4716 Log2(("HcFmInterval_w(%#010x) => %sFI=%d %sFSMPS=%d %sFIT=%d\n",
4717 val,
4718 chg & 0x00003fff ? "*" : "", val & 0x3fff,
4719 chg & 0x7fff0000 ? "*" : "", (val >> 16) & 0x7fff,
4720 chg >> 31 ? "*" : "", (val >> 31) & 1));
4721 if ( pThis->fi != (val & OHCI_FMI_FI) )
4722 {
4723 Log(("ohci: FrameInterval: %#010x -> %#010x\n", pThis->fi, val & OHCI_FMI_FI));
4724 AssertMsg(pThis->fit != ((val >> OHCI_FMI_FIT_SHIFT) & 1), ("HCD didn't toggle the FIT bit!!!\n"));
4725 }
4726
4727 /* update */
4728 pThis->fi = val & OHCI_FMI_FI;
4729 pThis->fit = (val & OHCI_FMI_FIT) >> OHCI_FMI_FIT_SHIFT;
4730 pThis->fsmps = (val & OHCI_FMI_FSMPS) >> OHCI_FMI_FSMPS_SHIFT;
4731 return VINF_SUCCESS;
4732}
4733
4734/**
4735 * Read the HcFmRemaining (Fm = Frame) register.
4736 */
4737static int HcFmRemaining_r(PCOHCI pThis, uint32_t iReg, uint32_t *pu32Value)
4738{
4739 RT_NOREF1(iReg);
4740 uint32_t Value = pThis->frt << 31;
4741 if ((pThis->ctl & OHCI_CTL_HCFS) == OHCI_USB_OPERATIONAL)
4742 {
4743 /*
4744 * Being in USB operational state guarantees SofTime was set already.
4745 */
4746 uint64_t tks = PDMDevHlpTMTimeVirtGet(pThis->CTX_SUFF(pDevIns)) - pThis->SofTime;
4747 if (tks < pThis->cTicksPerFrame) /* avoid muldiv if possible */
4748 {
4749 uint16_t fr;
4750 tks = ASMMultU64ByU32DivByU32(1, tks, pThis->cTicksPerUsbTick);
4751 fr = (uint16_t)(pThis->fi - tks);
4752 Value |= fr;
4753 }
4754 }
4755
4756 Log2(("HcFmRemaining_r() -> %#010x - FR=%d FRT=%d\n", Value, Value & 0x3fff, Value >> 31));
4757 *pu32Value = Value;
4758 return VINF_SUCCESS;
4759}
4760
4761/**
4762 * Write to the HcFmRemaining (Fm = Frame) register.
4763 */
4764static int HcFmRemaining_w(POHCI pThis, uint32_t iReg, uint32_t val)
4765{
4766 RT_NOREF3(pThis, iReg, val);
4767 Log2(("HcFmRemaining_w(%#010x) - denied\n", val));
4768 AssertMsgFailed(("Invalid operation!!! val=%#010x\n", val));
4769 return VINF_SUCCESS;
4770}
4771
4772/**
4773 * Read the HcFmNumber (Fm = Frame) register.
4774 */
4775static int HcFmNumber_r(PCOHCI pThis, uint32_t iReg, uint32_t *pu32Value)
4776{
4777 RT_NOREF1(iReg);
4778 uint32_t val = (uint16_t)pThis->HcFmNumber;
4779 Log2(("HcFmNumber_r() -> %#010x - FN=%#x(%d) (32-bit=%#x(%d))\n", val, val, val, pThis->HcFmNumber, pThis->HcFmNumber));
4780 *pu32Value = val;
4781 return VINF_SUCCESS;
4782}
4783
4784/**
4785 * Write to the HcFmNumber (Fm = Frame) register.
4786 */
4787static int HcFmNumber_w(POHCI pThis, uint32_t iReg, uint32_t val)
4788{
4789 RT_NOREF3(pThis, iReg, val);
4790 Log2(("HcFmNumber_w(%#010x) - denied\n", val));
4791 AssertMsgFailed(("Invalid operation!!! val=%#010x\n", val));
4792 return VINF_SUCCESS;
4793}
4794
4795/**
4796 * Read the HcPeriodicStart register.
4797 * The register determines when in a frame to switch from control&bulk to periodic lists.
4798 */
4799static int HcPeriodicStart_r(PCOHCI pThis, uint32_t iReg, uint32_t *pu32Value)
4800{
4801 RT_NOREF1(iReg);
4802 Log2(("HcPeriodicStart_r() -> %#010x - PS=%d\n", pThis->pstart, pThis->pstart & 0x3fff));
4803 *pu32Value = pThis->pstart;
4804 return VINF_SUCCESS;
4805}
4806
4807/**
4808 * Write to the HcPeriodicStart register.
4809 * The register determines when in a frame to switch from control&bulk to periodic lists.
4810 */
4811static int HcPeriodicStart_w(POHCI pThis, uint32_t iReg, uint32_t val)
4812{
4813 RT_NOREF1(iReg);
4814 Log2(("HcPeriodicStart_w(%#010x) => PS=%d\n", val, val & 0x3fff));
4815 if (val & ~0x3fff)
4816 Log2(("Unknown bits %#x are set!!!\n", val & ~0x3fff));
4817 pThis->pstart = val; /** @todo r=bird: should we support setting the other bits? */
4818 return VINF_SUCCESS;
4819}
4820
4821/**
4822 * Read the HcLSThreshold register.
4823 */
4824static int HcLSThreshold_r(PCOHCI pThis, uint32_t iReg, uint32_t *pu32Value)
4825{
4826 RT_NOREF2(pThis, iReg);
4827 Log2(("HcLSThreshold_r() -> %#010x\n", OHCI_LS_THRESH));
4828 *pu32Value = OHCI_LS_THRESH;
4829 return VINF_SUCCESS;
4830}
4831
4832/**
4833 * Write to the HcLSThreshold register.
4834 *
4835 * Docs are inconsistent here:
4836 *
4837 * "Neither the Host Controller nor the Host Controller Driver are allowed to change this value."
4838 *
4839 * "This value is calculated by HCD with the consideration of transmission and setup overhead."
4840 *
4841 * The register is marked "R/W" the HCD column.
4842 *
4843 */
4844static int HcLSThreshold_w(POHCI pThis, uint32_t iReg, uint32_t val)
4845{
4846 RT_NOREF3(pThis, iReg, val);
4847 Log2(("HcLSThreshold_w(%#010x) => LST=0x%03x(%d)\n", val, val & 0x0fff, val & 0x0fff));
4848 AssertMsg(val == OHCI_LS_THRESH,
4849 ("HCD tried to write bad LS threshold: 0x%x (see function header)\n", val));
4850 /** @todo the HCD can change this. */
4851 return VINF_SUCCESS;
4852}
4853
4854/**
4855 * Read the HcRhDescriptorA register.
4856 */
4857static int HcRhDescriptorA_r(PCOHCI pThis, uint32_t iReg, uint32_t *pu32Value)
4858{
4859 RT_NOREF1(iReg);
4860 uint32_t val = pThis->RootHub.desc_a;
4861#if 0 /* annoying */
4862 Log2(("HcRhDescriptorA_r() -> %#010x - NDP=%d PSM=%d NPS=%d DT=%d OCPM=%d NOCP=%d POTGT=%#x\n",
4863 val, val & 0xff, (val >> 8) & 1, (val >> 9) & 1, (val >> 10) & 1, (val >> 11) & 1,
4864 (val >> 12) & 1, (val >> 24) & 0xff));
4865#endif
4866 *pu32Value = val;
4867 return VINF_SUCCESS;
4868}
4869
4870/**
4871 * Write to the HcRhDescriptorA register.
4872 */
4873static int HcRhDescriptorA_w(POHCI pThis, uint32_t iReg, uint32_t val)
4874{
4875 RT_NOREF1(iReg);
4876 uint32_t chg = val ^ pThis->RootHub.desc_a; NOREF(chg);
4877 Log2(("HcRhDescriptorA_w(%#010x) => %sNDP=%d %sPSM=%d %sNPS=%d %sDT=%d %sOCPM=%d %sNOCP=%d %sPOTGT=%#x - %sPowerSwitching Set%sPower\n",
4878 val,
4879 chg & 0xff ?"!!!": "", val & 0xff,
4880 (chg >> 8) & 1 ? "*" : "", (val >> 8) & 1,
4881 (chg >> 9) & 1 ? "*" : "", (val >> 9) & 1,
4882 (chg >> 10) & 1 ?"!!!": "", 0,
4883 (chg >> 11) & 1 ? "*" : "", (val >> 11) & 1,
4884 (chg >> 12) & 1 ? "*" : "", (val >> 12) & 1,
4885 (chg >> 24)&0xff? "*" : "", (val >> 24) & 0xff,
4886 val & OHCI_RHA_NPS ? "No" : "",
4887 val & OHCI_RHA_PSM ? "Port" : "Global"));
4888 if (val & ~0xff001fff)
4889 Log2(("Unknown bits %#x are set!!!\n", val & ~0xff001fff));
4890
4891
4892 if ((val & (OHCI_RHA_NDP | OHCI_RHA_DT)) != OHCI_NDP_CFG(pThis))
4893 {
4894 Log(("ohci: %s: invalid write to NDP or DT in roothub descriptor A!!! val=0x%.8x\n",
4895 pThis->PciDev.pszNameR3, val));
4896 val &= ~(OHCI_RHA_NDP | OHCI_RHA_DT);
4897 val |= OHCI_NDP_CFG(pThis);
4898 }
4899
4900 pThis->RootHub.desc_a = val;
4901 return VINF_SUCCESS;
4902}
4903
4904/**
4905 * Read the HcRhDescriptorB register.
4906 */
4907static int HcRhDescriptorB_r(PCOHCI pThis, uint32_t iReg, uint32_t *pu32Value)
4908{
4909 uint32_t val = pThis->RootHub.desc_b;
4910 Log2(("HcRhDescriptorB_r() -> %#010x - DR=0x%04x PPCM=0x%04x\n",
4911 val, val & 0xffff, val >> 16));
4912 *pu32Value = val;
4913 RT_NOREF1(iReg);
4914 return VINF_SUCCESS;
4915}
4916
4917/**
4918 * Write to the HcRhDescriptorB register.
4919 */
4920static int HcRhDescriptorB_w(POHCI pThis, uint32_t iReg, uint32_t val)
4921{
4922 RT_NOREF1(iReg);
4923 uint32_t chg = pThis->RootHub.desc_b ^ val; NOREF(chg);
4924 Log2(("HcRhDescriptorB_w(%#010x) => %sDR=0x%04x %sPPCM=0x%04x\n",
4925 val,
4926 chg & 0xffff ? "!!!" : "", val & 0xffff,
4927 chg >> 16 ? "!!!" : "", val >> 16));
4928
4929 if ( pThis->RootHub.desc_b != val )
4930 Log(("ohci: %s: unsupported write to root descriptor B!!! 0x%.8x -> 0x%.8x\n",
4931 pThis->PciDev.pszNameR3, pThis->RootHub.desc_b, val));
4932 pThis->RootHub.desc_b = val;
4933 return VINF_SUCCESS;
4934}
4935
4936/**
4937 * Read the HcRhStatus (Rh = Root Hub) register.
4938 */
4939static int HcRhStatus_r(PCOHCI pThis, uint32_t iReg, uint32_t *pu32Value)
4940{
4941 uint32_t val = pThis->RootHub.status;
4942 if (val & (OHCI_RHS_LPSC | OHCI_RHS_OCIC))
4943 Log2(("HcRhStatus_r() -> %#010x - LPS=%d OCI=%d DRWE=%d LPSC=%d OCIC=%d CRWE=%d\n",
4944 val, val & 1, (val >> 1) & 1, (val >> 15) & 1, (val >> 16) & 1, (val >> 17) & 1, (val >> 31) & 1));
4945 *pu32Value = val;
4946 RT_NOREF1(iReg);
4947 return VINF_SUCCESS;
4948}
4949
4950/**
4951 * Write to the HcRhStatus (Rh = Root Hub) register.
4952 */
4953static int HcRhStatus_w(POHCI pThis, uint32_t iReg, uint32_t val)
4954{
4955#ifdef IN_RING3
4956 /* log */
4957 uint32_t old = pThis->RootHub.status;
4958 uint32_t chg;
4959 if (val & ~0x80038003)
4960 Log2(("HcRhStatus_w: Unknown bits %#x are set!!!\n", val & ~0x80038003));
4961 if ( (val & OHCI_RHS_LPSC) && (val & OHCI_RHS_LPS) )
4962 Log2(("HcRhStatus_w: Warning both CGP and SGP are set! (Clear/Set Global Power)\n"));
4963 if ( (val & OHCI_RHS_DRWE) && (val & OHCI_RHS_CRWE) )
4964 Log2(("HcRhStatus_w: Warning both CRWE and SRWE are set! (Clear/Set Remote Wakeup Enable)\n"));
4965
4966
4967 /* write 1 to clear OCIC */
4968 if ( val & OHCI_RHS_OCIC )
4969 pThis->RootHub.status &= ~OHCI_RHS_OCIC;
4970
4971 /* SetGlobalPower */
4972 if ( val & OHCI_RHS_LPSC )
4973 {
4974 unsigned i;
4975 Log2(("ohci: %s: global power up\n", pThis->PciDev.pszNameR3));
4976 for (i = 0; i < OHCI_NDP_CFG(pThis); i++)
4977 rhport_power(&pThis->RootHub, i, true /* power up */);
4978 }
4979
4980 /* ClearGlobalPower */
4981 if ( val & OHCI_RHS_LPS )
4982 {
4983 unsigned i;
4984 Log2(("ohci: %s: global power down\n", pThis->PciDev.pszNameR3));
4985 for (i = 0; i < OHCI_NDP_CFG(pThis); i++)
4986 rhport_power(&pThis->RootHub, i, false /* power down */);
4987 }
4988
4989 if ( val & OHCI_RHS_DRWE )
4990 pThis->RootHub.status |= OHCI_RHS_DRWE;
4991
4992 if ( val & OHCI_RHS_CRWE )
4993 pThis->RootHub.status &= ~OHCI_RHS_DRWE;
4994
4995 chg = pThis->RootHub.status ^ old;
4996 Log2(("HcRhStatus_w(%#010x) => %sCGP=%d %sOCI=%d %sSRWE=%d %sSGP=%d %sOCIC=%d %sCRWE=%d\n",
4997 val,
4998 chg & 1 ? "*" : "", val & 1,
4999 (chg >> 1) & 1 ?"!!!": "", (val >> 1) & 1,
5000 (chg >> 15) & 1 ? "*" : "", (val >> 15) & 1,
5001 (chg >> 16) & 1 ? "*" : "", (val >> 16) & 1,
5002 (chg >> 17) & 1 ? "*" : "", (val >> 17) & 1,
5003 (chg >> 31) & 1 ? "*" : "", (val >> 31) & 1));
5004 RT_NOREF1(iReg);
5005 return VINF_SUCCESS;
5006#else /* !IN_RING3 */
5007 RT_NOREF3(pThis, iReg, val);
5008 return VINF_IOM_R3_MMIO_WRITE;
5009#endif /* !IN_RING3 */
5010}
5011
5012/**
5013 * Read the HcRhPortStatus register of a port.
5014 */
5015static int HcRhPortStatus_r(PCOHCI pThis, uint32_t iReg, uint32_t *pu32Value)
5016{
5017 const unsigned i = iReg - 21;
5018 uint32_t val = pThis->RootHub.aPorts[i].fReg | OHCI_PORT_R_POWER_STATUS; /* PortPowerStatus: see todo on power in _w function. */
5019 if (val & OHCI_PORT_R_RESET_STATUS)
5020 {
5021#ifdef IN_RING3
5022 RTThreadYield();
5023#else
5024 Log2(("HcRhPortStatus_r: yield -> VINF_IOM_R3_MMIO_READ\n"));
5025 return VINF_IOM_R3_MMIO_READ;
5026#endif
5027 }
5028 if (val & (OHCI_PORT_R_RESET_STATUS | OHCI_PORT_CSC | OHCI_PORT_PESC | OHCI_PORT_PSSC | OHCI_PORT_OCIC | OHCI_PORT_PRSC))
5029 Log2(("HcRhPortStatus_r(): port %u: -> %#010x - CCS=%d PES=%d PSS=%d POCI=%d RRS=%d PPS=%d LSDA=%d CSC=%d PESC=%d PSSC=%d OCIC=%d PRSC=%d\n",
5030 i, val, val & 1, (val >> 1) & 1, (val >> 2) & 1, (val >> 3) & 1, (val >> 4) & 1, (val >> 8) & 1, (val >> 9) & 1,
5031 (val >> 16) & 1, (val >> 17) & 1, (val >> 18) & 1, (val >> 19) & 1, (val >> 20) & 1));
5032 *pu32Value = val;
5033 return VINF_SUCCESS;
5034}
5035
5036#ifdef IN_RING3
5037/**
5038 * Completion callback for the vusb_dev_reset() operation.
5039 * @thread EMT.
5040 */
5041static DECLCALLBACK(void) uchi_port_reset_done(PVUSBIDEVICE pDev, int rc, void *pvUser)
5042{
5043 POHCI pThis = (POHCI)pvUser;
5044
5045 /*
5046 * Find the port in question
5047 */
5048 POHCIHUBPORT pPort = NULL;
5049 unsigned iPort;
5050 for (iPort = 0; iPort < OHCI_NDP_CFG(pThis); iPort++) /* lazy bird */
5051 if (pThis->RootHub.aPorts[iPort].pDev == pDev)
5052 {
5053 pPort = &pThis->RootHub.aPorts[iPort];
5054 break;
5055 }
5056 if (!pPort)
5057 {
5058 Assert(pPort); /* sometimes happens because of @bugref{1510} */
5059 return;
5060 }
5061
5062 if (RT_SUCCESS(rc))
5063 {
5064 /*
5065 * Successful reset.
5066 */
5067 Log2(("uchi_port_reset_done: Reset completed.\n"));
5068 pPort->fReg &= ~(OHCI_PORT_R_RESET_STATUS | OHCI_PORT_R_SUSPEND_STATUS | OHCI_PORT_R_SUSPEND_STATUS_CHANGE);
5069 pPort->fReg |= OHCI_PORT_R_ENABLE_STATUS | OHCI_PORT_R_RESET_STATUS_CHANGE;
5070 }
5071 else
5072 {
5073 /* desperate measures. */
5074 if ( pPort->pDev
5075 && VUSBIDevGetState(pPort->pDev) == VUSB_DEVICE_STATE_ATTACHED)
5076 {
5077 /*
5078 * Damn, something weird happened during reset. We'll pretend the user did an
5079 * incredible fast reconnect or something. (probably not gonna work)
5080 */
5081 Log2(("uchi_port_reset_done: The reset failed (rc=%Rrc)!!! Pretending reconnect at the speed of light.\n", rc));
5082 pPort->fReg = OHCI_PORT_R_CURRENT_CONNECT_STATUS | OHCI_PORT_R_CONNECT_STATUS_CHANGE;
5083 }
5084 else
5085 {
5086 /*
5087 * The device have / will be disconnected.
5088 */
5089 Log2(("uchi_port_reset_done: Disconnected (rc=%Rrc)!!!\n", rc));
5090 pPort->fReg &= ~(OHCI_PORT_R_RESET_STATUS | OHCI_PORT_R_SUSPEND_STATUS | OHCI_PORT_R_SUSPEND_STATUS_CHANGE | OHCI_PORT_R_RESET_STATUS_CHANGE);
5091 pPort->fReg |= OHCI_PORT_R_CONNECT_STATUS_CHANGE;
5092 }
5093 }
5094
5095 /* Raise roothub status change interrupt. */
5096 ohciR3SetInterrupt(pThis, OHCI_INTR_ROOT_HUB_STATUS_CHANGE);
5097}
5098
5099/**
5100 * Sets a flag in a port status register but only set it if a device is
5101 * connected, if not set ConnectStatusChange flag to force HCD to reevaluate
5102 * connect status.
5103 *
5104 * @returns true if device was connected and the flag was cleared.
5105 */
5106static bool rhport_set_if_connected(POHCIROOTHUB pRh, int iPort, uint32_t fValue)
5107{
5108 /*
5109 * Writing a 0 has no effect
5110 */
5111 if (fValue == 0)
5112 return false;
5113
5114 /*
5115 * If CurrentConnectStatus is cleared we set ConnectStatusChange.
5116 */
5117 if (!(pRh->aPorts[iPort].fReg & OHCI_PORT_R_CURRENT_CONNECT_STATUS))
5118 {
5119 pRh->aPorts[iPort].fReg |= OHCI_PORT_R_CONNECT_STATUS_CHANGE;
5120 ohciR3SetInterrupt(pRh->pOhci, OHCI_INTR_ROOT_HUB_STATUS_CHANGE);
5121 return false;
5122 }
5123
5124 bool fRc = !(pRh->aPorts[iPort].fReg & fValue);
5125
5126 /* set the bit */
5127 pRh->aPorts[iPort].fReg |= fValue;
5128
5129 return fRc;
5130}
5131#endif /* IN_RING3 */
5132
5133/**
5134 * Write to the HcRhPortStatus register of a port.
5135 */
5136static int HcRhPortStatus_w(POHCI pThis, uint32_t iReg, uint32_t val)
5137{
5138#ifdef IN_RING3
5139 const unsigned i = iReg - 21;
5140 POHCIHUBPORT p = &pThis->RootHub.aPorts[i];
5141 uint32_t old_state = p->fReg;
5142
5143# ifdef LOG_ENABLED
5144 /*
5145 * Log it.
5146 */
5147 static const char *apszCmdNames[32] =
5148 {
5149 "ClearPortEnable", "SetPortEnable", "SetPortSuspend", "!!!ClearSuspendStatus",
5150 "SetPortReset", "!!!5", "!!!6", "!!!7",
5151 "SetPortPower", "ClearPortPower", "!!!10", "!!!11",
5152 "!!!12", "!!!13", "!!!14", "!!!15",
5153 "ClearCSC", "ClearPESC", "ClearPSSC", "ClearOCIC",
5154 "ClearPRSC", "!!!21", "!!!22", "!!!23",
5155 "!!!24", "!!!25", "!!!26", "!!!27",
5156 "!!!28", "!!!29", "!!!30", "!!!31"
5157 };
5158 Log2(("HcRhPortStatus_w(%#010x): port %u:", val, i));
5159 for (unsigned j = 0; j < RT_ELEMENTS(apszCmdNames); j++)
5160 if (val & (1 << j))
5161 Log2((" %s", apszCmdNames[j]));
5162 Log2(("\n"));
5163# endif
5164
5165 /* Write to clear any of the change bits: CSC, PESC, PSSC, OCIC and PRSC */
5166 if (val & OHCI_PORT_W_CLEAR_CHANGE_MASK)
5167 p->fReg &= ~(val & OHCI_PORT_W_CLEAR_CHANGE_MASK);
5168
5169 if (val & OHCI_PORT_W_CLEAR_ENABLE)
5170 {
5171 p->fReg &= ~OHCI_PORT_R_ENABLE_STATUS;
5172 Log2(("HcRhPortStatus_w(): port %u: DISABLE\n", i));
5173 }
5174
5175 if (rhport_set_if_connected(&pThis->RootHub, i, val & OHCI_PORT_W_SET_ENABLE))
5176 Log2(("HcRhPortStatus_w(): port %u: ENABLE\n", i));
5177
5178 if (rhport_set_if_connected(&pThis->RootHub, i, val & OHCI_PORT_W_SET_SUSPEND))
5179 Log2(("HcRhPortStatus_w(): port %u: SUSPEND - not implemented correctly!!!\n", i));
5180
5181 if (val & OHCI_PORT_W_SET_RESET)
5182 {
5183 if (rhport_set_if_connected(&pThis->RootHub, i, val & OHCI_PORT_W_SET_RESET))
5184 {
5185 PVM pVM = PDMDevHlpGetVM(pThis->CTX_SUFF(pDevIns));
5186 p->fReg &= ~OHCI_PORT_R_RESET_STATUS_CHANGE;
5187 VUSBIDevReset(p->pDev, false /* don't reset on linux */, uchi_port_reset_done, pThis, pVM);
5188 }
5189 else if (p->fReg & OHCI_PORT_R_RESET_STATUS)
5190 {
5191 /* the guest is getting impatient. */
5192 Log2(("HcRhPortStatus_w(): port %u: Impatient guest!\n", i));
5193 RTThreadYield();
5194 }
5195 }
5196
5197 if (!(pThis->RootHub.desc_a & OHCI_RHA_NPS))
5198 {
5199 /** @todo To implement per-device power-switching
5200 * we need to check PortPowerControlMask to make
5201 * sure it isn't gang powered
5202 */
5203 if (val & OHCI_PORT_W_CLEAR_POWER)
5204 rhport_power(&pThis->RootHub, i, false /* power down */);
5205 if (val & OHCI_PORT_W_SET_POWER)
5206 rhport_power(&pThis->RootHub, i, true /* power up */);
5207 }
5208
5209 /** @todo r=frank: ClearSuspendStatus. Timing? */
5210 if (val & OHCI_PORT_W_CLEAR_SUSPEND_STATUS)
5211 {
5212 rhport_power(&pThis->RootHub, i, true /* power up */);
5213 pThis->RootHub.aPorts[i].fReg &= ~OHCI_PORT_R_SUSPEND_STATUS;
5214 pThis->RootHub.aPorts[i].fReg |= OHCI_PORT_R_SUSPEND_STATUS_CHANGE;
5215 ohciR3SetInterrupt(pThis, OHCI_INTR_ROOT_HUB_STATUS_CHANGE);
5216 }
5217
5218 if (p->fReg != old_state)
5219 {
5220 uint32_t res = p->fReg;
5221 uint32_t chg = res ^ old_state; NOREF(chg);
5222 Log2(("HcRhPortStatus_w(%#010x): port %u: => %sCCS=%d %sPES=%d %sPSS=%d %sPOCI=%d %sRRS=%d %sPPS=%d %sLSDA=%d %sCSC=%d %sPESC=%d %sPSSC=%d %sOCIC=%d %sPRSC=%d\n",
5223 val, i,
5224 chg & 1 ? "*" : "", res & 1,
5225 (chg >> 1) & 1 ? "*" : "", (res >> 1) & 1,
5226 (chg >> 2) & 1 ? "*" : "", (res >> 2) & 1,
5227 (chg >> 3) & 1 ? "*" : "", (res >> 3) & 1,
5228 (chg >> 4) & 1 ? "*" : "", (res >> 4) & 1,
5229 (chg >> 8) & 1 ? "*" : "", (res >> 8) & 1,
5230 (chg >> 9) & 1 ? "*" : "", (res >> 9) & 1,
5231 (chg >> 16) & 1 ? "*" : "", (res >> 16) & 1,
5232 (chg >> 17) & 1 ? "*" : "", (res >> 17) & 1,
5233 (chg >> 18) & 1 ? "*" : "", (res >> 18) & 1,
5234 (chg >> 19) & 1 ? "*" : "", (res >> 19) & 1,
5235 (chg >> 20) & 1 ? "*" : "", (res >> 20) & 1));
5236 }
5237 return VINF_SUCCESS;
5238#else /* !IN_RING3 */
5239 RT_NOREF3(pThis, iReg, val);
5240 return VINF_IOM_R3_MMIO_WRITE;
5241#endif /* !IN_RING3 */
5242}
5243
5244/**
5245 * Register descriptor table
5246 */
5247static const OHCIOPREG g_aOpRegs[] =
5248{
5249 { "HcRevision", HcRevision_r, HcRevision_w }, /* 0 */
5250 { "HcControl", HcControl_r, HcControl_w }, /* 1 */
5251 { "HcCommandStatus", HcCommandStatus_r, HcCommandStatus_w }, /* 2 */
5252 { "HcInterruptStatus", HcInterruptStatus_r, HcInterruptStatus_w }, /* 3 */
5253 { "HcInterruptEnable", HcInterruptEnable_r, HcInterruptEnable_w }, /* 4 */
5254 { "HcInterruptDisable", HcInterruptDisable_r, HcInterruptDisable_w }, /* 5 */
5255 { "HcHCCA", HcHCCA_r, HcHCCA_w }, /* 6 */
5256 { "HcPeriodCurrentED", HcPeriodCurrentED_r, HcPeriodCurrentED_w }, /* 7 */
5257 { "HcControlHeadED", HcControlHeadED_r, HcControlHeadED_w }, /* 8 */
5258 { "HcControlCurrentED", HcControlCurrentED_r, HcControlCurrentED_w }, /* 9 */
5259 { "HcBulkHeadED", HcBulkHeadED_r, HcBulkHeadED_w }, /* 10 */
5260 { "HcBulkCurrentED", HcBulkCurrentED_r, HcBulkCurrentED_w }, /* 11 */
5261 { "HcDoneHead", HcDoneHead_r, HcDoneHead_w }, /* 12 */
5262 { "HcFmInterval", HcFmInterval_r, HcFmInterval_w }, /* 13 */
5263 { "HcFmRemaining", HcFmRemaining_r, HcFmRemaining_w }, /* 14 */
5264 { "HcFmNumber", HcFmNumber_r, HcFmNumber_w }, /* 15 */
5265 { "HcPeriodicStart", HcPeriodicStart_r, HcPeriodicStart_w }, /* 16 */
5266 { "HcLSThreshold", HcLSThreshold_r, HcLSThreshold_w }, /* 17 */
5267 { "HcRhDescriptorA", HcRhDescriptorA_r, HcRhDescriptorA_w }, /* 18 */
5268 { "HcRhDescriptorB", HcRhDescriptorB_r, HcRhDescriptorB_w }, /* 19 */
5269 { "HcRhStatus", HcRhStatus_r, HcRhStatus_w }, /* 20 */
5270
5271 /* The number of port status register depends on the definition
5272 * of OHCI_NDP_MAX macro
5273 */
5274 { "HcRhPortStatus[0]", HcRhPortStatus_r, HcRhPortStatus_w }, /* 21 */
5275 { "HcRhPortStatus[1]", HcRhPortStatus_r, HcRhPortStatus_w }, /* 22 */
5276 { "HcRhPortStatus[2]", HcRhPortStatus_r, HcRhPortStatus_w }, /* 23 */
5277 { "HcRhPortStatus[3]", HcRhPortStatus_r, HcRhPortStatus_w }, /* 24 */
5278 { "HcRhPortStatus[4]", HcRhPortStatus_r, HcRhPortStatus_w }, /* 25 */
5279 { "HcRhPortStatus[5]", HcRhPortStatus_r, HcRhPortStatus_w }, /* 26 */
5280 { "HcRhPortStatus[6]", HcRhPortStatus_r, HcRhPortStatus_w }, /* 27 */
5281 { "HcRhPortStatus[7]", HcRhPortStatus_r, HcRhPortStatus_w }, /* 28 */
5282 { "HcRhPortStatus[8]", HcRhPortStatus_r, HcRhPortStatus_w }, /* 29 */
5283 { "HcRhPortStatus[9]", HcRhPortStatus_r, HcRhPortStatus_w }, /* 30 */
5284 { "HcRhPortStatus[10]", HcRhPortStatus_r, HcRhPortStatus_w }, /* 31 */
5285 { "HcRhPortStatus[11]", HcRhPortStatus_r, HcRhPortStatus_w }, /* 32 */
5286 { "HcRhPortStatus[12]", HcRhPortStatus_r, HcRhPortStatus_w }, /* 33 */
5287 { "HcRhPortStatus[13]", HcRhPortStatus_r, HcRhPortStatus_w }, /* 34 */
5288 { "HcRhPortStatus[14]", HcRhPortStatus_r, HcRhPortStatus_w }, /* 35 */
5289};
5290
5291/* Quick way to determine how many op regs are valid. Since at least one port must
5292 * be configured (and no more than 15), there will be between 22 and 36 registers.
5293 */
5294#define NUM_OP_REGS(pohci) (21 + OHCI_NDP_CFG(pohci))
5295
5296AssertCompile(RT_ELEMENTS(g_aOpRegs) > 21);
5297AssertCompile(RT_ELEMENTS(g_aOpRegs) <= 36);
5298
5299/**
5300 * @callback_method_impl{FNIOMMMIOREAD}
5301 */
5302PDMBOTHCBDECL(int) ohciMmioRead(PPDMDEVINS pDevIns, void *pvUser, RTGCPHYS GCPhysAddr, void *pv, unsigned cb)
5303{
5304 POHCI pThis = PDMINS_2_DATA(pDevIns, POHCI);
5305 RT_NOREF1(pvUser);
5306
5307 /* Paranoia: Assert that IOMMMIO_FLAGS_READ_DWORD works. */
5308 AssertReturn(cb == sizeof(uint32_t), VERR_INTERNAL_ERROR_3);
5309 AssertReturn(!(GCPhysAddr & 0x3), VERR_INTERNAL_ERROR_4);
5310
5311 /*
5312 * Validate the register and call the read operator.
5313 */
5314 int rc;
5315 const uint32_t iReg = (GCPhysAddr - pThis->MMIOBase) >> 2;
5316 if (iReg < NUM_OP_REGS(pThis))
5317 {
5318 const OHCIOPREG *pReg = &g_aOpRegs[iReg];
5319 rc = pReg->pfnRead(pThis, iReg, (uint32_t *)pv);
5320 }
5321 else
5322 {
5323 Log(("ohci: Trying to read register %u/%u!!!\n", iReg, NUM_OP_REGS(pThis)));
5324 rc = VINF_IOM_MMIO_UNUSED_FF;
5325 }
5326 return rc;
5327}
5328
5329
5330/**
5331 * @callback_method_impl{FNIOMMMIOWRITE}
5332 */
5333PDMBOTHCBDECL(int) ohciMmioWrite(PPDMDEVINS pDevIns, void *pvUser, RTGCPHYS GCPhysAddr, void const *pv, unsigned cb)
5334{
5335 POHCI pThis = PDMINS_2_DATA(pDevIns, POHCI);
5336 RT_NOREF1(pvUser);
5337
5338 /* Paranoia: Assert that IOMMMIO_FLAGS_WRITE_DWORD_ZEROED works. */
5339 AssertReturn(cb == sizeof(uint32_t), VERR_INTERNAL_ERROR_3);
5340 AssertReturn(!(GCPhysAddr & 0x3), VERR_INTERNAL_ERROR_4);
5341
5342 /*
5343 * Validate the register and call the read operator.
5344 */
5345 int rc;
5346 const uint32_t iReg = (GCPhysAddr - pThis->MMIOBase) >> 2;
5347 if (iReg < NUM_OP_REGS(pThis))
5348 {
5349 const OHCIOPREG *pReg = &g_aOpRegs[iReg];
5350 rc = pReg->pfnWrite(pThis, iReg, *(uint32_t const *)pv);
5351 }
5352 else
5353 {
5354 Log(("ohci: Trying to write to register %u/%u!!!\n", iReg, NUM_OP_REGS(pThis)));
5355 rc = VINF_SUCCESS;
5356 }
5357 return rc;
5358}
5359
5360#ifdef IN_RING3
5361
5362/**
5363 * @callback_method_impl{FNPCIIOREGIONMAP}
5364 */
5365static DECLCALLBACK(int) ohciR3Map(PPDMDEVINS pDevIns, PPDMPCIDEV pPciDev, uint32_t iRegion,
5366 RTGCPHYS GCPhysAddress, RTGCPHYS cb, PCIADDRESSSPACE enmType)
5367{
5368 RT_NOREF(iRegion, enmType);
5369 POHCI pThis = (POHCI)pPciDev;
5370 int rc = PDMDevHlpMMIORegister(pDevIns, GCPhysAddress, cb, NULL /*pvUser*/,
5371 IOMMMIO_FLAGS_READ_DWORD | IOMMMIO_FLAGS_WRITE_DWORD_ZEROED
5372 | IOMMMIO_FLAGS_DBGSTOP_ON_COMPLICATED_WRITE,
5373 ohciMmioWrite, ohciMmioRead, "USB OHCI");
5374 if (RT_FAILURE(rc))
5375 return rc;
5376
5377 if (pThis->fRZEnabled)
5378 {
5379 rc = PDMDevHlpMMIORegisterRC(pDevIns, GCPhysAddress, cb, NIL_RTRCPTR /*pvUser*/, "ohciMmioWrite", "ohciMmioRead");
5380 if (RT_FAILURE(rc))
5381 return rc;
5382
5383 rc = PDMDevHlpMMIORegisterR0(pDevIns, GCPhysAddress, cb, NIL_RTR0PTR /*pvUser*/, "ohciMmioWrite", "ohciMmioRead");
5384 if (RT_FAILURE(rc))
5385 return rc;
5386 }
5387
5388 pThis->MMIOBase = GCPhysAddress;
5389 return VINF_SUCCESS;
5390}
5391
5392
5393/**
5394 * Prepares for state saving.
5395 * All URBs needs to be canceled.
5396 *
5397 * @returns VBox status code.
5398 * @param pDevIns The device instance.
5399 * @param pSSM The handle to save the state to.
5400 */
5401static DECLCALLBACK(int) ohciR3SavePrep(PPDMDEVINS pDevIns, PSSMHANDLE pSSM)
5402{
5403 RT_NOREF(pSSM);
5404 POHCI pThis = PDMINS_2_DATA(pDevIns, POHCI);
5405 POHCIROOTHUB pRh = &pThis->RootHub;
5406 LogFlow(("ohciR3SavePrep: \n"));
5407
5408 /*
5409 * Detach all proxied devices.
5410 */
5411 PDMCritSectEnter(pThis->pDevInsR3->pCritSectRoR3, VERR_IGNORED);
5412 /** @todo this won't work well when continuing after saving! */
5413 for (unsigned i = 0; i < RT_ELEMENTS(pRh->aPorts); i++)
5414 {
5415 PVUSBIDEVICE pDev = pRh->aPorts[i].pDev;
5416 if (pDev)
5417 {
5418 if (!VUSBIDevIsSavedStateSupported(pDev))
5419 {
5420 VUSBIRhDetachDevice(pRh->pIRhConn, pDev);
5421 /*
5422 * Save the device pointers here so we can reattach them afterwards.
5423 * This will work fine even if the save fails since the Done handler is
5424 * called unconditionally if the Prep handler was called.
5425 */
5426 pRh->aPorts[i].pDev = pDev;
5427 }
5428 }
5429 }
5430
5431 /*
5432 * If the bus was started set the timer. This is ugly but avoids changing the
5433 * saved state version for now so we can backport the changes to other branches.
5434 */
5435 /** @todo Do it properly for 4.4 by changing the saved state. */
5436 if (VUSBIRhGetPeriodicFrameRate(pRh->pIRhConn) != 0)
5437 {
5438 /* Calculate a new timer expiration so this saved state works with older releases. */
5439 uint64_t u64Expire = PDMDevHlpTMTimeVirtGet(pThis->CTX_SUFF(pDevIns)) + pThis->cTicksPerFrame;
5440
5441 LogFlowFunc(("Bus is active, setting timer to %llu\n", u64Expire));
5442 int rc = TMTimerSet(pThis->pEndOfFrameTimerR3, u64Expire);
5443 AssertRC(rc);
5444 }
5445
5446 PDMCritSectLeave(pThis->pDevInsR3->pCritSectRoR3);
5447
5448 /*
5449 * Kill old load data which might be hanging around.
5450 */
5451 if (pThis->pLoad)
5452 {
5453 TMR3TimerDestroy(pThis->pLoad->pTimer);
5454 MMR3HeapFree(pThis->pLoad);
5455 pThis->pLoad = NULL;
5456 }
5457 return VINF_SUCCESS;
5458}
5459
5460
5461/**
5462 * Saves the state of the OHCI device.
5463 *
5464 * @returns VBox status code.
5465 * @param pDevIns The device instance.
5466 * @param pSSM The handle to save the state to.
5467 */
5468static DECLCALLBACK(int) ohciR3SaveExec(PPDMDEVINS pDevIns, PSSMHANDLE pSSM)
5469{
5470 POHCI pThis = PDMINS_2_DATA(pDevIns, POHCI);
5471 LogFlow(("ohciR3SaveExec: \n"));
5472
5473 int rc = SSMR3PutStructEx(pSSM, pThis, sizeof(*pThis), 0 /*fFlags*/, &g_aOhciFields[0], NULL);
5474 if (RT_SUCCESS(rc))
5475 rc = TMR3TimerSave(pThis->CTX_SUFF(pEndOfFrameTimer), pSSM);
5476 return rc;
5477}
5478
5479
5480/**
5481 * Done state save operation.
5482 *
5483 * @returns VBox load code.
5484 * @param pDevIns Device instance of the device which registered the data unit.
5485 * @param pSSM SSM operation handle.
5486 */
5487static DECLCALLBACK(int) ohciR3SaveDone(PPDMDEVINS pDevIns, PSSMHANDLE pSSM)
5488{
5489 RT_NOREF(pSSM);
5490 POHCI pThis = PDMINS_2_DATA(pDevIns, POHCI);
5491 LogFlow(("ohciR3SaveDone: \n"));
5492
5493 /*
5494 * NULL the dev pointers.
5495 */
5496 POHCIROOTHUB pRh = &pThis->RootHub;
5497 OHCIROOTHUB Rh = *pRh;
5498 for (unsigned i = 0; i < RT_ELEMENTS(pRh->aPorts); i++)
5499 {
5500 if ( pRh->aPorts[i].pDev
5501 && !VUSBIDevIsSavedStateSupported(pRh->aPorts[i].pDev))
5502 pRh->aPorts[i].pDev = NULL;
5503 }
5504
5505 /*
5506 * Attach the devices.
5507 */
5508 for (unsigned i = 0; i < RT_ELEMENTS(pRh->aPorts); i++)
5509 {
5510 PVUSBIDEVICE pDev = Rh.aPorts[i].pDev;
5511 if ( pDev
5512 && !VUSBIDevIsSavedStateSupported(pDev))
5513 VUSBIRhAttachDevice(pRh->pIRhConn, pDev);
5514 }
5515
5516 return VINF_SUCCESS;
5517}
5518
5519
5520/**
5521 * Prepare loading the state of the OHCI device.
5522 * This must detach the devices currently attached and save
5523 * the up for reconnect after the state load have been completed
5524 *
5525 * @returns VBox status code.
5526 * @param pDevIns The device instance.
5527 * @param pSSM The handle to the saved state.
5528 */
5529static DECLCALLBACK(int) ohciR3LoadPrep(PPDMDEVINS pDevIns, PSSMHANDLE pSSM)
5530{
5531 RT_NOREF(pSSM);
5532 POHCI pThis = PDMINS_2_DATA(pDevIns, POHCI);
5533 LogFlow(("ohciR3LoadPrep:\n"));
5534 if (!pThis->pLoad)
5535 {
5536 /*
5537 * Detach all devices which are present in this session. Save them in the load
5538 * structure so we can reattach them after restoring the guest.
5539 */
5540 POHCIROOTHUB pRh = &pThis->RootHub;
5541 OHCILOAD Load;
5542 Load.pTimer = NULL;
5543 Load.cDevs = 0;
5544 for (unsigned i = 0; i < RT_ELEMENTS(pRh->aPorts); i++)
5545 {
5546 PVUSBIDEVICE pDev = pRh->aPorts[i].pDev;
5547 if ( pDev
5548 && !VUSBIDevIsSavedStateSupported(pDev))
5549 {
5550 Load.apDevs[Load.cDevs++] = pDev;
5551 VUSBIRhDetachDevice(pRh->pIRhConn, pDev);
5552 Assert(!pRh->aPorts[i].pDev);
5553 }
5554 }
5555
5556 /*
5557 * Any devices to reattach, if so duplicate the Load struct.
5558 */
5559 if (Load.cDevs)
5560 {
5561 pThis->pLoad = (POHCILOAD)PDMDevHlpMMHeapAlloc(pDevIns, sizeof(Load));
5562 if (!pThis->pLoad)
5563 return VERR_NO_MEMORY;
5564 *pThis->pLoad = Load;
5565 }
5566 }
5567 /* else: we ASSUME no device can be attached or detach in the period
5568 * between a state load and the pLoad stuff is processed. */
5569 return VINF_SUCCESS;
5570}
5571
5572
5573/**
5574 * Loads the state of the OHCI device.
5575 *
5576 * @returns VBox status code.
5577 * @param pDevIns The device instance.
5578 * @param pSSM The handle to the saved state.
5579 * @param uVersion The data unit version number.
5580 * @param uPass The data pass.
5581 */
5582static DECLCALLBACK(int) ohciR3LoadExec(PPDMDEVINS pDevIns, PSSMHANDLE pSSM, uint32_t uVersion, uint32_t uPass)
5583{
5584 POHCI pThis = PDMINS_2_DATA(pDevIns, POHCI);
5585 int rc;
5586 LogFlow(("ohciR3LoadExec:\n"));
5587 Assert(uPass == SSM_PASS_FINAL); NOREF(uPass);
5588
5589 if (uVersion == OHCI_SAVED_STATE_VERSION)
5590 {
5591 rc = SSMR3GetStructEx(pSSM, pThis, sizeof(*pThis), 0 /*fFlags*/, &g_aOhciFields[0], NULL);
5592 if (RT_FAILURE(rc))
5593 return rc;
5594 }
5595 else if (uVersion == OHCI_SAVED_STATE_VERSION_8PORTS)
5596 {
5597 static SSMFIELD const s_aOhciFields8Ports[] =
5598 {
5599 SSMFIELD_ENTRY( OHCI, SofTime),
5600 SSMFIELD_ENTRY_CUSTOM( dpic+fno, RT_OFFSETOF(OHCI, SofTime) + RT_SIZEOFMEMB(OHCI, SofTime), 4),
5601 SSMFIELD_ENTRY( OHCI, RootHub.status),
5602 SSMFIELD_ENTRY( OHCI, RootHub.desc_a),
5603 SSMFIELD_ENTRY( OHCI, RootHub.desc_b),
5604 SSMFIELD_ENTRY( OHCI, RootHub.aPorts[0].fReg),
5605 SSMFIELD_ENTRY( OHCI, RootHub.aPorts[1].fReg),
5606 SSMFIELD_ENTRY( OHCI, RootHub.aPorts[2].fReg),
5607 SSMFIELD_ENTRY( OHCI, RootHub.aPorts[3].fReg),
5608 SSMFIELD_ENTRY( OHCI, RootHub.aPorts[4].fReg),
5609 SSMFIELD_ENTRY( OHCI, RootHub.aPorts[5].fReg),
5610 SSMFIELD_ENTRY( OHCI, RootHub.aPorts[6].fReg),
5611 SSMFIELD_ENTRY( OHCI, RootHub.aPorts[7].fReg),
5612 SSMFIELD_ENTRY( OHCI, ctl),
5613 SSMFIELD_ENTRY( OHCI, status),
5614 SSMFIELD_ENTRY( OHCI, intr_status),
5615 SSMFIELD_ENTRY( OHCI, intr),
5616 SSMFIELD_ENTRY( OHCI, hcca),
5617 SSMFIELD_ENTRY( OHCI, per_cur),
5618 SSMFIELD_ENTRY( OHCI, ctrl_cur),
5619 SSMFIELD_ENTRY( OHCI, ctrl_head),
5620 SSMFIELD_ENTRY( OHCI, bulk_cur),
5621 SSMFIELD_ENTRY( OHCI, bulk_head),
5622 SSMFIELD_ENTRY( OHCI, done),
5623 SSMFIELD_ENTRY_CUSTOM( fsmps+fit+fi+frt, RT_OFFSETOF(OHCI, done) + RT_SIZEOFMEMB(OHCI, done), 4),
5624 SSMFIELD_ENTRY( OHCI, HcFmNumber),
5625 SSMFIELD_ENTRY( OHCI, pstart),
5626 SSMFIELD_ENTRY_TERM()
5627 };
5628
5629 rc = SSMR3GetStructEx(pSSM, pThis, sizeof(*pThis), 0 /*fFlags*/, &s_aOhciFields8Ports[0], NULL);
5630 if (RT_FAILURE(rc))
5631 return rc;
5632 }
5633 else if (uVersion == OHCI_SAVED_STATE_VERSION_MEM_HELL)
5634 {
5635 static SSMFIELD const s_aOhciFields22[] =
5636 {
5637 SSMFIELD_ENTRY_OLD( PciDev.abConfig, 256), /* DevPCI restores this. */
5638 SSMFIELD_ENTRY_OLD( PciDev.Int, 224),
5639 SSMFIELD_ENTRY_OLD( PciDev.uDevFn, 4),
5640 SSMFIELD_ENTRY_OLD( PciDev.Alignment0, 4),
5641 SSMFIELD_ENTRY_OLD_HCPTR( PciDev.pszNameR3),
5642 SSMFIELD_ENTRY_OLD_HCPTR( PciDev.pvReserved),
5643 SSMFIELD_ENTRY_OLD_HCPTR( pDevInsR3),
5644 SSMFIELD_ENTRY_OLD_HCPTR( pEndOfFrameTimerR3),
5645 SSMFIELD_ENTRY_OLD_HCPTR( pDevInsR0),
5646 SSMFIELD_ENTRY_OLD_HCPTR( pEndOfFrameTimerR0),
5647 SSMFIELD_ENTRY_OLD_RCPTR( pDevInsRC),
5648 SSMFIELD_ENTRY_OLD_RCPTR( pEndOfFrameTimerRC),
5649 SSMFIELD_ENTRY( OHCI, SofTime),
5650 SSMFIELD_ENTRY_CUSTOM( dpic+fno, RT_OFFSETOF(OHCI, SofTime) + RT_SIZEOFMEMB(OHCI, SofTime), 4),
5651 SSMFIELD_ENTRY_OLD( MMIOBase, 4), /* DevPCI implicitly restores this. */
5652 SSMFIELD_ENTRY_OLD_HCPTR( RootHub.pIBase),
5653 SSMFIELD_ENTRY_OLD_HCPTR( RootHub.pIRhConn),
5654 SSMFIELD_ENTRY_OLD_HCPTR( RootHub.pIDev),
5655 SSMFIELD_ENTRY_OLD_HCPTR( RootHub.IBase.pfnQueryInterface),
5656 SSMFIELD_ENTRY_OLD_HCPTR( RootHub.IRhPort.pfnGetAvailablePorts),
5657 SSMFIELD_ENTRY_OLD_HCPTR( RootHub.IRhPort.pfnGetUSBVersions),
5658 SSMFIELD_ENTRY_OLD_HCPTR( RootHub.IRhPort.pfnAttach),
5659 SSMFIELD_ENTRY_OLD_HCPTR( RootHub.IRhPort.pfnDetach),
5660 SSMFIELD_ENTRY_OLD_HCPTR( RootHub.IRhPort.pfnReset),
5661 SSMFIELD_ENTRY_OLD_HCPTR( RootHub.IRhPort.pfnXferCompletion),
5662 SSMFIELD_ENTRY_OLD_HCPTR( RootHub.IRhPort.pfnXferError),
5663 SSMFIELD_ENTRY_OLD_HCPTR( RootHub.IRhPort.Alignment),
5664 SSMFIELD_ENTRY_OLD( RootHub.Led, 16), /* No device restored. */
5665 SSMFIELD_ENTRY_OLD_HCPTR( RootHub.ILeds.pfnQueryStatusLed),
5666 SSMFIELD_ENTRY_OLD_HCPTR( RootHub.pLedsConnector),
5667 SSMFIELD_ENTRY( OHCI, RootHub.status),
5668 SSMFIELD_ENTRY( OHCI, RootHub.desc_a),
5669 SSMFIELD_ENTRY( OHCI, RootHub.desc_b),
5670 SSMFIELD_ENTRY_OLD_PAD_HC64( RootHub.Alignment0, 4),
5671 SSMFIELD_ENTRY( OHCI, RootHub.aPorts[0].fReg),
5672 SSMFIELD_ENTRY_OLD_PAD_HC64( RootHub.aPorts[0].Alignment0, 4),
5673 SSMFIELD_ENTRY_OLD_HCPTR( RootHub.aPorts[0].pDev),
5674 SSMFIELD_ENTRY( OHCI, RootHub.aPorts[1].fReg),
5675 SSMFIELD_ENTRY_OLD_PAD_HC64( RootHub.aPorts[1].Alignment0, 4),
5676 SSMFIELD_ENTRY_OLD_HCPTR( RootHub.aPorts[1].pDev),
5677 SSMFIELD_ENTRY( OHCI, RootHub.aPorts[2].fReg),
5678 SSMFIELD_ENTRY_OLD_PAD_HC64( RootHub.aPorts[2].Alignment0, 4),
5679 SSMFIELD_ENTRY_OLD_HCPTR( RootHub.aPorts[2].pDev),
5680 SSMFIELD_ENTRY( OHCI, RootHub.aPorts[3].fReg),
5681 SSMFIELD_ENTRY_OLD_PAD_HC64( RootHub.aPorts[3].Alignment0, 4),
5682 SSMFIELD_ENTRY_OLD_HCPTR( RootHub.aPorts[3].pDev),
5683 SSMFIELD_ENTRY( OHCI, RootHub.aPorts[4].fReg),
5684 SSMFIELD_ENTRY_OLD_PAD_HC64( RootHub.aPorts[4].Alignment0, 4),
5685 SSMFIELD_ENTRY_OLD_HCPTR( RootHub.aPorts[4].pDev),
5686 SSMFIELD_ENTRY( OHCI, RootHub.aPorts[5].fReg),
5687 SSMFIELD_ENTRY_OLD_PAD_HC64( RootHub.aPorts[5].Alignment0, 4),
5688 SSMFIELD_ENTRY_OLD_HCPTR( RootHub.aPorts[5].pDev),
5689 SSMFIELD_ENTRY( OHCI, RootHub.aPorts[6].fReg),
5690 SSMFIELD_ENTRY_OLD_PAD_HC64( RootHub.aPorts[6].Alignment0, 4),
5691 SSMFIELD_ENTRY_OLD_HCPTR( RootHub.aPorts[6].pDev),
5692 SSMFIELD_ENTRY( OHCI, RootHub.aPorts[7].fReg),
5693 SSMFIELD_ENTRY_OLD_PAD_HC64( RootHub.aPorts[7].Alignment0, 4),
5694 SSMFIELD_ENTRY_OLD_HCPTR( RootHub.aPorts[7].pDev),
5695 SSMFIELD_ENTRY_OLD_HCPTR( RootHub.pThis),
5696 SSMFIELD_ENTRY( OHCI, ctl),
5697 SSMFIELD_ENTRY( OHCI, status),
5698 SSMFIELD_ENTRY( OHCI, intr_status),
5699 SSMFIELD_ENTRY( OHCI, intr),
5700 SSMFIELD_ENTRY( OHCI, hcca),
5701 SSMFIELD_ENTRY( OHCI, per_cur),
5702 SSMFIELD_ENTRY( OHCI, ctrl_cur),
5703 SSMFIELD_ENTRY( OHCI, ctrl_head),
5704 SSMFIELD_ENTRY( OHCI, bulk_cur),
5705 SSMFIELD_ENTRY( OHCI, bulk_head),
5706 SSMFIELD_ENTRY( OHCI, done),
5707 SSMFIELD_ENTRY_CUSTOM( fsmps+fit+fi+frt, RT_OFFSETOF(OHCI, done) + RT_SIZEOFMEMB(OHCI, done), 4),
5708 SSMFIELD_ENTRY( OHCI, HcFmNumber),
5709 SSMFIELD_ENTRY( OHCI, pstart),
5710 SSMFIELD_ENTRY_OLD( cTicksPerFrame, 8), /* done by the constructor */
5711 SSMFIELD_ENTRY_OLD( cTicksPerUsbTick, 8), /* ditto */
5712 SSMFIELD_ENTRY_OLD( cInFlight, 4), /* no in-flight stuff when saving. */
5713 SSMFIELD_ENTRY_OLD( Alignment1, 4),
5714 SSMFIELD_ENTRY_OLD( aInFlight, 257 * 8),
5715 SSMFIELD_ENTRY_OLD_PAD_HC64( aInFlight, 257 * 8),
5716 SSMFIELD_ENTRY_OLD( cInDoneQueue, 4), /* strict builds only, so don't bother. */
5717 SSMFIELD_ENTRY_OLD( aInDoneQueue, 4*64),
5718 SSMFIELD_ENTRY_OLD( u32FmDoneQueueTail, 4), /* logging only */
5719 SSMFIELD_ENTRY_OLD_PAD_HC32( Alignment2, 4),
5720 SSMFIELD_ENTRY_OLD_HCPTR( pLoad),
5721 SSMFIELD_ENTRY_OLD( StatCanceledIsocUrbs, 8),
5722 SSMFIELD_ENTRY_OLD( StatCanceledGenUrbs, 8),
5723 SSMFIELD_ENTRY_OLD( StatDroppedUrbs, 8),
5724 SSMFIELD_ENTRY_OLD( StatTimer, 32),
5725 SSMFIELD_ENTRY_TERM()
5726 };
5727
5728 /* deserialize the struct */
5729 rc = SSMR3GetStructEx(pSSM, pThis, sizeof(*pThis), SSMSTRUCT_FLAGS_NO_MARKERS /*fFlags*/, &s_aOhciFields22[0], NULL);
5730 if (RT_FAILURE(rc))
5731 return rc;
5732
5733 /* check delimiter */
5734 uint32_t u32;
5735 rc = SSMR3GetU32(pSSM, &u32);
5736 if (RT_FAILURE(rc))
5737 return rc;
5738 AssertMsgReturn(u32 == ~0U, ("%#x\n", u32), VERR_SSM_DATA_UNIT_FORMAT_CHANGED);
5739 }
5740 else
5741 AssertMsgFailedReturn(("%d\n", uVersion), VERR_SSM_UNSUPPORTED_DATA_UNIT_VERSION);
5742
5743 /*
5744 * Finally restore the timer.
5745 */
5746 return TMR3TimerLoad(pThis->pEndOfFrameTimerR3, pSSM);
5747}
5748
5749
5750/**
5751 * Done state load operation.
5752 *
5753 * @returns VBox load code.
5754 * @param pDevIns Device instance of the device which registered the data unit.
5755 * @param pSSM SSM operation handle.
5756 */
5757static DECLCALLBACK(int) ohciR3LoadDone(PPDMDEVINS pDevIns, PSSMHANDLE pSSM)
5758{
5759 RT_NOREF(pSSM);
5760 POHCI pThis = PDMINS_2_DATA(pDevIns, POHCI);
5761 LogFlow(("ohciR3LoadDone:\n"));
5762
5763 /*
5764 * Start a timer if we've got devices to reattach
5765 */
5766 if (pThis->pLoad)
5767 {
5768 int rc = PDMDevHlpTMTimerCreate(pDevIns, TMCLOCK_VIRTUAL, ohciR3LoadReattachDevices, pThis,
5769 TMTIMER_FLAGS_NO_CRIT_SECT, "OHCI reattach devices on load",
5770 &pThis->pLoad->pTimer);
5771 if (RT_SUCCESS(rc))
5772 rc = TMTimerSetMillies(pThis->pLoad->pTimer, 250);
5773 return rc;
5774 }
5775
5776 return VINF_SUCCESS;
5777}
5778
5779
5780/**
5781 * Reattaches devices after a saved state load.
5782 */
5783static DECLCALLBACK(void) ohciR3LoadReattachDevices(PPDMDEVINS pDevIns, PTMTIMER pTimer, void *pvUser)
5784{
5785 RT_NOREF(pDevIns);
5786 POHCI pThis = (POHCI)pvUser;
5787 POHCILOAD pLoad = pThis->pLoad;
5788 POHCIROOTHUB pRh = &pThis->RootHub;
5789 LogFlow(("ohciR3LoadReattachDevices:\n"));
5790
5791 /*
5792 * Reattach devices.
5793 */
5794 for (unsigned i = 0; i < pLoad->cDevs; i++)
5795 VUSBIRhAttachDevice(pRh->pIRhConn, pLoad->apDevs[i]);
5796
5797 /*
5798 * Cleanup.
5799 */
5800 TMR3TimerDestroy(pTimer);
5801 MMR3HeapFree(pLoad);
5802 pThis->pLoad = NULL;
5803}
5804
5805
5806/**
5807 * Reset notification.
5808 *
5809 * @returns VBox status code.
5810 * @param pDevIns The device instance data.
5811 */
5812static DECLCALLBACK(void) ohciR3Reset(PPDMDEVINS pDevIns)
5813{
5814 POHCI pThis = PDMINS_2_DATA(pDevIns, POHCI);
5815 LogFlow(("ohciR3Reset:\n"));
5816
5817 /*
5818 * There is no distinction between cold boot, warm reboot and software reboots,
5819 * all of these are treated as cold boots. We are also doing the initialization
5820 * job of a BIOS or SMM driver.
5821 *
5822 * Important: Don't confuse UsbReset with hardware reset. Hardware reset is
5823 * just one way of getting into the UsbReset state.
5824 */
5825 ohciDoReset(pThis, OHCI_USB_RESET, true /* reset devices */);
5826}
5827
5828
5829/**
5830 * Resume notification.
5831 *
5832 * @returns VBox status code.
5833 * @param pDevIns The device instance data.
5834 */
5835static DECLCALLBACK(void) ohciR3Resume(PPDMDEVINS pDevIns)
5836{
5837 POHCI pThis = PDMINS_2_DATA(pDevIns, POHCI);
5838 LogFlowFunc(("\n"));
5839
5840 /* Restart the frame thread if the timer is active. */
5841 if (TMTimerIsActive(pThis->pEndOfFrameTimerR3))
5842 {
5843 int rc = TMTimerStop(pThis->pEndOfFrameTimerR3);
5844 AssertRC(rc);
5845
5846 LogFlowFunc(("Bus was active, enable periodic frame processing\n"));
5847 rc = pThis->RootHub.pIRhConn->pfnSetPeriodicFrameProcessing(pThis->RootHub.pIRhConn, OHCI_DEFAULT_TIMER_FREQ);
5848 AssertRC(rc);
5849 }
5850}
5851
5852
5853/**
5854 * Info handler, device version. Dumps OHCI control registers.
5855 *
5856 * @param pDevIns Device instance which registered the info.
5857 * @param pHlp Callback functions for doing output.
5858 * @param pszArgs Argument string. Optional and specific to the handler.
5859 */
5860static DECLCALLBACK(void) ohciR3InfoRegs(PPDMDEVINS pDevIns, PCDBGFINFOHLP pHlp, const char *pszArgs)
5861{
5862 RT_NOREF(pszArgs);
5863 POHCI pThis = PDMINS_2_DATA(pDevIns, POHCI);
5864 uint32_t val, ctl, status;
5865
5866 /* Control register */
5867 ctl = pThis->ctl;
5868 pHlp->pfnPrintf(pHlp, "HcControl: %08x - CBSR=%d PLE=%d IE=%d CLE=%d BLE=%d HCFS=%#x IR=%d RWC=%d RWE=%d\n",
5869 ctl, ctl & 3, (ctl >> 2) & 1, (ctl >> 3) & 1, (ctl >> 4) & 1, (ctl >> 5) & 1, (ctl >> 6) & 3, (ctl >> 8) & 1,
5870 (ctl >> 9) & 1, (ctl >> 10) & 1);
5871
5872 /* Command status register */
5873 status = pThis->status;
5874 pHlp->pfnPrintf(pHlp, "HcCommandStatus: %08x - HCR=%d CLF=%d BLF=%d OCR=%d SOC=%d\n",
5875 status, status & 1, (status >> 1) & 1, (status >> 2) & 1, (status >> 3) & 1, (status >> 16) & 3);
5876
5877 /* Interrupt status register */
5878 val = pThis->intr_status;
5879 pHlp->pfnPrintf(pHlp, "HcInterruptStatus: %08x - SO=%d WDH=%d SF=%d RD=%d UE=%d FNO=%d RHSC=%d OC=%d\n",
5880 val, val & 1, (val >> 1) & 1, (val >> 2) & 1, (val >> 3) & 1, (val >> 4) & 1, (val >> 5) & 1,
5881 (val >> 6) & 1, (val >> 30) & 1);
5882
5883 /* Interrupt enable register */
5884 val = pThis->intr;
5885 pHlp->pfnPrintf(pHlp, "HcInterruptEnable: %08x - SO=%d WDH=%d SF=%d RD=%d UE=%d FNO=%d RHSC=%d OC=%d MIE=%d\n",
5886 val, val & 1, (val >> 1) & 1, (val >> 2) & 1, (val >> 3) & 1, (val >> 4) & 1, (val >> 5) & 1,
5887 (val >> 6) & 1, (val >> 30) & 1, (val >> 31) & 1);
5888
5889 /* HCCA address register */
5890 pHlp->pfnPrintf(pHlp, "HcHCCA: %08x\n", pThis->hcca);
5891
5892 /* Current periodic ED register */
5893 pHlp->pfnPrintf(pHlp, "HcPeriodCurrentED: %08x\n", pThis->per_cur);
5894
5895 /* Control ED registers */
5896 pHlp->pfnPrintf(pHlp, "HcControlHeadED: %08x\n", pThis->ctrl_head);
5897 pHlp->pfnPrintf(pHlp, "HcControlCurrentED: %08x\n", pThis->ctrl_cur);
5898
5899 /* Bulk ED registers */
5900 pHlp->pfnPrintf(pHlp, "HcBulkHeadED: %08x\n", pThis->bulk_head);
5901 pHlp->pfnPrintf(pHlp, "HcBulkCurrentED: %08x\n", pThis->bulk_cur);
5902
5903 /* Done head register */
5904 pHlp->pfnPrintf(pHlp, "HcDoneHead: %08x\n", pThis->done);
5905
5906 pHlp->pfnPrintf(pHlp, "\n");
5907}
5908
5909
5910/**
5911 * Relocate device instance data.
5912 *
5913 * @returns VBox status code.
5914 * @param pDevIns The device instance data.
5915 * @param offDelta The relocation delta.
5916 */
5917static DECLCALLBACK(void) ohciR3Relocate(PPDMDEVINS pDevIns, RTGCINTPTR offDelta)
5918{
5919 RT_NOREF(offDelta);
5920 POHCI pThis = PDMINS_2_DATA(pDevIns, POHCI);
5921 pThis->pDevInsRC = PDMDEVINS_2_RCPTR(pDevIns);
5922 pThis->pEndOfFrameTimerRC = TMTimerRCPtr(pThis->pEndOfFrameTimerR3);
5923}
5924
5925
5926/**
5927 * Destruct a device instance.
5928 *
5929 * Most VM resources are freed by the VM. This callback is provided so that any non-VM
5930 * resources can be freed correctly.
5931 *
5932 * @returns VBox status code.
5933 * @param pDevIns The device instance data.
5934 */
5935static DECLCALLBACK(int) ohciR3Destruct(PPDMDEVINS pDevIns)
5936{
5937 POHCI pThis = PDMINS_2_DATA(pDevIns, POHCI);
5938 PDMDEV_CHECK_VERSIONS_RETURN_QUIET(pDevIns);
5939
5940#ifdef VBOX_WITH_OHCI_PHYS_READ_CACHE
5941 ohciPhysReadCacheFree(pThis->pCacheED);
5942 pThis->pCacheED = NULL;
5943 ohciPhysReadCacheFree(pThis->pCacheTD);
5944 pThis->pCacheTD = NULL;
5945#endif
5946
5947 if (RTCritSectIsInitialized(&pThis->CritSect))
5948 RTCritSectDelete(&pThis->CritSect);
5949 PDMR3CritSectDelete(&pThis->CsIrq);
5950
5951 /*
5952 * Tear down the per endpoint in-flight tracking...
5953 */
5954
5955 return VINF_SUCCESS;
5956}
5957
5958
5959/**
5960 * @interface_method_impl{PDMDEVREG,pfnConstruct,OHCI constructor}
5961 */
5962static DECLCALLBACK(int) ohciR3Construct(PPDMDEVINS pDevIns, int iInstance, PCFGMNODE pCfg)
5963{
5964 POHCI pThis = PDMINS_2_DATA(pDevIns, POHCI);
5965 uint32_t cPorts;
5966 PDMDEV_CHECK_VERSIONS_RETURN(pDevIns);
5967
5968 /*
5969 * Init instance data.
5970 */
5971 pThis->pDevInsR3 = pDevIns;
5972 pThis->pDevInsR0 = PDMDEVINS_2_R0PTR(pDevIns);
5973 pThis->pDevInsRC = PDMDEVINS_2_RCPTR(pDevIns);
5974
5975 PCIDevSetVendorId (&pThis->PciDev, 0x106b);
5976 PCIDevSetDeviceId (&pThis->PciDev, 0x003f);
5977 PCIDevSetClassProg (&pThis->PciDev, 0x10); /* OHCI */
5978 PCIDevSetClassSub (&pThis->PciDev, 0x03);
5979 PCIDevSetClassBase (&pThis->PciDev, 0x0c);
5980 PCIDevSetInterruptPin (&pThis->PciDev, 0x01);
5981#ifdef VBOX_WITH_MSI_DEVICES
5982 PCIDevSetStatus (&pThis->PciDev, VBOX_PCI_STATUS_CAP_LIST);
5983 PCIDevSetCapabilityList(&pThis->PciDev, 0x80);
5984#endif
5985
5986 pThis->RootHub.pOhci = pThis;
5987 pThis->RootHub.IBase.pfnQueryInterface = ohciRhQueryInterface;
5988 pThis->RootHub.IRhPort.pfnGetAvailablePorts = ohciRhGetAvailablePorts;
5989 pThis->RootHub.IRhPort.pfnGetUSBVersions = ohciRhGetUSBVersions;
5990 pThis->RootHub.IRhPort.pfnAttach = ohciRhAttach;
5991 pThis->RootHub.IRhPort.pfnDetach = ohciRhDetach;
5992 pThis->RootHub.IRhPort.pfnReset = ohciRhReset;
5993 pThis->RootHub.IRhPort.pfnXferCompletion = ohciRhXferCompletion;
5994 pThis->RootHub.IRhPort.pfnXferError = ohciRhXferError;
5995 pThis->RootHub.IRhPort.pfnStartFrame = ohciR3StartFrame;
5996 pThis->RootHub.IRhPort.pfnFrameRateChanged = ohciR3FrameRateChanged;
5997
5998 /* USB LED */
5999 pThis->RootHub.Led.u32Magic = PDMLED_MAGIC;
6000 pThis->RootHub.ILeds.pfnQueryStatusLed = ohciRhQueryStatusLed;
6001
6002
6003 /*
6004 * Read configuration.
6005 */
6006 PDMDEV_VALIDATE_CONFIG_RETURN(pDevIns, "RZEnabled", "");
6007 int rc = CFGMR3QueryBoolDef(pCfg, "RZEnabled", &pThis->fRZEnabled, true);
6008 AssertLogRelRCReturn(rc, rc);
6009
6010 /* Number of ports option. */
6011 rc = CFGMR3QueryU32Def(pCfg, "Ports", &cPorts, OHCI_NDP_DEFAULT);
6012 if (RT_FAILURE(rc))
6013 return PDMDEV_SET_ERROR(pDevIns, rc,
6014 N_("OHCI configuration error: failed to read Ports as integer"));
6015
6016 if (cPorts == 0 || cPorts > OHCI_NDP_MAX)
6017 return PDMDevHlpVMSetError(pDevIns, VERR_INVALID_PARAMETER, RT_SRC_POS,
6018 N_("OHCI configuration error: Ports must be in range [%u,%u]"),
6019 1, OHCI_NDP_MAX);
6020
6021 /* Store the configured NDP; it will be used everywhere else from now on. */
6022 pThis->RootHub.desc_a = cPorts;
6023
6024 /*
6025 * Register PCI device and I/O region.
6026 */
6027 rc = PDMDevHlpPCIRegister(pDevIns, &pThis->PciDev);
6028 if (RT_FAILURE(rc))
6029 return rc;
6030
6031#ifdef VBOX_WITH_MSI_DEVICES
6032 PDMMSIREG MsiReg;
6033 RT_ZERO(MsiReg);
6034 MsiReg.cMsiVectors = 1;
6035 MsiReg.iMsiCapOffset = 0x80;
6036 MsiReg.iMsiNextOffset = 0x00;
6037 rc = PDMDevHlpPCIRegisterMsi(pDevIns, &MsiReg);
6038 if (RT_FAILURE(rc))
6039 {
6040 PCIDevSetCapabilityList(&pThis->PciDev, 0x0);
6041 /* That's OK, we can work without MSI */
6042 }
6043#endif
6044
6045 rc = PDMDevHlpPCIIORegionRegister(pDevIns, 0, 4096, PCI_ADDRESS_SPACE_MEM, ohciR3Map);
6046 if (RT_FAILURE(rc))
6047 return rc;
6048
6049 /*
6050 * Create the end-of-frame timer.
6051 */
6052 rc = PDMDevHlpTMTimerCreate(pDevIns, TMCLOCK_VIRTUAL, ohciFrameBoundaryTimer, pThis,
6053 TMTIMER_FLAGS_DEFAULT_CRIT_SECT, "USB Frame Timer",
6054 &pThis->pEndOfFrameTimerR3);
6055 if (RT_FAILURE(rc))
6056 return rc;
6057 pThis->pEndOfFrameTimerR0 = TMTimerR0Ptr(pThis->pEndOfFrameTimerR3);
6058 pThis->pEndOfFrameTimerRC = TMTimerRCPtr(pThis->pEndOfFrameTimerR3);
6059
6060 /*
6061 * Register the saved state data unit.
6062 */
6063 rc = PDMDevHlpSSMRegisterEx(pDevIns, OHCI_SAVED_STATE_VERSION, sizeof(*pThis), NULL,
6064 NULL, NULL, NULL,
6065 ohciR3SavePrep, ohciR3SaveExec, ohciR3SaveDone,
6066 ohciR3LoadPrep, ohciR3LoadExec, ohciR3LoadDone);
6067 if (RT_FAILURE(rc))
6068 return rc;
6069
6070 /*
6071 * Attach to the VBox USB RootHub Driver on LUN #0.
6072 */
6073 rc = PDMDevHlpDriverAttach(pDevIns, 0, &pThis->RootHub.IBase, &pThis->RootHub.pIBase, "RootHub");
6074 if (RT_FAILURE(rc))
6075 {
6076 AssertMsgFailed(("Configuration error: No roothub driver attached to LUN #0!\n"));
6077 return rc;
6078 }
6079 pThis->RootHub.pIRhConn = PDMIBASE_QUERY_INTERFACE(pThis->RootHub.pIBase, VUSBIROOTHUBCONNECTOR);
6080 AssertMsgReturn(pThis->RootHub.pIRhConn,
6081 ("Configuration error: The driver doesn't provide the VUSBIROOTHUBCONNECTOR interface!\n"),
6082 VERR_PDM_MISSING_INTERFACE);
6083 pThis->RootHub.pIDev = PDMIBASE_QUERY_INTERFACE(pThis->RootHub.pIBase, VUSBIDEVICE);
6084 AssertMsgReturn(pThis->RootHub.pIDev,
6085 ("Configuration error: The driver doesn't provide the VUSBIDEVICE interface!\n"),
6086 VERR_PDM_MISSING_INTERFACE);
6087
6088 /*
6089 * Attach status driver (optional).
6090 */
6091 PPDMIBASE pBase;
6092 rc = PDMDevHlpDriverAttach(pDevIns, PDM_STATUS_LUN, &pThis->RootHub.IBase, &pBase, "Status Port");
6093 if (RT_SUCCESS(rc))
6094 pThis->RootHub.pLedsConnector = PDMIBASE_QUERY_INTERFACE(pBase, PDMILEDCONNECTORS);
6095 else if (rc != VERR_PDM_NO_ATTACHED_DRIVER)
6096 {
6097 AssertMsgFailed(("Failed to attach to status driver. rc=%Rrc\n", rc));
6098 return rc;
6099 }
6100
6101 /* Set URB parameters. */
6102 rc = VUSBIRhSetUrbParams(pThis->RootHub.pIRhConn, sizeof(VUSBURBHCIINT), sizeof(VUSBURBHCITDINT));
6103 if (RT_FAILURE(rc))
6104 return PDMDevHlpVMSetError(pDevIns, rc, RT_SRC_POS,
6105 N_("OHCI: Failed to set URB parameters"));
6106
6107 /*
6108 * Calculate the timer intervals.
6109 * This assumes that the VM timer doesn't change frequency during the run.
6110 */
6111 pThis->u64TimerHz = TMTimerGetFreq(pThis->CTX_SUFF(pEndOfFrameTimer));
6112
6113 rc = PDMDevHlpCritSectInit(pDevIns, &pThis->CsIrq, RT_SRC_POS, "OHCI#%uIrq", iInstance);
6114 if (RT_FAILURE(rc))
6115 return PDMDevHlpVMSetError(pDevIns, rc, RT_SRC_POS,
6116 N_("OHCI: Failed to create critical section"));
6117
6118 rc = RTCritSectInit(&pThis->CritSect);
6119 if (RT_FAILURE(rc))
6120 return PDMDevHlpVMSetError(pDevIns, rc, RT_SRC_POS,
6121 N_("OHCI: Failed to create critical section"));
6122
6123#ifdef VBOX_WITH_OHCI_PHYS_READ_CACHE
6124 pThis->pCacheED = ohciPhysReadCacheAlloc();
6125 pThis->pCacheTD = ohciPhysReadCacheAlloc();
6126 if (pThis->pCacheED == NULL || pThis->pCacheTD == NULL)
6127 return PDMDevHlpVMSetError(pDevIns, VERR_NO_MEMORY, RT_SRC_POS,
6128 N_("OHCI: Failed to allocate PhysRead cache"));
6129#endif
6130
6131 /*
6132 * Do a hardware reset.
6133 */
6134 ohciDoReset(pThis, OHCI_USB_RESET, false /* don't reset devices */);
6135
6136#ifdef VBOX_WITH_STATISTICS
6137 /*
6138 * Register statistics.
6139 */
6140 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatCanceledIsocUrbs, STAMTYPE_COUNTER, "/Devices/OHCI/CanceledIsocUrbs", STAMUNIT_OCCURENCES, "Detected canceled isochronous URBs.");
6141 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatCanceledGenUrbs, STAMTYPE_COUNTER, "/Devices/OHCI/CanceledGenUrbs", STAMUNIT_OCCURENCES, "Detected canceled general URBs.");
6142 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatDroppedUrbs, STAMTYPE_COUNTER, "/Devices/OHCI/DroppedUrbs", STAMUNIT_OCCURENCES, "Dropped URBs (endpoint halted, or URB canceled).");
6143#endif
6144
6145 /*
6146 * Register debugger info callbacks.
6147 */
6148 PDMDevHlpDBGFInfoRegister(pDevIns, "ohci", "OHCI control registers.", ohciR3InfoRegs);
6149
6150#if 0/*def DEBUG_bird*/
6151// g_fLogInterruptEPs = true;
6152 g_fLogControlEPs = true;
6153 g_fLogBulkEPs = true;
6154#endif
6155
6156 return VINF_SUCCESS;
6157}
6158
6159
6160const PDMDEVREG g_DeviceOHCI =
6161{
6162 /* u32version */
6163 PDM_DEVREG_VERSION,
6164 /* szName */
6165 "usb-ohci",
6166 /* szRCMod */
6167 "VBoxDDRC.rc",
6168 /* szR0Mod */
6169 "VBoxDDR0.r0",
6170 /* pszDescription */
6171 "OHCI USB controller.\n",
6172 /* fFlags */
6173 PDM_DEVREG_FLAGS_DEFAULT_BITS | PDM_DEVREG_FLAGS_RC | PDM_DEVREG_FLAGS_R0,
6174 /* fClass */
6175 PDM_DEVREG_CLASS_BUS_USB,
6176 /* cMaxInstances */
6177 ~0U,
6178 /* cbInstance */
6179 sizeof(OHCI),
6180 /* pfnConstruct */
6181 ohciR3Construct,
6182 /* pfnDestruct */
6183 ohciR3Destruct,
6184 /* pfnRelocate */
6185 ohciR3Relocate,
6186 /* pfnMemSetup */
6187 NULL,
6188 /* pfnPowerOn */
6189 NULL,
6190 /* pfnReset */
6191 ohciR3Reset,
6192 /* pfnSuspend */
6193 NULL,
6194 /* pfnResume */
6195 ohciR3Resume,
6196 /* pfnAttach */
6197 NULL,
6198 /* pfnDetach */
6199 NULL,
6200 /* pfnQueryInterface */
6201 NULL,
6202 /* pfnInitComplete */
6203 NULL,
6204 /* pfnPowerOff */
6205 NULL,
6206 /* pfnSoftReset */
6207 NULL,
6208 /* u32VersionEnd */
6209 PDM_DEVREG_VERSION
6210};
6211
6212#endif /* IN_RING3 */
6213#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