xref: /haiku/src/add-ons/kernel/bus_managers/ata/ATAChannel.cpp (revision 155fa31ec619414bb0e0fb1ffe9ad913e4ecd398)
1 /*
2  * Copyright 2009, Michael Lotz, mmlr@mlotz.ch.
3  * Copyright 2008, Marcus Overhagen.
4  * Copyright 2004-2008, Axel Dörfler, axeld@pinc-software.de.
5  * Copyright 2002-2003, Thomas Kurschel.
6  *
7  * Distributed under the terms of the MIT License.
8  */
9 
10 #include "ATAPrivate.h"
11 
12 
13 ATAChannel::ATAChannel(device_node *node)
14 	:
15 	fNode(node),
16 	fChannelID(0),
17 	fController(NULL),
18 	fCookie(NULL),
19 	fExpectsInterrupt(false),
20 	fStatus(B_NO_INIT),
21 	fSCSIBus(NULL),
22 	fDeviceCount(0),
23 	fDevices(NULL),
24 	fUseDMA(true),
25 	fRequest(NULL)
26 {
27 	B_INITIALIZE_SPINLOCK(&fInterruptLock);
28 	fInterruptCondition.Init(this, "ata dma transfer");
29 
30 	gDeviceManager->get_attr_uint32(node, ATA_CHANNEL_ID_ITEM, &fChannelID,
31 		true);
32 	snprintf(fDebugContext, sizeof(fDebugContext), " %lu", fChannelID);
33 
34 	if (fUseDMA) {
35 		void *settings = load_driver_settings(B_SAFEMODE_DRIVER_SETTINGS);
36 		if (settings != NULL) {
37 			if (get_driver_boolean_parameter(settings,
38 				B_SAFEMODE_DISABLE_IDE_DMA, false, false)) {
39 				TRACE_ALWAYS("disabling DMA because of safemode setting\n");
40 				fUseDMA = false;
41 			}
42 
43 			unload_driver_settings(settings);
44 		}
45 	}
46 
47 	if (fUseDMA) {
48 		uint8 canDMA;
49 		if (gDeviceManager->get_attr_uint8(node, ATA_CONTROLLER_CAN_DMA_ITEM,
50 			&canDMA, true) != B_OK) {
51 			TRACE_ERROR("unknown if controller supports DMA, not using it\n");
52 			fUseDMA = false;
53 		}
54 
55 		if (canDMA == 0) {
56 			TRACE_ALWAYS("controller doesn't support DMA, disabling\n");
57 			fUseDMA = false;
58 		}
59 	}
60 
61 	fRequest = new(std::nothrow) ATARequest(true);
62 	if (fRequest == NULL) {
63 		fStatus = B_NO_MEMORY;
64 		return;
65 	}
66 
67 	uint8 maxDevices = 2;
68 	if (gDeviceManager->get_attr_uint8(node, ATA_CONTROLLER_MAX_DEVICES_ITEM,
69 			&maxDevices, true) != B_OK) {
70 		maxDevices = 2;
71 	}
72 
73 	fDeviceCount = MIN(maxDevices, 2);
74 	fDevices = new(std::nothrow) ATADevice *[fDeviceCount];
75 	if (fDevices == NULL) {
76 		fStatus = B_NO_MEMORY;
77 		return;
78 	}
79 
80 	for (uint8 i = 0; i < fDeviceCount; i++)
81 		fDevices[i] = NULL;
82 
83 	device_node *parent = gDeviceManager->get_parent_node(node);
84 	fStatus = gDeviceManager->get_driver(parent,
85 		(driver_module_info **)&fController, &fCookie);
86 	gDeviceManager->put_node(parent);
87 
88 	fController->set_channel(fCookie, this);
89 }
90 
91 
92 ATAChannel::~ATAChannel()
93 {
94 	if (fDevices) {
95 		for (uint8 i = 0; i < fDeviceCount; i++)
96 			delete fDevices[i];
97 		delete [] fDevices;
98 	}
99 
100 	delete fRequest;
101 }
102 
103 
104 status_t
105 ATAChannel::InitCheck()
106 {
107 	return fStatus;
108 }
109 
110 
111 void
112 ATAChannel::SetBus(scsi_bus bus)
113 {
114 	fSCSIBus = bus;
115 }
116 
117 
118 status_t
119 ATAChannel::ScanBus()
120 {
121 	// check if there is anything at all
122 	if (AltStatus() == 0xff) {
123 		TRACE_ALWAYS("illegal status value, assuming no devices connected\n");
124 		return B_OK;
125 	}
126 
127 	bool devicePresent[fDeviceCount];
128 	uint16 deviceSignature[fDeviceCount];
129 	status_t result = Reset(devicePresent, deviceSignature);
130 	if (result != B_OK) {
131 		TRACE_ERROR("resetting the channel failed\n");
132 		return result;
133 	}
134 
135 	for (uint8 i = 0; i < fDeviceCount; i++) {
136 		if (!devicePresent[i])
137 			continue;
138 
139 		ATADevice *device = NULL;
140 		if (deviceSignature[i] == ATA_SIGNATURE_ATAPI)
141 			device = new(std::nothrow) ATAPIDevice(this, i);
142 		else
143 			device = new(std::nothrow) ATADevice(this, i);
144 
145 		if (device == NULL) {
146 			TRACE_ERROR("out of memory allocating device\n");
147 			return B_NO_MEMORY;
148 		}
149 
150 		TRACE("trying ATA%s device %u\n", device->IsATAPI() ? "PI" : "", i);
151 
152 		if (device->Identify() != B_OK) {
153 			delete device;
154 			continue;
155 		}
156 
157 		if (device->Configure() != B_OK) {
158 			TRACE_ERROR("failed to configure device\n");
159 			delete device;
160 			continue;
161 		}
162 
163 		TRACE_ALWAYS("identified ATA%s device %u\n", device->IsATAPI()
164 			? "PI" : "", i);
165 
166 		fDevices[i] = device;
167 	}
168 
169 	return B_OK;
170 }
171 
172 
173 void
174 ATAChannel::PathInquiry(scsi_path_inquiry *info)
175 {
176 	info->hba_inquiry = SCSI_PI_TAG_ABLE | SCSI_PI_WIDE_16;
177 	info->hba_misc = 0;
178 	info->sim_priv = 0;
179 	info->initiator_id = 2;
180 	info->hba_queue_size = 1;
181 	memset(info->vuhba_flags, 0, sizeof(info->vuhba_flags));
182 
183 	strlcpy(info->sim_vid, "Haiku", SCSI_SIM_ID);
184 
185 	const char *controllerName = NULL;
186 	if (gDeviceManager->get_attr_string(fNode,
187 			SCSI_DESCRIPTION_CONTROLLER_NAME, &controllerName, true) == B_OK)
188 		strlcpy(info->hba_vid, controllerName, SCSI_HBA_ID);
189 	else
190 		strlcpy(info->hba_vid, "unknown", SCSI_HBA_ID);
191 
192 	strlcpy(info->sim_version, "1.0", SCSI_VERS);
193 	strlcpy(info->hba_version, "1.0", SCSI_VERS);
194 	strlcpy(info->controller_family, "ATA", SCSI_FAM_ID);
195 	strlcpy(info->controller_type, "ATA", SCSI_TYPE_ID);
196 }
197 
198 
199 void
200 ATAChannel::GetRestrictions(uint8 targetID, bool *isATAPI, bool *noAutoSense,
201 	uint32 *maxBlocks)
202 {
203 	// we always indicate ATAPI so we have to emulate fewer commands
204 	*isATAPI = true;
205 	*noAutoSense = false;
206 	*maxBlocks = 0x100;
207 
208 	if (targetID < fDeviceCount && fDevices[targetID] != NULL)
209 		fDevices[targetID]->GetRestrictions(noAutoSense, maxBlocks);
210 }
211 
212 
213 status_t
214 ATAChannel::ExecuteIO(scsi_ccb *ccb)
215 {
216 	TRACE_FUNCTION("%p\n", ccb);
217 	status_t result = fRequest->Start(ccb);
218 	if (result != B_OK)
219 		return result;
220 
221 	if (ccb->cdb[0] == SCSI_OP_REQUEST_SENSE && fRequest->HasSense()) {
222 		TRACE("request sense\n");
223 		fRequest->RequestSense();
224 		fRequest->Finish(false);
225 		return B_OK;
226 	}
227 
228 	// we aren't a check sense request, clear sense data for new request
229 	fRequest->ClearSense();
230 
231 	if (ccb->target_id >= fDeviceCount) {
232 		TRACE_ERROR("invalid target device\n");
233 		fRequest->SetStatus(SCSI_SEL_TIMEOUT);
234 		fRequest->Finish(false);
235 		return B_BAD_INDEX;
236 	}
237 
238 	ATADevice *device = fDevices[ccb->target_id];
239 	if (device == NULL) {
240 		TRACE_ERROR("target device not present\n");
241 		fRequest->SetStatus(SCSI_SEL_TIMEOUT);
242 		fRequest->Finish(false);
243 		return B_BAD_INDEX;
244 	}
245 
246 	fRequest->SetTimeout(ccb->timeout > 0 ? ccb->timeout * 1000 * 1000
247 		: ATA_STANDARD_TIMEOUT);
248 
249 	result = device->ExecuteIO(fRequest);
250 	fRequest->Finish(false);
251 	return result;
252 }
253 
254 
255 status_t
256 ATAChannel::SelectDevice(uint8 device)
257 {
258 	TRACE_FUNCTION("device: %u\n", device);
259 
260 	if (device > 1)
261 		return B_BAD_INDEX;
262 
263 	ata_task_file taskFile;
264 	taskFile.lba.mode = ATA_MODE_LBA;
265 	taskFile.lba.device = device;
266 
267 	_WriteRegs(&taskFile, ATA_MASK_DEVICE_HEAD);
268 	_FlushAndWait(1);
269 
270 #if 0
271 	// for debugging only
272 	_ReadRegs(&taskFile, ATA_MASK_DEVICE_HEAD);
273 	if (taskFile.chs.device != device) {
274 		TRACE_ERROR("device %d not selected! head 0x%x, mode 0x%x, device %d\n",
275 			device, taskFile.chs.head, taskFile.chs.mode, taskFile.chs.device);
276 		return B_ERROR;
277 	}
278 #endif
279 
280 	return B_OK;
281 }
282 
283 
284 uint8
285 ATAChannel::SelectedDevice()
286 {
287 	ata_task_file taskFile;
288 	_ReadRegs(&taskFile, ATA_MASK_DEVICE_HEAD);
289 	return taskFile.lba.device;
290 }
291 
292 
293 status_t
294 ATAChannel::Reset(bool *presence, uint16 *signatures)
295 {
296 	TRACE_FUNCTION("\n");
297 
298 	SelectDevice(0);
299 
300 	// disable interrupts and assert SRST for at least 5 usec
301 	if (_WriteControl(ATA_DEVICE_CONTROL_DISABLE_INTS
302 		| ATA_DEVICE_CONTROL_SOFT_RESET) != B_OK) {
303 		TRACE_ERROR("failed to set reset signaling\n");
304 		return B_ERROR;
305 	}
306 
307 	_FlushAndWait(20);
308 
309 	// clear reset and wait for at least 2 ms (wait 150ms like everyone else)
310 	if (_WriteControl(ATA_DEVICE_CONTROL_DISABLE_INTS) != B_OK) {
311 		TRACE_ERROR("failed to clear reset signaling\n");
312 		return B_ERROR;
313 	}
314 
315 	_FlushAndWait(150 * 1000);
316 
317 	if (presence != NULL) {
318 		for (uint8 i = 0; i < fDeviceCount; i++)
319 			presence[i] = false;
320 	}
321 
322 	uint8 deviceCount = fDeviceCount;
323 	for (uint8 i = 0; i < deviceCount; i++) {
324 		SelectDevice(i);
325 
326 		if (AltStatus() == 0xff) {
327 			TRACE_ALWAYS("illegal status value for device %d,"
328 				" assuming not present\n", i);
329 			continue;
330 		}
331 
332 		if (SelectedDevice() != i) {
333 			TRACE_ALWAYS("cannot select device %d, assuming not present\n", i);
334 			continue;
335 		}
336 
337 		// ensure interrupts are disabled for this device
338 		_WriteControl(ATA_DEVICE_CONTROL_DISABLE_INTS);
339 
340 		// wait up to 31 seconds for busy to clear
341 		if (Wait(0, ATA_STATUS_BUSY, 0, 31 * 1000 * 1000) != B_OK) {
342 			TRACE_ERROR("device %d reset timeout\n", i);
343 			continue;
344 		}
345 
346 		ata_task_file taskFile;
347 		if (_ReadRegs(&taskFile, ATA_MASK_LBA_MID | ATA_MASK_LBA_HIGH
348 				| ATA_MASK_ERROR) != B_OK) {
349 			TRACE_ERROR("reading status failed\n");
350 			return B_ERROR;
351 		}
352 
353 		if (taskFile.read.error != 0x01
354 			&& (i > 0 || taskFile.read.error != 0x81)) {
355 			TRACE_ERROR("device %d failed, error code is 0x%02x\n", i,
356 				taskFile.read.error);
357 			continue;
358 		}
359 
360 		if (i == 0 && taskFile.read.error >= 0x80) {
361 			TRACE_ERROR("device %d indicates that other device failed"
362 				" with code 0x%02x\n", i, taskFile.read.error);
363 			deviceCount = 1;
364 		}
365 
366 		if (presence != NULL)
367 			presence[i] = true;
368 
369 		uint16 signature = taskFile.lba.lba_8_15
370 			| (((uint16)taskFile.lba.lba_16_23) << 8);
371 		TRACE_ALWAYS("signature of device %d: 0x%04x\n", i, signature);
372 
373 		if (signatures != NULL)
374 			signatures[i] = signature;
375 	}
376 
377 	return B_OK;
378 }
379 
380 
381 status_t
382 ATAChannel::Wait(uint8 setBits, uint8 clearedBits, uint32 flags,
383 	bigtime_t timeout)
384 {
385 	bigtime_t startTime = system_time();
386 	_FlushAndWait(1);
387 
388 	TRACE("waiting for set bits 0x%02x and cleared bits 0x%02x\n",
389 		setBits, clearedBits);
390 
391 	while (true) {
392 		uint8 status = AltStatus();
393 		if ((flags & ATA_CHECK_ERROR_BIT) != 0
394 			&& (status & ATA_STATUS_ERROR) != 0) {
395 			TRACE("error bit set while waiting\n");
396 			return B_ERROR;
397 		}
398 
399 		if ((flags & ATA_CHECK_DEVICE_FAULT) != 0
400 			&& (status & ATA_STATUS_DEVICE_FAULT) != 0) {
401 			TRACE("device fault bit set while waiting\n");
402 			return B_ERROR;
403 		}
404 
405 		if ((status & clearedBits) == 0) {
406 			if ((flags & ATA_WAIT_ANY_BIT) != 0 && (status & setBits) != 0)
407 				return B_OK;
408 			if ((status & setBits) == setBits)
409 				return B_OK;
410 		}
411 
412 		bigtime_t elapsedTime = system_time() - startTime;
413 		TRACE("wait status after %lld: 0x%02x\n", elapsedTime, status);
414 		if (elapsedTime > timeout)
415 			return B_TIMED_OUT;
416 
417 		// The device may be ready almost immediatelly. If it isn't,
418 		// poll often during the first 20ms, otherwise poll lazyly.
419 		if (elapsedTime < 1000)
420 			spin(1);
421 		else if (elapsedTime < 20000)
422 			snooze(1000);
423 		else
424 			snooze(50000);
425 	}
426 
427 	return B_ERROR;
428 }
429 
430 
431 status_t
432 ATAChannel::WaitDataRequest(bool high)
433 {
434 	return Wait(high ? ATA_STATUS_DATA_REQUEST : 0,
435 		high ? 0 : ATA_STATUS_DATA_REQUEST, 0, (high ? 10 : 1) * 1000 * 1000);
436 }
437 
438 
439 status_t
440 ATAChannel::WaitDeviceReady()
441 {
442 	return Wait(ATA_STATUS_DEVICE_READY, 0, 0, 5 * 1000 * 1000);
443 }
444 
445 
446 status_t
447 ATAChannel::WaitForIdle()
448 {
449 	return Wait(0, ATA_STATUS_BUSY | ATA_STATUS_DATA_REQUEST, 0, 50 * 1000);
450 }
451 
452 
453 void
454 ATAChannel::PrepareWaitingForInterrupt()
455 {
456 	TRACE_FUNCTION("\n");
457 	InterruptsSpinLocker locker(fInterruptLock);
458 	fExpectsInterrupt = true;
459 	fInterruptCondition.Add(&fInterruptConditionEntry);
460 
461 	// enable interrupts
462 	_WriteControl(0);
463 }
464 
465 
466 status_t
467 ATAChannel::WaitForInterrupt(bigtime_t timeout)
468 {
469 	TRACE_FUNCTION("timeout: %lld\n", timeout);
470 	status_t result = fInterruptConditionEntry.Wait(B_RELATIVE_TIMEOUT,
471 		timeout);
472 
473 	InterruptsSpinLocker locker(fInterruptLock);
474 	fExpectsInterrupt = false;
475 	locker.Unlock();
476 
477 	// disable interrupts
478 	_WriteControl(ATA_DEVICE_CONTROL_DISABLE_INTS);
479 
480 	if (result != B_OK) {
481 		TRACE_ERROR("timeout waiting for interrupt\n");
482 		return B_TIMED_OUT;
483 	}
484 
485 	return B_OK;
486 }
487 
488 
489 status_t
490 ATAChannel::SendRequest(ATARequest *request, uint32 flags)
491 {
492 	ATADevice *device = request->Device();
493 	if (device->Select() != B_OK || WaitForIdle() != B_OK) {
494 		// resetting the device here will discard current configuration,
495 		// it's better when the SCSI bus manager requests an external reset.
496 		TRACE_ERROR("device selection timeout\n");
497 		request->SetStatus(SCSI_SEL_TIMEOUT);
498 		return B_TIMED_OUT;
499 	}
500 
501 	if ((flags & ATA_DEVICE_READY_REQUIRED) != 0
502 		&& (AltStatus() & ATA_STATUS_DEVICE_READY) == 0) {
503 		TRACE_ERROR("device ready not set\n");
504 		request->SetStatus(SCSI_SEQUENCE_FAIL);
505 		return B_ERROR;
506 	}
507 
508 	if (_WriteRegs(device->TaskFile(), device->RegisterMask()
509 			| ATA_MASK_COMMAND) != B_OK) {
510 		TRACE_ERROR("can't write command\n");
511 		request->SetStatus(SCSI_HBA_ERR);
512 		return B_ERROR;
513 	}
514 
515 	return B_OK;
516 }
517 
518 
519 status_t
520 ATAChannel::FinishRequest(ATARequest *request, uint32 flags, uint8 errorMask)
521 {
522 	if (flags & ATA_WAIT_FINISH) {
523 		// wait for the device to finish current command (device no longer busy)
524 		status_t result = Wait(0, ATA_STATUS_BUSY, flags, request->Timeout());
525 		if (result != B_OK) {
526 			TRACE_ERROR("timeout waiting for request finish\n");
527 			request->SetStatus(SCSI_CMD_TIMEOUT);
528 			return result;
529 		}
530 	}
531 
532 	ata_task_file *taskFile = request->Device()->TaskFile();
533 
534 	// read status, this also acknowledges pending interrupts
535 	status_t result = _ReadRegs(taskFile, ATA_MASK_STATUS | ATA_MASK_ERROR);
536 	if (result != B_OK) {
537 		TRACE("reading status failed\n");
538 		request->SetStatus(SCSI_SEQUENCE_FAIL);
539 		return result;
540 	}
541 
542 	if (taskFile->read.status & ATA_STATUS_BUSY) {
543 		TRACE("command failed, device still busy\n");
544 		request->SetStatus(SCSI_SEQUENCE_FAIL);
545 		return B_ERROR;
546 	}
547 
548 	if ((flags & ATA_DEVICE_READY_REQUIRED)
549 		&& (taskFile->read.status & ATA_STATUS_DEVICE_READY) == 0) {
550 		TRACE("command failed, device ready required but not set\n");
551 		request->SetStatus(SCSI_SEQUENCE_FAIL);
552 		return B_ERROR;
553 	}
554 
555 	uint8 checkFlags = ATA_STATUS_ERROR;
556 	if (flags & ATA_CHECK_DEVICE_FAULT)
557 		checkFlags |= ATA_STATUS_DEVICE_FAULT;
558 
559 	if ((taskFile->read.status & checkFlags) == 0)
560 		return B_OK;
561 
562 	if ((taskFile->read.error & ATA_ERROR_MEDIUM_CHANGED)
563 			!= ATA_ERROR_MEDIUM_CHANGED) {
564 		TRACE_ERROR("command failed, error bit is set: 0x%02x\n",
565 			taskFile->read.error);
566 	}
567 
568 	uint8 error = taskFile->read.error & errorMask;
569 	if (error & ATA_ERROR_INTERFACE_CRC) {
570 		TRACE_ERROR("interface crc error\n");
571 		request->SetSense(SCSIS_KEY_HARDWARE_ERROR, SCSIS_ASC_LUN_COM_CRC);
572 		return B_ERROR;
573 	}
574 
575 	if (request->IsWrite()) {
576 		if (error & ATA_ERROR_WRITE_PROTECTED) {
577 			request->SetSense(SCSIS_KEY_DATA_PROTECT, SCSIS_ASC_WRITE_PROTECTED);
578 			return B_ERROR;
579 		}
580 	} else {
581 		if (error & ATA_ERROR_UNCORRECTABLE) {
582 			request->SetSense(SCSIS_KEY_MEDIUM_ERROR, SCSIS_ASC_UNREC_READ_ERR);
583 			return B_ERROR;
584 		}
585 	}
586 
587 	if (error & ATA_ERROR_MEDIUM_CHANGED) {
588 		request->SetSense(SCSIS_KEY_UNIT_ATTENTION, SCSIS_ASC_MEDIUM_CHANGED);
589 		return B_ERROR;
590 	}
591 
592 	if (error & ATA_ERROR_INVALID_ADDRESS) {
593 		// XXX strange error code, don't really know what it means
594 		request->SetSense(SCSIS_KEY_MEDIUM_ERROR, SCSIS_ASC_RANDOM_POS_ERROR);
595 		return B_ERROR;
596 	}
597 
598 	if (error & ATA_ERROR_MEDIA_CHANGE_REQUESTED) {
599 		request->SetSense(SCSIS_KEY_UNIT_ATTENTION, SCSIS_ASC_REMOVAL_REQUESTED);
600 		return B_ERROR;
601 	}
602 
603 	if (error & ATA_ERROR_NO_MEDIA) {
604 		request->SetSense(SCSIS_KEY_MEDIUM_ERROR, SCSIS_ASC_NO_MEDIUM);
605 		return B_ERROR;
606 	}
607 
608 	if (error & ATA_ERROR_ABORTED) {
609 		request->SetSense(SCSIS_KEY_ABORTED_COMMAND, SCSIS_ASC_NO_SENSE);
610 		return B_ERROR;
611 	}
612 
613 	// either there was no error bit set or it was masked out
614 	request->SetSense(SCSIS_KEY_HARDWARE_ERROR, SCSIS_ASC_INTERNAL_FAILURE);
615 	return B_ERROR;
616 }
617 
618 
619 status_t
620 ATAChannel::PrepareDMA(ATARequest *request)
621 {
622 	scsi_ccb *ccb = request->CCB();
623 	return fController->prepare_dma(fCookie, ccb->sg_list, ccb->sg_count,
624 		request->IsWrite());
625 }
626 
627 
628 status_t
629 ATAChannel::StartDMA()
630 {
631 	return fController->start_dma(fCookie);
632 }
633 
634 
635 status_t
636 ATAChannel::FinishDMA()
637 {
638 	return fController->finish_dma(fCookie);
639 }
640 
641 
642 status_t
643 ATAChannel::ExecutePIOTransfer(ATARequest *request)
644 {
645 	bigtime_t timeout = request->Timeout();
646 	status_t result = B_OK;
647 	size_t *bytesLeft = request->BytesLeft();
648 	while (*bytesLeft > 0) {
649 		size_t currentLength = MIN(*bytesLeft, ATA_BLOCK_SIZE);
650 		if (request->IsWrite()) {
651 			result = _WritePIOBlock(request, currentLength);
652 			if (result != B_OK) {
653 				TRACE_ERROR("failed to write pio block\n");
654 				break;
655 			}
656 		} else {
657 			result = _ReadPIOBlock(request, currentLength);
658 			if (result != B_OK) {
659 				TRACE_ERROR("failed to read pio block\n");
660 				break;
661 			}
662 		}
663 
664 		*bytesLeft -= currentLength;
665 
666 		if (*bytesLeft > 0) {
667 			// wait for next block to be ready
668 			if (Wait(ATA_STATUS_DATA_REQUEST, ATA_STATUS_BUSY,
669 				ATA_CHECK_ERROR_BIT | ATA_CHECK_DEVICE_FAULT,
670 				timeout) != B_OK) {
671 				TRACE_ERROR("timeout waiting for device to request data\n");
672 				result = B_TIMED_OUT;
673 				break;
674 			}
675 		}
676 	}
677 
678 	if (result == B_OK && WaitDataRequest(false) != B_OK) {
679 		TRACE_ERROR("device still expects data transfer\n");
680 		result = B_ERROR;
681 	}
682 
683 	return result;
684 }
685 
686 
687 status_t
688 ATAChannel::ReadRegs(ATADevice *device)
689 {
690 	return _ReadRegs(device->TaskFile(), device->RegisterMask());
691 }
692 
693 
694 uint8
695 ATAChannel::AltStatus()
696 {
697 	return fController->get_altstatus(fCookie);
698 }
699 
700 
701 status_t
702 ATAChannel::ReadPIO(uint8 *buffer, size_t length)
703 {
704 	return fController->read_pio(fCookie, (uint16 *)buffer,
705 		length / sizeof(uint16), false);
706 }
707 
708 
709 status_t
710 ATAChannel::WritePIO(uint8 *buffer, size_t length)
711 {
712 	return fController->write_pio(fCookie, (uint16 *)buffer,
713 		length / sizeof(uint16), true);
714 }
715 
716 
717 status_t
718 ATAChannel::Interrupt(uint8 status)
719 {
720 	SpinLocker locker(fInterruptLock);
721 	if (!fExpectsInterrupt) {
722 		TRACE("interrupt when not expecting transfer\n");
723 		return B_UNHANDLED_INTERRUPT;
724 	}
725 
726 	if ((status & ATA_STATUS_BUSY) != 0) {
727 		TRACE(("interrupt while device is busy\n"));
728 		return B_UNHANDLED_INTERRUPT;
729 	}
730 
731 	fInterruptCondition.NotifyAll();
732 	return B_INVOKE_SCHEDULER;
733 }
734 
735 
736 status_t
737 ATAChannel::_ReadRegs(ata_task_file *taskFile, ata_reg_mask mask)
738 {
739 	return fController->read_command_block_regs(fCookie, taskFile, mask);
740 }
741 
742 
743 status_t
744 ATAChannel::_WriteRegs(ata_task_file *taskFile, ata_reg_mask mask)
745 {
746 	return fController->write_command_block_regs(fCookie, taskFile, mask);
747 }
748 
749 
750 status_t
751 ATAChannel::_WriteControl(uint8 value)
752 {
753 	return fController->write_device_control(fCookie, ATA_DEVICE_CONTROL_BIT3
754 		| value);
755 }
756 
757 
758 void
759 ATAChannel::_FlushAndWait(bigtime_t waitTime)
760 {
761 	AltStatus();
762 	if (waitTime > 100)
763 		snooze(waitTime);
764 	else
765 		spin(waitTime);
766 }
767 
768 
769 status_t
770 ATAChannel::_ReadPIOBlock(ATARequest *request, size_t length)
771 {
772 	uint32 transferred = 0;
773 	status_t result = _TransferPIOBlock(request, length, &transferred);
774 	request->CCB()->data_resid -= transferred;
775 
776 	// if length was odd, there's an extra byte waiting in request->OddByte()
777 	if (request->GetOddByte(NULL)) {
778 		// discard byte and adjust res_id as the extra byte didn't reach the
779 		// buffer
780 		request->CCB()->data_resid++;
781 	}
782 
783 	if (result != B_BUFFER_OVERFLOW)
784 		return result;
785 
786 	// the device returns more data then the buffer can store;
787 	// for ATAPI this is OK - we just discard remaining bytes (there
788 	// is no way to tell ATAPI about that, but we "only" waste time)
789 
790 	// perhaps discarding the extra odd-byte was sufficient
791 	if (transferred >= length)
792 		return B_OK;
793 
794 	TRACE_ERROR("pio read: discarding after %lu bytes\n", transferred);
795 
796 	uint8 buffer[32];
797 	length -= transferred;
798 	// discard 32 bytes at once	(see _WritePIOBlock())
799 	while (length > 0) {
800 		// read extra byte if length is odd (that's the "length + 1")
801 		size_t currentLength = MIN(length + 1, (uint32)sizeof(buffer))
802 			/ sizeof(uint16);
803 		fController->read_pio(fCookie, (uint16 *)buffer, currentLength, false);
804 		length -= currentLength * 2;
805 	}
806 
807 	return B_OK;
808 }
809 
810 
811 status_t
812 ATAChannel::_WritePIOBlock(ATARequest *request, size_t length)
813 {
814 	size_t transferred = 0;
815 	status_t result = _TransferPIOBlock(request, length, &transferred);
816 	request->CCB()->data_resid -= transferred;
817 
818 	if (result != B_BUFFER_OVERFLOW)
819 		return result;
820 
821 	// there may be a pending odd byte - transmit that now
822 	uint8 byte;
823 	if (request->GetOddByte(&byte)) {
824 		uint8 buffer[2];
825 		buffer[0] = byte;
826 		buffer[1] = 0;
827 
828 		fController->write_pio(fCookie, (uint16 *)buffer, 1, false);
829 		request->CCB()->data_resid--;
830 		transferred += 2;
831 	}
832 
833 	// "transferred" may actually be larger then length because the last odd-byte
834 	// is sent together with an extra zero-byte
835 	if (transferred >= length)
836 		return B_OK;
837 
838 	// Ouch! the device asks for data but we haven't got any left.
839 	// Sadly, this behaviour is OK for ATAPI packets, but there is no
840 	// way to tell the device that we don't have any data left;
841 	// only solution is to send zero bytes, though it's BAD
842 	static const uint8 buffer[32] = {};
843 
844 	TRACE_ERROR("pio write: discarding after %lu bytes\n", transferred);
845 
846 	length -= transferred;
847 	while (length > 0) {
848 		// if device asks for odd number of bytes, append an extra byte to
849 		// make length even (this is the "length + 1" term)
850 		size_t currentLength = MIN(length + 1, (int)(sizeof(buffer)))
851 			/ sizeof(uint16);
852 		fController->write_pio(fCookie, (uint16 *)buffer, currentLength, false);
853 		length -= currentLength * 2;
854 	}
855 
856 	return B_BUFFER_OVERFLOW;
857 }
858 
859 
860 status_t
861 ATAChannel::_TransferPIOBlock(ATARequest *request, size_t length,
862 	size_t *transferred)
863 {
864 	// data is usually split up into multiple scatter/gather blocks
865 	while (length > 0) {
866 		if (request->SGElementsLeft() == 0) {
867 			// ups - buffer too small (for ATAPI data, this is OK)
868 			return B_BUFFER_OVERFLOW;
869 		}
870 
871 		// we might have transmitted part of a scatter/entry already
872 		const physical_entry *entry = request->CurrentSGElement();
873 		uint32 offset = request->CurrentSGOffset();
874 		uint32 currentLength = MIN(entry->size - offset, length);
875 
876 		status_t result = _TransferPIOPhysical(request,
877 			(addr_t)entry->address + offset, currentLength, transferred);
878 		if (result != B_OK) {
879 			request->SetSense(SCSIS_KEY_HARDWARE_ERROR,
880 				SCSIS_ASC_INTERNAL_FAILURE);
881 			return result;
882 		}
883 
884 		request->AdvanceSG(currentLength);
885 		length -= currentLength;
886 	}
887 
888 	return B_OK;
889 }
890 
891 
892 // TODO: this should not be necessary, we could directly use virtual addresses
893 #include <vm.h>
894 #include <thread.h>
895 
896 status_t
897 ATAChannel::_TransferPIOPhysical(ATARequest *request, addr_t physicalAddress,
898 	size_t length, size_t *transferred)
899 {
900 	// we must split up chunk into B_PAGE_SIZE blocks as we can map only
901 	// one page into address space at once
902 	while (length > 0) {
903 		struct thread *thread = thread_get_current_thread();
904 		thread_pin_to_current_cpu(thread);
905 
906 		void *handle;
907 		addr_t virtualAddress;
908 		if (vm_get_physical_page_current_cpu(physicalAddress, &virtualAddress,
909 				&handle) != B_OK) {
910 			thread_unpin_from_current_cpu(thread);
911 			// ouch: this should never ever happen
912 			return B_ERROR;
913 		}
914 
915 		ASSERT(physicalAddress % B_PAGE_SIZE == virtualAddress % B_PAGE_SIZE);
916 
917 		// if chunk starts in the middle of a page, we have even less then
918 		// a page left
919 		size_t pageLeft = B_PAGE_SIZE - physicalAddress % B_PAGE_SIZE;
920 		size_t currentLength = MIN(pageLeft, length);
921 
922 		status_t result = _TransferPIOVirtual(request, (uint8 *)virtualAddress,
923 			currentLength, transferred);
924 
925 		vm_put_physical_page_current_cpu(virtualAddress, handle);
926 		thread_unpin_from_current_cpu(thread);
927 
928 		if (result != B_OK)
929 			return result;
930 
931 		length -= currentLength;
932 		physicalAddress += currentLength;
933 	}
934 
935 	return B_OK;
936 }
937 
938 
939 status_t
940 ATAChannel::_TransferPIOVirtual(ATARequest *request, uint8 *virtualAddress,
941 	size_t length, size_t *transferred)
942 {
943 	if (request->IsWrite()) {
944 		// if there is a byte left from last chunk, transmit it together
945 		// with the first byte of the current chunk (IDE requires 16 bits
946 		// to be transmitted at once)
947 		uint8 byte;
948 		if (request->GetOddByte(&byte)) {
949 			uint8 buffer[2];
950 
951 			buffer[0] = byte;
952 			buffer[1] = *virtualAddress++;
953 
954 			fController->write_pio(fCookie, (uint16 *)buffer, 1, false);
955 
956 			length--;
957 			*transferred += 2;
958 		}
959 
960 		fController->write_pio(fCookie, (uint16 *)virtualAddress, length / 2,
961 			false);
962 
963 		// take care if chunk size was odd, which means that 1 byte remains
964 		virtualAddress += length & ~1;
965 		*transferred += length & ~1;
966 
967 		if ((length & 1) != 0)
968 			request->SetOddByte(*virtualAddress);
969 	} else {
970 		// if we read one byte too much last time, push it into current chunk
971 		uint8 byte;
972 		if (request->GetOddByte(&byte)) {
973 			*virtualAddress++ = byte;
974 			length--;
975 		}
976 
977 		fController->read_pio(fCookie, (uint16 *)virtualAddress, length / 2,
978 			false);
979 
980 		// take care of odd chunk size;
981 		// in this case we read 1 byte to few!
982 		virtualAddress += length & ~1;
983 		*transferred += length & ~1;
984 
985 		if ((length & 1) != 0) {
986 			uint8 buffer[2];
987 
988 			// now read the missing byte; as we have to read 2 bytes at once,
989 			// we'll read one byte too much
990 			fController->read_pio(fCookie, (uint16 *)buffer, 1, false);
991 
992 			*virtualAddress = buffer[0];
993 			request->SetOddByte(buffer[1]);
994 
995 			*transferred += 2;
996 		}
997 	}
998 
999 	return B_OK;
1000 }
1001