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