xref: /haiku/src/add-ons/kernel/busses/usb/xhci.cpp (revision 445d4fd926c569e7b9ae28017da86280aaecbae2)
1 /*
2  * Copyright 2011-2021, Haiku, Inc. All rights reserved.
3  * Distributed under the terms of the MIT License.
4  *
5  * Authors:
6  *		Augustin Cavalier <waddlesplash>
7  *		Jian Chiang <j.jian.chiang@gmail.com>
8  *		Jérôme Duval <jerome.duval@gmail.com>
9  *		Akshay Jaggi <akshay1994.leo@gmail.com>
10  *		Michael Lotz <mmlr@mlotz.ch>
11  *		Alexander von Gluck <kallisti5@unixzen.com>
12  */
13 
14 
15 #include <stdio.h>
16 
17 #include <bus/PCI.h>
18 #include <USB3.h>
19 #include <KernelExport.h>
20 
21 #include <ByteOrder.h>
22 #include <util/AutoLock.h>
23 
24 #include "xhci.h"
25 
26 
27 #define CALLED(x...)	TRACE_MODULE("CALLED %s\n", __PRETTY_FUNCTION__)
28 
29 
30 #define USB_MODULE_NAME	"xhci"
31 
32 device_manager_info* gDeviceManager;
33 static usb_for_controller_interface* gUSB;
34 
35 
36 #define XHCI_PCI_DEVICE_MODULE_NAME "busses/usb/xhci/pci/driver_v1"
37 #define XHCI_PCI_USB_BUS_MODULE_NAME "busses/usb/xhci/device_v1"
38 
39 
40 typedef struct {
41 	XHCI* xhci;
42 	pci_device_module_info* pci;
43 	pci_device* device;
44 
45 	pci_info pciinfo;
46 
47 	device_node* node;
48 	device_node* driver_node;
49 } xhci_pci_sim_info;
50 
51 
52 //	#pragma mark -
53 
54 
55 static status_t
56 init_bus(device_node* node, void** bus_cookie)
57 {
58 	CALLED();
59 
60 	driver_module_info* driver;
61 	xhci_pci_sim_info* bus;
62 	device_node* parent = gDeviceManager->get_parent_node(node);
63 	gDeviceManager->get_driver(parent, &driver, (void**)&bus);
64 	gDeviceManager->put_node(parent);
65 
66 	Stack *stack;
67 	if (gUSB->get_stack((void**)&stack) != B_OK)
68 		return B_ERROR;
69 
70 	XHCI *xhci = new(std::nothrow) XHCI(&bus->pciinfo, bus->pci, bus->device, stack, node);
71 	if (xhci == NULL) {
72 		return B_NO_MEMORY;
73 	}
74 
75 	if (xhci->InitCheck() < B_OK) {
76 		TRACE_MODULE_ERROR("bus failed init check\n");
77 		delete xhci;
78 		return B_ERROR;
79 	}
80 
81 	if (xhci->Start() != B_OK) {
82 		delete xhci;
83 		return B_ERROR;
84 	}
85 
86 	*bus_cookie = xhci;
87 
88 	return B_OK;
89 }
90 
91 
92 static void
93 uninit_bus(void* bus_cookie)
94 {
95 	CALLED();
96 	XHCI* xhci = (XHCI*)bus_cookie;
97 	delete xhci;
98 }
99 
100 
101 static status_t
102 register_child_devices(void* cookie)
103 {
104 	CALLED();
105 	xhci_pci_sim_info* bus = (xhci_pci_sim_info*)cookie;
106 	device_node* node = bus->driver_node;
107 
108 	char prettyName[25];
109 	sprintf(prettyName, "XHCI Controller %" B_PRIu16, 0);
110 
111 	device_attr attrs[] = {
112 		// properties of this controller for the usb bus manager
113 		{ B_DEVICE_PRETTY_NAME, B_STRING_TYPE,
114 			{ .string = prettyName }},
115 		{ B_DEVICE_FIXED_CHILD, B_STRING_TYPE,
116 			{ .string = USB_FOR_CONTROLLER_MODULE_NAME }},
117 
118 		// private data to identify the device
119 		{ NULL }
120 	};
121 
122 	return gDeviceManager->register_node(node, XHCI_PCI_USB_BUS_MODULE_NAME,
123 		attrs, NULL, NULL);
124 }
125 
126 
127 static status_t
128 init_device(device_node* node, void** device_cookie)
129 {
130 	CALLED();
131 	xhci_pci_sim_info* bus = (xhci_pci_sim_info*)calloc(1,
132 		sizeof(xhci_pci_sim_info));
133 	if (bus == NULL)
134 		return B_NO_MEMORY;
135 
136 	pci_device_module_info* pci;
137 	pci_device* device;
138 	{
139 		device_node* pciParent = gDeviceManager->get_parent_node(node);
140 		gDeviceManager->get_driver(pciParent, (driver_module_info**)&pci,
141 			(void**)&device);
142 		gDeviceManager->put_node(pciParent);
143 	}
144 
145 	bus->pci = pci;
146 	bus->device = device;
147 	bus->driver_node = node;
148 
149 	pci_info *pciInfo = &bus->pciinfo;
150 	pci->get_pci_info(device, pciInfo);
151 
152 	*device_cookie = bus;
153 	return B_OK;
154 }
155 
156 
157 static void
158 uninit_device(void* device_cookie)
159 {
160 	CALLED();
161 	xhci_pci_sim_info* bus = (xhci_pci_sim_info*)device_cookie;
162 	free(bus);
163 }
164 
165 
166 static status_t
167 register_device(device_node* parent)
168 {
169 	CALLED();
170 	device_attr attrs[] = {
171 		{B_DEVICE_PRETTY_NAME, B_STRING_TYPE, {.string = "XHCI PCI"}},
172 		{}
173 	};
174 
175 	return gDeviceManager->register_node(parent,
176 		XHCI_PCI_DEVICE_MODULE_NAME, attrs, NULL, NULL);
177 }
178 
179 
180 static float
181 supports_device(device_node* parent)
182 {
183 	CALLED();
184 	const char* bus;
185 	uint16 type, subType, api;
186 
187 	// make sure parent is a XHCI PCI device node
188 	if (gDeviceManager->get_attr_string(parent, B_DEVICE_BUS, &bus, false)
189 		< B_OK) {
190 		return -1;
191 	}
192 
193 	if (strcmp(bus, "pci") != 0)
194 		return 0.0f;
195 
196 	if (gDeviceManager->get_attr_uint16(parent, B_DEVICE_SUB_TYPE, &subType,
197 			false) < B_OK
198 		|| gDeviceManager->get_attr_uint16(parent, B_DEVICE_TYPE, &type,
199 			false) < B_OK
200 		|| gDeviceManager->get_attr_uint16(parent, B_DEVICE_INTERFACE, &api,
201 			false) < B_OK) {
202 		TRACE_MODULE("Could not find type/subtype/interface attributes\n");
203 		return -1;
204 	}
205 
206 	if (type == PCI_serial_bus && subType == PCI_usb && api == PCI_usb_xhci) {
207 		pci_device_module_info* pci;
208 		pci_device* device;
209 		gDeviceManager->get_driver(parent, (driver_module_info**)&pci,
210 			(void**)&device);
211 		TRACE_MODULE("XHCI Device found!\n");
212 
213 		return 0.8f;
214 	}
215 
216 	return 0.0f;
217 }
218 
219 
220 static const char*
221 xhci_error_string(uint32 error)
222 {
223 	switch (error) {
224 		case COMP_INVALID: return "Invalid";
225 		case COMP_SUCCESS: return "Success";
226 		case COMP_DATA_BUFFER: return "Data buffer";
227 		case COMP_BABBLE: return "Babble detected";
228 		case COMP_USB_TRANSACTION: return "USB transaction";
229 		case COMP_TRB: return "TRB";
230 		case COMP_STALL: return "Stall";
231 		case COMP_RESOURCE: return "Resource";
232 		case COMP_BANDWIDTH: return "Bandwidth";
233 		case COMP_NO_SLOTS: return "No slots";
234 		case COMP_INVALID_STREAM: return "Invalid stream";
235 		case COMP_SLOT_NOT_ENABLED: return "Slot not enabled";
236 		case COMP_ENDPOINT_NOT_ENABLED: return "Endpoint not enabled";
237 		case COMP_SHORT_PACKET: return "Short packet";
238 		case COMP_RING_UNDERRUN: return "Ring underrun";
239 		case COMP_RING_OVERRUN: return "Ring overrun";
240 		case COMP_VF_RING_FULL: return "VF Event Ring Full";
241 		case COMP_PARAMETER: return "Parameter";
242 		case COMP_BANDWIDTH_OVERRUN: return "Bandwidth overrun";
243 		case COMP_CONTEXT_STATE: return "Context state";
244 		case COMP_NO_PING_RESPONSE: return "No ping response";
245 		case COMP_EVENT_RING_FULL: return "Event ring full";
246 		case COMP_INCOMPATIBLE_DEVICE: return "Incompatible device";
247 		case COMP_MISSED_SERVICE: return "Missed service";
248 		case COMP_COMMAND_RING_STOPPED: return "Command ring stopped";
249 		case COMP_COMMAND_ABORTED: return "Command aborted";
250 		case COMP_STOPPED: return "Stopped";
251 		case COMP_LENGTH_INVALID: return "Length invalid";
252 		case COMP_MAX_EXIT_LATENCY: return "Max exit latency too large";
253 		case COMP_ISOC_OVERRUN: return "Isoch buffer overrun";
254 		case COMP_EVENT_LOST: return "Event lost";
255 		case COMP_UNDEFINED: return "Undefined";
256 		case COMP_INVALID_STREAM_ID: return "Invalid stream ID";
257 		case COMP_SECONDARY_BANDWIDTH: return "Secondary bandwidth";
258 		case COMP_SPLIT_TRANSACTION: return "Split transaction";
259 
260 		default: return "Undefined";
261 	}
262 }
263 
264 
265 module_dependency module_dependencies[] = {
266 	{ USB_FOR_CONTROLLER_MODULE_NAME, (module_info**)&gUSB },
267 	{ B_DEVICE_MANAGER_MODULE_NAME, (module_info**)&gDeviceManager },
268 	{}
269 };
270 
271 
272 static usb_bus_interface gXHCIPCIDeviceModule = {
273 	{
274 		{
275 			XHCI_PCI_USB_BUS_MODULE_NAME,
276 			0,
277 			NULL
278 		},
279 		NULL,  // supports device
280 		NULL,  // register device
281 		init_bus,
282 		uninit_bus,
283 		NULL,  // register child devices
284 		NULL,  // rescan
285 		NULL,  // device removed
286 	},
287 };
288 
289 // Root device that binds to the PCI bus. It will register an usb_bus_interface
290 // node for each device.
291 static driver_module_info sXHCIDevice = {
292 	{
293 		XHCI_PCI_DEVICE_MODULE_NAME,
294 		0,
295 		NULL
296 	},
297 	supports_device,
298 	register_device,
299 	init_device,
300 	uninit_device,
301 	register_child_devices,
302 	NULL, // rescan
303 	NULL, // device removed
304 };
305 
306 module_info* modules[] = {
307 	(module_info* )&sXHCIDevice,
308 	(module_info* )&gXHCIPCIDeviceModule,
309 	NULL
310 };
311 
312 
313 XHCI::XHCI(pci_info *info, 	pci_device_module_info* pci, pci_device* device, Stack *stack,
314 	device_node* node)
315 	:	BusManager(stack, node),
316 		fRegisterArea(-1),
317 		fRegisters(NULL),
318 		fPCIInfo(info),
319 		fPci(pci),
320 		fDevice(device),
321 		fStack(stack),
322 		fIRQ(0),
323 		fUseMSI(false),
324 		fErstArea(-1),
325 		fDcbaArea(-1),
326 		fCmdCompSem(-1),
327 		fStopThreads(false),
328 		fRootHub(NULL),
329 		fPortCount(0),
330 		fSlotCount(0),
331 		fScratchpadCount(0),
332 		fContextSizeShift(0),
333 		fFinishedHead(NULL),
334 		fFinishTransfersSem(-1),
335 		fFinishThread(-1),
336 		fEventSem(-1),
337 		fEventThread(-1),
338 		fEventIdx(0),
339 		fCmdIdx(0),
340 		fEventCcs(1),
341 		fCmdCcs(1)
342 {
343 	B_INITIALIZE_SPINLOCK(&fSpinlock);
344 	mutex_init(&fFinishedLock, "XHCI finished transfers");
345 	mutex_init(&fEventLock, "XHCI event handler");
346 
347 	if (BusManager::InitCheck() < B_OK) {
348 		TRACE_ERROR("bus manager failed to init\n");
349 		return;
350 	}
351 
352 	TRACE("constructing new XHCI host controller driver\n");
353 	fInitOK = false;
354 
355 	// enable busmaster and memory mapped access
356 	uint16 command = fPci->read_pci_config(fDevice, PCI_command, 2);
357 	command &= ~(PCI_command_io | PCI_command_int_disable);
358 	command |= PCI_command_master | PCI_command_memory;
359 
360 	fPci->write_pci_config(fDevice, PCI_command, 2, command);
361 
362 	// map the registers (low + high for 64-bit when requested)
363 	phys_addr_t physicalAddress = fPCIInfo->u.h0.base_registers[0];
364 	if ((fPCIInfo->u.h0.base_register_flags[0] & PCI_address_type)
365 			== PCI_address_type_64) {
366 		physicalAddress |= (uint64)fPCIInfo->u.h0.base_registers[1] << 32;
367 	}
368 
369 	size_t mapSize = fPCIInfo->u.h0.base_register_sizes[0];
370 
371 	TRACE("map registers %08" B_PRIxPHYSADDR ", size: %" B_PRIuSIZE "\n",
372 		physicalAddress, mapSize);
373 
374 	fRegisterArea = map_physical_memory("XHCI memory mapped registers",
375 		physicalAddress, mapSize, B_ANY_KERNEL_BLOCK_ADDRESS,
376 		B_KERNEL_READ_AREA | B_KERNEL_WRITE_AREA,
377 		(void **)&fRegisters);
378 	if (fRegisterArea < B_OK) {
379 		TRACE_ERROR("failed to map register memory\n");
380 		return;
381 	}
382 
383 	// determine the register offsets
384 	fCapabilityRegisterOffset = 0;
385 	fOperationalRegisterOffset = HCI_CAPLENGTH(ReadCapReg32(XHCI_HCI_CAPLENGTH));
386 	fRuntimeRegisterOffset = ReadCapReg32(XHCI_RTSOFF) & ~0x1F;
387 	fDoorbellRegisterOffset = ReadCapReg32(XHCI_DBOFF) & ~0x3;
388 
389 	TRACE("mapped registers: %p\n", fRegisters);
390 	TRACE("operational register offset: %" B_PRId32 "\n", fOperationalRegisterOffset);
391 	TRACE("runtime register offset: %" B_PRId32 "\n", fRuntimeRegisterOffset);
392 	TRACE("doorbell register offset: %" B_PRId32 "\n", fDoorbellRegisterOffset);
393 
394 	int32 interfaceVersion = HCI_VERSION(ReadCapReg32(XHCI_HCI_VERSION));
395 	if (interfaceVersion < 0x0090 || interfaceVersion > 0x0120) {
396 		TRACE_ERROR("unsupported interface version: 0x%04" B_PRIx32 "\n",
397 			interfaceVersion);
398 		return;
399 	}
400 	TRACE_ALWAYS("interface version: 0x%04" B_PRIx32 "\n", interfaceVersion);
401 
402 	TRACE_ALWAYS("structural parameters: 1:0x%08" B_PRIx32 " 2:0x%08"
403 		B_PRIx32 " 3:0x%08" B_PRIx32 "\n", ReadCapReg32(XHCI_HCSPARAMS1),
404 		ReadCapReg32(XHCI_HCSPARAMS2), ReadCapReg32(XHCI_HCSPARAMS3));
405 
406 	uint32 cparams = ReadCapReg32(XHCI_HCCPARAMS);
407 	if (cparams == 0xffffffff)
408 		return;
409 	TRACE_ALWAYS("capability parameters: 0x%08" B_PRIx32 "\n", cparams);
410 
411 	// if 64 bytes context structures, then 1
412 	fContextSizeShift = HCC_CSZ(cparams);
413 
414 	// Assume ownership of the controller from the BIOS.
415 	uint32 eec = 0xffffffff;
416 	uint32 eecp = HCS0_XECP(cparams) << 2;
417 	for (; eecp != 0 && XECP_NEXT(eec); eecp += XECP_NEXT(eec) << 2) {
418 		TRACE("eecp register: 0x%08" B_PRIx32 "\n", eecp);
419 
420 		eec = ReadCapReg32(eecp);
421 		if (XECP_ID(eec) != XHCI_LEGSUP_CAPID)
422 			continue;
423 
424 		if (eec & XHCI_LEGSUP_BIOSOWNED) {
425 			TRACE_ALWAYS("the host controller is bios owned, claiming"
426 				" ownership\n");
427 			WriteCapReg32(eecp, eec | XHCI_LEGSUP_OSOWNED);
428 
429 			for (int32 i = 0; i < 20; i++) {
430 				eec = ReadCapReg32(eecp);
431 
432 				if ((eec & XHCI_LEGSUP_BIOSOWNED) == 0)
433 					break;
434 
435 				TRACE_ALWAYS("controller is still bios owned, waiting\n");
436 				snooze(50000);
437 			}
438 
439 			if (eec & XHCI_LEGSUP_BIOSOWNED) {
440 				TRACE_ERROR("bios won't give up control over the host "
441 					"controller (ignoring)\n");
442 			} else if (eec & XHCI_LEGSUP_OSOWNED) {
443 				TRACE_ALWAYS("successfully took ownership of the host "
444 					"controller\n");
445 			}
446 
447 			// Force off the BIOS owned flag, and clear all SMIs. Some BIOSes
448 			// do indicate a successful handover but do not remove their SMIs
449 			// and then freeze the system when interrupts are generated.
450 			WriteCapReg32(eecp, eec & ~XHCI_LEGSUP_BIOSOWNED);
451 		}
452 		break;
453 	}
454 	uint32 legctlsts = ReadCapReg32(eecp + XHCI_LEGCTLSTS);
455 	legctlsts &= XHCI_LEGCTLSTS_DISABLE_SMI;
456 	legctlsts |= XHCI_LEGCTLSTS_EVENTS_SMI;
457 	WriteCapReg32(eecp + XHCI_LEGCTLSTS, legctlsts);
458 
459 	// We need to explicitly take ownership of EHCI ports on earlier Intel chipsets.
460 	if (fPCIInfo->vendor_id == PCI_VENDOR_INTEL) {
461 		switch (fPCIInfo->device_id) {
462 			case PCI_DEVICE_INTEL_PANTHER_POINT_XHCI:
463 			case PCI_DEVICE_INTEL_LYNX_POINT_XHCI:
464 			case PCI_DEVICE_INTEL_LYNX_POINT_LP_XHCI:
465 			case PCI_DEVICE_INTEL_BAYTRAIL_XHCI:
466 			case PCI_DEVICE_INTEL_WILDCAT_POINT_XHCI:
467 			case PCI_DEVICE_INTEL_WILDCAT_POINT_LP_XHCI:
468 				_SwitchIntelPorts();
469 				break;
470 		}
471 	}
472 
473 	// halt the host controller
474 	if (ControllerHalt() < B_OK) {
475 		return;
476 	}
477 
478 	// reset the host controller
479 	if (ControllerReset() < B_OK) {
480 		TRACE_ERROR("host controller failed to reset\n");
481 		return;
482 	}
483 
484 	fCmdCompSem = create_sem(0, "XHCI Command Complete");
485 	fFinishTransfersSem = create_sem(0, "XHCI Finish Transfers");
486 	fEventSem = create_sem(0, "XHCI Event");
487 	if (fFinishTransfersSem < B_OK || fCmdCompSem < B_OK || fEventSem < B_OK) {
488 		TRACE_ERROR("failed to create semaphores\n");
489 		return;
490 	}
491 
492 	// create event handler thread
493 	fEventThread = spawn_kernel_thread(EventThread, "xhci event thread",
494 		B_URGENT_PRIORITY, (void *)this);
495 	resume_thread(fEventThread);
496 
497 	// create finisher service thread
498 	fFinishThread = spawn_kernel_thread(FinishThread, "xhci finish thread",
499 		B_URGENT_PRIORITY - 1, (void *)this);
500 	resume_thread(fFinishThread);
501 
502 	// Find the right interrupt vector, using MSIs if available.
503 	fIRQ = fPCIInfo->u.h0.interrupt_line;
504 #if 0
505 	if (fPci->get_msix_count(fDevice) >= 1) {
506 		uint8 msiVector = 0;
507 		if (fPci->configure_msix(fDevice, 1, &msiVector) == B_OK
508 			&& fPci->enable_msix(fDevice) == B_OK) {
509 			TRACE_ALWAYS("using MSI-X\n");
510 			fIRQ = msiVector;
511 			fUseMSI = true;
512 		}
513 	} else
514 #endif
515 	if (fPci->get_msi_count(fDevice) >= 1) {
516 		uint8 msiVector = 0;
517 		if (fPci->configure_msi(fDevice, 1, &msiVector) == B_OK
518 			&& fPci->enable_msi(fDevice) == B_OK) {
519 			TRACE_ALWAYS("using message signaled interrupts\n");
520 			fIRQ = msiVector;
521 			fUseMSI = true;
522 		}
523 	}
524 
525 	if (fIRQ == 0 || fIRQ == 0xFF) {
526 		TRACE_MODULE_ERROR("device PCI:%d:%d:%d was assigned an invalid IRQ\n",
527 			fPCIInfo->bus, fPCIInfo->device, fPCIInfo->function);
528 		return;
529 	}
530 
531 	// Install the interrupt handler
532 	TRACE("installing interrupt handler\n");
533 	install_io_interrupt_handler(fIRQ, InterruptHandler, (void *)this, 0);
534 
535 	memset(fPortSpeeds, 0, sizeof(fPortSpeeds));
536 	memset(fDevices, 0, sizeof(fDevices));
537 
538 	fInitOK = true;
539 	TRACE("driver construction successful\n");
540 }
541 
542 
543 XHCI::~XHCI()
544 {
545 	TRACE("tear down XHCI host controller driver\n");
546 
547 	WriteOpReg(XHCI_CMD, 0);
548 
549 	int32 result = 0;
550 	fStopThreads = true;
551 	delete_sem(fCmdCompSem);
552 	delete_sem(fFinishTransfersSem);
553 	delete_sem(fEventSem);
554 	wait_for_thread(fFinishThread, &result);
555 	wait_for_thread(fEventThread, &result);
556 
557 	mutex_destroy(&fFinishedLock);
558 	mutex_destroy(&fEventLock);
559 
560 	remove_io_interrupt_handler(fIRQ, InterruptHandler, (void *)this);
561 
562 	delete_area(fRegisterArea);
563 	delete_area(fErstArea);
564 	for (uint32 i = 0; i < fScratchpadCount; i++)
565 		delete_area(fScratchpadArea[i]);
566 	delete_area(fDcbaArea);
567 
568 	if (fUseMSI) {
569 		fPci->disable_msi(fDevice);
570 		fPci->unconfigure_msi(fDevice);
571 	}
572 }
573 
574 
575 void
576 XHCI::_SwitchIntelPorts()
577 {
578 	TRACE("Looking for EHCI owned ports\n");
579 	uint32 ports = fPci->read_pci_config(fDevice, XHCI_INTEL_USB3PRM, 4);
580 	TRACE("Superspeed Ports: 0x%" B_PRIx32 "\n", ports);
581 	fPci->write_pci_config(fDevice, XHCI_INTEL_USB3_PSSEN, 4, ports);
582 	ports = fPci->read_pci_config(fDevice, XHCI_INTEL_USB3_PSSEN, 4);
583 	TRACE("Superspeed ports now under XHCI : 0x%" B_PRIx32 "\n", ports);
584 	ports = fPci->read_pci_config(fDevice, XHCI_INTEL_USB2PRM, 4);
585 	TRACE("USB 2.0 Ports : 0x%" B_PRIx32 "\n", ports);
586 	fPci->write_pci_config(fDevice, XHCI_INTEL_XUSB2PR, 4, ports);
587 	ports = fPci->read_pci_config(fDevice, XHCI_INTEL_XUSB2PR, 4);
588 	TRACE("USB 2.0 ports now under XHCI: 0x%" B_PRIx32 "\n", ports);
589 }
590 
591 
592 status_t
593 XHCI::Start()
594 {
595 	TRACE_ALWAYS("starting XHCI host controller\n");
596 	TRACE("usbcmd: 0x%08" B_PRIx32 "; usbsts: 0x%08" B_PRIx32 "\n",
597 		ReadOpReg(XHCI_CMD), ReadOpReg(XHCI_STS));
598 
599 	if (WaitOpBits(XHCI_STS, STS_CNR, 0) != B_OK) {
600 		TRACE("Start() failed STS_CNR\n");
601 	}
602 
603 	if ((ReadOpReg(XHCI_CMD) & CMD_RUN) != 0) {
604 		TRACE_ERROR("Start() warning, starting running XHCI controller!\n");
605 	}
606 
607 	if ((ReadOpReg(XHCI_PAGESIZE) & (1 << 0)) == 0) {
608 		TRACE_ERROR("controller does not support 4K page size\n");
609 		return B_ERROR;
610 	}
611 
612 	// read port count from capability register
613 	uint32 capabilities = ReadCapReg32(XHCI_HCSPARAMS1);
614 	fPortCount = HCS_MAX_PORTS(capabilities);
615 	if (fPortCount == 0) {
616 		TRACE_ERROR("invalid number of ports: %u\n", fPortCount);
617 		return B_ERROR;
618 	}
619 
620 	fSlotCount = HCS_MAX_SLOTS(capabilities);
621 	if (fSlotCount > XHCI_MAX_DEVICES)
622 		fSlotCount = XHCI_MAX_DEVICES;
623 	WriteOpReg(XHCI_CONFIG, fSlotCount);
624 
625 	// find out which protocol is used for each port
626 	uint8 portFound = 0;
627 	uint32 cparams = ReadCapReg32(XHCI_HCCPARAMS);
628 	uint32 eec = 0xffffffff;
629 	uint32 eecp = HCS0_XECP(cparams) << 2;
630 	for (; eecp != 0 && XECP_NEXT(eec) && portFound < fPortCount;
631 		eecp += XECP_NEXT(eec) << 2) {
632 		eec = ReadCapReg32(eecp);
633 		if (XECP_ID(eec) != XHCI_SUPPORTED_PROTOCOLS_CAPID)
634 			continue;
635 		if (XHCI_SUPPORTED_PROTOCOLS_0_MAJOR(eec) > 3)
636 			continue;
637 		uint32 temp = ReadCapReg32(eecp + 8);
638 		uint32 offset = XHCI_SUPPORTED_PROTOCOLS_1_OFFSET(temp);
639 		uint32 count = XHCI_SUPPORTED_PROTOCOLS_1_COUNT(temp);
640 		if (offset == 0 || count == 0)
641 			continue;
642 		offset--;
643 		for (uint32 i = offset; i < offset + count; i++) {
644 			if (XHCI_SUPPORTED_PROTOCOLS_0_MAJOR(eec) == 0x3)
645 				fPortSpeeds[i] = USB_SPEED_SUPERSPEED;
646 			else
647 				fPortSpeeds[i] = USB_SPEED_HIGHSPEED;
648 
649 			TRACE("speed for port %" B_PRId32 " is %s\n", i,
650 				fPortSpeeds[i] == USB_SPEED_SUPERSPEED ? "super" : "high");
651 		}
652 		portFound += count;
653 	}
654 
655 	uint32 params2 = ReadCapReg32(XHCI_HCSPARAMS2);
656 	fScratchpadCount = HCS_MAX_SC_BUFFERS(params2);
657 	if (fScratchpadCount > XHCI_MAX_SCRATCHPADS) {
658 		TRACE_ERROR("invalid number of scratchpads: %" B_PRIu32 "\n",
659 			fScratchpadCount);
660 		return B_ERROR;
661 	}
662 
663 	uint32 params3 = ReadCapReg32(XHCI_HCSPARAMS3);
664 	fExitLatMax = HCS_U1_DEVICE_LATENCY(params3)
665 		+ HCS_U2_DEVICE_LATENCY(params3);
666 
667 	// clear interrupts & disable device notifications
668 	WriteOpReg(XHCI_STS, ReadOpReg(XHCI_STS));
669 	WriteOpReg(XHCI_DNCTRL, 0);
670 
671 	// allocate Device Context Base Address array
672 	phys_addr_t dmaAddress;
673 	fDcbaArea = fStack->AllocateArea((void **)&fDcba, &dmaAddress,
674 		sizeof(*fDcba), "DCBA Area");
675 	if (fDcbaArea < B_OK) {
676 		TRACE_ERROR("unable to create the DCBA area\n");
677 		return B_ERROR;
678 	}
679 	memset(fDcba, 0, sizeof(*fDcba));
680 	memset(fScratchpadArea, 0, sizeof(fScratchpadArea));
681 	memset(fScratchpad, 0, sizeof(fScratchpad));
682 
683 	// setting the first address to the scratchpad array address
684 	fDcba->baseAddress[0] = dmaAddress
685 		+ offsetof(struct xhci_device_context_array, scratchpad);
686 
687 	// fill up the scratchpad array with scratchpad pages
688 	for (uint32 i = 0; i < fScratchpadCount; i++) {
689 		phys_addr_t scratchDmaAddress;
690 		fScratchpadArea[i] = fStack->AllocateArea((void **)&fScratchpad[i],
691 			&scratchDmaAddress, B_PAGE_SIZE, "Scratchpad Area");
692 		if (fScratchpadArea[i] < B_OK) {
693 			TRACE_ERROR("unable to create the scratchpad area\n");
694 			return B_ERROR;
695 		}
696 		fDcba->scratchpad[i] = scratchDmaAddress;
697 	}
698 
699 	TRACE("setting DCBAAP %" B_PRIxPHYSADDR "\n", dmaAddress);
700 	WriteOpReg(XHCI_DCBAAP_LO, (uint32)dmaAddress);
701 	WriteOpReg(XHCI_DCBAAP_HI, (uint32)(dmaAddress >> 32));
702 
703 	// allocate Event Ring Segment Table
704 	uint8 *addr;
705 	fErstArea = fStack->AllocateArea((void **)&addr, &dmaAddress,
706 		(XHCI_MAX_COMMANDS + XHCI_MAX_EVENTS) * sizeof(xhci_trb)
707 		+ sizeof(xhci_erst_element),
708 		"USB XHCI ERST CMD_RING and EVENT_RING Area");
709 
710 	if (fErstArea < B_OK) {
711 		TRACE_ERROR("unable to create the ERST AND RING area\n");
712 		delete_area(fDcbaArea);
713 		return B_ERROR;
714 	}
715 	fErst = (xhci_erst_element *)addr;
716 	memset(fErst, 0, (XHCI_MAX_COMMANDS + XHCI_MAX_EVENTS) * sizeof(xhci_trb)
717 		+ sizeof(xhci_erst_element));
718 
719 	// fill with Event Ring Segment Base Address and Event Ring Segment Size
720 	fErst->rs_addr = dmaAddress + sizeof(xhci_erst_element);
721 	fErst->rs_size = XHCI_MAX_EVENTS;
722 	fErst->rsvdz = 0;
723 
724 	addr += sizeof(xhci_erst_element);
725 	fEventRing = (xhci_trb *)addr;
726 	addr += XHCI_MAX_EVENTS * sizeof(xhci_trb);
727 	fCmdRing = (xhci_trb *)addr;
728 
729 	TRACE("setting ERST size\n");
730 	WriteRunReg32(XHCI_ERSTSZ(0), XHCI_ERSTS_SET(1));
731 
732 	TRACE("setting ERDP addr = 0x%" B_PRIx64 "\n", fErst->rs_addr);
733 	WriteRunReg32(XHCI_ERDP_LO(0), (uint32)fErst->rs_addr);
734 	WriteRunReg32(XHCI_ERDP_HI(0), (uint32)(fErst->rs_addr >> 32));
735 
736 	TRACE("setting ERST base addr = 0x%" B_PRIxPHYSADDR "\n", dmaAddress);
737 	WriteRunReg32(XHCI_ERSTBA_LO(0), (uint32)dmaAddress);
738 	WriteRunReg32(XHCI_ERSTBA_HI(0), (uint32)(dmaAddress >> 32));
739 
740 	dmaAddress += sizeof(xhci_erst_element) + XHCI_MAX_EVENTS
741 		* sizeof(xhci_trb);
742 
743 	// Make sure the Command Ring is stopped
744 	if ((ReadOpReg(XHCI_CRCR_LO) & CRCR_CRR) != 0) {
745 		TRACE_ALWAYS("Command Ring is running, send stop/cancel\n");
746 		WriteOpReg(XHCI_CRCR_LO, CRCR_CS);
747 		WriteOpReg(XHCI_CRCR_HI, 0);
748 		WriteOpReg(XHCI_CRCR_LO, CRCR_CA);
749 		WriteOpReg(XHCI_CRCR_HI, 0);
750 		snooze(1000);
751 		if ((ReadOpReg(XHCI_CRCR_LO) & CRCR_CRR) != 0) {
752 			TRACE_ERROR("Command Ring still running after stop/cancel\n");
753 		}
754 	}
755 	TRACE("setting CRCR addr = 0x%" B_PRIxPHYSADDR "\n", dmaAddress);
756 	WriteOpReg(XHCI_CRCR_LO, (uint32)dmaAddress | CRCR_RCS);
757 	WriteOpReg(XHCI_CRCR_HI, (uint32)(dmaAddress >> 32));
758 	// link trb
759 	fCmdRing[XHCI_MAX_COMMANDS - 1].address = dmaAddress;
760 
761 	TRACE("setting interrupt rate\n");
762 
763 	// Setting IMOD below 0x3F8 on Intel Lynx Point can cause IRQ lockups
764 	if (fPCIInfo->vendor_id == PCI_VENDOR_INTEL
765 		&& (fPCIInfo->device_id == PCI_DEVICE_INTEL_PANTHER_POINT_XHCI
766 			|| fPCIInfo->device_id == PCI_DEVICE_INTEL_LYNX_POINT_XHCI
767 			|| fPCIInfo->device_id == PCI_DEVICE_INTEL_LYNX_POINT_LP_XHCI
768 			|| fPCIInfo->device_id == PCI_DEVICE_INTEL_BAYTRAIL_XHCI
769 			|| fPCIInfo->device_id == PCI_DEVICE_INTEL_WILDCAT_POINT_XHCI)) {
770 		WriteRunReg32(XHCI_IMOD(0), 0x000003f8); // 4000 irq/s
771 	} else {
772 		WriteRunReg32(XHCI_IMOD(0), 0x000001f4); // 8000 irq/s
773 	}
774 
775 	TRACE("enabling interrupt\n");
776 	WriteRunReg32(XHCI_IMAN(0), ReadRunReg32(XHCI_IMAN(0)) | IMAN_INTR_ENA);
777 
778 	WriteOpReg(XHCI_CMD, CMD_RUN | CMD_INTE | CMD_HSEE);
779 
780 	// wait for start up state
781 	if (WaitOpBits(XHCI_STS, STS_HCH, 0) != B_OK) {
782 		TRACE_ERROR("HCH start up timeout\n");
783 	}
784 
785 	fRootHub = new(std::nothrow) XHCIRootHub(RootObject(), 1);
786 	if (!fRootHub) {
787 		TRACE_ERROR("no memory to allocate root hub\n");
788 		return B_NO_MEMORY;
789 	}
790 
791 	if (fRootHub->InitCheck() < B_OK) {
792 		TRACE_ERROR("root hub failed init check\n");
793 		return fRootHub->InitCheck();
794 	}
795 
796 	SetRootHub(fRootHub);
797 
798 	fRootHub->RegisterNode(Node());
799 
800 	TRACE_ALWAYS("successfully started the controller\n");
801 
802 #ifdef TRACE_USB
803 	TRACE("No-Op test...\n");
804 	Noop();
805 #endif
806 
807 	return BusManager::Start();
808 }
809 
810 
811 status_t
812 XHCI::SubmitTransfer(Transfer *transfer)
813 {
814 	// short circuit the root hub
815 	if (transfer->TransferPipe()->DeviceAddress() == 1)
816 		return fRootHub->ProcessTransfer(this, transfer);
817 
818 	TRACE("SubmitTransfer(%p)\n", transfer);
819 	Pipe *pipe = transfer->TransferPipe();
820 	if ((pipe->Type() & USB_OBJECT_CONTROL_PIPE) != 0)
821 		return SubmitControlRequest(transfer);
822 	return SubmitNormalRequest(transfer);
823 }
824 
825 
826 status_t
827 XHCI::SubmitControlRequest(Transfer *transfer)
828 {
829 	Pipe *pipe = transfer->TransferPipe();
830 	usb_request_data *requestData = transfer->RequestData();
831 	bool directionIn = (requestData->RequestType & USB_REQTYPE_DEVICE_IN) != 0;
832 
833 	TRACE("SubmitControlRequest() length %d\n", requestData->Length);
834 
835 	xhci_endpoint *endpoint = (xhci_endpoint *)pipe->ControllerCookie();
836 	if (endpoint == NULL) {
837 		TRACE_ERROR("control pipe has no endpoint!\n");
838 		return B_BAD_VALUE;
839 	}
840 	if (endpoint->device == NULL) {
841 		panic("endpoint is not initialized!");
842 		return B_NO_INIT;
843 	}
844 
845 	status_t status = transfer->InitKernelAccess();
846 	if (status != B_OK)
847 		return status;
848 
849 	xhci_td *descriptor = CreateDescriptor(3, 1, requestData->Length);
850 	if (descriptor == NULL)
851 		return B_NO_MEMORY;
852 	descriptor->transfer = transfer;
853 
854 	// Setup Stage
855 	uint8 index = 0;
856 	memcpy(&descriptor->trbs[index].address, requestData,
857 		sizeof(usb_request_data));
858 	descriptor->trbs[index].status = TRB_2_IRQ(0) | TRB_2_BYTES(8);
859 	descriptor->trbs[index].flags
860 		= TRB_3_TYPE(TRB_TYPE_SETUP_STAGE) | TRB_3_IDT_BIT | TRB_3_CYCLE_BIT;
861 	if (requestData->Length > 0) {
862 		descriptor->trbs[index].flags |=
863 			directionIn ? TRB_3_TRT_IN : TRB_3_TRT_OUT;
864 	}
865 
866 	index++;
867 
868 	// Data Stage (if any)
869 	if (requestData->Length > 0) {
870 		descriptor->trbs[index].address = descriptor->buffer_addrs[0];
871 		descriptor->trbs[index].status = TRB_2_IRQ(0)
872 			| TRB_2_BYTES(requestData->Length)
873 			| TRB_2_TD_SIZE(0);
874 		descriptor->trbs[index].flags = TRB_3_TYPE(TRB_TYPE_DATA_STAGE)
875 				| (directionIn ? TRB_3_DIR_IN : 0)
876 				| TRB_3_CYCLE_BIT;
877 
878 		if (!directionIn) {
879 			transfer->PrepareKernelAccess();
880 			WriteDescriptor(descriptor, transfer->Vector(),
881 				transfer->VectorCount(), transfer->IsPhysical());
882 		}
883 
884 		index++;
885 	}
886 
887 	// Status Stage
888 	descriptor->trbs[index].address = 0;
889 	descriptor->trbs[index].status = TRB_2_IRQ(0);
890 	descriptor->trbs[index].flags = TRB_3_TYPE(TRB_TYPE_STATUS_STAGE)
891 			| TRB_3_CHAIN_BIT | TRB_3_ENT_BIT | TRB_3_CYCLE_BIT;
892 		// The CHAIN bit must be set when using an Event Data TRB
893 		// (XHCI 1.2 § 6.4.1.2.3 Table 6-31 p472).
894 
895 	// Status Stage is an OUT transfer when the device is sending data
896 	// (XHCI 1.2 § 4.11.2.2 Table 4-7 p213), otherwise set the IN bit.
897 	if (requestData->Length == 0 || !directionIn)
898 		descriptor->trbs[index].flags |= TRB_3_DIR_IN;
899 
900 	descriptor->trb_used = index + 1;
901 
902 	status = _LinkDescriptorForPipe(descriptor, endpoint);
903 	if (status != B_OK) {
904 		FreeDescriptor(descriptor);
905 		return status;
906 	}
907 
908 	return B_OK;
909 }
910 
911 
912 status_t
913 XHCI::SubmitNormalRequest(Transfer *transfer)
914 {
915 	TRACE("SubmitNormalRequest() length %" B_PRIuSIZE "\n", transfer->FragmentLength());
916 
917 	Pipe *pipe = transfer->TransferPipe();
918 	usb_isochronous_data *isochronousData = transfer->IsochronousData();
919 	bool directionIn = (pipe->Direction() == Pipe::In);
920 
921 	xhci_endpoint *endpoint = (xhci_endpoint *)pipe->ControllerCookie();
922 	if (endpoint == NULL) {
923 		TRACE_ERROR("pipe has no endpoint!\n");
924 		return B_BAD_VALUE;
925 	}
926 	if (endpoint->device == NULL) {
927 		panic("endpoint is not initialized!");
928 		return B_NO_INIT;
929 	}
930 
931 	status_t status = transfer->InitKernelAccess();
932 	if (status != B_OK)
933 		return status;
934 
935 	// TRBs within a TD must be "grouped" into TD Fragments, which mostly means
936 	// that a max_burst_payload boundary cannot be crossed within a TRB, but
937 	// only between TRBs. More than one TRB can be in a TD Fragment, but we keep
938 	// things simple by setting trbSize to the MBP. (XHCI 1.2 § 4.11.7.1 p235.)
939 	size_t trbSize = endpoint->max_burst_payload;
940 
941 	if (isochronousData != NULL) {
942 		if (isochronousData->packet_count == 0)
943 			return B_BAD_VALUE;
944 
945 		// Isochronous transfers use more specifically sized packets.
946 		trbSize = transfer->DataLength() / isochronousData->packet_count;
947 		if (trbSize == 0 || trbSize > pipe->MaxPacketSize() || trbSize
948 				!= (size_t)isochronousData->packet_descriptors[0].request_length)
949 			return B_BAD_VALUE;
950 	}
951 
952 	// Now that we know trbSize, compute the count.
953 	const int32 trbCount = (transfer->FragmentLength() + trbSize - 1) / trbSize;
954 
955 	xhci_td *td = CreateDescriptor(trbCount, trbCount, trbSize);
956 	if (td == NULL)
957 		return B_NO_MEMORY;
958 
959 	// Normal Stage
960 	const size_t maxPacketSize = pipe->MaxPacketSize();
961 	size_t remaining = transfer->FragmentLength();
962 	for (int32 i = 0; i < trbCount; i++) {
963 		int32 trbLength = (remaining < trbSize) ? remaining : trbSize;
964 		remaining -= trbLength;
965 
966 		// The "TD Size" field of a transfer TRB indicates the number of
967 		// remaining maximum-size *packets* in this TD, *not* including the
968 		// packets in the current TRB, and capped at 31 if there are more
969 		// than 31 packets remaining in the TD. (XHCI 1.2 § 4.11.2.4 p218.)
970 		int32 tdSize = (remaining + maxPacketSize - 1) / maxPacketSize;
971 		if (tdSize > 31)
972 			tdSize = 31;
973 
974 		td->trbs[i].address = td->buffer_addrs[i];
975 		td->trbs[i].status = TRB_2_IRQ(0)
976 			| TRB_2_BYTES(trbLength)
977 			| TRB_2_TD_SIZE(tdSize);
978 		td->trbs[i].flags = TRB_3_TYPE(TRB_TYPE_NORMAL)
979 			| TRB_3_CYCLE_BIT | TRB_3_CHAIN_BIT;
980 
981 		td->trb_used++;
982 	}
983 
984 	// Isochronous-specific
985 	if (isochronousData != NULL) {
986 		// This is an isochronous transfer; we need to make the first TRB
987 		// an isochronous TRB.
988 		td->trbs[0].flags &= ~(TRB_3_TYPE(TRB_TYPE_NORMAL));
989 		td->trbs[0].flags |= TRB_3_TYPE(TRB_TYPE_ISOCH);
990 
991 		// Isochronous pipes are scheduled by microframes, one of which
992 		// is 125us for USB 2 and above. But for USB 1 it was 1ms, so
993 		// we need to use a different frame delta for that case.
994 		uint8 frameDelta = 1;
995 		if (transfer->TransferPipe()->Speed() == USB_SPEED_FULLSPEED)
996 			frameDelta = 8;
997 
998 		// TODO: We do not currently take Mult into account at all!
999 		// How are we supposed to do that here?
1000 
1001 		// Determine the (starting) frame number: if ISO_ASAP is set,
1002 		// we are queueing this "right away", and so want to reset
1003 		// the starting_frame_number. Otherwise we use the passed one.
1004 		uint32 frame;
1005 		if ((isochronousData->flags & USB_ISO_ASAP) != 0
1006 				|| isochronousData->starting_frame_number == NULL) {
1007 			// All reads from the microframe index register must be
1008 			// incremented by 1. (XHCI 1.2 § 4.14.2.1.4 p265.)
1009 			frame = ReadRunReg32(XHCI_MFINDEX) + 1;
1010 			td->trbs[0].flags |= TRB_3_ISO_SIA_BIT;
1011 		} else {
1012 			frame = *isochronousData->starting_frame_number;
1013 			td->trbs[0].flags |= TRB_3_FRID(frame);
1014 		}
1015 		frame = (frame + frameDelta) % 2048;
1016 		if (isochronousData->starting_frame_number != NULL)
1017 			*isochronousData->starting_frame_number = frame;
1018 
1019 		// TODO: The OHCI bus driver seems to also do this for inbound
1020 		// isochronous transfers. Perhaps it should be moved into the stack?
1021 		if (directionIn) {
1022 			for (uint32 i = 0; i < isochronousData->packet_count; i++) {
1023 				isochronousData->packet_descriptors[i].actual_length = 0;
1024 				isochronousData->packet_descriptors[i].status = B_NO_INIT;
1025 			}
1026 		}
1027 	}
1028 
1029 	// Set the ENT (Evaluate Next TRB) bit, so that the HC will not switch
1030 	// contexts before evaluating the Link TRB that _LinkDescriptorForPipe
1031 	// will insert, as otherwise there would be a race between us freeing
1032 	// and unlinking the descriptor, and the controller evaluating the Link TRB
1033 	// and thus getting back onto the main ring and executing the Event Data
1034 	// TRB that generates the interrupt for this transfer.
1035 	//
1036 	// Note that we *do not* unset the CHAIN bit in this TRB, thus including
1037 	// the Link TRB in this TD formally, which is required when using the
1038 	// ENT bit. (XHCI 1.2 § 4.12.3 p250.)
1039 	td->trbs[td->trb_used - 1].flags |= TRB_3_ENT_BIT;
1040 
1041 	if (!directionIn) {
1042 		TRACE("copying out iov count %ld\n", transfer->VectorCount());
1043 		status_t status = transfer->PrepareKernelAccess();
1044 		if (status != B_OK) {
1045 			FreeDescriptor(td);
1046 			return status;
1047 		}
1048 		WriteDescriptor(td, transfer->Vector(),
1049 			transfer->VectorCount(), transfer->IsPhysical());
1050 	}
1051 
1052 	td->transfer = transfer;
1053 	status = _LinkDescriptorForPipe(td, endpoint);
1054 	if (status != B_OK) {
1055 		FreeDescriptor(td);
1056 		return status;
1057 	}
1058 
1059 	return B_OK;
1060 }
1061 
1062 
1063 status_t
1064 XHCI::CancelQueuedTransfers(Pipe *pipe, bool force)
1065 {
1066 	xhci_endpoint* endpoint = (xhci_endpoint*)pipe->ControllerCookie();
1067 	if (endpoint == NULL || endpoint->trbs == NULL) {
1068 		// Someone's de-allocated this pipe or endpoint in the meantime.
1069 		// (Possibly AllocateDevice failed, and we were the temporary pipe.)
1070 		return B_NO_INIT;
1071 	}
1072 
1073 #ifndef TRACE_USB
1074 	if (force)
1075 #endif
1076 	{
1077 		TRACE_ALWAYS("cancel queued transfers (%" B_PRId8 ") for pipe %p (%d)\n",
1078 			endpoint->used, pipe, pipe->EndpointAddress());
1079 	}
1080 
1081 	MutexLocker endpointLocker(endpoint->lock);
1082 
1083 	if (endpoint->td_head == NULL) {
1084 		// There aren't any currently pending transfers to cancel.
1085 		return B_OK;
1086 	}
1087 
1088 	// Calling the callbacks while holding the endpoint lock could potentially
1089 	// cause deadlocks, so we instead store them in a pointer array. We need
1090 	// to do this separately from freeing the TDs, for in the case we fail
1091 	// to stop the endpoint, we cancel the transfers but do not free the TDs.
1092 	Transfer* transfers[XHCI_MAX_TRANSFERS];
1093 	int32 transfersCount = 0;
1094 
1095 	for (xhci_td* td = endpoint->td_head; td != NULL; td = td->next) {
1096 		if (td->transfer == NULL)
1097 			continue;
1098 
1099 		// We can't cancel or delete transfers under "force", as they probably
1100 		// are not safe to use anymore.
1101 		if (!force) {
1102 			transfers[transfersCount] = td->transfer;
1103 			transfersCount++;
1104 		}
1105 		td->transfer = NULL;
1106 	}
1107 
1108 	// It is possible that while waiting for the stop-endpoint command to
1109 	// complete, one of the queued transfers posts a completion event, so in
1110 	// order to avoid a deadlock, we must unlock the endpoint.
1111 	endpointLocker.Unlock();
1112 	status_t status = StopEndpoint(false, endpoint);
1113 	if (status != B_OK && status != B_DEV_STALLED) {
1114 		// It is possible that the endpoint was stopped by the controller at the
1115 		// same time our STOP command was in progress, causing a "Context State"
1116 		// error. In that case, try again; if the endpoint is already stopped,
1117 		// StopEndpoint will notice this. (XHCI 1.2 § 4.6.9 p137.)
1118 		status = StopEndpoint(false, endpoint);
1119 	}
1120 	if (status == B_DEV_STALLED) {
1121 		// Only exit from a Halted state is a RESET. (XHCI 1.2 § 4.8.3 p163.)
1122 		TRACE_ERROR("cancel queued transfers: halted endpoint, reset!\n");
1123 		status = ResetEndpoint(false, endpoint);
1124 	}
1125 	endpointLocker.Lock();
1126 
1127 	// Detach the head TD from the endpoint.
1128 	xhci_td* td_head = endpoint->td_head;
1129 	endpoint->td_head = NULL;
1130 
1131 	if (status == B_OK) {
1132 		// Clear the endpoint's TRBs.
1133 		memset(endpoint->trbs, 0, sizeof(xhci_trb) * XHCI_ENDPOINT_RING_SIZE);
1134 		endpoint->used = 0;
1135 		endpoint->current = 0;
1136 
1137 		// Set dequeue pointer location to the beginning of the ring.
1138 		SetTRDequeue(endpoint->trb_addr, 0, endpoint->id + 1,
1139 			endpoint->device->slot);
1140 
1141 		// We don't need to do anything else to restart the ring, as it will resume
1142 		// operation as normal upon the next doorbell. (XHCI 1.2 § 4.6.9 p136.)
1143 	} else {
1144 		// We couldn't stop the endpoint. Most likely the device has been
1145 		// removed and the endpoint was stopped by the hardware, or is
1146 		// for some reason busy and cannot be stopped.
1147 		TRACE_ERROR("cancel queued transfers: could not stop endpoint: %s!\n",
1148 			strerror(status));
1149 
1150 		// Instead of freeing the TDs, we want to leave them in the endpoint
1151 		// so that when/if the hardware returns, they can be properly unlinked,
1152 		// as otherwise the endpoint could get "stuck" by having the "used"
1153 		// slowly accumulate due to "dead" transfers.
1154 		endpoint->td_head = td_head;
1155 		td_head = NULL;
1156 	}
1157 
1158 	endpointLocker.Unlock();
1159 
1160 	for (int32 i = 0; i < transfersCount; i++) {
1161 		transfers[i]->Finished(B_CANCELED, 0);
1162 		delete transfers[i];
1163 	}
1164 
1165 	// This loop looks a bit strange because we need to store the "next"
1166 	// pointer before freeing the descriptor.
1167 	xhci_td* td;
1168 	while ((td = td_head) != NULL) {
1169 		td_head = td_head->next;
1170 		FreeDescriptor(td);
1171 	}
1172 
1173 	return B_OK;
1174 }
1175 
1176 
1177 status_t
1178 XHCI::StartDebugTransfer(Transfer *transfer)
1179 {
1180 	Pipe *pipe = transfer->TransferPipe();
1181 	xhci_endpoint *endpoint = (xhci_endpoint *)pipe->ControllerCookie();
1182 	if (endpoint == NULL)
1183 		return B_BAD_VALUE;
1184 
1185 	// Check all locks that we are going to hit when running transfers.
1186 	if (mutex_trylock(&endpoint->lock) != B_OK)
1187 		return B_WOULD_BLOCK;
1188 	if (mutex_trylock(&fFinishedLock) != B_OK) {
1189 		mutex_unlock(&endpoint->lock);
1190 		return B_WOULD_BLOCK;
1191 	}
1192 	if (mutex_trylock(&fEventLock) != B_OK) {
1193 		mutex_unlock(&endpoint->lock);
1194 		mutex_unlock(&fFinishedLock);
1195 		return B_WOULD_BLOCK;
1196 	}
1197 	mutex_unlock(&endpoint->lock);
1198 	mutex_unlock(&fFinishedLock);
1199 	mutex_unlock(&fEventLock);
1200 
1201 	status_t status = SubmitTransfer(transfer);
1202 	if (status != B_OK)
1203 		return status;
1204 
1205 	// The endpoint's head TD is the TD of the just-submitted transfer.
1206 	// Just like EHCI, abuse the callback cookie to hold the TD pointer.
1207 	transfer->SetCallback(NULL, endpoint->td_head);
1208 
1209 	return B_OK;
1210 }
1211 
1212 
1213 status_t
1214 XHCI::CheckDebugTransfer(Transfer *transfer)
1215 {
1216 	xhci_td *transfer_td = (xhci_td *)transfer->CallbackCookie();
1217 	if (transfer_td == NULL)
1218 		return B_NO_INIT;
1219 
1220 	// Process events once, and then look for it in the finished list.
1221 	ProcessEvents();
1222 	xhci_td *previous = NULL;
1223 	for (xhci_td *td = fFinishedHead; td != NULL; td = td->next) {
1224 		if (td != transfer_td) {
1225 			previous = td;
1226 			continue;
1227 		}
1228 
1229 		// We've found it!
1230 		if (previous == NULL) {
1231 			fFinishedHead = fFinishedHead->next;
1232 		} else {
1233 			previous->next = td->next;
1234 		}
1235 
1236 		bool directionIn = (transfer->TransferPipe()->Direction() != Pipe::Out);
1237 		status_t status = (td->trb_completion_code == COMP_SUCCESS
1238 			|| td->trb_completion_code == COMP_SHORT_PACKET) ? B_OK : B_ERROR;
1239 
1240 		if (status == B_OK && directionIn) {
1241 			ReadDescriptor(td, transfer->Vector(), transfer->VectorCount(),
1242 				transfer->IsPhysical());
1243 		}
1244 
1245 		FreeDescriptor(td);
1246 		transfer->SetCallback(NULL, NULL);
1247 		return status;
1248 	}
1249 
1250 	// We didn't find it.
1251 	spin(75);
1252 	return B_DEV_PENDING;
1253 }
1254 
1255 
1256 void
1257 XHCI::CancelDebugTransfer(Transfer *transfer)
1258 {
1259 	while (CheckDebugTransfer(transfer) == B_DEV_PENDING)
1260 		spin(100);
1261 }
1262 
1263 
1264 status_t
1265 XHCI::NotifyPipeChange(Pipe *pipe, usb_change change)
1266 {
1267 	TRACE("pipe change %d for pipe %p (%d)\n", change, pipe,
1268 		pipe->EndpointAddress());
1269 
1270 	switch (change) {
1271 	case USB_CHANGE_CREATED:
1272 		return _InsertEndpointForPipe(pipe);
1273 	case USB_CHANGE_DESTROYED:
1274 		return _RemoveEndpointForPipe(pipe);
1275 
1276 	case USB_CHANGE_PIPE_POLICY_CHANGED:
1277 		// We don't care about these, at least for now.
1278 		return B_OK;
1279 	}
1280 
1281 	TRACE_ERROR("unknown pipe change!\n");
1282 	return B_UNSUPPORTED;
1283 }
1284 
1285 
1286 xhci_td *
1287 XHCI::CreateDescriptor(uint32 trbCount, uint32 bufferCount, size_t bufferSize)
1288 {
1289 	const bool inKDL = debug_debugger_running();
1290 
1291 	xhci_td *result;
1292 	if (!inKDL) {
1293 		result = (xhci_td*)calloc(1, sizeof(xhci_td));
1294 	} else {
1295 		// Just use the physical memory allocator while in KDL; it's less
1296 		// secure than using the regular heap, but it's easier to deal with.
1297 		phys_addr_t dummy;
1298 		fStack->AllocateChunk((void **)&result, &dummy, sizeof(xhci_td));
1299 	}
1300 
1301 	if (result == NULL) {
1302 		TRACE_ERROR("failed to allocate a transfer descriptor\n");
1303 		return NULL;
1304 	}
1305 
1306 	// We always allocate 1 more TRB than requested, so that
1307 	// _LinkDescriptorForPipe() has room to insert a link TRB.
1308 	trbCount++;
1309 	if (fStack->AllocateChunk((void **)&result->trbs, &result->trb_addr,
1310 			(trbCount * sizeof(xhci_trb))) < B_OK) {
1311 		TRACE_ERROR("failed to allocate TRBs\n");
1312 		FreeDescriptor(result);
1313 		return NULL;
1314 	}
1315 	result->trb_count = trbCount;
1316 	result->trb_used = 0;
1317 
1318 	if (bufferSize > 0) {
1319 		// Due to how the USB stack allocates physical memory, we can't just
1320 		// request one large chunk the size of the transfer, and so instead we
1321 		// create a series of buffers as requested by our caller.
1322 
1323 		// We store the buffer pointers and addresses in one memory block.
1324 		if (!inKDL) {
1325 			result->buffers = (void**)calloc(bufferCount,
1326 				(sizeof(void*) + sizeof(phys_addr_t)));
1327 		} else {
1328 			phys_addr_t dummy;
1329 			fStack->AllocateChunk((void **)&result->buffers, &dummy,
1330 				bufferCount * (sizeof(void*) + sizeof(phys_addr_t)));
1331 		}
1332 		if (result->buffers == NULL) {
1333 			TRACE_ERROR("unable to allocate space for buffer infos\n");
1334 			FreeDescriptor(result);
1335 			return NULL;
1336 		}
1337 		result->buffer_addrs = (phys_addr_t*)&result->buffers[bufferCount];
1338 		result->buffer_size = bufferSize;
1339 		result->buffer_count = bufferCount;
1340 
1341 		// Optimization: If the requested total size of all buffers is less
1342 		// than 32*B_PAGE_SIZE (the maximum size that the physical memory
1343 		// allocator can handle), we allocate only one buffer and segment it.
1344 		size_t totalSize = bufferSize * bufferCount;
1345 		if (totalSize < (32 * B_PAGE_SIZE)) {
1346 			if (fStack->AllocateChunk(&result->buffers[0],
1347 					&result->buffer_addrs[0], totalSize) < B_OK) {
1348 				TRACE_ERROR("unable to allocate space for large buffer (size %ld)\n",
1349 					totalSize);
1350 				FreeDescriptor(result);
1351 				return NULL;
1352 			}
1353 			for (uint32 i = 1; i < bufferCount; i++) {
1354 				result->buffers[i] = (void*)((addr_t)(result->buffers[i - 1])
1355 					+ bufferSize);
1356 				result->buffer_addrs[i] = result->buffer_addrs[i - 1]
1357 					+ bufferSize;
1358 			}
1359 		} else {
1360 			// Otherwise, we allocate each buffer individually.
1361 			for (uint32 i = 0; i < bufferCount; i++) {
1362 				if (fStack->AllocateChunk(&result->buffers[i],
1363 						&result->buffer_addrs[i], bufferSize) < B_OK) {
1364 					TRACE_ERROR("unable to allocate space for a buffer (size "
1365 						"%" B_PRIuSIZE ", count %" B_PRIu32 ")\n",
1366 						bufferSize, bufferCount);
1367 					FreeDescriptor(result);
1368 					return NULL;
1369 				}
1370 			}
1371 		}
1372 	} else {
1373 		result->buffers = NULL;
1374 		result->buffer_addrs = NULL;
1375 	}
1376 
1377 	// Initialize all other fields.
1378 	result->transfer = NULL;
1379 	result->trb_completion_code = 0;
1380 	result->trb_left = 0;
1381 	result->next = NULL;
1382 
1383 	TRACE("CreateDescriptor allocated %p, buffer_size %ld, buffer_count %" B_PRIu32 "\n",
1384 		result, result->buffer_size, result->buffer_count);
1385 
1386 	return result;
1387 }
1388 
1389 
1390 void
1391 XHCI::FreeDescriptor(xhci_td *descriptor)
1392 {
1393 	if (descriptor == NULL)
1394 		return;
1395 
1396 	const bool inKDL = debug_debugger_running();
1397 
1398 	if (descriptor->trbs != NULL) {
1399 		fStack->FreeChunk(descriptor->trbs, descriptor->trb_addr,
1400 			(descriptor->trb_count * sizeof(xhci_trb)));
1401 	}
1402 	if (descriptor->buffers != NULL) {
1403 		size_t totalSize = descriptor->buffer_size * descriptor->buffer_count;
1404 		if (totalSize < (32 * B_PAGE_SIZE)) {
1405 			// This was allocated as one contiguous buffer.
1406 			fStack->FreeChunk(descriptor->buffers[0], descriptor->buffer_addrs[0],
1407 				totalSize);
1408 		} else {
1409 			for (uint32 i = 0; i < descriptor->buffer_count; i++) {
1410 				if (descriptor->buffers[i] == NULL)
1411 					continue;
1412 				fStack->FreeChunk(descriptor->buffers[i], descriptor->buffer_addrs[i],
1413 					descriptor->buffer_size);
1414 			}
1415 		}
1416 
1417 		if (!inKDL) {
1418 			free(descriptor->buffers);
1419 		} else {
1420 			fStack->FreeChunk(descriptor->buffers, 0,
1421 				descriptor->buffer_count * (sizeof(void*) + sizeof(phys_addr_t)));
1422 		}
1423 	}
1424 
1425 	if (!inKDL)
1426 		free(descriptor);
1427 	else
1428 		fStack->FreeChunk(descriptor, 0, sizeof(xhci_td));
1429 }
1430 
1431 
1432 size_t
1433 XHCI::WriteDescriptor(xhci_td *descriptor, generic_io_vec *vector, size_t vectorCount, bool physical)
1434 {
1435 	size_t written = 0;
1436 
1437 	size_t bufIdx = 0, bufUsed = 0;
1438 	for (size_t vecIdx = 0; vecIdx < vectorCount; vecIdx++) {
1439 		size_t length = vector[vecIdx].length;
1440 
1441 		while (length > 0 && bufIdx < descriptor->buffer_count) {
1442 			size_t toCopy = min_c(length, descriptor->buffer_size - bufUsed);
1443 			status_t status = generic_memcpy(
1444 				(generic_addr_t)descriptor->buffers[bufIdx] + bufUsed, false,
1445 				vector[vecIdx].base + (vector[vecIdx].length - length), physical,
1446 				toCopy);
1447 			ASSERT(status == B_OK);
1448 
1449 			written += toCopy;
1450 			bufUsed += toCopy;
1451 			length -= toCopy;
1452 			if (bufUsed == descriptor->buffer_size) {
1453 				bufIdx++;
1454 				bufUsed = 0;
1455 			}
1456 		}
1457 	}
1458 
1459 	TRACE("wrote descriptor (%" B_PRIuSIZE " bytes)\n", written);
1460 	return written;
1461 }
1462 
1463 
1464 size_t
1465 XHCI::ReadDescriptor(xhci_td *descriptor, generic_io_vec *vector, size_t vectorCount, bool physical)
1466 {
1467 	size_t read = 0;
1468 
1469 	size_t bufIdx = 0, bufUsed = 0;
1470 	for (size_t vecIdx = 0; vecIdx < vectorCount; vecIdx++) {
1471 		size_t length = vector[vecIdx].length;
1472 
1473 		while (length > 0 && bufIdx < descriptor->buffer_count) {
1474 			size_t toCopy = min_c(length, descriptor->buffer_size - bufUsed);
1475 			status_t status = generic_memcpy(
1476 				vector[vecIdx].base + (vector[vecIdx].length - length), physical,
1477 				(generic_addr_t)descriptor->buffers[bufIdx] + bufUsed, false, toCopy);
1478 			ASSERT(status == B_OK);
1479 
1480 			read += toCopy;
1481 			bufUsed += toCopy;
1482 			length -= toCopy;
1483 			if (bufUsed == descriptor->buffer_size) {
1484 				bufIdx++;
1485 				bufUsed = 0;
1486 			}
1487 		}
1488 	}
1489 
1490 	TRACE("read descriptor (%" B_PRIuSIZE " bytes)\n", read);
1491 	return read;
1492 }
1493 
1494 
1495 Device *
1496 XHCI::AllocateDevice(Hub *parent, int8 hubAddress, uint8 hubPort,
1497 	usb_speed speed)
1498 {
1499 	TRACE("AllocateDevice hubAddress %d hubPort %d speed %d\n", hubAddress,
1500 		hubPort, speed);
1501 
1502 	uint8 slot = XHCI_MAX_SLOTS;
1503 	status_t status = EnableSlot(&slot);
1504 	if (status != B_OK) {
1505 		TRACE_ERROR("failed to enable slot: %s\n", strerror(status));
1506 		return NULL;
1507 	}
1508 
1509 	if (slot == 0 || slot > fSlotCount) {
1510 		TRACE_ERROR("AllocateDevice: bad slot\n");
1511 		return NULL;
1512 	}
1513 
1514 	if (fDevices[slot].slot != 0) {
1515 		TRACE_ERROR("AllocateDevice: slot already used\n");
1516 		return NULL;
1517 	}
1518 
1519 	struct xhci_device *device = &fDevices[slot];
1520 	device->slot = slot;
1521 
1522 	device->input_ctx_area = fStack->AllocateArea((void **)&device->input_ctx,
1523 		&device->input_ctx_addr, sizeof(*device->input_ctx) << fContextSizeShift,
1524 		"XHCI input context");
1525 	if (device->input_ctx_area < B_OK) {
1526 		TRACE_ERROR("unable to create a input context area\n");
1527 		CleanupDevice(device);
1528 		return NULL;
1529 	}
1530 	if (fContextSizeShift == 1) {
1531 		// 64-byte contexts have to be page-aligned in order for
1532 		// _OffsetContextAddr to function properly.
1533 		ASSERT((((addr_t)device->input_ctx) % B_PAGE_SIZE) == 0);
1534 	}
1535 
1536 	memset(device->input_ctx, 0, sizeof(*device->input_ctx) << fContextSizeShift);
1537 	_WriteContext(&device->input_ctx->input.dropFlags, 0);
1538 	_WriteContext(&device->input_ctx->input.addFlags, 3);
1539 
1540 	uint8 rhPort = hubPort;
1541 	uint32 route = 0;
1542 	for (Device *hubDevice = parent; hubDevice != RootObject();
1543 			hubDevice = (Device *)hubDevice->Parent()) {
1544 		if (hubDevice->Parent() == RootObject())
1545 			break;
1546 
1547 		if (rhPort > 15)
1548 			rhPort = 15;
1549 		route = route << 4;
1550 		route |= rhPort;
1551 
1552 		rhPort = hubDevice->HubPort();
1553 	}
1554 
1555 	uint32 dwslot0 = SLOT_0_NUM_ENTRIES(1) | SLOT_0_ROUTE(route);
1556 
1557 	// Get speed of port, only if device connected to root hub port
1558 	// else we have to rely on value reported by the Hub Explore thread
1559 	if (route == 0) {
1560 		GetPortSpeed(hubPort - 1, &speed);
1561 		TRACE("speed updated %d\n", speed);
1562 	}
1563 
1564 	// add the speed
1565 	switch (speed) {
1566 	case USB_SPEED_LOWSPEED:
1567 		dwslot0 |= SLOT_0_SPEED(2);
1568 		break;
1569 	case USB_SPEED_FULLSPEED:
1570 		dwslot0 |= SLOT_0_SPEED(1);
1571 		break;
1572 	case USB_SPEED_HIGHSPEED:
1573 		dwslot0 |= SLOT_0_SPEED(3);
1574 		break;
1575 	case USB_SPEED_SUPERSPEED:
1576 		dwslot0 |= SLOT_0_SPEED(4);
1577 		break;
1578 	default:
1579 		TRACE_ERROR("unknown usb speed\n");
1580 		break;
1581 	}
1582 
1583 	_WriteContext(&device->input_ctx->slot.dwslot0, dwslot0);
1584 	// TODO enable power save
1585 	_WriteContext(&device->input_ctx->slot.dwslot1, SLOT_1_RH_PORT(rhPort));
1586 	uint32 dwslot2 = SLOT_2_IRQ_TARGET(0);
1587 
1588 	// If LS/FS device connected to non-root HS device
1589 	if (route != 0 && parent->Speed() == USB_SPEED_HIGHSPEED
1590 		&& (speed == USB_SPEED_LOWSPEED || speed == USB_SPEED_FULLSPEED)) {
1591 		struct xhci_device *parenthub = (struct xhci_device *)
1592 			parent->ControllerCookie();
1593 		dwslot2 |= SLOT_2_PORT_NUM(hubPort);
1594 		dwslot2 |= SLOT_2_TT_HUB_SLOT(parenthub->slot);
1595 	}
1596 
1597 	_WriteContext(&device->input_ctx->slot.dwslot2, dwslot2);
1598 
1599 	_WriteContext(&device->input_ctx->slot.dwslot3, SLOT_3_SLOT_STATE(0)
1600 		| SLOT_3_DEVICE_ADDRESS(0));
1601 
1602 	TRACE("slot 0x%08" B_PRIx32 " 0x%08" B_PRIx32 " 0x%08" B_PRIx32 " 0x%08" B_PRIx32
1603 		"\n", _ReadContext(&device->input_ctx->slot.dwslot0),
1604 		_ReadContext(&device->input_ctx->slot.dwslot1),
1605 		_ReadContext(&device->input_ctx->slot.dwslot2),
1606 		_ReadContext(&device->input_ctx->slot.dwslot3));
1607 
1608 	device->device_ctx_area = fStack->AllocateArea((void **)&device->device_ctx,
1609 		&device->device_ctx_addr, sizeof(*device->device_ctx) << fContextSizeShift,
1610 		"XHCI device context");
1611 	if (device->device_ctx_area < B_OK) {
1612 		TRACE_ERROR("unable to create a device context area\n");
1613 		CleanupDevice(device);
1614 		return NULL;
1615 	}
1616 	memset(device->device_ctx, 0, sizeof(*device->device_ctx) << fContextSizeShift);
1617 
1618 	device->trb_area = fStack->AllocateArea((void **)&device->trbs,
1619 		&device->trb_addr, sizeof(xhci_trb) * (XHCI_MAX_ENDPOINTS - 1)
1620 			* XHCI_ENDPOINT_RING_SIZE, "XHCI endpoint trbs");
1621 	if (device->trb_area < B_OK) {
1622 		TRACE_ERROR("unable to create a device trbs area\n");
1623 		CleanupDevice(device);
1624 		return NULL;
1625 	}
1626 
1627 	// set up slot pointer to device context
1628 	fDcba->baseAddress[slot] = device->device_ctx_addr;
1629 
1630 	size_t maxPacketSize;
1631 	switch (speed) {
1632 	case USB_SPEED_LOWSPEED:
1633 	case USB_SPEED_FULLSPEED:
1634 		maxPacketSize = 8;
1635 		break;
1636 	case USB_SPEED_HIGHSPEED:
1637 		maxPacketSize = 64;
1638 		break;
1639 	default:
1640 		maxPacketSize = 512;
1641 		break;
1642 	}
1643 
1644 	xhci_endpoint* endpoint0 = &device->endpoints[0];
1645 	mutex_init(&endpoint0->lock, "xhci endpoint lock");
1646 	endpoint0->device = device;
1647 	endpoint0->id = 0;
1648 	endpoint0->td_head = NULL;
1649 	endpoint0->used = 0;
1650 	endpoint0->current = 0;
1651 	endpoint0->trbs = device->trbs;
1652 	endpoint0->trb_addr = device->trb_addr;
1653 
1654 	// configure the Control endpoint 0
1655 	if (ConfigureEndpoint(endpoint0, slot, 0, USB_OBJECT_CONTROL_PIPE, false,
1656 			0, maxPacketSize, speed, 0, 0) != B_OK) {
1657 		TRACE_ERROR("unable to configure default control endpoint\n");
1658 		CleanupDevice(device);
1659 		return NULL;
1660 	}
1661 
1662 	// device should get to addressed state (bsr = 0)
1663 	status = SetAddress(device->input_ctx_addr, false, slot);
1664 	if (status != B_OK) {
1665 		TRACE_ERROR("unable to set address: %s\n", strerror(status));
1666 		CleanupDevice(device);
1667 		return NULL;
1668 	}
1669 
1670 	device->address = SLOT_3_DEVICE_ADDRESS_GET(_ReadContext(
1671 		&device->device_ctx->slot.dwslot3));
1672 
1673 	TRACE("device: address 0x%x state 0x%08" B_PRIx32 "\n", device->address,
1674 		SLOT_3_SLOT_STATE_GET(_ReadContext(
1675 			&device->device_ctx->slot.dwslot3)));
1676 	TRACE("endpoint0 state 0x%08" B_PRIx32 "\n",
1677 		ENDPOINT_0_STATE_GET(_ReadContext(
1678 			&device->device_ctx->endpoints[0].dwendpoint0)));
1679 
1680 	// Wait a bit for the device to complete addressing
1681 	snooze(USB_DELAY_SET_ADDRESS);
1682 
1683 	// Create a temporary pipe with the new address
1684 	ControlPipe pipe(parent);
1685 	pipe.SetControllerCookie(endpoint0);
1686 	pipe.InitCommon(device->address + 1, 0, speed, Pipe::Default, maxPacketSize, 0,
1687 		hubAddress, hubPort);
1688 
1689 	// Get the device descriptor
1690 	// Just retrieve the first 8 bytes of the descriptor -> minimum supported
1691 	// size of any device. It is enough because it includes the device type.
1692 
1693 	size_t actualLength = 0;
1694 	usb_device_descriptor deviceDescriptor;
1695 
1696 	TRACE("getting the device descriptor\n");
1697 	status = pipe.SendRequest(
1698 		USB_REQTYPE_DEVICE_IN | USB_REQTYPE_STANDARD,		// type
1699 		USB_REQUEST_GET_DESCRIPTOR,							// request
1700 		USB_DESCRIPTOR_DEVICE << 8,							// value
1701 		0,													// index
1702 		8,													// length
1703 		(void *)&deviceDescriptor,							// buffer
1704 		8,													// buffer length
1705 		&actualLength);										// actual length
1706 
1707 	if (actualLength != 8) {
1708 		TRACE_ERROR("failed to get the device descriptor: %s\n",
1709 			strerror(status));
1710 		CleanupDevice(device);
1711 		return NULL;
1712 	}
1713 
1714 	TRACE("device_class: %d device_subclass %d device_protocol %d\n",
1715 		deviceDescriptor.device_class, deviceDescriptor.device_subclass,
1716 		deviceDescriptor.device_protocol);
1717 
1718 	if (speed == USB_SPEED_FULLSPEED && deviceDescriptor.max_packet_size_0 != 8) {
1719 		TRACE("Full speed device with different max packet size for Endpoint 0\n");
1720 		uint32 dwendpoint1 = _ReadContext(
1721 			&device->input_ctx->endpoints[0].dwendpoint1);
1722 		dwendpoint1 &= ~ENDPOINT_1_MAXPACKETSIZE(0xffff);
1723 		dwendpoint1 |= ENDPOINT_1_MAXPACKETSIZE(
1724 			deviceDescriptor.max_packet_size_0);
1725 		_WriteContext(&device->input_ctx->endpoints[0].dwendpoint1,
1726 			dwendpoint1);
1727 		_WriteContext(&device->input_ctx->input.dropFlags, 0);
1728 		_WriteContext(&device->input_ctx->input.addFlags, (1 << 1));
1729 		EvaluateContext(device->input_ctx_addr, device->slot);
1730 	}
1731 
1732 	Device *deviceObject = NULL;
1733 	if (deviceDescriptor.device_class == 0x09) {
1734 		TRACE("creating new Hub\n");
1735 		TRACE("getting the hub descriptor\n");
1736 		size_t actualLength = 0;
1737 		usb_hub_descriptor hubDescriptor;
1738 		status = pipe.SendRequest(
1739 			USB_REQTYPE_DEVICE_IN | USB_REQTYPE_CLASS,			// type
1740 			USB_REQUEST_GET_DESCRIPTOR,							// request
1741 			USB_DESCRIPTOR_HUB << 8,							// value
1742 			0,													// index
1743 			sizeof(usb_hub_descriptor),							// length
1744 			(void *)&hubDescriptor,								// buffer
1745 			sizeof(usb_hub_descriptor),							// buffer length
1746 			&actualLength);
1747 
1748 		if (actualLength != sizeof(usb_hub_descriptor)) {
1749 			TRACE_ERROR("error while getting the hub descriptor: %s\n",
1750 				strerror(status));
1751 			CleanupDevice(device);
1752 			return NULL;
1753 		}
1754 
1755 		uint32 dwslot0 = _ReadContext(&device->input_ctx->slot.dwslot0);
1756 		dwslot0 |= SLOT_0_HUB_BIT;
1757 		_WriteContext(&device->input_ctx->slot.dwslot0, dwslot0);
1758 		uint32 dwslot1 = _ReadContext(&device->input_ctx->slot.dwslot1);
1759 		dwslot1 |= SLOT_1_NUM_PORTS(hubDescriptor.num_ports);
1760 		_WriteContext(&device->input_ctx->slot.dwslot1, dwslot1);
1761 		if (speed == USB_SPEED_HIGHSPEED) {
1762 			uint32 dwslot2 = _ReadContext(&device->input_ctx->slot.dwslot2);
1763 			dwslot2 |= SLOT_2_TT_TIME(HUB_TTT_GET(hubDescriptor.characteristics));
1764 			_WriteContext(&device->input_ctx->slot.dwslot2, dwslot2);
1765 		}
1766 
1767 		deviceObject = new(std::nothrow) Hub(parent, hubAddress, hubPort,
1768 			deviceDescriptor, device->address + 1, speed, false, device);
1769 	} else {
1770 		TRACE("creating new device\n");
1771 		deviceObject = new(std::nothrow) Device(parent, hubAddress, hubPort,
1772 			deviceDescriptor, device->address + 1, speed, false, device);
1773 	}
1774 	if (deviceObject == NULL || deviceObject->InitCheck() != B_OK) {
1775 		if (deviceObject == NULL) {
1776 			TRACE_ERROR("no memory to allocate device\n");
1777 		} else {
1778 			TRACE_ERROR("device object failed to initialize\n");
1779 		}
1780 		CleanupDevice(device);
1781 		return NULL;
1782 	}
1783 
1784 	// We don't want to disable the default endpoint, naturally, which would
1785 	// otherwise happen when this Pipe object is destroyed.
1786 	pipe.SetControllerCookie(NULL);
1787 
1788 	deviceObject->RegisterNode();
1789 
1790 	TRACE("AllocateDevice() port %d slot %d\n", hubPort, slot);
1791 	return deviceObject;
1792 }
1793 
1794 
1795 void
1796 XHCI::FreeDevice(Device *usbDevice)
1797 {
1798 	xhci_device* device = (xhci_device*)usbDevice->ControllerCookie();
1799 	TRACE("FreeDevice() slot %d\n", device->slot);
1800 
1801 	// Delete the device first, so it cleans up its pipes and tells us
1802 	// what we need to destroy before we tear down our internal state.
1803 	delete usbDevice;
1804 
1805 	CleanupDevice(device);
1806 }
1807 
1808 
1809 void
1810 XHCI::CleanupDevice(xhci_device *device)
1811 {
1812 	if (device->slot != 0) {
1813 		DisableSlot(device->slot);
1814 		fDcba->baseAddress[device->slot] = 0;
1815 	}
1816 
1817 	if (device->trb_addr != 0)
1818 		delete_area(device->trb_area);
1819 	if (device->input_ctx_addr != 0)
1820 		delete_area(device->input_ctx_area);
1821 	if (device->device_ctx_addr != 0)
1822 		delete_area(device->device_ctx_area);
1823 
1824 	memset(device, 0, sizeof(xhci_device));
1825 }
1826 
1827 
1828 uint8
1829 XHCI::_GetEndpointState(xhci_endpoint* endpoint)
1830 {
1831 	struct xhci_device_ctx* device_ctx = endpoint->device->device_ctx;
1832 	return ENDPOINT_0_STATE_GET(
1833 		_ReadContext(&device_ctx->endpoints[endpoint->id].dwendpoint0));
1834 }
1835 
1836 
1837 status_t
1838 XHCI::_InsertEndpointForPipe(Pipe *pipe)
1839 {
1840 	TRACE("insert endpoint for pipe %p (%d)\n", pipe, pipe->EndpointAddress());
1841 
1842 	if (pipe->ControllerCookie() != NULL
1843 			|| pipe->Parent()->Type() != USB_OBJECT_DEVICE) {
1844 		// default pipe is already referenced
1845 		return B_OK;
1846 	}
1847 
1848 	Device* usbDevice = (Device *)pipe->Parent();
1849 	if (usbDevice->Parent() == RootObject()) {
1850 		// root hub needs no initialization
1851 		return B_OK;
1852 	}
1853 
1854 	struct xhci_device *device = (struct xhci_device *)
1855 		usbDevice->ControllerCookie();
1856 	if (device == NULL) {
1857 		panic("device is NULL\n");
1858 		return B_NO_INIT;
1859 	}
1860 
1861 	const uint8 id = (2 * pipe->EndpointAddress()
1862 		+ (pipe->Direction() != Pipe::Out ? 1 : 0)) - 1;
1863 	if (id >= XHCI_MAX_ENDPOINTS - 1)
1864 		return B_BAD_VALUE;
1865 
1866 	if (id > 0) {
1867 		uint32 devicedwslot0 = _ReadContext(&device->device_ctx->slot.dwslot0);
1868 		if (SLOT_0_NUM_ENTRIES_GET(devicedwslot0) == 1) {
1869 			uint32 inputdwslot0 = _ReadContext(&device->input_ctx->slot.dwslot0);
1870 			inputdwslot0 &= ~(SLOT_0_NUM_ENTRIES(0x1f));
1871 			inputdwslot0 |= SLOT_0_NUM_ENTRIES(XHCI_MAX_ENDPOINTS - 1);
1872 			_WriteContext(&device->input_ctx->slot.dwslot0, inputdwslot0);
1873 			EvaluateContext(device->input_ctx_addr, device->slot);
1874 		}
1875 
1876 		xhci_endpoint* endpoint = &device->endpoints[id];
1877 		mutex_init(&endpoint->lock, "xhci endpoint lock");
1878 		MutexLocker endpointLocker(endpoint->lock);
1879 
1880 		endpoint->device = device;
1881 		endpoint->id = id;
1882 		endpoint->td_head = NULL;
1883 		endpoint->used = 0;
1884 		endpoint->current = 0;
1885 
1886 		endpoint->trbs = device->trbs + id * XHCI_ENDPOINT_RING_SIZE;
1887 		endpoint->trb_addr = device->trb_addr
1888 			+ id * XHCI_ENDPOINT_RING_SIZE * sizeof(xhci_trb);
1889 		memset(endpoint->trbs, 0,
1890 			sizeof(xhci_trb) * XHCI_ENDPOINT_RING_SIZE);
1891 
1892 		TRACE("insert endpoint for pipe: trbs, device %p endpoint %p\n",
1893 			device->trbs, endpoint->trbs);
1894 		TRACE("insert endpoint for pipe: trb_addr, device 0x%" B_PRIxPHYSADDR
1895 			" endpoint 0x%" B_PRIxPHYSADDR "\n", device->trb_addr,
1896 			endpoint->trb_addr);
1897 
1898 		const uint8 endpointNum = id + 1;
1899 
1900 		status_t status = ConfigureEndpoint(endpoint, device->slot, id, pipe->Type(),
1901 			pipe->Direction() == Pipe::In, pipe->Interval(), pipe->MaxPacketSize(),
1902 			usbDevice->Speed(), pipe->MaxBurst(), pipe->BytesPerInterval());
1903 		if (status != B_OK) {
1904 			TRACE_ERROR("unable to configure endpoint: %s\n", strerror(status));
1905 			return status;
1906 		}
1907 
1908 		_WriteContext(&device->input_ctx->input.dropFlags, 0);
1909 		_WriteContext(&device->input_ctx->input.addFlags,
1910 			(1 << endpointNum) | (1 << 0));
1911 
1912 		ConfigureEndpoint(device->input_ctx_addr, false, device->slot);
1913 
1914 		TRACE("device: address 0x%x state 0x%08" B_PRIx32 "\n",
1915 			device->address, SLOT_3_SLOT_STATE_GET(_ReadContext(
1916 				&device->device_ctx->slot.dwslot3)));
1917 		TRACE("endpoint[0] state 0x%08" B_PRIx32 "\n",
1918 			ENDPOINT_0_STATE_GET(_ReadContext(
1919 				&device->device_ctx->endpoints[0].dwendpoint0)));
1920 		TRACE("endpoint[%d] state 0x%08" B_PRIx32 "\n", id,
1921 			ENDPOINT_0_STATE_GET(_ReadContext(
1922 				&device->device_ctx->endpoints[id].dwendpoint0)));
1923 	}
1924 	pipe->SetControllerCookie(&device->endpoints[id]);
1925 
1926 	return B_OK;
1927 }
1928 
1929 
1930 status_t
1931 XHCI::_RemoveEndpointForPipe(Pipe *pipe)
1932 {
1933 	TRACE("remove endpoint for pipe %p (%d)\n", pipe, pipe->EndpointAddress());
1934 
1935 	if (pipe->Parent()->Type() != USB_OBJECT_DEVICE)
1936 		return B_OK;
1937 	Device* usbDevice = (Device *)pipe->Parent();
1938 	if (usbDevice->Parent() == RootObject())
1939 		return B_BAD_VALUE;
1940 
1941 	xhci_endpoint *endpoint = (xhci_endpoint *)pipe->ControllerCookie();
1942 	if (endpoint == NULL || endpoint->trbs == NULL)
1943 		return B_NO_INIT;
1944 
1945 	pipe->SetControllerCookie(NULL);
1946 
1947 	if (endpoint->id > 0) {
1948 		xhci_device *device = endpoint->device;
1949 		uint8 epNumber = endpoint->id + 1;
1950 		StopEndpoint(true, endpoint);
1951 
1952 		mutex_lock(&endpoint->lock);
1953 
1954 		// See comment in CancelQueuedTransfers.
1955 		xhci_td* td;
1956 		while ((td = endpoint->td_head) != NULL) {
1957 			endpoint->td_head = endpoint->td_head->next;
1958 			FreeDescriptor(td);
1959 		}
1960 
1961 		mutex_destroy(&endpoint->lock);
1962 		memset(endpoint, 0, sizeof(xhci_endpoint));
1963 
1964 		_WriteContext(&device->input_ctx->input.dropFlags, (1 << epNumber));
1965 		_WriteContext(&device->input_ctx->input.addFlags, (1 << 0));
1966 
1967 		// The Deconfigure bit in the Configure Endpoint command indicates
1968 		// that *all* endpoints are to be deconfigured, and not just the ones
1969 		// specified in the context flags. (XHCI 1.2 § 4.6.6 p115.)
1970 		ConfigureEndpoint(device->input_ctx_addr, false, device->slot);
1971 	}
1972 
1973 	return B_OK;
1974 }
1975 
1976 
1977 status_t
1978 XHCI::_LinkDescriptorForPipe(xhci_td *descriptor, xhci_endpoint *endpoint)
1979 {
1980 	TRACE("link descriptor for pipe\n");
1981 
1982 	// Use mutex_trylock first, in case we are in KDL.
1983 	MutexLocker endpointLocker(&endpoint->lock, mutex_trylock(&endpoint->lock) == B_OK);
1984 
1985 	// "used" refers to the number of currently linked TDs, not the number of
1986 	// used TRBs on the ring (we use 2 TRBs on the ring per transfer.)
1987 	if (endpoint->used >= (XHCI_MAX_TRANSFERS - 1)) {
1988 		TRACE_ERROR("link descriptor for pipe: max transfers count exceeded\n");
1989 		return B_BAD_VALUE;
1990 	}
1991 
1992 	// We do not support queuing other transfers in tandem with a fragmented one.
1993 	if (endpoint->td_head != NULL && endpoint->td_head->transfer != NULL
1994 			&& endpoint->td_head->transfer->IsFragmented()) {
1995 		TRACE_ERROR("cannot submit transfer: a fragmented transfer is queued\n");
1996 		return B_DEV_RESOURCE_CONFLICT;
1997 	}
1998 
1999 	endpoint->used++;
2000 	descriptor->next = endpoint->td_head;
2001 	endpoint->td_head = descriptor;
2002 
2003 	const uint32 current = endpoint->current,
2004 		eventdata = current + 1,
2005 		last = XHCI_ENDPOINT_RING_SIZE - 1;
2006 	uint32 next = eventdata + 1;
2007 
2008 	TRACE("link descriptor for pipe: current %d, next %d\n", current, next);
2009 
2010 	// Add a Link TRB to the end of the descriptor.
2011 	phys_addr_t addr = endpoint->trb_addr + eventdata * sizeof(xhci_trb);
2012 	descriptor->trbs[descriptor->trb_used].address = addr;
2013 	descriptor->trbs[descriptor->trb_used].status = TRB_2_IRQ(0);
2014 	descriptor->trbs[descriptor->trb_used].flags = TRB_3_TYPE(TRB_TYPE_LINK)
2015 		| TRB_3_CHAIN_BIT | TRB_3_CYCLE_BIT;
2016 		// It is specified that (XHCI 1.2 § 4.12.3 Note 2 p251) if the TRB
2017 		// following one with the ENT bit set is a Link TRB, the Link TRB
2018 		// shall be evaluated *and* the subsequent TRB shall be. Thus a
2019 		// TRB_3_ENT_BIT is unnecessary here; and from testing seems to
2020 		// break all transfers on a (very) small number of controllers.
2021 
2022 #if !B_HOST_IS_LENDIAN
2023 	// Convert endianness.
2024 	for (uint32 i = 0; i <= descriptor->trb_used; i++) {
2025 		descriptor->trbs[i].address =
2026 			B_HOST_TO_LENDIAN_INT64(descriptor->trbs[i].address);
2027 		descriptor->trbs[i].status =
2028 			B_HOST_TO_LENDIAN_INT32(descriptor->trbs[i].status);
2029 		descriptor->trbs[i].flags =
2030 			B_HOST_TO_LENDIAN_INT32(descriptor->trbs[i].flags);
2031 	}
2032 #endif
2033 
2034 	// Link the descriptor.
2035 	endpoint->trbs[current].address =
2036 		B_HOST_TO_LENDIAN_INT64(descriptor->trb_addr);
2037 	endpoint->trbs[current].status =
2038 		B_HOST_TO_LENDIAN_INT32(TRB_2_IRQ(0));
2039 	endpoint->trbs[current].flags =
2040 		B_HOST_TO_LENDIAN_INT32(TRB_3_TYPE(TRB_TYPE_LINK));
2041 
2042 	// Set up the Event Data TRB (XHCI 1.2 § 4.11.5.2 p230.)
2043 	//
2044 	// We do this on the main ring for two reasons: first, to avoid a small
2045 	// potential race between the interrupt and the controller evaluating
2046 	// the link TRB to get back onto the ring; and second, because many
2047 	// controllers throw errors if the target of a Link TRB is not valid
2048 	// (i.e. does not have its Cycle Bit set.)
2049 	//
2050 	// We also set the "address" field, which the controller will copy
2051 	// verbatim into the TRB it posts to the event ring, to be the last
2052 	// "real" TRB in the TD; this will allow us to determine what transfer
2053 	// the resulting Transfer Event TRB refers to.
2054 	endpoint->trbs[eventdata].address =
2055 		B_HOST_TO_LENDIAN_INT64(descriptor->trb_addr
2056 			+ (descriptor->trb_used - 1) * sizeof(xhci_trb));
2057 	endpoint->trbs[eventdata].status =
2058 		B_HOST_TO_LENDIAN_INT32(TRB_2_IRQ(0));
2059 	endpoint->trbs[eventdata].flags =
2060 		B_HOST_TO_LENDIAN_INT32(TRB_3_TYPE(TRB_TYPE_EVENT_DATA)
2061 			| TRB_3_IOC_BIT | TRB_3_CYCLE_BIT);
2062 
2063 	if (next == last) {
2064 		// We always use 2 TRBs per _Link..() call, so if "next" is the last
2065 		// TRB in the ring, we need to generate a link TRB at "next", and
2066 		// then wrap it to 0. (We write the cycle bit later, after wrapping,
2067 		// for the reason noted in the previous comment.)
2068 		endpoint->trbs[next].address =
2069 			B_HOST_TO_LENDIAN_INT64(endpoint->trb_addr);
2070 		endpoint->trbs[next].status =
2071 			B_HOST_TO_LENDIAN_INT32(TRB_2_IRQ(0));
2072 		endpoint->trbs[next].flags =
2073 			B_HOST_TO_LENDIAN_INT32(TRB_3_TYPE(TRB_TYPE_LINK));
2074 
2075 		next = 0;
2076 	}
2077 
2078 	endpoint->trbs[next].address = 0;
2079 	endpoint->trbs[next].status = 0;
2080 	endpoint->trbs[next].flags = 0;
2081 
2082 	memory_write_barrier();
2083 
2084 	// Everything is ready, so write the cycle bit(s).
2085 	endpoint->trbs[current].flags |= B_HOST_TO_LENDIAN_INT32(TRB_3_CYCLE_BIT);
2086 	if (current == 0 && endpoint->trbs[last].address != 0)
2087 		endpoint->trbs[last].flags |= B_HOST_TO_LENDIAN_INT32(TRB_3_CYCLE_BIT);
2088 
2089 	TRACE("_LinkDescriptorForPipe pCurrent %p phys 0x%" B_PRIxPHYSADDR
2090 		" 0x%" B_PRIxPHYSADDR " 0x%08" B_PRIx32 "\n", &endpoint->trbs[current],
2091 		endpoint->trb_addr + current * sizeof(struct xhci_trb),
2092 		endpoint->trbs[current].address,
2093 		B_LENDIAN_TO_HOST_INT32(endpoint->trbs[current].flags));
2094 
2095 	endpoint->current = next;
2096 	endpointLocker.Unlock();
2097 
2098 	TRACE("Endpoint status 0x%08" B_PRIx32 " 0x%08" B_PRIx32 " 0x%016" B_PRIx64 "\n",
2099 		_ReadContext(&endpoint->device->device_ctx->endpoints[endpoint->id].dwendpoint0),
2100 		_ReadContext(&endpoint->device->device_ctx->endpoints[endpoint->id].dwendpoint1),
2101 		_ReadContext(&endpoint->device->device_ctx->endpoints[endpoint->id].qwendpoint2));
2102 
2103 	Ring(endpoint->device->slot, endpoint->id + 1);
2104 
2105 	TRACE("Endpoint status 0x%08" B_PRIx32 " 0x%08" B_PRIx32 " 0x%016" B_PRIx64 "\n",
2106 		_ReadContext(&endpoint->device->device_ctx->endpoints[endpoint->id].dwendpoint0),
2107 		_ReadContext(&endpoint->device->device_ctx->endpoints[endpoint->id].dwendpoint1),
2108 		_ReadContext(&endpoint->device->device_ctx->endpoints[endpoint->id].qwendpoint2));
2109 
2110 	return B_OK;
2111 }
2112 
2113 
2114 status_t
2115 XHCI::_UnlinkDescriptorForPipe(xhci_td *descriptor, xhci_endpoint *endpoint)
2116 {
2117 	TRACE("unlink descriptor for pipe\n");
2118 	// We presume that the caller has already locked or owns the endpoint.
2119 
2120 	endpoint->used--;
2121 	if (descriptor == endpoint->td_head) {
2122 		endpoint->td_head = descriptor->next;
2123 		descriptor->next = NULL;
2124 		return B_OK;
2125 	} else {
2126 		for (xhci_td *td = endpoint->td_head; td->next != NULL; td = td->next) {
2127 			if (td->next == descriptor) {
2128 				td->next = descriptor->next;
2129 				descriptor->next = NULL;
2130 				return B_OK;
2131 			}
2132 		}
2133 	}
2134 
2135 	endpoint->used++;
2136 	return B_ERROR;
2137 }
2138 
2139 
2140 status_t
2141 XHCI::ConfigureEndpoint(xhci_endpoint* ep, uint8 slot, uint8 number, uint8 type,
2142 	bool directionIn, uint16 interval, uint16 maxPacketSize, usb_speed speed,
2143 	uint8 maxBurst, uint16 bytesPerInterval)
2144 {
2145 	struct xhci_device* device = &fDevices[slot];
2146 
2147 	uint32 dwendpoint0 = 0;
2148 	uint32 dwendpoint1 = 0;
2149 	uint64 qwendpoint2 = 0;
2150 	uint32 dwendpoint4 = 0;
2151 
2152 	// Compute and assign the endpoint type. (XHCI 1.2 § 6.2.3 Table 6-9 p452.)
2153 	uint8 xhciType = 4;
2154 	if ((type & USB_OBJECT_INTERRUPT_PIPE) != 0)
2155 		xhciType = 3;
2156 	if ((type & USB_OBJECT_BULK_PIPE) != 0)
2157 		xhciType = 2;
2158 	if ((type & USB_OBJECT_ISO_PIPE) != 0)
2159 		xhciType = 1;
2160 	xhciType |= directionIn ? (1 << 2) : 0;
2161 	dwendpoint1 |= ENDPOINT_1_EPTYPE(xhciType);
2162 
2163 	// Compute and assign interval. (XHCI 1.2 § 6.2.3.6 p456.)
2164 	uint16 calcInterval;
2165 	if ((type & USB_OBJECT_BULK_PIPE) != 0
2166 			|| (type & USB_OBJECT_CONTROL_PIPE) != 0) {
2167 		// Bulk and Control endpoints never issue NAKs.
2168 		calcInterval = 0;
2169 	} else {
2170 		switch (speed) {
2171 		case USB_SPEED_FULLSPEED:
2172 			if ((type & USB_OBJECT_ISO_PIPE) != 0) {
2173 				// Convert 1-16 into 3-18.
2174 				calcInterval = min_c(max_c(interval, 1), 16) + 2;
2175 				break;
2176 			}
2177 
2178 			// fall through
2179 		case USB_SPEED_LOWSPEED: {
2180 			// Convert 1ms-255ms into 3-10.
2181 
2182 			// Find the index of the highest set bit in "interval".
2183 			uint32 temp = min_c(max_c(interval, 1), 255);
2184 			for (calcInterval = 0; temp != 1; calcInterval++)
2185 				temp = temp >> 1;
2186 			calcInterval += 3;
2187 			break;
2188 		}
2189 
2190 		case USB_SPEED_HIGHSPEED:
2191 		case USB_SPEED_SUPERSPEED:
2192 		default:
2193 			// Convert 1-16 into 0-15.
2194 			calcInterval = min_c(max_c(interval, 1), 16) - 1;
2195 			break;
2196 		}
2197 	}
2198 	dwendpoint0 |= ENDPOINT_0_INTERVAL(calcInterval);
2199 
2200 	// For non-isochronous endpoints, we want the controller to retry failed
2201 	// transfers, if possible. (XHCI 1.2 § 4.10.2.3 p197.)
2202 	if ((type & USB_OBJECT_ISO_PIPE) == 0)
2203 		dwendpoint1 |= ENDPOINT_1_CERR(3);
2204 
2205 	// Assign maximum burst size. For USB3 devices this is passed in; for
2206 	// all other devices we compute it. (XHCI 1.2 § 4.8.2 p161.)
2207 	if (speed == USB_SPEED_HIGHSPEED && (type & (USB_OBJECT_INTERRUPT_PIPE
2208 			| USB_OBJECT_ISO_PIPE)) != 0) {
2209 		maxBurst = (maxPacketSize & 0x1800) >> 11;
2210 	} else if (speed != USB_SPEED_SUPERSPEED) {
2211 		maxBurst = 0;
2212 	}
2213 	dwendpoint1 |= ENDPOINT_1_MAXBURST(maxBurst);
2214 
2215 	// Assign maximum packet size, set the ring address, and set the
2216 	// "Dequeue Cycle State" bit. (XHCI 1.2 § 6.2.3 Table 6-10 p453.)
2217 	dwendpoint1 |= ENDPOINT_1_MAXPACKETSIZE(maxPacketSize);
2218 	qwendpoint2 |= ENDPOINT_2_DCS_BIT | ep->trb_addr;
2219 
2220 	// The Max Burst Payload is the number of bytes moved by a
2221 	// maximum sized burst. (XHCI 1.2 § 4.11.7.1 p236.)
2222 	ep->max_burst_payload = (maxBurst + 1) * maxPacketSize;
2223 	if (ep->max_burst_payload == 0) {
2224 		TRACE_ERROR("ConfigureEndpoint() failed invalid max_burst_payload\n");
2225 		return B_BAD_VALUE;
2226 	}
2227 
2228 	// Assign average TRB length.
2229 	if ((type & USB_OBJECT_CONTROL_PIPE) != 0) {
2230 		// Control pipes are a special case, as they rarely have
2231 		// outbound transfers of any substantial size.
2232 		dwendpoint4 |= ENDPOINT_4_AVGTRBLENGTH(8);
2233 	} else if ((type & USB_OBJECT_ISO_PIPE) != 0) {
2234 		// Isochronous pipes are another special case: the TRB size will be
2235 		// one packet (which is normally smaller than the max packet size,
2236 		// but we don't know what it is here.)
2237 		dwendpoint4 |= ENDPOINT_4_AVGTRBLENGTH(maxPacketSize);
2238 	} else {
2239 		// Under all other circumstances, we put max_burst_payload in a TRB.
2240 		dwendpoint4 |= ENDPOINT_4_AVGTRBLENGTH(ep->max_burst_payload);
2241 	}
2242 
2243 	// Assign maximum ESIT payload. (XHCI 1.2 § 4.14.2 p259.)
2244 	if ((type & (USB_OBJECT_INTERRUPT_PIPE | USB_OBJECT_ISO_PIPE)) != 0) {
2245 		// TODO: For SuperSpeedPlus endpoints, there is yet another descriptor
2246 		// for isochronous endpoints that specifies the maximum ESIT payload.
2247 		// We don't fetch this yet, so just fall back to the USB2 computation
2248 		// method if bytesPerInterval is 0.
2249 		if (speed == USB_SPEED_SUPERSPEED && bytesPerInterval != 0)
2250 			dwendpoint4 |= ENDPOINT_4_MAXESITPAYLOAD(bytesPerInterval);
2251 		else if (speed >= USB_SPEED_HIGHSPEED)
2252 			dwendpoint4 |= ENDPOINT_4_MAXESITPAYLOAD((maxBurst + 1) * maxPacketSize);
2253 	}
2254 
2255 	_WriteContext(&device->input_ctx->endpoints[number].dwendpoint0,
2256 		dwendpoint0);
2257 	_WriteContext(&device->input_ctx->endpoints[number].dwendpoint1,
2258 		dwendpoint1);
2259 	_WriteContext(&device->input_ctx->endpoints[number].qwendpoint2,
2260 		qwendpoint2);
2261 	_WriteContext(&device->input_ctx->endpoints[number].dwendpoint4,
2262 		dwendpoint4);
2263 
2264 	TRACE("endpoint 0x%" B_PRIx32 " 0x%" B_PRIx32 " 0x%" B_PRIx64 " 0x%"
2265 		B_PRIx32 "\n",
2266 		_ReadContext(&device->input_ctx->endpoints[number].dwendpoint0),
2267 		_ReadContext(&device->input_ctx->endpoints[number].dwendpoint1),
2268 		_ReadContext(&device->input_ctx->endpoints[number].qwendpoint2),
2269 		_ReadContext(&device->input_ctx->endpoints[number].dwendpoint4));
2270 
2271 	return B_OK;
2272 }
2273 
2274 
2275 status_t
2276 XHCI::GetPortSpeed(uint8 index, usb_speed* speed)
2277 {
2278 	if (index >= fPortCount)
2279 		return B_BAD_INDEX;
2280 
2281 	uint32 portStatus = ReadOpReg(XHCI_PORTSC(index));
2282 
2283 	switch (PS_SPEED_GET(portStatus)) {
2284 	case 2:
2285 		*speed = USB_SPEED_LOWSPEED;
2286 		break;
2287 	case 1:
2288 		*speed = USB_SPEED_FULLSPEED;
2289 		break;
2290 	case 3:
2291 		*speed = USB_SPEED_HIGHSPEED;
2292 		break;
2293 	case 4:
2294 		*speed = USB_SPEED_SUPERSPEED;
2295 		break;
2296 	default:
2297 		TRACE_ALWAYS("nonstandard port speed %" B_PRId32 ", assuming SuperSpeed\n",
2298 			PS_SPEED_GET(portStatus));
2299 		*speed = USB_SPEED_SUPERSPEED;
2300 		break;
2301 	}
2302 
2303 	return B_OK;
2304 }
2305 
2306 
2307 status_t
2308 XHCI::GetPortStatus(uint8 index, usb_port_status* status)
2309 {
2310 	if (index >= fPortCount)
2311 		return B_BAD_INDEX;
2312 
2313 	status->status = status->change = 0;
2314 	uint32 portStatus = ReadOpReg(XHCI_PORTSC(index));
2315 	TRACE("port %" B_PRId8 " status=0x%08" B_PRIx32 "\n", index, portStatus);
2316 
2317 	// build the status
2318 	switch (PS_SPEED_GET(portStatus)) {
2319 	case 3:
2320 		status->status |= PORT_STATUS_HIGH_SPEED;
2321 		break;
2322 	case 2:
2323 		status->status |= PORT_STATUS_LOW_SPEED;
2324 		break;
2325 	default:
2326 		break;
2327 	}
2328 
2329 	if (portStatus & PS_CCS)
2330 		status->status |= PORT_STATUS_CONNECTION;
2331 	if (portStatus & PS_PED)
2332 		status->status |= PORT_STATUS_ENABLE;
2333 	if (portStatus & PS_OCA)
2334 		status->status |= PORT_STATUS_OVER_CURRENT;
2335 	if (portStatus & PS_PR)
2336 		status->status |= PORT_STATUS_RESET;
2337 	if (portStatus & PS_PP) {
2338 		if (fPortSpeeds[index] == USB_SPEED_SUPERSPEED)
2339 			status->status |= PORT_STATUS_SS_POWER;
2340 		else
2341 			status->status |= PORT_STATUS_POWER;
2342 	}
2343 
2344 	// build the change
2345 	if (portStatus & PS_CSC)
2346 		status->change |= PORT_STATUS_CONNECTION;
2347 	if (portStatus & PS_PEC)
2348 		status->change |= PORT_STATUS_ENABLE;
2349 	if (portStatus & PS_OCC)
2350 		status->change |= PORT_STATUS_OVER_CURRENT;
2351 	if (portStatus & PS_PRC)
2352 		status->change |= PORT_STATUS_RESET;
2353 
2354 	if (fPortSpeeds[index] == USB_SPEED_SUPERSPEED) {
2355 		if (portStatus & PS_PLC)
2356 			status->change |= PORT_CHANGE_LINK_STATE;
2357 		if (portStatus & PS_WRC)
2358 			status->change |= PORT_CHANGE_BH_PORT_RESET;
2359 	}
2360 
2361 	return B_OK;
2362 }
2363 
2364 
2365 status_t
2366 XHCI::SetPortFeature(uint8 index, uint16 feature)
2367 {
2368 	TRACE("set port feature index %u feature %u\n", index, feature);
2369 	if (index >= fPortCount)
2370 		return B_BAD_INDEX;
2371 
2372 	uint32 portRegister = XHCI_PORTSC(index);
2373 	uint32 portStatus = ReadOpReg(portRegister) & ~PS_CLEAR;
2374 
2375 	switch (feature) {
2376 	case PORT_SUSPEND:
2377 		if ((portStatus & PS_PED) == 0 || (portStatus & PS_PR)
2378 			|| (portStatus & PS_PLS_MASK) >= PS_XDEV_U3) {
2379 			TRACE_ERROR("USB core suspending device not in U0/U1/U2.\n");
2380 			return B_BAD_VALUE;
2381 		}
2382 		portStatus &= ~PS_PLS_MASK;
2383 		WriteOpReg(portRegister, portStatus | PS_LWS | PS_XDEV_U3);
2384 		break;
2385 
2386 	case PORT_RESET:
2387 		WriteOpReg(portRegister, portStatus | PS_PR);
2388 		break;
2389 
2390 	case PORT_POWER:
2391 		WriteOpReg(portRegister, portStatus | PS_PP);
2392 		break;
2393 	default:
2394 		return B_BAD_VALUE;
2395 	}
2396 	ReadOpReg(portRegister);
2397 	return B_OK;
2398 }
2399 
2400 
2401 status_t
2402 XHCI::ClearPortFeature(uint8 index, uint16 feature)
2403 {
2404 	TRACE("clear port feature index %u feature %u\n", index, feature);
2405 	if (index >= fPortCount)
2406 		return B_BAD_INDEX;
2407 
2408 	uint32 portRegister = XHCI_PORTSC(index);
2409 	uint32 portStatus = ReadOpReg(portRegister) & ~PS_CLEAR;
2410 
2411 	switch (feature) {
2412 	case PORT_SUSPEND:
2413 		portStatus = ReadOpReg(portRegister);
2414 		if (portStatus & PS_PR)
2415 			return B_BAD_VALUE;
2416 		if (portStatus & PS_XDEV_U3) {
2417 			if ((portStatus & PS_PED) == 0)
2418 				return B_BAD_VALUE;
2419 			portStatus &= ~PS_PLS_MASK;
2420 			WriteOpReg(portRegister, portStatus | PS_XDEV_U0 | PS_LWS);
2421 		}
2422 		break;
2423 	case PORT_ENABLE:
2424 		WriteOpReg(portRegister, portStatus | PS_PED);
2425 		break;
2426 	case PORT_POWER:
2427 		WriteOpReg(portRegister, portStatus & ~PS_PP);
2428 		break;
2429 	case C_PORT_CONNECTION:
2430 		WriteOpReg(portRegister, portStatus | PS_CSC);
2431 		break;
2432 	case C_PORT_ENABLE:
2433 		WriteOpReg(portRegister, portStatus | PS_PEC);
2434 		break;
2435 	case C_PORT_OVER_CURRENT:
2436 		WriteOpReg(portRegister, portStatus | PS_OCC);
2437 		break;
2438 	case C_PORT_RESET:
2439 		WriteOpReg(portRegister, portStatus | PS_PRC);
2440 		break;
2441 	case C_PORT_BH_PORT_RESET:
2442 		WriteOpReg(portRegister, portStatus | PS_WRC);
2443 		break;
2444 	case C_PORT_LINK_STATE:
2445 		WriteOpReg(portRegister, portStatus | PS_PLC);
2446 		break;
2447 	default:
2448 		return B_BAD_VALUE;
2449 	}
2450 
2451 	ReadOpReg(portRegister);
2452 	return B_OK;
2453 }
2454 
2455 
2456 status_t
2457 XHCI::ControllerHalt()
2458 {
2459 	// Mask off run state
2460 	WriteOpReg(XHCI_CMD, ReadOpReg(XHCI_CMD) & ~CMD_RUN);
2461 
2462 	// wait for shutdown state
2463 	if (WaitOpBits(XHCI_STS, STS_HCH, STS_HCH) != B_OK) {
2464 		TRACE_ERROR("HCH shutdown timeout\n");
2465 		return B_ERROR;
2466 	}
2467 	return B_OK;
2468 }
2469 
2470 
2471 status_t
2472 XHCI::ControllerReset()
2473 {
2474 	TRACE("ControllerReset() cmd: 0x%" B_PRIx32 " sts: 0x%" B_PRIx32 "\n",
2475 		ReadOpReg(XHCI_CMD), ReadOpReg(XHCI_STS));
2476 	WriteOpReg(XHCI_CMD, ReadOpReg(XHCI_CMD) | CMD_HCRST);
2477 
2478 	if (WaitOpBits(XHCI_CMD, CMD_HCRST, 0) != B_OK) {
2479 		TRACE_ERROR("ControllerReset() failed CMD_HCRST\n");
2480 		return B_ERROR;
2481 	}
2482 
2483 	if (WaitOpBits(XHCI_STS, STS_CNR, 0) != B_OK) {
2484 		TRACE_ERROR("ControllerReset() failed STS_CNR\n");
2485 		return B_ERROR;
2486 	}
2487 
2488 	return B_OK;
2489 }
2490 
2491 
2492 int32
2493 XHCI::InterruptHandler(void* data)
2494 {
2495 	return ((XHCI*)data)->Interrupt();
2496 }
2497 
2498 
2499 int32
2500 XHCI::Interrupt()
2501 {
2502 	SpinLocker _(&fSpinlock);
2503 
2504 	uint32 status = ReadOpReg(XHCI_STS);
2505 	uint32 temp = ReadRunReg32(XHCI_IMAN(0));
2506 	WriteOpReg(XHCI_STS, status);
2507 	WriteRunReg32(XHCI_IMAN(0), temp);
2508 
2509 	int32 result = B_HANDLED_INTERRUPT;
2510 
2511 	if ((status & STS_HCH) != 0) {
2512 		TRACE_ERROR("Host Controller halted\n");
2513 		return result;
2514 	}
2515 	if ((status & STS_HSE) != 0) {
2516 		TRACE_ERROR("Host System Error\n");
2517 		return result;
2518 	}
2519 	if ((status & STS_HCE) != 0) {
2520 		TRACE_ERROR("Host Controller Error\n");
2521 		return result;
2522 	}
2523 
2524 	if ((status & STS_EINT) == 0) {
2525 		TRACE("STS: 0x%" B_PRIx32 " IRQ_PENDING: 0x%" B_PRIx32 "\n",
2526 			status, temp);
2527 		return B_UNHANDLED_INTERRUPT;
2528 	}
2529 
2530 	TRACE("Event Interrupt\n");
2531 	release_sem_etc(fEventSem, 1, B_DO_NOT_RESCHEDULE);
2532 	return B_INVOKE_SCHEDULER;
2533 }
2534 
2535 
2536 void
2537 XHCI::Ring(uint8 slot, uint8 endpoint)
2538 {
2539 	TRACE("Ding Dong! slot:%d endpoint %d\n", slot, endpoint)
2540 	if ((slot == 0 && endpoint > 0) || (slot > 0 && endpoint == 0))
2541 		panic("Ring() invalid slot/endpoint combination\n");
2542 	if (slot > fSlotCount || endpoint >= XHCI_MAX_ENDPOINTS)
2543 		panic("Ring() invalid slot or endpoint\n");
2544 
2545 	WriteDoorReg32(XHCI_DOORBELL(slot), XHCI_DOORBELL_TARGET(endpoint)
2546 		| XHCI_DOORBELL_STREAMID(0));
2547 	ReadDoorReg32(XHCI_DOORBELL(slot));
2548 		// Flush PCI writes
2549 }
2550 
2551 
2552 void
2553 XHCI::QueueCommand(xhci_trb* trb)
2554 {
2555 	uint8 i, j;
2556 	uint32 temp;
2557 
2558 	i = fCmdIdx;
2559 	j = fCmdCcs;
2560 
2561 	TRACE("command[%u] = %" B_PRId32 " (0x%016" B_PRIx64 ", 0x%08" B_PRIx32
2562 		", 0x%08" B_PRIx32 ")\n", i, TRB_3_TYPE_GET(trb->flags), trb->address,
2563 		trb->status, trb->flags);
2564 
2565 	fCmdRing[i].address = trb->address;
2566 	fCmdRing[i].status = trb->status;
2567 	temp = trb->flags;
2568 
2569 	if (j)
2570 		temp |= TRB_3_CYCLE_BIT;
2571 	else
2572 		temp &= ~TRB_3_CYCLE_BIT;
2573 	temp &= ~TRB_3_TC_BIT;
2574 	fCmdRing[i].flags = B_HOST_TO_LENDIAN_INT32(temp);
2575 
2576 	fCmdAddr = fErst->rs_addr + (XHCI_MAX_EVENTS + i) * sizeof(xhci_trb);
2577 
2578 	i++;
2579 
2580 	if (i == (XHCI_MAX_COMMANDS - 1)) {
2581 		temp = TRB_3_TYPE(TRB_TYPE_LINK) | TRB_3_TC_BIT;
2582 		if (j)
2583 			temp |= TRB_3_CYCLE_BIT;
2584 		fCmdRing[i].flags = B_HOST_TO_LENDIAN_INT32(temp);
2585 
2586 		i = 0;
2587 		j ^= 1;
2588 	}
2589 
2590 	fCmdIdx = i;
2591 	fCmdCcs = j;
2592 }
2593 
2594 
2595 void
2596 XHCI::HandleCmdComplete(xhci_trb* trb)
2597 {
2598 	if (fCmdAddr == trb->address) {
2599 		TRACE("Received command event\n");
2600 		fCmdResult[0] = trb->status;
2601 		fCmdResult[1] = B_LENDIAN_TO_HOST_INT32(trb->flags);
2602 		release_sem_etc(fCmdCompSem, 1, B_DO_NOT_RESCHEDULE);
2603 	} else
2604 		TRACE_ERROR("received command event for unknown command!\n")
2605 }
2606 
2607 
2608 void
2609 XHCI::HandleTransferComplete(xhci_trb* trb)
2610 {
2611 	const uint32 flags = B_LENDIAN_TO_HOST_INT32(trb->flags);
2612 	const uint8 endpointNumber = TRB_3_ENDPOINT_GET(flags),
2613 		slot = TRB_3_SLOT_GET(flags);
2614 
2615 	if (slot > fSlotCount)
2616 		TRACE_ERROR("invalid slot\n");
2617 	if (endpointNumber == 0 || endpointNumber >= XHCI_MAX_ENDPOINTS) {
2618 		TRACE_ERROR("invalid endpoint\n");
2619 		return;
2620 	}
2621 
2622 	xhci_device *device = &fDevices[slot];
2623 	xhci_endpoint *endpoint = &device->endpoints[endpointNumber - 1];
2624 
2625 	if (endpoint->trbs == NULL) {
2626 		TRACE_ERROR("got TRB but endpoint is not allocated!\n");
2627 		return;
2628 	}
2629 
2630 	// Use mutex_trylock first, in case we are in KDL.
2631 	MutexLocker endpointLocker(endpoint->lock, mutex_trylock(&endpoint->lock) == B_OK);
2632 	if (!endpointLocker.IsLocked()) {
2633 		// We failed to get the lock. Most likely it was destroyed
2634 		// while we were waiting for it.
2635 		return;
2636 	}
2637 
2638 	// In the case of an Event Data TRB, the "transferred" field refers
2639 	// to the actual number of bytes transferred across the whole TD.
2640 	// (XHCI 1.2 § 6.4.2.1 Table 6-38 p478.)
2641 	const uint8 completionCode = TRB_2_COMP_CODE_GET(trb->status);
2642 	int32 transferred = TRB_2_REM_GET(trb->status), remainder = -1;
2643 
2644 	TRACE("HandleTransferComplete: ed %" B_PRIu32 ", code %" B_PRIu8 ", transferred %" B_PRId32 "\n",
2645 		  (flags & TRB_3_EVENT_DATA_BIT), completionCode, transferred);
2646 
2647 	if ((flags & TRB_3_EVENT_DATA_BIT) == 0) {
2648 		// This should only occur under error conditions.
2649 		TRACE("got an interrupt for a non-Event Data TRB!\n");
2650 		remainder = transferred;
2651 		transferred = -1;
2652 	}
2653 
2654 	if (completionCode != COMP_SUCCESS && completionCode != COMP_SHORT_PACKET
2655 			&& completionCode != COMP_STOPPED) {
2656 		TRACE_ALWAYS("transfer error on slot %" B_PRId8 " endpoint %" B_PRId8
2657 			": %s\n", slot, endpointNumber, xhci_error_string(completionCode));
2658 	}
2659 
2660 	const phys_addr_t source = B_LENDIAN_TO_HOST_INT64(trb->address);
2661 	for (xhci_td *td = endpoint->td_head; td != NULL; td = td->next) {
2662 		int64 offset = (source - td->trb_addr) / sizeof(xhci_trb);
2663 		if (offset < 0 || offset >= td->trb_count)
2664 			continue;
2665 
2666 		TRACE("HandleTransferComplete td %p trb %" B_PRId64 " found\n",
2667 			td, offset);
2668 
2669 		// The TRB at offset trb_used will be the link TRB, which we do not
2670 		// care about (and should not generate an interrupt at all.) We really
2671 		// care about the properly last TRB, at index "count - 1", which the
2672 		// Event Data TRB that _LinkDescriptorForPipe creates points to.
2673 		//
2674 		// But if we have an unsuccessful completion code, the transfer
2675 		// likely failed midway; so just accept it anyway.
2676 		if (offset == (td->trb_used - 1) || completionCode != COMP_SUCCESS) {
2677 			_UnlinkDescriptorForPipe(td, endpoint);
2678 			endpointLocker.Unlock();
2679 
2680 			td->trb_completion_code = completionCode;
2681 			td->td_transferred = transferred;
2682 			td->trb_left = remainder;
2683 
2684 			// add descriptor to finished list
2685 			if (mutex_trylock(&fFinishedLock) != B_OK)
2686 				mutex_lock(&fFinishedLock);
2687 			td->next = fFinishedHead;
2688 			fFinishedHead = td;
2689 			mutex_unlock(&fFinishedLock);
2690 
2691 			release_sem_etc(fFinishTransfersSem, 1, B_DO_NOT_RESCHEDULE);
2692 			TRACE("HandleTransferComplete td %p done\n", td);
2693 		} else {
2694 			TRACE_ERROR("successful TRB 0x%" B_PRIxPHYSADDR " was found, but it wasn't "
2695 				"the last in the TD!\n", source);
2696 		}
2697 		return;
2698 	}
2699 	TRACE_ERROR("TRB 0x%" B_PRIxPHYSADDR " was not found in the endpoint!\n", source);
2700 }
2701 
2702 
2703 void
2704 XHCI::DumpRing(xhci_trb *trbs, uint32 size)
2705 {
2706 	if (!Lock()) {
2707 		TRACE("Unable to get lock!\n");
2708 		return;
2709 	}
2710 
2711 	for (uint32 i = 0; i < size; i++) {
2712 		TRACE("command[%" B_PRId32 "] = %" B_PRId32 " (0x%016" B_PRIx64 ","
2713 			" 0x%08" B_PRIx32 ", 0x%08" B_PRIx32 ")\n", i,
2714 			TRB_3_TYPE_GET(B_LENDIAN_TO_HOST_INT32(trbs[i].flags)),
2715 			trbs[i].address, trbs[i].status, trbs[i].flags);
2716 	}
2717 
2718 	Unlock();
2719 }
2720 
2721 
2722 status_t
2723 XHCI::DoCommand(xhci_trb* trb)
2724 {
2725 	if (!Lock()) {
2726 		TRACE("Unable to get lock!\n");
2727 		return B_ERROR;
2728 	}
2729 
2730 	QueueCommand(trb);
2731 	Ring(0, 0);
2732 
2733 	// Begin with a 50ms timeout.
2734 	if (acquire_sem_etc(fCmdCompSem, 1, B_RELATIVE_TIMEOUT, 50 * 1000) != B_OK) {
2735 		// We've hit the timeout. In some error cases, interrupts are not
2736 		// generated; so here we force the event ring to be polled once.
2737 		release_sem(fEventSem);
2738 
2739 		// Now try again, this time with a 750ms timeout.
2740 		if (acquire_sem_etc(fCmdCompSem, 1, B_RELATIVE_TIMEOUT,
2741 				750 * 1000) != B_OK) {
2742 			TRACE("Unable to obtain fCmdCompSem!\n");
2743 			fCmdAddr = 0;
2744 			Unlock();
2745 			return B_TIMED_OUT;
2746 		}
2747 	}
2748 
2749 	// eat up sems that have been released by multiple interrupts
2750 	int32 semCount = 0;
2751 	get_sem_count(fCmdCompSem, &semCount);
2752 	if (semCount > 0)
2753 		acquire_sem_etc(fCmdCompSem, semCount, B_RELATIVE_TIMEOUT, 0);
2754 
2755 	status_t status = B_OK;
2756 	uint32 completionCode = TRB_2_COMP_CODE_GET(fCmdResult[0]);
2757 	TRACE("command complete\n");
2758 	if (completionCode != COMP_SUCCESS) {
2759 		TRACE_ERROR("unsuccessful command %" B_PRId32 ", error %s (%" B_PRId32 ")\n",
2760 			TRB_3_TYPE_GET(trb->flags), xhci_error_string(completionCode),
2761 			completionCode);
2762 		status = B_IO_ERROR;
2763 	}
2764 
2765 	trb->status = fCmdResult[0];
2766 	trb->flags = fCmdResult[1];
2767 
2768 	fCmdAddr = 0;
2769 	Unlock();
2770 	return status;
2771 }
2772 
2773 
2774 status_t
2775 XHCI::Noop()
2776 {
2777 	TRACE("Issue No-Op\n");
2778 	xhci_trb trb;
2779 	trb.address = 0;
2780 	trb.status = 0;
2781 	trb.flags = TRB_3_TYPE(TRB_TYPE_CMD_NOOP);
2782 
2783 	return DoCommand(&trb);
2784 }
2785 
2786 
2787 status_t
2788 XHCI::EnableSlot(uint8* slot)
2789 {
2790 	TRACE("Enable Slot\n");
2791 	xhci_trb trb;
2792 	trb.address = 0;
2793 	trb.status = 0;
2794 	trb.flags = TRB_3_TYPE(TRB_TYPE_ENABLE_SLOT);
2795 
2796 	status_t status = DoCommand(&trb);
2797 	if (status != B_OK)
2798 		return status;
2799 
2800 	*slot = TRB_3_SLOT_GET(trb.flags);
2801 	return *slot != 0 ? B_OK : B_BAD_VALUE;
2802 }
2803 
2804 
2805 status_t
2806 XHCI::DisableSlot(uint8 slot)
2807 {
2808 	TRACE("Disable Slot\n");
2809 	xhci_trb trb;
2810 	trb.address = 0;
2811 	trb.status = 0;
2812 	trb.flags = TRB_3_TYPE(TRB_TYPE_DISABLE_SLOT) | TRB_3_SLOT(slot);
2813 
2814 	return DoCommand(&trb);
2815 }
2816 
2817 
2818 status_t
2819 XHCI::SetAddress(uint64 inputContext, bool bsr, uint8 slot)
2820 {
2821 	TRACE("Set Address\n");
2822 	xhci_trb trb;
2823 	trb.address = inputContext;
2824 	trb.status = 0;
2825 	trb.flags = TRB_3_TYPE(TRB_TYPE_ADDRESS_DEVICE) | TRB_3_SLOT(slot);
2826 
2827 	if (bsr)
2828 		trb.flags |= TRB_3_BSR_BIT;
2829 
2830 	return DoCommand(&trb);
2831 }
2832 
2833 
2834 status_t
2835 XHCI::ConfigureEndpoint(uint64 inputContext, bool deconfigure, uint8 slot)
2836 {
2837 	TRACE("Configure Endpoint\n");
2838 	xhci_trb trb;
2839 	trb.address = inputContext;
2840 	trb.status = 0;
2841 	trb.flags = TRB_3_TYPE(TRB_TYPE_CONFIGURE_ENDPOINT) | TRB_3_SLOT(slot);
2842 
2843 	if (deconfigure)
2844 		trb.flags |= TRB_3_DCEP_BIT;
2845 
2846 	return DoCommand(&trb);
2847 }
2848 
2849 
2850 status_t
2851 XHCI::EvaluateContext(uint64 inputContext, uint8 slot)
2852 {
2853 	TRACE("Evaluate Context\n");
2854 	xhci_trb trb;
2855 	trb.address = inputContext;
2856 	trb.status = 0;
2857 	trb.flags = TRB_3_TYPE(TRB_TYPE_EVALUATE_CONTEXT) | TRB_3_SLOT(slot);
2858 
2859 	return DoCommand(&trb);
2860 }
2861 
2862 
2863 status_t
2864 XHCI::ResetEndpoint(bool preserve, xhci_endpoint* endpoint)
2865 {
2866 	TRACE("Reset Endpoint\n");
2867 
2868 	switch (_GetEndpointState(endpoint)) {
2869 		case ENDPOINT_STATE_STOPPED:
2870 			TRACE("Reset Endpoint: already stopped");
2871 			return B_OK;
2872 		case ENDPOINT_STATE_HALTED:
2873 			TRACE("Reset Endpoint: warning, weird state!");
2874 		default:
2875 			break;
2876 	}
2877 
2878 	xhci_trb trb;
2879 	trb.address = 0;
2880 	trb.status = 0;
2881 	trb.flags = TRB_3_TYPE(TRB_TYPE_RESET_ENDPOINT)
2882 		| TRB_3_SLOT(endpoint->device->slot) | TRB_3_ENDPOINT(endpoint->id + 1);
2883 	if (preserve)
2884 		trb.flags |= TRB_3_PRSV_BIT;
2885 
2886 	return DoCommand(&trb);
2887 }
2888 
2889 
2890 status_t
2891 XHCI::StopEndpoint(bool suspend, xhci_endpoint* endpoint)
2892 {
2893 	TRACE("Stop Endpoint\n");
2894 
2895 	switch (_GetEndpointState(endpoint)) {
2896 		case ENDPOINT_STATE_HALTED:
2897 			TRACE("Stop Endpoint: error, halted");
2898 			return B_DEV_STALLED;
2899 		case ENDPOINT_STATE_STOPPED:
2900 			TRACE("Stop Endpoint: already stopped");
2901 			return B_OK;
2902 		default:
2903 			break;
2904 	}
2905 
2906 	xhci_trb trb;
2907 	trb.address = 0;
2908 	trb.status = 0;
2909 	trb.flags = TRB_3_TYPE(TRB_TYPE_STOP_ENDPOINT)
2910 		| TRB_3_SLOT(endpoint->device->slot) | TRB_3_ENDPOINT(endpoint->id + 1);
2911 	if (suspend)
2912 		trb.flags |= TRB_3_SUSPEND_ENDPOINT_BIT;
2913 
2914 	return DoCommand(&trb);
2915 }
2916 
2917 
2918 status_t
2919 XHCI::SetTRDequeue(uint64 dequeue, uint16 stream, uint8 endpoint, uint8 slot)
2920 {
2921 	TRACE("Set TR Dequeue\n");
2922 	xhci_trb trb;
2923 	trb.address = dequeue | ENDPOINT_2_DCS_BIT;
2924 		// The DCS bit is copied from the address field as in ConfigureEndpoint.
2925 		// (XHCI 1.2 § 4.6.10 p142.)
2926 	trb.status = TRB_2_STREAM(stream);
2927 	trb.flags = TRB_3_TYPE(TRB_TYPE_SET_TR_DEQUEUE)
2928 		| TRB_3_SLOT(slot) | TRB_3_ENDPOINT(endpoint);
2929 
2930 	return DoCommand(&trb);
2931 }
2932 
2933 
2934 status_t
2935 XHCI::ResetDevice(uint8 slot)
2936 {
2937 	TRACE("Reset Device\n");
2938 	xhci_trb trb;
2939 	trb.address = 0;
2940 	trb.status = 0;
2941 	trb.flags = TRB_3_TYPE(TRB_TYPE_RESET_DEVICE) | TRB_3_SLOT(slot);
2942 
2943 	return DoCommand(&trb);
2944 }
2945 
2946 
2947 int32
2948 XHCI::EventThread(void* data)
2949 {
2950 	((XHCI *)data)->CompleteEvents();
2951 	return B_OK;
2952 }
2953 
2954 
2955 void
2956 XHCI::CompleteEvents()
2957 {
2958 	while (!fStopThreads) {
2959 		if (acquire_sem(fEventSem) < B_OK)
2960 			continue;
2961 
2962 		// eat up sems that have been released by multiple interrupts
2963 		int32 semCount = 0;
2964 		get_sem_count(fEventSem, &semCount);
2965 		if (semCount > 0)
2966 			acquire_sem_etc(fEventSem, semCount, B_RELATIVE_TIMEOUT, 0);
2967 
2968 		ProcessEvents();
2969 	}
2970 }
2971 
2972 
2973 void
2974 XHCI::ProcessEvents()
2975 {
2976 	// Use mutex_trylock first, in case we are in KDL.
2977 	MutexLocker locker(fEventLock, mutex_trylock(&fEventLock) == B_OK);
2978 	if (!locker.IsLocked()) {
2979 		// We failed to get the lock. This really should not happen.
2980 		TRACE_ERROR("failed to acquire event lock!\n");
2981 		return;
2982 	}
2983 
2984 	uint16 i = fEventIdx;
2985 	uint8 j = fEventCcs;
2986 	uint8 t = 2;
2987 
2988 	while (1) {
2989 		uint32 temp = B_LENDIAN_TO_HOST_INT32(fEventRing[i].flags);
2990 		uint8 event = TRB_3_TYPE_GET(temp);
2991 		TRACE("event[%u] = %u (0x%016" B_PRIx64 " 0x%08" B_PRIx32 " 0x%08"
2992 			B_PRIx32 ")\n", i, event, fEventRing[i].address,
2993 			fEventRing[i].status, B_LENDIAN_TO_HOST_INT32(fEventRing[i].flags));
2994 		uint8 k = (temp & TRB_3_CYCLE_BIT) ? 1 : 0;
2995 		if (j != k)
2996 			break;
2997 
2998 		switch (event) {
2999 		case TRB_TYPE_COMMAND_COMPLETION:
3000 			HandleCmdComplete(&fEventRing[i]);
3001 			break;
3002 		case TRB_TYPE_TRANSFER:
3003 			HandleTransferComplete(&fEventRing[i]);
3004 			break;
3005 		case TRB_TYPE_PORT_STATUS_CHANGE:
3006 			TRACE("port change detected\n");
3007 			break;
3008 		default:
3009 			TRACE_ERROR("Unhandled event = %u\n", event);
3010 			break;
3011 		}
3012 
3013 		i++;
3014 		if (i == XHCI_MAX_EVENTS) {
3015 			i = 0;
3016 			j ^= 1;
3017 			if (!--t)
3018 				break;
3019 		}
3020 	}
3021 
3022 	fEventIdx = i;
3023 	fEventCcs = j;
3024 
3025 	uint64 addr = fErst->rs_addr + i * sizeof(xhci_trb);
3026 	WriteRunReg32(XHCI_ERDP_LO(0), (uint32)addr | ERDP_BUSY);
3027 	WriteRunReg32(XHCI_ERDP_HI(0), (uint32)(addr >> 32));
3028 }
3029 
3030 
3031 int32
3032 XHCI::FinishThread(void* data)
3033 {
3034 	((XHCI *)data)->FinishTransfers();
3035 	return B_OK;
3036 }
3037 
3038 
3039 void
3040 XHCI::FinishTransfers()
3041 {
3042 	while (!fStopThreads) {
3043 		if (acquire_sem(fFinishTransfersSem) < B_OK)
3044 			continue;
3045 
3046 		// eat up sems that have been released by multiple interrupts
3047 		int32 semCount = 0;
3048 		get_sem_count(fFinishTransfersSem, &semCount);
3049 		if (semCount > 0)
3050 			acquire_sem_etc(fFinishTransfersSem, semCount, B_RELATIVE_TIMEOUT, 0);
3051 
3052 		mutex_lock(&fFinishedLock);
3053 		TRACE("finishing transfers\n");
3054 		while (fFinishedHead != NULL) {
3055 			xhci_td* td = fFinishedHead;
3056 			fFinishedHead = td->next;
3057 			td->next = NULL;
3058 			mutex_unlock(&fFinishedLock);
3059 
3060 			TRACE("finishing transfer td %p\n", td);
3061 
3062 			Transfer* transfer = td->transfer;
3063 			if (transfer == NULL) {
3064 				// No transfer? Quick way out.
3065 				FreeDescriptor(td);
3066 				mutex_lock(&fFinishedLock);
3067 				continue;
3068 			}
3069 
3070 			bool directionIn = (transfer->TransferPipe()->Direction() != Pipe::Out);
3071 
3072 			status_t callbackStatus = B_OK;
3073 			const uint8 completionCode = td->trb_completion_code;
3074 			switch (completionCode) {
3075 				case COMP_SHORT_PACKET:
3076 				case COMP_SUCCESS:
3077 					callbackStatus = B_OK;
3078 					break;
3079 				case COMP_DATA_BUFFER:
3080 					callbackStatus = directionIn ? B_DEV_DATA_OVERRUN
3081 						: B_DEV_DATA_UNDERRUN;
3082 					break;
3083 				case COMP_BABBLE:
3084 					callbackStatus = directionIn ? B_DEV_FIFO_OVERRUN
3085 						: B_DEV_FIFO_UNDERRUN;
3086 					break;
3087 				case COMP_USB_TRANSACTION:
3088 					callbackStatus = B_DEV_CRC_ERROR;
3089 					break;
3090 				case COMP_STALL:
3091 					callbackStatus = B_DEV_STALLED;
3092 					break;
3093 				default:
3094 					callbackStatus = B_DEV_STALLED;
3095 					break;
3096 			}
3097 
3098 			size_t actualLength = transfer->FragmentLength();
3099 			if (completionCode != COMP_SUCCESS) {
3100 				actualLength = td->td_transferred;
3101 				if (td->td_transferred == -1)
3102 					actualLength = transfer->FragmentLength() - td->trb_left;
3103 				TRACE("transfer not successful, actualLength=%" B_PRIuSIZE "\n",
3104 					actualLength);
3105 			}
3106 
3107 			usb_isochronous_data* isochronousData = transfer->IsochronousData();
3108 			if (isochronousData != NULL) {
3109 				size_t packetSize = transfer->DataLength()
3110 						/ isochronousData->packet_count,
3111 					left = actualLength;
3112 				for (uint32 i = 0; i < isochronousData->packet_count; i++) {
3113 					size_t size = min_c(packetSize, left);
3114 					isochronousData->packet_descriptors[i].actual_length = size;
3115 					isochronousData->packet_descriptors[i].status = (size > 0)
3116 						? B_OK : B_DEV_FIFO_UNDERRUN;
3117 					left -= size;
3118  				}
3119  			}
3120 
3121 			if (callbackStatus == B_OK && directionIn && actualLength > 0) {
3122 				TRACE("copying in iov count %ld\n", transfer->VectorCount());
3123 				status_t status = transfer->PrepareKernelAccess();
3124 				if (status == B_OK) {
3125 					ReadDescriptor(td, transfer->Vector(),
3126 						transfer->VectorCount(), transfer->IsPhysical());
3127 				} else {
3128 					callbackStatus = status;
3129 				}
3130 			}
3131 
3132 			FreeDescriptor(td);
3133 
3134 			// this transfer may still have data left
3135 			bool finished = true;
3136 			transfer->AdvanceByFragment(actualLength);
3137 			if (completionCode == COMP_SUCCESS
3138 					&& transfer->FragmentLength() > 0) {
3139 				TRACE("still %" B_PRIuSIZE " bytes left on transfer\n",
3140 					transfer->FragmentLength());
3141 				callbackStatus = SubmitTransfer(transfer);
3142 				finished = (callbackStatus != B_OK);
3143 			}
3144 			if (finished) {
3145 				// The actualLength was already handled in AdvanceByFragment.
3146 				transfer->Finished(callbackStatus, 0);
3147 				delete transfer;
3148 			}
3149 
3150 			mutex_lock(&fFinishedLock);
3151 		}
3152 		mutex_unlock(&fFinishedLock);
3153 	}
3154 }
3155 
3156 
3157 inline void
3158 XHCI::WriteOpReg(uint32 reg, uint32 value)
3159 {
3160 	*(volatile uint32 *)(fRegisters + fOperationalRegisterOffset + reg) = value;
3161 }
3162 
3163 
3164 inline uint32
3165 XHCI::ReadOpReg(uint32 reg)
3166 {
3167 	return *(volatile uint32 *)(fRegisters + fOperationalRegisterOffset + reg);
3168 }
3169 
3170 
3171 inline status_t
3172 XHCI::WaitOpBits(uint32 reg, uint32 mask, uint32 expected)
3173 {
3174 	int loops = 0;
3175 	uint32 value = ReadOpReg(reg);
3176 	while ((value & mask) != expected) {
3177 		snooze(1000);
3178 		value = ReadOpReg(reg);
3179 		if (loops == 100) {
3180 			TRACE("delay waiting on reg 0x%" B_PRIX32 " match 0x%" B_PRIX32
3181 				" (0x%" B_PRIX32 ")\n",	reg, expected, mask);
3182 		} else if (loops > 250) {
3183 			TRACE_ERROR("timeout waiting on reg 0x%" B_PRIX32
3184 				" match 0x%" B_PRIX32 " (0x%" B_PRIX32 ")\n", reg, expected,
3185 				mask);
3186 			return B_ERROR;
3187 		}
3188 		loops++;
3189 	}
3190 	return B_OK;
3191 }
3192 
3193 
3194 inline uint32
3195 XHCI::ReadCapReg32(uint32 reg)
3196 {
3197 	return *(volatile uint32 *)(fRegisters + fCapabilityRegisterOffset + reg);
3198 }
3199 
3200 
3201 inline void
3202 XHCI::WriteCapReg32(uint32 reg, uint32 value)
3203 {
3204 	*(volatile uint32 *)(fRegisters + fCapabilityRegisterOffset + reg) = value;
3205 }
3206 
3207 
3208 inline uint32
3209 XHCI::ReadRunReg32(uint32 reg)
3210 {
3211 	return *(volatile uint32 *)(fRegisters + fRuntimeRegisterOffset + reg);
3212 }
3213 
3214 
3215 inline void
3216 XHCI::WriteRunReg32(uint32 reg, uint32 value)
3217 {
3218 	*(volatile uint32 *)(fRegisters + fRuntimeRegisterOffset + reg) = value;
3219 }
3220 
3221 
3222 inline uint32
3223 XHCI::ReadDoorReg32(uint32 reg)
3224 {
3225 	return *(volatile uint32 *)(fRegisters + fDoorbellRegisterOffset + reg);
3226 }
3227 
3228 
3229 inline void
3230 XHCI::WriteDoorReg32(uint32 reg, uint32 value)
3231 {
3232 	*(volatile uint32 *)(fRegisters + fDoorbellRegisterOffset + reg) = value;
3233 }
3234 
3235 
3236 inline addr_t
3237 XHCI::_OffsetContextAddr(addr_t p)
3238 {
3239 	if (fContextSizeShift == 1) {
3240 		// each structure is page aligned, each pointer is 32 bits aligned
3241 		uint32 offset = p & ((B_PAGE_SIZE - 1) & ~31U);
3242 		p += offset;
3243 	}
3244 	return p;
3245 }
3246 
3247 inline uint32
3248 XHCI::_ReadContext(uint32* p)
3249 {
3250 	p = (uint32*)_OffsetContextAddr((addr_t)p);
3251 	return *p;
3252 }
3253 
3254 
3255 inline void
3256 XHCI::_WriteContext(uint32* p, uint32 value)
3257 {
3258 	p = (uint32*)_OffsetContextAddr((addr_t)p);
3259 	*p = value;
3260 }
3261 
3262 
3263 inline uint64
3264 XHCI::_ReadContext(uint64* p)
3265 {
3266 	p = (uint64*)_OffsetContextAddr((addr_t)p);
3267 	return *p;
3268 }
3269 
3270 
3271 inline void
3272 XHCI::_WriteContext(uint64* p, uint64 value)
3273 {
3274 	p = (uint64*)_OffsetContextAddr((addr_t)p);
3275 	*p = value;
3276 }
3277