xref: /haiku/src/add-ons/kernel/busses/usb/ehci.cpp (revision efafab643ce980e3f3c916795ed302599f6b4f66)
1 /*
2  * Copyright 2006-2011, Haiku Inc. All rights reserved.
3  * Distributed under the terms of the MIT License.
4  *
5  * Authors:
6  *		Michael Lotz <mmlr@mlotz.ch>
7  *		Jérôme Duval <korli@users.berlios.de>
8  */
9 
10 
11 #include <driver_settings.h>
12 #include <module.h>
13 #include <PCI.h>
14 #include <PCI_x86.h>
15 #include <USB3.h>
16 #include <KernelExport.h>
17 
18 #include "ehci.h"
19 
20 #define USB_MODULE_NAME	"ehci"
21 
22 pci_module_info *EHCI::sPCIModule = NULL;
23 pci_x86_module_info *EHCI::sPCIx86Module = NULL;
24 
25 
26 static int32
27 ehci_std_ops(int32 op, ...)
28 {
29 	switch (op) {
30 		case B_MODULE_INIT:
31 			TRACE_MODULE("ehci init module\n");
32 			return B_OK;
33 		case B_MODULE_UNINIT:
34 			TRACE_MODULE("ehci uninit module\n");
35 			return B_OK;
36 	}
37 
38 	return EINVAL;
39 }
40 
41 
42 usb_host_controller_info ehci_module = {
43 	{
44 		"busses/usb/ehci",
45 		0,
46 		ehci_std_ops
47 	},
48 	NULL,
49 	EHCI::AddTo
50 };
51 
52 
53 module_info *modules[] = {
54 	(module_info *)&ehci_module,
55 	NULL
56 };
57 
58 
59 //
60 // #pragma mark -
61 //
62 
63 
64 #ifdef TRACE_USB
65 
66 void
67 print_descriptor_chain(ehci_qtd *descriptor)
68 {
69 	while (descriptor) {
70 		dprintf(" %08" B_PRIx32 " n%08" B_PRIx32 " a%08" B_PRIx32 " t%08"
71 			B_PRIx32 " %08" B_PRIx32 " %08" B_PRIx32 " %08" B_PRIx32 " %08"
72 			B_PRIx32 " %08" B_PRIx32 " s%" B_PRIuSIZE "\n",
73 			descriptor->this_phy, descriptor->next_phy,
74 			descriptor->alt_next_phy, descriptor->token,
75 			descriptor->buffer_phy[0], descriptor->buffer_phy[1],
76 			descriptor->buffer_phy[2], descriptor->buffer_phy[3],
77 			descriptor->buffer_phy[4], descriptor->buffer_size);
78 
79 		if (descriptor->next_phy & EHCI_ITEM_TERMINATE)
80 			break;
81 
82 		descriptor = descriptor->next_log;
83 	}
84 }
85 
86 
87 void
88 print_queue(ehci_qh *queueHead)
89 {
90 	dprintf("queue:    t%08" B_PRIx32 " n%08" B_PRIx32 " ch%08" B_PRIx32
91 		" ca%08" B_PRIx32 " cu%08" B_PRIx32 "\n",
92 		queueHead->this_phy, queueHead->next_phy, queueHead->endpoint_chars,
93 		queueHead->endpoint_caps, queueHead->current_qtd_phy);
94 	dprintf("overlay:  n%08" B_PRIx32 " a%08" B_PRIx32 " t%08" B_PRIx32
95 		" %08" B_PRIx32 " %08" B_PRIx32 " %08" B_PRIx32 " %08" B_PRIx32
96 		" %08" B_PRIx32 "\n", queueHead->overlay.next_phy,
97 		queueHead->overlay.alt_next_phy, queueHead->overlay.token,
98 		queueHead->overlay.buffer_phy[0], queueHead->overlay.buffer_phy[1],
99 		queueHead->overlay.buffer_phy[2], queueHead->overlay.buffer_phy[3],
100 		queueHead->overlay.buffer_phy[4]);
101 	print_descriptor_chain(queueHead->element_log);
102 }
103 
104 
105 #endif // TRACE_USB
106 
107 
108 //
109 // #pragma mark -
110 //
111 
112 
113 EHCI::EHCI(pci_info *info, Stack *stack)
114 	:	BusManager(stack),
115 		fCapabilityRegisters(NULL),
116 		fOperationalRegisters(NULL),
117 		fRegisterArea(-1),
118 		fPCIInfo(info),
119 		fStack(stack),
120 		fEnabledInterrupts(0),
121 		fThreshold(0),
122 		fPeriodicFrameListArea(-1),
123 		fPeriodicFrameList(NULL),
124 		fInterruptEntries(NULL),
125 		fItdEntries(NULL),
126 		fSitdEntries(NULL),
127 		fAsyncQueueHead(NULL),
128 		fAsyncAdvanceSem(-1),
129 		fFirstTransfer(NULL),
130 		fLastTransfer(NULL),
131 		fFinishTransfersSem(-1),
132 		fFinishThread(-1),
133 		fProcessingPipe(NULL),
134 		fFreeListHead(NULL),
135 		fCleanupSem(-1),
136 		fCleanupThread(-1),
137 		fStopThreads(false),
138 		fNextStartingFrame(-1),
139 		fFrameBandwidth(NULL),
140 		fFirstIsochronousTransfer(NULL),
141 		fLastIsochronousTransfer(NULL),
142 		fFinishIsochronousTransfersSem(-1),
143 		fFinishIsochronousThread(-1),
144 		fRootHub(NULL),
145 		fRootHubAddress(0),
146 		fPortCount(0),
147 		fPortResetChange(0),
148 		fPortSuspendChange(0),
149 		fInterruptPollThread(-1),
150 		fIRQ(0),
151 		fUseMSI(false)
152 {
153 	// Create a lock for the isochronous transfer list
154 	mutex_init(&fIsochronousLock, "EHCI isochronous lock");
155 
156 	if (BusManager::InitCheck() != B_OK) {
157 		TRACE_ERROR("bus manager failed to init\n");
158 		return;
159 	}
160 
161 	TRACE("constructing new EHCI host controller driver\n");
162 	fInitOK = false;
163 
164 	// ATI/AMD SB600/SB700 periodic list cache workaround
165 	// Logic kindly borrowed from NetBSD PR 40056
166 	if (fPCIInfo->vendor_id == AMD_SBX00_VENDOR) {
167 		bool applyWorkaround = false;
168 
169 		if (fPCIInfo->device_id == AMD_SB600_EHCI_CONTROLLER) {
170 			// always apply on SB600
171 			applyWorkaround = true;
172 		} else if (fPCIInfo->device_id == AMD_SB700_SB800_EHCI_CONTROLLER) {
173 			// only apply on certain chipsets, determined by SMBus revision
174 			pci_info smbus;
175 			int32 index = 0;
176 			while (sPCIModule->get_nth_pci_info(index++, &smbus) == B_OK) {
177 				if (smbus.vendor_id == AMD_SBX00_VENDOR
178 					&& smbus.device_id == AMD_SBX00_SMBUS_CONTROLLER) {
179 
180 					// Only applies to chipsets < SB710 (rev A14)
181 					if (smbus.revision == 0x3a || smbus.revision == 0x3b)
182 						applyWorkaround = true;
183 
184 					break;
185 				}
186 			}
187 		}
188 
189 		if (applyWorkaround) {
190 			// According to AMD errata of SB700 and SB600 register documentation
191 			// this disables the Periodic List Cache on SB600 and the Advanced
192 			// Periodic List Cache on early SB700. Both the BSDs and Linux use
193 			// this workaround.
194 
195 			TRACE_ALWAYS("disabling SB600/SB700 periodic list cache\n");
196 			uint32 workaround = sPCIModule->read_pci_config(fPCIInfo->bus,
197 				fPCIInfo->device, fPCIInfo->function,
198 				AMD_SBX00_EHCI_MISC_REGISTER, 4);
199 
200 			sPCIModule->write_pci_config(fPCIInfo->bus, fPCIInfo->device,
201 				fPCIInfo->function, AMD_SBX00_EHCI_MISC_REGISTER, 4,
202 				workaround | AMD_SBX00_EHCI_MISC_DISABLE_PERIODIC_LIST_CACHE);
203 		}
204 	}
205 
206 	// enable busmaster and memory mapped access
207 	uint16 command = sPCIModule->read_pci_config(fPCIInfo->bus,
208 		fPCIInfo->device, fPCIInfo->function, PCI_command, 2);
209 	command &= ~PCI_command_io;
210 	command |= PCI_command_master | PCI_command_memory;
211 
212 	sPCIModule->write_pci_config(fPCIInfo->bus, fPCIInfo->device,
213 		fPCIInfo->function, PCI_command, 2, command);
214 
215 	// map the registers
216 	uint32 offset = fPCIInfo->u.h0.base_registers[0] & (B_PAGE_SIZE - 1);
217 	phys_addr_t physicalAddress = fPCIInfo->u.h0.base_registers[0] - offset;
218 	size_t mapSize = (fPCIInfo->u.h0.base_register_sizes[0] + offset
219 		+ B_PAGE_SIZE - 1) & ~(B_PAGE_SIZE - 1);
220 
221 	TRACE("map physical memory 0x%08" B_PRIx32 " (base: 0x%08" B_PRIxPHYSADDR
222 		"; offset: %" B_PRIx32 "); size: %" B_PRIu32 "\n",
223 		fPCIInfo->u.h0.base_registers[0], physicalAddress, offset,
224 		fPCIInfo->u.h0.base_register_sizes[0]);
225 
226 	fRegisterArea = map_physical_memory("EHCI memory mapped registers",
227 		physicalAddress, mapSize, B_ANY_KERNEL_BLOCK_ADDRESS,
228 		B_KERNEL_READ_AREA | B_KERNEL_WRITE_AREA,
229 		(void **)&fCapabilityRegisters);
230 	if (fRegisterArea < 0) {
231 		TRACE_ERROR("failed to map register memory\n");
232 		return;
233 	}
234 
235 	fCapabilityRegisters += offset;
236 	fOperationalRegisters = fCapabilityRegisters + ReadCapReg8(EHCI_CAPLENGTH);
237 	TRACE("mapped capability registers: 0x%p\n", fCapabilityRegisters);
238 	TRACE("mapped operational registers: 0x%p\n", fOperationalRegisters);
239 
240 	TRACE("structural parameters: 0x%08" B_PRIx32 "\n",
241 		ReadCapReg32(EHCI_HCSPARAMS));
242 	TRACE("capability parameters: 0x%08" B_PRIx32 "\n",
243 		ReadCapReg32(EHCI_HCCPARAMS));
244 
245 	if (EHCI_HCCPARAMS_FRAME_CACHE(ReadCapReg32(EHCI_HCCPARAMS)))
246 		fThreshold = 2 + 8;
247 	else
248 		fThreshold = 2 + EHCI_HCCPARAMS_IPT(ReadCapReg32(EHCI_HCCPARAMS));
249 
250 	// read port count from capability register
251 	fPortCount = ReadCapReg32(EHCI_HCSPARAMS) & 0x0f;
252 
253 	uint32 extendedCapPointer = ReadCapReg32(EHCI_HCCPARAMS) >> EHCI_ECP_SHIFT;
254 	extendedCapPointer &= EHCI_ECP_MASK;
255 	if (extendedCapPointer > 0) {
256 		TRACE("extended capabilities register at %" B_PRIu32 "\n",
257 			extendedCapPointer);
258 
259 		uint32 legacySupport = sPCIModule->read_pci_config(fPCIInfo->bus,
260 			fPCIInfo->device, fPCIInfo->function, extendedCapPointer, 4);
261 		if ((legacySupport & EHCI_LEGSUP_CAPID_MASK) == EHCI_LEGSUP_CAPID) {
262 			if ((legacySupport & EHCI_LEGSUP_BIOSOWNED) != 0) {
263 				TRACE_ALWAYS("the host controller is bios owned, claiming"
264 					" ownership\n");
265 
266 				sPCIModule->write_pci_config(fPCIInfo->bus, fPCIInfo->device,
267 					fPCIInfo->function, extendedCapPointer + 3, 1, 1);
268 
269 				for (int32 i = 0; i < 20; i++) {
270 					legacySupport = sPCIModule->read_pci_config(fPCIInfo->bus,
271 						fPCIInfo->device, fPCIInfo->function,
272 						extendedCapPointer, 4);
273 
274 					if ((legacySupport & EHCI_LEGSUP_BIOSOWNED) == 0)
275 						break;
276 
277 					TRACE_ALWAYS("controller is still bios owned, waiting\n");
278 					snooze(50000);
279 				}
280 			}
281 
282 			if (legacySupport & EHCI_LEGSUP_BIOSOWNED) {
283 				TRACE_ERROR("bios won't give up control over the host "
284 					"controller (ignoring)\n");
285 			} else if (legacySupport & EHCI_LEGSUP_OSOWNED) {
286 				TRACE_ALWAYS(
287 					"successfully took ownership of the host controller\n");
288 			}
289 
290 			// Force off the BIOS owned flag, and clear all SMIs. Some BIOSes
291 			// do indicate a successful handover but do not remove their SMIs
292 			// and then freeze the system when interrupts are generated.
293 			sPCIModule->write_pci_config(fPCIInfo->bus, fPCIInfo->device,
294 				fPCIInfo->function, extendedCapPointer + 2, 1, 0);
295 			sPCIModule->write_pci_config(fPCIInfo->bus, fPCIInfo->device,
296 				fPCIInfo->function, extendedCapPointer + 4, 4, 0);
297 		} else {
298 			TRACE_ALWAYS(
299 				"extended capability is not a legacy support register\n");
300 		}
301 	} else {
302 		TRACE_ALWAYS("no extended capabilities register\n");
303 	}
304 
305 	// disable interrupts
306 	WriteOpReg(EHCI_USBINTR, 0);
307 
308 	// reset the host controller
309 	if (ControllerReset() != B_OK) {
310 		TRACE_ERROR("host controller failed to reset\n");
311 		return;
312 	}
313 
314 	// reset the segment register
315 	WriteOpReg(EHCI_CTRDSSEGMENT, 0);
316 
317 	// create semaphores the finisher thread will wait for
318 	fAsyncAdvanceSem = create_sem(0, "EHCI Async Advance");
319 	fFinishTransfersSem = create_sem(0, "EHCI Finish Transfers");
320 	fCleanupSem = create_sem(0, "EHCI Cleanup");
321 	if (fFinishTransfersSem < 0 || fAsyncAdvanceSem < 0 || fCleanupSem < 0) {
322 		TRACE_ERROR("failed to create semaphores\n");
323 		return;
324 	}
325 
326 	// create finisher service thread
327 	fFinishThread = spawn_kernel_thread(FinishThread, "ehci finish thread",
328 		B_NORMAL_PRIORITY, (void *)this);
329 	resume_thread(fFinishThread);
330 
331 	// Create semaphore the isochronous finisher thread will wait for
332 	fFinishIsochronousTransfersSem = create_sem(0,
333 		"EHCI Isochronous Finish Transfers");
334 	if (fFinishIsochronousTransfersSem < 0) {
335 		TRACE_ERROR("failed to create isochronous finisher semaphore\n");
336 		return;
337 	}
338 
339 	// Create the isochronous finisher service thread
340 	fFinishIsochronousThread = spawn_kernel_thread(FinishIsochronousThread,
341 		"ehci isochronous finish thread", B_URGENT_DISPLAY_PRIORITY,
342 		(void *)this);
343 	resume_thread(fFinishIsochronousThread);
344 
345 	// create cleanup service thread
346 	fCleanupThread = spawn_kernel_thread(CleanupThread, "ehci cleanup thread",
347 		B_NORMAL_PRIORITY, (void *)this);
348 	resume_thread(fCleanupThread);
349 
350 	// set up interrupts or interrupt polling now that the controller is ready
351 	bool polling = false;
352 	void *settings = load_driver_settings(B_SAFEMODE_DRIVER_SETTINGS);
353 	if (settings != NULL) {
354 		polling = get_driver_boolean_parameter(settings, "ehci_polling", false,
355 			false);
356 		unload_driver_settings(settings);
357 	}
358 
359 	if (polling) {
360 		// create and run the polling thread
361 		TRACE_ALWAYS("enabling ehci polling\n");
362 		fInterruptPollThread = spawn_kernel_thread(InterruptPollThread,
363 			"ehci interrupt poll thread", B_NORMAL_PRIORITY, (void *)this);
364 		resume_thread(fInterruptPollThread);
365 	} else {
366 		// Find the right interrupt vector, using MSIs if available.
367 		fIRQ = fPCIInfo->u.h0.interrupt_line;
368 		if (sPCIx86Module != NULL && sPCIx86Module->get_msi_count(
369 				fPCIInfo->bus, fPCIInfo->device, fPCIInfo->function) >= 1) {
370 			uint8 msiVector = 0;
371 			if (sPCIx86Module->configure_msi(fPCIInfo->bus, fPCIInfo->device,
372 					fPCIInfo->function, 1, &msiVector) == B_OK
373 				&& sPCIx86Module->enable_msi(fPCIInfo->bus, fPCIInfo->device,
374 					fPCIInfo->function) == B_OK) {
375 				TRACE_ALWAYS("using message signaled interrupts\n");
376 				fIRQ = msiVector;
377 				fUseMSI = true;
378 			}
379 		}
380 
381 		// install the interrupt handler and enable interrupts
382 		install_io_interrupt_handler(fIRQ, InterruptHandler,
383 			(void *)this, 0);
384 	}
385 
386 	// ensure that interrupts are en-/disabled on the PCI device
387 	command = sPCIModule->read_pci_config(fPCIInfo->bus, fPCIInfo->device,
388 		fPCIInfo->function, PCI_command, 2);
389 	if ((polling || fUseMSI) == ((command & PCI_command_int_disable) == 0)) {
390 		if (polling || fUseMSI)
391 			command &= ~PCI_command_int_disable;
392 		else
393 			command |= PCI_command_int_disable;
394 
395 		sPCIModule->write_pci_config(fPCIInfo->bus, fPCIInfo->device,
396 			fPCIInfo->function, PCI_command, 2, command);
397 	}
398 
399 	fEnabledInterrupts = EHCI_USBINTR_HOSTSYSERR | EHCI_USBINTR_USBERRINT
400 		| EHCI_USBINTR_USBINT | EHCI_USBINTR_INTONAA;
401 	WriteOpReg(EHCI_USBINTR, fEnabledInterrupts);
402 
403 	// structures don't span page boundaries
404 	size_t itdListSize = EHCI_VFRAMELIST_ENTRIES_COUNT
405 		/ (B_PAGE_SIZE / sizeof(itd_entry)) * B_PAGE_SIZE;
406 	size_t sitdListSize = EHCI_VFRAMELIST_ENTRIES_COUNT
407 		/ (B_PAGE_SIZE / sizeof(sitd_entry)) * B_PAGE_SIZE;
408 	size_t frameListSize = B_PAGE_SIZE + B_PAGE_SIZE + itdListSize
409 		+ sitdListSize;
410 
411 	// allocate the periodic frame list
412 	fPeriodicFrameListArea = fStack->AllocateArea((void **)&fPeriodicFrameList,
413 		&physicalAddress, frameListSize, "USB EHCI Periodic Framelist");
414 	if (fPeriodicFrameListArea < 0) {
415 		TRACE_ERROR("unable to allocate periodic framelist\n");
416 		return;
417 	}
418 
419 	if ((physicalAddress & 0xfff) != 0) {
420 		panic("EHCI_PERIODICLISTBASE not aligned on 4k: 0x%" B_PRIxPHYSADDR
421 			"\n", physicalAddress);
422 	}
423 
424 	// set the periodic frame list base on the controller
425 	WriteOpReg(EHCI_PERIODICLISTBASE, (uint32)physicalAddress);
426 
427 	// create the interrupt entries to support different polling intervals
428 	TRACE("creating interrupt entries\n");
429 	uint32_t physicalBase = physicalAddress + B_PAGE_SIZE;
430 	uint8 *logicalBase = (uint8 *)fPeriodicFrameList + B_PAGE_SIZE;
431 	memset(logicalBase, 0, B_PAGE_SIZE);
432 
433 	fInterruptEntries = (interrupt_entry *)logicalBase;
434 	for (int32 i = 0; i < EHCI_INTERRUPT_ENTRIES_COUNT; i++) {
435 		ehci_qh *queueHead = &fInterruptEntries[i].queue_head;
436 		queueHead->this_phy = physicalBase | EHCI_ITEM_TYPE_QH;
437 		queueHead->current_qtd_phy = 0;
438 		queueHead->overlay.next_phy = EHCI_ITEM_TERMINATE;
439 		queueHead->overlay.alt_next_phy = EHCI_ITEM_TERMINATE;
440 		queueHead->overlay.token = EHCI_QTD_STATUS_HALTED;
441 
442 		// set dummy endpoint information
443 		queueHead->endpoint_chars = EHCI_QH_CHARS_EPS_HIGH
444 			| (3 << EHCI_QH_CHARS_RL_SHIFT) | (64 << EHCI_QH_CHARS_MPL_SHIFT)
445 			| EHCI_QH_CHARS_TOGGLE;
446 		queueHead->endpoint_caps = (1 << EHCI_QH_CAPS_MULT_SHIFT)
447 			| (0xff << EHCI_QH_CAPS_ISM_SHIFT);
448 
449 		physicalBase += sizeof(interrupt_entry);
450 		if ((physicalBase & 0x1f) != 0) {
451 			panic("physical base for interrupt entry %" B_PRId32
452 				" not aligned on 32, interrupt entry structure size %lu\n",
453 					i, sizeof(interrupt_entry));
454 		}
455 	}
456 
457 	// create the itd and sitd entries
458 	TRACE("build up iso entries\n");
459 	uint32_t itdPhysicalBase = physicalAddress + B_PAGE_SIZE + B_PAGE_SIZE;
460 	itd_entry* itds = (itd_entry *)((uint8 *)fPeriodicFrameList + B_PAGE_SIZE
461 		+ B_PAGE_SIZE);
462 	memset(itds, 0, itdListSize);
463 
464 	uint32_t sitdPhysicalBase = itdPhysicalBase + itdListSize;
465 	sitd_entry* sitds = (sitd_entry *)((uint8 *)fPeriodicFrameList + B_PAGE_SIZE
466 		+ B_PAGE_SIZE + itdListSize);
467 	memset(sitds, 0, sitdListSize);
468 
469 	fItdEntries = new(std::nothrow) ehci_itd *[EHCI_VFRAMELIST_ENTRIES_COUNT];
470 	fSitdEntries = new(std::nothrow) ehci_sitd *[EHCI_VFRAMELIST_ENTRIES_COUNT];
471 
472 	dprintf("sitd entry size %lu, itd entry size %lu\n", sizeof(sitd_entry),
473 		sizeof(itd_entry));
474 	for (int32 i = 0; i < EHCI_VFRAMELIST_ENTRIES_COUNT; i++) {
475 		ehci_sitd *sitd = &sitds[i].sitd;
476 		sitd->this_phy = sitdPhysicalBase | EHCI_ITEM_TYPE_SITD;
477 		sitd->back_phy = EHCI_ITEM_TERMINATE;
478 		fSitdEntries[i] = sitd;
479 		TRACE("sitd entry %" B_PRId32 " %p 0x%" B_PRIx32 "\n", i, sitd,
480 			sitd->this_phy);
481 
482 		ehci_itd *itd = &itds[i].itd;
483 		itd->this_phy = itdPhysicalBase | EHCI_ITEM_TYPE_ITD;
484 		itd->next_phy = sitd->this_phy;
485 		fItdEntries[i] = itd;
486 		TRACE("itd entry %" B_PRId32 " %p 0x%" B_PRIx32 "\n", i, itd,
487 			itd->this_phy);
488 
489 		sitdPhysicalBase += sizeof(sitd_entry);
490 		itdPhysicalBase += sizeof(itd_entry);
491 		if ((sitdPhysicalBase & 0x10) != 0 || (itdPhysicalBase & 0x10) != 0)
492 			panic("physical base for entry %" B_PRId32 " not aligned on 32\n",
493 				i);
494 	}
495 
496 	// build flat interrupt tree
497 	TRACE("build up interrupt links\n");
498 	uint32 interval = EHCI_VFRAMELIST_ENTRIES_COUNT;
499 	uint32 intervalIndex = EHCI_INTERRUPT_ENTRIES_COUNT - 1;
500 	while (interval > 1) {
501 		for (uint32 insertIndex = interval / 2;
502 			insertIndex < EHCI_VFRAMELIST_ENTRIES_COUNT;
503 			insertIndex += interval) {
504 			fSitdEntries[insertIndex]->next_phy
505 				= fInterruptEntries[intervalIndex].queue_head.this_phy;
506 		}
507 
508 		intervalIndex--;
509 		interval /= 2;
510 	}
511 
512 	// setup the empty slot in the list and linking of all -> first
513 	ehci_qh *firstLogical = &fInterruptEntries[0].queue_head;
514 	fSitdEntries[0]->next_phy = firstLogical->this_phy;
515 	for (int32 i = 1; i < EHCI_INTERRUPT_ENTRIES_COUNT; i++) {
516 		fInterruptEntries[i].queue_head.next_phy = firstLogical->this_phy;
517 		fInterruptEntries[i].queue_head.next_log = firstLogical;
518 		fInterruptEntries[i].queue_head.prev_log = NULL;
519 	}
520 
521 	// terminate the first entry
522 	firstLogical->next_phy = EHCI_ITEM_TERMINATE;
523 	firstLogical->next_log = NULL;
524 	firstLogical->prev_log = NULL;
525 
526 	for (int32 i = 0; i < EHCI_FRAMELIST_ENTRIES_COUNT; i++) {
527 		fPeriodicFrameList[i]
528 			= fItdEntries[i & (EHCI_VFRAMELIST_ENTRIES_COUNT - 1)]->this_phy;
529 		TRACE("periodic entry %" B_PRId32 " linked to 0x%" B_PRIx32 "\n", i,
530 			fPeriodicFrameList[i]);
531 	}
532 
533 	// Create the array that will keep bandwidth information
534 	fFrameBandwidth = new(std::nothrow) uint16[EHCI_VFRAMELIST_ENTRIES_COUNT];
535 	for (int32 i = 0; i < EHCI_VFRAMELIST_ENTRIES_COUNT; i++) {
536 		fFrameBandwidth[i] = MAX_AVAILABLE_BANDWIDTH;
537 	}
538 
539 	// allocate a queue head that will always stay in the async frame list
540 	fAsyncQueueHead = CreateQueueHead();
541 	if (!fAsyncQueueHead) {
542 		TRACE_ERROR("unable to allocate stray async queue head\n");
543 		return;
544 	}
545 
546 	fAsyncQueueHead->next_phy = fAsyncQueueHead->this_phy;
547 	fAsyncQueueHead->next_log = fAsyncQueueHead;
548 	fAsyncQueueHead->prev_log = fAsyncQueueHead;
549 	fAsyncQueueHead->endpoint_chars = EHCI_QH_CHARS_EPS_HIGH
550 		| EHCI_QH_CHARS_RECHEAD;
551 	fAsyncQueueHead->endpoint_caps = 1 << EHCI_QH_CAPS_MULT_SHIFT;
552 	fAsyncQueueHead->overlay.next_phy = EHCI_ITEM_TERMINATE;
553 
554 	WriteOpReg(EHCI_ASYNCLISTADDR, (uint32)fAsyncQueueHead->this_phy);
555 	TRACE("set the async list addr to 0x%08" B_PRIx32 "\n",
556 		ReadOpReg(EHCI_ASYNCLISTADDR));
557 
558 	fInitOK = true;
559 	TRACE("EHCI host controller driver constructed\n");
560 }
561 
562 
563 EHCI::~EHCI()
564 {
565 	TRACE("tear down EHCI host controller driver\n");
566 
567 	WriteOpReg(EHCI_USBCMD, 0);
568 	WriteOpReg(EHCI_CONFIGFLAG, 0);
569 	CancelAllPendingTransfers();
570 
571 	int32 result = 0;
572 	fStopThreads = true;
573 	delete_sem(fAsyncAdvanceSem);
574 	delete_sem(fFinishTransfersSem);
575 	delete_sem(fFinishIsochronousTransfersSem);
576 	wait_for_thread(fFinishThread, &result);
577 	wait_for_thread(fCleanupThread, &result);
578 	wait_for_thread(fFinishIsochronousThread, &result);
579 
580 	if (fInterruptPollThread >= 0)
581 		wait_for_thread(fInterruptPollThread, &result);
582 	else
583 		remove_io_interrupt_handler(fIRQ, InterruptHandler, (void *)this);
584 
585 	LockIsochronous();
586 	isochronous_transfer_data *isoTransfer = fFirstIsochronousTransfer;
587 	while (isoTransfer) {
588 		isochronous_transfer_data *next = isoTransfer->link;
589 		delete isoTransfer;
590 		isoTransfer = next;
591 	}
592 	mutex_destroy(&fIsochronousLock);
593 
594 	delete fRootHub;
595 	delete [] fFrameBandwidth;
596 	delete [] fItdEntries;
597 	delete [] fSitdEntries;
598 	delete_area(fPeriodicFrameListArea);
599 	delete_area(fRegisterArea);
600 
601 	if (fUseMSI && sPCIx86Module != NULL) {
602 		sPCIx86Module->disable_msi(fPCIInfo->bus,
603 			fPCIInfo->device, fPCIInfo->function);
604 		sPCIx86Module->unconfigure_msi(fPCIInfo->bus,
605 			fPCIInfo->device, fPCIInfo->function);
606 	}
607 	put_module(B_PCI_MODULE_NAME);
608 
609 	if (sPCIx86Module != NULL) {
610 		sPCIx86Module = NULL;
611 		put_module(B_PCI_X86_MODULE_NAME);
612 	}
613 }
614 
615 
616 status_t
617 EHCI::Start()
618 {
619 	TRACE("starting EHCI host controller\n");
620 	TRACE("usbcmd: 0x%08" B_PRIx32 "; usbsts: 0x%08" B_PRIx32 "\n",
621 		ReadOpReg(EHCI_USBCMD), ReadOpReg(EHCI_USBSTS));
622 
623 	bool hasPerPortChangeEvent = (ReadCapReg32(EHCI_HCCPARAMS)
624 		& EHCI_HCCPARAMS_PPCEC) != 0;
625 
626 	uint32 config = ReadOpReg(EHCI_USBCMD);
627 	config &= ~((EHCI_USBCMD_ITC_MASK << EHCI_USBCMD_ITC_SHIFT)
628 		| EHCI_USBCMD_PPCEE);
629 	uint32 frameListSize = (config >> EHCI_USBCMD_FLS_SHIFT)
630 		& EHCI_USBCMD_FLS_MASK;
631 
632 	WriteOpReg(EHCI_USBCMD, config | EHCI_USBCMD_RUNSTOP
633 		| (hasPerPortChangeEvent ? EHCI_USBCMD_PPCEE : 0)
634 		| EHCI_USBCMD_ASENABLE | EHCI_USBCMD_PSENABLE
635 		| (frameListSize << EHCI_USBCMD_FLS_SHIFT)
636 		| (1 << EHCI_USBCMD_ITC_SHIFT));
637 
638 	switch (frameListSize) {
639 		case 0:
640 			TRACE("frame list size 1024\n");
641 			break;
642 		case 1:
643 			TRACE("frame list size 512\n");
644 			break;
645 		case 2:
646 			TRACE("frame list size 256\n");
647 			break;
648 		default:
649 			TRACE_ALWAYS("unknown frame list size\n");
650 	}
651 
652 	bool running = false;
653 	for (int32 i = 0; i < 10; i++) {
654 		uint32 status = ReadOpReg(EHCI_USBSTS);
655 		TRACE("try %" B_PRId32 ": status 0x%08" B_PRIx32 "\n", i, status);
656 
657 		if (status & EHCI_USBSTS_HCHALTED) {
658 			snooze(10000);
659 		} else {
660 			running = true;
661 			break;
662 		}
663 	}
664 
665 	if (!running) {
666 		TRACE_ERROR("host controller didn't start\n");
667 		return B_ERROR;
668 	}
669 
670 	// route all ports to us
671 	WriteOpReg(EHCI_CONFIGFLAG, EHCI_CONFIGFLAG_FLAG);
672 	snooze(10000);
673 
674 	fRootHubAddress = AllocateAddress();
675 	fRootHub = new(std::nothrow) EHCIRootHub(RootObject(), fRootHubAddress);
676 	if (!fRootHub) {
677 		TRACE_ERROR("no memory to allocate root hub\n");
678 		return B_NO_MEMORY;
679 	}
680 
681 	if (fRootHub->InitCheck() != B_OK) {
682 		TRACE_ERROR("root hub failed init check\n");
683 		return fRootHub->InitCheck();
684 	}
685 
686 	SetRootHub(fRootHub);
687 
688 	TRACE_ALWAYS("successfully started the controller\n");
689 	return BusManager::Start();
690 }
691 
692 
693 status_t
694 EHCI::StartDebugTransfer(Transfer *transfer)
695 {
696 	static transfer_data transferData;
697 
698 	transferData.queue_head = CreateQueueHead();
699 	if (transferData.queue_head == NULL)
700 		return B_NO_MEMORY;
701 
702 	Pipe *pipe = transfer->TransferPipe();
703 	status_t result = InitQueueHead(transferData.queue_head, pipe);
704 	if (result != B_OK) {
705 		FreeQueueHead(transferData.queue_head);
706 		return result;
707 	}
708 
709 	if ((pipe->Type() & USB_OBJECT_CONTROL_PIPE) != 0) {
710 		result = FillQueueWithRequest(transfer, transferData.queue_head,
711 			&transferData.data_descriptor, &transferData.incoming);
712 	} else {
713 		result = FillQueueWithData(transfer, transferData.queue_head,
714 			&transferData.data_descriptor, &transferData.incoming);
715 	}
716 
717 	if (result != B_OK) {
718 		FreeQueueHead(transferData.queue_head);
719 		return result;
720 	}
721 
722 	if ((pipe->Type() & USB_OBJECT_INTERRUPT_PIPE) != 0)
723 		LinkPeriodicDebugQueueHead(transferData.queue_head, pipe);
724 	else
725 		LinkAsyncDebugQueueHead(transferData.queue_head);
726 
727 	// we abuse the callback cookie to hold our transfer data
728 	transfer->SetCallback(NULL, &transferData);
729 	return B_OK;
730 }
731 
732 
733 void
734 EHCI::LinkAsyncDebugQueueHead(ehci_qh *queueHead)
735 {
736 	ehci_qh *prevHead = fAsyncQueueHead->prev_log;
737 	queueHead->next_phy = fAsyncQueueHead->this_phy;
738 	queueHead->next_log = fAsyncQueueHead;
739 	queueHead->prev_log = prevHead;
740 	fAsyncQueueHead->prev_log = queueHead;
741 	prevHead->next_log = queueHead;
742 	prevHead->next_phy = queueHead->this_phy;
743 }
744 
745 
746 void
747 EHCI::LinkPeriodicDebugQueueHead(ehci_qh *queueHead, Pipe *pipe)
748 {
749 	if (pipe->Speed() == USB_SPEED_HIGHSPEED)
750 		queueHead->endpoint_caps |= (0xff << EHCI_QH_CAPS_ISM_SHIFT);
751 	else {
752 		queueHead->endpoint_caps |= (0x01 << EHCI_QH_CAPS_ISM_SHIFT);
753 		queueHead->endpoint_caps |= (0x1c << EHCI_QH_CAPS_SCM_SHIFT);
754 	}
755 
756 	ehci_qh *interruptQueue = &fInterruptEntries[0].queue_head;
757 	queueHead->next_phy = interruptQueue->next_phy;
758 	queueHead->next_log = interruptQueue->next_log;
759 	queueHead->prev_log = interruptQueue;
760 	if (interruptQueue->next_log)
761 		interruptQueue->next_log->prev_log = queueHead;
762 	interruptQueue->next_log = queueHead;
763 	interruptQueue->next_phy = queueHead->this_phy;
764 }
765 
766 
767 status_t
768 EHCI::CheckDebugTransfer(Transfer *transfer)
769 {
770 	bool transferOK = false;
771 	bool transferError = false;
772 	transfer_data *transferData = (transfer_data *)transfer->CallbackCookie();
773 	ehci_qtd *descriptor = transferData->queue_head->element_log;
774 
775 	while (descriptor) {
776 		uint32 status = descriptor->token;
777 		if ((status & EHCI_QTD_STATUS_ACTIVE) != 0) {
778 			// still in progress
779 			break;
780 		}
781 
782 		if ((status & EHCI_QTD_STATUS_ERRMASK) != 0) {
783 			transferError = true;
784 			break;
785 		}
786 
787 		if ((descriptor->next_phy & EHCI_ITEM_TERMINATE) != 0) {
788 			// we arrived at the last (stray) descriptor, we're done
789 			transferOK = true;
790 			break;
791 		}
792 
793 		if (((status >> EHCI_QTD_PID_SHIFT) & EHCI_QTD_PID_MASK)
794 				== EHCI_QTD_PID_IN
795 			&& ((status >> EHCI_QTD_BYTES_SHIFT) & EHCI_QTD_BYTES_MASK) != 0) {
796 			// a short packet condition existed on this descriptor
797 			if (descriptor->alt_next_log != NULL) {
798 				descriptor = descriptor->alt_next_log;
799 				continue;
800 			}
801 
802 			transferOK = true;
803 			break;
804 		}
805 
806 		descriptor = descriptor->next_log;
807 	}
808 
809 	if (!transferOK && !transferError) {
810 		spin(75);
811 		return B_DEV_PENDING;
812 	}
813 
814 	if (transferOK) {
815 		bool nextDataToggle = false;
816 		if (transferData->data_descriptor != NULL && transferData->incoming) {
817 			// data to read out
818 			iovec *vector = transfer->Vector();
819 			size_t vectorCount = transfer->VectorCount();
820 
821 			ReadDescriptorChain(transferData->data_descriptor,
822 				vector, vectorCount, &nextDataToggle);
823 		} else if (transferData->data_descriptor != NULL)
824 			ReadActualLength(transferData->data_descriptor, &nextDataToggle);
825 
826 		transfer->TransferPipe()->SetDataToggle(nextDataToggle);
827 	}
828 
829 	CleanupDebugTransfer(transfer);
830 	return transferOK ? B_OK : B_IO_ERROR;
831 }
832 
833 
834 void
835 EHCI::CancelDebugTransfer(Transfer *transfer)
836 {
837 	transfer_data *transferData = (transfer_data *)transfer->CallbackCookie();
838 
839 	// clear the active bit so the descriptors are canceled
840 	ehci_qtd *descriptor = transferData->queue_head->element_log;
841 	while (descriptor != NULL) {
842 		descriptor->token &= ~EHCI_QTD_STATUS_ACTIVE;
843 		descriptor = descriptor->next_log;
844 	}
845 
846 	transfer->Finished(B_CANCELED, 0);
847 	CleanupDebugTransfer(transfer);
848 }
849 
850 
851 void
852 EHCI::CleanupDebugTransfer(Transfer *transfer)
853 {
854 	transfer_data *transferData = (transfer_data *)transfer->CallbackCookie();
855 	ehci_qh *queueHead = transferData->queue_head;
856 	ehci_qh *prevHead = queueHead->prev_log;
857 	if (prevHead != NULL) {
858 		prevHead->next_phy = queueHead->next_phy;
859 		prevHead->next_log = queueHead->next_log;
860 	}
861 
862 	ehci_qh *nextHead = queueHead->next_log;
863 	if (nextHead != NULL)
864 		nextHead->prev_log = queueHead->prev_log;
865 
866 	queueHead->next_phy = fAsyncQueueHead->this_phy;
867 	queueHead->prev_log = NULL;
868 	queueHead->next_log = NULL;
869 
870 	// wait for async advance to ensure the controller does not access this
871 	// queue head anymore.
872 	spin(125);
873 
874 	FreeQueueHead(queueHead);
875 }
876 
877 
878 status_t
879 EHCI::SubmitTransfer(Transfer *transfer)
880 {
881 	// short circuit the root hub
882 	if (transfer->TransferPipe()->DeviceAddress() == fRootHubAddress)
883 		return fRootHub->ProcessTransfer(this, transfer);
884 
885 	Pipe *pipe = transfer->TransferPipe();
886 	if ((pipe->Type() & USB_OBJECT_ISO_PIPE) != 0)
887 		return SubmitIsochronous(transfer);
888 
889 	ehci_qh *queueHead = CreateQueueHead();
890 	if (!queueHead) {
891 		TRACE_ERROR("failed to allocate queue head\n");
892 		return B_NO_MEMORY;
893 	}
894 
895 	status_t result = InitQueueHead(queueHead, pipe);
896 	if (result != B_OK) {
897 		TRACE_ERROR("failed to init queue head\n");
898 		FreeQueueHead(queueHead);
899 		return result;
900 	}
901 
902 	bool directionIn;
903 	ehci_qtd *dataDescriptor;
904 	if ((pipe->Type() & USB_OBJECT_CONTROL_PIPE) != 0) {
905 		result = FillQueueWithRequest(transfer, queueHead, &dataDescriptor,
906 			&directionIn);
907 	} else {
908 		result = FillQueueWithData(transfer, queueHead, &dataDescriptor,
909 			&directionIn);
910 	}
911 
912 	if (result != B_OK) {
913 		TRACE_ERROR("failed to fill transfer queue with data\n");
914 		FreeQueueHead(queueHead);
915 		return result;
916 	}
917 
918 	result = AddPendingTransfer(transfer, queueHead, dataDescriptor,
919 		directionIn);
920 	if (result != B_OK) {
921 		TRACE_ERROR("failed to add pending transfer\n");
922 		FreeQueueHead(queueHead);
923 		return result;
924 	}
925 
926 #ifdef TRACE_USB
927 	TRACE("linking queue\n");
928 	print_queue(queueHead);
929 #endif
930 
931 	if ((pipe->Type() & USB_OBJECT_INTERRUPT_PIPE) != 0)
932 		result = LinkInterruptQueueHead(queueHead, pipe);
933 	else
934 		result = LinkQueueHead(queueHead);
935 
936 	if (result != B_OK) {
937 		TRACE_ERROR("failed to link queue head\n");
938 		FreeQueueHead(queueHead);
939 		return result;
940 	}
941 
942 	return B_OK;
943 }
944 
945 
946 status_t
947 EHCI::SubmitIsochronous(Transfer *transfer)
948 {
949 	Pipe *pipe = transfer->TransferPipe();
950 	bool directionIn = (pipe->Direction() == Pipe::In);
951 	usb_isochronous_data *isochronousData = transfer->IsochronousData();
952 	size_t packetSize = transfer->DataLength();
953 #ifdef TRACE_USB
954 	size_t restSize = packetSize % isochronousData->packet_count;
955 #endif
956 	packetSize /= isochronousData->packet_count;
957 	uint16 currentFrame;
958 
959 	if (packetSize > pipe->MaxPacketSize()) {
960 		TRACE_ERROR(
961 			"isochronous packetSize is bigger than pipe MaxPacketSize\n");
962 		return B_BAD_VALUE;
963 	}
964 
965 	// Ignore the fact that the last descriptor might need less bandwidth.
966 	// The overhead is not worthy.
967 	uint16 bandwidth = transfer->Bandwidth() / isochronousData->packet_count;
968 
969 	TRACE("isochronous transfer descriptor bandwidth %d\n", bandwidth);
970 
971 	// The following holds the list of transfer descriptor of the
972 	// isochronous request. It is used to quickly remove all the isochronous
973 	// descriptors from the frame list, as descriptors are not link to each
974 	// other in a queue like for every other transfer.
975 	ehci_itd **isoRequest
976 		= new(std::nothrow) ehci_itd *[isochronousData->packet_count];
977 	if (isoRequest == NULL) {
978 		TRACE("failed to create isoRequest array!\n");
979 		return B_NO_MEMORY;
980 	}
981 
982 	TRACE("isochronous submitted size=%" B_PRIuSIZE " bytes, TDs=%" B_PRIu32
983 		", maxPacketSize=%" B_PRIuSIZE ", packetSize=%" B_PRIuSIZE
984 		", restSize=%" B_PRIuSIZE "\n", transfer->DataLength(),
985 		isochronousData->packet_count, pipe->MaxPacketSize(), packetSize,
986 		restSize);
987 
988 	// Find the entry where to start inserting the first Isochronous descriptor
989 	if ((isochronousData->flags & USB_ISO_ASAP) != 0 ||
990 		isochronousData->starting_frame_number == NULL) {
991 
992 		if (fFirstIsochronousTransfer != NULL && fNextStartingFrame != -1)
993 			currentFrame = fNextStartingFrame;
994 		else {
995 			uint32 threshold = fThreshold;
996 			TRACE("threshold: %" B_PRIu32 "\n", threshold);
997 
998 			// find the first available frame with enough bandwidth.
999 			// This should always be the case, as defining the starting frame
1000 			// number in the driver makes no sense for many reason, one of which
1001 			// is that frame numbers value are host controller specific, and the
1002 			// driver does not know which host controller is running.
1003 			currentFrame = ((ReadOpReg(EHCI_FRINDEX) + threshold) / 8)
1004 				& (EHCI_FRAMELIST_ENTRIES_COUNT - 1);
1005 		}
1006 
1007 		// Make sure that:
1008 		// 1. We are at least 5ms ahead the controller
1009 		// 2. We stay in the range 0-127
1010 		// 3. There is enough bandwidth in the first entry
1011 		currentFrame &= EHCI_VFRAMELIST_ENTRIES_COUNT - 1;
1012 	} else {
1013 		// Find out if the frame number specified has enough bandwidth,
1014 		// otherwise find the first next available frame with enough bandwidth
1015 		currentFrame = *isochronousData->starting_frame_number;
1016 	}
1017 
1018 	TRACE("isochronous starting frame=%d\n", currentFrame);
1019 
1020 	uint16 itdIndex = 0;
1021 	size_t dataLength = transfer->DataLength();
1022 	void* bufferLog;
1023 	phys_addr_t bufferPhy;
1024 	if (fStack->AllocateChunk(&bufferLog, &bufferPhy, dataLength) != B_OK) {
1025 		TRACE_ERROR("unable to allocate itd buffer\n");
1026 		delete[] isoRequest;
1027 		return B_NO_MEMORY;
1028 	}
1029 
1030 	memset(bufferLog, 0, dataLength);
1031 
1032 	phys_addr_t currentPhy = bufferPhy;
1033 	uint32 frameCount = 0;
1034 	while (dataLength > 0) {
1035 		ehci_itd* itd = CreateItdDescriptor();
1036 		isoRequest[itdIndex++] = itd;
1037 		uint16 pg = 0;
1038 		itd->buffer_phy[pg] = currentPhy & 0xfffff000;
1039 		uint32 offset = currentPhy & 0xfff;
1040 		TRACE("isochronous created itd, filling it with phy %" B_PRIxPHYSADDR
1041 			"\n", currentPhy);
1042 		for (int32 i = 0; i < 8 && dataLength > 0; i++) {
1043 			size_t length = min_c(dataLength, packetSize);
1044 			itd->token[i] = (EHCI_ITD_STATUS_ACTIVE << EHCI_ITD_STATUS_SHIFT)
1045 				| (length << EHCI_ITD_TLENGTH_SHIFT) | (pg << EHCI_ITD_PG_SHIFT)
1046 				| (offset << EHCI_ITD_TOFFSET_SHIFT);
1047 			itd->last_token = i;
1048 			TRACE("isochronous filled slot %" B_PRId32 " 0x%" B_PRIx32 "\n", i,
1049 				itd->token[i]);
1050 			dataLength -= length;
1051 			offset += length;
1052 			if (dataLength > 0 && offset > 0xfff) {
1053 				offset -= B_PAGE_SIZE;
1054 				currentPhy += B_PAGE_SIZE;
1055 				itd->buffer_phy[pg + 1] = currentPhy & 0xfffff000;
1056 				pg++;
1057 			}
1058 			if (dataLength <= 0)
1059 				itd->token[i] |= EHCI_ITD_IOC;
1060 		}
1061 
1062 		currentPhy += (offset & 0xfff) - (currentPhy & 0xfff);
1063 
1064 		itd->buffer_phy[0]
1065 			|= (pipe->EndpointAddress() << EHCI_ITD_ENDPOINT_SHIFT)
1066 				| (pipe->DeviceAddress() << EHCI_ITD_ADDRESS_SHIFT);
1067 		itd->buffer_phy[1]
1068 			|= (pipe->MaxPacketSize() & EHCI_ITD_MAXPACKETSIZE_MASK)
1069 				| (directionIn << EHCI_ITD_DIR_SHIFT);
1070 		itd->buffer_phy[2]
1071 			|= ((((pipe->MaxPacketSize() >> EHCI_ITD_MAXPACKETSIZE_LENGTH) + 1)
1072 				& EHCI_ITD_MUL_MASK) << EHCI_ITD_MUL_SHIFT);
1073 
1074 		TRACE("isochronous filled itd buffer_phy[0,1,2] 0x%" B_PRIx32 ", 0x%"
1075 			B_PRIx32 " 0x%" B_PRIx32 "\n",
1076 			itd->buffer_phy[0], itd->buffer_phy[1], itd->buffer_phy[2]);
1077 
1078 		if (!LockIsochronous())
1079 			continue;
1080 		LinkITDescriptors(itd, &fItdEntries[currentFrame]);
1081 		UnlockIsochronous();
1082 		fFrameBandwidth[currentFrame] -= bandwidth;
1083 		currentFrame = (currentFrame + 1) & (EHCI_VFRAMELIST_ENTRIES_COUNT - 1);
1084 		frameCount++;
1085 	}
1086 
1087 	TRACE("isochronous filled itds count %d\n", itdIndex);
1088 
1089 	// Add transfer to the list
1090 	status_t result = AddPendingIsochronousTransfer(transfer, isoRequest,
1091 		itdIndex - 1, directionIn, bufferPhy, bufferLog,
1092 		transfer->DataLength());
1093 	if (result != B_OK) {
1094 		TRACE_ERROR("failed to add pending isochronous transfer\n");
1095 		for (uint32 i = 0; i < itdIndex; i++)
1096 			FreeDescriptor(isoRequest[i]);
1097 		delete[] isoRequest;
1098 		return result;
1099 	}
1100 
1101 	TRACE("appended isochronous transfer by starting at frame number %d\n",
1102 		currentFrame);
1103 	fNextStartingFrame = currentFrame + 1;
1104 
1105 	// Wake up the isochronous finisher thread
1106 	release_sem_etc(fFinishIsochronousTransfersSem, 1 /*frameCount*/,
1107 		B_DO_NOT_RESCHEDULE);
1108 
1109 	return B_OK;
1110 }
1111 
1112 
1113 isochronous_transfer_data *
1114 EHCI::FindIsochronousTransfer(ehci_itd *itd)
1115 {
1116 	// Simply check every last descriptor of the isochronous transfer list
1117 	isochronous_transfer_data *transfer = fFirstIsochronousTransfer;
1118 	if (transfer) {
1119 		while (transfer->descriptors[transfer->last_to_process]
1120 			!= itd) {
1121 			transfer = transfer->link;
1122 			if (!transfer)
1123 				break;
1124 		}
1125 	}
1126 	return transfer;
1127 }
1128 
1129 
1130 status_t
1131 EHCI::NotifyPipeChange(Pipe *pipe, usb_change change)
1132 {
1133 	TRACE("pipe change %d for pipe %p\n", change, pipe);
1134 	switch (change) {
1135 		case USB_CHANGE_CREATED:
1136 		case USB_CHANGE_DESTROYED: {
1137 			// ToDo: we should create and keep a single queue head
1138 			// for all transfers to/from this pipe
1139 			break;
1140 		}
1141 
1142 		case USB_CHANGE_PIPE_POLICY_CHANGED: {
1143 			// ToDo: for isochronous pipes we might need to adapt to new
1144 			// pipe policy settings here
1145 			break;
1146 		}
1147 	}
1148 
1149 	return B_OK;
1150 }
1151 
1152 
1153 status_t
1154 EHCI::AddTo(Stack *stack)
1155 {
1156 #ifdef TRACE_USB
1157 	set_dprintf_enabled(true);
1158 #endif
1159 
1160 	if (!sPCIModule) {
1161 		status_t status = get_module(B_PCI_MODULE_NAME,
1162 			(module_info **)&sPCIModule);
1163 		if (status != B_OK) {
1164 			TRACE_MODULE_ERROR("getting pci module failed! 0x%08" B_PRIx32
1165 				"\n", status);
1166 			return status;
1167 		}
1168 	}
1169 
1170 	TRACE_MODULE("searching devices\n");
1171 	bool found = false;
1172 	pci_info *item = new(std::nothrow) pci_info;
1173 	if (!item) {
1174 		sPCIModule = NULL;
1175 		put_module(B_PCI_MODULE_NAME);
1176 		return B_NO_MEMORY;
1177 	}
1178 
1179 	// Try to get the PCI x86 module as well so we can enable possible MSIs.
1180 	if (sPCIx86Module == NULL && get_module(B_PCI_X86_MODULE_NAME,
1181 			(module_info **)&sPCIx86Module) != B_OK) {
1182 		// If it isn't there, that's not critical though.
1183 		TRACE_MODULE_ERROR("failed to get pci x86 module\n");
1184 		sPCIx86Module = NULL;
1185 	}
1186 
1187 	for (int32 i = 0; sPCIModule->get_nth_pci_info(i, item) >= B_OK; i++) {
1188 		if (item->class_base == PCI_serial_bus && item->class_sub == PCI_usb
1189 			&& item->class_api == PCI_usb_ehci) {
1190 			if (item->u.h0.interrupt_line == 0
1191 				|| item->u.h0.interrupt_line == 0xFF) {
1192 				TRACE_MODULE_ERROR("found device with invalid IRQ - "
1193 					"check IRQ assignement\n");
1194 				continue;
1195 			}
1196 
1197 			TRACE_MODULE("found device at IRQ %u\n", item->u.h0.interrupt_line);
1198 			EHCI *bus = new(std::nothrow) EHCI(item, stack);
1199 			if (!bus) {
1200 				delete item;
1201 				sPCIModule = NULL;
1202 				put_module(B_PCI_MODULE_NAME);
1203 				if (sPCIx86Module != NULL) {
1204 					sPCIx86Module = NULL;
1205 					put_module(B_PCI_X86_MODULE_NAME);
1206 				}
1207 				return B_NO_MEMORY;
1208 			}
1209 
1210 			if (bus->InitCheck() != B_OK) {
1211 				TRACE_MODULE_ERROR("bus failed init check\n");
1212 				delete bus;
1213 				continue;
1214 			}
1215 
1216 			// the bus took it away
1217 			item = new(std::nothrow) pci_info;
1218 
1219 			bus->Start();
1220 			stack->AddBusManager(bus);
1221 			found = true;
1222 		}
1223 	}
1224 
1225 	if (!found) {
1226 		TRACE_MODULE_ERROR("no devices found\n");
1227 		delete item;
1228 		sPCIModule = NULL;
1229 		put_module(B_PCI_MODULE_NAME);
1230 		if (sPCIx86Module != NULL) {
1231 			sPCIx86Module = NULL;
1232 			put_module(B_PCI_X86_MODULE_NAME);
1233 		}
1234 		return ENODEV;
1235 	}
1236 
1237 	delete item;
1238 	return B_OK;
1239 }
1240 
1241 
1242 status_t
1243 EHCI::GetPortStatus(uint8 index, usb_port_status *status)
1244 {
1245 	if (index >= fPortCount)
1246 		return B_BAD_INDEX;
1247 
1248 	status->status = status->change = 0;
1249 	uint32 portStatus = ReadOpReg(EHCI_PORTSC + index * sizeof(uint32));
1250 
1251 	// build the status
1252 	if (portStatus & EHCI_PORTSC_CONNSTATUS)
1253 		status->status |= PORT_STATUS_CONNECTION;
1254 	if (portStatus & EHCI_PORTSC_ENABLE)
1255 		status->status |= PORT_STATUS_ENABLE;
1256 	if (portStatus & EHCI_PORTSC_ENABLE)
1257 		status->status |= PORT_STATUS_HIGH_SPEED;
1258 	if (portStatus & EHCI_PORTSC_OCACTIVE)
1259 		status->status |= PORT_STATUS_OVER_CURRENT;
1260 	if (portStatus & EHCI_PORTSC_PORTRESET)
1261 		status->status |= PORT_STATUS_RESET;
1262 	if (portStatus & EHCI_PORTSC_PORTPOWER)
1263 		status->status |= PORT_STATUS_POWER;
1264 	if (portStatus & EHCI_PORTSC_SUSPEND)
1265 		status->status |= PORT_STATUS_SUSPEND;
1266 	if (portStatus & EHCI_PORTSC_DMINUS)
1267 		status->status |= PORT_STATUS_LOW_SPEED;
1268 
1269 	// build the change
1270 	if (portStatus & EHCI_PORTSC_CONNCHANGE)
1271 		status->change |= PORT_STATUS_CONNECTION;
1272 	if (portStatus & EHCI_PORTSC_ENABLECHANGE)
1273 		status->change |= PORT_STATUS_ENABLE;
1274 	if (portStatus & EHCI_PORTSC_OCCHANGE)
1275 		status->change |= PORT_STATUS_OVER_CURRENT;
1276 
1277 	// there are no bits to indicate suspend and reset change
1278 	if (fPortResetChange & (1 << index))
1279 		status->change |= PORT_STATUS_RESET;
1280 	if (fPortSuspendChange & (1 << index))
1281 		status->change |= PORT_STATUS_SUSPEND;
1282 
1283 	return B_OK;
1284 }
1285 
1286 
1287 status_t
1288 EHCI::SetPortFeature(uint8 index, uint16 feature)
1289 {
1290 	if (index >= fPortCount)
1291 		return B_BAD_INDEX;
1292 
1293 	uint32 portRegister = EHCI_PORTSC + index * sizeof(uint32);
1294 	uint32 portStatus = ReadOpReg(portRegister) & EHCI_PORTSC_DATAMASK;
1295 
1296 	switch (feature) {
1297 		case PORT_SUSPEND:
1298 			return SuspendPort(index);
1299 
1300 		case PORT_RESET:
1301 			return ResetPort(index);
1302 
1303 		case PORT_POWER:
1304 			WriteOpReg(portRegister, portStatus | EHCI_PORTSC_PORTPOWER);
1305 			return B_OK;
1306 	}
1307 
1308 	return B_BAD_VALUE;
1309 }
1310 
1311 
1312 status_t
1313 EHCI::ClearPortFeature(uint8 index, uint16 feature)
1314 {
1315 	if (index >= fPortCount)
1316 		return B_BAD_INDEX;
1317 
1318 	uint32 portRegister = EHCI_PORTSC + index * sizeof(uint32);
1319 	uint32 portStatus = ReadOpReg(portRegister) & EHCI_PORTSC_DATAMASK;
1320 
1321 	switch (feature) {
1322 		case PORT_ENABLE:
1323 			WriteOpReg(portRegister, portStatus & ~EHCI_PORTSC_ENABLE);
1324 			return B_OK;
1325 
1326 		case PORT_POWER:
1327 			WriteOpReg(portRegister, portStatus & ~EHCI_PORTSC_PORTPOWER);
1328 			return B_OK;
1329 
1330 		case C_PORT_CONNECTION:
1331 			WriteOpReg(portRegister, portStatus | EHCI_PORTSC_CONNCHANGE);
1332 			return B_OK;
1333 
1334 		case C_PORT_ENABLE:
1335 			WriteOpReg(portRegister, portStatus | EHCI_PORTSC_ENABLECHANGE);
1336 			return B_OK;
1337 
1338 		case C_PORT_OVER_CURRENT:
1339 			WriteOpReg(portRegister, portStatus | EHCI_PORTSC_OCCHANGE);
1340 			return B_OK;
1341 
1342 		case C_PORT_RESET:
1343 			fPortResetChange &= ~(1 << index);
1344 			return B_OK;
1345 
1346 		case C_PORT_SUSPEND:
1347 			fPortSuspendChange &= ~(1 << index);
1348 			return B_OK;
1349 	}
1350 
1351 	return B_BAD_VALUE;
1352 }
1353 
1354 
1355 status_t
1356 EHCI::ResetPort(uint8 index)
1357 {
1358 	TRACE("reset port %d\n", index);
1359 	uint32 portRegister = EHCI_PORTSC + index * sizeof(uint32);
1360 	uint32 portStatus = ReadOpReg(portRegister) & EHCI_PORTSC_DATAMASK;
1361 
1362 	if (portStatus & EHCI_PORTSC_DMINUS) {
1363 		TRACE_ALWAYS("lowspeed device connected, giving up port ownership\n");
1364 		// there is a lowspeed device connected.
1365 		// we give the ownership to a companion controller.
1366 		WriteOpReg(portRegister, portStatus | EHCI_PORTSC_PORTOWNER);
1367 		fPortResetChange |= (1 << index);
1368 		return B_OK;
1369 	}
1370 
1371 	// enable reset signaling
1372 	WriteOpReg(portRegister, (portStatus & ~EHCI_PORTSC_ENABLE)
1373 		| EHCI_PORTSC_PORTRESET);
1374 	snooze(50000);
1375 
1376 	// disable reset signaling
1377 	portStatus = ReadOpReg(portRegister) & EHCI_PORTSC_DATAMASK;
1378 	WriteOpReg(portRegister, portStatus & ~EHCI_PORTSC_PORTRESET);
1379 	snooze(2000);
1380 
1381 	portStatus = ReadOpReg(portRegister) & EHCI_PORTSC_DATAMASK;
1382 	if (portStatus & EHCI_PORTSC_PORTRESET) {
1383 		TRACE_ERROR("port reset won't complete\n");
1384 		return B_ERROR;
1385 	}
1386 
1387 	if ((portStatus & EHCI_PORTSC_ENABLE) == 0) {
1388 		TRACE_ALWAYS("fullspeed device connected, giving up port ownership\n");
1389 		// the port was not enabled, this means that no high speed device is
1390 		// attached to this port. we give up ownership to a companion controler
1391 		WriteOpReg(portRegister, portStatus | EHCI_PORTSC_PORTOWNER);
1392 	}
1393 
1394 	fPortResetChange |= (1 << index);
1395 	return B_OK;
1396 }
1397 
1398 
1399 status_t
1400 EHCI::SuspendPort(uint8 index)
1401 {
1402 	uint32 portRegister = EHCI_PORTSC + index * sizeof(uint32);
1403 	uint32 portStatus = ReadOpReg(portRegister) & EHCI_PORTSC_DATAMASK;
1404 	WriteOpReg(portRegister, portStatus | EHCI_PORTSC_SUSPEND);
1405 	fPortSuspendChange |= (1 << index);
1406 	return B_OK;
1407 }
1408 
1409 
1410 status_t
1411 EHCI::ControllerReset()
1412 {
1413 	// halt the controller first
1414 	WriteOpReg(EHCI_USBCMD, 0);
1415 	snooze(10000);
1416 
1417 	// then reset it
1418 	WriteOpReg(EHCI_USBCMD, EHCI_USBCMD_HCRESET);
1419 
1420 	int32 tries = 5;
1421 	while (ReadOpReg(EHCI_USBCMD) & EHCI_USBCMD_HCRESET) {
1422 		snooze(10000);
1423 		if (tries-- < 0)
1424 			return B_ERROR;
1425 	}
1426 
1427 	return B_OK;
1428 }
1429 
1430 
1431 status_t
1432 EHCI::LightReset()
1433 {
1434 	return B_ERROR;
1435 }
1436 
1437 
1438 int32
1439 EHCI::InterruptHandler(void *data)
1440 {
1441 	return ((EHCI *)data)->Interrupt();
1442 }
1443 
1444 
1445 int32
1446 EHCI::Interrupt()
1447 {
1448 	static spinlock lock = B_SPINLOCK_INITIALIZER;
1449 	acquire_spinlock(&lock);
1450 
1451 	// check if any interrupt was generated
1452 	uint32 status = ReadOpReg(EHCI_USBSTS) & EHCI_USBSTS_INTMASK;
1453 	if ((status & fEnabledInterrupts) == 0) {
1454 		if (status != 0) {
1455 			TRACE("discarding not enabled interrupts 0x%08" B_PRIx32 "\n",
1456 				status);
1457 			WriteOpReg(EHCI_USBSTS, status);
1458 		}
1459 
1460 		release_spinlock(&lock);
1461 		return B_UNHANDLED_INTERRUPT;
1462 	}
1463 
1464 	bool asyncAdvance = false;
1465 	bool finishTransfers = false;
1466 	int32 result = B_HANDLED_INTERRUPT;
1467 
1468 	if (status & EHCI_USBSTS_USBINT) {
1469 		TRACE("transfer finished\n");
1470 		result = B_INVOKE_SCHEDULER;
1471 		finishTransfers = true;
1472 	}
1473 
1474 	if (status & EHCI_USBSTS_USBERRINT) {
1475 		TRACE("transfer error\n");
1476 		result = B_INVOKE_SCHEDULER;
1477 		finishTransfers = true;
1478 	}
1479 
1480 	if (status & EHCI_USBSTS_FLROLLOVER)
1481 		TRACE("frame list rollover\n");
1482 
1483 	if (status & EHCI_USBSTS_PORTCHANGE)
1484 		TRACE("port change detected\n");
1485 
1486 	if (status & EHCI_USBSTS_INTONAA) {
1487 		TRACE("interrupt on async advance\n");
1488 		asyncAdvance = true;
1489 		result = B_INVOKE_SCHEDULER;
1490 	}
1491 
1492 	if (status & EHCI_USBSTS_HOSTSYSERR)
1493 		TRACE_ERROR("host system error!\n");
1494 
1495 	WriteOpReg(EHCI_USBSTS, status);
1496 	release_spinlock(&lock);
1497 
1498 	if (asyncAdvance)
1499 		release_sem_etc(fAsyncAdvanceSem, 1, B_DO_NOT_RESCHEDULE);
1500 	if (finishTransfers)
1501 		release_sem_etc(fFinishTransfersSem, 1, B_DO_NOT_RESCHEDULE);
1502 
1503 	return result;
1504 }
1505 
1506 
1507 int32
1508 EHCI::InterruptPollThread(void *data)
1509 {
1510 	EHCI *ehci = (EHCI *)data;
1511 
1512 	while (!ehci->fStopThreads) {
1513 		// TODO: this could be handled much better by only polling when there
1514 		// are actual transfers going on...
1515 		snooze(1000);
1516 
1517 		cpu_status status = disable_interrupts();
1518 		ehci->Interrupt();
1519 		restore_interrupts(status);
1520 	}
1521 
1522 	return 0;
1523 }
1524 
1525 
1526 status_t
1527 EHCI::AddPendingTransfer(Transfer *transfer, ehci_qh *queueHead,
1528 	ehci_qtd *dataDescriptor, bool directionIn)
1529 {
1530 	transfer_data *data = new(std::nothrow) transfer_data;
1531 	if (!data)
1532 		return B_NO_MEMORY;
1533 
1534 	status_t result = transfer->InitKernelAccess();
1535 	if (result != B_OK) {
1536 		delete data;
1537 		return result;
1538 	}
1539 
1540 	data->transfer = transfer;
1541 	data->queue_head = queueHead;
1542 	data->data_descriptor = dataDescriptor;
1543 	data->incoming = directionIn;
1544 	data->canceled = false;
1545 	data->link = NULL;
1546 
1547 	if (!Lock()) {
1548 		delete data;
1549 		return B_ERROR;
1550 	}
1551 
1552 	if (fLastTransfer)
1553 		fLastTransfer->link = data;
1554 	else
1555 		fFirstTransfer = data;
1556 
1557 	fLastTransfer = data;
1558 	Unlock();
1559 
1560 	return B_OK;
1561 }
1562 
1563 
1564 status_t
1565 EHCI::AddPendingIsochronousTransfer(Transfer *transfer, ehci_itd **isoRequest,
1566 	uint32 lastIndex, bool directionIn, addr_t bufferPhy, void* bufferLog,
1567 	size_t bufferSize)
1568 {
1569 	if (!transfer || !isoRequest)
1570 		return B_BAD_VALUE;
1571 
1572 	isochronous_transfer_data *data
1573 		= new(std::nothrow) isochronous_transfer_data;
1574 	if (!data)
1575 		return B_NO_MEMORY;
1576 
1577 	status_t result = transfer->InitKernelAccess();
1578 	if (result != B_OK) {
1579 		delete data;
1580 		return result;
1581 	}
1582 
1583 	data->transfer = transfer;
1584 	data->descriptors = isoRequest;
1585 	data->last_to_process = lastIndex;
1586 	data->incoming = directionIn;
1587 	data->is_active = true;
1588 	data->link = NULL;
1589 	data->buffer_phy = bufferPhy;
1590 	data->buffer_log = bufferLog;
1591 	data->buffer_size = bufferSize;
1592 
1593 	// Put in the isochronous transfer list
1594 	if (!LockIsochronous()) {
1595 		delete data;
1596 		return B_ERROR;
1597 	}
1598 
1599 	if (fLastIsochronousTransfer)
1600 		fLastIsochronousTransfer->link = data;
1601 	else if (!fFirstIsochronousTransfer)
1602 		fFirstIsochronousTransfer = data;
1603 
1604 	fLastIsochronousTransfer = data;
1605 	UnlockIsochronous();
1606 	return B_OK;
1607 }
1608 
1609 
1610 status_t
1611 EHCI::CancelQueuedTransfers(Pipe *pipe, bool force)
1612 {
1613 	if ((pipe->Type() & USB_OBJECT_ISO_PIPE) != 0)
1614 		return CancelQueuedIsochronousTransfers(pipe, force);
1615 
1616 	if (!Lock())
1617 		return B_ERROR;
1618 
1619 	struct transfer_entry {
1620 		Transfer *			transfer;
1621 		transfer_entry *	next;
1622 	};
1623 
1624 	transfer_entry *list = NULL;
1625 	transfer_data *current = fFirstTransfer;
1626 	while (current) {
1627 		if (current->transfer && current->transfer->TransferPipe() == pipe) {
1628 			// clear the active bit so the descriptors are canceled
1629 			ehci_qtd *descriptor = current->queue_head->element_log;
1630 			while (descriptor) {
1631 				descriptor->token &= ~EHCI_QTD_STATUS_ACTIVE;
1632 				descriptor = descriptor->next_log;
1633 			}
1634 
1635 			if (!force) {
1636 				// if the transfer is canceled by force, the one causing the
1637 				// cancel is probably not the one who initiated the transfer
1638 				// and the callback is likely not safe anymore
1639 				transfer_entry *entry
1640 					= (transfer_entry *)malloc(sizeof(transfer_entry));
1641 				if (entry != NULL) {
1642 					entry->transfer = current->transfer;
1643 					current->transfer = NULL;
1644 					entry->next = list;
1645 					list = entry;
1646 				}
1647 			}
1648 
1649 			current->canceled = true;
1650 		}
1651 
1652 		current = current->link;
1653 	}
1654 
1655 	Unlock();
1656 
1657 	while (list != NULL) {
1658 		transfer_entry *next = list->next;
1659 		list->transfer->Finished(B_CANCELED, 0);
1660 		delete list->transfer;
1661 		free(list);
1662 		list = next;
1663 	}
1664 
1665 	// wait for any transfers that might have made it before canceling
1666 	while (fProcessingPipe == pipe)
1667 		snooze(1000);
1668 
1669 	// notify the finisher so it can clean up the canceled transfers
1670 	release_sem_etc(fFinishTransfersSem, 1, B_DO_NOT_RESCHEDULE);
1671 	return B_OK;
1672 }
1673 
1674 
1675 status_t
1676 EHCI::CancelQueuedIsochronousTransfers(Pipe *pipe, bool force)
1677 {
1678 	isochronous_transfer_data *current = fFirstIsochronousTransfer;
1679 
1680 	while (current) {
1681 		if (current->transfer->TransferPipe() == pipe) {
1682 			// TODO implement
1683 
1684 			// TODO: Use the force paramater in order to avoid calling
1685 			// invalid callbacks
1686 			current->is_active = false;
1687 		}
1688 
1689 		current = current->link;
1690 	}
1691 
1692 	TRACE_ERROR("no isochronous transfer found!\n");
1693 	return B_ERROR;
1694 }
1695 
1696 
1697 status_t
1698 EHCI::CancelAllPendingTransfers()
1699 {
1700 	if (!Lock())
1701 		return B_ERROR;
1702 
1703 	transfer_data *transfer = fFirstTransfer;
1704 	while (transfer) {
1705 		transfer->transfer->Finished(B_CANCELED, 0);
1706 		delete transfer->transfer;
1707 
1708 		transfer_data *next = transfer->link;
1709 		delete transfer;
1710 		transfer = next;
1711 	}
1712 
1713 	fFirstTransfer = NULL;
1714 	fLastTransfer = NULL;
1715 	Unlock();
1716 	return B_OK;
1717 }
1718 
1719 
1720 int32
1721 EHCI::FinishThread(void *data)
1722 {
1723 	((EHCI *)data)->FinishTransfers();
1724 	return B_OK;
1725 }
1726 
1727 
1728 void
1729 EHCI::FinishTransfers()
1730 {
1731 	while (!fStopThreads) {
1732 		if (acquire_sem(fFinishTransfersSem) != B_OK)
1733 			continue;
1734 
1735 		// eat up sems that have been released by multiple interrupts
1736 		int32 semCount = 0;
1737 		get_sem_count(fFinishTransfersSem, &semCount);
1738 		if (semCount > 0) {
1739 			acquire_sem_etc(fFinishTransfersSem, semCount, B_RELATIVE_TIMEOUT,
1740 				0);
1741 		}
1742 
1743 		if (!Lock())
1744 			continue;
1745 
1746 		TRACE("finishing transfers\n");
1747 		transfer_data *lastTransfer = NULL;
1748 		transfer_data *transfer = fFirstTransfer;
1749 		Unlock();
1750 
1751 		while (transfer) {
1752 			bool transferDone = false;
1753 			ehci_qtd *descriptor = transfer->queue_head->element_log;
1754 			status_t callbackStatus = B_OK;
1755 
1756 			while (descriptor) {
1757 				uint32 status = descriptor->token;
1758 				if (status & EHCI_QTD_STATUS_ACTIVE) {
1759 					// still in progress
1760 					TRACE("qtd (0x%08" B_PRIx32 ") still active\n",
1761 						descriptor->this_phy);
1762 					break;
1763 				}
1764 
1765 				if (status & EHCI_QTD_STATUS_ERRMASK) {
1766 					// a transfer error occured
1767 					TRACE_ERROR("qtd (0x%" B_PRIx32 ") error: 0x%08" B_PRIx32
1768 						"\n", descriptor->this_phy, status);
1769 
1770 					uint8 errorCount = status >> EHCI_QTD_ERRCOUNT_SHIFT;
1771 					errorCount &= EHCI_QTD_ERRCOUNT_MASK;
1772 					if (errorCount == 0) {
1773 						// the error counter counted down to zero, report why
1774 						int32 reasons = 0;
1775 						if (status & EHCI_QTD_STATUS_BUFFER) {
1776 							callbackStatus = transfer->incoming
1777 								? B_DEV_DATA_OVERRUN : B_DEV_DATA_UNDERRUN;
1778 							reasons++;
1779 						}
1780 						if (status & EHCI_QTD_STATUS_TERROR) {
1781 							callbackStatus = B_DEV_CRC_ERROR;
1782 							reasons++;
1783 						}
1784 						if ((transfer->queue_head->endpoint_chars
1785 								& EHCI_QH_CHARS_EPS_HIGH) == 0) {
1786 							// For full-/lowspeed endpoints the unused ping
1787 							// state bit is used as another error bit, it is
1788 							// unspecific however.
1789 							if ((status & EHCI_QTD_STATUS_LS_ERR) != 0) {
1790 								callbackStatus = B_DEV_STALLED;
1791 								reasons++;
1792 							}
1793 						}
1794 
1795 						if (reasons > 1)
1796 							callbackStatus = B_DEV_MULTIPLE_ERRORS;
1797 						else if (reasons == 0) {
1798 							TRACE_ERROR("error counter counted down to zero "
1799 								"but none of the error bits are set\n");
1800 							callbackStatus = B_DEV_STALLED;
1801 						}
1802 					} else if (status & EHCI_QTD_STATUS_BABBLE) {
1803 						// there is a babble condition
1804 						callbackStatus = transfer->incoming
1805 							? B_DEV_FIFO_OVERRUN : B_DEV_FIFO_UNDERRUN;
1806 					} else {
1807 						// if the error counter didn't count down to zero
1808 						// and there was no babble, then this halt was caused
1809 						// by a stall handshake
1810 						callbackStatus = B_DEV_STALLED;
1811 					}
1812 
1813 					transferDone = true;
1814 					break;
1815 				}
1816 
1817 				if (descriptor->next_phy & EHCI_ITEM_TERMINATE) {
1818 					// we arrived at the last (stray) descriptor, we're done
1819 					TRACE("qtd (0x%08" B_PRIx32 ") done\n",
1820 						descriptor->this_phy);
1821 					callbackStatus = B_OK;
1822 					transferDone = true;
1823 					break;
1824 				}
1825 
1826 				if (((status >> EHCI_QTD_PID_SHIFT) & EHCI_QTD_PID_MASK)
1827 						== EHCI_QTD_PID_IN
1828 					&& ((status >> EHCI_QTD_BYTES_SHIFT) & EHCI_QTD_BYTES_MASK)
1829 						!= 0) {
1830 					// a short packet condition existed on this descriptor,
1831 					// follow the alternate next pointer if set
1832 					if (descriptor->alt_next_log != NULL) {
1833 						descriptor = descriptor->alt_next_log;
1834 						continue;
1835 					}
1836 
1837 					// no alternate next, transfer is done
1838 					callbackStatus = B_OK;
1839 					transferDone = true;
1840 					break;
1841 				}
1842 
1843 				descriptor = descriptor->next_log;
1844 			}
1845 
1846 			if (!transferDone) {
1847 				lastTransfer = transfer;
1848 				transfer = transfer->link;
1849 				continue;
1850 			}
1851 
1852 			// remove the transfer from the list first so we are sure
1853 			// it doesn't get canceled while we still process it
1854 			transfer_data *next = transfer->link;
1855 			if (Lock()) {
1856 				if (lastTransfer)
1857 					lastTransfer->link = transfer->link;
1858 
1859 				if (transfer == fFirstTransfer)
1860 					fFirstTransfer = transfer->link;
1861 				if (transfer == fLastTransfer)
1862 					fLastTransfer = lastTransfer;
1863 
1864 				// store the currently processing pipe here so we can wait
1865 				// in cancel if we are processing something on the target pipe
1866 				if (!transfer->canceled)
1867 					fProcessingPipe = transfer->transfer->TransferPipe();
1868 
1869 				transfer->link = NULL;
1870 				Unlock();
1871 			}
1872 
1873 			// if canceled the callback has already been called
1874 			if (!transfer->canceled) {
1875 				size_t actualLength = 0;
1876 
1877 				if (callbackStatus == B_OK) {
1878 					bool nextDataToggle = false;
1879 					if (transfer->data_descriptor && transfer->incoming) {
1880 						// data to read out
1881 						iovec *vector = transfer->transfer->Vector();
1882 						size_t vectorCount = transfer->transfer->VectorCount();
1883 						transfer->transfer->PrepareKernelAccess();
1884 						actualLength = ReadDescriptorChain(
1885 							transfer->data_descriptor,
1886 							vector, vectorCount,
1887 							&nextDataToggle);
1888 					} else if (transfer->data_descriptor) {
1889 						// calculate transfered length
1890 						actualLength = ReadActualLength(
1891 							transfer->data_descriptor, &nextDataToggle);
1892 					}
1893 
1894 					transfer->transfer->TransferPipe()->SetDataToggle(
1895 						nextDataToggle);
1896 
1897 					if (transfer->transfer->IsFragmented()) {
1898 						// this transfer may still have data left
1899 						transfer->transfer->AdvanceByFragment(actualLength);
1900 						if (transfer->transfer->VectorLength() > 0) {
1901 							FreeDescriptorChain(transfer->data_descriptor);
1902 							transfer->transfer->PrepareKernelAccess();
1903 							status_t result = FillQueueWithData(
1904 								transfer->transfer,
1905 								transfer->queue_head,
1906 								&transfer->data_descriptor, NULL);
1907 
1908 							if (result == B_OK && Lock()) {
1909 								// reappend the transfer
1910 								if (fLastTransfer)
1911 									fLastTransfer->link = transfer;
1912 								if (!fFirstTransfer)
1913 									fFirstTransfer = transfer;
1914 
1915 								fLastTransfer = transfer;
1916 								Unlock();
1917 
1918 								transfer = next;
1919 								continue;
1920 							}
1921 						}
1922 
1923 						// the transfer is done, but we already set the
1924 						// actualLength with AdvanceByFragment()
1925 						actualLength = 0;
1926 					}
1927 				}
1928 
1929 				transfer->transfer->Finished(callbackStatus, actualLength);
1930 				fProcessingPipe = NULL;
1931 			}
1932 
1933 			// unlink hardware queue and delete the transfer
1934 			UnlinkQueueHead(transfer->queue_head, &fFreeListHead);
1935 			delete transfer->transfer;
1936 			delete transfer;
1937 			transfer = next;
1938 			release_sem(fCleanupSem);
1939 		}
1940 	}
1941 }
1942 
1943 
1944 int32
1945 EHCI::CleanupThread(void *data)
1946 {
1947 	((EHCI *)data)->Cleanup();
1948 	return B_OK;
1949 }
1950 
1951 
1952 void
1953 EHCI::Cleanup()
1954 {
1955 	ehci_qh *lastFreeListHead = NULL;
1956 
1957 	while (!fStopThreads) {
1958 		if (acquire_sem(fCleanupSem) != B_OK)
1959 			continue;
1960 
1961 		ehci_qh *freeListHead = fFreeListHead;
1962 		if (freeListHead == lastFreeListHead)
1963 			continue;
1964 
1965 		// set the doorbell and wait for the host controller to notify us
1966 		WriteOpReg(EHCI_USBCMD, ReadOpReg(EHCI_USBCMD) | EHCI_USBCMD_INTONAAD);
1967 		if (acquire_sem(fAsyncAdvanceSem) != B_OK)
1968 			continue;
1969 
1970 		ehci_qh *current = freeListHead;
1971 		while (current != lastFreeListHead) {
1972 			ehci_qh *next = current->next_log;
1973 			FreeQueueHead(current);
1974 			current = next;
1975 		}
1976 
1977 		lastFreeListHead = freeListHead;
1978 	}
1979 }
1980 
1981 
1982 int32
1983 EHCI::FinishIsochronousThread(void *data)
1984 {
1985 	((EHCI *)data)->FinishIsochronousTransfers();
1986 	return B_OK;
1987 }
1988 
1989 
1990 void
1991 EHCI::FinishIsochronousTransfers()
1992 {
1993 	/* This thread stays one position behind the controller and processes every
1994 	* isochronous descriptor. Once it finds the last isochronous descriptor
1995 	* of a transfer, it processes the entire transfer.
1996 	*/
1997 	while (!fStopThreads) {
1998 		// Go to sleep if there are no isochronous transfers to process
1999 		if (acquire_sem(fFinishIsochronousTransfersSem) != B_OK)
2000 			return;
2001 
2002 		bool transferDone = false;
2003 
2004 		uint32 frame = (ReadOpReg(EHCI_FRINDEX) / 8 )
2005 			& (EHCI_FRAMELIST_ENTRIES_COUNT - 1);
2006 		uint32 currentFrame = (frame + EHCI_VFRAMELIST_ENTRIES_COUNT - 5)
2007 			& (EHCI_VFRAMELIST_ENTRIES_COUNT - 1);
2008 		uint32 loop = 0;
2009 
2010 		// Process the frame list until one transfer is processed
2011 		while (!transferDone && loop++ < EHCI_VFRAMELIST_ENTRIES_COUNT) {
2012 			// wait 1ms in order to be sure to be one position behind
2013 			// the controller
2014 			while (currentFrame == (((ReadOpReg(EHCI_FRINDEX) / 8)
2015 				& (EHCI_VFRAMELIST_ENTRIES_COUNT - 1)))) {
2016 				snooze(1000);
2017 			}
2018 
2019 			ehci_itd *itd = fItdEntries[currentFrame];
2020 
2021 			TRACE("FinishIsochronousTransfers itd %p phy 0x%" B_PRIx32
2022 				" prev (%p/0x%" B_PRIx32 ") at frame %" B_PRId32 "\n", itd,
2023 				itd->this_phy, itd->prev, itd->prev != NULL
2024 					? itd->prev->this_phy : 0, currentFrame);
2025 
2026 			if (!LockIsochronous())
2027 				continue;
2028 
2029 			// Process the frame till it has isochronous descriptors in it.
2030 			while (!(itd->next_phy & EHCI_ITEM_TERMINATE) && itd->prev != NULL) {
2031 				TRACE("FinishIsochronousTransfers checking itd %p last_token"
2032 					" %" B_PRId32 "\n", itd, itd->last_token);
2033 				TRACE("FinishIsochronousTransfers tokens 0x%" B_PRIx32 " 0x%"
2034 					B_PRIx32 " 0x%" B_PRIx32 " 0x%" B_PRIx32 " 0x%" B_PRIx32
2035 					" 0x%" B_PRIx32 " 0x%" B_PRIx32 " 0x%" B_PRIx32 "\n",
2036 					itd->token[0], itd->token[1], itd->token[2], itd->token[3],
2037 					itd->token[4], itd->token[5], itd->token[6], itd->token[7]);
2038 				if (((itd->token[itd->last_token] >> EHCI_ITD_STATUS_SHIFT)
2039 					& EHCI_ITD_STATUS_ACTIVE) == EHCI_ITD_STATUS_ACTIVE) {
2040 					TRACE("FinishIsochronousTransfers unprocessed active itd\n");
2041 				}
2042 				UnlinkITDescriptors(itd, &fItdEntries[currentFrame]);
2043 
2044 				// Process the transfer if we found the last descriptor
2045 				isochronous_transfer_data *transfer
2046 					= FindIsochronousTransfer(itd);
2047 					// Process the descriptors only if it is still active and
2048 					// belongs to an inbound transfer. If the transfer is not
2049 					// active, it means the request has been removed, so simply
2050 					// remove the descriptors.
2051 				if (transfer && transfer->is_active) {
2052 					TRACE("FinishIsochronousTransfers active transfer\n");
2053 					size_t actualLength = 0;
2054 					if (((itd->buffer_phy[1] >> EHCI_ITD_DIR_SHIFT) & 1) != 0) {
2055 						transfer->transfer->PrepareKernelAccess();
2056 						actualLength = ReadIsochronousDescriptorChain(transfer);
2057 					}
2058 
2059 					// Remove the transfer
2060 					if (transfer == fFirstIsochronousTransfer) {
2061 						fFirstIsochronousTransfer = transfer->link;
2062 						if (transfer == fLastIsochronousTransfer)
2063 							fLastIsochronousTransfer = NULL;
2064 					} else {
2065 						isochronous_transfer_data *temp
2066 							= fFirstIsochronousTransfer;
2067 						while (temp != NULL && transfer != temp->link)
2068 							temp = temp->link;
2069 
2070 						if (transfer == fLastIsochronousTransfer)
2071 							fLastIsochronousTransfer = temp;
2072 						if (temp != NULL && temp->link != NULL)
2073 							temp->link = temp->link->link;
2074 					}
2075 					transfer->link = NULL;
2076 
2077 					transfer->transfer->Finished(B_OK, actualLength);
2078 
2079 					itd = itd->prev;
2080 
2081 					for (uint32 i = 0; i <= transfer->last_to_process; i++)
2082 						FreeDescriptor(transfer->descriptors[i]);
2083 
2084 					TRACE("FinishIsochronousTransfers descriptors freed\n");
2085 
2086 					delete [] transfer->descriptors;
2087 					delete transfer->transfer;
2088 					fStack->FreeChunk(transfer->buffer_log,
2089 						(phys_addr_t)transfer->buffer_phy,
2090 						transfer->buffer_size);
2091 					delete transfer;
2092 					transferDone = true;
2093 				} else {
2094 					TRACE("FinishIsochronousTransfers not end of transfer\n");
2095 					itd = itd->prev;
2096 				}
2097 			}
2098 
2099 			UnlockIsochronous();
2100 
2101 			TRACE("FinishIsochronousTransfers next frame\n");
2102 
2103 			// Make sure to reset the frame bandwidth
2104 			fFrameBandwidth[currentFrame] = MAX_AVAILABLE_BANDWIDTH;
2105 			currentFrame = (currentFrame + 1) % EHCI_VFRAMELIST_ENTRIES_COUNT;
2106 		}
2107 	}
2108 }
2109 
2110 
2111 ehci_qh *
2112 EHCI::CreateQueueHead()
2113 {
2114 	ehci_qh *result;
2115 	phys_addr_t physicalAddress;
2116 	if (fStack->AllocateChunk((void **)&result, &physicalAddress,
2117 			sizeof(ehci_qh)) != B_OK) {
2118 		TRACE_ERROR("failed to allocate queue head\n");
2119 		return NULL;
2120 	}
2121 
2122 	result->this_phy = (addr_t)physicalAddress | EHCI_ITEM_TYPE_QH;
2123 	result->next_phy = EHCI_ITEM_TERMINATE;
2124 	result->next_log = NULL;
2125 	result->prev_log = NULL;
2126 
2127 	ehci_qtd *descriptor = CreateDescriptor(0, 0);
2128 	if (!descriptor) {
2129 		TRACE_ERROR("failed to allocate initial qtd for queue head\n");
2130 		fStack->FreeChunk(result, physicalAddress, sizeof(ehci_qh));
2131 		return NULL;
2132 	}
2133 
2134 	descriptor->token &= ~EHCI_QTD_STATUS_ACTIVE;
2135 	result->stray_log = descriptor;
2136 	result->element_log = descriptor;
2137 	result->current_qtd_phy = 0;
2138 	result->overlay.next_phy = descriptor->this_phy;
2139 	result->overlay.alt_next_phy = EHCI_ITEM_TERMINATE;
2140 	result->overlay.token = 0;
2141 	for (int32 i = 0; i < 5; i++) {
2142 		result->overlay.buffer_phy[i] = 0;
2143 		result->overlay.ext_buffer_phy[i] = 0;
2144 	}
2145 
2146 	return result;
2147 }
2148 
2149 
2150 status_t
2151 EHCI::InitQueueHead(ehci_qh *queueHead, Pipe *pipe)
2152 {
2153 	switch (pipe->Speed()) {
2154 		case USB_SPEED_LOWSPEED:
2155 			queueHead->endpoint_chars = EHCI_QH_CHARS_EPS_LOW;
2156 			break;
2157 		case USB_SPEED_FULLSPEED:
2158 			queueHead->endpoint_chars = EHCI_QH_CHARS_EPS_FULL;
2159 			break;
2160 		case USB_SPEED_HIGHSPEED:
2161 			queueHead->endpoint_chars = EHCI_QH_CHARS_EPS_HIGH;
2162 			break;
2163 		default:
2164 			TRACE_ERROR("unknown pipe speed\n");
2165 			return B_ERROR;
2166 	}
2167 
2168 	queueHead->endpoint_chars |= (3 << EHCI_QH_CHARS_RL_SHIFT)
2169 		| (pipe->MaxPacketSize() << EHCI_QH_CHARS_MPL_SHIFT)
2170 		| (pipe->EndpointAddress() << EHCI_QH_CHARS_EPT_SHIFT)
2171 		| (pipe->DeviceAddress() << EHCI_QH_CHARS_DEV_SHIFT)
2172 		| EHCI_QH_CHARS_TOGGLE;
2173 
2174 	queueHead->endpoint_caps = (1 << EHCI_QH_CAPS_MULT_SHIFT);
2175 	if (pipe->Speed() != USB_SPEED_HIGHSPEED) {
2176 		if ((pipe->Type() & USB_OBJECT_CONTROL_PIPE) != 0)
2177 			queueHead->endpoint_chars |= EHCI_QH_CHARS_CONTROL;
2178 
2179 		queueHead->endpoint_caps |= (pipe->HubPort() << EHCI_QH_CAPS_PORT_SHIFT)
2180 			| (pipe->HubAddress() << EHCI_QH_CAPS_HUB_SHIFT);
2181 	}
2182 
2183 	return B_OK;
2184 }
2185 
2186 
2187 void
2188 EHCI::FreeQueueHead(ehci_qh *queueHead)
2189 {
2190 	if (!queueHead)
2191 		return;
2192 
2193 	FreeDescriptorChain(queueHead->element_log);
2194 	FreeDescriptor(queueHead->stray_log);
2195 	fStack->FreeChunk(queueHead, (phys_addr_t)queueHead->this_phy,
2196 		sizeof(ehci_qh));
2197 }
2198 
2199 
2200 status_t
2201 EHCI::LinkQueueHead(ehci_qh *queueHead)
2202 {
2203 	if (!Lock())
2204 		return B_ERROR;
2205 
2206 	ehci_qh *prevHead = fAsyncQueueHead->prev_log;
2207 	queueHead->next_phy = fAsyncQueueHead->this_phy;
2208 	queueHead->next_log = fAsyncQueueHead;
2209 	queueHead->prev_log = prevHead;
2210 	fAsyncQueueHead->prev_log = queueHead;
2211 	prevHead->next_log = queueHead;
2212 	prevHead->next_phy = queueHead->this_phy;
2213 
2214 	Unlock();
2215 	return B_OK;
2216 }
2217 
2218 
2219 status_t
2220 EHCI::LinkInterruptQueueHead(ehci_qh *queueHead, Pipe *pipe)
2221 {
2222 	uint8 interval = pipe->Interval();
2223 	if (pipe->Speed() == USB_SPEED_HIGHSPEED) {
2224 		// Allow interrupts to be scheduled on each possible micro frame.
2225 		queueHead->endpoint_caps |= (0xff << EHCI_QH_CAPS_ISM_SHIFT);
2226 	} else {
2227 		// As we do not yet support FSTNs to correctly reference low/full
2228 		// speed interrupt transfers, we simply put them into the 1 interval
2229 		// queue. This way we ensure that we reach them on every micro frame
2230 		// and can do the corresponding start/complete split transactions.
2231 		// ToDo: use FSTNs to correctly link non high speed interrupt transfers
2232 		interval = 1;
2233 
2234 		// For now we also force start splits to be in micro frame 0 and
2235 		// complete splits to be in micro frame 2, 3 and 4.
2236 		queueHead->endpoint_caps |= (0x01 << EHCI_QH_CAPS_ISM_SHIFT);
2237 		queueHead->endpoint_caps |= (0x1c << EHCI_QH_CAPS_SCM_SHIFT);
2238 	}
2239 
2240 	// this should not happen
2241 	if (interval < 1)
2242 		interval = 1;
2243 
2244 	// this may happen as intervals can go up to 16; we limit the value to
2245 	// EHCI_INTERRUPT_ENTRIES_COUNT as you cannot support intervals above
2246 	// that with a frame list of just EHCI_VFRAMELIST_ENTRIES_COUNT entries...
2247 	if (interval > EHCI_INTERRUPT_ENTRIES_COUNT)
2248 		interval = EHCI_INTERRUPT_ENTRIES_COUNT;
2249 
2250 	if (!Lock())
2251 		return B_ERROR;
2252 
2253 	ehci_qh *interruptQueue = &fInterruptEntries[interval - 1].queue_head;
2254 	queueHead->next_phy = interruptQueue->next_phy;
2255 	queueHead->next_log = interruptQueue->next_log;
2256 	queueHead->prev_log = interruptQueue;
2257 	if (interruptQueue->next_log)
2258 		interruptQueue->next_log->prev_log = queueHead;
2259 	interruptQueue->next_log = queueHead;
2260 	interruptQueue->next_phy = queueHead->this_phy;
2261 
2262 	Unlock();
2263 	return B_OK;
2264 }
2265 
2266 
2267 status_t
2268 EHCI::UnlinkQueueHead(ehci_qh *queueHead, ehci_qh **freeListHead)
2269 {
2270 	if (!Lock())
2271 		return B_ERROR;
2272 
2273 	ehci_qh *prevHead = queueHead->prev_log;
2274 	ehci_qh *nextHead = queueHead->next_log;
2275 	if (prevHead) {
2276 		prevHead->next_phy = queueHead->next_phy;
2277 		prevHead->next_log = queueHead->next_log;
2278 	}
2279 
2280 	if (nextHead)
2281 		nextHead->prev_log = queueHead->prev_log;
2282 
2283 	queueHead->next_phy = fAsyncQueueHead->this_phy;
2284 	queueHead->prev_log = NULL;
2285 
2286 	queueHead->next_log = *freeListHead;
2287 	*freeListHead = queueHead;
2288 
2289 	Unlock();
2290 	return B_OK;
2291 }
2292 
2293 
2294 status_t
2295 EHCI::FillQueueWithRequest(Transfer *transfer, ehci_qh *queueHead,
2296 	ehci_qtd **_dataDescriptor, bool *_directionIn)
2297 {
2298 	Pipe *pipe = transfer->TransferPipe();
2299 	usb_request_data *requestData = transfer->RequestData();
2300 	bool directionIn = (requestData->RequestType & USB_REQTYPE_DEVICE_IN) > 0;
2301 
2302 	ehci_qtd *setupDescriptor = CreateDescriptor(sizeof(usb_request_data),
2303 		EHCI_QTD_PID_SETUP);
2304 	ehci_qtd *statusDescriptor = CreateDescriptor(0,
2305 		directionIn ? EHCI_QTD_PID_OUT : EHCI_QTD_PID_IN);
2306 
2307 	if (!setupDescriptor || !statusDescriptor) {
2308 		TRACE_ERROR("failed to allocate descriptors\n");
2309 		FreeDescriptor(setupDescriptor);
2310 		FreeDescriptor(statusDescriptor);
2311 		return B_NO_MEMORY;
2312 	}
2313 
2314 	iovec vector;
2315 	vector.iov_base = requestData;
2316 	vector.iov_len = sizeof(usb_request_data);
2317 	WriteDescriptorChain(setupDescriptor, &vector, 1);
2318 
2319 	ehci_qtd *strayDescriptor = queueHead->stray_log;
2320 	statusDescriptor->token |= EHCI_QTD_IOC | EHCI_QTD_DATA_TOGGLE;
2321 
2322 	ehci_qtd *dataDescriptor = NULL;
2323 	if (transfer->VectorCount() > 0) {
2324 		ehci_qtd *lastDescriptor = NULL;
2325 		status_t result = CreateDescriptorChain(pipe, &dataDescriptor,
2326 			&lastDescriptor, statusDescriptor, transfer->VectorLength(),
2327 			directionIn ? EHCI_QTD_PID_IN : EHCI_QTD_PID_OUT);
2328 
2329 		if (result != B_OK) {
2330 			FreeDescriptor(setupDescriptor);
2331 			FreeDescriptor(statusDescriptor);
2332 			return result;
2333 		}
2334 
2335 		if (!directionIn) {
2336 			WriteDescriptorChain(dataDescriptor, transfer->Vector(),
2337 				transfer->VectorCount());
2338 		}
2339 
2340 		LinkDescriptors(setupDescriptor, dataDescriptor, strayDescriptor);
2341 		LinkDescriptors(lastDescriptor, statusDescriptor, statusDescriptor);
2342 	} else {
2343 		// no data: link setup and status descriptors directly
2344 		LinkDescriptors(setupDescriptor, statusDescriptor, strayDescriptor);
2345 	}
2346 
2347 	queueHead->element_log = setupDescriptor;
2348 	queueHead->overlay.next_phy = setupDescriptor->this_phy;
2349 	queueHead->overlay.alt_next_phy = EHCI_ITEM_TERMINATE;
2350 
2351 	*_dataDescriptor = dataDescriptor;
2352 	*_directionIn = directionIn;
2353 	return B_OK;
2354 }
2355 
2356 
2357 status_t
2358 EHCI::FillQueueWithData(Transfer *transfer, ehci_qh *queueHead,
2359 	ehci_qtd **_dataDescriptor, bool *_directionIn)
2360 {
2361 	Pipe *pipe = transfer->TransferPipe();
2362 	bool directionIn = (pipe->Direction() == Pipe::In);
2363 
2364 	ehci_qtd *firstDescriptor = NULL;
2365 	ehci_qtd *lastDescriptor = NULL;
2366 	ehci_qtd *strayDescriptor = queueHead->stray_log;
2367 	status_t result = CreateDescriptorChain(pipe, &firstDescriptor,
2368 		&lastDescriptor, strayDescriptor, transfer->VectorLength(),
2369 		directionIn ? EHCI_QTD_PID_IN : EHCI_QTD_PID_OUT);
2370 
2371 	if (result != B_OK)
2372 		return result;
2373 
2374 	lastDescriptor->token |= EHCI_QTD_IOC;
2375 	if (!directionIn) {
2376 		WriteDescriptorChain(firstDescriptor, transfer->Vector(),
2377 			transfer->VectorCount());
2378 	}
2379 
2380 	queueHead->element_log = firstDescriptor;
2381 	queueHead->overlay.next_phy = firstDescriptor->this_phy;
2382 	queueHead->overlay.alt_next_phy = EHCI_ITEM_TERMINATE;
2383 
2384 	*_dataDescriptor = firstDescriptor;
2385 	if (_directionIn)
2386 		*_directionIn = directionIn;
2387 	return B_OK;
2388 }
2389 
2390 
2391 ehci_qtd *
2392 EHCI::CreateDescriptor(size_t bufferSize, uint8 pid)
2393 {
2394 	ehci_qtd *result;
2395 	phys_addr_t physicalAddress;
2396 	if (fStack->AllocateChunk((void **)&result, &physicalAddress,
2397 			sizeof(ehci_qtd)) != B_OK) {
2398 		TRACE_ERROR("failed to allocate a qtd\n");
2399 		return NULL;
2400 	}
2401 
2402 	result->this_phy = (addr_t)physicalAddress;
2403 	result->next_phy = EHCI_ITEM_TERMINATE;
2404 	result->next_log = NULL;
2405 	result->alt_next_phy = EHCI_ITEM_TERMINATE;
2406 	result->alt_next_log = NULL;
2407 	result->buffer_size = bufferSize;
2408 	result->token = bufferSize << EHCI_QTD_BYTES_SHIFT;
2409 	result->token |= 3 << EHCI_QTD_ERRCOUNT_SHIFT;
2410 	result->token |= pid << EHCI_QTD_PID_SHIFT;
2411 	result->token |= EHCI_QTD_STATUS_ACTIVE;
2412 	if (bufferSize == 0) {
2413 		result->buffer_log = NULL;
2414 		for (int32 i = 0; i < 5; i++) {
2415 			result->buffer_phy[i] = 0;
2416 			result->ext_buffer_phy[i] = 0;
2417 		}
2418 
2419 		return result;
2420 	}
2421 
2422 	if (fStack->AllocateChunk(&result->buffer_log, &physicalAddress,
2423 			bufferSize) != B_OK) {
2424 		TRACE_ERROR("unable to allocate qtd buffer\n");
2425 		fStack->FreeChunk(result, (phys_addr_t)result->this_phy,
2426 			sizeof(ehci_qtd));
2427 		return NULL;
2428 	}
2429 
2430 	addr_t physicalBase = (addr_t)physicalAddress;
2431 	result->buffer_phy[0] = physicalBase;
2432 	result->ext_buffer_phy[0] = 0;
2433 	for (int32 i = 1; i < 5; i++) {
2434 		physicalBase += B_PAGE_SIZE;
2435 		result->buffer_phy[i] = physicalBase & EHCI_QTD_PAGE_MASK;
2436 		result->ext_buffer_phy[i] = 0;
2437 	}
2438 
2439 	return result;
2440 }
2441 
2442 
2443 status_t
2444 EHCI::CreateDescriptorChain(Pipe *pipe, ehci_qtd **_firstDescriptor,
2445 	ehci_qtd **_lastDescriptor, ehci_qtd *strayDescriptor, size_t bufferSize,
2446 	uint8 pid)
2447 {
2448 	size_t packetSize = B_PAGE_SIZE * 4;
2449 	int32 descriptorCount = (bufferSize + packetSize - 1) / packetSize;
2450 
2451 	bool dataToggle = pipe->DataToggle();
2452 	ehci_qtd *firstDescriptor = NULL;
2453 	ehci_qtd *lastDescriptor = *_firstDescriptor;
2454 	for (int32 i = 0; i < descriptorCount; i++) {
2455 		ehci_qtd *descriptor = CreateDescriptor(min_c(packetSize, bufferSize),
2456 			pid);
2457 
2458 		if (!descriptor) {
2459 			FreeDescriptorChain(firstDescriptor);
2460 			return B_NO_MEMORY;
2461 		}
2462 
2463 		if (dataToggle)
2464 			descriptor->token |= EHCI_QTD_DATA_TOGGLE;
2465 
2466 		if (lastDescriptor)
2467 			LinkDescriptors(lastDescriptor, descriptor, strayDescriptor);
2468 
2469 		bufferSize -= packetSize;
2470 		lastDescriptor = descriptor;
2471 		if (!firstDescriptor)
2472 			firstDescriptor = descriptor;
2473 	}
2474 
2475 	*_firstDescriptor = firstDescriptor;
2476 	*_lastDescriptor = lastDescriptor;
2477 	return B_OK;
2478 }
2479 
2480 
2481 void
2482 EHCI::FreeDescriptor(ehci_qtd *descriptor)
2483 {
2484 	if (!descriptor)
2485 		return;
2486 
2487 	if (descriptor->buffer_log) {
2488 		fStack->FreeChunk(descriptor->buffer_log,
2489 			(phys_addr_t)descriptor->buffer_phy[0], descriptor->buffer_size);
2490 	}
2491 
2492 	fStack->FreeChunk(descriptor, (phys_addr_t)descriptor->this_phy,
2493 		sizeof(ehci_qtd));
2494 }
2495 
2496 
2497 void
2498 EHCI::FreeDescriptorChain(ehci_qtd *topDescriptor)
2499 {
2500 	ehci_qtd *current = topDescriptor;
2501 	ehci_qtd *next = NULL;
2502 
2503 	while (current) {
2504 		next = current->next_log;
2505 		FreeDescriptor(current);
2506 		current = next;
2507 	}
2508 }
2509 
2510 
2511 ehci_itd *
2512 EHCI::CreateItdDescriptor()
2513 {
2514 	ehci_itd *result;
2515 	phys_addr_t physicalAddress;
2516 	if (fStack->AllocateChunk((void **)&result, &physicalAddress,
2517 			sizeof(ehci_itd)) != B_OK) {
2518 		TRACE_ERROR("failed to allocate a itd\n");
2519 		return NULL;
2520 	}
2521 
2522 	memset(result, 0, sizeof(ehci_itd));
2523 	result->this_phy = (addr_t)physicalAddress;
2524 	result->next_phy = EHCI_ITEM_TERMINATE;
2525 
2526 	return result;
2527 }
2528 
2529 
2530 ehci_sitd *
2531 EHCI::CreateSitdDescriptor()
2532 {
2533 	ehci_sitd *result;
2534 	phys_addr_t physicalAddress;
2535 	if (fStack->AllocateChunk((void **)&result, &physicalAddress,
2536 			sizeof(ehci_sitd)) != B_OK) {
2537 		TRACE_ERROR("failed to allocate a sitd\n");
2538 		return NULL;
2539 	}
2540 
2541 	memset(result, 0, sizeof(ehci_sitd));
2542 	result->this_phy = (addr_t)physicalAddress | EHCI_ITEM_TYPE_SITD;
2543 	result->next_phy = EHCI_ITEM_TERMINATE;
2544 
2545 	return result;
2546 }
2547 
2548 
2549 void
2550 EHCI::FreeDescriptor(ehci_itd *descriptor)
2551 {
2552 	if (!descriptor)
2553 		return;
2554 
2555 	fStack->FreeChunk(descriptor, (phys_addr_t)descriptor->this_phy,
2556 		sizeof(ehci_itd));
2557 }
2558 
2559 
2560 void
2561 EHCI::FreeDescriptor(ehci_sitd *descriptor)
2562 {
2563 	if (!descriptor)
2564 		return;
2565 
2566 	fStack->FreeChunk(descriptor, (phys_addr_t)descriptor->this_phy,
2567 		sizeof(ehci_sitd));
2568 }
2569 
2570 
2571 void
2572 EHCI::LinkDescriptors(ehci_qtd *first, ehci_qtd *last, ehci_qtd *alt)
2573 {
2574 	first->next_phy = last->this_phy;
2575 	first->next_log = last;
2576 
2577 	if (alt) {
2578 		first->alt_next_phy = alt->this_phy;
2579 		first->alt_next_log = alt;
2580 	} else {
2581 		first->alt_next_phy = EHCI_ITEM_TERMINATE;
2582 		first->alt_next_log = NULL;
2583 	}
2584 }
2585 
2586 
2587 void
2588 EHCI::LinkITDescriptors(ehci_itd *itd, ehci_itd **_last)
2589 {
2590 	ehci_itd *last = *_last;
2591 	itd->next_phy = last->next_phy;
2592 	itd->next = NULL;
2593 	itd->prev = last;
2594 	last->next = itd;
2595 	last->next_phy = itd->this_phy;
2596 	*_last = itd;
2597 }
2598 
2599 
2600 void
2601 EHCI::LinkSITDescriptors(ehci_sitd *sitd, ehci_sitd **_last)
2602 {
2603 	ehci_sitd *last = *_last;
2604 	sitd->next_phy = last->next_phy;
2605 	sitd->next = NULL;
2606 	sitd->prev = last;
2607 	last->next = sitd;
2608 	last->next_phy = sitd->this_phy;
2609 	*_last = sitd;
2610 }
2611 
2612 
2613 void
2614 EHCI::UnlinkITDescriptors(ehci_itd *itd, ehci_itd **last)
2615 {
2616 	itd->prev->next_phy = itd->next_phy;
2617 	itd->prev->next = itd->next;
2618 	if (itd->next != NULL)
2619 		itd->next->prev = itd->prev;
2620 	if (itd == *last)
2621 		*last = itd->prev;
2622 }
2623 
2624 
2625 void
2626 EHCI::UnlinkSITDescriptors(ehci_sitd *sitd, ehci_sitd **last)
2627 {
2628 	sitd->prev->next_phy = sitd->next_phy;
2629 	sitd->prev->next = sitd->next;
2630 	if (sitd->next != NULL)
2631 		sitd->next->prev = sitd->prev;
2632 	if (sitd == *last)
2633 		*last = sitd->prev;
2634 }
2635 
2636 
2637 size_t
2638 EHCI::WriteDescriptorChain(ehci_qtd *topDescriptor, iovec *vector,
2639 	size_t vectorCount)
2640 {
2641 	ehci_qtd *current = topDescriptor;
2642 	size_t actualLength = 0;
2643 	size_t vectorIndex = 0;
2644 	size_t vectorOffset = 0;
2645 	size_t bufferOffset = 0;
2646 
2647 	while (current) {
2648 		if (!current->buffer_log)
2649 			break;
2650 
2651 		while (true) {
2652 			size_t length = min_c(current->buffer_size - bufferOffset,
2653 				vector[vectorIndex].iov_len - vectorOffset);
2654 
2655 			memcpy((uint8 *)current->buffer_log + bufferOffset,
2656 				(uint8 *)vector[vectorIndex].iov_base + vectorOffset, length);
2657 
2658 			actualLength += length;
2659 			vectorOffset += length;
2660 			bufferOffset += length;
2661 
2662 			if (vectorOffset >= vector[vectorIndex].iov_len) {
2663 				if (++vectorIndex >= vectorCount) {
2664 					TRACE("wrote descriptor chain (%ld bytes, no more vectors)"
2665 						"\n", actualLength);
2666 					return actualLength;
2667 				}
2668 
2669 				vectorOffset = 0;
2670 			}
2671 
2672 			if (bufferOffset >= current->buffer_size) {
2673 				bufferOffset = 0;
2674 				break;
2675 			}
2676 		}
2677 
2678 		if (current->next_phy & EHCI_ITEM_TERMINATE)
2679 			break;
2680 
2681 		current = current->next_log;
2682 	}
2683 
2684 	TRACE("wrote descriptor chain (%ld bytes)\n", actualLength);
2685 	return actualLength;
2686 }
2687 
2688 
2689 size_t
2690 EHCI::ReadDescriptorChain(ehci_qtd *topDescriptor, iovec *vector,
2691 	size_t vectorCount, bool *nextDataToggle)
2692 {
2693 	uint32 dataToggle = 0;
2694 	ehci_qtd *current = topDescriptor;
2695 	size_t actualLength = 0;
2696 	size_t vectorIndex = 0;
2697 	size_t vectorOffset = 0;
2698 	size_t bufferOffset = 0;
2699 
2700 	while (current && (current->token & EHCI_QTD_STATUS_ACTIVE) == 0) {
2701 		if (!current->buffer_log)
2702 			break;
2703 
2704 		dataToggle = current->token & EHCI_QTD_DATA_TOGGLE;
2705 		size_t bufferSize = current->buffer_size;
2706 		bufferSize -= (current->token >> EHCI_QTD_BYTES_SHIFT)
2707 			& EHCI_QTD_BYTES_MASK;
2708 
2709 		while (true) {
2710 			size_t length = min_c(bufferSize - bufferOffset,
2711 				vector[vectorIndex].iov_len - vectorOffset);
2712 
2713 			memcpy((uint8 *)vector[vectorIndex].iov_base + vectorOffset,
2714 				(uint8 *)current->buffer_log + bufferOffset, length);
2715 
2716 			actualLength += length;
2717 			vectorOffset += length;
2718 			bufferOffset += length;
2719 
2720 			if (vectorOffset >= vector[vectorIndex].iov_len) {
2721 				if (++vectorIndex >= vectorCount) {
2722 					TRACE("read descriptor chain (%ld bytes, no more vectors)"
2723 						"\n", actualLength);
2724 					*nextDataToggle = dataToggle > 0 ? true : false;
2725 					return actualLength;
2726 				}
2727 
2728 				vectorOffset = 0;
2729 			}
2730 
2731 			if (bufferOffset >= bufferSize) {
2732 				bufferOffset = 0;
2733 				break;
2734 			}
2735 		}
2736 
2737 		if (current->next_phy & EHCI_ITEM_TERMINATE)
2738 			break;
2739 
2740 		current = current->next_log;
2741 	}
2742 
2743 	TRACE("read descriptor chain (%ld bytes)\n", actualLength);
2744 	*nextDataToggle = dataToggle > 0 ? true : false;
2745 	return actualLength;
2746 }
2747 
2748 
2749 size_t
2750 EHCI::ReadActualLength(ehci_qtd *topDescriptor, bool *nextDataToggle)
2751 {
2752 	size_t actualLength = 0;
2753 	ehci_qtd *current = topDescriptor;
2754 	uint32 dataToggle = 0;
2755 
2756 	while (current && (current->token & EHCI_QTD_STATUS_ACTIVE) == 0) {
2757 		dataToggle = current->token & EHCI_QTD_DATA_TOGGLE;
2758 		size_t length = current->buffer_size;
2759 		length -= (current->token >> EHCI_QTD_BYTES_SHIFT)
2760 			& EHCI_QTD_BYTES_MASK;
2761 		actualLength += length;
2762 
2763 		if (current->next_phy & EHCI_ITEM_TERMINATE)
2764 			break;
2765 
2766 		current = current->next_log;
2767 	}
2768 
2769 	TRACE("read actual length (%ld bytes)\n", actualLength);
2770 	*nextDataToggle = dataToggle > 0 ? true : false;
2771 	return actualLength;
2772 }
2773 
2774 
2775 size_t
2776 EHCI::WriteIsochronousDescriptorChain(isochronous_transfer_data *transfer,
2777 	uint32 packetCount,	iovec *vector)
2778 {
2779 	// TODO implement
2780 	return 0;
2781 }
2782 
2783 
2784 size_t
2785 EHCI::ReadIsochronousDescriptorChain(isochronous_transfer_data *transfer)
2786 {
2787 	iovec *vector = transfer->transfer->Vector();
2788 	size_t vectorCount = transfer->transfer->VectorCount();
2789 	size_t vectorOffset = 0;
2790 	size_t vectorIndex = 0;
2791 	usb_isochronous_data *isochronousData
2792 		= transfer->transfer->IsochronousData();
2793 	uint32 packet = 0;
2794 	size_t totalLength = 0;
2795 	size_t bufferOffset = 0;
2796 
2797 	size_t packetSize = transfer->transfer->DataLength();
2798 	packetSize /= isochronousData->packet_count;
2799 
2800 	for (uint32 i = 0; i <= transfer->last_to_process; i++) {
2801 		ehci_itd *itd = transfer->descriptors[i];
2802 		for (uint32 j = 0; j <= itd->last_token
2803 			&& packet < isochronousData->packet_count; j++) {
2804 
2805 			size_t bufferSize = (itd->token[j] >> EHCI_ITD_TLENGTH_SHIFT)
2806 				& EHCI_ITD_TLENGTH_MASK;
2807 			if (((itd->token[j] >> EHCI_ITD_STATUS_SHIFT)
2808 				& EHCI_ITD_STATUS_MASK) != 0) {
2809 				bufferSize = 0;
2810 			}
2811 			isochronousData->packet_descriptors[packet].actual_length
2812 				= bufferSize;
2813 
2814 			if (bufferSize > 0)
2815 				isochronousData->packet_descriptors[packet].status = B_OK;
2816 			else
2817 				isochronousData->packet_descriptors[packet].status = B_ERROR;
2818 
2819 			totalLength += bufferSize;
2820 
2821 			size_t offset = bufferOffset;
2822 			size_t skipSize = packetSize - bufferSize;
2823 			while (bufferSize > 0) {
2824 				size_t length = min_c(bufferSize,
2825 					vector[vectorIndex].iov_len - vectorOffset);
2826 				memcpy((uint8 *)vector[vectorIndex].iov_base + vectorOffset,
2827 					(uint8 *)transfer->buffer_log + bufferOffset, length);
2828 				offset += length;
2829 				vectorOffset += length;
2830 				bufferSize -= length;
2831 
2832 				if (vectorOffset >= vector[vectorIndex].iov_len) {
2833 					if (++vectorIndex >= vectorCount) {
2834 						TRACE("read isodescriptor chain (%ld bytes, no more "
2835 							"vectors)\n", totalLength);
2836 						return totalLength;
2837 					}
2838 
2839 					vectorOffset = 0;
2840 				}
2841 			}
2842 
2843 			// skip to next packet offset
2844 			while (skipSize > 0) {
2845 				size_t length = min_c(skipSize,
2846 					vector[vectorIndex].iov_len - vectorOffset);
2847 				vectorOffset += length;
2848 				skipSize -= length;
2849 				if (vectorOffset >= vector[vectorIndex].iov_len) {
2850 					if (++vectorIndex >= vectorCount) {
2851 						TRACE("read isodescriptor chain (%ld bytes, no more "
2852 							"vectors)\n", totalLength);
2853 						return totalLength;
2854 					}
2855 
2856 					vectorOffset = 0;
2857 				}
2858 			}
2859 
2860 			bufferOffset += packetSize;
2861 			if (bufferOffset >= transfer->buffer_size)
2862 				return totalLength;
2863 
2864 			packet++;
2865 		}
2866 	}
2867 
2868 	TRACE("ReadIsochronousDescriptorChain packet count %" B_PRId32 "\n",
2869 		packet);
2870 
2871 	return totalLength;
2872 }
2873 
2874 
2875 bool
2876 EHCI::LockIsochronous()
2877 {
2878 	return (mutex_lock(&fIsochronousLock) == B_OK);
2879 }
2880 
2881 
2882 void
2883 EHCI::UnlockIsochronous()
2884 {
2885 	mutex_unlock(&fIsochronousLock);
2886 }
2887 
2888 
2889 inline void
2890 EHCI::WriteOpReg(uint32 reg, uint32 value)
2891 {
2892 	*(volatile uint32 *)(fOperationalRegisters + reg) = value;
2893 }
2894 
2895 
2896 inline uint32
2897 EHCI::ReadOpReg(uint32 reg)
2898 {
2899 	return *(volatile uint32 *)(fOperationalRegisters + reg);
2900 }
2901 
2902 
2903 inline uint8
2904 EHCI::ReadCapReg8(uint32 reg)
2905 {
2906 	return *(volatile uint8 *)(fCapabilityRegisters + reg);
2907 }
2908 
2909 
2910 inline uint16
2911 EHCI::ReadCapReg16(uint32 reg)
2912 {
2913 	return *(volatile uint16 *)(fCapabilityRegisters + reg);
2914 }
2915 
2916 
2917 inline uint32
2918 EHCI::ReadCapReg32(uint32 reg)
2919 {
2920 	return *(volatile uint32 *)(fCapabilityRegisters + reg);
2921 }
2922