xref: /haiku/src/add-ons/kernel/busses/usb/xhci.cpp (revision 4c8e85b316c35a9161f5a1c50ad70bc91c83a76f)
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 to 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 	device->slot = slot;
1377 
1378 	device->input_ctx_area = fStack->AllocateArea((void **)&device->input_ctx,
1379 		&device->input_ctx_addr, sizeof(*device->input_ctx) << fContextSizeShift,
1380 		"XHCI input context");
1381 	if (device->input_ctx_area < B_OK) {
1382 		TRACE_ERROR("unable to create a input context area\n");
1383 		CleanupDevice(device);
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 		CleanupDevice(device);
1470 		return NULL;
1471 	}
1472 	memset(device->device_ctx, 0, sizeof(*device->device_ctx) << fContextSizeShift);
1473 
1474 	device->trb_area = fStack->AllocateArea((void **)&device->trbs,
1475 		&device->trb_addr, sizeof(xhci_trb) * (XHCI_MAX_ENDPOINTS - 1)
1476 			* XHCI_ENDPOINT_RING_SIZE, "XHCI endpoint trbs");
1477 	if (device->trb_area < B_OK) {
1478 		TRACE_ERROR("unable to create a device trbs area\n");
1479 		CleanupDevice(device);
1480 		return NULL;
1481 	}
1482 
1483 	// set up slot pointer to device context
1484 	fDcba->baseAddress[slot] = device->device_ctx_addr;
1485 
1486 	size_t maxPacketSize;
1487 	switch (speed) {
1488 	case USB_SPEED_LOWSPEED:
1489 	case USB_SPEED_FULLSPEED:
1490 		maxPacketSize = 8;
1491 		break;
1492 	case USB_SPEED_HIGHSPEED:
1493 		maxPacketSize = 64;
1494 		break;
1495 	default:
1496 		maxPacketSize = 512;
1497 		break;
1498 	}
1499 
1500 	xhci_endpoint* endpoint0 = &device->endpoints[0];
1501 	mutex_init(&endpoint0->lock, "xhci endpoint lock");
1502 	endpoint0->device = device;
1503 	endpoint0->id = 0;
1504 	endpoint0->td_head = NULL;
1505 	endpoint0->used = 0;
1506 	endpoint0->current = 0;
1507 	endpoint0->trbs = device->trbs;
1508 	endpoint0->trb_addr = device->trb_addr;
1509 
1510 	// configure the Control endpoint 0
1511 	if (ConfigureEndpoint(endpoint0, slot, 0, USB_OBJECT_CONTROL_PIPE, false,
1512 			0, maxPacketSize, speed, 0, 0) != B_OK) {
1513 		TRACE_ERROR("unable to configure default control endpoint\n");
1514 		CleanupDevice(device);
1515 		return NULL;
1516 	}
1517 
1518 	// device should get to addressed state (bsr = 0)
1519 	if (SetAddress(device->input_ctx_addr, false, slot) != B_OK) {
1520 		TRACE_ERROR("unable to set address\n");
1521 		CleanupDevice(device);
1522 		return NULL;
1523 	}
1524 
1525 	device->address = SLOT_3_DEVICE_ADDRESS_GET(_ReadContext(
1526 		&device->device_ctx->slot.dwslot3));
1527 
1528 	TRACE("device: address 0x%x state 0x%08" B_PRIx32 "\n", device->address,
1529 		SLOT_3_SLOT_STATE_GET(_ReadContext(
1530 			&device->device_ctx->slot.dwslot3)));
1531 	TRACE("endpoint0 state 0x%08" B_PRIx32 "\n",
1532 		ENDPOINT_0_STATE_GET(_ReadContext(
1533 			&device->device_ctx->endpoints[0].dwendpoint0)));
1534 
1535 	// Create a temporary pipe with the new address
1536 	ControlPipe pipe(parent);
1537 	pipe.SetControllerCookie(endpoint0);
1538 	pipe.InitCommon(device->address + 1, 0, speed, Pipe::Default, maxPacketSize, 0,
1539 		hubAddress, hubPort);
1540 
1541 	// Get the device descriptor
1542 	// Just retrieve the first 8 bytes of the descriptor -> minimum supported
1543 	// size of any device. It is enough because it includes the device type.
1544 
1545 	size_t actualLength = 0;
1546 	usb_device_descriptor deviceDescriptor;
1547 
1548 	TRACE("getting the device descriptor\n");
1549 	status_t status = pipe.SendRequest(
1550 		USB_REQTYPE_DEVICE_IN | USB_REQTYPE_STANDARD,		// type
1551 		USB_REQUEST_GET_DESCRIPTOR,							// request
1552 		USB_DESCRIPTOR_DEVICE << 8,							// value
1553 		0,													// index
1554 		8,													// length
1555 		(void *)&deviceDescriptor,							// buffer
1556 		8,													// buffer length
1557 		&actualLength);										// actual length
1558 
1559 	if (actualLength != 8) {
1560 		TRACE_ERROR("failed to get the device descriptor: %s\n",
1561 			strerror(status));
1562 		CleanupDevice(device);
1563 		return NULL;
1564 	}
1565 
1566 	TRACE("device_class: %d device_subclass %d device_protocol %d\n",
1567 		deviceDescriptor.device_class, deviceDescriptor.device_subclass,
1568 		deviceDescriptor.device_protocol);
1569 
1570 	if (speed == USB_SPEED_FULLSPEED && deviceDescriptor.max_packet_size_0 != 8) {
1571 		TRACE("Full speed device with different max packet size for Endpoint 0\n");
1572 		uint32 dwendpoint1 = _ReadContext(
1573 			&device->input_ctx->endpoints[0].dwendpoint1);
1574 		dwendpoint1 &= ~ENDPOINT_1_MAXPACKETSIZE(0xffff);
1575 		dwendpoint1 |= ENDPOINT_1_MAXPACKETSIZE(
1576 			deviceDescriptor.max_packet_size_0);
1577 		_WriteContext(&device->input_ctx->endpoints[0].dwendpoint1,
1578 			dwendpoint1);
1579 		_WriteContext(&device->input_ctx->input.dropFlags, 0);
1580 		_WriteContext(&device->input_ctx->input.addFlags, (1 << 1));
1581 		EvaluateContext(device->input_ctx_addr, device->slot);
1582 	}
1583 
1584 	Device *deviceObject = NULL;
1585 	if (deviceDescriptor.device_class == 0x09) {
1586 		TRACE("creating new Hub\n");
1587 		TRACE("getting the hub descriptor\n");
1588 		size_t actualLength = 0;
1589 		usb_hub_descriptor hubDescriptor;
1590 		status = pipe.SendRequest(
1591 			USB_REQTYPE_DEVICE_IN | USB_REQTYPE_CLASS,			// type
1592 			USB_REQUEST_GET_DESCRIPTOR,							// request
1593 			USB_DESCRIPTOR_HUB << 8,							// value
1594 			0,													// index
1595 			sizeof(usb_hub_descriptor),							// length
1596 			(void *)&hubDescriptor,								// buffer
1597 			sizeof(usb_hub_descriptor),							// buffer length
1598 			&actualLength);
1599 
1600 		if (actualLength != sizeof(usb_hub_descriptor)) {
1601 			TRACE_ERROR("error while getting the hub descriptor: %s\n",
1602 				strerror(status));
1603 			CleanupDevice(device);
1604 			return NULL;
1605 		}
1606 
1607 		uint32 dwslot0 = _ReadContext(&device->input_ctx->slot.dwslot0);
1608 		dwslot0 |= SLOT_0_HUB_BIT;
1609 		_WriteContext(&device->input_ctx->slot.dwslot0, dwslot0);
1610 		uint32 dwslot1 = _ReadContext(&device->input_ctx->slot.dwslot1);
1611 		dwslot1 |= SLOT_1_NUM_PORTS(hubDescriptor.num_ports);
1612 		_WriteContext(&device->input_ctx->slot.dwslot1, dwslot1);
1613 		if (speed == USB_SPEED_HIGHSPEED) {
1614 			uint32 dwslot2 = _ReadContext(&device->input_ctx->slot.dwslot2);
1615 			dwslot2 |= SLOT_2_TT_TIME(HUB_TTT_GET(hubDescriptor.characteristics));
1616 			_WriteContext(&device->input_ctx->slot.dwslot2, dwslot2);
1617 		}
1618 
1619 		deviceObject = new(std::nothrow) Hub(parent, hubAddress, hubPort,
1620 			deviceDescriptor, device->address + 1, speed, false, device);
1621 	} else {
1622 		TRACE("creating new device\n");
1623 		deviceObject = new(std::nothrow) Device(parent, hubAddress, hubPort,
1624 			deviceDescriptor, device->address + 1, speed, false, device);
1625 	}
1626 	if (deviceObject == NULL || deviceObject->InitCheck() != B_OK) {
1627 		if (deviceObject == NULL) {
1628 			TRACE_ERROR("no memory to allocate device\n");
1629 		} else {
1630 			TRACE_ERROR("device object failed to initialize\n");
1631 		}
1632 		CleanupDevice(device);
1633 		return NULL;
1634 	}
1635 
1636 	// We don't want to disable the default endpoint, naturally, which would
1637 	// otherwise happen when this Pipe object is destroyed.
1638 	pipe.SetControllerCookie(NULL);
1639 
1640 	TRACE("AllocateDevice() port %d slot %d\n", hubPort, slot);
1641 	return deviceObject;
1642 }
1643 
1644 
1645 void
1646 XHCI::FreeDevice(Device *usbDevice)
1647 {
1648 	xhci_device* device = (xhci_device*)usbDevice->ControllerCookie();
1649 	TRACE("FreeDevice() slot %d\n", device->slot);
1650 
1651 	// Delete the device first, so it cleans up its pipes and tells us
1652 	// what we need to destroy before we tear down our internal state.
1653 	delete usbDevice;
1654 
1655 	CleanupDevice(device);
1656 }
1657 
1658 
1659 void
1660 XHCI::CleanupDevice(xhci_device *device)
1661 {
1662 	if (device->slot != 0) {
1663 		DisableSlot(device->slot);
1664 		fDcba->baseAddress[device->slot] = 0;
1665 	}
1666 
1667 	if (device->trb_addr != 0)
1668 		delete_area(device->trb_area);
1669 	if (device->input_ctx_addr != 0)
1670 		delete_area(device->input_ctx_area);
1671 	if (device->device_ctx_addr != 0)
1672 		delete_area(device->device_ctx_area);
1673 
1674 	memset(device, 0, sizeof(xhci_device));
1675 }
1676 
1677 
1678 uint8
1679 XHCI::_GetEndpointState(xhci_endpoint* endpoint)
1680 {
1681 	struct xhci_device_ctx* device_ctx = endpoint->device->device_ctx;
1682 	return ENDPOINT_0_STATE_GET(
1683 		_ReadContext(&device_ctx->endpoints[endpoint->id].dwendpoint0));
1684 }
1685 
1686 
1687 status_t
1688 XHCI::_InsertEndpointForPipe(Pipe *pipe)
1689 {
1690 	TRACE("insert endpoint for pipe %p (%d)\n", pipe, pipe->EndpointAddress());
1691 
1692 	if (pipe->ControllerCookie() != NULL
1693 			|| pipe->Parent()->Type() != USB_OBJECT_DEVICE) {
1694 		// default pipe is already referenced
1695 		return B_OK;
1696 	}
1697 
1698 	Device* usbDevice = (Device *)pipe->Parent();
1699 	if (usbDevice->Parent() == RootObject()) {
1700 		// root hub needs no initialization
1701 		return B_OK;
1702 	}
1703 
1704 	struct xhci_device *device = (struct xhci_device *)
1705 		usbDevice->ControllerCookie();
1706 	if (device == NULL) {
1707 		panic("device is NULL\n");
1708 		return B_NO_INIT;
1709 	}
1710 
1711 	const uint8 id = (2 * pipe->EndpointAddress()
1712 		+ (pipe->Direction() != Pipe::Out ? 1 : 0)) - 1;
1713 	if (id >= XHCI_MAX_ENDPOINTS - 1)
1714 		return B_BAD_VALUE;
1715 
1716 	if (id > 0) {
1717 		uint32 devicedwslot0 = _ReadContext(&device->device_ctx->slot.dwslot0);
1718 		if (SLOT_0_NUM_ENTRIES_GET(devicedwslot0) == 1) {
1719 			uint32 inputdwslot0 = _ReadContext(&device->input_ctx->slot.dwslot0);
1720 			inputdwslot0 &= ~(SLOT_0_NUM_ENTRIES(0x1f));
1721 			inputdwslot0 |= SLOT_0_NUM_ENTRIES(XHCI_MAX_ENDPOINTS - 1);
1722 			_WriteContext(&device->input_ctx->slot.dwslot0, inputdwslot0);
1723 			EvaluateContext(device->input_ctx_addr, device->slot);
1724 		}
1725 
1726 		xhci_endpoint* endpoint = &device->endpoints[id];
1727 		mutex_init(&endpoint->lock, "xhci endpoint lock");
1728 		MutexLocker endpointLocker(endpoint->lock);
1729 
1730 		endpoint->device = device;
1731 		endpoint->id = id;
1732 		endpoint->td_head = NULL;
1733 		endpoint->used = 0;
1734 		endpoint->current = 0;
1735 
1736 		endpoint->trbs = device->trbs + id * XHCI_ENDPOINT_RING_SIZE;
1737 		endpoint->trb_addr = device->trb_addr
1738 			+ id * XHCI_ENDPOINT_RING_SIZE * sizeof(xhci_trb);
1739 		memset(endpoint->trbs, 0,
1740 			sizeof(xhci_trb) * XHCI_ENDPOINT_RING_SIZE);
1741 
1742 		TRACE("insert endpoint for pipe: trbs, device %p endpoint %p\n",
1743 			device->trbs, endpoint->trbs);
1744 		TRACE("insert endpoint for pipe: trb_addr, device 0x%" B_PRIxPHYSADDR
1745 			" endpoint 0x%" B_PRIxPHYSADDR "\n", device->trb_addr,
1746 			endpoint->trb_addr);
1747 
1748 		const uint8 endpointNum = id + 1;
1749 
1750 		status_t status = ConfigureEndpoint(endpoint, device->slot, id, pipe->Type(),
1751 			pipe->Direction() == Pipe::In, pipe->Interval(), pipe->MaxPacketSize(),
1752 			usbDevice->Speed(), pipe->MaxBurst(), pipe->BytesPerInterval());
1753 		if (status != B_OK) {
1754 			TRACE_ERROR("unable to configure endpoint: %s\n", strerror(status));
1755 			return status;
1756 		}
1757 
1758 		_WriteContext(&device->input_ctx->input.dropFlags, 0);
1759 		_WriteContext(&device->input_ctx->input.addFlags,
1760 			(1 << endpointNum) | (1 << 0));
1761 
1762 		ConfigureEndpoint(device->input_ctx_addr, false, device->slot);
1763 
1764 		TRACE("device: address 0x%x state 0x%08" B_PRIx32 "\n",
1765 			device->address, SLOT_3_SLOT_STATE_GET(_ReadContext(
1766 				&device->device_ctx->slot.dwslot3)));
1767 		TRACE("endpoint[0] state 0x%08" B_PRIx32 "\n",
1768 			ENDPOINT_0_STATE_GET(_ReadContext(
1769 				&device->device_ctx->endpoints[0].dwendpoint0)));
1770 		TRACE("endpoint[%d] state 0x%08" B_PRIx32 "\n", id,
1771 			ENDPOINT_0_STATE_GET(_ReadContext(
1772 				&device->device_ctx->endpoints[id].dwendpoint0)));
1773 	}
1774 	pipe->SetControllerCookie(&device->endpoints[id]);
1775 
1776 	return B_OK;
1777 }
1778 
1779 
1780 status_t
1781 XHCI::_RemoveEndpointForPipe(Pipe *pipe)
1782 {
1783 	TRACE("remove endpoint for pipe %p (%d)\n", pipe, pipe->EndpointAddress());
1784 
1785 	if (pipe->Parent()->Type() != USB_OBJECT_DEVICE)
1786 		return B_OK;
1787 	Device* usbDevice = (Device *)pipe->Parent();
1788 	if (usbDevice->Parent() == RootObject())
1789 		return B_BAD_VALUE;
1790 
1791 	xhci_endpoint *endpoint = (xhci_endpoint *)pipe->ControllerCookie();
1792 	if (endpoint == NULL || endpoint->trbs == NULL)
1793 		return B_NO_INIT;
1794 
1795 	pipe->SetControllerCookie(NULL);
1796 
1797 	if (endpoint->id > 0) {
1798 		xhci_device *device = endpoint->device;
1799 		uint8 epNumber = endpoint->id + 1;
1800 		StopEndpoint(true, endpoint);
1801 
1802 		mutex_lock(&endpoint->lock);
1803 
1804 		// See comment in CancelQueuedTransfers.
1805 		xhci_td* td;
1806 		while ((td = endpoint->td_head) != NULL) {
1807 			endpoint->td_head = endpoint->td_head->next;
1808 			FreeDescriptor(td);
1809 		}
1810 
1811 		mutex_destroy(&endpoint->lock);
1812 		memset(endpoint, 0, sizeof(xhci_endpoint));
1813 
1814 		_WriteContext(&device->input_ctx->input.dropFlags, (1 << epNumber));
1815 		_WriteContext(&device->input_ctx->input.addFlags, (1 << 0));
1816 
1817 		// The Deconfigure bit in the Configure Endpoint command indicates
1818 		// that *all* endpoints are to be deconfigured, and not just the ones
1819 		// specified in the context flags. (XHCI 1.2 § 4.6.6 p115.)
1820 		ConfigureEndpoint(device->input_ctx_addr, false, device->slot);
1821 	}
1822 
1823 	return B_OK;
1824 }
1825 
1826 
1827 status_t
1828 XHCI::_LinkDescriptorForPipe(xhci_td *descriptor, xhci_endpoint *endpoint)
1829 {
1830 	TRACE("link descriptor for pipe\n");
1831 
1832 	// Use mutex_trylock first, in case we are in KDL.
1833 	MutexLocker endpointLocker(&endpoint->lock, mutex_trylock(&endpoint->lock) == B_OK);
1834 
1835 	// "used" refers to the number of currently linked TDs, not the number of
1836 	// used TRBs on the ring (we use 2 TRBs on the ring per transfer.)
1837 	if (endpoint->used >= (XHCI_MAX_TRANSFERS - 1)) {
1838 		TRACE_ERROR("link descriptor for pipe: max transfers count exceeded\n");
1839 		return B_BAD_VALUE;
1840 	}
1841 
1842 	// We do not support queuing other transfers in tandem with a fragmented one.
1843 	if (endpoint->td_head != NULL && endpoint->td_head->transfer != NULL
1844 			&& endpoint->td_head->transfer->IsFragmented()) {
1845 		TRACE_ERROR("cannot submit transfer: a fragmented transfer is queued\n");
1846 		return B_DEV_RESOURCE_CONFLICT;
1847 	}
1848 
1849 	endpoint->used++;
1850 	descriptor->next = endpoint->td_head;
1851 	endpoint->td_head = descriptor;
1852 
1853 	const uint8 current = endpoint->current,
1854 		eventdata = current + 1;
1855 	uint8 next = eventdata + 1;
1856 
1857 	TRACE("link descriptor for pipe: current %d, next %d\n", current, next);
1858 
1859 	// Add a Link TRB to the end of the descriptor.
1860 	phys_addr_t addr = endpoint->trb_addr + eventdata * sizeof(xhci_trb);
1861 	descriptor->trbs[descriptor->trb_used].address = addr;
1862 	descriptor->trbs[descriptor->trb_used].status = TRB_2_IRQ(0);
1863 	descriptor->trbs[descriptor->trb_used].flags = TRB_3_TYPE(TRB_TYPE_LINK)
1864 		| TRB_3_CHAIN_BIT | TRB_3_CYCLE_BIT;
1865 		// It is specified that (XHCI 1.2 § 4.12.3 Note 2 p251) if the TRB
1866 		// following one with the ENT bit set is a Link TRB, the Link TRB
1867 		// shall be evaluated *and* the subsequent TRB shall be. Thus a
1868 		// TRB_3_ENT_BIT is unnecessary here; and from testing seems to
1869 		// break all transfers on a (very) small number of controllers.
1870 
1871 #if !B_HOST_IS_LENDIAN
1872 	// Convert endianness.
1873 	for (uint32 i = 0; i <= descriptor->trb_used; i++) {
1874 		descriptor->trbs[i].address =
1875 			B_HOST_TO_LENDIAN_INT64(descriptor->trbs[i].address);
1876 		descriptor->trbs[i].status =
1877 			B_HOST_TO_LENDIAN_INT32(descriptor->trbs[i].status);
1878 		descriptor->trbs[i].flags =
1879 			B_HOST_TO_LENDIAN_INT32(descriptor->trbs[i].flags);
1880 	}
1881 #endif
1882 
1883 	// Link the descriptor.
1884 	endpoint->trbs[current].address =
1885 		B_HOST_TO_LENDIAN_INT64(descriptor->trb_addr);
1886 	endpoint->trbs[current].status =
1887 		B_HOST_TO_LENDIAN_INT32(TRB_2_IRQ(0));
1888 	endpoint->trbs[current].flags =
1889 		B_HOST_TO_LENDIAN_INT32(TRB_3_TYPE(TRB_TYPE_LINK));
1890 
1891 	// Set up the Event Data TRB (XHCI 1.2 § 4.11.5.2 p230.)
1892 	//
1893 	// We do this on the main ring for two reasons: first, to avoid a small
1894 	// potential race between the interrupt and the controller evaluating
1895 	// the link TRB to get back onto the ring; and second, because many
1896 	// controllers throw errors if the target of a Link TRB is not valid
1897 	// (i.e. does not have its Cycle Bit set.)
1898 	//
1899 	// We also set the "address" field, which the controller will copy
1900 	// verbatim into the TRB it posts to the event ring, to be the last
1901 	// "real" TRB in the TD; this will allow us to determine what transfer
1902 	// the resulting Transfer Event TRB refers to.
1903 	endpoint->trbs[eventdata].address =
1904 		B_HOST_TO_LENDIAN_INT64(descriptor->trb_addr
1905 			+ (descriptor->trb_used - 1) * sizeof(xhci_trb));
1906 	endpoint->trbs[eventdata].status =
1907 		B_HOST_TO_LENDIAN_INT32(TRB_2_IRQ(0));
1908 	endpoint->trbs[eventdata].flags =
1909 		B_HOST_TO_LENDIAN_INT32(TRB_3_TYPE(TRB_TYPE_EVENT_DATA)
1910 			| TRB_3_IOC_BIT | TRB_3_CYCLE_BIT);
1911 
1912 	if (next == (XHCI_ENDPOINT_RING_SIZE - 1)) {
1913 		// We always use 2 TRBs per _Link..() call, so if "next" is the last
1914 		// TRB in the ring, we need to generate a link TRB at "next", and
1915 		// then wrap it to 0.
1916 		endpoint->trbs[next].address =
1917 			B_HOST_TO_LENDIAN_INT64(endpoint->trb_addr);
1918 		endpoint->trbs[next].status =
1919 			B_HOST_TO_LENDIAN_INT32(TRB_2_IRQ(0));
1920 		endpoint->trbs[next].flags =
1921 			B_HOST_TO_LENDIAN_INT32(TRB_3_TYPE(TRB_TYPE_LINK) | TRB_3_CYCLE_BIT);
1922 
1923 		next = 0;
1924 	}
1925 
1926 	endpoint->trbs[next].address = 0;
1927 	endpoint->trbs[next].status = 0;
1928 	endpoint->trbs[next].flags = 0;
1929 
1930 	// Everything is ready, so write the cycle bit.
1931 	endpoint->trbs[current].flags |= B_HOST_TO_LENDIAN_INT32(TRB_3_CYCLE_BIT);
1932 
1933 	TRACE("_LinkDescriptorForPipe pCurrent %p phys 0x%" B_PRIxPHYSADDR
1934 		" 0x%" B_PRIxPHYSADDR " 0x%08" B_PRIx32 "\n", &endpoint->trbs[current],
1935 		endpoint->trb_addr + current * sizeof(struct xhci_trb),
1936 		endpoint->trbs[current].address,
1937 		B_LENDIAN_TO_HOST_INT32(endpoint->trbs[current].flags));
1938 
1939 	endpoint->current = next;
1940 	endpointLocker.Unlock();
1941 
1942 	TRACE("Endpoint status 0x%08" B_PRIx32 " 0x%08" B_PRIx32 " 0x%016" B_PRIx64 "\n",
1943 		_ReadContext(&endpoint->device->device_ctx->endpoints[endpoint->id].dwendpoint0),
1944 		_ReadContext(&endpoint->device->device_ctx->endpoints[endpoint->id].dwendpoint1),
1945 		_ReadContext(&endpoint->device->device_ctx->endpoints[endpoint->id].qwendpoint2));
1946 
1947 	Ring(endpoint->device->slot, endpoint->id + 1);
1948 
1949 	TRACE("Endpoint status 0x%08" B_PRIx32 " 0x%08" B_PRIx32 " 0x%016" B_PRIx64 "\n",
1950 		_ReadContext(&endpoint->device->device_ctx->endpoints[endpoint->id].dwendpoint0),
1951 		_ReadContext(&endpoint->device->device_ctx->endpoints[endpoint->id].dwendpoint1),
1952 		_ReadContext(&endpoint->device->device_ctx->endpoints[endpoint->id].qwendpoint2));
1953 
1954 	return B_OK;
1955 }
1956 
1957 
1958 status_t
1959 XHCI::_UnlinkDescriptorForPipe(xhci_td *descriptor, xhci_endpoint *endpoint)
1960 {
1961 	TRACE("unlink descriptor for pipe\n");
1962 	// We presume that the caller has already locked or owns the endpoint.
1963 
1964 	endpoint->used--;
1965 	if (descriptor == endpoint->td_head) {
1966 		endpoint->td_head = descriptor->next;
1967 		descriptor->next = NULL;
1968 		return B_OK;
1969 	} else {
1970 		for (xhci_td *td = endpoint->td_head; td->next != NULL; td = td->next) {
1971 			if (td->next == descriptor) {
1972 				td->next = descriptor->next;
1973 				descriptor->next = NULL;
1974 				return B_OK;
1975 			}
1976 		}
1977 	}
1978 
1979 	endpoint->used++;
1980 	return B_ERROR;
1981 }
1982 
1983 
1984 status_t
1985 XHCI::ConfigureEndpoint(xhci_endpoint* ep, uint8 slot, uint8 number, uint8 type,
1986 	bool directionIn, uint16 interval, uint16 maxPacketSize, usb_speed speed,
1987 	uint8 maxBurst, uint16 bytesPerInterval)
1988 {
1989 	struct xhci_device* device = &fDevices[slot];
1990 
1991 	uint32 dwendpoint0 = 0;
1992 	uint32 dwendpoint1 = 0;
1993 	uint64 qwendpoint2 = 0;
1994 	uint32 dwendpoint4 = 0;
1995 
1996 	// Compute and assign the endpoint type. (XHCI 1.2 § 6.2.3 Table 6-9 p452.)
1997 	uint8 xhciType = 4;
1998 	if ((type & USB_OBJECT_INTERRUPT_PIPE) != 0)
1999 		xhciType = 3;
2000 	if ((type & USB_OBJECT_BULK_PIPE) != 0)
2001 		xhciType = 2;
2002 	if ((type & USB_OBJECT_ISO_PIPE) != 0)
2003 		xhciType = 1;
2004 	xhciType |= directionIn ? (1 << 2) : 0;
2005 	dwendpoint1 |= ENDPOINT_1_EPTYPE(xhciType);
2006 
2007 	// Compute and assign interval. (XHCI 1.2 § 6.2.3.6 p456.)
2008 	uint16 calcInterval;
2009 	if ((type & USB_OBJECT_BULK_PIPE) != 0
2010 			|| (type & USB_OBJECT_CONTROL_PIPE) != 0) {
2011 		// Bulk and Control endpoints never issue NAKs.
2012 		calcInterval = 0;
2013 	} else {
2014 		switch (speed) {
2015 		case USB_SPEED_FULLSPEED:
2016 			if ((type & USB_OBJECT_ISO_PIPE) != 0) {
2017 				// Convert 1-16 into 3-18.
2018 				calcInterval = min_c(max_c(interval, 1), 16) + 2;
2019 				break;
2020 			}
2021 
2022 			// fall through
2023 		case USB_SPEED_LOWSPEED: {
2024 			// Convert 1ms-255ms into 3-10.
2025 
2026 			// Find the index of the highest set bit in "interval".
2027 			uint32 temp = min_c(max_c(interval, 1), 255);
2028 			for (calcInterval = 0; temp != 1; calcInterval++)
2029 				temp = temp >> 1;
2030 			calcInterval += 3;
2031 			break;
2032 		}
2033 
2034 		case USB_SPEED_HIGHSPEED:
2035 		case USB_SPEED_SUPERSPEED:
2036 		default:
2037 			// Convert 1-16 into 0-15.
2038 			calcInterval = min_c(max_c(interval, 1), 16) - 1;
2039 			break;
2040 		}
2041 	}
2042 	dwendpoint0 |= ENDPOINT_0_INTERVAL(calcInterval);
2043 
2044 	// For non-isochronous endpoints, we want the controller to retry failed
2045 	// transfers, if possible. (XHCI 1.2 § 4.10.2.3 p197.)
2046 	if ((type & USB_OBJECT_ISO_PIPE) == 0)
2047 		dwendpoint1 |= ENDPOINT_1_CERR(3);
2048 
2049 	// Assign maximum burst size. For USB3 devices this is passed in; for
2050 	// all other devices we compute it. (XHCI 1.2 § 4.8.2 p161.)
2051 	if (speed == USB_SPEED_HIGHSPEED && (type & (USB_OBJECT_INTERRUPT_PIPE
2052 			| USB_OBJECT_ISO_PIPE)) != 0) {
2053 		maxBurst = (maxPacketSize & 0x1800) >> 11;
2054 	} else if (speed != USB_SPEED_SUPERSPEED) {
2055 		maxBurst = 0;
2056 	}
2057 	dwendpoint1 |= ENDPOINT_1_MAXBURST(maxBurst);
2058 
2059 	// Assign maximum packet size, set the ring address, and set the
2060 	// "Dequeue Cycle State" bit. (XHCI 1.2 § 6.2.3 Table 6-10 p453.)
2061 	dwendpoint1 |= ENDPOINT_1_MAXPACKETSIZE(maxPacketSize);
2062 	qwendpoint2 |= ENDPOINT_2_DCS_BIT | ep->trb_addr;
2063 
2064 	// The Max Burst Payload is the number of bytes moved by a
2065 	// maximum sized burst. (XHCI 1.2 § 4.11.7.1 p236.)
2066 	ep->max_burst_payload = (maxBurst + 1) * maxPacketSize;
2067 	if (ep->max_burst_payload == 0) {
2068 		TRACE_ERROR("ConfigureEndpoint() failed invalid max_burst_payload\n");
2069 		return B_BAD_VALUE;
2070 	}
2071 
2072 	// Assign average TRB length.
2073 	if ((type & USB_OBJECT_CONTROL_PIPE) != 0) {
2074 		// Control pipes are a special case, as they rarely have
2075 		// outbound transfers of any substantial size.
2076 		dwendpoint4 |= ENDPOINT_4_AVGTRBLENGTH(8);
2077 	} else if ((type & USB_OBJECT_ISO_PIPE) != 0) {
2078 		// Isochronous pipes are another special case: the TRB size will be
2079 		// one packet (which is normally smaller than the max packet size,
2080 		// but we don't know what it is here.)
2081 		dwendpoint4 |= ENDPOINT_4_AVGTRBLENGTH(maxPacketSize);
2082 	} else {
2083 		// Under all other circumstances, we put max_burst_payload in a TRB.
2084 		dwendpoint4 |= ENDPOINT_4_AVGTRBLENGTH(ep->max_burst_payload);
2085 	}
2086 
2087 	// Assign maximum ESIT payload. (XHCI 1.2 § 4.14.2 p259.)
2088 	if ((type & (USB_OBJECT_INTERRUPT_PIPE | USB_OBJECT_ISO_PIPE)) != 0) {
2089 		// TODO: For SuperSpeedPlus endpoints, there is yet another descriptor
2090 		// for isochronous endpoints that specifies the maximum ESIT payload.
2091 		// We don't fetch this yet, so just fall back to the USB2 computation
2092 		// method if bytesPerInterval is 0.
2093 		if (speed == USB_SPEED_SUPERSPEED && bytesPerInterval != 0)
2094 			dwendpoint4 |= ENDPOINT_4_MAXESITPAYLOAD(bytesPerInterval);
2095 		else if (speed >= USB_SPEED_HIGHSPEED)
2096 			dwendpoint4 |= ENDPOINT_4_MAXESITPAYLOAD((maxBurst + 1) * maxPacketSize);
2097 	}
2098 
2099 	_WriteContext(&device->input_ctx->endpoints[number].dwendpoint0,
2100 		dwendpoint0);
2101 	_WriteContext(&device->input_ctx->endpoints[number].dwendpoint1,
2102 		dwendpoint1);
2103 	_WriteContext(&device->input_ctx->endpoints[number].qwendpoint2,
2104 		qwendpoint2);
2105 	_WriteContext(&device->input_ctx->endpoints[number].dwendpoint4,
2106 		dwendpoint4);
2107 
2108 	TRACE("endpoint 0x%" B_PRIx32 " 0x%" B_PRIx32 " 0x%" B_PRIx64 " 0x%"
2109 		B_PRIx32 "\n",
2110 		_ReadContext(&device->input_ctx->endpoints[number].dwendpoint0),
2111 		_ReadContext(&device->input_ctx->endpoints[number].dwendpoint1),
2112 		_ReadContext(&device->input_ctx->endpoints[number].qwendpoint2),
2113 		_ReadContext(&device->input_ctx->endpoints[number].dwendpoint4));
2114 
2115 	return B_OK;
2116 }
2117 
2118 
2119 status_t
2120 XHCI::GetPortSpeed(uint8 index, usb_speed* speed)
2121 {
2122 	if (index >= fPortCount)
2123 		return B_BAD_INDEX;
2124 
2125 	uint32 portStatus = ReadOpReg(XHCI_PORTSC(index));
2126 
2127 	switch (PS_SPEED_GET(portStatus)) {
2128 	case 2:
2129 		*speed = USB_SPEED_LOWSPEED;
2130 		break;
2131 	case 1:
2132 		*speed = USB_SPEED_FULLSPEED;
2133 		break;
2134 	case 3:
2135 		*speed = USB_SPEED_HIGHSPEED;
2136 		break;
2137 	case 4:
2138 		*speed = USB_SPEED_SUPERSPEED;
2139 		break;
2140 	default:
2141 		TRACE_ALWAYS("nonstandard port speed %" B_PRId32 ", assuming SuperSpeed\n",
2142 			PS_SPEED_GET(portStatus));
2143 		*speed = USB_SPEED_SUPERSPEED;
2144 		break;
2145 	}
2146 
2147 	return B_OK;
2148 }
2149 
2150 
2151 status_t
2152 XHCI::GetPortStatus(uint8 index, usb_port_status* status)
2153 {
2154 	if (index >= fPortCount)
2155 		return B_BAD_INDEX;
2156 
2157 	status->status = status->change = 0;
2158 	uint32 portStatus = ReadOpReg(XHCI_PORTSC(index));
2159 	TRACE("port %" B_PRId8 " status=0x%08" B_PRIx32 "\n", index, portStatus);
2160 
2161 	// build the status
2162 	switch (PS_SPEED_GET(portStatus)) {
2163 	case 3:
2164 		status->status |= PORT_STATUS_HIGH_SPEED;
2165 		break;
2166 	case 2:
2167 		status->status |= PORT_STATUS_LOW_SPEED;
2168 		break;
2169 	default:
2170 		break;
2171 	}
2172 
2173 	if (portStatus & PS_CCS)
2174 		status->status |= PORT_STATUS_CONNECTION;
2175 	if (portStatus & PS_PED)
2176 		status->status |= PORT_STATUS_ENABLE;
2177 	if (portStatus & PS_OCA)
2178 		status->status |= PORT_STATUS_OVER_CURRENT;
2179 	if (portStatus & PS_PR)
2180 		status->status |= PORT_STATUS_RESET;
2181 	if (portStatus & PS_PP) {
2182 		if (fPortSpeeds[index] == USB_SPEED_SUPERSPEED)
2183 			status->status |= PORT_STATUS_SS_POWER;
2184 		else
2185 			status->status |= PORT_STATUS_POWER;
2186 	}
2187 
2188 	// build the change
2189 	if (portStatus & PS_CSC)
2190 		status->change |= PORT_STATUS_CONNECTION;
2191 	if (portStatus & PS_PEC)
2192 		status->change |= PORT_STATUS_ENABLE;
2193 	if (portStatus & PS_OCC)
2194 		status->change |= PORT_STATUS_OVER_CURRENT;
2195 	if (portStatus & PS_PRC)
2196 		status->change |= PORT_STATUS_RESET;
2197 
2198 	if (fPortSpeeds[index] == USB_SPEED_SUPERSPEED) {
2199 		if (portStatus & PS_PLC)
2200 			status->change |= PORT_CHANGE_LINK_STATE;
2201 		if (portStatus & PS_WRC)
2202 			status->change |= PORT_CHANGE_BH_PORT_RESET;
2203 	}
2204 
2205 	return B_OK;
2206 }
2207 
2208 
2209 status_t
2210 XHCI::SetPortFeature(uint8 index, uint16 feature)
2211 {
2212 	TRACE("set port feature index %u feature %u\n", index, feature);
2213 	if (index >= fPortCount)
2214 		return B_BAD_INDEX;
2215 
2216 	uint32 portRegister = XHCI_PORTSC(index);
2217 	uint32 portStatus = ReadOpReg(portRegister) & ~PS_CLEAR;
2218 
2219 	switch (feature) {
2220 	case PORT_SUSPEND:
2221 		if ((portStatus & PS_PED) == 0 || (portStatus & PS_PR)
2222 			|| (portStatus & PS_PLS_MASK) >= PS_XDEV_U3) {
2223 			TRACE_ERROR("USB core suspending device not in U0/U1/U2.\n");
2224 			return B_BAD_VALUE;
2225 		}
2226 		portStatus &= ~PS_PLS_MASK;
2227 		WriteOpReg(portRegister, portStatus | PS_LWS | PS_XDEV_U3);
2228 		break;
2229 
2230 	case PORT_RESET:
2231 		WriteOpReg(portRegister, portStatus | PS_PR);
2232 		break;
2233 
2234 	case PORT_POWER:
2235 		WriteOpReg(portRegister, portStatus | PS_PP);
2236 		break;
2237 	default:
2238 		return B_BAD_VALUE;
2239 	}
2240 	ReadOpReg(portRegister);
2241 	return B_OK;
2242 }
2243 
2244 
2245 status_t
2246 XHCI::ClearPortFeature(uint8 index, uint16 feature)
2247 {
2248 	TRACE("clear port feature index %u feature %u\n", index, feature);
2249 	if (index >= fPortCount)
2250 		return B_BAD_INDEX;
2251 
2252 	uint32 portRegister = XHCI_PORTSC(index);
2253 	uint32 portStatus = ReadOpReg(portRegister) & ~PS_CLEAR;
2254 
2255 	switch (feature) {
2256 	case PORT_SUSPEND:
2257 		portStatus = ReadOpReg(portRegister);
2258 		if (portStatus & PS_PR)
2259 			return B_BAD_VALUE;
2260 		if (portStatus & PS_XDEV_U3) {
2261 			if ((portStatus & PS_PED) == 0)
2262 				return B_BAD_VALUE;
2263 			portStatus &= ~PS_PLS_MASK;
2264 			WriteOpReg(portRegister, portStatus | PS_XDEV_U0 | PS_LWS);
2265 		}
2266 		break;
2267 	case PORT_ENABLE:
2268 		WriteOpReg(portRegister, portStatus | PS_PED);
2269 		break;
2270 	case PORT_POWER:
2271 		WriteOpReg(portRegister, portStatus & ~PS_PP);
2272 		break;
2273 	case C_PORT_CONNECTION:
2274 		WriteOpReg(portRegister, portStatus | PS_CSC);
2275 		break;
2276 	case C_PORT_ENABLE:
2277 		WriteOpReg(portRegister, portStatus | PS_PEC);
2278 		break;
2279 	case C_PORT_OVER_CURRENT:
2280 		WriteOpReg(portRegister, portStatus | PS_OCC);
2281 		break;
2282 	case C_PORT_RESET:
2283 		WriteOpReg(portRegister, portStatus | PS_PRC);
2284 		break;
2285 	case C_PORT_BH_PORT_RESET:
2286 		WriteOpReg(portRegister, portStatus | PS_WRC);
2287 		break;
2288 	case C_PORT_LINK_STATE:
2289 		WriteOpReg(portRegister, portStatus | PS_PLC);
2290 		break;
2291 	default:
2292 		return B_BAD_VALUE;
2293 	}
2294 
2295 	ReadOpReg(portRegister);
2296 	return B_OK;
2297 }
2298 
2299 
2300 status_t
2301 XHCI::ControllerHalt()
2302 {
2303 	// Mask off run state
2304 	WriteOpReg(XHCI_CMD, ReadOpReg(XHCI_CMD) & ~CMD_RUN);
2305 
2306 	// wait for shutdown state
2307 	if (WaitOpBits(XHCI_STS, STS_HCH, STS_HCH) != B_OK) {
2308 		TRACE_ERROR("HCH shutdown timeout\n");
2309 		return B_ERROR;
2310 	}
2311 	return B_OK;
2312 }
2313 
2314 
2315 status_t
2316 XHCI::ControllerReset()
2317 {
2318 	TRACE("ControllerReset() cmd: 0x%" B_PRIx32 " sts: 0x%" B_PRIx32 "\n",
2319 		ReadOpReg(XHCI_CMD), ReadOpReg(XHCI_STS));
2320 	WriteOpReg(XHCI_CMD, ReadOpReg(XHCI_CMD) | CMD_HCRST);
2321 
2322 	if (WaitOpBits(XHCI_CMD, CMD_HCRST, 0) != B_OK) {
2323 		TRACE_ERROR("ControllerReset() failed CMD_HCRST\n");
2324 		return B_ERROR;
2325 	}
2326 
2327 	if (WaitOpBits(XHCI_STS, STS_CNR, 0) != B_OK) {
2328 		TRACE_ERROR("ControllerReset() failed STS_CNR\n");
2329 		return B_ERROR;
2330 	}
2331 
2332 	return B_OK;
2333 }
2334 
2335 
2336 int32
2337 XHCI::InterruptHandler(void* data)
2338 {
2339 	return ((XHCI*)data)->Interrupt();
2340 }
2341 
2342 
2343 int32
2344 XHCI::Interrupt()
2345 {
2346 	SpinLocker _(&fSpinlock);
2347 
2348 	uint32 status = ReadOpReg(XHCI_STS);
2349 	uint32 temp = ReadRunReg32(XHCI_IMAN(0));
2350 	WriteOpReg(XHCI_STS, status);
2351 	WriteRunReg32(XHCI_IMAN(0), temp);
2352 
2353 	int32 result = B_HANDLED_INTERRUPT;
2354 
2355 	if ((status & STS_HCH) != 0) {
2356 		TRACE_ERROR("Host Controller halted\n");
2357 		return result;
2358 	}
2359 	if ((status & STS_HSE) != 0) {
2360 		TRACE_ERROR("Host System Error\n");
2361 		return result;
2362 	}
2363 	if ((status & STS_HCE) != 0) {
2364 		TRACE_ERROR("Host Controller Error\n");
2365 		return result;
2366 	}
2367 
2368 	if ((status & STS_EINT) == 0) {
2369 		TRACE("STS: 0x%" B_PRIx32 " IRQ_PENDING: 0x%" B_PRIx32 "\n",
2370 			status, temp);
2371 		return B_UNHANDLED_INTERRUPT;
2372 	}
2373 
2374 	TRACE("Event Interrupt\n");
2375 	release_sem_etc(fEventSem, 1, B_DO_NOT_RESCHEDULE);
2376 	return B_INVOKE_SCHEDULER;
2377 }
2378 
2379 
2380 void
2381 XHCI::Ring(uint8 slot, uint8 endpoint)
2382 {
2383 	TRACE("Ding Dong! slot:%d endpoint %d\n", slot, endpoint)
2384 	if ((slot == 0 && endpoint > 0) || (slot > 0 && endpoint == 0))
2385 		panic("Ring() invalid slot/endpoint combination\n");
2386 	if (slot > fSlotCount || endpoint >= XHCI_MAX_ENDPOINTS)
2387 		panic("Ring() invalid slot or endpoint\n");
2388 
2389 	WriteDoorReg32(XHCI_DOORBELL(slot), XHCI_DOORBELL_TARGET(endpoint)
2390 		| XHCI_DOORBELL_STREAMID(0));
2391 	ReadDoorReg32(XHCI_DOORBELL(slot));
2392 		// Flush PCI writes
2393 }
2394 
2395 
2396 void
2397 XHCI::QueueCommand(xhci_trb* trb)
2398 {
2399 	uint8 i, j;
2400 	uint32 temp;
2401 
2402 	i = fCmdIdx;
2403 	j = fCmdCcs;
2404 
2405 	TRACE("command[%u] = %" B_PRId32 " (0x%016" B_PRIx64 ", 0x%08" B_PRIx32
2406 		", 0x%08" B_PRIx32 ")\n", i, TRB_3_TYPE_GET(trb->flags), trb->address,
2407 		trb->status, trb->flags);
2408 
2409 	fCmdRing[i].address = trb->address;
2410 	fCmdRing[i].status = trb->status;
2411 	temp = trb->flags;
2412 
2413 	if (j)
2414 		temp |= TRB_3_CYCLE_BIT;
2415 	else
2416 		temp &= ~TRB_3_CYCLE_BIT;
2417 	temp &= ~TRB_3_TC_BIT;
2418 	fCmdRing[i].flags = B_HOST_TO_LENDIAN_INT32(temp);
2419 
2420 	fCmdAddr = fErst->rs_addr + (XHCI_MAX_EVENTS + i) * sizeof(xhci_trb);
2421 
2422 	i++;
2423 
2424 	if (i == (XHCI_MAX_COMMANDS - 1)) {
2425 		temp = TRB_3_TYPE(TRB_TYPE_LINK) | TRB_3_TC_BIT;
2426 		if (j)
2427 			temp |= TRB_3_CYCLE_BIT;
2428 		fCmdRing[i].flags = B_HOST_TO_LENDIAN_INT32(temp);
2429 
2430 		i = 0;
2431 		j ^= 1;
2432 	}
2433 
2434 	fCmdIdx = i;
2435 	fCmdCcs = j;
2436 }
2437 
2438 
2439 void
2440 XHCI::HandleCmdComplete(xhci_trb* trb)
2441 {
2442 	if (fCmdAddr == trb->address) {
2443 		TRACE("Received command event\n");
2444 		fCmdResult[0] = trb->status;
2445 		fCmdResult[1] = B_LENDIAN_TO_HOST_INT32(trb->flags);
2446 		release_sem_etc(fCmdCompSem, 1, B_DO_NOT_RESCHEDULE);
2447 	} else
2448 		TRACE_ERROR("received command event for unknown command!\n")
2449 }
2450 
2451 
2452 void
2453 XHCI::HandleTransferComplete(xhci_trb* trb)
2454 {
2455 	const uint32 flags = B_LENDIAN_TO_HOST_INT32(trb->flags);
2456 	const uint8 endpointNumber = TRB_3_ENDPOINT_GET(flags),
2457 		slot = TRB_3_SLOT_GET(flags);
2458 
2459 	if (slot > fSlotCount)
2460 		TRACE_ERROR("invalid slot\n");
2461 	if (endpointNumber == 0 || endpointNumber >= XHCI_MAX_ENDPOINTS) {
2462 		TRACE_ERROR("invalid endpoint\n");
2463 		return;
2464 	}
2465 
2466 	xhci_device *device = &fDevices[slot];
2467 	xhci_endpoint *endpoint = &device->endpoints[endpointNumber - 1];
2468 
2469 	if (endpoint->trbs == NULL) {
2470 		TRACE_ERROR("got TRB but endpoint is not allocated!\n");
2471 		return;
2472 	}
2473 
2474 	// Use mutex_trylock first, in case we are in KDL.
2475 	MutexLocker endpointLocker(endpoint->lock, mutex_trylock(&endpoint->lock) == B_OK);
2476 	if (!endpointLocker.IsLocked()) {
2477 		// We failed to get the lock. Most likely it was destroyed
2478 		// while we were waiting for it.
2479 		return;
2480 	}
2481 
2482 	// In the case of an Event Data TRB, the "transferred" field refers
2483 	// to the actual number of bytes transferred across the whole TD.
2484 	// (XHCI 1.2 § 6.4.2.1 Table 6-38 p478.)
2485 	const uint8 completionCode = TRB_2_COMP_CODE_GET(trb->status);
2486 	int32 transferred = TRB_2_REM_GET(trb->status), remainder = -1;
2487 
2488 	TRACE("HandleTransferComplete: ed %d, code %d, transferred %d\n",
2489 		  (flags & TRB_3_EVENT_DATA_BIT), completionCode, transferred);
2490 
2491 	if ((flags & TRB_3_EVENT_DATA_BIT) == 0) {
2492 		// This should only occur under error conditions.
2493 		TRACE("got an interrupt for a non-Event Data TRB!\n");
2494 		remainder = transferred;
2495 		transferred = -1;
2496 	}
2497 
2498 	if (completionCode != COMP_SUCCESS && completionCode != COMP_SHORT_PACKET) {
2499 		TRACE_ALWAYS("transfer error on slot %" B_PRId8 " endpoint %" B_PRId8
2500 			": %s\n", slot, endpointNumber, xhci_error_string(completionCode));
2501 	}
2502 
2503 	const phys_addr_t source = B_LENDIAN_TO_HOST_INT64(trb->address);
2504 	for (xhci_td *td = endpoint->td_head; td != NULL; td = td->next) {
2505 		int64 offset = (source - td->trb_addr) / sizeof(xhci_trb);
2506 		if (offset < 0 || offset >= td->trb_count)
2507 			continue;
2508 
2509 		TRACE("HandleTransferComplete td %p trb %" B_PRId64 " found\n",
2510 			td, offset);
2511 
2512 		// The TRB at offset trb_used will be the link TRB, which we do not
2513 		// care about (and should not generate an interrupt at all.) We really
2514 		// care about the properly last TRB, at index "count - 1", which the
2515 		// Event Data TRB that _LinkDescriptorForPipe creates points to.
2516 		//
2517 		// But if we have an unsuccessful completion code, the transfer
2518 		// likely failed midway; so just accept it anyway.
2519 		if (offset == (td->trb_used - 1) || completionCode != COMP_SUCCESS) {
2520 			_UnlinkDescriptorForPipe(td, endpoint);
2521 			endpointLocker.Unlock();
2522 
2523 			td->trb_completion_code = completionCode;
2524 			td->td_transferred = transferred;
2525 			td->trb_left = remainder;
2526 
2527 			// add descriptor to finished list
2528 			if (mutex_trylock(&fFinishedLock) != B_OK)
2529 				mutex_lock(&fFinishedLock);
2530 			td->next = fFinishedHead;
2531 			fFinishedHead = td;
2532 			mutex_unlock(&fFinishedLock);
2533 
2534 			release_sem_etc(fFinishTransfersSem, 1, B_DO_NOT_RESCHEDULE);
2535 			TRACE("HandleTransferComplete td %p done\n", td);
2536 		} else {
2537 			TRACE_ERROR("successful TRB 0x%" B_PRIxPHYSADDR " was found, but it wasn't "
2538 				"the last in the TD!\n", source);
2539 		}
2540 		return;
2541 	}
2542 	TRACE_ERROR("TRB 0x%" B_PRIxPHYSADDR " was not found in the endpoint!\n", source);
2543 }
2544 
2545 
2546 void
2547 XHCI::DumpRing(xhci_trb *trbs, uint32 size)
2548 {
2549 	if (!Lock()) {
2550 		TRACE("Unable to get lock!\n");
2551 		return;
2552 	}
2553 
2554 	for (uint32 i = 0; i < size; i++) {
2555 		TRACE("command[%" B_PRId32 "] = %" B_PRId32 " (0x%016" B_PRIx64 ","
2556 			" 0x%08" B_PRIx32 ", 0x%08" B_PRIx32 ")\n", i,
2557 			TRB_3_TYPE_GET(B_LENDIAN_TO_HOST_INT32(trbs[i].flags)),
2558 			trbs[i].address, trbs[i].status, trbs[i].flags);
2559 	}
2560 
2561 	Unlock();
2562 }
2563 
2564 
2565 status_t
2566 XHCI::DoCommand(xhci_trb* trb)
2567 {
2568 	if (!Lock()) {
2569 		TRACE("Unable to get lock!\n");
2570 		return B_ERROR;
2571 	}
2572 
2573 	QueueCommand(trb);
2574 	Ring(0, 0);
2575 
2576 	// Begin with a 50ms timeout.
2577 	if (acquire_sem_etc(fCmdCompSem, 1, B_RELATIVE_TIMEOUT, 50 * 1000) != B_OK) {
2578 		// We've hit the timeout. In some error cases, interrupts are not
2579 		// generated; so here we force the event ring to be polled once.
2580 		release_sem(fEventSem);
2581 
2582 		// Now try again, this time with a 750ms timeout.
2583 		if (acquire_sem_etc(fCmdCompSem, 1, B_RELATIVE_TIMEOUT,
2584 				750 * 1000) != B_OK) {
2585 			TRACE("Unable to obtain fCmdCompSem!\n");
2586 			fCmdAddr = 0;
2587 			Unlock();
2588 			return B_TIMED_OUT;
2589 		}
2590 	}
2591 
2592 	// eat up sems that have been released by multiple interrupts
2593 	int32 semCount = 0;
2594 	get_sem_count(fCmdCompSem, &semCount);
2595 	if (semCount > 0)
2596 		acquire_sem_etc(fCmdCompSem, semCount, B_RELATIVE_TIMEOUT, 0);
2597 
2598 	status_t status = B_OK;
2599 	uint32 completionCode = TRB_2_COMP_CODE_GET(fCmdResult[0]);
2600 	TRACE("command complete\n");
2601 	if (completionCode != COMP_SUCCESS) {
2602 		TRACE_ERROR("unsuccessful command %" B_PRId32 ", error %s (%" B_PRId32 ")\n",
2603 			TRB_3_TYPE_GET(trb->flags), xhci_error_string(completionCode),
2604 			completionCode);
2605 		status = B_IO_ERROR;
2606 	}
2607 
2608 	trb->status = fCmdResult[0];
2609 	trb->flags = fCmdResult[1];
2610 
2611 	fCmdAddr = 0;
2612 	Unlock();
2613 	return status;
2614 }
2615 
2616 
2617 status_t
2618 XHCI::Noop()
2619 {
2620 	TRACE("Issue No-Op\n");
2621 	xhci_trb trb;
2622 	trb.address = 0;
2623 	trb.status = 0;
2624 	trb.flags = TRB_3_TYPE(TRB_TYPE_CMD_NOOP);
2625 
2626 	return DoCommand(&trb);
2627 }
2628 
2629 
2630 status_t
2631 XHCI::EnableSlot(uint8* slot)
2632 {
2633 	TRACE("Enable Slot\n");
2634 	xhci_trb trb;
2635 	trb.address = 0;
2636 	trb.status = 0;
2637 	trb.flags = TRB_3_TYPE(TRB_TYPE_ENABLE_SLOT);
2638 
2639 	status_t status = DoCommand(&trb);
2640 	if (status != B_OK)
2641 		return status;
2642 
2643 	*slot = TRB_3_SLOT_GET(trb.flags);
2644 	return *slot != 0 ? B_OK : B_BAD_VALUE;
2645 }
2646 
2647 
2648 status_t
2649 XHCI::DisableSlot(uint8 slot)
2650 {
2651 	TRACE("Disable Slot\n");
2652 	xhci_trb trb;
2653 	trb.address = 0;
2654 	trb.status = 0;
2655 	trb.flags = TRB_3_TYPE(TRB_TYPE_DISABLE_SLOT) | TRB_3_SLOT(slot);
2656 
2657 	return DoCommand(&trb);
2658 }
2659 
2660 
2661 status_t
2662 XHCI::SetAddress(uint64 inputContext, bool bsr, uint8 slot)
2663 {
2664 	TRACE("Set Address\n");
2665 	xhci_trb trb;
2666 	trb.address = inputContext;
2667 	trb.status = 0;
2668 	trb.flags = TRB_3_TYPE(TRB_TYPE_ADDRESS_DEVICE) | TRB_3_SLOT(slot);
2669 
2670 	if (bsr)
2671 		trb.flags |= TRB_3_BSR_BIT;
2672 
2673 	return DoCommand(&trb);
2674 }
2675 
2676 
2677 status_t
2678 XHCI::ConfigureEndpoint(uint64 inputContext, bool deconfigure, uint8 slot)
2679 {
2680 	TRACE("Configure Endpoint\n");
2681 	xhci_trb trb;
2682 	trb.address = inputContext;
2683 	trb.status = 0;
2684 	trb.flags = TRB_3_TYPE(TRB_TYPE_CONFIGURE_ENDPOINT) | TRB_3_SLOT(slot);
2685 
2686 	if (deconfigure)
2687 		trb.flags |= TRB_3_DCEP_BIT;
2688 
2689 	return DoCommand(&trb);
2690 }
2691 
2692 
2693 status_t
2694 XHCI::EvaluateContext(uint64 inputContext, uint8 slot)
2695 {
2696 	TRACE("Evaluate Context\n");
2697 	xhci_trb trb;
2698 	trb.address = inputContext;
2699 	trb.status = 0;
2700 	trb.flags = TRB_3_TYPE(TRB_TYPE_EVALUATE_CONTEXT) | TRB_3_SLOT(slot);
2701 
2702 	return DoCommand(&trb);
2703 }
2704 
2705 
2706 status_t
2707 XHCI::ResetEndpoint(bool preserve, xhci_endpoint* endpoint)
2708 {
2709 	TRACE("Reset Endpoint\n");
2710 
2711 	switch (_GetEndpointState(endpoint)) {
2712 		case ENDPOINT_STATE_STOPPED:
2713 			TRACE("Reset Endpoint: already stopped");
2714 			return B_OK;
2715 		case ENDPOINT_STATE_HALTED:
2716 			TRACE("Reset Endpoint: warning, weird state!");
2717 		default:
2718 			break;
2719 	}
2720 
2721 	xhci_trb trb;
2722 	trb.address = 0;
2723 	trb.status = 0;
2724 	trb.flags = TRB_3_TYPE(TRB_TYPE_RESET_ENDPOINT)
2725 		| TRB_3_SLOT(endpoint->device->slot) | TRB_3_ENDPOINT(endpoint->id + 1);
2726 	if (preserve)
2727 		trb.flags |= TRB_3_PRSV_BIT;
2728 
2729 	return DoCommand(&trb);
2730 }
2731 
2732 
2733 status_t
2734 XHCI::StopEndpoint(bool suspend, xhci_endpoint* endpoint)
2735 {
2736 	TRACE("Stop Endpoint\n");
2737 
2738 	switch (_GetEndpointState(endpoint)) {
2739 		case ENDPOINT_STATE_HALTED:
2740 			TRACE("Stop Endpoint: error, halted");
2741 			return B_DEV_STALLED;
2742 		case ENDPOINT_STATE_STOPPED:
2743 			TRACE("Stop Endpoint: already stopped");
2744 			return B_OK;
2745 		default:
2746 			break;
2747 	}
2748 
2749 	xhci_trb trb;
2750 	trb.address = 0;
2751 	trb.status = 0;
2752 	trb.flags = TRB_3_TYPE(TRB_TYPE_STOP_ENDPOINT)
2753 		| TRB_3_SLOT(endpoint->device->slot) | TRB_3_ENDPOINT(endpoint->id + 1);
2754 	if (suspend)
2755 		trb.flags |= TRB_3_SUSPEND_ENDPOINT_BIT;
2756 
2757 	return DoCommand(&trb);
2758 }
2759 
2760 
2761 status_t
2762 XHCI::SetTRDequeue(uint64 dequeue, uint16 stream, uint8 endpoint, uint8 slot)
2763 {
2764 	TRACE("Set TR Dequeue\n");
2765 	xhci_trb trb;
2766 	trb.address = dequeue | ENDPOINT_2_DCS_BIT;
2767 		// The DCS bit is copied from the address field as in ConfigureEndpoint.
2768 		// (XHCI 1.2 § 4.6.10 p142.)
2769 	trb.status = TRB_2_STREAM(stream);
2770 	trb.flags = TRB_3_TYPE(TRB_TYPE_SET_TR_DEQUEUE)
2771 		| TRB_3_SLOT(slot) | TRB_3_ENDPOINT(endpoint);
2772 
2773 	return DoCommand(&trb);
2774 }
2775 
2776 
2777 status_t
2778 XHCI::ResetDevice(uint8 slot)
2779 {
2780 	TRACE("Reset Device\n");
2781 	xhci_trb trb;
2782 	trb.address = 0;
2783 	trb.status = 0;
2784 	trb.flags = TRB_3_TYPE(TRB_TYPE_RESET_DEVICE) | TRB_3_SLOT(slot);
2785 
2786 	return DoCommand(&trb);
2787 }
2788 
2789 
2790 int32
2791 XHCI::EventThread(void* data)
2792 {
2793 	((XHCI *)data)->CompleteEvents();
2794 	return B_OK;
2795 }
2796 
2797 
2798 void
2799 XHCI::CompleteEvents()
2800 {
2801 	while (!fStopThreads) {
2802 		if (acquire_sem(fEventSem) < B_OK)
2803 			continue;
2804 
2805 		// eat up sems that have been released by multiple interrupts
2806 		int32 semCount = 0;
2807 		get_sem_count(fEventSem, &semCount);
2808 		if (semCount > 0)
2809 			acquire_sem_etc(fEventSem, semCount, B_RELATIVE_TIMEOUT, 0);
2810 
2811 		ProcessEvents();
2812 	}
2813 }
2814 
2815 
2816 void
2817 XHCI::ProcessEvents()
2818 {
2819 	// Use mutex_trylock first, in case we are in KDL.
2820 	MutexLocker locker(fEventLock, mutex_trylock(&fEventLock) == B_OK);
2821 	if (!locker.IsLocked()) {
2822 		// We failed to get the lock. This really should not happen.
2823 		TRACE_ERROR("failed to acquire event lock!\n");
2824 		return;
2825 	}
2826 
2827 	uint16 i = fEventIdx;
2828 	uint8 j = fEventCcs;
2829 	uint8 t = 2;
2830 
2831 	while (1) {
2832 		uint32 temp = B_LENDIAN_TO_HOST_INT32(fEventRing[i].flags);
2833 		uint8 event = TRB_3_TYPE_GET(temp);
2834 		TRACE("event[%u] = %u (0x%016" B_PRIx64 " 0x%08" B_PRIx32 " 0x%08"
2835 			B_PRIx32 ")\n", i, event, fEventRing[i].address,
2836 			fEventRing[i].status, B_LENDIAN_TO_HOST_INT32(fEventRing[i].flags));
2837 		uint8 k = (temp & TRB_3_CYCLE_BIT) ? 1 : 0;
2838 		if (j != k)
2839 			break;
2840 
2841 		switch (event) {
2842 		case TRB_TYPE_COMMAND_COMPLETION:
2843 			HandleCmdComplete(&fEventRing[i]);
2844 			break;
2845 		case TRB_TYPE_TRANSFER:
2846 			HandleTransferComplete(&fEventRing[i]);
2847 			break;
2848 		case TRB_TYPE_PORT_STATUS_CHANGE:
2849 			TRACE("port change detected\n");
2850 			break;
2851 		default:
2852 			TRACE_ERROR("Unhandled event = %u\n", event);
2853 			break;
2854 		}
2855 
2856 		i++;
2857 		if (i == XHCI_MAX_EVENTS) {
2858 			i = 0;
2859 			j ^= 1;
2860 			if (!--t)
2861 				break;
2862 		}
2863 	}
2864 
2865 	fEventIdx = i;
2866 	fEventCcs = j;
2867 
2868 	uint64 addr = fErst->rs_addr + i * sizeof(xhci_trb);
2869 	WriteRunReg32(XHCI_ERDP_LO(0), (uint32)addr | ERDP_BUSY);
2870 	WriteRunReg32(XHCI_ERDP_HI(0), (uint32)(addr >> 32));
2871 }
2872 
2873 
2874 int32
2875 XHCI::FinishThread(void* data)
2876 {
2877 	((XHCI *)data)->FinishTransfers();
2878 	return B_OK;
2879 }
2880 
2881 
2882 void
2883 XHCI::FinishTransfers()
2884 {
2885 	while (!fStopThreads) {
2886 		if (acquire_sem(fFinishTransfersSem) < B_OK)
2887 			continue;
2888 
2889 		// eat up sems that have been released by multiple interrupts
2890 		int32 semCount = 0;
2891 		get_sem_count(fFinishTransfersSem, &semCount);
2892 		if (semCount > 0)
2893 			acquire_sem_etc(fFinishTransfersSem, semCount, B_RELATIVE_TIMEOUT, 0);
2894 
2895 		mutex_lock(&fFinishedLock);
2896 		TRACE("finishing transfers\n");
2897 		while (fFinishedHead != NULL) {
2898 			xhci_td* td = fFinishedHead;
2899 			fFinishedHead = td->next;
2900 			td->next = NULL;
2901 			mutex_unlock(&fFinishedLock);
2902 
2903 			TRACE("finishing transfer td %p\n", td);
2904 
2905 			Transfer* transfer = td->transfer;
2906 			if (transfer == NULL) {
2907 				// No transfer? Quick way out.
2908 				FreeDescriptor(td);
2909 				mutex_lock(&fFinishedLock);
2910 				continue;
2911 			}
2912 
2913 			bool directionIn = (transfer->TransferPipe()->Direction() != Pipe::Out);
2914 
2915 			status_t callbackStatus = B_OK;
2916 			const uint8 completionCode = td->trb_completion_code;
2917 			switch (completionCode) {
2918 				case COMP_SHORT_PACKET:
2919 				case COMP_SUCCESS:
2920 					callbackStatus = B_OK;
2921 					break;
2922 				case COMP_DATA_BUFFER:
2923 					callbackStatus = directionIn ? B_DEV_DATA_OVERRUN
2924 						: B_DEV_DATA_UNDERRUN;
2925 					break;
2926 				case COMP_BABBLE:
2927 					callbackStatus = directionIn ? B_DEV_FIFO_OVERRUN
2928 						: B_DEV_FIFO_UNDERRUN;
2929 					break;
2930 				case COMP_USB_TRANSACTION:
2931 					callbackStatus = B_DEV_CRC_ERROR;
2932 					break;
2933 				case COMP_STALL:
2934 					callbackStatus = B_DEV_STALLED;
2935 					break;
2936 				default:
2937 					callbackStatus = B_DEV_STALLED;
2938 					break;
2939 			}
2940 
2941 			size_t actualLength = transfer->FragmentLength();
2942 			if (completionCode != COMP_SUCCESS) {
2943 				actualLength = td->td_transferred;
2944 				if (td->td_transferred == -1)
2945 					actualLength = transfer->FragmentLength() - td->trb_left;
2946 				TRACE("transfer not successful, actualLength=%" B_PRIuSIZE "\n",
2947 					actualLength);
2948 			}
2949 
2950 			usb_isochronous_data* isochronousData = transfer->IsochronousData();
2951 			if (isochronousData != NULL) {
2952 				size_t packetSize = transfer->DataLength()
2953 						/ isochronousData->packet_count,
2954 					left = actualLength;
2955 				for (uint32 i = 0; i < isochronousData->packet_count; i++) {
2956 					size_t size = min_c(packetSize, left);
2957 					isochronousData->packet_descriptors[i].actual_length = size;
2958 					isochronousData->packet_descriptors[i].status = (size > 0)
2959 						? B_OK : B_DEV_FIFO_UNDERRUN;
2960 					left -= size;
2961  				}
2962  			}
2963 
2964 			if (callbackStatus == B_OK && directionIn && actualLength > 0) {
2965 				TRACE("copying in iov count %ld\n", transfer->VectorCount());
2966 				status_t status = transfer->PrepareKernelAccess();
2967 				if (status == B_OK) {
2968 					ReadDescriptor(td, transfer->Vector(),
2969 						transfer->VectorCount());
2970 				} else {
2971 					callbackStatus = status;
2972 				}
2973 			}
2974 
2975 			FreeDescriptor(td);
2976 
2977 			// this transfer may still have data left
2978 			transfer->AdvanceByFragment(actualLength);
2979 			if (completionCode == COMP_SUCCESS
2980 					&& transfer->FragmentLength() > 0) {
2981 				TRACE("still %" B_PRIuSIZE " bytes left on transfer\n",
2982 					transfer->FragmentLength());
2983 				SubmitTransfer(transfer);
2984 			} else {
2985 				// The actualLength was already handled in AdvanceByFragment.
2986 				transfer->Finished(callbackStatus, 0);
2987 				delete transfer;
2988 			}
2989 
2990 			mutex_lock(&fFinishedLock);
2991 		}
2992 		mutex_unlock(&fFinishedLock);
2993 	}
2994 }
2995 
2996 
2997 inline void
2998 XHCI::WriteOpReg(uint32 reg, uint32 value)
2999 {
3000 	*(volatile uint32 *)(fRegisters + fOperationalRegisterOffset + reg) = value;
3001 }
3002 
3003 
3004 inline uint32
3005 XHCI::ReadOpReg(uint32 reg)
3006 {
3007 	return *(volatile uint32 *)(fRegisters + fOperationalRegisterOffset + reg);
3008 }
3009 
3010 
3011 inline status_t
3012 XHCI::WaitOpBits(uint32 reg, uint32 mask, uint32 expected)
3013 {
3014 	int loops = 0;
3015 	uint32 value = ReadOpReg(reg);
3016 	while ((value & mask) != expected) {
3017 		snooze(1000);
3018 		value = ReadOpReg(reg);
3019 		if (loops == 100) {
3020 			TRACE("delay waiting on reg 0x%" B_PRIX32 " match 0x%" B_PRIX32
3021 				" (0x%" B_PRIX32 ")\n",	reg, expected, mask);
3022 		} else if (loops > 250) {
3023 			TRACE_ERROR("timeout waiting on reg 0x%" B_PRIX32
3024 				" match 0x%" B_PRIX32 " (0x%" B_PRIX32 ")\n", reg, expected,
3025 				mask);
3026 			return B_ERROR;
3027 		}
3028 		loops++;
3029 	}
3030 	return B_OK;
3031 }
3032 
3033 
3034 inline uint32
3035 XHCI::ReadCapReg32(uint32 reg)
3036 {
3037 	return *(volatile uint32 *)(fRegisters + fCapabilityRegisterOffset + reg);
3038 }
3039 
3040 
3041 inline void
3042 XHCI::WriteCapReg32(uint32 reg, uint32 value)
3043 {
3044 	*(volatile uint32 *)(fRegisters + fCapabilityRegisterOffset + reg) = value;
3045 }
3046 
3047 
3048 inline uint32
3049 XHCI::ReadRunReg32(uint32 reg)
3050 {
3051 	return *(volatile uint32 *)(fRegisters + fRuntimeRegisterOffset + reg);
3052 }
3053 
3054 
3055 inline void
3056 XHCI::WriteRunReg32(uint32 reg, uint32 value)
3057 {
3058 	*(volatile uint32 *)(fRegisters + fRuntimeRegisterOffset + reg) = value;
3059 }
3060 
3061 
3062 inline uint32
3063 XHCI::ReadDoorReg32(uint32 reg)
3064 {
3065 	return *(volatile uint32 *)(fRegisters + fDoorbellRegisterOffset + reg);
3066 }
3067 
3068 
3069 inline void
3070 XHCI::WriteDoorReg32(uint32 reg, uint32 value)
3071 {
3072 	*(volatile uint32 *)(fRegisters + fDoorbellRegisterOffset + reg) = value;
3073 }
3074 
3075 
3076 inline addr_t
3077 XHCI::_OffsetContextAddr(addr_t p)
3078 {
3079 	if (fContextSizeShift == 1) {
3080 		// each structure is page aligned, each pointer is 32 bits aligned
3081 		uint32 offset = p & ((B_PAGE_SIZE - 1) & ~31U);
3082 		p += offset;
3083 	}
3084 	return p;
3085 }
3086 
3087 inline uint32
3088 XHCI::_ReadContext(uint32* p)
3089 {
3090 	p = (uint32*)_OffsetContextAddr((addr_t)p);
3091 	return *p;
3092 }
3093 
3094 
3095 inline void
3096 XHCI::_WriteContext(uint32* p, uint32 value)
3097 {
3098 	p = (uint32*)_OffsetContextAddr((addr_t)p);
3099 	*p = value;
3100 }
3101 
3102 
3103 inline uint64
3104 XHCI::_ReadContext(uint64* p)
3105 {
3106 	p = (uint64*)_OffsetContextAddr((addr_t)p);
3107 	return *p;
3108 }
3109 
3110 
3111 inline void
3112 XHCI::_WriteContext(uint64* p, uint64 value)
3113 {
3114 	p = (uint64*)_OffsetContextAddr((addr_t)p);
3115 	*p = value;
3116 }
3117