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 "AtaController.h"
22 #include "ata-common.h"
23 #include "pedigree/kernel/Log.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 #ifdef CRIPPLE_HDD
35 #pragma GCC diagnostic ignored "-Wunreachable-code"
36 #endif
37 
38 // #define ATA_DEFAULT_BLOCK_SIZE 0x1000
39 #define ATA_DEFAULT_BLOCK_SIZE 0x10000 * 2
40 
41 // Note the IrqReceived mutex is deliberately started in the locked state.
42 AtaDisk::AtaDisk(
43  AtaController *pDev, bool isMaster, IoBase *commandRegs,
44  IoBase *controlRegs, BusMasterIde *busMaster)
45  : ScsiDisk(), m_IsMaster(isMaster), m_SupportsLBA28(true),
46  m_SupportsLBA48(false), m_BlockSize(ATA_DEFAULT_BLOCK_SIZE),
47  m_IrqReceived(0), m_AtaDiskType(NotPacket), m_PacketSize(0),
48  m_Removable(false), m_CommandRegs(commandRegs),
49  m_ControlRegs(controlRegs), m_BusMaster(busMaster), m_PrdTableLock(false),
50  m_PrdTable(0), m_LastPrdTableOffset(0), m_PrdTablePhys(0),
51  m_PrdTableMemRegion("ata-prdtable"), m_bDma(true)
52 {
53  m_pParent = pDev;
54 }
55 
56 AtaDisk::~AtaDisk()
57 {
58 }
59 
60 bool AtaDisk::initialise(size_t nUnit)
61 {
62  // Grab our parent.
63  AtaController *pParent = static_cast<AtaController *>(m_pParent);
64 
65  // Grab our parent's IoPorts for command and control accesses.
66  IoBase *commandRegs = m_CommandRegs;
67  IoBase *controlRegs = m_ControlRegs;
68 
69  // Drive spin-up (go from standby to active, if necessary)
70  setFeatures(0x07, 0, 0, 0, 0);
71 
72  // Check for device presence
73  uint8_t devSelect = (m_IsMaster) ? 0xA0 : 0xB0;
74  commandRegs->write8(devSelect, 6);
75  commandRegs->write8(0xEC, 7);
76  if (commandRegs->read8(7) == 0)
77  {
78  NOTICE("ATA: No device present here");
79  return false;
80  }
81 
82  // Select the device to transmit to
83  devSelect = (m_IsMaster) ? 0xA0 : 0xB0;
84  commandRegs->write8(devSelect, 6);
85 
86  // Wait for it to be selected
87  ataWait(commandRegs, controlRegs);
88 
89  // DEVICE RESET
90  commandRegs->write8(8, 7);
91 
92  // Wait for the drive to reset before requesting a device change
93  ataWait(commandRegs, controlRegs);
94 
95  //
96  // Start IDENTIFY command.
97  //
98 
99  AtaStatus status;
100 
101  // Disable IRQs on this device for now.
102  controlRegs->write8(0x2, 2);
103 
104  // Send IDENTIFY.
105  commandRegs->read8(7);
106  commandRegs->write8(0xEC, 7);
107 
108  // Read status register.
109  status = ataWait(commandRegs, controlRegs);
110 
111  // Check that the device actually exists
112  if (status.__reg_contents == 0)
113  return false;
114 
115  // Check for an ATAPI device
116  uint8_t m1 = commandRegs->read8(2);
117  uint8_t m2 = commandRegs->read8(3);
118  uint8_t m3 = commandRegs->read8(4);
119  uint8_t m4 = commandRegs->read8(5);
120  // #ifdef DEBUG
121  NOTICE("ATA signature: " << m1 << ", " << m2 << ", " << m3 << ", " << m4);
122  // #endif
123  m_AtaDiskType = None;
124  if (m3 == 0x14 && m4 == 0xeb)
125  {
126  // Run IDENTIFY PACKET DEVICE instead
127  commandRegs->write8(devSelect, 6);
128  commandRegs->write8(0xA1, 7);
129  status = ataWait(commandRegs, controlRegs);
130  }
131  else
132  {
133  m_AtaDiskType = NotPacket;
134  }
135 
136  // After checking signature and potentially retrying with IDENTIFY PACKET
137  // DEVICE, we can check for an error proper now.
138  if (status.reg.err)
139  {
140  WARNING("ATA drive errored on IDENTIFY!");
141  return false;
142  }
143 
144  // Read the data.
145  for (int i = 0; i < 256; i++)
146  {
147  m_pIdent.__raw[i] = commandRegs->read16(0);
148  }
149 
150  // Check for late error - final sanity check.
151  if (commandRegs->read8(7) & 1)
152  {
153  WARNING(
154  "ATA drive now has an error status after reading IDENTIFY data.");
155  return false;
156  }
157 
158  // Do we have integrity data?
159  if (m_pIdent.data.signature == 0xA5)
160  {
161  // Yes. Run a checksum.
162  uint8_t sum = 0;
163  uint8_t *bytes = reinterpret_cast<uint8_t *>(m_pIdent.__raw);
164  for (size_t i = 0; i < 512; ++i)
165  sum += bytes[i];
166 
167  // The result should be zero if the checksum is in fact correct.
168  if (sum)
169  {
170  WARNING("ATA IDENTIFY data failed checksum!");
171  return false;
172  }
173  }
174 
175  // Interpret the data.
176 
177  // Good device?
178  if ((m_AtaDiskType == NotPacket) && m_pIdent.data.general_config.not_ata)
179  {
180  ERROR("ATA: Device does not conform to the ATA specification.");
181  return false;
182  }
183  else if (
184  (m_AtaDiskType != NotPacket) && (!m_pIdent.data.general_config.not_ata))
185  {
186  ERROR("ATA: PACKET device does not conform to the ATA specification.");
187  return false;
188  }
189 
190  if (m_AtaDiskType != NotPacket)
191  {
192  m_AtaDiskType = static_cast<AtaDiskType>(
193  m_pIdent.data.general_config.packet_cmdset);
194  }
195 
196  // Get the device name.
197  ataLoadSwapped(m_pName, m_pIdent.data.model_number, 20);
198 
199  // The device name is padded by spaces. Backtrack through converting spaces
200  // into NULL bytes.
201  for (int i = 39; i > 0; i--)
202  {
203  if (m_pName[i] != ' ')
204  break;
205  m_pName[i] = '\0';
206  }
207  m_pName[40] = '\0';
208 
209  // Get the serial number.
210  ataLoadSwapped(m_pSerialNumber, m_pIdent.data.serial_number, 10);
211 
212  // The serial number is padded by spaces. Backtrack through converting
213  // spaces into NULL bytes.
214  for (int i = 19; i > 0; i--)
215  {
216  if (m_pSerialNumber[i] != ' ')
217  break;
218  m_pSerialNumber[i] = '\0';
219  }
220  m_pSerialNumber[20] = '\0';
221 
222  // Get the firmware revision.
223  ataLoadSwapped(m_pFirmwareRevision, m_pIdent.data.firmware_revision, 4);
224 
225  // The device name is padded by spaces. Backtrack through converting spaces
226  // into NULL bytes.
227  for (int i = 7; i > 0; i--)
228  {
229  if (m_pFirmwareRevision[i] != ' ')
230  break;
231  m_pFirmwareRevision[i] = '\0';
232  }
233  m_pFirmwareRevision[8] = '\0';
234 
235  // Check that LBA48 is actually enabled.
236  if (m_pIdent.data.command_sets_support.address48)
237  {
238  m_SupportsLBA48 = m_pIdent.data.command_sets_enabled.address48;
239  if (!m_SupportsLBA48)
240  WARNING("ATA: Device supports LBA48 but it isn't enabled.");
241  }
242 
243  // And check for LBA28 support, just in case.
244  if (!m_pIdent.data.caps.lba)
245  {
247  ERROR("ATA: Device does not support LBA.");
248  return false;
249  }
250 
251  // Do we have DMA?
252  m_bDma = false;
253  if (m_pIdent.data.caps.dma)
254  {
255  m_bDma = true;
256  NOTICE("ATA: Device supports DMA.");
257 
258  if (m_pIdent.data.validity.multiword_dma_valid)
259  {
260  size_t highest_mode = ~0U;
261  if (m_pIdent.data.multiword_dma.mode0)
262  highest_mode = 0;
263  if (m_pIdent.data.multiword_dma.mode1)
264  highest_mode = 1;
265  if (m_pIdent.data.multiword_dma.mode2)
266  highest_mode = 2;
267 
268  size_t sel_mode = ~0U;
269  if (m_pIdent.data.multiword_dma.sel_mode0)
270  sel_mode = 0;
271  if (m_pIdent.data.multiword_dma.sel_mode1)
272  sel_mode = 1;
273  if (m_pIdent.data.multiword_dma.sel_mode2)
274  sel_mode = 2;
275 
276  if (highest_mode != ~0U)
277  {
278  NOTICE(
279  "ATA: Device Multiword DMA: supports up to mode"
280  << Dec << highest_mode << Hex);
281  }
282  else
283  {
284  NOTICE("ATA: Device Multiword DMA: no support");
285  }
286 
287  if (sel_mode != ~0U)
288  {
289  NOTICE(
290  "ATA: Device Multiword DMA: mode" << Dec << sel_mode << Hex
291  << " is selected");
292  }
293  }
294 
295  if (m_pIdent.data.validity.ultra_dma_valid)
296  {
297  size_t highest_mode = ~0U;
298  if (m_pIdent.data.ultra_dma.supp_mode0)
299  highest_mode = 0;
300  if (m_pIdent.data.ultra_dma.supp_mode1)
301  highest_mode = 1;
302  if (m_pIdent.data.ultra_dma.supp_mode2)
303  highest_mode = 2;
304  if (m_pIdent.data.ultra_dma.supp_mode3)
305  highest_mode = 3;
306  if (m_pIdent.data.ultra_dma.supp_mode4)
307  highest_mode = 4;
308  if (m_pIdent.data.ultra_dma.supp_mode5)
309  highest_mode = 5;
310  if (m_pIdent.data.ultra_dma.supp_mode6)
311  highest_mode = 6;
312 
313  size_t sel_mode = ~0U;
314  if (m_pIdent.data.ultra_dma.sel_mode0)
315  sel_mode = 0;
316  if (m_pIdent.data.ultra_dma.sel_mode1)
317  sel_mode = 1;
318  if (m_pIdent.data.ultra_dma.sel_mode2)
319  sel_mode = 2;
320  if (m_pIdent.data.ultra_dma.sel_mode3)
321  sel_mode = 3;
322  if (m_pIdent.data.ultra_dma.sel_mode4)
323  sel_mode = 4;
324  if (m_pIdent.data.ultra_dma.sel_mode5)
325  sel_mode = 5;
326  if (m_pIdent.data.ultra_dma.sel_mode6)
327  sel_mode = 6;
328 
329  if (highest_mode != ~0U)
330  {
331  NOTICE(
332  "ATA: Device Ultra DMA: supports up to mode"
333  << Dec << highest_mode << Hex);
334  }
335  else
336  {
337  NOTICE("ATA: Device Ultra DMA: no support");
338  }
339 
340  if (sel_mode != ~0U)
341  {
342  NOTICE(
343  "ATA: Device Ultra DMA: mode" << Dec << sel_mode << Hex
344  << " is enabled");
345  }
346  }
347  }
348 
349  // Do we have a bus master with which to work with?
350  // ISA ATA does not.
351  if (!m_BusMaster)
352  {
353  WARNING("ATA: Controller does not support DMA");
354  m_bDma = false;
355  }
356 
357  if (m_pIdent.data.sector_size.logical_larger_than_512b ||
358  m_pIdent.data.sector_size.multiple_logical_per_physical)
359  {
360  // Large physical sectors.
361  size_t logical_size = 512;
362  if (m_pIdent.data.sector_size.logical_larger_than_512b)
363  logical_size = m_pIdent.data.words_per_logical * sizeof(uint16_t);
364 
365  // Logical sectors per physical sector.
366  size_t log_per_phys = 1
367  << m_pIdent.data.sector_size.logical_per_physical;
368  size_t physical_size = log_per_phys * logical_size;
369 
370  NOTICE(
371  "ATA: Physical sector size is " << Dec << physical_size << Hex
372  << " bytes.");
373  NOTICE(
374  "ATA: Logical sector size is " << Dec << logical_size << Hex
375  << " bytes.");
376 
377  if (physical_size > 512)
378  {
379  // Non-standard physical sectors; align block size to this.
380  if (m_BlockSize % physical_size)
381  {
382  // Default block size doesn't map to physical sectors well.
383  WARNING("ATA: Default block size doesn't map well to physical "
384  "sectors, performance may be degraded.");
385  }
386 
387  // Always make sure our blocks are bigger than physical sectors.
388  if (m_BlockSize < physical_size)
389  m_BlockSize = physical_size;
390  }
391  else
392  {
393  // Standard physical sectors - default block size is okay.
394  }
395  }
396 
397  NOTICE("ATA: IRQ is #" << Dec << getInterruptNumber() << Hex << ".");
398 
399  // ATAPI pieces.
400  if (m_AtaDiskType != NotPacket)
401  {
402  // Packet size?
403  m_PacketSize = m_pIdent.data.general_config.packet_sz ? 16 : 12;
404  NOTICE(
405  "ATAPI: packet size is " << Dec << m_PacketSize << " bytes" << Hex);
406 
407  commandRegs->write8(devSelect, 6);
408  commandRegs->write8(0xDA, 7); // GET MEDIA STATUS
409  status = ataWait(commandRegs, controlRegs);
410  if (status.reg.err)
411  {
412  // We have information in the error register
413  uint8_t err = commandRegs->read8(1);
414 
415  // ABORT?
416  if (err & 0x4)
417  {
418  WARNING("ATAPI: device does not support GET MEDIA STATUS.");
419  }
420  else if (err & 2)
421  {
422  WARNING("ATAPI: No media present in the drive - aborting.");
423  WARNING(" TODO: handle media changes/insertions/removal "
424  "properly");
425  return false;
426  }
427  else
428  {
429  NOTICE("ATAPI: Media status: " << err << ".");
430  }
431  }
432 
433  // Initialise SCSI disk interface.
434  if (!ScsiDisk::initialise(pParent, nUnit))
435  {
436  ERROR("ATAPI: ScsiDisk init failed.");
437  return false;
438  }
439 
440  // Grab Inquiry data to figure out what we're working with.
441  const ScsiDisk::Inquiry *pInquiry = getInquiry();
442  m_Removable = ((pInquiry->Removable & (1 << 7)) != 0);
443  AtaDiskType inquiryType =
444  static_cast<AtaDiskType>(pInquiry->Peripheral);
445  if (inquiryType != m_AtaDiskType)
446  {
447  ERROR("ATAPI: IDENTIY PACKET DEVICE and SCSI INQUIRY disagree on "
448  "device type.");
449  return false;
450  }
451 
452  // Supported device?
453  if (m_AtaDiskType != CdDvd && m_AtaDiskType != Block)
454  {
457  WARNING("Pedigree currently only supports CD/DVD and block ATAPI "
458  "devices.");
459  return false;
460  }
461  }
462 
463  NOTICE(
464  "Detected ATA device '" << m_pName << "', '" << m_pSerialNumber
465  << "', '" << m_pFirmwareRevision << "'");
466 
467  return true;
468 }
469 
471  size_t nUnit, uintptr_t pCommand, uint8_t nCommandSize,
472  uintptr_t pRespBuffer, uint16_t nRespBytes, bool bWrite)
473 {
474  if (m_AtaDiskType == NotPacket)
475  {
476  ERROR("AtaDisk::sendCommand called on a non-PACKET device");
477  return false;
478  }
479 
480  if (!m_PacketSize)
481  {
482  ERROR("sendCommand called but the packet size is not known!");
483  return false;
484  }
485 
486  AtaStatus status;
487 
488  IoBase *commandRegs = m_CommandRegs;
489  IoBase *controlRegs = m_ControlRegs;
490 
491  uint16_t *tmpPacket = new uint16_t[m_PacketSize / 2];
492  PointerGuard<uint16_t> tmpGuard(tmpPacket, true);
493  MemoryCopy(tmpPacket, reinterpret_cast<void *>(pCommand), nCommandSize);
494  ByteSet(tmpPacket + (nCommandSize / 2), 0, m_PacketSize - nCommandSize);
495 
496  // Set nIEN as we poll in sendCommand().
497  controlRegs->write8(2, 2);
498 
499  // Wait for the device to finish any outstanding operations
500  ataWait(commandRegs, controlRegs);
501 
502  // Select the device to transmit to
503  uint8_t devSelect = m_IsMaster ? 0xA0 : 0xB0;
504  commandRegs->write8(devSelect, 6);
505  ataWait(commandRegs, controlRegs);
506 
507  // Verify that it's the correct device
508  if ((commandRegs->read8(6) & devSelect) != devSelect)
509  {
510  WARNING("ATAPI: Device was not selected");
511  return false;
512  }
513 
514  bool bDmaSetup = false;
515  if (m_bDma && nRespBytes)
516  {
517  bDmaSetup = m_BusMaster->add(pRespBuffer, nRespBytes);
518  }
519 
520  // PACKET command
521  if ((m_pIdent.__raw[62] & (1 << 15)) &&
522  bDmaSetup) // Device requires DMADIR for Packet DMA commands
523  commandRegs->write8((bWrite ? 1 : 5), 1); // Transfer to host, DMA
524  else if (bDmaSetup)
525  commandRegs->write8(1, 1); // No overlap, DMA
526  else
527  commandRegs->write8(0, 1); // No overlap, no DMA
528  commandRegs->write8(0, 2); // Tag = 0
529  commandRegs->write8(0, 3); // N/A for PACKET command
530  commandRegs->write8(nRespBytes & 0xFF, 4); // Byte count limit
531  commandRegs->write8(((nRespBytes >> 8) & 0xFF), 5);
532 
533  // Transmit the PACKET command, wait for the device to be ready for the
534  // command.
535  commandRegs->write8(0xA0, 7);
536 
537  // Wait for sensible status before writing command packet.
538  status = ataWait(commandRegs, controlRegs);
539 
540  // Error?
541  if (status.reg.err)
542  {
543  ERROR(
544  "ATAPI Packet command error [status=" << status.__reg_contents
545  << "]!");
546  return false;
547  }
548 
549  // If DMA is set up, begin that now, before sending the SCSI command.
550  if (m_bDma && nRespBytes && bDmaSetup)
551  {
552  bDmaSetup = m_BusMaster->begin(bWrite);
553  }
554 
555  // Transmit the command (padded as needed)
556  for (size_t i = 0; i < (m_PacketSize / 2); i++)
557  {
558  commandRegs->write16(tmpPacket[i], 0);
559  }
560 
561  // 400ns wait before reading status register.
562  for (size_t i = 0; i < 4; ++i)
563  controlRegs->read8(2);
564 
565  // Check for errors...
566  // Note: not using ataWait as we don't want to block here.
567  uint8_t statusreg = commandRegs->read8(7);
568  if ((statusreg & 1) && !(statusreg & 0x80))
569  {
570  // CHK = 1, BSY = 0
571  uint8_t error = commandRegs->read8(1);
572  if (error & 0x4)
573  {
574  WARNING("ATAPI command failed (ABORT)");
575  }
576  else
577  {
578  WARNING(
579  "ATAPI error with status " << statusreg << " [error=" << error
580  << "]");
581  }
582 
583  return false;
584  }
585 
586  // If we aren't expecting anything from the device, we can just poll for
587  // completion instead of waiting for an IRQ.
588  if (!nRespBytes)
589  {
590  status = ataWait(commandRegs, controlRegs);
591  return !status.reg.err;
592  }
593 
594  while (true)
595  {
596  // Ensure we are not busy before continuing handling.
597  status = ataWait(commandRegs, controlRegs);
598  if (status.reg.err)
599  {
601  if (m_bDma && bDmaSetup)
602  {
603  m_BusMaster->commandComplete();
604  WARNING("ATAPI: read failed during DMA data transfer");
605  }
606  return false;
607  }
608 
609  // Poll for completion.
610  if (m_bDma && bDmaSetup)
611  {
612  if (m_BusMaster->hasInterrupt() || m_BusMaster->hasCompleted())
613  {
614  // commandComplete effectively resets the device state, so we
615  // need to get the error register first.
616  bool bError = m_BusMaster->hasError();
617  m_BusMaster->commandComplete();
618  if (bError)
619  return false;
620  else
621  break;
622  }
623  }
624  else
625  {
626  break;
627  }
628  }
629 
630  status = ataWait(commandRegs, controlRegs);
631  if (status.reg.err)
632  {
633  WARNING("ATAPI sendCommand failed after sending command packet");
634  logAtaStatus(status);
635  return false;
636  }
637 
638  // Check for DRQ, if not set, there's nothing to read
639  if (!status.reg.drq)
640  return true;
641 
642  // Read in the data, if we need to
643  if (!m_bDma && !bDmaSetup)
644  {
645  size_t realSz = commandRegs->read8(4) | (commandRegs->read8(5) << 8);
646  uint16_t *dest = reinterpret_cast<uint16_t *>(pRespBuffer);
647  if (nRespBytes)
648  {
649  size_t sizeToRead =
650  ((realSz > nRespBytes) ? nRespBytes : realSz) / 2;
651  for (size_t i = 0; i < sizeToRead; i++)
652  {
653  if (bWrite)
654  commandRegs->write16(dest[i], 0);
655  else
656  dest[i] = commandRegs->read16(0);
657  }
658  }
659 
660  // Discard unread data (or write pretend data)
661  if (realSz > nRespBytes)
662  {
663  NOTICE(
664  "sendCommand has to read beyond provided buffer ["
665  << realSz << " is bigger than " << nRespBytes << "]");
666  for (size_t i = nRespBytes; i < realSz; i += 2)
667  {
668  if (bWrite)
669  commandRegs->write16(0xFFFF, 0);
670  else
671  commandRegs->read16(0);
672  }
673  }
674  }
675 
676  // Complete
677  uint8_t endStatus = commandRegs->read8(7);
678  return (!(endStatus & 0x01));
679 }
680 
681 uint64_t AtaDisk::doRead(uint64_t location)
682 {
683  if (m_AtaDiskType != NotPacket)
684  return ScsiDisk::doRead(location);
685 
686  // Memory for the "already-read" buffers to point at for DMA scatter/gather
687  static char alreadyRead[4096] ALIGN(4096);
688 
689  // Create our set of buffers to read into.
690  size_t nBytes = getBlockSize();
691  location &= ~(nBytes - 1); // Align location to block size.
692 
693  // Allocate list of buffers, allowing us to handle cache pages being widely
694  // distributed around the virtual address space.
695  size_t nBuffers = nBytes / 0x1000;
696  Buffer *buffers = new Buffer[nBuffers];
697  PointerGuard<Buffer> guard2(buffers, true);
698 
699  bool bAlreadyAllRead = true;
700  for (size_t i = 0; i < nBuffers; ++i)
701  {
702  buffers[i].offset = i * 0x1000;
703 
704  uintptr_t buffer = getCache().lookup(location + buffers[i].offset);
705  if (buffer)
706  {
707  getCache().release(location + buffers[i].offset);
708  buffer = reinterpret_cast<uintptr_t>(alreadyRead);
709  }
710  else
711  {
712  buffer = getCache().insert(location + buffers[i].offset);
713  if (!buffer)
714  FATAL("AtaDisk::doRead - couldn't get a buffer!");
715 
716  bAlreadyAllRead = false;
717  }
718 
719  buffers[i].buffer = buffer;
720  }
721 
722  if (bAlreadyAllRead)
723  {
724  // All pages were already in cache.
725  return nBytes;
726  }
727 
728  // Grab our parent's IoPorts for command and control accesses.
729  IoBase *commandRegs = m_CommandRegs;
730 #ifndef PPC_COMMON
731  IoBase *controlRegs = m_ControlRegs;
732 #endif
733 
734  // How many sectors do we need to read?
736  uint32_t nSectors = nBytes / 512;
737 
738  // Wait for BSY and DRQ to be zero before selecting the device
739  AtaStatus status;
740  ataWait(commandRegs, controlRegs);
741 
742  // Select the device to transmit to
743  uint8_t devSelect;
744  if (m_SupportsLBA48)
745  devSelect = (m_IsMaster) ? 0xE0 : 0xF0;
746  else
747  devSelect = (m_IsMaster) ? 0xA0 : 0xB0;
748  commandRegs->write8(devSelect, 6);
749 
750  // Wait for it to be selected
751  ataWait(commandRegs, controlRegs);
752 
753  size_t buffersConsumed = 0;
754  while (nSectors > 0)
755  {
756  // Wait for status to be ready - spin until READY bit is set.
757  while (!(commandRegs->read8(7) & 0x40))
758  ;
759 
760  // Send out sector count.
761  uint8_t nSectorsToRead =
762  min(m_pIdent.data.max_sectors_per_irq, nSectors);
763  nSectors -= nSectorsToRead;
764 
765  // Buffers are 4K each, so calculate the number of buffers used for
766  // this particular read.
767  size_t buffersThisRead = (nSectorsToRead * 512) / 0x1000;
768 
769  bool bDmaSetup = false;
770  if (m_bDma)
771  {
772  for (size_t i = 0; i < buffersThisRead; ++i)
773  {
774  bDmaSetup = m_BusMaster->add(
775  buffers[buffersConsumed + i].buffer, 0x1000);
776  if (!bDmaSetup)
777  {
778  ERROR("DMA setup failed!");
779  break;
780  }
781  }
782 
783  buffersConsumed += buffersThisRead;
784  }
785 
786  if (m_SupportsLBA48)
787  setupLBA48(location, nSectorsToRead);
788  else
789  {
790  if (location >= 0x2000000000ULL)
791  {
792  WARNING("Ata: Sector > 128GB requested but LBA48 addressing "
793  "not supported!");
794  }
795  setupLBA28(location, nSectorsToRead);
796  }
797 
798  m_IrqReceived = new Mutex(true);
799  PointerGuard<Mutex> irqGuard(&m_IrqReceived);
800 
801  if (getInterruptNumber() != 0xFF)
802  {
803 // Enable IRQs so we can avoid spinning if possible.
804 #ifndef PPC_COMMON
805  controlRegs->write8(0, 2);
806 #endif
807 
808  bool oldInterrupts = Processor::getInterrupts();
809  if (!oldInterrupts)
811  }
812 
813  if (m_bDma && bDmaSetup)
814  {
815  // Prepare DMA before we send the command.
816  bDmaSetup = m_BusMaster->begin(false);
817 
818  if (!m_SupportsLBA48)
819  {
820  // Send command "read DMA"
821  commandRegs->write8(0xC8, 7);
822  }
823  else
824  {
825  // Send command "read DMA EXT"
826  commandRegs->write8(0x25, 7);
827  }
828  }
829  else
830  {
831  if (m_SupportsLBA48)
832  {
833  // Send command "read sectors EXT"
834  commandRegs->write8(0x24, 7);
835  }
836  else
837  {
838  // Send command "read sectors with retry"
839  commandRegs->write8(0x20, 7);
840  }
841  }
842 
843  // Acquire the 'outstanding IRQ' mutex, or use other means if no IRQ.
844  while (true)
845  {
846  if (getInterruptNumber() != 0xFF)
847  {
848  if (!m_IrqReceived->acquire(1, 10))
849  {
850  // Timeout.
851  ERROR("ATA: timeout during data transfer");
852  return 0;
853  }
854  }
855 
856  // Ensure we are not busy before continuing handling.
857  status = ataWait(commandRegs, controlRegs);
858  if (status.reg.err)
859  {
861  if (m_bDma && bDmaSetup)
862  {
863  m_BusMaster->commandComplete();
864  WARNING("ATA: read failed during DMA data transfer");
865  }
866  return false;
867  }
868 
869  if (m_bDma && bDmaSetup)
870  {
871  if (m_BusMaster->hasInterrupt() || m_BusMaster->hasCompleted())
872  {
873  // commandComplete effectively resets the device state, so
874  // we need to get the error register first.
875  bool bError = m_BusMaster->hasError();
876  m_BusMaster->commandComplete();
877  if (bError)
878  {
879  return 0;
880  }
881  else
882  {
883  break;
884  }
885  }
886  }
887  else
888  {
889  break;
890  }
891  }
892 
893  if (!m_bDma && !bDmaSetup)
894  {
895  size_t byteOffset = buffersConsumed * 0x1000;
896  for (int i = 0; i < nSectorsToRead; i++)
897  {
898  // Wait until !BUSY
899  status = ataWait(commandRegs, controlRegs);
900  if (status.reg.err)
901  {
902  // Ka-boom! Something went wrong :(
904  WARNING("ATA: read failed during data transfer");
905  return 0;
906  }
907 
908  // Figure out which buffer we care about here.
909  size_t nBuffer = byteOffset / 0x1000;
910  size_t offset = byteOffset % 0x1000;
911 
912  // Read the sector.
913  uint16_t *target = reinterpret_cast<uint16_t *>(
914  buffers[nBuffer].buffer + offset);
915  for (int j = 0; j < 256; j++)
916  {
917  *target++ = commandRegs->read16(0);
918  }
919 
920  byteOffset += 512;
921  }
922  }
923 
924  location += nSectorsToRead * 512;
925  }
926 
927  assert(buffersConsumed == nBuffers);
928 
929  // Update Cache - we're done reading.
930  for (size_t i = 0; i < nBuffers; ++i)
931  {
932  if (buffers[i].buffer == reinterpret_cast<uintptr_t>(alreadyRead))
933  {
934  continue;
935  }
936 
937  getCache().markNoLongerEditing(location + buffers[i].offset);
938  }
939 
940  return nBytes;
941 }
942 
943 uint64_t AtaDisk::doWrite(uint64_t location)
944 {
945  if (location % 512)
946  panic("AtaDisk: write request not on a sector boundary!");
947 
948 // Safety check
949 #ifdef CRIPPLE_HDD
950  return 0;
951 #endif
952 
953  if (m_AtaDiskType != NotPacket)
954  {
956  return 0;
957  }
958 
959  // Write only the affected page. This deviates from the behaviour of reads,
960  // which read a very large amount of data at once. Most writes (flush()
961  // aside) are done asynchronously, while reads are synchronous.
962  // This means we don't need to care about evicted pages within a disk block
963  // because we're writing only a specific page that we already know exists.
964  uintptr_t nBytes = 0x1000;
965  uintptr_t buffer = getCache().lookup(location);
966  if (!buffer)
967  {
968  FATAL("AtaDisk::doWrite - no buffer (completely misused method)");
969  }
970 
971  // Undo the pin done by ScsiDisk::write that verified this location exists
972  // in the first place. We have two active pins here: that from the above
973  // lookup(), and the one from ScsiDisk::write. This just ensures we're
974  // keeping the counts correct.
975  getCache().release(location);
976 
977  // Make sure we don't leave the refcnt increased by writing.
978  CachePageGuard guard(getCache(), location);
979 
980 #ifdef SUPERDEBUG
981  NOTICE("doWrite(" << location << ")");
982 #endif
983 
984  // Grab our parent's IoPorts for command and control accesses.
985  IoBase *commandRegs = m_CommandRegs;
986 #ifndef PPC_COMMON
987  IoBase *controlRegs = m_ControlRegs;
988 #endif
989 
990  // How many sectors do we need to read?
992  uint32_t nSectors = nBytes / 512;
993  if (nBytes % 512)
994  nSectors++;
995 
996  // Wait for BSY and DRQ to be zero before selecting the device
997  AtaStatus status;
998  ataWait(commandRegs, controlRegs);
999 
1000  // Select the device to transmit to
1001  uint8_t devSelect;
1002  if (m_SupportsLBA48)
1003  devSelect = (m_IsMaster) ? 0xE0 : 0xF0;
1004  else
1005  devSelect = (m_IsMaster) ? 0xA0 : 0xB0;
1006  commandRegs->write8(devSelect, 6);
1007 
1008  // Wait for it to be selected
1009  ataWait(commandRegs, controlRegs);
1010 
1011  uint16_t *tmp = reinterpret_cast<uint16_t *>(buffer);
1012 
1013  while (nSectors > 0)
1014  {
1015  // Wait for status to be ready - spin until READY bit is set.
1016  while (!(commandRegs->read8(7) & 0x40))
1017  ;
1018 
1019  // Send out sector count.
1020  uint8_t nSectorsToWrite =
1021  min(m_pIdent.data.max_sectors_per_irq, nSectors);
1022  nSectors -= nSectorsToWrite;
1023 
1024  bool bDmaSetup = false;
1025  if (m_bDma)
1026  {
1027  bDmaSetup = m_BusMaster->add(buffer, nSectorsToWrite * 512);
1028  }
1029 
1030  if (m_SupportsLBA48)
1031  setupLBA48(location, nSectorsToWrite);
1032  else
1033  {
1034  if (location >= 0x2000000000ULL)
1035  {
1036  WARNING("Ata: Sector > 128GB requested but LBA48 addressing "
1037  "not supported!");
1038  }
1039  setupLBA28(location, nSectorsToWrite);
1040  }
1041 
1042 // Enable IRQs so we can avoid spinning if possible.
1043 #ifndef PPC_COMMON
1044  controlRegs->write8(0, 2);
1045 #endif
1046 
1047  if (m_IrqReceived)
1048  WARNING("ATA: IRQ mutex already existed");
1049  m_IrqReceived = new Mutex(true);
1050  PointerGuard<Mutex> guardReceivedMutex(&m_IrqReceived);
1051 
1052  bool oldInterrupts = Processor::getInterrupts();
1053  if (!oldInterrupts)
1055 
1056  if (m_bDma && bDmaSetup)
1057  {
1058  // Start DMA before we send the command.
1059  bDmaSetup = m_BusMaster->begin(true);
1060 
1061  if (!m_SupportsLBA48)
1062  {
1063  // Send command "write DMA"
1064  commandRegs->write8(0xCA, 7);
1065  }
1066  else
1067  {
1068  // Send command "read write EXT"
1069  commandRegs->write8(0x35, 7);
1070  }
1071  }
1072  else
1073  {
1074  if (m_SupportsLBA48)
1075  {
1076  // Send command "write sectors EXT"
1077  commandRegs->write8(0x34, 7);
1078  }
1079  else
1080  {
1081  // Send command "write sectors with retry"
1082  commandRegs->write8(0x30, 7);
1083  }
1084  }
1085 
1086  // Wait for completion.
1087  while (true)
1088  {
1089  if (getInterruptNumber() != 0xFF)
1090  {
1091  // 10 second timeout.
1092  if (!m_IrqReceived->acquire(1, 10))
1093  {
1094  WARNING("ATA: failed to get IRQ");
1095  }
1096  }
1097 
1098  // Ensure we are not busy before continuing handling.
1099  status = ataWait(commandRegs, controlRegs);
1100  if (status.reg.err)
1101  {
1103  if (m_bDma && bDmaSetup)
1104  {
1105  m_BusMaster->commandComplete();
1106  WARNING("ATA: read failed during DMA data transfer");
1107  }
1108  return false;
1109  }
1110 
1111  if (m_bDma && bDmaSetup)
1112  {
1113  if (m_BusMaster->hasInterrupt() || m_BusMaster->hasCompleted())
1114  {
1115  // commandComplete effectively resets the device state, so
1116  // we need to get the error register first.
1117  bool bError = m_BusMaster->hasError();
1118  m_BusMaster->commandComplete();
1119  if (bError)
1120  return 0;
1121  else
1122  break;
1123  }
1124  }
1125  else
1126  break;
1127  }
1128 
1129  if (!m_bDma && !bDmaSetup)
1130  {
1131  for (int i = 0; i < nSectorsToWrite; i++)
1132  {
1133  // Wait until !BUSY
1134  status = ataWait(commandRegs, controlRegs);
1135  if (status.reg.err)
1136  {
1137  // Ka-boom! Something went wrong :(
1139  WARNING("ATA: write failed during data transfer");
1140  return 0;
1141  }
1142 
1143  // Write the sector to disk.
1144  for (int j = 0; j < 256; j++)
1145  commandRegs->write16(*tmp++, 0);
1146  }
1147  }
1148  }
1149 
1150 #ifdef SUPERDEBUG
1151  NOTICE("ATA: successfully wrote " << nBytes << " bytes to disk.");
1152 #endif
1153  return nBytes;
1154 }
1155 
1157 {
1158  if (m_IrqReceived)
1159  m_IrqReceived->release();
1160 }
1161 
1162 void AtaDisk::setupLBA28(uint64_t n, uint32_t nSectors)
1163 {
1164  IoBase *commandRegs = m_CommandRegs;
1165 
1166  commandRegs->write8(static_cast<uint8_t>(nSectors & 0xFF), 2);
1167 
1168  // Get the sector number of the address.
1169  n /= 512;
1170 
1171  uint8_t sector = static_cast<uint8_t>(n & 0xFF);
1172  uint8_t cLow = static_cast<uint8_t>((n >> 8) & 0xFF);
1173  uint8_t cHigh = static_cast<uint8_t>((n >> 16) & 0xFF);
1174  uint8_t head = static_cast<uint8_t>((n >> 24) & 0x0F);
1175  if (m_IsMaster)
1176  head |= 0xE0;
1177  else
1178  head |= 0xF0;
1179 
1180  commandRegs->write8(head, 6);
1181  commandRegs->write8(sector, 3);
1182  commandRegs->write8(cLow, 4);
1183  commandRegs->write8(cHigh, 5);
1184 }
1185 
1186 void AtaDisk::setupLBA48(uint64_t n, uint32_t nSectors)
1187 {
1188  IoBase *commandRegs = m_CommandRegs;
1189 
1190  // Get the sector number of the address.
1191  n /= 512;
1192 
1193  uint8_t lba1 = static_cast<uint8_t>(n & 0xFF);
1194  uint8_t lba2 = static_cast<uint8_t>((n >> 8) & 0xFF);
1195  uint8_t lba3 = static_cast<uint8_t>((n >> 16) & 0xFF);
1196  uint8_t lba4 = static_cast<uint8_t>((n >> 24) & 0xFF);
1197  uint8_t lba5 = static_cast<uint8_t>((n >> 32) & 0xFF);
1198  uint8_t lba6 = static_cast<uint8_t>((n >> 40) & 0xFF);
1199 
1200  commandRegs->write8((nSectors & 0xFFFF) >> 8, 2);
1201  commandRegs->write8(lba4, 3);
1202  commandRegs->write8(lba5, 4);
1203  commandRegs->write8(lba6, 5);
1204  commandRegs->write8((nSectors & 0xFF), 2);
1205  commandRegs->write8(lba1, 3);
1206  commandRegs->write8(lba2, 4);
1207  commandRegs->write8(lba3, 5);
1208 }
1209 
1211  uint8_t command, uint8_t countreg, uint8_t lowreg, uint8_t midreg,
1212  uint8_t hireg)
1213 {
1214  // Grab our parent's IoPorts for command and control accesses.
1215  IoBase *commandRegs = m_CommandRegs;
1216 
1217  uint8_t devSelect = (m_IsMaster) ? 0xA0 : 0xB0;
1218  commandRegs->write8(devSelect, 6);
1219 
1220  commandRegs->write8(command, 1);
1221  commandRegs->write8(countreg, 2);
1222  commandRegs->write8(lowreg, 3);
1223  commandRegs->write8(midreg, 4);
1224  commandRegs->write8(hireg, 5);
1225  commandRegs->write8(0xEF, 7);
1226 }
1227 
1228 size_t AtaDisk::getSize() const
1229 {
1230  if (m_AtaDiskType != NotPacket)
1231  {
1232  return ScsiDisk::getSize();
1233  }
1234 
1235  // Determine sector count.
1236  size_t sector_count = 0;
1237  if (m_SupportsLBA48)
1238  {
1239  // Try for the LBA48 sector count.
1240  if (m_pIdent.data.max_user_lba48)
1241  sector_count = m_pIdent.data.max_user_lba48;
1242  else
1243  sector_count = m_pIdent.data.sector_count;
1244  }
1245  else
1246  {
1247  sector_count = m_pIdent.data.sector_count;
1248  }
1249 
1250  // Determine sector size.
1251  size_t sector_size = 512;
1252  if (m_pIdent.data.sector_size.logical_larger_than_512b)
1253  {
1254  // Calculate.
1255  sector_size = m_pIdent.data.words_per_logical * sizeof(uint16_t);
1256  }
1257 
1258  return sector_count * sector_size;
1259 }
1260 
1262 {
1263  if (m_AtaDiskType != NotPacket)
1264  {
1265  return ScsiDisk::getBlockSize();
1266  }
1267  return m_BlockSize;
1268 }
1269 
1271 {
1272  if (m_AtaDiskType != NotPacket)
1273  {
1275  }
1276 
1277  // Native blocks are just sectors.
1278  size_t sector_size = 512;
1279  if (m_pIdent.data.sector_size.logical_larger_than_512b)
1280  {
1281  // Calculate.
1282  sector_size = m_pIdent.data.words_per_logical * sizeof(uint16_t);
1283  }
1284 
1285  return sector_size;
1286 }
1287 
1288 size_t AtaDisk::getBlockCount() const
1289 {
1290  if (m_AtaDiskType != NotPacket)
1291  {
1292  return ScsiDisk::getBlockCount();
1293  }
1294 
1295  // Determine sector count.
1296  size_t sector_count = 0;
1297  if (m_SupportsLBA48)
1298  {
1299  // Try for the LBA48 sector count.
1300  if (m_pIdent.data.max_user_lba48)
1301  sector_count = m_pIdent.data.max_user_lba48;
1302  else
1303  sector_count = m_pIdent.data.sector_count;
1304  }
1305  else
1306  {
1307  sector_count = m_pIdent.data.sector_count;
1308  }
1309 
1310  return sector_count;
1311 }
bool initialise(size_t nUnit=~0)
Definition: AtaDisk.cc:60
void setFeatures(uint8_t command, uint8_t countreg, uint8_t lowreg, uint8_t midreg, uint8_t hireg)
Definition: AtaDisk.cc:1210
virtual size_t getBlockSize() const
Gets the block size of the disk.
Definition: AtaDisk.cc:1261
static bool getInterrupts()
struct AtaStatus::@0 reg
virtual size_t getBlockSize() const
Gets the block size of the disk.
Definition: ScsiDisk.h:120
void setupLBA48(uint64_t n, uint32_t nSectors)
Definition: AtaDisk.cc:1186
virtual void write8(uint8_t value, size_t offset=0)=0
Device * m_pParent
Definition: Device.h:366
Definition: Mutex.h:58
virtual uint64_t doWrite(uint64_t location)
Definition: AtaDisk.cc:943
virtual uint16_t read16(size_t offset=0)=0
Abstrace base class for hardware I/O capabilities.
Definition: IoBase.h:31
virtual uintptr_t getInterruptNumber()
Definition: Device.h:262
virtual uint64_t doRead(uint64_t location)
Definition: AtaDisk.cc:681
virtual size_t getNativeBlockSize() const
Definition: ScsiDisk.h:129
virtual size_t getNativeBlockSize() const
Definition: AtaDisk.cc:1270
size_t offset
Offset into the read.
Definition: AtaDisk.h:129
virtual void write16(uint16_t value, size_t offset=0)=0
#define WARNING(text)
Definition: Log.h:78
virtual bool sendCommand(size_t nUnit, uintptr_t pCommand, uint8_t nCommandSize, uintptr_t pRespBuffer, uint16_t nRespBytes, bool bWrite)
Definition: AtaDisk.cc:470
#define NOTICE(text)
Definition: Log.h:74
uint8_t __reg_contents
"Hidden" integer which contains the actual register contents
Definition: ata-common.h:45
virtual uint64_t doRead(uint64_t location)
Definition: ScsiDisk.cc:448
Definition: Log.h:136
virtual void irqReceived()
Definition: AtaDisk.cc:1156
#define assert(x)
Definition: assert.h:37
static void setInterrupts(bool bEnable)
void setupLBA28(uint64_t n, uint32_t nSectors)
Definition: AtaDisk.cc:1162
virtual uint8_t read8(size_t offset=0)=0
bool initialise(class ScsiController *pController, size_t nUnit)
Definition: ScsiDisk.cc:78
uintptr_t buffer
Virtual address of buffer to read into (page sized).
Definition: AtaDisk.h:126
#define ERROR(text)
Definition: Log.h:82
virtual size_t getSize() const
Gets the size of the disk.
Definition: AtaDisk.cc:1228
Definition: Log.h:138
void EXPORTED_PUBLIC panic(const char *msg) NORETURN
Definition: panic.cc:121
#define FATAL(text)
Definition: Log.h:89
virtual size_t getSize() const
Gets the size of the disk.
Definition: ScsiDisk.h:110