The Pedigree Project 0.1
AtaDisk.cc
1/*
2 * Copyright (c) 2008-2014, Pedigree Developers
3 *
4 * Please see the CONTRIB file in the root of the source tree for a full
5 * list of contributors.
6 *
7 * Permission to use, copy, modify, and distribute this software for any
8 * purpose with or without fee is hereby granted, provided that the above
9 * copyright notice and this permission notice appear in all copies.
10 *
11 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18 */
19
20#include "AtaDisk.h"
21#include "pedigree/kernel/LockGuard.h"
22#include "pedigree/kernel/Log.h"
23#include "pedigree/kernel/TargetInfo.h"
24#include "pedigree/kernel/compiler.h"
25#include "pedigree/kernel/panic.h"
26#include "pedigree/kernel/processor/IoBase.h"
27#include "pedigree/kernel/processor/Processor.h"
28#include "pedigree/kernel/processor/types.h"
29#include "pedigree/kernel/utilities/Cache.h"
30#include "pedigree/kernel/utilities/PointerGuard.h"
31#include "pedigree/kernel/utilities/assert.h"
32#include "pedigree/kernel/utilities/utility.h"
33
34#include "AtaController.h"
35#include "AtaWriteCache.h"
36#include "ata-common.h"
37
38#if CRIPPLE_HDD
39#pragma GCC diagnostic ignored "-Wunreachable-code"
40#endif
41
42// #define ATA_DEFAULT_BLOCK_SIZE 0x1000
43#define ATA_DEFAULT_BLOCK_SIZE 0x10000 * 2
44
45namespace {
46constexpr Time::Timestamp AtapiCommandTimeout = 30 * Time::Multiplier::Second;
47constexpr size_t AtapiMaximumStatusPolls = 30000000;
48constexpr Time::Timestamp AtaDmaCompletionTimeout = 30 * Time::Multiplier::Second;
49constexpr size_t AtaDmaCompletionPollLimit = 30000000;
50constexpr Time::Timestamp AtaPioCompletionTimeout = 30 * Time::Multiplier::Second;
51constexpr size_t AtaPioCompletionPollLimit = 30000000;
52constexpr Time::Timestamp AtaFlushCompletionTimeout = 120 * Time::Multiplier::Second;
53constexpr size_t AtaFlushCompletionPollLimit = 120000000;
54
55bool waitForAtapiStatus(IoBase* commandRegs, IoBase* controlRegs, Time::Timestamp commandStarted,
56 size_t& commandPolls, AtaStatus& status) {
57 // One PACKET command gets one budget. Restarting ataWait's timeout at each
58 // data phase lets a device keep the caller here forever while still making
59 // occasional progress.
60 if (commandPolls >= AtapiMaximumStatusPolls ||
61 (Time::getTicks() - commandStarted) >= AtapiCommandTimeout) {
62 WARNING("ATAPI: PACKET command exceeded its completion deadline");
63 return false;
64 }
65
66 for (size_t i = 0; i < 4; ++i) {
67 controlRegs->read8(2);
68 }
69
70 status.__reg_contents = commandRegs->read8(7);
71 while (status.reg.bsy || (!status.reg.drq && !status.reg.drdy && !status.reg.err)) {
72 if (!status.__reg_contents) {
73 return true;
74 }
75 if (++commandPolls >= AtapiMaximumStatusPolls ||
76 (Time::getTicks() - commandStarted) >= AtapiCommandTimeout) {
77 WARNING(
78 "ATAPI: PACKET command timed out waiting for device status, "
79 "status="
80 << status.__reg_contents);
81 return false;
82 }
83
85 status.__reg_contents = commandRegs->read8(7);
86 }
87
88 return true;
89}
90
91class ScopedBusMasterTransaction {
92 public:
93 explicit ScopedBusMasterTransaction(BusMasterIde* busMaster)
94 : m_BusMaster(busMaster), m_OwnsTransaction(false) {}
95
96 ~ScopedBusMasterTransaction() {
97 complete();
98 }
99
100 bool add(uintptr_t buffer, size_t bytes) {
101 if (!m_BusMaster) {
102 return false;
103 }
104 if (!m_OwnsTransaction && !(m_OwnsTransaction = m_BusMaster->beginTransaction())) {
105 return false;
106 }
107 return m_BusMaster->add(buffer, bytes);
108 }
109
110 bool begin(bool write) {
111 return m_OwnsTransaction && m_BusMaster->begin(write);
112 }
113
114 void complete() {
115 if (m_OwnsTransaction) {
116 m_BusMaster->commandComplete();
117 m_OwnsTransaction = false;
118 }
119 }
120
121 private:
122 ScopedBusMasterTransaction(const ScopedBusMasterTransaction&) = delete;
123 ScopedBusMasterTransaction& operator=(const ScopedBusMasterTransaction&) = delete;
124
125 BusMasterIde* m_BusMaster;
126 bool m_OwnsTransaction;
127};
128
129class CachePageFillGuard {
130 public:
131 CachePageFillGuard(Cache& cache, uint64_t location, bool* insertedPages, size_t pageCount)
132 : m_Cache(cache),
133 m_Location(location),
134 m_InsertedPages(insertedPages),
135 m_PageCount(pageCount),
136 m_Published(false) {}
137
138 ~CachePageFillGuard() {
139 if (m_Published) {
140 return;
141 }
142
143 bool discarded = true;
144 for (size_t i = 0; i < m_PageCount; ++i) {
145 if (m_InsertedPages[i] && !m_Cache.discardEditing(m_Location + (i * 4096))) {
146 discarded = false;
147 }
148 }
149 if (!discarded) {
150 WARNING(
151 "AtaDisk could not discard every page from a failed cache "
152 "fill at "
153 << m_Location);
154 }
155 }
156
157 void publish() {
158 for (size_t i = 0; i < m_PageCount; ++i) {
159 if (m_InsertedPages[i]) {
160 m_Cache.markNoLongerEditing(m_Location + (i * 4096));
161 }
162 }
163 m_Published = true;
164 }
165
166 private:
167 CachePageFillGuard(const CachePageFillGuard&) = delete;
168 CachePageFillGuard& operator=(const CachePageFillGuard&) = delete;
169
170 Cache& m_Cache;
171 uint64_t m_Location;
172 bool* m_InsertedPages;
173 size_t m_PageCount;
174 bool m_Published;
175};
176} // namespace
177
178AtaDisk::IrqCompletion::IrqCompletion(AtaDisk& disk)
179 : m_Disk(disk),
180 m_Completion(0),
181 m_Published(false),
182 m_StackDiscardScope(&IrqCompletion::discard, this) {
183 LockGuard<Spinlock> guard(m_Disk.m_IrqLock);
184 if (m_Disk.m_IrqReceived) {
185 FATAL("ATA command attempted to replace a live IRQ completion");
186 }
187 m_Disk.m_IrqReceived = &m_Completion;
188 m_Published = true;
189}
190
191AtaDisk::IrqCompletion::~IrqCompletion() {
192 withdraw();
193}
194
195void AtaDisk::IrqCompletion::discard(void* context) {
196 reinterpret_cast<IrqCompletion*>(context)->withdraw();
197}
198
199void AtaDisk::IrqCompletion::withdraw() {
200 LockGuard<Spinlock> guard(m_Disk.m_IrqLock);
201 if (!m_Published) {
202 return;
203 }
204 if (m_Disk.m_IrqReceived != &m_Completion) {
205 FATAL("ATA IRQ completion publication was corrupted");
206 }
207 m_Disk.m_IrqReceived = nullptr;
208 m_Published = false;
209}
210
211AtaDisk::AtaDisk(AtaController* pDev, bool isMaster, IoBase* commandRegs, IoBase* controlRegs,
212 BusMasterIde* busMaster)
213 : ScsiDisk(),
214 m_Paging(nullptr),
215 m_IsMaster(isMaster),
216 m_SupportsLBA28(true),
217 m_SupportsLBA48(false),
218 m_BlockSize(ATA_DEFAULT_BLOCK_SIZE),
219 m_IrqReceived(0),
220 m_AtaDiskType(NotPacket),
221 m_PacketSize(0),
222 m_Removable(false),
223 m_CommandRegs(commandRegs),
224 m_ControlRegs(controlRegs),
225 m_BusMaster(busMaster),
227 m_PrdTable(0),
230 m_PrdTableMemRegion("ata-prdtable"),
231 m_bDma(true) {
232 m_pParent = pDev;
233}
234
235AtaDisk::~AtaDisk() {
236 releasePagingStorage();
237}
238
239void AtaDisk::shutdownDeviceCache() {
240 // Packet writes are rejected by this driver, including its paging path.
241 if (m_AtaDiskType == NotPacket)
242 ScsiDisk::shutdownDeviceCache();
243}
244
246 if (m_ControlRegs) {
247 // nIEN prevents fresh device IRQs after the controller queue drains.
248 m_ControlRegs->write8(0x02, 2);
249 }
250}
251
253 if (m_BusMaster) {
254 m_BusMaster->commandComplete();
255 }
256}
257
258bool AtaDisk::initialise(size_t nUnit) {
259 // The legacy cache walker and PRD builder assume 4 KiB cache pages. Reject
260 // other target pages until both sides of the transfer are converted.
261 if (TargetInfo::getPageSize() != 4096) {
262 ERROR("ATA: this driver requires 4096-byte target pages");
263 return false;
264 }
265
266 // Grab our parent.
267 AtaController* pParent = static_cast<AtaController*>(m_pParent);
268
269 // Grab our parent's IoPorts for command and control accesses.
270 IoBase* commandRegs = m_CommandRegs;
271 IoBase* controlRegs = m_ControlRegs;
272
273 // Drive spin-up (go from standby to active, if necessary)
274 setFeatures(0x07, 0, 0, 0, 0);
275
276 // Check for device presence
277 uint8_t devSelect = (m_IsMaster) ? 0xA0 : 0xB0;
278 commandRegs->write8(devSelect, 6);
279 commandRegs->write8(0xEC, 7);
280 if (commandRegs->read8(7) == 0) {
281 NOTICE("ATA: No device present here");
282 return false;
283 }
284
285 // Select the device to transmit to
286 devSelect = (m_IsMaster) ? 0xA0 : 0xB0;
287 commandRegs->write8(devSelect, 6);
288
289 // Wait for it to be selected
290 ataWait(commandRegs, controlRegs);
291
292 // DEVICE RESET
293 commandRegs->write8(8, 7);
294
295 // Wait for the drive to reset before requesting a device change
296 ataWait(commandRegs, controlRegs);
297
298 //
299 // Start IDENTIFY command.
300 //
301
302 AtaStatus status;
303
304 // Disable IRQs on this device for now.
305 controlRegs->write8(0x2, 2);
306
307 // Send IDENTIFY.
308 commandRegs->read8(7);
309 commandRegs->write8(0xEC, 7);
310
311 // Read status register.
312 status = ataWait(commandRegs, controlRegs);
313
314 // Check that the device actually exists
315 if (status.__reg_contents == 0)
316 return false;
317
318 // Check for an ATAPI device
319 uint8_t m1 = commandRegs->read8(2);
320 uint8_t m2 = commandRegs->read8(3);
321 uint8_t m3 = commandRegs->read8(4);
322 uint8_t m4 = commandRegs->read8(5);
323 // #ifdef DEBUG
324 NOTICE("ATA signature: " << m1 << ", " << m2 << ", " << m3 << ", " << m4);
325 // #endif
326 m_AtaDiskType = None;
327 if (m3 == 0x14 && m4 == 0xeb) {
328 // Run IDENTIFY PACKET DEVICE instead
329 commandRegs->write8(devSelect, 6);
330 commandRegs->write8(0xA1, 7);
331 status = ataWait(commandRegs, controlRegs);
332 } else {
333 m_AtaDiskType = NotPacket;
334 }
335
336 // After checking signature and potentially retrying with IDENTIFY PACKET
337 // DEVICE, we can check for an error proper now.
338 if (status.reg.err) {
339 WARNING("ATA drive errored on IDENTIFY!");
340 return false;
341 }
342
343 // Read the data.
344 for (int i = 0; i < 256; i++) {
345 m_pIdent.__raw[i] = commandRegs->read16(0);
346 }
347
348 // Check for late error - final sanity check.
349 if (commandRegs->read8(7) & 1) {
350 WARNING("ATA drive now has an error status after reading IDENTIFY data.");
351 return false;
352 }
353
354 // Do we have integrity data?
355 if (m_pIdent.data.signature == 0xA5) {
356 // Yes. Run a checksum.
357 uint8_t sum = 0;
358 uint8_t* bytes = reinterpret_cast<uint8_t*>(m_pIdent.__raw);
359 for (size_t i = 0; i < 512; ++i)
360 sum += bytes[i];
361
362 // The result should be zero if the checksum is in fact correct.
363 if (sum) {
364 WARNING("ATA IDENTIFY data failed checksum!");
365 return false;
366 }
367 }
368
369 // Interpret the data.
370
371 // Good device?
372 if ((m_AtaDiskType == NotPacket) && m_pIdent.data.general_config.not_ata) {
373 ERROR("ATA: Device does not conform to the ATA specification.");
374 return false;
375 } else if ((m_AtaDiskType != NotPacket) && (!m_pIdent.data.general_config.not_ata)) {
376 ERROR("ATA: PACKET device does not conform to the ATA specification.");
377 return false;
378 }
379
380 if (m_AtaDiskType != NotPacket) {
381 m_AtaDiskType = static_cast<AtaDiskType>(m_pIdent.data.general_config.packet_cmdset);
382 }
383
384 // Get the device name.
385 ataLoadSwapped(m_pName, m_pIdent.data.model_number, 20);
386
387 // The device name is padded by spaces. Backtrack through converting spaces
388 // into NULL bytes.
389 for (int i = 39; i > 0; i--) {
390 if (m_pName[i] != ' ')
391 break;
392 m_pName[i] = '\0';
393 }
394 m_pName[40] = '\0';
395
396 // Get the serial number.
397 ataLoadSwapped(m_pSerialNumber, m_pIdent.data.serial_number, 10);
398
399 // The serial number is padded by spaces. Backtrack through converting
400 // spaces into NULL bytes.
401 for (int i = 19; i > 0; i--) {
402 if (m_pSerialNumber[i] != ' ')
403 break;
404 m_pSerialNumber[i] = '\0';
405 }
406 m_pSerialNumber[20] = '\0';
407
408 // Get the firmware revision.
409 ataLoadSwapped(m_pFirmwareRevision, m_pIdent.data.firmware_revision, 4);
410
411 // The device name is padded by spaces. Backtrack through converting spaces
412 // into NULL bytes.
413 for (int i = 7; i > 0; i--) {
414 if (m_pFirmwareRevision[i] != ' ')
415 break;
416 m_pFirmwareRevision[i] = '\0';
417 }
418 m_pFirmwareRevision[8] = '\0';
419
420 // Check that LBA48 is actually enabled.
421 if (m_pIdent.data.command_sets_support.address48) {
422 m_SupportsLBA48 = m_pIdent.data.command_sets_enabled.address48;
423 if (!m_SupportsLBA48)
424 WARNING("ATA: Device supports LBA48 but it isn't enabled.");
425 }
426
427 // And check for LBA28 support, just in case.
428 if (!m_pIdent.data.caps.lba) {
430 ERROR("ATA: Device does not support LBA.");
431 return false;
432 }
433
434 // Do we have DMA?
435 m_bDma = false;
436 if (m_pIdent.data.caps.dma) {
437 m_bDma = true;
438 NOTICE("ATA: Device supports DMA.");
439
440 if (m_pIdent.data.validity.multiword_dma_valid) {
441 size_t highest_mode = ~0U;
442 if (m_pIdent.data.multiword_dma.mode0)
443 highest_mode = 0;
444 if (m_pIdent.data.multiword_dma.mode1)
445 highest_mode = 1;
446 if (m_pIdent.data.multiword_dma.mode2)
447 highest_mode = 2;
448
449 size_t sel_mode = ~0U;
450 if (m_pIdent.data.multiword_dma.sel_mode0)
451 sel_mode = 0;
452 if (m_pIdent.data.multiword_dma.sel_mode1)
453 sel_mode = 1;
454 if (m_pIdent.data.multiword_dma.sel_mode2)
455 sel_mode = 2;
456
457 if (highest_mode != ~0U) {
458 NOTICE("ATA: Device Multiword DMA: supports up to mode" << Dec << highest_mode << Hex);
459 } else {
460 NOTICE("ATA: Device Multiword DMA: no support");
461 }
462
463 if (sel_mode != ~0U) {
464 NOTICE("ATA: Device Multiword DMA: mode" << Dec << sel_mode << Hex << " is selected");
465 }
466 }
467
468 if (m_pIdent.data.validity.ultra_dma_valid) {
469 size_t highest_mode = ~0U;
470 if (m_pIdent.data.ultra_dma.supp_mode0)
471 highest_mode = 0;
472 if (m_pIdent.data.ultra_dma.supp_mode1)
473 highest_mode = 1;
474 if (m_pIdent.data.ultra_dma.supp_mode2)
475 highest_mode = 2;
476 if (m_pIdent.data.ultra_dma.supp_mode3)
477 highest_mode = 3;
478 if (m_pIdent.data.ultra_dma.supp_mode4)
479 highest_mode = 4;
480 if (m_pIdent.data.ultra_dma.supp_mode5)
481 highest_mode = 5;
482 if (m_pIdent.data.ultra_dma.supp_mode6)
483 highest_mode = 6;
484
485 size_t sel_mode = ~0U;
486 if (m_pIdent.data.ultra_dma.sel_mode0)
487 sel_mode = 0;
488 if (m_pIdent.data.ultra_dma.sel_mode1)
489 sel_mode = 1;
490 if (m_pIdent.data.ultra_dma.sel_mode2)
491 sel_mode = 2;
492 if (m_pIdent.data.ultra_dma.sel_mode3)
493 sel_mode = 3;
494 if (m_pIdent.data.ultra_dma.sel_mode4)
495 sel_mode = 4;
496 if (m_pIdent.data.ultra_dma.sel_mode5)
497 sel_mode = 5;
498 if (m_pIdent.data.ultra_dma.sel_mode6)
499 sel_mode = 6;
500
501 if (highest_mode != ~0U) {
502 NOTICE("ATA: Device Ultra DMA: supports up to mode" << Dec << highest_mode << Hex);
503 } else {
504 NOTICE("ATA: Device Ultra DMA: no support");
505 }
506
507 if (sel_mode != ~0U) {
508 NOTICE("ATA: Device Ultra DMA: mode" << Dec << sel_mode << Hex << " is enabled");
509 }
510 }
511 }
512
513 // Do we have a bus master with which to work with?
514 // ISA ATA does not.
515 if (!m_BusMaster) {
516 WARNING("ATA: Controller does not support DMA");
517 m_bDma = false;
518 }
519
520 if (m_pIdent.data.sector_size.logical_larger_than_512b ||
521 m_pIdent.data.sector_size.multiple_logical_per_physical) {
522 // Large physical sectors.
523 size_t logical_size = 512;
524 if (m_pIdent.data.sector_size.logical_larger_than_512b)
525 logical_size = m_pIdent.data.words_per_logical * sizeof(uint16_t);
526
527 // Logical sectors per physical sector.
528 size_t log_per_phys = 1 << m_pIdent.data.sector_size.logical_per_physical;
529 size_t physical_size = log_per_phys * logical_size;
530
531 NOTICE("ATA: Physical sector size is " << Dec << physical_size << Hex << " bytes.");
532 NOTICE("ATA: Logical sector size is " << Dec << logical_size << Hex << " bytes.");
533
534 if (physical_size > 512) {
535 // Non-standard physical sectors; align block size to this.
536 if (m_BlockSize % physical_size) {
537 // Default block size doesn't map to physical sectors well.
538 WARNING(
539 "ATA: Default block size doesn't map well to physical "
540 "sectors, performance may be degraded.");
541 }
542
543 // Always make sure our blocks are bigger than physical sectors.
544 if (m_BlockSize < physical_size)
545 m_BlockSize = physical_size;
546 } else {
547 // Standard physical sectors - default block size is okay.
548 }
549 }
550
551 NOTICE("ATA: IRQ is #" << Dec << getInterruptNumber() << Hex << ".");
552
553 // ATAPI pieces.
554 if (m_AtaDiskType != NotPacket) {
555 // Packet size?
556 m_PacketSize = m_pIdent.data.general_config.packet_sz ? 16 : 12;
557 NOTICE("ATAPI: packet size is " << Dec << m_PacketSize << " bytes" << Hex);
558
559 commandRegs->write8(devSelect, 6);
560 commandRegs->write8(0xDA, 7); // GET MEDIA STATUS
561 status = ataWait(commandRegs, controlRegs);
562 if (status.reg.err) {
563 // We have information in the error register
564 uint8_t err = commandRegs->read8(1);
565
566 // ABORT?
567 if (err & 0x4) {
568 WARNING("ATAPI: device does not support GET MEDIA STATUS.");
569 } else if (err & 2) {
570 WARNING("ATAPI: No media present in the drive - aborting.");
571 WARNING(
572 " TODO: handle media changes/insertions/removal "
573 "properly");
574 return false;
575 } else {
576 NOTICE("ATAPI: Media status: " << err << ".");
577 }
578 }
579
580 // Initialise SCSI disk interface.
581 if (!ScsiDisk::initialise(pParent, nUnit)) {
582 ERROR("ATAPI: ScsiDisk init failed.");
583 return false;
584 }
585
586 // Grab Inquiry data to figure out what we're working with.
587 const ScsiDisk::Inquiry* pInquiry = getInquiry();
588 m_Removable = ((pInquiry->Removable & (1 << 7)) != 0);
589 AtaDiskType inquiryType = static_cast<AtaDiskType>(pInquiry->Peripheral & 0x1F);
590 if (inquiryType != m_AtaDiskType) {
591 ERROR(
592 "ATAPI: IDENTIY PACKET DEVICE and SCSI INQUIRY disagree on "
593 "device type.");
594 return false;
595 }
596
597 // Supported device?
598 if (m_AtaDiskType != CdDvd && m_AtaDiskType != Block) {
601 WARNING(
602 "Pedigree currently only supports CD/DVD and block ATAPI "
603 "devices.");
604 return false;
605 }
606 }
607
608 preparePagingStorage();
609 publishEndpoint();
610
611 NOTICE("Detected ATA device '" << m_pName << "', '" << m_pSerialNumber << "', '"
612 << m_pFirmwareRevision << "'");
613
614 return true;
615}
616
617bool AtaDisk::sendCommand(size_t nUnit, uintptr_t pCommand, uint8_t nCommandSize,
618 uintptr_t pRespBuffer, uint16_t nRespBytes, bool bWrite) {
619 if (m_AtaDiskType == NotPacket) {
620 ERROR("AtaDisk::sendCommand called on a non-PACKET device");
621 return false;
622 }
623
624 if (!m_PacketSize) {
625 ERROR("sendCommand called but the packet size is not known!");
626 return false;
627 }
628
629 AtaStatus status;
630
631 IoBase* commandRegs = m_CommandRegs;
632 IoBase* controlRegs = m_ControlRegs;
633
634 uint16_t* tmpPacket = new uint16_t[m_PacketSize / 2];
635 PointerGuard<uint16_t> tmpGuard(tmpPacket, true);
636 if (nCommandSize > m_PacketSize) {
637 ERROR("ATAPI command is " << Dec << nCommandSize << " bytes, but the device accepts only "
638 << m_PacketSize << Hex);
639 return false;
640 }
641 MemoryCopy(tmpPacket, reinterpret_cast<void*>(pCommand), nCommandSize);
642 ByteSet(reinterpret_cast<uint8_t*>(tmpPacket) + nCommandSize, 0, m_PacketSize - nCommandSize);
643
644 // Set nIEN as we poll in sendCommand().
645 controlRegs->write8(2, 2);
646
647 // Status belongs to the currently selected device. Select our target
648 // before waiting so a failed probe of the other device cannot strand us
649 // polling an absent slave forever.
650 uint8_t devSelect = m_IsMaster ? 0xA0 : 0xB0;
651 commandRegs->write8(devSelect, 6);
652 ataWait(commandRegs, controlRegs);
653
654 // Verify that it's the correct device
655 if ((commandRegs->read8(6) & devSelect) != devSelect) {
656 WARNING("ATAPI: Device was not selected");
657 return false;
658 }
659
660 ScopedBusMasterTransaction dmaTransaction(m_BusMaster);
661 bool bDmaSetup = false;
662 if (m_bDma && nRespBytes) {
663 bDmaSetup = dmaTransaction.add(pRespBuffer, nRespBytes);
664 if (bDmaSetup) {
665 // Start the bus master before selecting PACKET DMA. If this fails,
666 // the command can still be issued cleanly in PIO mode.
667 bDmaSetup = dmaTransaction.begin(bWrite);
668 }
669 }
670
671 // PACKET command
672 if ((m_pIdent.__raw[62] & (1 << 15)) &&
673 bDmaSetup) // Device requires DMADIR for Packet DMA commands
674 commandRegs->write8((bWrite ? 1 : 5), 1); // Transfer to host, DMA
675 else if (bDmaSetup)
676 commandRegs->write8(1, 1); // No overlap, DMA
677 else
678 commandRegs->write8(0, 1); // No overlap, no DMA
679 commandRegs->write8(0, 2); // Tag = 0
680 commandRegs->write8(0, 3); // N/A for PACKET command
681 commandRegs->write8(nRespBytes & 0xFF, 4); // Byte count limit
682 commandRegs->write8(((nRespBytes >> 8) & 0xFF), 5);
683
684 // Packet commands such as optical-media reads may legitimately need time
685 // for the medium to become ready, but every status transition and data
686 // phase below shares this 30-second command budget.
687 const Time::Timestamp commandStarted = Time::getTicks();
688 size_t commandPolls = 0;
689
690 // Transmit the PACKET command, wait for the device to be ready for the
691 // command.
692 commandRegs->write8(0xA0, 7);
693
694 // Wait for sensible status before writing command packet.
695 if (!waitForAtapiStatus(commandRegs, controlRegs, commandStarted, commandPolls, status)) {
696 return false;
697 }
698
699 // Error?
700 if (status.reg.err) {
701 ERROR("ATAPI Packet command error [status=" << status.__reg_contents << "]!");
702 return false;
703 }
704
705 // Transmit the command (padded as needed)
706 for (size_t i = 0; i < (m_PacketSize / 2); i++) {
707 commandRegs->write16(tmpPacket[i], 0);
708 }
709
710 // 400ns wait before reading status register.
711 for (size_t i = 0; i < 4; ++i)
712 controlRegs->read8(2);
713
714 // Check for errors...
715 // Note: not using ataWait as we don't want to block here.
716 uint8_t statusreg = commandRegs->read8(7);
717 if ((statusreg & 1) && !(statusreg & 0x80)) {
718 // CHK = 1, BSY = 0
719 uint8_t error = commandRegs->read8(1);
720 if (error & 0x4) {
721 WARNING("ATAPI command failed (ABORT)");
722 } else {
723 WARNING("ATAPI error with status " << statusreg << " [error=" << error << "]");
724 }
725
726 return false;
727 }
728
729 // If we aren't expecting anything from the device, we can just poll for
730 // completion instead of waiting for an IRQ.
731 if (!nRespBytes) {
732 if (!waitForAtapiStatus(commandRegs, controlRegs, commandStarted, commandPolls, status)) {
733 return false;
734 }
735 return !status.reg.err;
736 }
737
738 if (bDmaSetup) {
739 while (true) {
740 if (commandPolls >= AtapiMaximumStatusPolls ||
741 (Time::getTicks() - commandStarted) >= AtapiCommandTimeout) {
742 WARNING("ATAPI: DMA command timed out");
743 return false;
744 }
745
746 status.__reg_contents = commandRegs->read8(7);
747 if (!status.reg.bsy && status.reg.err) {
748 WARNING("ATAPI: read failed during DMA data transfer");
749 return false;
750 }
751
752 if (m_BusMaster->hasInterrupt() || m_BusMaster->hasCompleted()) {
753 // commandComplete effectively resets the device state, so we
754 // need to get the error register first.
755 bool bError = m_BusMaster->hasError();
756 dmaTransaction.complete();
757 if (bError)
758 return false;
759 else
760 break;
761 }
762
763 ++commandPolls;
765 }
766
767 if (!waitForAtapiStatus(commandRegs, controlRegs, commandStarted, commandPolls, status)) {
768 return false;
769 }
770 if (status.reg.err) {
771 WARNING("ATAPI sendCommand failed after sending command packet");
772 logAtaStatus(status);
773 return false;
774 }
775
776 return true;
777 }
778
779 // ATAPI PIO may split a response into multiple DRQ phases. This commonly
780 // happens for CD reads, where each phase is limited to one native sector.
781 size_t transferred = 0;
782 size_t pioPhases = 0;
783 const size_t maximumPioPhases = nRespBytes / sizeof(uint16_t);
784 while (true) {
785 if ((Time::getTicks() - commandStarted) >= AtapiCommandTimeout) {
786 WARNING("ATAPI: PIO command timed out");
787 return false;
788 }
789 if (!waitForAtapiStatus(commandRegs, controlRegs, commandStarted, commandPolls, status)) {
790 return false;
791 }
792 if (status.reg.err) {
793 WARNING("ATAPI PIO command failed during a data phase");
794 logAtaStatus(status);
795 return false;
796 }
797 if (!status.reg.drq) {
798 return true;
799 }
800 if (++pioPhases > maximumPioPhases) {
801 ERROR("ATAPI PIO command exceeded its possible data-phase count");
802 return false;
803 }
804
805 size_t realSz = commandRegs->read8(4) | (commandRegs->read8(5) << 8);
806 if (!realSz) {
807 ERROR("ATAPI PIO data phase reported a zero byte count");
808 return false;
809 }
810 if (realSz & 1) {
811 ERROR("ATAPI PIO data phase reported an odd byte count");
812 return false;
813 }
814
815 const size_t remaining = nRespBytes - transferred;
816 const size_t transferSz = realSz < remaining ? realSz : remaining;
817 uint16_t* dest = reinterpret_cast<uint16_t*>(pRespBuffer + transferred);
818 for (size_t i = 0; i < (transferSz / 2); ++i) {
819 if (bWrite)
820 commandRegs->write16(dest[i], 0);
821 else
822 dest[i] = commandRegs->read16(0);
823 }
824
825 // A malformed device must not make us touch past the caller's buffer,
826 // but abandoning a partially consumed phase leaves DRQ asserted and
827 // poisons the next command on the channel. Drain this one bounded
828 // 16-bit phase, then report the protocol violation.
829 for (size_t i = transferSz; i < realSz; i += sizeof(uint16_t)) {
830 if (bWrite)
831 commandRegs->write16(0xFFFF, 0);
832 else
833 commandRegs->read16(0);
834 }
835 if (realSz > remaining) {
836 ERROR("ATAPI PIO data phase exceeds the response buffer: phase="
837 << Dec << realSz << ", remaining=" << remaining << Hex);
838 return false;
839 }
840 transferred += transferSz;
841 }
842}
843
844uint64_t AtaDisk::doRead(uint64_t location) {
845 if (m_AtaDiskType != NotPacket)
846 return ScsiDisk::doRead(location);
847
848 // Memory for the "already-read" buffers to point at for DMA scatter/gather
849 static char alreadyRead[4096] ALIGN(4096);
850
851 // Create our set of buffers to read into.
852 size_t nBytes = getCacheFillLength(location);
853 if (!nBytes) {
854 return 0;
855 }
856 // This legacy path allocates and publishes only complete 4 KiB cache pages.
857 // Do not report a terminal native-block tail as a successful empty transfer.
858 if (nBytes % 4096) {
859 ERROR("ATA: cache fill did not cover a complete 4096-byte cache page");
860 return 0;
861 }
862 const uint64_t cacheLocation = location;
863 uint64_t ioLocation = location;
864
865 // Allocate list of buffers, allowing us to handle cache pages being widely
866 // distributed around the virtual address space.
867 size_t nBuffers = nBytes / 0x1000;
868 Buffer* buffers = new Buffer[nBuffers];
869 PointerGuard<Buffer> guard2(buffers, true);
870 bool* insertedPages = new bool[nBuffers];
871 PointerGuard<bool> insertedPagesGuard(insertedPages, true);
872 ByteSet(insertedPages, 0, nBuffers * sizeof(bool));
873 CachePageFillGuard fillGuard(getCache(), cacheLocation, insertedPages, nBuffers);
874
875 bool bAlreadyAllRead = true;
876 for (size_t i = 0; i < nBuffers; ++i) {
877 buffers[i].offset = i * 0x1000;
878
879 uintptr_t buffer = getCache().lookup(location + buffers[i].offset);
880 if (buffer) {
881 getCache().release(location + buffers[i].offset);
882 buffer = reinterpret_cast<uintptr_t>(alreadyRead);
883 } else {
884 bool didExist = false;
885 buffer = getCache().insert(location + buffers[i].offset, &didExist);
886 if (!buffer) {
887 FATAL("AtaDisk::doRead - couldn't get a buffer!");
888 return 0;
889 }
890
891 if (didExist) {
892 buffer = reinterpret_cast<uintptr_t>(alreadyRead);
893 } else {
894 insertedPages[i] = true;
895 bAlreadyAllRead = false;
896 }
897 }
898
899 buffers[i].buffer = buffer;
900 }
901
902 if (bAlreadyAllRead) {
903 // All pages were already in cache.
904 return nBytes;
905 }
906
907 // Grab our parent's IoPorts for command and control accesses.
908 IoBase* commandRegs = m_CommandRegs;
909 IoBase* controlRegs = m_ControlRegs;
910
911 // How many sectors do we need to read?
913 uint32_t nSectors = nBytes / 512;
914
915 // Wait for BSY and DRQ to be zero before selecting the device
916 AtaStatus status;
917 ataWait(commandRegs, controlRegs);
918
919 // Select the device to transmit to
920 uint8_t devSelect;
921 if (m_SupportsLBA48)
922 devSelect = (m_IsMaster) ? 0xE0 : 0xF0;
923 else
924 devSelect = (m_IsMaster) ? 0xA0 : 0xB0;
925 commandRegs->write8(devSelect, 6);
926
927 // Wait for it to be selected
928 ataWait(commandRegs, controlRegs);
929
930 size_t buffersConsumed = 0;
931 while (nSectors > 0) {
932 ScopedBusMasterTransaction dmaTransaction(m_BusMaster);
933
934 // ataWait applies both a wall-clock and poll-count deadline. A device
935 // which never becomes ready must fail this request rather than strand
936 // the RequestQueue worker forever.
937 status = ataWait(commandRegs, controlRegs);
938 if (status.reg.err || !status.reg.drdy) {
939 ERROR("ATA: drive did not become ready for read");
940 return 0;
941 }
942
943 // Send out sector count.
944 uint8_t nSectorsToRead = min(m_pIdent.data.max_sectors_per_irq, nSectors);
945 nSectors -= nSectorsToRead;
946
947 // Buffers are 4K each, so calculate the number of buffers used for
948 // this particular read.
949 size_t buffersThisRead = (nSectorsToRead * 512) / 0x1000;
950 const size_t firstBuffer = buffersConsumed;
951
952 bool bDmaSetup = false;
953 if (m_bDma) {
954 for (size_t i = 0; i < buffersThisRead; ++i) {
955 bDmaSetup = dmaTransaction.add(buffers[firstBuffer + i].buffer, 0x1000);
956 if (!bDmaSetup) {
957 ERROR("DMA setup failed!");
958 break;
959 }
960 }
961 }
962
963 if (m_SupportsLBA48)
964 setupLBA48(ioLocation, nSectorsToRead);
965 else {
966 if (ioLocation >= 0x2000000000ULL) {
967 WARNING(
968 "Ata: Sector > 128GB requested but LBA48 addressing "
969 "not supported!");
970 }
971 setupLBA28(ioLocation, nSectorsToRead);
972 }
973
974 IrqCompletion irqCompletion(*this);
975
976 if (getInterruptNumber() != 0xFF) {
977 // Enable IRQs so we can avoid spinning if possible.
978 controlRegs->write8(0, 2);
979
980 bool oldInterrupts = Processor::getInterrupts();
981 if (!oldInterrupts)
983 }
984
985 if (m_bDma && bDmaSetup) {
986 // Prepare DMA before we send the command.
987 bDmaSetup = dmaTransaction.begin(false);
988
989 if (!m_SupportsLBA48) {
990 // Send command "read DMA"
991 commandRegs->write8(0xC8, 7);
992 } else {
993 // Send command "read DMA EXT"
994 commandRegs->write8(0x25, 7);
995 }
996 } else {
997 if (m_SupportsLBA48) {
998 // Send command "read sectors EXT"
999 commandRegs->write8(0x24, 7);
1000 } else {
1001 // Send command "read sectors with retry"
1002 commandRegs->write8(0x20, 7);
1003 }
1004 }
1005
1006 const Time::Timestamp completionStarted = Time::getTicks();
1007 size_t completionPolls = 0;
1008
1009 // Acquire the 'outstanding IRQ' mutex, or use other means if no IRQ.
1010 while (true) {
1011 if (++completionPolls >= AtaDmaCompletionPollLimit ||
1012 (Time::getTicks() - completionStarted) >= AtaDmaCompletionTimeout) {
1013 ERROR("ATA: DMA read exceeded its completion deadline");
1014 return 0;
1015 }
1016
1017 if (getInterruptNumber() != 0xFF) {
1018 if (!irqCompletion->acquireForCompletion(1, 10)) {
1019 // Timeout.
1020 ERROR("ATA: timeout during data transfer");
1021 return 0;
1022 }
1023 }
1024
1025 // Ensure we are not busy before continuing handling.
1026 status = ataWait(commandRegs, controlRegs);
1027 if (status.reg.err) {
1029 if (m_bDma && bDmaSetup) {
1030 WARNING("ATA: read failed during DMA data transfer");
1031 }
1032 return false;
1033 }
1034
1035 if (m_bDma && bDmaSetup) {
1036 if (m_BusMaster->hasInterrupt() || m_BusMaster->hasCompleted()) {
1037 // commandComplete effectively resets the device state, so
1038 // we need to get the error register first.
1039 bool bError = m_BusMaster->hasError();
1040 dmaTransaction.complete();
1041 if (bError) {
1042 return 0;
1043 } else {
1044 break;
1045 }
1046 }
1047 } else {
1048 break;
1049 }
1051 }
1052
1053 if (!bDmaSetup) {
1054 size_t byteOffset = firstBuffer * 0x1000;
1055 for (int i = 0; i < nSectorsToRead; i++) {
1056 // Wait until !BUSY
1057 status = ataWait(commandRegs, controlRegs);
1058 if (status.reg.err) {
1059 // Ka-boom! Something went wrong :(
1061 WARNING("ATA: read failed during data transfer");
1062 return 0;
1063 }
1064
1065 // Figure out which buffer we care about here.
1066 size_t nBuffer = byteOffset / 0x1000;
1067 size_t offset = byteOffset % 0x1000;
1068
1069 // Read the sector.
1070 uint16_t* target = reinterpret_cast<uint16_t*>(buffers[nBuffer].buffer + offset);
1071 for (int j = 0; j < 256; j++) {
1072 *target++ = commandRegs->read16(0);
1073 }
1074
1075 byteOffset += 512;
1076 }
1077 }
1078
1079 buffersConsumed += buffersThisRead;
1080 ioLocation += nSectorsToRead * 512;
1081 }
1082
1083 assert(buffersConsumed == nBuffers);
1084
1085 fillGuard.publish();
1086 return nBytes;
1087}
1088
1089uint64_t AtaDisk::doWrite(uint64_t location) {
1090 if (location % 512)
1091 panic("AtaDisk: write request not on a sector boundary!");
1092
1093// Safety check
1094#if CRIPPLE_HDD
1095 return 0;
1096#endif
1097
1098 if (m_AtaDiskType != NotPacket) {
1100 // ATA controllers bypass ScsiController's post-write unpin, so unsupported
1101 // packet writes must retire the cache pin transferred by ScsiDisk::write.
1102 getCache().endMutableLoan(location);
1103 getCache().release(location);
1104 return 0;
1105 }
1106
1107 // Write only the affected page. This deviates from the behaviour of reads,
1108 // which read a very large amount of data at once. Most writes (flush()
1109 // aside) are done asynchronously, while reads are synchronous.
1110 // This means we don't need to care about evicted pages within a disk block
1111 // because we're writing only a specific page that we already know exists.
1112 const uintptr_t buffer = ataTakeQueuedWritePage(getCache(), location);
1113 if (!buffer) {
1114 ERROR("AtaDisk::doWrite - queued buffer was not in cache");
1115 return 0;
1116 }
1117
1118 // Make sure we don't leave the refcnt increased by writing.
1119 CachePageGuard guard(getCache(), location);
1120
1121 return writePageBuffer(location, buffer);
1122}
1123
1124uint64_t AtaDisk::doWriteDirect(uint64_t location, uintptr_t page) {
1125 if ((location % 512) || !page)
1126 return 0;
1127
1128// Safety check
1129#if CRIPPLE_HDD
1130 return 0;
1131#endif
1132
1133 if (m_AtaDiskType != NotPacket)
1134 return 0;
1135
1136 return writePageBuffer(location, page);
1137}
1138
1139uint64_t AtaDisk::doSync(uint64_t location) {
1140#if CRIPPLE_HDD
1141 return 0;
1142#endif
1143
1144 if (m_AtaDiskType != NotPacket) {
1145 return ScsiDisk::doSync(location);
1146 }
1147
1148 const bool wholeDevice = location == SyncWholeDevice;
1149 const size_t nativeBlockSize = getNativeBlockSize();
1150 if (!getSize() || (!wholeDevice && location >= getSize())) {
1151 return 0;
1152 }
1153 const size_t validLength =
1154 wholeDevice ? 1 : min(static_cast<size_t>(getSize() - location), TargetInfo::getPageSize());
1155 if (!nativeBlockSize || !validLength ||
1156 (!wholeDevice && ((location % nativeBlockSize) || (validLength % nativeBlockSize))) ||
1157 !m_CommandRegs || !m_ControlRegs) {
1158 return 0;
1159 }
1160
1161 if ((m_pIdent.__raw[83] & 0xC000) != 0x4000) {
1162 return 0;
1163 }
1164 const bool extended = m_SupportsLBA48 && m_pIdent.data.command_sets_support.flush_cache_ext;
1165 if (!extended && !m_pIdent.data.command_sets_support.flush_cache) {
1166 WARNING("ATA: device does not advertise a supported cache flush command");
1167 return 0;
1168 }
1169
1170 // The controller request worker serialises this non-data command with I/O.
1171 // Polling avoids relying on a data-transfer IRQ completion for cache flush.
1172 m_ControlRegs->write8(2, 2);
1173 AtaStatus status = ataWait(m_CommandRegs, m_ControlRegs);
1174 if (status.reg.bsy || status.reg.drq) {
1175 return 0;
1176 }
1177 m_CommandRegs->write8(m_IsMaster ? 0xA0 : 0xB0, 6);
1178 status = ataWait(m_CommandRegs, m_ControlRegs);
1179 if (status.reg.bsy || status.reg.drq || status.reg.df || !status.reg.drdy) {
1180 return 0;
1181 }
1182
1183 // ACS-3 permits FLUSH CACHE to exceed 30 seconds. A single larger budget
1184 // still bounds a stuck device, including systems whose clock stops ticking.
1185 AtaPioPollBudget budget = {Time::getTicks(), AtaFlushCompletionTimeout, 0,
1186 AtaFlushCompletionPollLimit};
1187 m_CommandRegs->write8(extended ? 0xEA : 0xE7, 7);
1188 status.__reg_contents = 0;
1189 if (!ataPollPioWriteStatus(m_CommandRegs, m_ControlRegs, budget, status, false)) {
1190 WARNING("ATA: cache flush failed or exceeded its completion deadline, status="
1191 << status.__reg_contents);
1192 return 0;
1193 }
1194 return validLength;
1195}
1196
1197uint64_t AtaDisk::writePageBuffer(uint64_t location, uintptr_t buffer) {
1198 const uintptr_t nBytes = 0x1000;
1199
1200 if (getNativeBlockSize() != 512) {
1201 ERROR("ATA: writes require 512-byte logical sectors");
1202 return 0;
1203 }
1204
1205#if SUPERDEBUG
1206 NOTICE("doWrite(" << location << ")");
1207#endif
1208
1209 // Grab our parent's IoPorts for command and control accesses.
1210 IoBase* commandRegs = m_CommandRegs;
1211 IoBase* controlRegs = m_ControlRegs;
1212
1213 // Geometry has been validated above, so one cache page is eight sectors.
1214 uint32_t nSectors = nBytes / 512;
1215 if (nBytes % 512)
1216 nSectors++;
1217
1218 // Wait for BSY and DRQ to be zero before selecting the device
1219 AtaStatus status;
1220 ataWait(commandRegs, controlRegs);
1221
1222 // Select the device to transmit to
1223 uint8_t devSelect;
1224 if (m_SupportsLBA48)
1225 devSelect = (m_IsMaster) ? 0xE0 : 0xF0;
1226 else
1227 devSelect = (m_IsMaster) ? 0xA0 : 0xB0;
1228 commandRegs->write8(devSelect, 6);
1229
1230 // Wait for it to be selected
1231 ataWait(commandRegs, controlRegs);
1232
1233 uint16_t* tmp = reinterpret_cast<uint16_t*>(buffer);
1234
1235 while (nSectors > 0) {
1236 ScopedBusMasterTransaction dmaTransaction(m_BusMaster);
1237
1238 // Keep write admission on the same bounded readiness contract as
1239 // reads. This used to be an unbounded boot/storage stall.
1240 status = ataWait(commandRegs, controlRegs);
1241 if (status.reg.err || !status.reg.drdy) {
1242 ERROR("ATA: drive did not become ready for write");
1243 return 0;
1244 }
1245
1246 // PIO WRITE SECTORS is one page-sized command. The IDENTIFY multiple-mode
1247 // limit does not apply to it.
1248 uint8_t nSectorsToWrite =
1249 m_bDma ? min(m_pIdent.data.max_sectors_per_irq, nSectors) : static_cast<uint8_t>(nSectors);
1250
1251 bool bDmaSetup = false;
1252 if (m_bDma && nSectorsToWrite) {
1253 bDmaSetup = dmaTransaction.add(buffer, nSectorsToWrite * 512);
1254 }
1255 if (!bDmaSetup) {
1256 nSectorsToWrite = static_cast<uint8_t>(nSectors);
1257 }
1258 nSectors -= nSectorsToWrite;
1259
1260 if (m_SupportsLBA48)
1261 setupLBA48(location, nSectorsToWrite);
1262 else {
1263 if (location >= 0x2000000000ULL) {
1264 WARNING(
1265 "Ata: Sector > 128GB requested but LBA48 addressing "
1266 "not supported!");
1267 }
1268 setupLBA28(location, nSectorsToWrite);
1269 }
1270
1271 // Enable IRQs so we can avoid spinning if possible.
1272 controlRegs->write8(0, 2);
1273
1274 IrqCompletion irqCompletion(*this);
1275
1276 bool oldInterrupts = Processor::getInterrupts();
1277 if (!oldInterrupts)
1279
1280 if (m_bDma && bDmaSetup) {
1281 // Start DMA before we send the command.
1282 if (!dmaTransaction.begin(true)) {
1283 ERROR("ATA: failed to start DMA write");
1284 return 0;
1285 }
1286
1287 if (!m_SupportsLBA48) {
1288 // Send command "write DMA"
1289 commandRegs->write8(0xCA, 7);
1290 } else {
1291 // Send command "read write EXT"
1292 commandRegs->write8(0x35, 7);
1293 }
1294 const Time::Timestamp completionStarted = Time::getTicks();
1295 size_t completionPolls = 0;
1296
1297 // Wait for completion.
1298 while (true) {
1299 if (++completionPolls >= AtaDmaCompletionPollLimit ||
1300 (Time::getTicks() - completionStarted) >= AtaDmaCompletionTimeout) {
1301 ERROR("ATA: DMA write exceeded its completion deadline");
1302 return 0;
1303 }
1304
1305 if (getInterruptNumber() != 0xFF) {
1306 // 10 second timeout.
1307 if (!irqCompletion->acquireForCompletion(1, 10)) {
1308 WARNING("ATA: failed to get IRQ");
1309 return 0;
1310 }
1311 }
1312
1313 // Ensure we are not busy before continuing handling.
1314 status = ataWait(commandRegs, controlRegs);
1315 if (status.reg.err) {
1317 WARNING("ATA: write failed during DMA data transfer");
1318 return false;
1319 }
1320
1321 if (m_BusMaster->hasInterrupt() || m_BusMaster->hasCompleted()) {
1322 // commandComplete effectively resets the device state, so
1323 // we need to get the error register first.
1324 bool bError = m_BusMaster->hasError();
1325 dmaTransaction.complete();
1326 if (bError)
1327 return 0;
1328 else
1329 break;
1330 }
1332 }
1333 } else {
1334 AtaPioPollBudget budget = {Time::getTicks(), AtaPioCompletionTimeout, 0,
1335 AtaPioCompletionPollLimit};
1336
1337 if (m_SupportsLBA48) {
1338 // Send command "write sectors EXT"
1339 commandRegs->write8(0x34, 7);
1340 } else {
1341 // Send command "write sectors with retry"
1342 commandRegs->write8(0x30, 7);
1343 }
1344
1345 // A write-completion IRQ cannot arrive until the host services the
1346 // initial DRQ, so the data-phase poll must begin immediately.
1347 if (!ataPioWrite512ByteSectors(commandRegs, controlRegs, tmp, nSectorsToWrite, budget,
1348 status)) {
1349 WARNING("ATA: PIO write failed, status=" << status.__reg_contents);
1350 return 0;
1351 }
1352 }
1353 }
1354
1355#if SUPERDEBUG
1356 NOTICE("ATA: successfully wrote " << nBytes << " bytes to disk.");
1357#endif
1358 return nBytes;
1359}
1360
1362 LockGuard<Spinlock> guard(m_IrqLock);
1363 if (m_IrqReceived) {
1365 }
1366}
1367
1368void AtaDisk::setupLBA28(uint64_t n, uint32_t nSectors) {
1369 IoBase* commandRegs = m_CommandRegs;
1370
1371 commandRegs->write8(static_cast<uint8_t>(nSectors & 0xFF), 2);
1372
1373 // Get the sector number of the address.
1374 n /= 512;
1375
1376 uint8_t sector = static_cast<uint8_t>(n & 0xFF);
1377 uint8_t cLow = static_cast<uint8_t>((n >> 8) & 0xFF);
1378 uint8_t cHigh = static_cast<uint8_t>((n >> 16) & 0xFF);
1379 uint8_t head = static_cast<uint8_t>((n >> 24) & 0x0F);
1380 if (m_IsMaster)
1381 head |= 0xE0;
1382 else
1383 head |= 0xF0;
1384
1385 commandRegs->write8(head, 6);
1386 commandRegs->write8(sector, 3);
1387 commandRegs->write8(cLow, 4);
1388 commandRegs->write8(cHigh, 5);
1389}
1390
1391void AtaDisk::setupLBA48(uint64_t n, uint32_t nSectors) {
1392 IoBase* commandRegs = m_CommandRegs;
1393
1394 // Get the sector number of the address.
1395 n /= 512;
1396
1397 uint8_t lba1 = static_cast<uint8_t>(n & 0xFF);
1398 uint8_t lba2 = static_cast<uint8_t>((n >> 8) & 0xFF);
1399 uint8_t lba3 = static_cast<uint8_t>((n >> 16) & 0xFF);
1400 uint8_t lba4 = static_cast<uint8_t>((n >> 24) & 0xFF);
1401 uint8_t lba5 = static_cast<uint8_t>((n >> 32) & 0xFF);
1402 uint8_t lba6 = static_cast<uint8_t>((n >> 40) & 0xFF);
1403
1404 commandRegs->write8((nSectors & 0xFFFF) >> 8, 2);
1405 commandRegs->write8(lba4, 3);
1406 commandRegs->write8(lba5, 4);
1407 commandRegs->write8(lba6, 5);
1408 commandRegs->write8((nSectors & 0xFF), 2);
1409 commandRegs->write8(lba1, 3);
1410 commandRegs->write8(lba2, 4);
1411 commandRegs->write8(lba3, 5);
1412}
1413
1414void AtaDisk::setFeatures(uint8_t command, uint8_t countreg, uint8_t lowreg, uint8_t midreg,
1415 uint8_t hireg) {
1416 // Grab our parent's IoPorts for command and control accesses.
1417 IoBase* commandRegs = m_CommandRegs;
1418
1419 uint8_t devSelect = (m_IsMaster) ? 0xA0 : 0xB0;
1420 commandRegs->write8(devSelect, 6);
1421
1422 commandRegs->write8(command, 1);
1423 commandRegs->write8(countreg, 2);
1424 commandRegs->write8(lowreg, 3);
1425 commandRegs->write8(midreg, 4);
1426 commandRegs->write8(hireg, 5);
1427 commandRegs->write8(0xEF, 7);
1428}
1429
1430size_t AtaDisk::getSize() const {
1431 if (m_AtaDiskType != NotPacket) {
1432 return ScsiDisk::getSize();
1433 }
1434
1435 // Determine sector count.
1436 size_t sector_count = 0;
1437 if (m_SupportsLBA48) {
1438 // Try for the LBA48 sector count.
1439 if (m_pIdent.data.max_user_lba48)
1440 sector_count = m_pIdent.data.max_user_lba48;
1441 else
1442 sector_count = m_pIdent.data.sector_count;
1443 } else {
1444 sector_count = m_pIdent.data.sector_count;
1445 }
1446
1447 // Determine sector size.
1448 size_t sector_size = 512;
1449 if (m_pIdent.data.sector_size.logical_larger_than_512b) {
1450 // Calculate.
1451 sector_size = m_pIdent.data.words_per_logical * sizeof(uint16_t);
1452 }
1453
1454 return sector_count * sector_size;
1455}
1456
1458 if (m_AtaDiskType != NotPacket) {
1459 return ScsiDisk::getBlockSize();
1460 }
1461 return m_BlockSize;
1462}
1463
1465 if (m_AtaDiskType != NotPacket) {
1467 }
1468 return m_BlockSize;
1469}
1470
1472 if (m_AtaDiskType != NotPacket) {
1474 }
1475
1476 // Native blocks are just sectors.
1477 size_t sector_size = 512;
1478 if (m_pIdent.data.sector_size.logical_larger_than_512b) {
1479 // Calculate.
1480 sector_size = m_pIdent.data.words_per_logical * sizeof(uint16_t);
1481 }
1482
1483 return sector_size;
1484}
1485
1486size_t AtaDisk::getBlockCount() const {
1487 if (m_AtaDiskType != NotPacket) {
1488 return ScsiDisk::getBlockCount();
1489 }
1490
1491 // Determine sector count.
1492 size_t sector_count = 0;
1493 if (m_SupportsLBA48) {
1494 // Try for the LBA48 sector count.
1495 if (m_pIdent.data.max_user_lba48)
1496 sector_count = m_pIdent.data.max_user_lba48;
1497 else
1498 sector_count = m_pIdent.data.sector_count;
1499 } else {
1500 sector_count = m_pIdent.data.sector_count;
1501 }
1502
1503 return sector_count;
1504}
IoBase * m_CommandRegs
Definition AtaDisk.h:211
IdentifyData m_pIdent
Definition AtaDisk.h:177
AtaDiskType m_AtaDiskType
Definition AtaDisk.h:198
bool m_Removable
Definition AtaDisk.h:204
virtual MUST_USE_RESULT uint64_t doWriteDirect(uint64_t location, uintptr_t page)
Definition AtaDisk.cc:1124
uint8_t m_PacketSize
Definition AtaDisk.h:201
char m_pName[64]
Definition AtaDisk.h:179
void setupLBA28(uint64_t n, uint32_t nSectors)
Definition AtaDisk.cc:1368
void maskInterrupts()
Definition AtaDisk.cc:245
bool m_IsMaster
Definition AtaDisk.h:174
virtual uint64_t doWrite(uint64_t location)
Definition AtaDisk.cc:1089
virtual size_t getNativeBlockSize() const
Definition AtaDisk.cc:1471
Semaphore * m_IrqReceived
Definition AtaDisk.h:194
virtual size_t getCacheFillSize() const
Definition AtaDisk.cc:1464
size_t m_LastPrdTableOffset
Definition AtaDisk.h:223
Mutex m_PrdTableLock
Definition AtaDisk.h:216
void setFeatures(uint8_t command, uint8_t countreg, uint8_t lowreg, uint8_t midreg, uint8_t hireg)
Definition AtaDisk.cc:1414
bool initialise(size_t nUnit=~0)
Definition AtaDisk.cc:258
char m_pSerialNumber[64]
Definition AtaDisk.h:181
char m_pFirmwareRevision[64]
Definition AtaDisk.h:183
physical_uintptr_t m_PrdTablePhys
Definition AtaDisk.h:226
void setupLBA48(uint64_t n, uint32_t nSectors)
Definition AtaDisk.cc:1391
virtual uint64_t doRead(uint64_t location)
Definition AtaDisk.cc:844
bool m_SupportsLBA28
Definition AtaDisk.h:185
PhysicalRegionDescriptor * m_PrdTable
Definition AtaDisk.h:219
virtual void irqReceived()
Definition AtaDisk.cc:1361
size_t m_BlockSize
Definition AtaDisk.h:189
uint64_t writePageBuffer(uint64_t location, uintptr_t page)
Definition AtaDisk.cc:1197
void stopDma()
Definition AtaDisk.cc:252
MemoryRegion m_PrdTableMemRegion
Definition AtaDisk.h:229
virtual size_t getSize() const
Gets the size of the disk.
Definition AtaDisk.cc:1430
virtual size_t getBlockSize() const
Gets the preferred I/O extent of the disk.
Definition AtaDisk.cc:1457
bool m_SupportsLBA48
Definition AtaDisk.h:187
bool m_bDma
Definition AtaDisk.h:232
bool hasError()
Determines if an ERROR has occurred on this channel.
bool hasCompleted()
Determines if the CURRENT TRANSFER has completed.
void commandComplete()
Called by drivers when a command completes.
bool hasInterrupt()
Determines if an INTERRUPT has occurred on this channel.
Definition Cache.h:207
void release(uintptr_t key)
Definition Cache.cc:1570
uintptr_t insert(uintptr_t key, bool *alreadyExisted=nullptr)
Definition Cache.cc:890
uintptr_t lookup(uintptr_t key)
Definition Cache.cc:737
Device * m_pParent
Definition Device.h:353
virtual uintptr_t getInterruptNumber()
Definition Device.h:271
Abstrace base class for hardware I/O capabilities.
Definition IoBase.h:32
virtual uint8_t read8(size_t offset=0)=0
virtual void write8(uint8_t value, size_t offset=0)=0
virtual void write16(uint16_t value, size_t offset=0)=0
virtual uint16_t read16(size_t offset=0)=0
static bool getInterrupts()
static void pause()
static void setInterrupts(bool bEnable)
virtual uint64_t doRead(uint64_t location)
Definition ScsiDisk.cc:1267
bool initialise(class ScsiController *pController, size_t nUnit)
Definition ScsiDisk.cc:286
virtual size_t getSize() const
Gets the size of the disk.
Definition ScsiDisk.h:141
size_t getCacheFillLength(uint64_t location) const
Definition ScsiDisk.cc:1389
virtual size_t getCacheFillSize() const
Definition ScsiDisk.h:192
virtual size_t getBlockSize() const
Gets the preferred I/O extent of the disk.
Definition ScsiDisk.h:149
virtual size_t getNativeBlockSize() const
Definition ScsiDisk.h:157
void release(size_t n=1)
Definition Semaphore.cc:549
MUST_USE_RESULT bool acquireForCompletion(size_t n=1, size_t timeoutSecs=0, size_t timeoutUsecs=0)
Definition Semaphore.cc:372
static constexpr size_t getPageSize() noexcept
Definition TargetInfo.h:40
void EXPORTED_PUBLIC panic(const char *msg) NORETURN
Definition panic.cc:118
@ Dec
Definition Log.h:126
@ Hex
Definition Log.h:124
size_t offset
Offset into the read.
Definition AtaDisk.h:170
uintptr_t buffer
Virtual address of buffer to read into (page sized).
Definition AtaDisk.h:167