xref: /haiku/src/add-ons/kernel/busses/usb/xhci.cpp (revision 05fc1277c47440dc36134816d70e5723c99cfcd2)
1 /*
2  * Copyright 2006-2014, Haiku Inc. All rights reserved.
3  * Distributed under the terms of the MIT License.
4  *
5  * Some code borrowed from the Haiku EHCI driver
6  *
7  * Authors:
8  *		Michael Lotz <mmlr@mlotz.ch>
9  * 		Jian Chiang <j.jian.chiang@gmail.com>
10  *		Jérôme Duval <jerome.duval@gmail.com>
11  *		Akshay Jaggi <akshay1994.leo@gmail.com>
12  */
13 
14 
15 #include <module.h>
16 #include <PCI.h>
17 #include <PCI_x86.h>
18 #include <USB3.h>
19 #include <KernelExport.h>
20 
21 #include <util/AutoLock.h>
22 
23 #include "xhci.h"
24 
25 #define USB_MODULE_NAME	"xhci"
26 
27 pci_module_info *XHCI::sPCIModule = NULL;
28 pci_x86_module_info *XHCI::sPCIx86Module = NULL;
29 
30 
31 static int32
32 xhci_std_ops(int32 op, ...)
33 {
34 	switch (op) {
35 		case B_MODULE_INIT:
36 			TRACE_MODULE("xhci init module\n");
37 			return B_OK;
38 		case B_MODULE_UNINIT:
39 			TRACE_MODULE("xhci uninit module\n");
40 			return B_OK;
41 	}
42 
43 	return EINVAL;
44 }
45 
46 
47 static const char*
48 xhci_error_string(uint32 error)
49 {
50 	switch (error) {
51 		case COMP_INVALID: return "Invalid";
52 		case COMP_SUCCESS: return "Success";
53 		case COMP_DATA_BUFFER: return "Data buffer";
54 		case COMP_BABBLE: return "Babble detected";
55 		case COMP_USB_TRANSACTION: return "USB transaction";
56 		case COMP_TRB: return "TRB";
57 		case COMP_STALL: return "Stall";
58 		case COMP_RESOURCE: return "Resource";
59 		case COMP_BANDWIDTH: return "Bandwidth";
60 		case COMP_NO_SLOTS: return "No slots";
61 		case COMP_INVALID_STREAM: return "Invalid stream";
62 		case COMP_SLOT_NOT_ENABLED: return "Slot not enabled";
63 		case COMP_ENDPOINT_NOT_ENABLED: return "Endpoint not enabled";
64 		case COMP_SHORT_PACKET: return "Short packet";
65 		case COMP_RING_UNDERRUN: return "Ring underrun";
66 		case COMP_RING_OVERRUN: return "Ring overrun";
67 		case COMP_VF_RING_FULL: return "VF Event Ring Full";
68 		case COMP_PARAMETER: return "Parameter";
69 		case COMP_BANDWIDTH_OVERRUN: return "Bandwidth overrun";
70 		case COMP_CONTEXT_STATE: return "Context state";
71 		case COMP_NO_PING_RESPONSE: return "No ping response";
72 		case COMP_EVENT_RING_FULL: return "Event ring full";
73 		case COMP_INCOMPATIBLE_DEVICE: return "Incompatible device";
74 		case COMP_MISSED_SERVICE: return "Missed service";
75 		case COMP_COMMAND_RING_STOPPED: return "Command ring stopped";
76 		case COMP_COMMAND_ABORTED: return "Command aborted";
77 		case COMP_STOPPED: return "Stopped";
78 		case COMP_LENGTH_INVALID: return "Length invalid";
79 		case COMP_MAX_EXIT_LATENCY: return "Max exit latency too large";
80 		case COMP_ISOC_OVERRUN: return "Isoch buffer overrun";
81 		case COMP_EVENT_LOST: return "Event lost";
82 		case COMP_UNDEFINED: return "Undefined";
83 		case COMP_INVALID_STREAM_ID: return "Invalid stream ID";
84 		case COMP_SECONDARY_BANDWIDTH: return "Secondary bandwidth";
85 		case COMP_SPLIT_TRANSACTION: return "Split transaction";
86 
87 		default: return "Undefined";
88 	}
89 }
90 
91 
92 usb_host_controller_info xhci_module = {
93 	{
94 		"busses/usb/xhci",
95 		0,
96 		xhci_std_ops
97 	},
98 	NULL,
99 	XHCI::AddTo
100 };
101 
102 
103 module_info *modules[] = {
104 	(module_info *)&xhci_module,
105 	NULL
106 };
107 
108 
109 XHCI::XHCI(pci_info *info, Stack *stack)
110 	:	BusManager(stack),
111 		fCapabilityRegisters(NULL),
112 		fOperationalRegisters(NULL),
113 		fRegisterArea(-1),
114 		fPCIInfo(info),
115 		fStack(stack),
116 		fIRQ(0),
117 		fUseMSI(false),
118 		fErstArea(-1),
119 		fDcbaArea(-1),
120 		fCmdCompSem(-1),
121 		fFinishTransfersSem(-1),
122 		fFinishThread(-1),
123 		fStopThreads(false),
124 		fFinishedHead(NULL),
125 		fRootHub(NULL),
126 		fRootHubAddress(0),
127 		fPortCount(0),
128 		fSlotCount(0),
129 		fScratchpadCount(0),
130 		fEventSem(-1),
131 		fEventThread(-1),
132 		fEventIdx(0),
133 		fCmdIdx(0),
134 		fEventCcs(1),
135 		fCmdCcs(1)
136 {
137 	B_INITIALIZE_SPINLOCK(&fSpinlock);
138 
139 	if (BusManager::InitCheck() < B_OK) {
140 		TRACE_ERROR("bus manager failed to init\n");
141 		return;
142 	}
143 
144 	TRACE("constructing new XHCI host controller driver\n");
145 	fInitOK = false;
146 
147 	// enable busmaster and memory mapped access
148 	uint16 command = sPCIModule->read_pci_config(fPCIInfo->bus,
149 		fPCIInfo->device, fPCIInfo->function, PCI_command, 2);
150 	command &= ~(PCI_command_io | PCI_command_int_disable);
151 	command |= PCI_command_master | PCI_command_memory;
152 
153 	sPCIModule->write_pci_config(fPCIInfo->bus, fPCIInfo->device,
154 		fPCIInfo->function, PCI_command, 2, command);
155 
156 	// map the registers
157 	uint32 offset = fPCIInfo->u.h0.base_registers[0] & (B_PAGE_SIZE - 1);
158 	phys_addr_t physicalAddress = fPCIInfo->u.h0.base_registers[0] - offset;
159 	size_t mapSize = (fPCIInfo->u.h0.base_register_sizes[0] + offset
160 		+ B_PAGE_SIZE - 1) & ~(B_PAGE_SIZE - 1);
161 
162 	TRACE("map physical memory 0x%08" B_PRIx32 " (base: 0x%08" B_PRIxPHYSADDR
163 		"; offset: %" B_PRIx32 "); size: %" B_PRId32 "\n",
164 		fPCIInfo->u.h0.base_registers[0], physicalAddress, offset,
165 		fPCIInfo->u.h0.base_register_sizes[0]);
166 
167 	fRegisterArea = map_physical_memory("XHCI memory mapped registers",
168 		physicalAddress, mapSize, B_ANY_KERNEL_BLOCK_ADDRESS,
169 		B_KERNEL_READ_AREA | B_KERNEL_WRITE_AREA | B_READ_AREA | B_WRITE_AREA,
170 		(void **)&fCapabilityRegisters);
171 	if (fRegisterArea < B_OK) {
172 		TRACE("failed to map register memory\n");
173 		return;
174 	}
175 
176 	uint32 hciCapLength = ReadCapReg32(XHCI_HCI_CAPLENGTH);
177 	fCapabilityRegisters += offset;
178 	fCapabilityLength = HCI_CAPLENGTH(hciCapLength);
179 	TRACE("mapped capability length: 0x%" B_PRIx32 "\n", fCapabilityLength);
180 	fOperationalRegisters = fCapabilityRegisters + fCapabilityLength;
181 	fRuntimeRegisters = fCapabilityRegisters + ReadCapReg32(XHCI_RTSOFF);
182 	fDoorbellRegisters = fCapabilityRegisters + ReadCapReg32(XHCI_DBOFF);
183 	TRACE("mapped capability registers: 0x%p\n", fCapabilityRegisters);
184 	TRACE("mapped operational registers: 0x%p\n", fOperationalRegisters);
185 	TRACE("mapped runtime registers: 0x%p\n", fRuntimeRegisters);
186 	TRACE("mapped doorbell registers: 0x%p\n", fDoorbellRegisters);
187 
188 	TRACE("structural parameters1: 0x%08" B_PRIx32 "\n",
189 		ReadCapReg32(XHCI_HCSPARAMS1));
190 	TRACE("structural parameters2: 0x%08" B_PRIx32 "\n",
191 		ReadCapReg32(XHCI_HCSPARAMS2));
192 	TRACE("structural parameters3: 0x%08" B_PRIx32 "\n",
193 		ReadCapReg32(XHCI_HCSPARAMS3));
194 	TRACE("capability parameters: 0x%08" B_PRIx32 "\n",
195 		ReadCapReg32(XHCI_HCCPARAMS));
196 
197 	uint32 cparams = ReadCapReg32(XHCI_HCCPARAMS);
198 	uint32 eec = 0xffffffff;
199 	uint32 eecp = HCS0_XECP(cparams) << 2;
200 	for (; eecp != 0 && XECP_NEXT(eec); eecp += XECP_NEXT(eec) << 2) {
201 		eec = ReadCapReg32(eecp);
202 		if (XECP_ID(eec) != XHCI_LEGSUP_CAPID)
203 			continue;
204 
205 		TRACE("eecp register: 0x%08" B_PRIx32 "\n", eecp);
206 		if (eec & XHCI_LEGSUP_BIOSOWNED) {
207 			TRACE_ALWAYS("the host controller is bios owned, claiming"
208 				" ownership\n");
209 			WriteCapReg32(eecp, eec | XHCI_LEGSUP_OSOWNED);
210 
211 			for (int32 i = 0; i < 20; i++) {
212 				eec = ReadCapReg32(eecp);
213 
214 				if ((eec & XHCI_LEGSUP_BIOSOWNED) == 0)
215 					break;
216 
217 				TRACE_ALWAYS("controller is still bios owned, waiting\n");
218 				snooze(50000);
219 			}
220 
221 			if (eec & XHCI_LEGSUP_BIOSOWNED) {
222 				TRACE_ERROR("bios won't give up control over the host "
223 					"controller (ignoring)\n");
224 			} else if (eec & XHCI_LEGSUP_OSOWNED) {
225 				TRACE_ALWAYS("successfully took ownership of the host "
226 					"controller\n");
227 			}
228 
229 			// Force off the BIOS owned flag, and clear all SMIs. Some BIOSes
230 			// do indicate a successful handover but do not remove their SMIs
231 			// and then freeze the system when interrupts are generated.
232 			WriteCapReg32(eecp, eec & ~XHCI_LEGSUP_BIOSOWNED);
233 		}
234 		break;
235 	}
236 	uint32 legctlsts = ReadCapReg32(eecp + XHCI_LEGCTLSTS);
237 	legctlsts &= XHCI_LEGCTLSTS_DISABLE_SMI;
238 	legctlsts |= XHCI_LEGCTLSTS_EVENTS_SMI;
239 	WriteCapReg32(eecp + XHCI_LEGCTLSTS, legctlsts);
240 
241 	// On Intel's Panther Point and Lynx Point Chipset taking ownership
242 	// of EHCI owned ports, is what we do here.
243 	if (fPCIInfo->vendor_id == PCI_VENDOR_INTEL) {
244 		switch (fPCIInfo->device_id) {
245 			case PCI_DEVICE_INTEL_PANTHER_POINT_XHCI:
246 			case PCI_DEVICE_INTEL_LYNX_POINT_XHCI:
247 			case PCI_DEVICE_INTEL_LYNX_POINT_LP_XHCI:
248 			case PCI_DEVICE_INTEL_BAYTRAIL_XHCI:
249 			case PCI_DEVICE_INTEL_WILDCAT_POINT_XHCI:
250 			case PCI_DEVICE_INTEL_WILDCAT_POINT_LP_XHCI:
251 				_SwitchIntelPorts();
252 				break;
253 		}
254 	}
255 
256 	// halt the host controller
257 	if (ControllerHalt() < B_OK) {
258 		return;
259 	}
260 
261 	// reset the host controller
262 	if (ControllerReset() < B_OK) {
263 		TRACE_ERROR("host controller failed to reset\n");
264 		return;
265 	}
266 
267 	fCmdCompSem = create_sem(0, "XHCI Command Complete");
268 	fFinishTransfersSem = create_sem(0, "XHCI Finish Transfers");
269 	fEventSem = create_sem(0, "XHCI Event");
270 	if (fFinishTransfersSem < B_OK || fCmdCompSem < B_OK || fEventSem < B_OK) {
271 		TRACE_ERROR("failed to create semaphores\n");
272 		return;
273 	}
274 
275 	// create finisher service thread
276 	fFinishThread = spawn_kernel_thread(FinishThread, "xhci finish thread",
277 		B_NORMAL_PRIORITY, (void *)this);
278 	resume_thread(fFinishThread);
279 
280 	// create finisher service thread
281 	fEventThread = spawn_kernel_thread(EventThread, "xhci event thread",
282 		B_NORMAL_PRIORITY, (void *)this);
283 	resume_thread(fEventThread);
284 
285 	// Find the right interrupt vector, using MSIs if available.
286 	fIRQ = fPCIInfo->u.h0.interrupt_line;
287 	if (sPCIx86Module != NULL && sPCIx86Module->get_msi_count(fPCIInfo->bus,
288 			fPCIInfo->device, fPCIInfo->function) >= 1) {
289 		uint8 msiVector = 0;
290 		if (sPCIx86Module->configure_msi(fPCIInfo->bus, fPCIInfo->device,
291 				fPCIInfo->function, 1, &msiVector) == B_OK
292 			&& sPCIx86Module->enable_msi(fPCIInfo->bus, fPCIInfo->device,
293 				fPCIInfo->function) == B_OK) {
294 			TRACE_ALWAYS("using message signaled interrupts\n");
295 			fIRQ = msiVector;
296 			fUseMSI = true;
297 		}
298 	}
299 
300 	// Install the interrupt handler
301 	TRACE("installing interrupt handler\n");
302 	install_io_interrupt_handler(fIRQ, InterruptHandler, (void *)this, 0);
303 
304 	memset(fPortSpeeds, 0, sizeof(fPortSpeeds));
305 	memset(fPortSlots, 0, sizeof(fPortSlots));
306 	memset(fDevices, 0, sizeof(fDevices));
307 
308 	fInitOK = true;
309 	TRACE("XHCI host controller driver constructed\n");
310 }
311 
312 
313 XHCI::~XHCI()
314 {
315 	TRACE("tear down XHCI host controller driver\n");
316 
317 	WriteOpReg(XHCI_CMD, 0);
318 
319 	int32 result = 0;
320 	fStopThreads = true;
321 	delete_sem(fCmdCompSem);
322 	delete_sem(fFinishTransfersSem);
323 	delete_sem(fEventSem);
324 	wait_for_thread(fFinishThread, &result);
325 	wait_for_thread(fEventThread, &result);
326 
327 	remove_io_interrupt_handler(fIRQ, InterruptHandler, (void *)this);
328 
329 	delete_area(fRegisterArea);
330 	delete_area(fErstArea);
331 	for (uint32 i = 0; i < fScratchpadCount; i++)
332 		delete_area(fScratchpadArea[i]);
333 	delete_area(fDcbaArea);
334 
335 	if (fUseMSI && sPCIx86Module != NULL) {
336 		sPCIx86Module->disable_msi(fPCIInfo->bus,
337 			fPCIInfo->device, fPCIInfo->function);
338 		sPCIx86Module->unconfigure_msi(fPCIInfo->bus,
339 			fPCIInfo->device, fPCIInfo->function);
340 	}
341 	put_module(B_PCI_MODULE_NAME);
342 	if (sPCIx86Module != NULL) {
343 		sPCIx86Module = NULL;
344 		put_module(B_PCI_X86_MODULE_NAME);
345 	}
346 }
347 
348 
349 void
350 XHCI::_SwitchIntelPorts()
351 {
352 	TRACE("Intel xHC Controller\n");
353 	TRACE("Looking for EHCI owned ports\n");
354 	uint32 ports = sPCIModule->read_pci_config(fPCIInfo->bus,
355 		fPCIInfo->device, fPCIInfo->function, XHCI_INTEL_USB3PRM, 4);
356 	TRACE("Superspeed Ports: 0x%" B_PRIx32 "\n", ports);
357 	sPCIModule->write_pci_config(fPCIInfo->bus, fPCIInfo->device,
358 		fPCIInfo->function, XHCI_INTEL_USB3_PSSEN, 4, ports);
359 	ports = sPCIModule->read_pci_config(fPCIInfo->bus,
360 		fPCIInfo->device, fPCIInfo->function, XHCI_INTEL_USB3_PSSEN, 4);
361 	TRACE("Superspeed ports now under XHCI : 0x%" B_PRIx32 "\n", ports);
362 	ports = sPCIModule->read_pci_config(fPCIInfo->bus,
363 		fPCIInfo->device, fPCIInfo->function, XHCI_INTEL_USB2PRM, 4);
364 	TRACE("USB 2.0 Ports : 0x%" B_PRIx32 "\n", ports);
365 	sPCIModule->write_pci_config(fPCIInfo->bus, fPCIInfo->device,
366 		fPCIInfo->function, XHCI_INTEL_XUSB2PR, 4, ports);
367 	ports = sPCIModule->read_pci_config(fPCIInfo->bus,
368 		fPCIInfo->device, fPCIInfo->function, XHCI_INTEL_XUSB2PR, 4);
369 	TRACE("USB 2.0 ports now under XHCI: 0x%" B_PRIx32 "\n", ports);
370 }
371 
372 
373 status_t
374 XHCI::Start()
375 {
376 	TRACE_ALWAYS("starting XHCI host controller\n");
377 	TRACE("usbcmd: 0x%08" B_PRIx32 "; usbsts: 0x%08" B_PRIx32 "\n",
378 		ReadOpReg(XHCI_CMD), ReadOpReg(XHCI_STS));
379 
380 	if ((ReadOpReg(XHCI_PAGESIZE) & (1 << 0)) == 0) {
381 		TRACE_ERROR("Controller does not support 4K page size.\n");
382 		return B_ERROR;
383 	}
384 
385 	// read port count from capability register
386 	uint32 capabilities = ReadCapReg32(XHCI_HCSPARAMS1);
387 	fPortCount = HCS_MAX_PORTS(capabilities);
388 	if (fPortCount == 0) {
389 		TRACE_ERROR("Invalid number of ports: %u\n", fPortCount);
390 		fPortCount = 0;
391 		return B_ERROR;
392 	}
393 	fSlotCount = HCS_MAX_SLOTS(capabilities);
394 	WriteOpReg(XHCI_CONFIG, fSlotCount);
395 
396 	// find out which protocol is used for each port
397 	uint8 portFound = 0;
398 	uint32 cparams = ReadCapReg32(XHCI_HCCPARAMS);
399 	uint32 eec = 0xffffffff;
400 	uint32 eecp = HCS0_XECP(cparams) << 2;
401 	for (; eecp != 0 && XECP_NEXT(eec) && portFound < fPortCount;
402 		eecp += XECP_NEXT(eec) << 2) {
403 		eec = ReadCapReg32(eecp);
404 		if (XECP_ID(eec) != XHCI_SUPPORTED_PROTOCOLS_CAPID)
405 			continue;
406 		if (XHCI_SUPPORTED_PROTOCOLS_0_MAJOR(eec) > 3)
407 			continue;
408 		uint32 temp = ReadCapReg32(eecp + 8);
409 		uint32 offset = XHCI_SUPPORTED_PROTOCOLS_1_OFFSET(temp);
410 		uint32 count = XHCI_SUPPORTED_PROTOCOLS_1_COUNT(temp);
411 		if (offset == 0 || count == 0)
412 			continue;
413 		offset--;
414 		for (uint32 i = offset; i < offset + count; i++) {
415 			if (XHCI_SUPPORTED_PROTOCOLS_0_MAJOR(eec) == 0x3)
416 				fPortSpeeds[i] = USB_SPEED_SUPER;
417 			else
418 				fPortSpeeds[i] = USB_SPEED_HIGHSPEED;
419 			TRACE("speed for port %" B_PRId32 " is %s\n", i,
420 				fPortSpeeds[i] == USB_SPEED_SUPER ? "super" : "high");
421 		}
422 		portFound += count;
423 	}
424 
425 	uint32 params2 = ReadCapReg32(XHCI_HCSPARAMS2);
426 	fScratchpadCount = HCS_MAX_SC_BUFFERS(params2);
427 	if (fScratchpadCount > XHCI_MAX_SCRATCHPADS) {
428 		TRACE_ERROR("Invalid number of scratchpads: %" B_PRIu32 "\n",
429 			fScratchpadCount);
430 		return B_ERROR;
431 	}
432 
433 	uint32 params3 = ReadCapReg32(XHCI_HCSPARAMS3);
434 	fExitLatMax = HCS_U1_DEVICE_LATENCY(params3)
435 		+ HCS_U2_DEVICE_LATENCY(params3);
436 
437 	WriteOpReg(XHCI_DNCTRL, 0);
438 
439 	// allocate Device Context Base Address array
440 	phys_addr_t dmaAddress;
441 	fDcbaArea = fStack->AllocateArea((void **)&fDcba, &dmaAddress,
442 		sizeof(*fDcba), "DCBA Area");
443 	if (fDcbaArea < B_OK) {
444 		TRACE_ERROR("unable to create the DCBA area\n");
445 		return B_ERROR;
446 	}
447 	memset(fDcba, 0, sizeof(*fDcba));
448 	memset(fScratchpadArea, 0, sizeof(fScratchpadArea));
449 	memset(fScratchpad, 0, sizeof(fScratchpad));
450 
451 	// setting the first address to the scratchpad array address
452 	fDcba->baseAddress[0] = dmaAddress
453 		+ offsetof(struct xhci_device_context_array, scratchpad);
454 
455 	// fill up the scratchpad array with scratchpad pages
456 	for (uint32 i = 0; i < fScratchpadCount; i++) {
457 		phys_addr_t scratchDmaAddress;
458 		fScratchpadArea[i] = fStack->AllocateArea((void **)&fScratchpad[i],
459 		&scratchDmaAddress, B_PAGE_SIZE, "Scratchpad Area");
460 		if (fScratchpadArea[i] < B_OK) {
461 			TRACE_ERROR("unable to create the scratchpad area\n");
462 			return B_ERROR;
463 		}
464 		fDcba->scratchpad[i] = scratchDmaAddress;
465 	}
466 
467 	TRACE("setting DCBAAP %" B_PRIxPHYSADDR "\n", dmaAddress);
468 	WriteOpReg(XHCI_DCBAAP_LO, (uint32)dmaAddress);
469 	WriteOpReg(XHCI_DCBAAP_HI, /*(uint32)(dmaAddress >> 32)*/0);
470 
471 	// allocate Event Ring Segment Table
472 	uint8 *addr;
473 	fErstArea = fStack->AllocateArea((void **)&addr, &dmaAddress,
474 		(XHCI_MAX_COMMANDS + XHCI_MAX_EVENTS) * sizeof(xhci_trb)
475 		+ sizeof(xhci_erst_element),
476 		"USB XHCI ERST CMD_RING and EVENT_RING Area");
477 
478 	if (fErstArea < B_OK) {
479 		TRACE_ERROR("unable to create the ERST AND RING area\n");
480 		delete_area(fDcbaArea);
481 		return B_ERROR;
482 	}
483 	fErst = (xhci_erst_element *)addr;
484 	memset(fErst, 0, (XHCI_MAX_COMMANDS + XHCI_MAX_EVENTS) * sizeof(xhci_trb)
485 		+ sizeof(xhci_erst_element));
486 
487 	// fill with Event Ring Segment Base Address and Event Ring Segment Size
488 	fErst->rs_addr = dmaAddress + sizeof(xhci_erst_element);
489 	fErst->rs_size = XHCI_MAX_EVENTS;
490 	fErst->rsvdz = 0;
491 
492 	addr += sizeof(xhci_erst_element);
493 	fEventRing = (xhci_trb *)addr;
494 	addr += XHCI_MAX_EVENTS * sizeof(xhci_trb);
495 	fCmdRing = (xhci_trb *)addr;
496 
497 	TRACE("setting ERST size\n");
498 	WriteRunReg32(XHCI_ERSTSZ(0), XHCI_ERSTS_SET(1));
499 
500 	TRACE("setting ERDP addr = 0x%" B_PRIx64 "\n", fErst->rs_addr);
501 	WriteRunReg32(XHCI_ERDP_LO(0), (uint32)fErst->rs_addr);
502 	WriteRunReg32(XHCI_ERDP_HI(0), /*(uint32)(fErst->rs_addr >> 32)*/0);
503 
504 	TRACE("setting ERST base addr = 0x%" B_PRIxPHYSADDR "\n", dmaAddress);
505 	WriteRunReg32(XHCI_ERSTBA_LO(0), (uint32)dmaAddress);
506 	WriteRunReg32(XHCI_ERSTBA_HI(0), /*(uint32)(dmaAddress >> 32)*/0);
507 
508 	dmaAddress += sizeof(xhci_erst_element) + XHCI_MAX_EVENTS
509 		* sizeof(xhci_trb);
510 	TRACE("setting CRCR addr = 0x%" B_PRIxPHYSADDR "\n", dmaAddress);
511 	WriteOpReg(XHCI_CRCR_LO, (uint32)dmaAddress | CRCR_RCS);
512 	WriteOpReg(XHCI_CRCR_HI, /*(uint32)(dmaAddress >> 32)*/0);
513 	// link trb
514 	fCmdRing[XHCI_MAX_COMMANDS - 1].qwtrb0 = dmaAddress;
515 
516 	TRACE("setting interrupt rate\n");
517 
518 	// Setting IMOD below 0x3F8 on Intel Lynx Point can cause IRQ lockups
519 	if (fPCIInfo->vendor_id == PCI_VENDOR_INTEL
520 		&& (fPCIInfo->device_id == PCI_DEVICE_INTEL_PANTHER_POINT_XHCI
521 			|| fPCIInfo->device_id == PCI_DEVICE_INTEL_LYNX_POINT_XHCI
522 			|| fPCIInfo->device_id == PCI_DEVICE_INTEL_LYNX_POINT_LP_XHCI
523 			|| fPCIInfo->device_id == PCI_DEVICE_INTEL_BAYTRAIL_XHCI
524 			|| fPCIInfo->device_id == PCI_DEVICE_INTEL_WILDCAT_POINT_XHCI)) {
525 		WriteRunReg32(XHCI_IMOD(0), 0x000003f8); // 4000 irq/s
526 	} else {
527 		WriteRunReg32(XHCI_IMOD(0), 0x000001f4); // 8000 irq/s
528 	}
529 
530 	TRACE("enabling interrupt\n");
531 	WriteRunReg32(XHCI_IMAN(0), ReadRunReg32(XHCI_IMAN(0)) | IMAN_INTR_ENA);
532 
533 	WriteOpReg(XHCI_CMD, CMD_RUN | CMD_EIE | CMD_HSEIE);
534 
535 	// wait for start up state
536 	int32 tries = 100;
537 	while ((ReadOpReg(XHCI_STS) & STS_HCH) != 0) {
538 		snooze(1000);
539 		if (tries-- < 0) {
540 			TRACE_ERROR("start up timeout\n");
541 			break;
542 		}
543 	}
544 
545 	fRootHubAddress = AllocateAddress();
546 	fRootHub = new(std::nothrow) XHCIRootHub(RootObject(), fRootHubAddress);
547 	if (!fRootHub) {
548 		TRACE_ERROR("no memory to allocate root hub\n");
549 		return B_NO_MEMORY;
550 	}
551 
552 	if (fRootHub->InitCheck() < B_OK) {
553 		TRACE_ERROR("root hub failed init check\n");
554 		return fRootHub->InitCheck();
555 	}
556 
557 	SetRootHub(fRootHub);
558 
559 	TRACE_ALWAYS("successfully started the controller\n");
560 #ifdef TRACE_USB
561 	TRACE("No-Op test\n");
562 	Noop();
563 #endif
564 	return BusManager::Start();
565 }
566 
567 
568 status_t
569 XHCI::SubmitTransfer(Transfer *transfer)
570 {
571 	// short circuit the root hub
572 	if (transfer->TransferPipe()->DeviceAddress() == fRootHubAddress)
573 		return fRootHub->ProcessTransfer(this, transfer);
574 
575 	TRACE("SubmitTransfer()\n");
576 	Pipe *pipe = transfer->TransferPipe();
577 	if ((pipe->Type() & USB_OBJECT_ISO_PIPE) != 0)
578 		return B_UNSUPPORTED;
579 	if ((pipe->Type() & USB_OBJECT_CONTROL_PIPE) != 0)
580 		return SubmitControlRequest(transfer);
581 	return SubmitNormalRequest(transfer);
582 }
583 
584 
585 status_t
586 XHCI::SubmitControlRequest(Transfer *transfer)
587 {
588 	Pipe *pipe = transfer->TransferPipe();
589 	usb_request_data *requestData = transfer->RequestData();
590 	bool directionIn = (requestData->RequestType & USB_REQTYPE_DEVICE_IN) != 0;
591 
592 	TRACE("SubmitControlRequest() length %d\n", requestData->Length);
593 
594 	xhci_td *setupDescriptor = CreateDescriptor(requestData->Length);
595 
596 	// set SetupStage
597 	uint8 index = 0;
598 	setupDescriptor->trbs[index].dwtrb2 = TRB_2_IRQ(0) | TRB_2_BYTES(8);
599 	setupDescriptor->trbs[index].dwtrb3 = TRB_3_TYPE(TRB_TYPE_SETUP_STAGE)
600 		| TRB_3_IDT_BIT | TRB_3_CYCLE_BIT;
601 	if (requestData->Length > 0) {
602 		setupDescriptor->trbs[index].dwtrb3 |= directionIn ? TRB_3_TRT_IN
603 			: TRB_3_TRT_OUT;
604 	}
605 	memcpy(&setupDescriptor->trbs[index].qwtrb0, requestData,
606 		sizeof(usb_request_data));
607 
608 	index++;
609 
610 	if (requestData->Length > 0) {
611 		// set DataStage if any
612 		setupDescriptor->trbs[index].qwtrb0 = setupDescriptor->buffer_phy[0];
613 		setupDescriptor->trbs[index].dwtrb2 = TRB_2_IRQ(0)
614 			| TRB_2_BYTES(requestData->Length)
615 			| TRB_2_TD_SIZE(transfer->VectorCount());
616 		setupDescriptor->trbs[index].dwtrb3 = TRB_3_TYPE(TRB_TYPE_DATA_STAGE)
617 			| (directionIn ? TRB_3_DIR_IN : 0) | TRB_3_CYCLE_BIT;
618 
619 		// TODO copy data for out transfers
620 		index++;
621 	}
622 
623 	// set StatusStage
624 	setupDescriptor->trbs[index].dwtrb2 = TRB_2_IRQ(0);
625 	setupDescriptor->trbs[index].dwtrb3 = TRB_3_TYPE(TRB_TYPE_STATUS_STAGE)
626 		| ((directionIn && requestData->Length > 0) ? 0 : TRB_3_DIR_IN)
627 		| TRB_3_IOC_BIT | TRB_3_CYCLE_BIT;
628 
629 	setupDescriptor->trb_count = index + 1;
630 
631 	xhci_endpoint *endpoint = (xhci_endpoint *)pipe->ControllerCookie();
632 	uint8 id = XHCI_ENDPOINT_ID(pipe);
633 	if (id >= XHCI_MAX_ENDPOINTS) {
634 		TRACE_ERROR("Invalid Endpoint");
635 		return B_BAD_VALUE;
636 	}
637 	setupDescriptor->transfer = transfer;
638 	transfer->InitKernelAccess();
639 	_LinkDescriptorForPipe(setupDescriptor, endpoint);
640 
641 	TRACE("SubmitControlRequest() request linked\n");
642 
643 	TRACE("Endpoint status 0x%08" B_PRIx32 " 0x%08" B_PRIx32 " 0x%016" B_PRIx64 "\n",
644 		endpoint->device->device_ctx->endpoints[id-1].dwendpoint0,
645 		endpoint->device->device_ctx->endpoints[id-1].dwendpoint1,
646 		endpoint->device->device_ctx->endpoints[id-1].qwendpoint2);
647 	Ring(endpoint->device->slot, id);
648 	TRACE("Endpoint status 0x%08" B_PRIx32 " 0x%08" B_PRIx32 " 0x%016" B_PRIx64 "\n",
649 		endpoint->device->device_ctx->endpoints[id-1].dwendpoint0,
650 		endpoint->device->device_ctx->endpoints[id-1].dwendpoint1,
651 		endpoint->device->device_ctx->endpoints[id-1].qwendpoint2);
652 	return B_OK;
653 }
654 
655 
656 status_t
657 XHCI::SubmitNormalRequest(Transfer *transfer)
658 {
659 	TRACE("SubmitNormalRequest() length %ld\n", transfer->DataLength());
660 	Pipe *pipe = transfer->TransferPipe();
661 	uint8 id = XHCI_ENDPOINT_ID(pipe);
662 	if (id >= XHCI_MAX_ENDPOINTS)
663 		return B_BAD_VALUE;
664 	bool directionIn = (pipe->Direction() == Pipe::In);
665 
666 	xhci_td *descriptor = CreateDescriptorChain(transfer->DataLength());
667 	if (descriptor == NULL)
668 		return B_NO_MEMORY;
669 	descriptor->trb_count = descriptor->buffer_count;
670 
671 	// set NormalStage
672 	uint8 index;
673 	for (index = 0; index < descriptor->buffer_count; index++) {
674 		descriptor->trbs[index].qwtrb0 = descriptor->buffer_phy[index];
675 		descriptor->trbs[index].dwtrb2 = TRB_2_IRQ(0)
676 			| TRB_2_BYTES(descriptor->buffer_size[index])
677 			| TRB_2_TD_SIZE(descriptor->trb_count);
678 		descriptor->trbs[index].dwtrb3 = TRB_3_TYPE(TRB_TYPE_NORMAL)
679 			| TRB_3_CYCLE_BIT;
680 	}
681 	if (descriptor->trb_count > 0)
682 		descriptor->trbs[index - 1].dwtrb3 |= TRB_3_IOC_BIT;
683 
684 	if (!directionIn) {
685 		TRACE("copying out iov count %ld\n", transfer->VectorCount());
686 		WriteDescriptorChain(descriptor, transfer->Vector(),
687 			transfer->VectorCount());
688 	}
689 	/*	memcpy(descriptor->buffer_log[index],
690 				(uint8 *)transfer->Vector()[index].iov_base, transfer->VectorLength());
691 		}*/
692 
693 	xhci_endpoint *endpoint = (xhci_endpoint *)pipe->ControllerCookie();
694 	descriptor->transfer = transfer;
695 	transfer->InitKernelAccess();
696 	_LinkDescriptorForPipe(descriptor, endpoint);
697 
698 	TRACE("SubmitNormalRequest() request linked\n");
699 
700 	TRACE("Endpoint status 0x%08" B_PRIx32 " 0x%08" B_PRIx32 " 0x%016" B_PRIx64 "\n",
701 		endpoint->device->device_ctx->endpoints[id - 1].dwendpoint0,
702 		endpoint->device->device_ctx->endpoints[id - 1].dwendpoint1,
703 		endpoint->device->device_ctx->endpoints[id - 1].qwendpoint2);
704 	Ring(endpoint->device->slot, id);
705 	TRACE("Endpoint status 0x%08" B_PRIx32 " 0x%08" B_PRIx32 " 0x%016" B_PRIx64 "\n",
706 		endpoint->device->device_ctx->endpoints[id - 1].dwendpoint0,
707 		endpoint->device->device_ctx->endpoints[id - 1].dwendpoint1,
708 		endpoint->device->device_ctx->endpoints[id - 1].qwendpoint2);
709 	return B_OK;
710 }
711 
712 
713 status_t
714 XHCI::CancelQueuedTransfers(Pipe *pipe, bool force)
715 {
716 	TRACE_ALWAYS("cancel queued transfers for pipe %p (%d)\n", pipe,
717 		pipe->EndpointAddress());
718 	return B_OK;
719 }
720 
721 
722 status_t
723 XHCI::NotifyPipeChange(Pipe *pipe, usb_change change)
724 {
725 	TRACE("pipe change %d for pipe %p (%d)\n", change, pipe,
726 		pipe->EndpointAddress());
727 	switch (change) {
728 		case USB_CHANGE_CREATED:
729 			_InsertEndpointForPipe(pipe);
730 			break;
731 		case USB_CHANGE_DESTROYED:
732 			_RemoveEndpointForPipe(pipe);
733 			break;
734 
735 		case USB_CHANGE_PIPE_POLICY_CHANGED: {
736 			// ToDo: for isochronous pipes we might need to adapt to new
737 			// pipe policy settings here
738 			break;
739 		}
740 	}
741 
742 	return B_OK;
743 }
744 
745 
746 status_t
747 XHCI::AddTo(Stack *stack)
748 {
749 #ifdef TRACE_USB
750 	set_dprintf_enabled(true);
751 #endif
752 
753 	if (!sPCIModule) {
754 		status_t status = get_module(B_PCI_MODULE_NAME,
755 			(module_info **)&sPCIModule);
756 		if (status < B_OK) {
757 			TRACE_MODULE_ERROR("getting pci module failed! 0x%08" B_PRIx32
758 				"\n", status);
759 			return status;
760 		}
761 	}
762 
763 	TRACE_MODULE("searching devices\n");
764 	bool found = false;
765 	pci_info *item = new(std::nothrow) pci_info;
766 	if (!item) {
767 		sPCIModule = NULL;
768 		put_module(B_PCI_MODULE_NAME);
769 		return B_NO_MEMORY;
770 	}
771 
772 	// Try to get the PCI x86 module as well so we can enable possible MSIs.
773 	if (sPCIx86Module == NULL && get_module(B_PCI_X86_MODULE_NAME,
774 			(module_info **)&sPCIx86Module) != B_OK) {
775 		// If it isn't there, that's not critical though.
776 		TRACE_MODULE_ERROR("failed to get pci x86 module\n");
777 		sPCIx86Module = NULL;
778 	}
779 
780 	for (int32 i = 0; sPCIModule->get_nth_pci_info(i, item) >= B_OK; i++) {
781 		if (item->class_base == PCI_serial_bus && item->class_sub == PCI_usb
782 			&& item->class_api == PCI_usb_xhci) {
783 			if (item->u.h0.interrupt_line == 0
784 				|| item->u.h0.interrupt_line == 0xFF) {
785 				TRACE_MODULE_ERROR("found device with invalid IRQ - check IRQ "
786 					"assignment\n");
787 				continue;
788 			}
789 
790 			// whitelists a few devices for the time being
791 			switch ((item->vendor_id << 16) | item->device_id) {
792 				case 0x10330194:	// Nec Corporation uPD720200
793 				case 0x1b731009:	// Fresco Logic FL1009
794 				case 0x80861e31:	// Intel xHCI Panther Point (VirtualBox5)
795 				case 0x80869c31:	// Intel xHCI Panther Point
796 					break;
797 				default:
798 					TRACE_MODULE_ERROR("found device but unsupported\n");
799 					continue;
800 			}
801 
802 			TRACE_MODULE("found device at IRQ %u\n",
803 				item->u.h0.interrupt_line);
804 			XHCI *bus = new(std::nothrow) XHCI(item, stack);
805 			if (!bus) {
806 				delete item;
807 				sPCIModule = NULL;
808 				put_module(B_PCI_MODULE_NAME);
809 				return B_NO_MEMORY;
810 			}
811 
812 			if (bus->InitCheck() < B_OK) {
813 				TRACE_MODULE_ERROR("bus failed init check\n");
814 				delete bus;
815 				continue;
816 			}
817 
818 			// the bus took it away
819 			item = new(std::nothrow) pci_info;
820 
821 			bus->Start();
822 			stack->AddBusManager(bus);
823 			found = true;
824 		}
825 	}
826 
827 	if (!found) {
828 		TRACE_MODULE_ERROR("no devices found\n");
829 		delete item;
830 		sPCIModule = NULL;
831 		put_module(B_PCI_MODULE_NAME);
832 		return ENODEV;
833 	}
834 
835 	delete item;
836 	return B_OK;
837 }
838 
839 
840 xhci_td *
841 XHCI::CreateDescriptorChain(size_t bufferSize)
842 {
843 	size_t packetSize = B_PAGE_SIZE * 16;
844 	int32 trbCount = (bufferSize + packetSize - 1) / packetSize;
845 	// keep one trb for linking
846 	int32 tdCount = (trbCount + XHCI_MAX_TRBS_PER_TD - 2)
847 		/ (XHCI_MAX_TRBS_PER_TD - 1);
848 
849 	xhci_td *first = NULL;
850 	xhci_td *last = NULL;
851 	for (int32 i = 0; i < tdCount; i++) {
852 		xhci_td *descriptor = CreateDescriptor(0);
853 		if (!descriptor) {
854 			//FreeDescriptorChain(firstDescriptor);
855 			return NULL;
856 		} else if (first == NULL)
857 			first = descriptor;
858 
859 		uint8 trbs = min_c(trbCount, XHCI_MAX_TRBS_PER_TD);
860 		TRACE("CreateDescriptorChain trbs %d for td %" B_PRId32 "\n", trbs, i);
861 		for (int j = 0; j < trbs; j++) {
862 			if (fStack->AllocateChunk(&descriptor->buffer_log[j],
863 				&descriptor->buffer_phy[j],
864 				min_c(packetSize, bufferSize)) < B_OK) {
865 				TRACE_ERROR("unable to allocate space for the buffer (size %"
866 					B_PRIuSIZE ")\n", bufferSize);
867 				return NULL;
868 			}
869 
870 			descriptor->buffer_size[j] = min_c(packetSize, bufferSize);
871 			bufferSize -= descriptor->buffer_size[j];
872 			TRACE("CreateDescriptorChain allocated %ld for trb %d\n",
873 				descriptor->buffer_size[j], j);
874 		}
875 
876 		descriptor->buffer_count = trbs;
877 		trbCount -= trbs;
878 		if (last != NULL)
879 			last->next_chain = descriptor;
880 		last = descriptor;
881 	}
882 
883 	return first;
884 }
885 
886 
887 xhci_td *
888 XHCI::CreateDescriptor(size_t bufferSize)
889 {
890 	xhci_td *result;
891 	phys_addr_t physicalAddress;
892 
893 	if (fStack->AllocateChunk((void **)&result, &physicalAddress,
894 		sizeof(xhci_td)) < B_OK) {
895 		TRACE_ERROR("failed to allocate a transfer descriptor\n");
896 		return NULL;
897 	}
898 
899 	result->this_phy = physicalAddress;
900 	result->buffer_size[0] = bufferSize;
901 	result->trb_count = 0;
902 	result->buffer_count = 1;
903 	if (bufferSize <= 0) {
904 		result->buffer_log[0] = NULL;
905 		result->buffer_phy[0] = 0;
906 		return result;
907 	}
908 
909 	if (fStack->AllocateChunk(&result->buffer_log[0],
910 		&result->buffer_phy[0], bufferSize) < B_OK) {
911 		TRACE_ERROR("unable to allocate space for the buffer (size %ld)\n",
912 			bufferSize);
913 		fStack->FreeChunk(result, result->this_phy, sizeof(xhci_td));
914 		return NULL;
915 	}
916 
917 	return result;
918 }
919 
920 
921 void
922 XHCI::FreeDescriptor(xhci_td *descriptor)
923 {
924 	if (!descriptor)
925 		return;
926 
927 	for (int i = 0; i < descriptor->buffer_count; i++) {
928 		if (descriptor->buffer_size[i] == 0)
929 			continue;
930 		TRACE("FreeDescriptor buffer %d buffer_size %ld\n", i,
931 			descriptor->buffer_size[i]);
932 		fStack->FreeChunk(descriptor->buffer_log[i],
933 			descriptor->buffer_phy[i], descriptor->buffer_size[i]);
934 	}
935 
936 	fStack->FreeChunk(descriptor, descriptor->this_phy,
937 		sizeof(xhci_td));
938 }
939 
940 
941 size_t
942 XHCI::WriteDescriptorChain(xhci_td *descriptor, iovec *vector,
943 	size_t vectorCount)
944 {
945 	xhci_td *current = descriptor;
946 	uint8 trbIndex = 0;
947 	size_t actualLength = 0;
948 	uint8 vectorIndex = 0;
949 	size_t vectorOffset = 0;
950 	size_t bufferOffset = 0;
951 
952 	while (current != NULL) {
953 		if (current->buffer_log == NULL)
954 			break;
955 
956 		while (true) {
957 			size_t length = min_c(current->buffer_size[trbIndex] - bufferOffset,
958 				vector[vectorIndex].iov_len - vectorOffset);
959 
960 			TRACE("copying %ld bytes to bufferOffset %ld from"
961 				" vectorOffset %ld at index %d of %ld\n", length, bufferOffset,
962 				vectorOffset, vectorIndex, vectorCount);
963 			memcpy((uint8 *)current->buffer_log[trbIndex] + bufferOffset,
964 				(uint8 *)vector[vectorIndex].iov_base + vectorOffset, length);
965 
966 			actualLength += length;
967 			vectorOffset += length;
968 			bufferOffset += length;
969 
970 			if (vectorOffset >= vector[vectorIndex].iov_len) {
971 				if (++vectorIndex >= vectorCount) {
972 					TRACE("wrote descriptor chain (%ld bytes, no more vectors)\n",
973 						actualLength);
974 					return actualLength;
975 				}
976 
977 				vectorOffset = 0;
978 			}
979 
980 			if (bufferOffset >= current->buffer_size[trbIndex]) {
981 				if (++trbIndex >= current->buffer_count)
982 					break;
983 				bufferOffset = 0;
984 			}
985 		}
986 
987 		current = current->next_chain;
988 		trbIndex = 0;
989 	}
990 
991 	TRACE("wrote descriptor chain (%ld bytes)\n", actualLength);
992 	return actualLength;
993 }
994 
995 
996 size_t
997 XHCI::ReadDescriptorChain(xhci_td *descriptor, iovec *vector,
998 	size_t vectorCount)
999 {
1000 	xhci_td *current = descriptor;
1001 	uint8 trbIndex = 0;
1002 	size_t actualLength = 0;
1003 	uint8 vectorIndex = 0;
1004 	size_t vectorOffset = 0;
1005 	size_t bufferOffset = 0;
1006 
1007 	while (current != NULL) {
1008 		if (current->buffer_log == NULL)
1009 			break;
1010 
1011 		while (true) {
1012 			size_t length = min_c(current->buffer_size[trbIndex] - bufferOffset,
1013 				vector[vectorIndex].iov_len - vectorOffset);
1014 
1015 			TRACE("copying %ld bytes to vectorOffset %ld from"
1016 				" bufferOffset %ld at index %d of %ld\n", length, vectorOffset,
1017 				bufferOffset, vectorIndex, vectorCount);
1018 			memcpy((uint8 *)vector[vectorIndex].iov_base + vectorOffset,
1019 				(uint8 *)current->buffer_log[trbIndex] + bufferOffset, length);
1020 
1021 			actualLength += length;
1022 			vectorOffset += length;
1023 			bufferOffset += length;
1024 
1025 			if (vectorOffset >= vector[vectorIndex].iov_len) {
1026 				if (++vectorIndex >= vectorCount) {
1027 					TRACE("read descriptor chain (%ld bytes, no more vectors)\n",
1028 						actualLength);
1029 					return actualLength;
1030 				}
1031 
1032 				vectorOffset = 0;
1033 			}
1034 
1035 			if (bufferOffset >= current->buffer_size[trbIndex]) {
1036 				if (++trbIndex >= current->buffer_count)
1037 					break;
1038 				bufferOffset = 0;
1039 			}
1040 		}
1041 
1042 		current = current->next_chain;
1043 		trbIndex = 0;
1044 	}
1045 
1046 	TRACE("read descriptor chain (%ld bytes)\n", actualLength);
1047 	return actualLength;
1048 }
1049 
1050 
1051 Device *
1052 XHCI::AllocateDevice(Hub *parent, int8 hubAddress, uint8 hubPort,
1053 	usb_speed speed)
1054 {
1055 	TRACE("AllocateDevice hubAddress %d hubPort %d speed %d\n", hubAddress,
1056 		hubPort, speed);
1057 
1058 	uint8 slot = XHCI_MAX_SLOTS;
1059 	if (EnableSlot(&slot) != B_OK) {
1060 		TRACE_ERROR("AllocateDevice() failed enable slot\n");
1061 		return NULL;
1062 	}
1063 
1064 	if (slot == 0 || slot > fSlotCount) {
1065 		TRACE_ERROR("AllocateDevice() bad slot\n");
1066 		return NULL;
1067 	}
1068 
1069 	if (fDevices[slot].state != XHCI_STATE_DISABLED) {
1070 		TRACE_ERROR("AllocateDevice() slot already used\n");
1071 		return NULL;
1072 	}
1073 
1074 	struct xhci_device *device = &fDevices[slot];
1075 	memset(device, 0, sizeof(struct xhci_device));
1076 	device->state = XHCI_STATE_ENABLED;
1077 	device->slot = slot;
1078 
1079 	device->input_ctx_area = fStack->AllocateArea((void **)&device->input_ctx,
1080 		&device->input_ctx_addr, sizeof(*device->input_ctx),
1081 		"XHCI input context");
1082 	if (device->input_ctx_area < B_OK) {
1083 		TRACE_ERROR("unable to create a input context area\n");
1084 		device->state = XHCI_STATE_DISABLED;
1085 		return NULL;
1086 	}
1087 
1088 	memset(device->input_ctx, 0, sizeof(*device->input_ctx));
1089 	device->input_ctx->input.dropFlags = 0;
1090 	device->input_ctx->input.addFlags = 3;
1091 
1092 	uint32 route = 0;
1093 	uint8 routePort = hubPort;
1094 	uint8 rhPort = hubPort;
1095 	for (Device *hubDevice = parent; hubDevice != RootObject();
1096 		hubDevice = (Device *)hubDevice->Parent()) {
1097 
1098 		rhPort = routePort;
1099 		if (hubDevice->Parent() == RootObject())
1100 			break;
1101 		route *= 16;
1102 		if (hubPort > 15)
1103 			route += 15;
1104 		else
1105 			route += routePort;
1106 
1107 		routePort = hubDevice->HubPort();
1108 	}
1109 
1110 	// Get speed of port, only if device connected to root hub port
1111 	// else we have to rely on value reported by the Hub Explore thread
1112 	if (route == 0) {
1113 		GetPortSpeed(hubPort - 1, &speed);
1114 		TRACE("speed updated %d\n", speed);
1115 	}
1116 
1117 	device->input_ctx->slot.dwslot0 = SLOT_0_NUM_ENTRIES(1) | SLOT_0_ROUTE(route);
1118 
1119 	// add the speed
1120 	switch (speed) {
1121 	case USB_SPEED_LOWSPEED:
1122 		device->input_ctx->slot.dwslot0 |= SLOT_0_SPEED(2);
1123 		break;
1124 	case USB_SPEED_HIGHSPEED:
1125 		device->input_ctx->slot.dwslot0 |= SLOT_0_SPEED(3);
1126 		break;
1127 	case USB_SPEED_FULLSPEED:
1128 		device->input_ctx->slot.dwslot0 |= SLOT_0_SPEED(1);
1129 		break;
1130 	case USB_SPEED_SUPER:
1131 		device->input_ctx->slot.dwslot0 |= SLOT_0_SPEED(4);
1132 		break;
1133 	default:
1134 		TRACE_ERROR("unknown usb speed\n");
1135 		break;
1136 	}
1137 
1138 	device->input_ctx->slot.dwslot1 = SLOT_1_RH_PORT(rhPort); // TODO enable power save
1139 	device->input_ctx->slot.dwslot2 = SLOT_2_IRQ_TARGET(0);
1140 
1141 	// If LS/FS device connected to non-root HS device
1142 	if (route != 0 && parent->Speed() == USB_SPEED_HIGHSPEED
1143 		&& (speed == USB_SPEED_LOWSPEED || speed == USB_SPEED_FULLSPEED)) {
1144 		struct xhci_device *parenthub = (struct xhci_device *)
1145 			parent->ControllerCookie();
1146 		device->input_ctx->slot.dwslot2 |= SLOT_2_PORT_NUM(hubPort);
1147 		device->input_ctx->slot.dwslot2 |= SLOT_2_TT_HUB_SLOT(parenthub->slot);
1148 	}
1149 
1150 	device->input_ctx->slot.dwslot3 = SLOT_3_SLOT_STATE(0)
1151 		| SLOT_3_DEVICE_ADDRESS(0);
1152 
1153 	TRACE("slot 0x%08" B_PRIx32 " 0x%08" B_PRIx32 " 0x%08" B_PRIx32 " 0x%08" B_PRIx32
1154 		"\n", device->input_ctx->slot.dwslot0,
1155 		device->input_ctx->slot.dwslot1, device->input_ctx->slot.dwslot2,
1156 		device->input_ctx->slot.dwslot3);
1157 
1158 	device->device_ctx_area = fStack->AllocateArea((void **)&device->device_ctx,
1159 		&device->device_ctx_addr, sizeof(*device->device_ctx),
1160 		"XHCI device context");
1161 	if (device->device_ctx_area < B_OK) {
1162 		TRACE_ERROR("unable to create a device context area\n");
1163 		device->state = XHCI_STATE_DISABLED;
1164 		delete_area(device->input_ctx_area);
1165 		return NULL;
1166 	}
1167 	memset(device->device_ctx, 0, sizeof(*device->device_ctx));
1168 
1169 	device->trb_area = fStack->AllocateArea((void **)&device->trbs,
1170 		&device->trb_addr, sizeof(*device->trbs) * (XHCI_MAX_ENDPOINTS - 1)
1171 			* XHCI_MAX_TRANSFERS, "XHCI endpoint trbs");
1172 	if (device->trb_area < B_OK) {
1173 		TRACE_ERROR("unable to create a device trbs area\n");
1174 		device->state = XHCI_STATE_DISABLED;
1175 		delete_area(device->input_ctx_area);
1176 		delete_area(device->device_ctx_area);
1177 		return NULL;
1178 	}
1179 
1180 	// set up slot pointer to device context
1181 	fDcba->baseAddress[slot] = device->device_ctx_addr;
1182 
1183 	size_t maxPacketSize;
1184 	switch (speed) {
1185 	case USB_SPEED_LOWSPEED:
1186 	case USB_SPEED_FULLSPEED:
1187 		maxPacketSize = 8;
1188 		break;
1189 	case USB_SPEED_HIGHSPEED:
1190 		maxPacketSize = 64;
1191 		break;
1192 	default:
1193 		maxPacketSize = 512;
1194 		break;
1195 	}
1196 
1197 	// configure the Control endpoint 0 (type 4)
1198 	if (ConfigureEndpoint(slot, 0, 4, device->trb_addr, 0,
1199 		maxPacketSize, maxPacketSize & 0x7ff, speed) != B_OK) {
1200 		TRACE_ERROR("unable to configure default control endpoint\n");
1201 		device->state = XHCI_STATE_DISABLED;
1202 		delete_area(device->input_ctx_area);
1203 		delete_area(device->device_ctx_area);
1204 		delete_area(device->trb_area);
1205 		return NULL;
1206 	}
1207 
1208 	device->endpoints[0].device = device;
1209 	device->endpoints[0].td_head = NULL;
1210 	device->endpoints[0].trbs = device->trbs;
1211 	device->endpoints[0].used = 0;
1212 	device->endpoints[0].current = 0;
1213 	device->endpoints[0].trb_addr = device->trb_addr;
1214 	mutex_init(&device->endpoints[0].lock, "xhci endpoint lock");
1215 
1216 	// device should get to addressed state (bsr = 0)
1217 	if (SetAddress(device->input_ctx_addr, false, slot) != B_OK) {
1218 		TRACE_ERROR("unable to set address\n");
1219 		device->state = XHCI_STATE_DISABLED;
1220 		delete_area(device->input_ctx_area);
1221 		delete_area(device->device_ctx_area);
1222 		delete_area(device->trb_area);
1223 		return NULL;
1224 	}
1225 
1226 	device->state = XHCI_STATE_ADDRESSED;
1227 	device->address = SLOT_3_DEVICE_ADDRESS_GET(
1228 		device->device_ctx->slot.dwslot3);
1229 
1230 	TRACE("device: address 0x%x state 0x%08" B_PRIx32 "\n", device->address,
1231 		SLOT_3_SLOT_STATE_GET(device->device_ctx->slot.dwslot3));
1232 	TRACE("endpoint0 state 0x%08" B_PRIx32 "\n",
1233 		ENDPOINT_0_STATE_GET(device->device_ctx->endpoints[0].dwendpoint0));
1234 
1235 	// Create a temporary pipe with the new address
1236 	ControlPipe pipe(parent);
1237 	pipe.SetControllerCookie(&device->endpoints[0]);
1238 	pipe.InitCommon(device->address + 1, 0, speed, Pipe::Default, maxPacketSize, 0,
1239 		hubAddress, hubPort);
1240 
1241 	// Get the device descriptor
1242 	// Just retrieve the first 8 bytes of the descriptor -> minimum supported
1243 	// size of any device. It is enough because it includes the device type.
1244 
1245 	size_t actualLength = 0;
1246 	usb_device_descriptor deviceDescriptor;
1247 
1248 	TRACE("getting the device descriptor\n");
1249 	pipe.SendRequest(
1250 		USB_REQTYPE_DEVICE_IN | USB_REQTYPE_STANDARD,		// type
1251 		USB_REQUEST_GET_DESCRIPTOR,							// request
1252 		USB_DESCRIPTOR_DEVICE << 8,							// value
1253 		0,													// index
1254 		8,													// length
1255 		(void *)&deviceDescriptor,							// buffer
1256 		8,													// buffer length
1257 		&actualLength);										// actual length
1258 
1259 	if (actualLength != 8) {
1260 		TRACE_ERROR("error while getting the device descriptor\n");
1261 		device->state = XHCI_STATE_DISABLED;
1262 		delete_area(device->input_ctx_area);
1263 		delete_area(device->device_ctx_area);
1264 		delete_area(device->trb_area);
1265 		return NULL;
1266 	}
1267 
1268 	TRACE("device_class: %d device_subclass %d device_protocol %d\n",
1269 		deviceDescriptor.device_class, deviceDescriptor.device_subclass,
1270 		deviceDescriptor.device_protocol);
1271 
1272 	if (speed == USB_SPEED_FULLSPEED && deviceDescriptor.max_packet_size_0 != 8) {
1273 		TRACE("Full speed device with different max packet size for Endpoint 0\n");
1274 		device->input_ctx->endpoints[0].dwendpoint1 &=
1275 			~ENDPOINT_1_MAXPACKETSIZE(0xffff);
1276 		device->input_ctx->endpoints[0].dwendpoint1 |=
1277 			ENDPOINT_1_MAXPACKETSIZE(deviceDescriptor.max_packet_size_0);
1278 		device->input_ctx->input.dropFlags = 0;
1279 		device->input_ctx->input.addFlags = (1 << 1);
1280 		EvaluateContext(device->input_ctx_addr, device->slot);
1281 	}
1282 
1283 	Device *deviceObject = NULL;
1284 	if (deviceDescriptor.device_class == 0x09) {
1285 		TRACE("creating new Hub\n");
1286 		TRACE("getting the hub descriptor\n");
1287 		size_t actualLength = 0;
1288 		usb_hub_descriptor hubDescriptor;
1289 		pipe.SendRequest(
1290 			USB_REQTYPE_DEVICE_IN | USB_REQTYPE_STANDARD,		// type
1291 			USB_REQUEST_GET_DESCRIPTOR,							// request
1292 			USB_DESCRIPTOR_HUB << 8,							// value
1293 			0,													// index
1294 			sizeof(usb_hub_descriptor),							// length
1295 			(void *)&hubDescriptor,								// buffer
1296 			sizeof(usb_hub_descriptor),							// buffer length
1297 			&actualLength);
1298 
1299 		if (actualLength != sizeof(usb_hub_descriptor)) {
1300 			TRACE_ERROR("error while getting the hub descriptor\n");
1301 			device->state = XHCI_STATE_DISABLED;
1302 			delete_area(device->input_ctx_area);
1303 			delete_area(device->device_ctx_area);
1304 			delete_area(device->trb_area);
1305 			return NULL;
1306 		}
1307 
1308 		device->input_ctx->slot.dwslot0 |= SLOT_0_HUB_BIT;
1309 		device->input_ctx->slot.dwslot1 |= SLOT_1_NUM_PORTS(hubDescriptor.num_ports);
1310 		if (speed == USB_SPEED_HIGHSPEED) {
1311 			device->input_ctx->slot.dwslot2 |=
1312 				SLOT_2_TT_TIME(HUB_TTT_GET(hubDescriptor.characteristics));
1313 		}
1314 
1315 		deviceObject = new(std::nothrow) Hub(parent, hubAddress, hubPort,
1316 			deviceDescriptor, device->address + 1, speed, false, device);
1317 	} else {
1318 		TRACE("creating new device\n");
1319 		deviceObject = new(std::nothrow) Device(parent, hubAddress, hubPort,
1320 			deviceDescriptor, device->address + 1, speed, false, device);
1321 	}
1322 	if (deviceObject == NULL) {
1323 		TRACE_ERROR("no memory to allocate device\n");
1324 		device->state = XHCI_STATE_DISABLED;
1325 		delete_area(device->input_ctx_area);
1326 		delete_area(device->device_ctx_area);
1327 		delete_area(device->trb_area);
1328 		return NULL;
1329 	}
1330 	fPortSlots[hubPort] = slot;
1331 	TRACE("AllocateDevice() port %d slot %d\n", hubPort, slot);
1332 	return deviceObject;
1333 }
1334 
1335 
1336 void
1337 XHCI::FreeDevice(Device *device)
1338 {
1339 	uint8 slot = fPortSlots[device->HubPort()];
1340 	TRACE("FreeDevice() port %d slot %d\n", device->HubPort(), slot);
1341 	DisableSlot(slot);
1342 	fDcba->baseAddress[slot] = 0;
1343 	fPortSlots[device->HubPort()] = 0;
1344 	delete_area(fDevices[slot].trb_area);
1345 	delete_area(fDevices[slot].input_ctx_area);
1346 	delete_area(fDevices[slot].device_ctx_area);
1347 	fDevices[slot].state = XHCI_STATE_DISABLED;
1348 	delete device;
1349 }
1350 
1351 
1352 status_t
1353 XHCI::_InsertEndpointForPipe(Pipe *pipe)
1354 {
1355 	TRACE("_InsertEndpointForPipe endpoint address %" B_PRId8 "\n",
1356 		pipe->EndpointAddress());
1357 	if (pipe->ControllerCookie() != NULL
1358 		|| pipe->Parent()->Type() != USB_OBJECT_DEVICE) {
1359 		// default pipe is already referenced
1360 		return B_OK;
1361 	}
1362 
1363 	Device* usbDevice = (Device *)pipe->Parent();
1364 	struct xhci_device *device = (struct xhci_device *)
1365 		usbDevice->ControllerCookie();
1366 	if (usbDevice->Parent() == RootObject())
1367 		return B_OK;
1368 	if (device == NULL) {
1369 		panic("_InsertEndpointForPipe device is NULL\n");
1370 		return B_OK;
1371 	}
1372 
1373 	uint8 id = XHCI_ENDPOINT_ID(pipe) - 1;
1374 	if (id >= XHCI_MAX_ENDPOINTS - 1)
1375 		return B_BAD_VALUE;
1376 
1377 	if (id > 0) {
1378 		if (SLOT_0_NUM_ENTRIES_GET(device->device_ctx->slot.dwslot0) == 1) {
1379 			device->input_ctx->slot.dwslot0 &= ~(SLOT_0_NUM_ENTRIES(0x1f));
1380 			device->input_ctx->slot.dwslot0 |=
1381 				SLOT_0_NUM_ENTRIES(XHCI_MAX_ENDPOINTS - 1);
1382 			EvaluateContext(device->input_ctx_addr, device->slot);
1383 		}
1384 
1385 		device->endpoints[id].device = device;
1386 		device->endpoints[id].trbs = device->trbs
1387 			+ id * XHCI_MAX_TRANSFERS;
1388 		device->endpoints[id].td_head = NULL;
1389 		device->endpoints[id].used = 0;
1390 		device->endpoints[id].trb_addr = device->trb_addr
1391 			+ id * XHCI_MAX_TRANSFERS * sizeof(xhci_trb);
1392 		mutex_init(&device->endpoints[id].lock, "xhci endpoint lock");
1393 
1394 		TRACE("_InsertEndpointForPipe trbs device %p endpoint %p\n",
1395 			device->trbs, device->endpoints[id].trbs);
1396 		TRACE("_InsertEndpointForPipe trb_addr device 0x%" B_PRIxPHYSADDR
1397 			" endpoint 0x%" B_PRIxPHYSADDR "\n", device->trb_addr,
1398 			device->endpoints[id].trb_addr);
1399 
1400 		uint8 endpoint = id + 1;
1401 
1402 		/* TODO: invalid Context State running the 3 following commands
1403 		StopEndpoint(false, endpoint, device->slot);
1404 
1405 		ResetEndpoint(false, endpoint, device->slot);
1406 
1407 		SetTRDequeue(device->endpoints[id].trb_addr, 0, endpoint,
1408 			device->slot); */
1409 
1410 		device->input_ctx->input.dropFlags = 0;
1411 		device->input_ctx->input.addFlags = (1 << endpoint) | (1 << 0);
1412 
1413 		// configure the Control endpoint 0 (type 4)
1414 		uint32 type = 4;
1415 		if ((pipe->Type() & USB_OBJECT_INTERRUPT_PIPE) != 0)
1416 			type = 3;
1417 		if ((pipe->Type() & USB_OBJECT_BULK_PIPE) != 0)
1418 			type = 2;
1419 		if ((pipe->Type() & USB_OBJECT_ISO_PIPE) != 0)
1420 			type = 1;
1421 		type |= (pipe->Direction() == Pipe::In) ? (1 << 2) : 0;
1422 
1423 		TRACE("trb_addr 0x%" B_PRIxPHYSADDR "\n", device->endpoints[id].trb_addr);
1424 
1425 		if (ConfigureEndpoint(device->slot, id, type,
1426 			device->endpoints[id].trb_addr, pipe->Interval(),
1427 			pipe->MaxPacketSize(), pipe->MaxPacketSize() & 0x7ff,
1428 			usbDevice->Speed()) != B_OK) {
1429 			TRACE_ERROR("unable to configure endpoint\n");
1430 			return B_ERROR;
1431 		}
1432 
1433 		EvaluateContext(device->input_ctx_addr, device->slot);
1434 
1435 		ConfigureEndpoint(device->input_ctx_addr, false, device->slot);
1436 		TRACE("device: address 0x%x state 0x%08" B_PRIx32 "\n", device->address,
1437 			SLOT_3_SLOT_STATE_GET(device->device_ctx->slot.dwslot3));
1438 		TRACE("endpoint[0] state 0x%08" B_PRIx32 "\n",
1439 			ENDPOINT_0_STATE_GET(device->device_ctx->endpoints[0].dwendpoint0));
1440 		TRACE("endpoint[%d] state 0x%08" B_PRIx32 "\n", id,
1441 			ENDPOINT_0_STATE_GET(device->device_ctx->endpoints[id].dwendpoint0));
1442 		device->state = XHCI_STATE_CONFIGURED;
1443 	}
1444 	pipe->SetControllerCookie(&device->endpoints[id]);
1445 
1446 	TRACE("_InsertEndpointForPipe for pipe %p at id %d\n", pipe, id);
1447 
1448 	return B_OK;
1449 }
1450 
1451 
1452 status_t
1453 XHCI::_RemoveEndpointForPipe(Pipe *pipe)
1454 {
1455 	if (pipe->Parent()->Type() != USB_OBJECT_DEVICE)
1456 		return B_OK;
1457 	//Device* device = (Device *)pipe->Parent();
1458 
1459 	return B_OK;
1460 }
1461 
1462 
1463 status_t
1464 XHCI::_LinkDescriptorForPipe(xhci_td *descriptor, xhci_endpoint *endpoint)
1465 {
1466 	TRACE("_LinkDescriptorForPipe\n");
1467 	MutexLocker endpointLocker(endpoint->lock);
1468 	if (endpoint->used >= XHCI_MAX_TRANSFERS) {
1469 		TRACE_ERROR("_LinkDescriptorForPipe max transfers count exceeded\n");
1470 		return B_BAD_VALUE;
1471 	}
1472 
1473 	endpoint->used++;
1474 	if (endpoint->td_head == NULL)
1475 		descriptor->next = NULL;
1476 	else
1477 		descriptor->next = endpoint->td_head;
1478 	endpoint->td_head = descriptor;
1479 
1480 	uint8 current = endpoint->current;
1481 	uint8 next = (current + 1) % (XHCI_MAX_TRANSFERS);
1482 
1483 	TRACE("_LinkDescriptorForPipe current %d, next %d\n", current, next);
1484 
1485 	// compute next link
1486 	addr_t addr = endpoint->trb_addr + next * sizeof(struct xhci_trb);
1487 	descriptor->trbs[descriptor->trb_count].qwtrb0 = addr;
1488 	descriptor->trbs[descriptor->trb_count].dwtrb2 = TRB_2_IRQ(0);
1489 	descriptor->trbs[descriptor->trb_count].dwtrb3 = TRB_3_TYPE(TRB_TYPE_LINK)
1490 		| TRB_3_IOC_BIT | TRB_3_CYCLE_BIT;
1491 
1492 	endpoint->trbs[next].qwtrb0 = 0;
1493 	endpoint->trbs[next].dwtrb2 = 0;
1494 	endpoint->trbs[next].dwtrb3 = 0;
1495 
1496 	endpoint->trbs[current].qwtrb0 = descriptor->this_phy;
1497 	endpoint->trbs[current].dwtrb2 = TRB_2_IRQ(0);
1498 	endpoint->trbs[current].dwtrb3 = TRB_3_TYPE(TRB_TYPE_LINK)
1499 		| TRB_3_CYCLE_BIT;
1500 
1501 	TRACE("_LinkDescriptorForPipe pCurrent %p phys 0x%" B_PRIxPHYSADDR
1502 		" 0x%" B_PRIxPHYSADDR " 0x%08" B_PRIx32 "\n", &endpoint->trbs[current],
1503 		endpoint->trb_addr + current * sizeof(struct xhci_trb),
1504 		endpoint->trbs[current].qwtrb0, endpoint->trbs[current].dwtrb3);
1505 	endpoint->current = next;
1506 
1507 	return B_OK;
1508 }
1509 
1510 
1511 status_t
1512 XHCI::_UnlinkDescriptorForPipe(xhci_td *descriptor, xhci_endpoint *endpoint)
1513 {
1514 	TRACE("_UnlinkDescriptorForPipe\n");
1515 	MutexLocker endpointLocker(endpoint->lock);
1516 	endpoint->used--;
1517 	if (descriptor == endpoint->td_head) {
1518 		endpoint->td_head = descriptor->next;
1519 		descriptor->next = NULL;
1520 		return B_OK;
1521 	} else {
1522 		for (xhci_td *td = endpoint->td_head; td->next != NULL; td = td->next) {
1523 			if (td->next == descriptor) {
1524 				td->next = descriptor->next;
1525 				descriptor->next = NULL;
1526 				return B_OK;
1527 			}
1528 		}
1529 	}
1530 
1531 	endpoint->used++;
1532 	return B_ERROR;
1533 }
1534 
1535 
1536 status_t
1537 XHCI::ConfigureEndpoint(uint8 slot, uint8 number, uint8 type, uint64 ringAddr,
1538 	uint16 interval, uint16 maxPacketSize, uint16 maxFrameSize, usb_speed speed)
1539 {
1540 	struct xhci_device* device = &fDevices[slot];
1541 	struct xhci_endpoint_ctx* endpoint = &device->input_ctx->endpoints[number];
1542 
1543 	uint8 maxBurst = (maxPacketSize & 0x1800) >> 11;
1544 	maxPacketSize = (maxPacketSize & 0x7ff);
1545 
1546 	endpoint->dwendpoint0 = 0;
1547 	endpoint->dwendpoint1 = 0;
1548 	endpoint->qwendpoint2 = 0;
1549 	endpoint->dwendpoint4 = 0;
1550 
1551 	// Assigning Interval
1552 	uint16 calcInterval = 0;
1553 	if (speed == USB_SPEED_HIGHSPEED && (type == 4 || type == 2)) {
1554 		if (interval != 0) {
1555 			while ((1<<calcInterval) <= interval)
1556 				calcInterval++;
1557 			calcInterval--;
1558 		}
1559 	}
1560 	if ((type & 0x3) == 3 &&
1561 		(speed == USB_SPEED_FULLSPEED || speed == USB_SPEED_LOWSPEED)) {
1562 		while ((1<<calcInterval) <= interval * 8)
1563 			calcInterval++;
1564 		calcInterval--;
1565 	}
1566 	if ((type & 0x3) == 1 && speed == USB_SPEED_FULLSPEED) {
1567 		calcInterval = interval + 2;
1568 	}
1569 	if (((type & 0x3) == 1 || (type & 0x3) == 3) &&
1570 		(speed == USB_SPEED_HIGHSPEED || speed == USB_SPEED_SUPER)) {
1571 		calcInterval = interval - 1;
1572 	}
1573 
1574 	endpoint->dwendpoint0 |= ENDPOINT_0_INTERVAL(calcInterval);
1575 
1576 	// Assigning CERR for non-isoch endpoints
1577 	if ((type & 0x3) != 1) {
1578 		endpoint->dwendpoint1 |= ENDPOINT_1_CERR(3);
1579 	}
1580 
1581 	endpoint->dwendpoint1 |= ENDPOINT_1_EPTYPE(type);
1582 
1583 	// Assigning MaxBurst for HighSpeed
1584 	if (speed == USB_SPEED_HIGHSPEED &&
1585 		((type & 0x3) == 1 || (type & 0x3) == 3)) {
1586 		endpoint->dwendpoint1 |= ENDPOINT_1_MAXBURST(maxBurst);
1587 	}
1588 
1589 	// TODO Assign MaxBurst for SuperSpeed
1590 
1591 	endpoint->dwendpoint1 |= ENDPOINT_1_MAXPACKETSIZE(maxPacketSize);
1592 	endpoint->qwendpoint2 |= ENDPOINT_2_DCS_BIT | ringAddr;
1593 
1594 	// Assign MaxESITPayload
1595 	// Assign AvgTRBLength
1596 	switch (type) {
1597 		case 4:
1598 			endpoint->dwendpoint4 =	ENDPOINT_4_AVGTRBLENGTH(8);
1599 			break;
1600 		case 1:
1601 		case 3:
1602 		case 5:
1603 		case 7:
1604 			endpoint->dwendpoint4 =	ENDPOINT_4_AVGTRBLENGTH(min_c(maxFrameSize,
1605 				B_PAGE_SIZE)) | ENDPOINT_4_MAXESITPAYLOAD((
1606 					(maxBurst+1) * maxPacketSize));
1607 			break;
1608 		default:
1609 			endpoint->dwendpoint4 =	ENDPOINT_4_AVGTRBLENGTH(B_PAGE_SIZE);
1610 			break;
1611 	}
1612 
1613 	TRACE("endpoint 0x%" B_PRIx32 " 0x%" B_PRIx32 " 0x%" B_PRIx64 " 0x%"
1614 		B_PRIx32 "\n", endpoint->dwendpoint0, endpoint->dwendpoint1,
1615 		endpoint->qwendpoint2, endpoint->dwendpoint4);
1616 
1617 	return B_OK;
1618 }
1619 
1620 
1621 status_t
1622 XHCI::GetPortSpeed(uint8 index, usb_speed* speed)
1623 {
1624 	uint32 portStatus = ReadOpReg(XHCI_PORTSC(index));
1625 
1626 	switch (PS_SPEED_GET(portStatus)) {
1627 	case 3:
1628 		*speed = USB_SPEED_HIGHSPEED;
1629 		break;
1630 	case 2:
1631 		*speed = USB_SPEED_LOWSPEED;
1632 		break;
1633 	case 1:
1634 		*speed = USB_SPEED_FULLSPEED;
1635 		break;
1636 	case 4:
1637 		*speed = USB_SPEED_SUPER;
1638 		break;
1639 	default:
1640 		TRACE("Non Standard Port Speed\n");
1641 		TRACE("Assuming Superspeed\n");
1642 		*speed = USB_SPEED_SUPER;
1643 		break;
1644 	}
1645 
1646 	return B_OK;
1647 }
1648 
1649 
1650 status_t
1651 XHCI::GetPortStatus(uint8 index, usb_port_status* status)
1652 {
1653 	if (index >= fPortCount)
1654 		return B_BAD_INDEX;
1655 
1656 	status->status = status->change = 0;
1657 	uint32 portStatus = ReadOpReg(XHCI_PORTSC(index));
1658 	TRACE("port %" B_PRId8 " status=0x%08" B_PRIx32 "\n", index, portStatus);
1659 
1660 	// build the status
1661 	switch (PS_SPEED_GET(portStatus)) {
1662 	case 3:
1663 		status->status |= PORT_STATUS_HIGH_SPEED;
1664 		break;
1665 	case 2:
1666 		status->status |= PORT_STATUS_LOW_SPEED;
1667 		break;
1668 	default:
1669 		break;
1670 	}
1671 
1672 	if (portStatus & PS_CCS)
1673 		status->status |= PORT_STATUS_CONNECTION;
1674 	if (portStatus & PS_PED)
1675 		status->status |= PORT_STATUS_ENABLE;
1676 	if (portStatus & PS_OCA)
1677 		status->status |= PORT_STATUS_OVER_CURRENT;
1678 	if (portStatus & PS_PR)
1679 		status->status |= PORT_STATUS_RESET;
1680 	if (portStatus & PS_PP) {
1681 		if (fPortSpeeds[index] == USB_SPEED_SUPER)
1682 			status->status |= PORT_STATUS_SS_POWER;
1683 		else
1684 			status->status |= PORT_STATUS_POWER;
1685 	}
1686 
1687 	// build the change
1688 	if (portStatus & PS_CSC)
1689 		status->change |= PORT_STATUS_CONNECTION;
1690 	if (portStatus & PS_PEC)
1691 		status->change |= PORT_STATUS_ENABLE;
1692 	if (portStatus & PS_OCC)
1693 		status->change |= PORT_STATUS_OVER_CURRENT;
1694 	if (portStatus & PS_PRC)
1695 		status->change |= PORT_STATUS_RESET;
1696 
1697 	if (fPortSpeeds[index] == USB_SPEED_SUPER) {
1698 		if (portStatus & PS_PLC)
1699 			status->change |= PORT_LINK_STATE;
1700 		if (portStatus & PS_WRC)
1701 			status->change |= PORT_BH_PORT_RESET;
1702 	}
1703 
1704 	return B_OK;
1705 }
1706 
1707 
1708 status_t
1709 XHCI::SetPortFeature(uint8 index, uint16 feature)
1710 {
1711 	TRACE("set port feature index %u feature %u\n", index, feature);
1712 	if (index >= fPortCount)
1713 		return B_BAD_INDEX;
1714 
1715 	uint32 portRegister = XHCI_PORTSC(index);
1716 	uint32 portStatus = ReadOpReg(portRegister) & ~PS_CLEAR;
1717 
1718 	switch (feature) {
1719 	case PORT_SUSPEND:
1720 		if ((portStatus & PS_PED) == 0 || (portStatus & PS_PR)
1721 			|| (portStatus & PS_PLS_MASK) >= PS_XDEV_U3) {
1722 			TRACE_ERROR("USB core suspending device not in U0/U1/U2.\n");
1723 			return B_BAD_VALUE;
1724 		}
1725 		portStatus &= ~PS_PLS_MASK;
1726 		WriteOpReg(portRegister, portStatus | PS_LWS | PS_XDEV_U3);
1727 		break;
1728 
1729 	case PORT_RESET:
1730 		WriteOpReg(portRegister, portStatus | PS_PR);
1731 		break;
1732 
1733 	case PORT_POWER:
1734 		WriteOpReg(portRegister, portStatus | PS_PP);
1735 		break;
1736 	default:
1737 		return B_BAD_VALUE;
1738 	}
1739 	ReadOpReg(portRegister);
1740 	return B_OK;
1741 }
1742 
1743 
1744 status_t
1745 XHCI::ClearPortFeature(uint8 index, uint16 feature)
1746 {
1747 	TRACE("clear port feature index %u feature %u\n", index, feature);
1748 	if (index >= fPortCount)
1749 		return B_BAD_INDEX;
1750 
1751 	uint32 portRegister = XHCI_PORTSC(index);
1752 	uint32 portStatus = ReadOpReg(portRegister) & ~PS_CLEAR;
1753 
1754 	switch (feature) {
1755 	case PORT_SUSPEND:
1756 		portStatus = ReadOpReg(portRegister);
1757 		if (portStatus & PS_PR)
1758 			return B_BAD_VALUE;
1759 		if (portStatus & PS_XDEV_U3) {
1760 			if ((portStatus & PS_PED) == 0)
1761 				return B_BAD_VALUE;
1762 			portStatus &= ~PS_PLS_MASK;
1763 			WriteOpReg(portRegister, portStatus | PS_XDEV_U0 | PS_LWS);
1764 		}
1765 		break;
1766 	case PORT_ENABLE:
1767 		WriteOpReg(portRegister, portStatus | PS_PED);
1768 		break;
1769 	case PORT_POWER:
1770 		WriteOpReg(portRegister, portStatus & ~PS_PP);
1771 		break;
1772 	case C_PORT_CONNECTION:
1773 		WriteOpReg(portRegister, portStatus | PS_CSC);
1774 		break;
1775 	case C_PORT_ENABLE:
1776 		WriteOpReg(portRegister, portStatus | PS_PEC);
1777 		break;
1778 	case C_PORT_OVER_CURRENT:
1779 		WriteOpReg(portRegister, portStatus | PS_OCC);
1780 		break;
1781 	case C_PORT_RESET:
1782 		WriteOpReg(portRegister, portStatus | PS_PRC);
1783 		break;
1784 	default:
1785 		return B_BAD_VALUE;
1786 	}
1787 
1788 	ReadOpReg(portRegister);
1789 	return B_OK;
1790 }
1791 
1792 
1793 status_t
1794 XHCI::ControllerHalt()
1795 {
1796 	WriteOpReg(XHCI_CMD, 0);
1797 
1798 	int32 tries = 100;
1799 	while ((ReadOpReg(XHCI_STS) & STS_HCH) == 0) {
1800 		snooze(1000);
1801 		if (tries-- < 0)
1802 			return B_ERROR;
1803 	}
1804 
1805 	return B_OK;
1806 }
1807 
1808 
1809 status_t
1810 XHCI::ControllerReset()
1811 {
1812 	TRACE("ControllerReset() cmd: 0x%" B_PRIx32 " sts: 0x%" B_PRIx32 "\n",
1813 		ReadOpReg(XHCI_CMD), ReadOpReg(XHCI_STS));
1814 	WriteOpReg(XHCI_CMD, ReadOpReg(XHCI_CMD) | CMD_HCRST);
1815 
1816 	int32 tries = 250;
1817 	while (ReadOpReg(XHCI_CMD) & CMD_HCRST) {
1818 		snooze(1000);
1819 		if (tries-- < 0) {
1820 			TRACE("ControllerReset() failed CMD_HCRST\n");
1821 			return B_ERROR;
1822 		}
1823 	}
1824 
1825 	tries = 250;
1826 	while (ReadOpReg(XHCI_STS) & STS_CNR) {
1827 		snooze(1000);
1828 		if (tries-- < 0) {
1829 			TRACE("ControllerReset() failed STS_CNR\n");
1830 			return B_ERROR;
1831 		}
1832 	}
1833 
1834 	return B_OK;
1835 }
1836 
1837 
1838 int32
1839 XHCI::InterruptHandler(void* data)
1840 {
1841 	return ((XHCI*)data)->Interrupt();
1842 }
1843 
1844 
1845 int32
1846 XHCI::Interrupt()
1847 {
1848 	SpinLocker _(&fSpinlock);
1849 
1850 	uint32 status = ReadOpReg(XHCI_STS);
1851 	uint32 temp = ReadRunReg32(XHCI_IMAN(0));
1852 	WriteOpReg(XHCI_STS, status);
1853 	WriteRunReg32(XHCI_IMAN(0), temp);
1854 
1855 	int32 result = B_HANDLED_INTERRUPT;
1856 
1857 	if ((status & STS_HCH) != 0) {
1858 		TRACE_ERROR("Host Controller halted\n");
1859 		return result;
1860 	}
1861 	if ((status & STS_HSE) != 0) {
1862 		TRACE_ERROR("Host System Error\n");
1863 		return result;
1864 	}
1865 	if ((status & STS_HCE) != 0) {
1866 		TRACE_ERROR("Host Controller Error\n");
1867 		return result;
1868 	}
1869 
1870 	if ((status & STS_EINT) == 0) {
1871 		TRACE("STS: %" B_PRIx32 " IRQ_PENDING: %" B_PRIx32 "\n", status, temp);
1872 		return B_UNHANDLED_INTERRUPT;
1873 	}
1874 
1875 	TRACE("Event Interrupt\n");
1876 	release_sem_etc(fEventSem, 1, B_DO_NOT_RESCHEDULE);
1877 	return B_INVOKE_SCHEDULER;
1878 }
1879 
1880 
1881 void
1882 XHCI::Ring(uint8 slot, uint8 endpoint)
1883 {
1884 	TRACE("Ding Dong! slot:%d endpoint %d\n", slot, endpoint)
1885 	if ((slot == 0 && endpoint > 0) || (slot > 0 && endpoint == 0))
1886 		panic("Ring() invalid slot/endpoint combination\n");
1887 	if (slot > fSlotCount || endpoint >= XHCI_MAX_ENDPOINTS)
1888 		panic("Ring() invalid slot or endpoint\n");
1889 	WriteDoorReg32(XHCI_DOORBELL(slot), XHCI_DOORBELL_TARGET(endpoint)
1890 		| XHCI_DOORBELL_STREAMID(0));
1891 	/* Flush PCI posted writes */
1892 	ReadDoorReg32(XHCI_DOORBELL(slot));
1893 }
1894 
1895 
1896 void
1897 XHCI::QueueCommand(xhci_trb* trb)
1898 {
1899 	uint8 i, j;
1900 	uint32 temp;
1901 
1902 	i = fCmdIdx;
1903 	j = fCmdCcs;
1904 
1905 	TRACE("command[%u] = %" B_PRIx32 " (0x%016" B_PRIx64 ", 0x%08" B_PRIx32
1906 		", 0x%08" B_PRIx32 ")\n", i, TRB_3_TYPE_GET(trb->dwtrb3),
1907 		trb->qwtrb0, trb->dwtrb2, trb->dwtrb3);
1908 
1909 	fCmdRing[i].qwtrb0 = trb->qwtrb0;
1910 	fCmdRing[i].dwtrb2 = trb->dwtrb2;
1911 	temp = trb->dwtrb3;
1912 
1913 	if (j)
1914 		temp |= TRB_3_CYCLE_BIT;
1915 	else
1916 		temp &= ~TRB_3_CYCLE_BIT;
1917 	temp &= ~TRB_3_TC_BIT;
1918 	fCmdRing[i].dwtrb3 = temp;
1919 
1920 	fCmdAddr = fErst->rs_addr + (XHCI_MAX_EVENTS + i) * sizeof(xhci_trb);
1921 
1922 	i++;
1923 
1924 	if (i == (XHCI_MAX_COMMANDS - 1)) {
1925 		temp = TRB_3_TYPE(TRB_TYPE_LINK) | TRB_3_TC_BIT;
1926 		if (j)
1927 			temp |= TRB_3_CYCLE_BIT;
1928 		fCmdRing[i].dwtrb3 = temp;
1929 
1930 		i = 0;
1931 		j ^= 1;
1932 	}
1933 
1934 	fCmdIdx = i;
1935 	fCmdCcs = j;
1936 }
1937 
1938 
1939 void
1940 XHCI::HandleCmdComplete(xhci_trb* trb)
1941 {
1942 	if (fCmdAddr == trb->qwtrb0) {
1943 		TRACE("Received command event\n");
1944 		fCmdResult[0] = trb->dwtrb2;
1945 		fCmdResult[1] = trb->dwtrb3;
1946 		release_sem_etc(fCmdCompSem, 1, B_DO_NOT_RESCHEDULE);
1947 	}
1948 
1949 }
1950 
1951 
1952 void
1953 XHCI::HandleTransferComplete(xhci_trb* trb)
1954 {
1955 	TRACE("HandleTransferComplete trb %p\n", trb);
1956 	addr_t source = trb->qwtrb0;
1957 	uint8 completionCode = TRB_2_COMP_CODE_GET(trb->dwtrb2);
1958 	uint32 remainder = TRB_2_REM_GET(trb->dwtrb2);
1959 	uint8 endpointNumber = TRB_3_ENDPOINT_GET(trb->dwtrb3);
1960 	uint8 slot = TRB_3_SLOT_GET(trb->dwtrb3);
1961 
1962 	if (slot > fSlotCount)
1963 		TRACE_ERROR("invalid slot\n");
1964 	if (endpointNumber == 0 || endpointNumber >= XHCI_MAX_ENDPOINTS)
1965 		TRACE_ERROR("invalid endpoint\n");
1966 
1967 	xhci_device *device = &fDevices[slot];
1968 	xhci_endpoint *endpoint = &device->endpoints[endpointNumber - 1];
1969 	xhci_td *td = endpoint->td_head;
1970 	for (; td != NULL; td = td->next) {
1971 		xhci_td *td_chain = td;
1972 		for (; td_chain != NULL; td_chain = td_chain->next_chain) {
1973 			int64 offset = source - td_chain->this_phy;
1974 			TRACE("HandleTransferComplete td %p offset %" B_PRId64 " %"
1975 				B_PRIx64 "\n", td_chain, offset, source);
1976 			offset = offset / sizeof(xhci_trb);
1977 			if (offset <= td_chain->trb_count && offset >= 0) {
1978 				TRACE("HandleTransferComplete td %p trb %" B_PRId64 " found "
1979 					"\n", td_chain, offset);
1980 				// is it the last trb?
1981 				if (offset == td_chain->trb_count) {
1982 					_UnlinkDescriptorForPipe(td, endpoint);
1983 					td->trb_completion_code = completionCode;
1984 					td->trb_left = remainder;
1985 					// add descriptor to finished list
1986 					Lock();
1987 					td->next = fFinishedHead;
1988 					fFinishedHead = td;
1989 					Unlock();
1990 					release_sem(fFinishTransfersSem);
1991 					TRACE("HandleTransferComplete td %p\n", td);
1992 				}
1993 				return;
1994 			}
1995 		}
1996 	}
1997 
1998 }
1999 
2000 
2001 status_t
2002 XHCI::DoCommand(xhci_trb* trb)
2003 {
2004 	if (!Lock())
2005 		return B_ERROR;
2006 
2007 	QueueCommand(trb);
2008 	Ring(0, 0);
2009 
2010 	if (acquire_sem(fCmdCompSem) < B_OK) {
2011 		Unlock();
2012 		return B_ERROR;
2013 	}
2014 	// eat up sems that have been released by multiple interrupts
2015 	int32 semCount = 0;
2016 	get_sem_count(fCmdCompSem, &semCount);
2017 	if (semCount > 0)
2018 		acquire_sem_etc(fCmdCompSem, semCount, B_RELATIVE_TIMEOUT, 0);
2019 
2020 	status_t status = B_OK;
2021 	TRACE("Command Complete\n");
2022 	if (TRB_2_COMP_CODE_GET(fCmdResult[0]) != COMP_SUCCESS) {
2023 		uint32 errorCode = TRB_2_COMP_CODE_GET(fCmdResult[0]);
2024 		TRACE_ERROR("unsuccessful command %s (%" B_PRId32 ")\n",
2025 			xhci_error_string(errorCode), errorCode);
2026 		status = B_IO_ERROR;
2027 	}
2028 
2029 	trb->dwtrb2 = fCmdResult[0];
2030 	trb->dwtrb3 = fCmdResult[1];
2031 	TRACE("Storing trb 0x%08" B_PRIx32 " 0x%08" B_PRIx32 "\n", trb->dwtrb2,
2032 		trb->dwtrb3);
2033 
2034 	Unlock();
2035 	return status;
2036 }
2037 
2038 
2039 status_t
2040 XHCI::Noop()
2041 {
2042 	TRACE("Noop\n");
2043 	xhci_trb trb;
2044 	trb.qwtrb0 = 0;
2045 	trb.dwtrb2 = 0;
2046 	trb.dwtrb3 = TRB_3_TYPE(TRB_TYPE_CMD_NOOP);
2047 
2048 	return DoCommand(&trb);
2049 }
2050 
2051 
2052 status_t
2053 XHCI::EnableSlot(uint8* slot)
2054 {
2055 	TRACE("Enable Slot\n");
2056 	xhci_trb trb;
2057 	trb.qwtrb0 = 0;
2058 	trb.dwtrb2 = 0;
2059 	trb.dwtrb3 = TRB_3_TYPE(TRB_TYPE_ENABLE_SLOT);
2060 
2061 	status_t status = DoCommand(&trb);
2062 	if (status != B_OK)
2063 		return status;
2064 
2065 	*slot = TRB_3_SLOT_GET(trb.dwtrb3);
2066 	return *slot != 0 ? B_OK : B_BAD_VALUE;
2067 }
2068 
2069 
2070 status_t
2071 XHCI::DisableSlot(uint8 slot)
2072 {
2073 	TRACE("Disable Slot\n");
2074 	xhci_trb trb;
2075 	trb.qwtrb0 = 0;
2076 	trb.dwtrb2 = 0;
2077 	trb.dwtrb3 = TRB_3_TYPE(TRB_TYPE_DISABLE_SLOT) | TRB_3_SLOT(slot);
2078 
2079 	return DoCommand(&trb);
2080 }
2081 
2082 
2083 status_t
2084 XHCI::SetAddress(uint64 inputContext, bool bsr, uint8 slot)
2085 {
2086 	TRACE("Set Address\n");
2087 	xhci_trb trb;
2088 	trb.qwtrb0 = inputContext;
2089 	trb.dwtrb2 = 0;
2090 	trb.dwtrb3 = TRB_3_TYPE(TRB_TYPE_ADDRESS_DEVICE) | TRB_3_SLOT(slot);
2091 
2092 	if (bsr)
2093 		trb.dwtrb3 |= TRB_3_BSR_BIT;
2094 
2095 	return DoCommand(&trb);
2096 }
2097 
2098 
2099 status_t
2100 XHCI::ConfigureEndpoint(uint64 inputContext, bool deconfigure, uint8 slot)
2101 {
2102 	TRACE("Configure Endpoint\n");
2103 	xhci_trb trb;
2104 	trb.qwtrb0 = inputContext;
2105 	trb.dwtrb2 = 0;
2106 	trb.dwtrb3 = TRB_3_TYPE(TRB_TYPE_CONFIGURE_ENDPOINT) | TRB_3_SLOT(slot);
2107 
2108 	if (deconfigure)
2109 		trb.dwtrb3 |= TRB_3_DCEP_BIT;
2110 
2111 	return DoCommand(&trb);
2112 }
2113 
2114 
2115 status_t
2116 XHCI::EvaluateContext(uint64 inputContext, uint8 slot)
2117 {
2118 	TRACE("Evaluate Context\n");
2119 	xhci_trb trb;
2120 	trb.qwtrb0 = inputContext;
2121 	trb.dwtrb2 = 0;
2122 	trb.dwtrb3 = TRB_3_TYPE(TRB_TYPE_EVALUATE_CONTEXT) | TRB_3_SLOT(slot);
2123 
2124 	return DoCommand(&trb);
2125 }
2126 
2127 
2128 status_t
2129 XHCI::ResetEndpoint(bool preserve, uint8 endpoint, uint8 slot)
2130 {
2131 	TRACE("Reset Endpoint\n");
2132 	xhci_trb trb;
2133 	trb.qwtrb0 = 0;
2134 	trb.dwtrb2 = 0;
2135 	trb.dwtrb3 = TRB_3_TYPE(TRB_TYPE_RESET_ENDPOINT) | TRB_3_SLOT(slot)
2136 		| TRB_3_ENDPOINT(endpoint);
2137 	if (preserve)
2138 		trb.dwtrb3 |= TRB_3_PRSV_BIT;
2139 
2140 	return DoCommand(&trb);
2141 }
2142 
2143 
2144 status_t
2145 XHCI::StopEndpoint(bool suspend, uint8 endpoint, uint8 slot)
2146 {
2147 	TRACE("Stop Endpoint\n");
2148 	xhci_trb trb;
2149 	trb.qwtrb0 = 0;
2150 	trb.dwtrb2 = 0;
2151 	trb.dwtrb3 = TRB_3_TYPE(TRB_TYPE_STOP_ENDPOINT) | TRB_3_SLOT(slot)
2152 		| TRB_3_ENDPOINT(endpoint);
2153 	if (suspend)
2154 		trb.dwtrb3 |= TRB_3_SUSPEND_ENDPOINT_BIT;
2155 
2156 	return DoCommand(&trb);
2157 }
2158 
2159 
2160 status_t
2161 XHCI::SetTRDequeue(uint64 dequeue, uint16 stream, uint8 endpoint, uint8 slot)
2162 {
2163 	TRACE("Set TR Dequeue\n");
2164 	xhci_trb trb;
2165 	trb.qwtrb0 = dequeue;
2166 	trb.dwtrb2 = TRB_2_STREAM(stream);
2167 	trb.dwtrb3 = TRB_3_TYPE(TRB_TYPE_SET_TR_DEQUEUE) | TRB_3_SLOT(slot)
2168 		| TRB_3_ENDPOINT(endpoint);
2169 
2170 	return DoCommand(&trb);
2171 }
2172 
2173 
2174 status_t
2175 XHCI::ResetDevice(uint8 slot)
2176 {
2177 	TRACE("Reset Device\n");
2178 	xhci_trb trb;
2179 	trb.qwtrb0 = 0;
2180 	trb.dwtrb2 = 0;
2181 	trb.dwtrb3 = TRB_3_TYPE(TRB_TYPE_RESET_DEVICE) | TRB_3_SLOT(slot);
2182 
2183 	return DoCommand(&trb);
2184 }
2185 
2186 
2187 int32
2188 XHCI::EventThread(void* data)
2189 {
2190 	((XHCI *)data)->CompleteEvents();
2191 	return B_OK;
2192 }
2193 
2194 
2195 void
2196 XHCI::CompleteEvents()
2197 {
2198 	while (!fStopThreads) {
2199 		if (acquire_sem(fEventSem) < B_OK)
2200 			continue;
2201 
2202 		// eat up sems that have been released by multiple interrupts
2203 		int32 semCount = 0;
2204 		get_sem_count(fEventSem, &semCount);
2205 		if (semCount > 0)
2206 			acquire_sem_etc(fEventSem, semCount, B_RELATIVE_TIMEOUT, 0);
2207 
2208 		uint16 i = fEventIdx;
2209 		uint8 j = fEventCcs;
2210 		uint8 t = 2;
2211 
2212 		while (1) {
2213 			uint32 temp = fEventRing[i].dwtrb3;
2214 			TRACE("event[%u] = %u (0x%016" B_PRIx64 " 0x%08" B_PRIx32 " 0x%08"
2215 				B_PRIx32 ")\n", i, (uint8)TRB_3_TYPE_GET(temp), fEventRing[i].qwtrb0,
2216 				fEventRing[i].dwtrb2, fEventRing[i].dwtrb3);
2217 			uint8 k = (temp & TRB_3_CYCLE_BIT) ? 1 : 0;
2218 			if (j != k)
2219 				break;
2220 
2221 			uint8 event = TRB_3_TYPE_GET(temp);
2222 
2223 			TRACE("event[%u] = %u (0x%016" B_PRIx64 " 0x%08" B_PRIx32 " 0x%08"
2224 				B_PRIx32 ")\n", i, event, fEventRing[i].qwtrb0,
2225 				fEventRing[i].dwtrb2, fEventRing[i].dwtrb3);
2226 			switch (event) {
2227 			case TRB_TYPE_COMMAND_COMPLETION:
2228 				HandleCmdComplete(&fEventRing[i]);
2229 				break;
2230 			case TRB_TYPE_TRANSFER:
2231 				HandleTransferComplete(&fEventRing[i]);
2232 				break;
2233 			case TRB_TYPE_PORT_STATUS_CHANGE:
2234 				TRACE("port change detected\n");
2235 				break;
2236 			default:
2237 				TRACE_ERROR("Unhandled event = %u\n", event);
2238 				break;
2239 			}
2240 
2241 			i++;
2242 			if (i == XHCI_MAX_EVENTS) {
2243 				i = 0;
2244 				j ^= 1;
2245 				if (!--t)
2246 					break;
2247 			}
2248 		}
2249 
2250 		fEventIdx = i;
2251 		fEventCcs = j;
2252 
2253 		uint64 addr = fErst->rs_addr + i * sizeof(xhci_trb);
2254 		addr |= ERST_EHB;
2255 		WriteRunReg32(XHCI_ERDP_LO(0), (uint32)addr);
2256 		WriteRunReg32(XHCI_ERDP_HI(0), (uint32)(addr >> 32));
2257 	}
2258 }
2259 
2260 
2261 int32
2262 XHCI::FinishThread(void* data)
2263 {
2264 	((XHCI *)data)->FinishTransfers();
2265 	return B_OK;
2266 }
2267 
2268 
2269 void
2270 XHCI::FinishTransfers()
2271 {
2272 	while (!fStopThreads) {
2273 		if (acquire_sem(fFinishTransfersSem) < B_OK)
2274 			continue;
2275 
2276 		// eat up sems that have been released by multiple interrupts
2277 		int32 semCount = 0;
2278 		get_sem_count(fFinishTransfersSem, &semCount);
2279 		if (semCount > 0)
2280 			acquire_sem_etc(fFinishTransfersSem, semCount, B_RELATIVE_TIMEOUT, 0);
2281 
2282 		Lock();
2283 		TRACE("finishing transfers\n");
2284 		while (fFinishedHead != NULL) {
2285 			xhci_td* td = fFinishedHead;
2286 			fFinishedHead = td->next;
2287 			td->next = NULL;
2288 			Unlock();
2289 
2290 			TRACE("finishing transfer td %p\n", td);
2291 
2292 			Transfer* transfer = td->transfer;
2293 			bool directionIn = (transfer->TransferPipe()->Direction() != Pipe::Out);
2294 			usb_request_data *requestData = transfer->RequestData();
2295 
2296 			status_t callbackStatus = B_OK;
2297 			switch (td->trb_completion_code) {
2298 				case COMP_SHORT_PACKET:
2299 				case COMP_SUCCESS:
2300 					callbackStatus = B_OK;
2301 					break;
2302 				case COMP_DATA_BUFFER:
2303 					callbackStatus = directionIn ? B_DEV_DATA_OVERRUN
2304 						: B_DEV_DATA_UNDERRUN;
2305 					break;
2306 				case COMP_BABBLE:
2307 					callbackStatus = directionIn ? B_DEV_FIFO_OVERRUN
2308 						: B_DEV_FIFO_UNDERRUN;
2309 					break;
2310 				case COMP_USB_TRANSACTION:
2311 					callbackStatus = B_DEV_CRC_ERROR;
2312 					break;
2313 				case COMP_STALL:
2314 					callbackStatus = B_DEV_STALLED;
2315 					break;
2316 				default:
2317 					callbackStatus = B_DEV_STALLED;
2318 					break;
2319 			}
2320 
2321 			size_t actualLength = 0;
2322 			if (callbackStatus == B_OK) {
2323 				actualLength = requestData ? requestData->Length
2324 					: transfer->DataLength();
2325 
2326 				if (td->trb_completion_code == COMP_SHORT_PACKET)
2327 					actualLength -= td->trb_left;
2328 
2329 				if (directionIn && actualLength > 0) {
2330 					if (requestData) {
2331 						TRACE("copying in data %d bytes\n", requestData->Length);
2332 						transfer->PrepareKernelAccess();
2333 						memcpy((uint8 *)transfer->Vector()[0].iov_base,
2334 							td->buffer_log[0], requestData->Length);
2335 					} else {
2336 						TRACE("copying in iov count %ld\n", transfer->VectorCount());
2337 						transfer->PrepareKernelAccess();
2338 						ReadDescriptorChain(td, transfer->Vector(),
2339 							transfer->VectorCount());
2340 					}
2341 				}
2342 			}
2343 			transfer->Finished(callbackStatus, actualLength);
2344 			delete transfer;
2345 			FreeDescriptor(td);
2346 			Lock();
2347 		}
2348 		Unlock();
2349 
2350 	}
2351 }
2352 
2353 
2354 inline void
2355 XHCI::WriteOpReg(uint32 reg, uint32 value)
2356 {
2357 	*(volatile uint32 *)(fOperationalRegisters + reg) = value;
2358 }
2359 
2360 
2361 inline uint32
2362 XHCI::ReadOpReg(uint32 reg)
2363 {
2364 	return *(volatile uint32 *)(fOperationalRegisters + reg);
2365 }
2366 
2367 
2368 inline uint32
2369 XHCI::ReadCapReg32(uint32 reg)
2370 {
2371 	return *(volatile uint32 *)(fCapabilityRegisters + reg);
2372 }
2373 
2374 
2375 inline void
2376 XHCI::WriteCapReg32(uint32 reg, uint32 value)
2377 {
2378 	*(volatile uint32 *)(fCapabilityRegisters + reg) = value;
2379 }
2380 
2381 
2382 inline uint32
2383 XHCI::ReadRunReg32(uint32 reg)
2384 {
2385 	return *(volatile uint32 *)(fRuntimeRegisters + reg);
2386 }
2387 
2388 
2389 inline void
2390 XHCI::WriteRunReg32(uint32 reg, uint32 value)
2391 {
2392 	*(volatile uint32 *)(fRuntimeRegisters + reg) = value;
2393 }
2394 
2395 
2396 inline uint32
2397 XHCI::ReadDoorReg32(uint32 reg)
2398 {
2399 	return *(volatile uint32 *)(fDoorbellRegisters + reg);
2400 }
2401 
2402 
2403 inline void
2404 XHCI::WriteDoorReg32(uint32 reg, uint32 value)
2405 {
2406 	*(volatile uint32 *)(fDoorbellRegisters + reg) = value;
2407 }
2408