IDEChannel.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include <AK/ByteBuffer.h>
  27. #include <AK/Singleton.h>
  28. #include <AK/StringView.h>
  29. #include <Kernel/FileSystem/ProcFS.h>
  30. #include <Kernel/IO.h>
  31. #include <Kernel/Process.h>
  32. #include <Kernel/Storage/IDEChannel.h>
  33. #include <Kernel/Storage/IDEController.h>
  34. #include <Kernel/Storage/PATADiskDevice.h>
  35. #include <Kernel/VM/MemoryManager.h>
  36. namespace Kernel {
  37. #define PATA_PRIMARY_IRQ 14
  38. #define PATA_SECONDARY_IRQ 15
  39. #define ATA_SR_BSY 0x80
  40. #define ATA_SR_DRDY 0x40
  41. #define ATA_SR_DF 0x20
  42. #define ATA_SR_DSC 0x10
  43. #define ATA_SR_DRQ 0x08
  44. #define ATA_SR_CORR 0x04
  45. #define ATA_SR_IDX 0x02
  46. #define ATA_SR_ERR 0x01
  47. #define ATA_ER_BBK 0x80
  48. #define ATA_ER_UNC 0x40
  49. #define ATA_ER_MC 0x20
  50. #define ATA_ER_IDNF 0x10
  51. #define ATA_ER_MCR 0x08
  52. #define ATA_ER_ABRT 0x04
  53. #define ATA_ER_TK0NF 0x02
  54. #define ATA_ER_AMNF 0x01
  55. #define ATA_CMD_READ_PIO 0x20
  56. #define ATA_CMD_READ_PIO_EXT 0x24
  57. #define ATA_CMD_READ_DMA 0xC8
  58. #define ATA_CMD_READ_DMA_EXT 0x25
  59. #define ATA_CMD_WRITE_PIO 0x30
  60. #define ATA_CMD_WRITE_PIO_EXT 0x34
  61. #define ATA_CMD_WRITE_DMA 0xCA
  62. #define ATA_CMD_WRITE_DMA_EXT 0x35
  63. #define ATA_CMD_CACHE_FLUSH 0xE7
  64. #define ATA_CMD_CACHE_FLUSH_EXT 0xEA
  65. #define ATA_CMD_PACKET 0xA0
  66. #define ATA_CMD_IDENTIFY_PACKET 0xA1
  67. #define ATA_CMD_IDENTIFY 0xEC
  68. #define ATAPI_CMD_READ 0xA8
  69. #define ATAPI_CMD_EJECT 0x1B
  70. #define ATA_IDENT_DEVICETYPE 0
  71. #define ATA_IDENT_CYLINDERS 2
  72. #define ATA_IDENT_HEADS 6
  73. #define ATA_IDENT_SECTORS 12
  74. #define ATA_IDENT_SERIAL 20
  75. #define ATA_IDENT_MODEL 54
  76. #define ATA_IDENT_CAPABILITIES 98
  77. #define ATA_IDENT_FIELDVALID 106
  78. #define ATA_IDENT_MAX_LBA 120
  79. #define ATA_IDENT_COMMANDSETS 164
  80. #define ATA_IDENT_MAX_LBA_EXT 200
  81. #define IDE_ATA 0x00
  82. #define IDE_ATAPI 0x01
  83. #define ATA_REG_DATA 0x00
  84. #define ATA_REG_ERROR 0x01
  85. #define ATA_REG_FEATURES 0x01
  86. #define ATA_REG_SECCOUNT0 0x02
  87. #define ATA_REG_LBA0 0x03
  88. #define ATA_REG_LBA1 0x04
  89. #define ATA_REG_LBA2 0x05
  90. #define ATA_REG_HDDEVSEL 0x06
  91. #define ATA_REG_COMMAND 0x07
  92. #define ATA_REG_STATUS 0x07
  93. #define ATA_REG_SECCOUNT1 0x08
  94. #define ATA_REG_LBA3 0x09
  95. #define ATA_REG_LBA4 0x0A
  96. #define ATA_REG_LBA5 0x0B
  97. #define ATA_CTL_CONTROL 0x00
  98. #define ATA_CTL_ALTSTATUS 0x00
  99. #define ATA_CTL_DEVADDRESS 0x01
  100. #define ATA_CAP_LBA 0x200
  101. #define PCI_Mass_Storage_Class 0x1
  102. #define PCI_IDE_Controller_Subclass 0x1
  103. NonnullOwnPtr<IDEChannel> IDEChannel::create(const IDEController& controller, IOAddressGroup io_group, ChannelType type, bool force_pio)
  104. {
  105. return make<IDEChannel>(controller, io_group, type, force_pio);
  106. }
  107. RefPtr<StorageDevice> IDEChannel::master_device() const
  108. {
  109. return m_master;
  110. }
  111. RefPtr<StorageDevice> IDEChannel::slave_device() const
  112. {
  113. return m_slave;
  114. }
  115. IDEChannel::IDEChannel(const IDEController& controller, IOAddressGroup io_group, ChannelType type, bool force_pio)
  116. : IRQHandler(type == ChannelType::Primary ? PATA_PRIMARY_IRQ : PATA_SECONDARY_IRQ)
  117. , m_channel_type(type)
  118. , m_io_group(io_group)
  119. , m_parent_controller(controller)
  120. {
  121. disable_irq();
  122. // FIXME: The device may not be capable of DMA.
  123. m_dma_enabled.resource() = !force_pio;
  124. ProcFS::add_sys_bool("ide_dma", m_dma_enabled);
  125. initialize(force_pio);
  126. detect_disks();
  127. // Note: calling to detect_disks could generate an interrupt, clear it if that's the case
  128. clear_pending_interrupts();
  129. enable_irq();
  130. }
  131. void IDEChannel::clear_pending_interrupts() const
  132. {
  133. m_io_group.io_base().offset(ATA_REG_STATUS).in<u8>();
  134. }
  135. IDEChannel::~IDEChannel()
  136. {
  137. }
  138. void IDEChannel::start_request(AsyncBlockDeviceRequest& request, bool use_dma, bool is_slave, u16 capabilities)
  139. {
  140. ScopedSpinLock lock(m_request_lock);
  141. dbgln<PATA_DEBUG>("IDEChannel::start_request");
  142. m_current_request = &request;
  143. m_current_request_block_index = 0;
  144. m_current_request_uses_dma = use_dma;
  145. m_current_request_flushing_cache = false;
  146. if (request.request_type() == AsyncBlockDeviceRequest::Read) {
  147. if (use_dma)
  148. ata_read_sectors_with_dma(is_slave, capabilities);
  149. else
  150. ata_read_sectors(is_slave, capabilities);
  151. } else {
  152. if (use_dma)
  153. ata_write_sectors_with_dma(is_slave, capabilities);
  154. else
  155. ata_write_sectors(is_slave, capabilities);
  156. }
  157. }
  158. void IDEChannel::complete_current_request(AsyncDeviceRequest::RequestResult result)
  159. {
  160. // NOTE: this may be called from the interrupt handler!
  161. ASSERT(m_current_request);
  162. ASSERT(m_request_lock.is_locked());
  163. // Now schedule reading back the buffer as soon as we leave the irq handler.
  164. // This is important so that we can safely write the buffer back,
  165. // which could cause page faults. Note that this may be called immediately
  166. // before Processor::deferred_call_queue returns!
  167. Processor::deferred_call_queue([this, result]() {
  168. dbgln<PATA_DEBUG>("IDEChannel::complete_current_request result: {}", (int)result);
  169. ASSERT(m_current_request);
  170. auto& request = *m_current_request;
  171. m_current_request = nullptr;
  172. if (m_current_request_uses_dma) {
  173. if (result == AsyncDeviceRequest::Success) {
  174. if (request.request_type() == AsyncBlockDeviceRequest::Read) {
  175. if (!request.write_to_buffer(request.buffer(), m_dma_buffer_page->paddr().offset(0xc0000000).as_ptr(), 512 * request.block_count())) {
  176. request.complete(AsyncDeviceRequest::MemoryFault);
  177. return;
  178. }
  179. }
  180. // I read somewhere that this may trigger a cache flush so let's do it.
  181. m_io_group.bus_master_base().offset(2).out<u8>(m_io_group.bus_master_base().offset(2).in<u8>() | 0x6);
  182. }
  183. }
  184. request.complete(result);
  185. });
  186. }
  187. void IDEChannel::initialize(bool force_pio)
  188. {
  189. m_parent_controller->enable_pin_based_interrupts();
  190. dbgln<PATA_DEBUG>("IDEChannel: {} IO base: {}", channel_type_string(), m_io_group.io_base());
  191. dbgln<PATA_DEBUG>("IDEChannel: {} control base: {}", channel_type_string(), m_io_group.control_base());
  192. dbgln<PATA_DEBUG>("IDEChannel: {} bus master base: {}", channel_type_string(), m_io_group.bus_master_base());
  193. if (force_pio) {
  194. dbgln("IDEChannel: Requested to force PIO mode; not setting up DMA");
  195. return;
  196. }
  197. // Let's try to set up DMA transfers.
  198. PCI::enable_bus_mastering(m_parent_controller->pci_address());
  199. m_prdt_page = MM.allocate_supervisor_physical_page();
  200. prdt().end_of_table = 0x8000;
  201. m_dma_buffer_page = MM.allocate_supervisor_physical_page();
  202. }
  203. static void print_ide_status(u8 status)
  204. {
  205. klog() << "IDEChannel: print_ide_status: DRQ=" << ((status & ATA_SR_DRQ) != 0) << " BSY=" << ((status & ATA_SR_BSY) != 0) << " DRDY=" << ((status & ATA_SR_DRDY) != 0) << " DSC=" << ((status & ATA_SR_DSC) != 0) << " DF=" << ((status & ATA_SR_DF) != 0) << " CORR=" << ((status & ATA_SR_CORR) != 0) << " IDX=" << ((status & ATA_SR_IDX) != 0) << " ERR=" << ((status & ATA_SR_ERR) != 0);
  206. }
  207. void IDEChannel::try_disambiguate_error()
  208. {
  209. dbgln("IDEChannel: Error cause:");
  210. switch (m_device_error) {
  211. case ATA_ER_BBK:
  212. dbgln("IDEChannel: - Bad block");
  213. break;
  214. case ATA_ER_UNC:
  215. dbgln("IDEChannel: - Uncorrectable data");
  216. break;
  217. case ATA_ER_MC:
  218. dbgln("IDEChannel: - Media changed");
  219. break;
  220. case ATA_ER_IDNF:
  221. dbgln("IDEChannel: - ID mark not found");
  222. break;
  223. case ATA_ER_MCR:
  224. dbgln("IDEChannel: - Media change request");
  225. break;
  226. case ATA_ER_ABRT:
  227. dbgln("IDEChannel: - Command aborted");
  228. break;
  229. case ATA_ER_TK0NF:
  230. dbgln("IDEChannel: - Track 0 not found");
  231. break;
  232. case ATA_ER_AMNF:
  233. dbgln("IDEChannel: - No address mark");
  234. break;
  235. default:
  236. dbgln("IDEChannel: - No one knows");
  237. break;
  238. }
  239. }
  240. void IDEChannel::handle_irq(const RegisterState&)
  241. {
  242. u8 status = m_io_group.io_base().offset(ATA_REG_STATUS).in<u8>();
  243. m_entropy_source.add_random_event(status);
  244. u8 bstatus = m_io_group.bus_master_base().offset(2).in<u8>();
  245. if (!(bstatus & 0x4)) {
  246. // interrupt not from this device, ignore
  247. dbgln<PATA_DEBUG>("IDEChannel: ignore interrupt");
  248. return;
  249. }
  250. ScopedSpinLock lock(m_request_lock);
  251. #if PATA_DEBUG
  252. klog() << "IDEChannel: interrupt: DRQ=" << ((status & ATA_SR_DRQ) != 0) << " BSY=" << ((status & ATA_SR_BSY) != 0) << " DRDY=" << ((status & ATA_SR_DRDY) != 0);
  253. #endif
  254. if (!m_current_request) {
  255. #if PATA_DEBUG
  256. dbgln("IDEChannel: IRQ but no pending request!");
  257. #endif
  258. return;
  259. }
  260. if (status & ATA_SR_ERR) {
  261. print_ide_status(status);
  262. m_device_error = m_io_group.io_base().offset(ATA_REG_ERROR).in<u8>();
  263. dbgln("IDEChannel: Error {:#02x}!", (u8)m_device_error);
  264. try_disambiguate_error();
  265. complete_current_request(AsyncDeviceRequest::Failure);
  266. return;
  267. }
  268. m_device_error = 0;
  269. if (m_current_request_uses_dma) {
  270. complete_current_request(AsyncDeviceRequest::Success);
  271. return;
  272. }
  273. // Now schedule reading/writing the buffer as soon as we leave the irq handler.
  274. // This is important so that we can safely access the buffers, which could
  275. // trigger page faults
  276. Processor::deferred_call_queue([this]() {
  277. ScopedSpinLock lock(m_request_lock);
  278. if (m_current_request->request_type() == AsyncBlockDeviceRequest::Read) {
  279. dbgln<PATA_DEBUG>("IDEChannel: Read block {}/{}", m_current_request_block_index, m_current_request->block_count());
  280. if (ata_do_read_sector()) {
  281. if (++m_current_request_block_index >= m_current_request->block_count()) {
  282. complete_current_request(AsyncDeviceRequest::Success);
  283. return;
  284. }
  285. // Wait for the next block
  286. enable_irq();
  287. }
  288. } else {
  289. if (!m_current_request_flushing_cache) {
  290. dbgln<PATA_DEBUG>("IDEChannel: Wrote block {}/{}", m_current_request_block_index, m_current_request->block_count());
  291. if (++m_current_request_block_index >= m_current_request->block_count()) {
  292. // We read the last block, flush cache
  293. ASSERT(!m_current_request_flushing_cache);
  294. m_current_request_flushing_cache = true;
  295. m_io_group.io_base().offset(ATA_REG_COMMAND).out<u8>(ATA_CMD_CACHE_FLUSH);
  296. } else {
  297. // Read next block
  298. ata_do_write_sector();
  299. }
  300. } else {
  301. complete_current_request(AsyncDeviceRequest::Success);
  302. }
  303. }
  304. });
  305. }
  306. static void io_delay()
  307. {
  308. for (int i = 0; i < 4; ++i)
  309. IO::in8(0x3f6);
  310. }
  311. void IDEChannel::wait_until_not_busy()
  312. {
  313. while (m_io_group.control_base().in<u8>() & ATA_SR_BSY)
  314. ;
  315. }
  316. String IDEChannel::channel_type_string() const
  317. {
  318. if (m_channel_type == ChannelType::Primary)
  319. return "Primary";
  320. return "Secondary";
  321. }
  322. void IDEChannel::detect_disks()
  323. {
  324. auto channel_string = [](u8 i) -> const char* {
  325. if (i == 0)
  326. return "master";
  327. return "slave";
  328. };
  329. // There are only two possible disks connected to a channel
  330. for (auto i = 0; i < 2; i++) {
  331. m_io_group.io_base().offset(ATA_REG_HDDEVSEL).out<u8>(0xA0 | (i << 4)); // First, we need to select the drive itself
  332. m_io_group.io_base().offset(ATA_REG_COMMAND).out<u8>(ATA_CMD_IDENTIFY); // Send the ATA_IDENTIFY command
  333. // Wait for the BSY flag to be reset
  334. while (m_io_group.control_base().in<u8>() & ATA_SR_BSY)
  335. ;
  336. if (m_io_group.control_base().in<u8>() == 0x00) {
  337. dbgln<PATA_DEBUG>("IDEChannel: No {} {} disk detected!", channel_type_string().to_lowercase(), channel_string(i));
  338. continue;
  339. }
  340. bool check_for_atapi = false;
  341. PATADiskDevice::InterfaceType interface_type = PATADiskDevice::InterfaceType::ATA;
  342. for (;;) {
  343. u8 status = m_io_group.control_base().in<u8>();
  344. if (status & ATA_SR_ERR) {
  345. dbgln<PATA_DEBUG>("IDEChannel: {} {} device is not ATA. Will check for ATAPI.", channel_type_string(), channel_string(i));
  346. check_for_atapi = true;
  347. break;
  348. }
  349. if (!(status & ATA_SR_BSY) && (status & ATA_SR_DRQ)) {
  350. dbgln<PATA_DEBUG>("IDEChannel: {} {} device appears to be ATA.", channel_type_string(), channel_string(i));
  351. interface_type = PATADiskDevice::InterfaceType::ATA;
  352. break;
  353. }
  354. }
  355. if (check_for_atapi) {
  356. u8 cl = m_io_group.io_base().offset(ATA_REG_LBA1).in<u8>();
  357. u8 ch = m_io_group.io_base().offset(ATA_REG_LBA2).in<u8>();
  358. if ((cl == 0x14 && ch == 0xEB) || (cl == 0x69 && ch == 0x96)) {
  359. interface_type = PATADiskDevice::InterfaceType::ATAPI;
  360. 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));
  361. continue;
  362. } else {
  363. dbgln("IDEChannel: {} {} device doesn't appear to be ATA or ATAPI. Ignoring it.", channel_type_string(), channel_string(i));
  364. continue;
  365. }
  366. }
  367. ByteBuffer wbuf = ByteBuffer::create_uninitialized(512);
  368. ByteBuffer bbuf = ByteBuffer::create_uninitialized(512);
  369. u8* b = bbuf.data();
  370. u16* w = (u16*)wbuf.data();
  371. const u16* wbufbase = (u16*)wbuf.data();
  372. for (u32 i = 0; i < 256; ++i) {
  373. u16 data = m_io_group.io_base().offset(ATA_REG_DATA).in<u16>();
  374. *(w++) = data;
  375. *(b++) = MSB(data);
  376. *(b++) = LSB(data);
  377. }
  378. // "Unpad" the device name string.
  379. for (u32 i = 93; i > 54 && bbuf[i] == ' '; --i)
  380. bbuf[i] = 0;
  381. u16 cyls = wbufbase[ATA_IDENT_CYLINDERS / sizeof(u16)];
  382. u16 heads = wbufbase[ATA_IDENT_HEADS / sizeof(u16)];
  383. u16 spt = wbufbase[ATA_IDENT_SECTORS / sizeof(u16)];
  384. u16 capabilities = wbufbase[ATA_IDENT_CAPABILITIES / sizeof(u16)];
  385. if (cyls == 0 || heads == 0 || spt == 0)
  386. continue;
  387. dbgln("IDEChannel: {} {} device found: Type={}, Name={}, C/H/Spt={}/{}/{}, Capabilities=0x{:04x}", channel_type_string(), channel_string(i), interface_type == PATADiskDevice::InterfaceType::ATA ? "ATA" : "ATAPI", ((char*)bbuf.data() + 54), cyls, heads, spt, capabilities);
  388. if (i == 0) {
  389. m_master = PATADiskDevice::create(m_parent_controller, *this, PATADiskDevice::DriveType::Master, interface_type, cyls, heads, spt, capabilities, 3, (m_channel_type == ChannelType::Primary) ? 0 : 2);
  390. } else {
  391. m_slave = PATADiskDevice::create(m_parent_controller, *this, PATADiskDevice::DriveType::Slave, interface_type, cyls, heads, spt, capabilities, 3, (m_channel_type == ChannelType::Primary) ? 1 : 3);
  392. }
  393. }
  394. }
  395. void IDEChannel::ata_access(Direction direction, bool slave_request, u32 lba, u8 block_count, u16 capabilities, bool use_dma)
  396. {
  397. LBAMode lba_mode;
  398. u8 head = 0;
  399. u8 sector = 0;
  400. u16 cylinder = 0;
  401. if (lba >= 0x10000000) {
  402. ASSERT(capabilities & ATA_CAP_LBA);
  403. lba_mode = LBAMode::FortyEightBit;
  404. head = 0;
  405. } else if (capabilities & ATA_CAP_LBA) {
  406. lba_mode = LBAMode::TwentyEightBit;
  407. head = (lba & 0xF000000) >> 24;
  408. } else {
  409. lba_mode = LBAMode::None;
  410. sector = (lba % 63) + 1;
  411. cylinder = (lba + 1 - sector) / (16 * 63);
  412. head = (lba + 1 - sector) % (16 * 63) / (63);
  413. }
  414. wait_until_not_busy();
  415. if (lba_mode == LBAMode::None)
  416. m_io_group.io_base().offset(ATA_REG_HDDEVSEL).out<u8>(0xA0 | (static_cast<u8>(slave_request) << 4) | head);
  417. else
  418. m_io_group.io_base().offset(ATA_REG_HDDEVSEL).out<u8>(0xE0 | (static_cast<u8>(slave_request) << 4) | head);
  419. if (lba_mode == LBAMode::FortyEightBit) {
  420. m_io_group.io_base().offset(ATA_REG_SECCOUNT1).out<u8>(0);
  421. m_io_group.io_base().offset(ATA_REG_LBA3).out<u8>((lba & 0xFF000000) >> 24);
  422. m_io_group.io_base().offset(ATA_REG_LBA4).out<u8>(0);
  423. m_io_group.io_base().offset(ATA_REG_LBA5).out<u8>(0);
  424. }
  425. m_io_group.io_base().offset(ATA_REG_SECCOUNT0).out<u8>(block_count);
  426. if (lba_mode == LBAMode::FortyEightBit || lba_mode == LBAMode::TwentyEightBit) {
  427. m_io_group.io_base().offset(ATA_REG_LBA0).out<u8>((lba & 0x000000FF) >> 0);
  428. m_io_group.io_base().offset(ATA_REG_LBA1).out<u8>((lba & 0x0000FF00) >> 8);
  429. m_io_group.io_base().offset(ATA_REG_LBA2).out<u8>((lba & 0x00FF0000) >> 16);
  430. } else {
  431. m_io_group.io_base().offset(ATA_REG_LBA0).out<u8>(sector);
  432. m_io_group.io_base().offset(ATA_REG_LBA1).out<u8>((cylinder >> 0) & 0xFF);
  433. m_io_group.io_base().offset(ATA_REG_LBA2).out<u8>((cylinder >> 8) & 0xFF);
  434. }
  435. for (;;) {
  436. auto status = m_io_group.control_base().in<u8>();
  437. if (!(status & ATA_SR_BSY) && (status & ATA_SR_DRDY))
  438. break;
  439. }
  440. if (lba_mode != LBAMode::FortyEightBit) {
  441. if (use_dma)
  442. m_io_group.io_base().offset(ATA_REG_COMMAND).out<u8>(direction == Direction::Read ? ATA_CMD_READ_DMA : ATA_CMD_WRITE_DMA);
  443. else
  444. m_io_group.io_base().offset(ATA_REG_COMMAND).out<u8>(direction == Direction::Read ? ATA_CMD_READ_PIO : ATA_CMD_WRITE_PIO);
  445. } else {
  446. if (use_dma)
  447. m_io_group.io_base().offset(ATA_REG_COMMAND).out<u8>(direction == Direction::Read ? ATA_CMD_READ_DMA_EXT : ATA_CMD_WRITE_DMA_EXT);
  448. else
  449. m_io_group.io_base().offset(ATA_REG_COMMAND).out<u8>(direction == Direction::Read ? ATA_CMD_READ_PIO_EXT : ATA_CMD_WRITE_PIO_EXT);
  450. }
  451. enable_irq();
  452. }
  453. void IDEChannel::ata_read_sectors_with_dma(bool slave_request, u16 capabilities)
  454. {
  455. auto& request = *m_current_request;
  456. u32 lba = request.block_index();
  457. dbgln<PATA_DEBUG>("IDEChannel::ata_read_sectors_with_dma ({} x {})", lba, request.block_count());
  458. prdt().offset = m_dma_buffer_page->paddr();
  459. prdt().size = 512 * request.block_count();
  460. ASSERT(prdt().size <= PAGE_SIZE);
  461. // Stop bus master
  462. m_io_group.bus_master_base().out<u8>(0);
  463. // Write the PRDT location
  464. m_io_group.bus_master_base().offset(4).out(m_prdt_page->paddr().get());
  465. // Turn on "Interrupt" and "Error" flag. The error flag should be cleared by hardware.
  466. m_io_group.bus_master_base().offset(2).out<u8>(m_io_group.bus_master_base().offset(2).in<u8>() | 0x6);
  467. // Set transfer direction
  468. m_io_group.bus_master_base().out<u8>(0x8);
  469. ata_access(Direction::Read, slave_request, lba, request.block_count(), capabilities, true);
  470. // Start bus master
  471. m_io_group.bus_master_base().out<u8>(0x9);
  472. }
  473. bool IDEChannel::ata_do_read_sector()
  474. {
  475. dbgln<PATA_DEBUG>("IDEChannel::ata_do_read_sector");
  476. auto& request = *m_current_request;
  477. auto out_buffer = request.buffer().offset(m_current_request_block_index * 512);
  478. ssize_t nwritten = request.write_to_buffer_buffered<512>(out_buffer, 512, [&](u8* buffer, size_t buffer_bytes) {
  479. for (size_t i = 0; i < buffer_bytes; i += sizeof(u16))
  480. *(u16*)&buffer[i] = IO::in16(m_io_group.io_base().offset(ATA_REG_DATA).get());
  481. return (ssize_t)buffer_bytes;
  482. });
  483. if (nwritten < 0) {
  484. // TODO: Do we need to abort the PATA read if this wasn't the last block?
  485. complete_current_request(AsyncDeviceRequest::MemoryFault);
  486. return false;
  487. }
  488. return true;
  489. }
  490. // FIXME: This doesn't quite work and locks up reading LBA 3.
  491. void IDEChannel::ata_read_sectors(bool slave_request, u16 capabilities)
  492. {
  493. auto& request = *m_current_request;
  494. ASSERT(request.block_count() <= 256);
  495. dbgln<PATA_DEBUG>("IDEChannel::ata_read_sectors");
  496. auto lba = request.block_index();
  497. dbgln<PATA_DEBUG>("IDEChannel: Reading {} sector(s) @ LBA {}", request.block_count(), lba);
  498. ata_access(Direction::Read, slave_request, lba, request.block_count(), capabilities, false);
  499. }
  500. void IDEChannel::ata_write_sectors_with_dma(bool slave_request, u16 capabilities)
  501. {
  502. auto& request = *m_current_request;
  503. u32 lba = request.block_index();
  504. dbgln<PATA_DEBUG>("IDEChannel::ata_write_sectors_with_dma ({} x {})", lba, request.block_count());
  505. prdt().offset = m_dma_buffer_page->paddr();
  506. prdt().size = 512 * request.block_count();
  507. if (!request.read_from_buffer(request.buffer(), m_dma_buffer_page->paddr().offset(0xc0000000).as_ptr(), 512 * request.block_count())) {
  508. complete_current_request(AsyncDeviceRequest::MemoryFault);
  509. return;
  510. }
  511. ASSERT(prdt().size <= PAGE_SIZE);
  512. // Stop bus master
  513. m_io_group.bus_master_base().out<u8>(0);
  514. // Write the PRDT location
  515. m_io_group.bus_master_base().offset(4).out<u32>(m_prdt_page->paddr().get());
  516. // Turn on "Interrupt" and "Error" flag. The error flag should be cleared by hardware.
  517. m_io_group.bus_master_base().offset(2).out<u8>(m_io_group.bus_master_base().offset(2).in<u8>() | 0x6);
  518. ata_access(Direction::Write, slave_request, lba, request.block_count(), capabilities, true);
  519. // Start bus master
  520. m_io_group.bus_master_base().out<u8>(0x1);
  521. }
  522. void IDEChannel::ata_do_write_sector()
  523. {
  524. auto& request = *m_current_request;
  525. io_delay();
  526. while ((m_io_group.control_base().in<u8>() & ATA_SR_BSY) || !(m_io_group.control_base().in<u8>() & ATA_SR_DRQ))
  527. ;
  528. u8 status = m_io_group.control_base().in<u8>();
  529. ASSERT(status & ATA_SR_DRQ);
  530. auto in_buffer = request.buffer().offset(m_current_request_block_index * 512);
  531. dbgln<PATA_DEBUG>("IDEChannel: Writing 512 bytes (part {}) (status={:#02x})...", m_current_request_block_index, status);
  532. ssize_t nread = request.read_from_buffer_buffered<512>(in_buffer, 512, [&](const u8* buffer, size_t buffer_bytes) {
  533. for (size_t i = 0; i < buffer_bytes; i += sizeof(u16))
  534. IO::out16(m_io_group.io_base().offset(ATA_REG_DATA).get(), *(const u16*)&buffer[i]);
  535. return (ssize_t)buffer_bytes;
  536. });
  537. if (nread < 0)
  538. complete_current_request(AsyncDeviceRequest::MemoryFault);
  539. }
  540. // FIXME: I'm assuming this doesn't work based on the fact PIO read doesn't work.
  541. void IDEChannel::ata_write_sectors(bool slave_request, u16 capabilities)
  542. {
  543. auto& request = *m_current_request;
  544. ASSERT(request.block_count() <= 256);
  545. u32 start_sector = request.block_index();
  546. u32 count = request.block_count();
  547. dbgln<PATA_DEBUG>("IDEChannel: Writing {} sector(s) @ LBA {}", count, start_sector);
  548. ata_access(Direction::Write, slave_request, start_sector, request.block_count(), capabilities, false);
  549. ata_do_write_sector();
  550. }
  551. }