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