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