IDEChannel.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  1. /*
  2. * Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/ByteBuffer.h>
  7. #include <AK/Singleton.h>
  8. #include <AK/StringView.h>
  9. #include <Kernel/IO.h>
  10. #include <Kernel/Process.h>
  11. #include <Kernel/Storage/ATA.h>
  12. #include <Kernel/Storage/IDEChannel.h>
  13. #include <Kernel/Storage/IDEController.h>
  14. #include <Kernel/Storage/PATADiskDevice.h>
  15. #include <Kernel/VM/MemoryManager.h>
  16. #include <Kernel/WorkQueue.h>
  17. namespace Kernel {
  18. #define PATA_PRIMARY_IRQ 14
  19. #define PATA_SECONDARY_IRQ 15
  20. #define PCI_Mass_Storage_Class 0x1
  21. #define PCI_IDE_Controller_Subclass 0x1
  22. UNMAP_AFTER_INIT NonnullRefPtr<IDEChannel> IDEChannel::create(const IDEController& controller, IOAddressGroup io_group, ChannelType type)
  23. {
  24. return adopt_ref(*new IDEChannel(controller, io_group, type));
  25. }
  26. UNMAP_AFTER_INIT NonnullRefPtr<IDEChannel> IDEChannel::create(const IDEController& controller, u8 irq, IOAddressGroup io_group, ChannelType type)
  27. {
  28. return adopt_ref(*new IDEChannel(controller, irq, io_group, type));
  29. }
  30. RefPtr<StorageDevice> IDEChannel::master_device() const
  31. {
  32. return m_master;
  33. }
  34. RefPtr<StorageDevice> IDEChannel::slave_device() const
  35. {
  36. return m_slave;
  37. }
  38. UNMAP_AFTER_INIT void IDEChannel::initialize()
  39. {
  40. disable_irq();
  41. dbgln_if(PATA_DEBUG, "IDEChannel: {} IO base: {}", channel_type_string(), m_io_group.io_base());
  42. dbgln_if(PATA_DEBUG, "IDEChannel: {} control base: {}", channel_type_string(), m_io_group.control_base());
  43. if (m_io_group.bus_master_base().has_value())
  44. dbgln_if(PATA_DEBUG, "IDEChannel: {} bus master base: {}", channel_type_string(), m_io_group.bus_master_base().value());
  45. else
  46. dbgln_if(PATA_DEBUG, "IDEChannel: {} bus master base disabled", channel_type_string());
  47. m_parent_controller->enable_pin_based_interrupts();
  48. detect_disks();
  49. // Note: calling to detect_disks could generate an interrupt, clear it if that's the case
  50. clear_pending_interrupts();
  51. }
  52. UNMAP_AFTER_INIT IDEChannel::IDEChannel(const IDEController& controller, u8 irq, IOAddressGroup io_group, ChannelType type)
  53. : IRQHandler(irq)
  54. , m_channel_type(type)
  55. , m_io_group(io_group)
  56. , m_parent_controller(controller)
  57. {
  58. initialize();
  59. }
  60. UNMAP_AFTER_INIT IDEChannel::IDEChannel(const IDEController& controller, IOAddressGroup io_group, ChannelType type)
  61. : IRQHandler(type == ChannelType::Primary ? PATA_PRIMARY_IRQ : PATA_SECONDARY_IRQ)
  62. , m_channel_type(type)
  63. , m_io_group(io_group)
  64. , m_parent_controller(controller)
  65. {
  66. initialize();
  67. }
  68. void IDEChannel::clear_pending_interrupts() const
  69. {
  70. m_io_group.io_base().offset(ATA_REG_STATUS).in<u8>();
  71. }
  72. UNMAP_AFTER_INIT IDEChannel::~IDEChannel()
  73. {
  74. }
  75. void IDEChannel::start_request(AsyncBlockDeviceRequest& request, bool is_slave, u16 capabilities)
  76. {
  77. LOCKER(m_lock);
  78. VERIFY(m_current_request.is_null());
  79. dbgln_if(PATA_DEBUG, "IDEChannel::start_request");
  80. m_current_request = request;
  81. m_current_request_block_index = 0;
  82. m_current_request_flushing_cache = false;
  83. if (request.request_type() == AsyncBlockDeviceRequest::Read)
  84. ata_read_sectors(is_slave, capabilities);
  85. else
  86. ata_write_sectors(is_slave, capabilities);
  87. }
  88. void IDEChannel::complete_current_request(AsyncDeviceRequest::RequestResult result)
  89. {
  90. // NOTE: this may be called from the interrupt handler!
  91. VERIFY(m_current_request);
  92. VERIFY(m_request_lock.is_locked());
  93. // Now schedule reading back the buffer as soon as we leave the irq handler.
  94. // This is important so that we can safely write the buffer back,
  95. // which could cause page faults. Note that this may be called immediately
  96. // before Processor::deferred_call_queue returns!
  97. g_io_work->queue([this, result]() {
  98. dbgln_if(PATA_DEBUG, "IDEChannel::complete_current_request result: {}", (int)result);
  99. LOCKER(m_lock);
  100. VERIFY(m_current_request);
  101. auto current_request = m_current_request;
  102. m_current_request.clear();
  103. current_request->complete(result);
  104. });
  105. }
  106. static void print_ide_status(u8 status)
  107. {
  108. dbgln("IDEChannel: print_ide_status: DRQ={} BSY={}, DRDY={}, DSC={}, DF={}, CORR={}, IDX={}, ERR={}",
  109. (status & ATA_SR_DRQ) != 0,
  110. (status & ATA_SR_BSY) != 0,
  111. (status & ATA_SR_DRDY) != 0,
  112. (status & ATA_SR_DSC) != 0,
  113. (status & ATA_SR_DF) != 0,
  114. (status & ATA_SR_CORR) != 0,
  115. (status & ATA_SR_IDX) != 0,
  116. (status & ATA_SR_ERR) != 0);
  117. }
  118. void IDEChannel::try_disambiguate_error()
  119. {
  120. VERIFY(m_lock.is_locked());
  121. dbgln("IDEChannel: Error cause:");
  122. switch (m_device_error) {
  123. case ATA_ER_BBK:
  124. dbgln("IDEChannel: - Bad block");
  125. break;
  126. case ATA_ER_UNC:
  127. dbgln("IDEChannel: - Uncorrectable data");
  128. break;
  129. case ATA_ER_MC:
  130. dbgln("IDEChannel: - Media changed");
  131. break;
  132. case ATA_ER_IDNF:
  133. dbgln("IDEChannel: - ID mark not found");
  134. break;
  135. case ATA_ER_MCR:
  136. dbgln("IDEChannel: - Media change request");
  137. break;
  138. case ATA_ER_ABRT:
  139. dbgln("IDEChannel: - Command aborted");
  140. break;
  141. case ATA_ER_TK0NF:
  142. dbgln("IDEChannel: - Track 0 not found");
  143. break;
  144. case ATA_ER_AMNF:
  145. dbgln("IDEChannel: - No address mark");
  146. break;
  147. default:
  148. dbgln("IDEChannel: - No one knows");
  149. break;
  150. }
  151. }
  152. void IDEChannel::handle_irq(const RegisterState&)
  153. {
  154. u8 status = m_io_group.io_base().offset(ATA_REG_STATUS).in<u8>();
  155. m_entropy_source.add_random_event(status);
  156. ScopedSpinLock lock(m_request_lock);
  157. dbgln_if(PATA_DEBUG, "IDEChannel: interrupt: DRQ={}, BSY={}, DRDY={}",
  158. (status & ATA_SR_DRQ) != 0,
  159. (status & ATA_SR_BSY) != 0,
  160. (status & ATA_SR_DRDY) != 0);
  161. if (!m_current_request) {
  162. dbgln("IDEChannel: IRQ but no pending request!");
  163. return;
  164. }
  165. if (status & ATA_SR_ERR) {
  166. print_ide_status(status);
  167. m_device_error = m_io_group.io_base().offset(ATA_REG_ERROR).in<u8>();
  168. dbgln("IDEChannel: Error {:#02x}!", (u8)m_device_error);
  169. try_disambiguate_error();
  170. complete_current_request(AsyncDeviceRequest::Failure);
  171. return;
  172. }
  173. m_device_error = 0;
  174. // Now schedule reading/writing the buffer as soon as we leave the irq handler.
  175. // This is important so that we can safely access the buffers, which could
  176. // trigger page faults
  177. g_io_work->queue([this]() {
  178. LOCKER(m_lock);
  179. ScopedSpinLock lock(m_request_lock);
  180. if (m_current_request->request_type() == AsyncBlockDeviceRequest::Read) {
  181. dbgln_if(PATA_DEBUG, "IDEChannel: Read block {}/{}", m_current_request_block_index, m_current_request->block_count());
  182. if (ata_do_read_sector()) {
  183. if (++m_current_request_block_index >= m_current_request->block_count()) {
  184. complete_current_request(AsyncDeviceRequest::Success);
  185. return;
  186. }
  187. // Wait for the next block
  188. enable_irq();
  189. }
  190. } else {
  191. if (!m_current_request_flushing_cache) {
  192. dbgln_if(PATA_DEBUG, "IDEChannel: Wrote block {}/{}", m_current_request_block_index, m_current_request->block_count());
  193. if (++m_current_request_block_index >= m_current_request->block_count()) {
  194. // We read the last block, flush cache
  195. VERIFY(!m_current_request_flushing_cache);
  196. m_current_request_flushing_cache = true;
  197. m_io_group.io_base().offset(ATA_REG_COMMAND).out<u8>(ATA_CMD_CACHE_FLUSH);
  198. } else {
  199. // Read next block
  200. ata_do_write_sector();
  201. }
  202. } else {
  203. complete_current_request(AsyncDeviceRequest::Success);
  204. }
  205. }
  206. });
  207. }
  208. static void io_delay()
  209. {
  210. for (int i = 0; i < 4; ++i)
  211. IO::in8(0x3f6);
  212. }
  213. void IDEChannel::wait_until_not_busy()
  214. {
  215. while (m_io_group.control_base().in<u8>() & ATA_SR_BSY)
  216. ;
  217. }
  218. String IDEChannel::channel_type_string() const
  219. {
  220. if (m_channel_type == ChannelType::Primary)
  221. return "Primary";
  222. return "Secondary";
  223. }
  224. UNMAP_AFTER_INIT void IDEChannel::detect_disks()
  225. {
  226. auto channel_string = [](u8 i) -> const char* {
  227. if (i == 0)
  228. return "master";
  229. return "slave";
  230. };
  231. // There are only two possible disks connected to a channel
  232. for (auto i = 0; i < 2; i++) {
  233. // We need to select the drive and then we wait 20 microseconds... and it doesn't hurt anything so let's just do it.
  234. m_io_group.io_base().offset(ATA_REG_HDDEVSEL).out<u8>(0xA0 | (i << 4)); // First, we need to select the drive itself
  235. IO::delay(20);
  236. m_io_group.io_base().offset(ATA_REG_SECCOUNT0).out<u8>(0);
  237. m_io_group.io_base().offset(ATA_REG_LBA0).out<u8>(0);
  238. m_io_group.io_base().offset(ATA_REG_LBA1).out<u8>(0);
  239. m_io_group.io_base().offset(ATA_REG_LBA2).out<u8>(0);
  240. m_io_group.io_base().offset(ATA_REG_COMMAND).out<u8>(ATA_CMD_IDENTIFY); // Send the ATA_IDENTIFY command
  241. // Wait for the BSY flag to be reset
  242. while (m_io_group.control_base().in<u8>() & ATA_SR_BSY)
  243. ;
  244. if (m_io_group.control_base().in<u8>() == 0x00) {
  245. dbgln_if(PATA_DEBUG, "IDEChannel: No {} {} disk detected!", channel_type_string().to_lowercase(), channel_string(i));
  246. continue;
  247. }
  248. bool check_for_atapi = false;
  249. PATADiskDevice::InterfaceType interface_type = PATADiskDevice::InterfaceType::ATA;
  250. for (;;) {
  251. u8 status = m_io_group.control_base().in<u8>();
  252. if (status & ATA_SR_ERR) {
  253. dbgln_if(PATA_DEBUG, "IDEChannel: {} {} device is not ATA. Will check for ATAPI.", channel_type_string(), channel_string(i));
  254. check_for_atapi = true;
  255. break;
  256. }
  257. if (!(status & ATA_SR_BSY) && (status & ATA_SR_DRQ)) {
  258. dbgln_if(PATA_DEBUG, "IDEChannel: {} {} device appears to be ATA.", channel_type_string(), channel_string(i));
  259. interface_type = PATADiskDevice::InterfaceType::ATA;
  260. break;
  261. }
  262. }
  263. if (check_for_atapi) {
  264. u8 cl = m_io_group.io_base().offset(ATA_REG_LBA1).in<u8>();
  265. u8 ch = m_io_group.io_base().offset(ATA_REG_LBA2).in<u8>();
  266. if ((cl == 0x14 && ch == 0xEB) || (cl == 0x69 && ch == 0x96)) {
  267. interface_type = PATADiskDevice::InterfaceType::ATAPI;
  268. dbgln("IDEChannel: {} {} device appears to be ATAPI. We're going to ignore it for now as we don't support it.", channel_type_string(), channel_string(i));
  269. continue;
  270. } else {
  271. dbgln("IDEChannel: {} {} device doesn't appear to be ATA or ATAPI. Ignoring it.", channel_type_string(), channel_string(i));
  272. continue;
  273. }
  274. }
  275. ByteBuffer wbuf = ByteBuffer::create_uninitialized(512);
  276. ByteBuffer bbuf = ByteBuffer::create_uninitialized(512);
  277. u8* b = bbuf.data();
  278. u16* w = (u16*)wbuf.data();
  279. for (u32 i = 0; i < 256; ++i) {
  280. u16 data = m_io_group.io_base().offset(ATA_REG_DATA).in<u16>();
  281. *(w++) = data;
  282. *(b++) = MSB(data);
  283. *(b++) = LSB(data);
  284. }
  285. // "Unpad" the device name string.
  286. for (u32 i = 93; i > 54 && bbuf[i] == ' '; --i)
  287. bbuf[i] = 0;
  288. volatile ATAIdentifyBlock& identify_block = (volatile ATAIdentifyBlock&)(*wbuf.data());
  289. u16 capabilities = identify_block.capabilities[0];
  290. // If the drive is so old that it doesn't support LBA, ignore it.
  291. if (!(capabilities & ATA_CAP_LBA))
  292. continue;
  293. u64 max_addressable_block = identify_block.max_28_bit_addressable_logical_sector;
  294. // if we support 48-bit LBA, use that value instead.
  295. if (identify_block.commands_and_feature_sets_supported[1] & (1 << 10))
  296. max_addressable_block = identify_block.user_addressable_logical_sectors_count;
  297. dbgln("IDEChannel: {} {} {} device found: Name={}, Capacity={}, Capabilities=0x{:04x}", channel_type_string(), channel_string(i), interface_type == PATADiskDevice::InterfaceType::ATA ? "ATA" : "ATAPI", ((char*)bbuf.data() + 54), max_addressable_block * 512, capabilities);
  298. if (i == 0) {
  299. m_master = PATADiskDevice::create(m_parent_controller, *this, PATADiskDevice::DriveType::Master, interface_type, capabilities, max_addressable_block);
  300. } else {
  301. m_slave = PATADiskDevice::create(m_parent_controller, *this, PATADiskDevice::DriveType::Slave, interface_type, capabilities, max_addressable_block);
  302. }
  303. }
  304. }
  305. void IDEChannel::ata_access(Direction direction, bool slave_request, u64 lba, u8 block_count, u16 capabilities)
  306. {
  307. VERIFY(m_lock.is_locked());
  308. VERIFY(m_request_lock.is_locked());
  309. LBAMode lba_mode;
  310. u8 head = 0;
  311. VERIFY(capabilities & ATA_CAP_LBA);
  312. if (lba >= 0x10000000) {
  313. lba_mode = LBAMode::FortyEightBit;
  314. head = 0;
  315. } else {
  316. lba_mode = LBAMode::TwentyEightBit;
  317. head = (lba & 0xF000000) >> 24;
  318. }
  319. wait_until_not_busy();
  320. // We need to select the drive and then we wait 20 microseconds... and it doesn't hurt anything so let's just do it.
  321. m_io_group.io_base().offset(ATA_REG_HDDEVSEL).out<u8>(0xE0 | (static_cast<u8>(slave_request) << 4) | head);
  322. IO::delay(20);
  323. if (lba_mode == LBAMode::FortyEightBit) {
  324. m_io_group.io_base().offset(ATA_REG_SECCOUNT1).out<u8>(0);
  325. m_io_group.io_base().offset(ATA_REG_LBA3).out<u8>((lba & 0xFF000000) >> 24);
  326. m_io_group.io_base().offset(ATA_REG_LBA4).out<u8>((lba & 0xFF00000000ull) >> 32);
  327. m_io_group.io_base().offset(ATA_REG_LBA5).out<u8>((lba & 0xFF0000000000ull) >> 40);
  328. }
  329. m_io_group.io_base().offset(ATA_REG_SECCOUNT0).out<u8>(block_count);
  330. m_io_group.io_base().offset(ATA_REG_LBA0).out<u8>((lba & 0x000000FF) >> 0);
  331. m_io_group.io_base().offset(ATA_REG_LBA1).out<u8>((lba & 0x0000FF00) >> 8);
  332. m_io_group.io_base().offset(ATA_REG_LBA2).out<u8>((lba & 0x00FF0000) >> 16);
  333. for (;;) {
  334. auto status = m_io_group.control_base().in<u8>();
  335. if (!(status & ATA_SR_BSY) && (status & ATA_SR_DRDY))
  336. break;
  337. }
  338. send_ata_io_command(lba_mode, direction);
  339. enable_irq();
  340. }
  341. void IDEChannel::send_ata_io_command(LBAMode lba_mode, Direction direction) const
  342. {
  343. if (lba_mode != LBAMode::FortyEightBit) {
  344. m_io_group.io_base().offset(ATA_REG_COMMAND).out<u8>(direction == Direction::Read ? ATA_CMD_READ_PIO : ATA_CMD_WRITE_PIO);
  345. } else {
  346. m_io_group.io_base().offset(ATA_REG_COMMAND).out<u8>(direction == Direction::Read ? ATA_CMD_READ_PIO_EXT : ATA_CMD_WRITE_PIO_EXT);
  347. }
  348. }
  349. bool IDEChannel::ata_do_read_sector()
  350. {
  351. VERIFY(m_lock.is_locked());
  352. VERIFY(m_request_lock.is_locked());
  353. VERIFY(!m_current_request.is_null());
  354. dbgln_if(PATA_DEBUG, "IDEChannel::ata_do_read_sector");
  355. auto& request = *m_current_request;
  356. auto out_buffer = request.buffer().offset(m_current_request_block_index * 512);
  357. ssize_t nwritten = request.write_to_buffer_buffered<512>(out_buffer, 512, [&](u8* buffer, size_t buffer_bytes) {
  358. for (size_t i = 0; i < buffer_bytes; i += sizeof(u16))
  359. *(u16*)&buffer[i] = IO::in16(m_io_group.io_base().offset(ATA_REG_DATA).get());
  360. return (ssize_t)buffer_bytes;
  361. });
  362. if (nwritten < 0) {
  363. // TODO: Do we need to abort the PATA read if this wasn't the last block?
  364. complete_current_request(AsyncDeviceRequest::MemoryFault);
  365. return false;
  366. }
  367. return true;
  368. }
  369. // FIXME: This doesn't quite work and locks up reading LBA 3.
  370. void IDEChannel::ata_read_sectors(bool slave_request, u16 capabilities)
  371. {
  372. VERIFY(m_lock.is_locked());
  373. VERIFY(!m_current_request.is_null());
  374. VERIFY(m_current_request->block_count() <= 256);
  375. ScopedSpinLock m_lock(m_request_lock);
  376. dbgln_if(PATA_DEBUG, "IDEChannel::ata_read_sectors");
  377. dbgln_if(PATA_DEBUG, "IDEChannel: Reading {} sector(s) @ LBA {}", m_current_request->block_count(), m_current_request->block_index());
  378. ata_access(Direction::Read, slave_request, m_current_request->block_index(), m_current_request->block_count(), capabilities);
  379. }
  380. void IDEChannel::ata_do_write_sector()
  381. {
  382. VERIFY(m_lock.is_locked());
  383. VERIFY(m_request_lock.is_locked());
  384. VERIFY(!m_current_request.is_null());
  385. auto& request = *m_current_request;
  386. io_delay();
  387. while ((m_io_group.control_base().in<u8>() & ATA_SR_BSY) || !(m_io_group.control_base().in<u8>() & ATA_SR_DRQ))
  388. ;
  389. u8 status = m_io_group.control_base().in<u8>();
  390. VERIFY(status & ATA_SR_DRQ);
  391. auto in_buffer = request.buffer().offset(m_current_request_block_index * 512);
  392. dbgln_if(PATA_DEBUG, "IDEChannel: Writing 512 bytes (part {}) (status={:#02x})...", m_current_request_block_index, status);
  393. ssize_t nread = request.read_from_buffer_buffered<512>(in_buffer, 512, [&](const u8* buffer, size_t buffer_bytes) {
  394. for (size_t i = 0; i < buffer_bytes; i += sizeof(u16))
  395. IO::out16(m_io_group.io_base().offset(ATA_REG_DATA).get(), *(const u16*)&buffer[i]);
  396. return (ssize_t)buffer_bytes;
  397. });
  398. if (nread < 0)
  399. complete_current_request(AsyncDeviceRequest::MemoryFault);
  400. }
  401. // FIXME: I'm assuming this doesn't work based on the fact PIO read doesn't work.
  402. void IDEChannel::ata_write_sectors(bool slave_request, u16 capabilities)
  403. {
  404. VERIFY(m_lock.is_locked());
  405. VERIFY(!m_current_request.is_null());
  406. VERIFY(m_current_request->block_count() <= 256);
  407. ScopedSpinLock m_lock(m_request_lock);
  408. dbgln_if(PATA_DEBUG, "IDEChannel: Writing {} sector(s) @ LBA {}", m_current_request->block_count(), m_current_request->block_index());
  409. ata_access(Direction::Write, slave_request, m_current_request->block_index(), m_current_request->block_count(), capabilities);
  410. ata_do_write_sector();
  411. }
  412. }