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