AHCIPort.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808
  1. /*
  2. * Copyright (c) 2021, Liav A. <liavalb@hotmail.co.il>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. // For more information about locking in this code
  7. // please look at Documentation/Kernel/AHCILocking.md
  8. #include <AK/Atomic.h>
  9. #include <Kernel/Locking/Spinlock.h>
  10. #include <Kernel/Memory/MemoryManager.h>
  11. #include <Kernel/Memory/ScatterGatherList.h>
  12. #include <Kernel/Memory/TypedMapping.h>
  13. #include <Kernel/Storage/AHCIPort.h>
  14. #include <Kernel/Storage/ATA.h>
  15. #include <Kernel/Storage/SATADiskDevice.h>
  16. #include <Kernel/WorkQueue.h>
  17. namespace Kernel {
  18. NonnullRefPtr<AHCIPort> AHCIPort::create(const AHCIPortHandler& handler, volatile AHCI::PortRegisters& registers, u32 port_index)
  19. {
  20. return adopt_ref(*new AHCIPort(handler, registers, port_index));
  21. }
  22. AHCIPort::AHCIPort(const AHCIPortHandler& handler, volatile AHCI::PortRegisters& registers, u32 port_index)
  23. : m_port_index(port_index)
  24. , m_port_registers(registers)
  25. , m_parent_handler(handler)
  26. , m_interrupt_status((volatile u32&)m_port_registers.is)
  27. , m_interrupt_enable((volatile u32&)m_port_registers.ie)
  28. {
  29. if (is_interface_disabled()) {
  30. m_disabled_by_firmware = true;
  31. return;
  32. }
  33. m_command_list_page = MM.allocate_supervisor_physical_page();
  34. m_fis_receive_page = MM.allocate_supervisor_physical_page();
  35. if (m_command_list_page.is_null() || m_fis_receive_page.is_null())
  36. return;
  37. dbgln_if(AHCI_DEBUG, "AHCI Port {}: Command list page at {}", representative_port_index(), m_command_list_page->paddr());
  38. dbgln_if(AHCI_DEBUG, "AHCI Port {}: FIS receive page at {}", representative_port_index(), m_command_list_page->paddr());
  39. for (size_t index = 0; index < 1; index++) {
  40. m_dma_buffers.append(MM.allocate_supervisor_physical_page().release_nonnull());
  41. }
  42. for (size_t index = 0; index < 1; index++) {
  43. m_command_table_pages.append(MM.allocate_supervisor_physical_page().release_nonnull());
  44. }
  45. m_command_list_region = MM.allocate_kernel_region(m_command_list_page->paddr(), PAGE_SIZE, "AHCI Port Command List", Memory::Region::Access::ReadWrite, Memory::Region::Cacheable::No);
  46. dbgln_if(AHCI_DEBUG, "AHCI Port {}: Command list region at {}", representative_port_index(), m_command_list_region->vaddr());
  47. }
  48. void AHCIPort::clear_sata_error_register() const
  49. {
  50. dbgln_if(AHCI_DEBUG, "AHCI Port {}: Clearing SATA error register.", representative_port_index());
  51. m_port_registers.serr = m_port_registers.serr;
  52. }
  53. void AHCIPort::handle_interrupt()
  54. {
  55. dbgln_if(AHCI_DEBUG, "AHCI Port {}: Interrupt handled, PxIS {}", representative_port_index(), m_interrupt_status.raw_value());
  56. if (m_interrupt_status.raw_value() == 0) {
  57. return;
  58. }
  59. if (m_interrupt_status.is_set(AHCI::PortInterruptFlag::PRC)) {
  60. clear_sata_error_register();
  61. m_wait_connect_for_completion = true;
  62. }
  63. if (m_interrupt_status.is_set(AHCI::PortInterruptFlag::INF)) {
  64. // We need to defer the reset, because we can receive interrupts when
  65. // resetting the device.
  66. g_io_work->queue([this]() {
  67. reset();
  68. });
  69. return;
  70. }
  71. if (m_interrupt_status.is_set(AHCI::PortInterruptFlag::IF) || m_interrupt_status.is_set(AHCI::PortInterruptFlag::TFE) || m_interrupt_status.is_set(AHCI::PortInterruptFlag::HBD) || m_interrupt_status.is_set(AHCI::PortInterruptFlag::HBF)) {
  72. g_io_work->queue([this]() {
  73. recover_from_fatal_error();
  74. });
  75. return;
  76. }
  77. if (m_interrupt_status.is_set(AHCI::PortInterruptFlag::DHR) || m_interrupt_status.is_set(AHCI::PortInterruptFlag::PS)) {
  78. m_wait_for_completion = false;
  79. // Now schedule reading/writing the buffer as soon as we leave the irq handler.
  80. // This is important so that we can safely access the buffers, which could
  81. // trigger page faults
  82. if (!m_current_request) {
  83. dbgln_if(AHCI_DEBUG, "AHCI Port {}: Request handled, probably identify request", representative_port_index());
  84. } else {
  85. g_io_work->queue([this]() {
  86. dbgln_if(AHCI_DEBUG, "AHCI Port {}: Request handled", representative_port_index());
  87. MutexLocker locker(m_lock);
  88. VERIFY(m_current_request);
  89. VERIFY(m_current_scatter_list);
  90. if (m_current_request->request_type() == AsyncBlockDeviceRequest::Read) {
  91. if (!m_current_request->write_to_buffer(m_current_request->buffer(), m_current_scatter_list->dma_region().as_ptr(), m_connected_device->block_size() * m_current_request->block_count())) {
  92. dbgln_if(AHCI_DEBUG, "AHCI Port {}: Request failure, memory fault occurred when reading in data.", representative_port_index());
  93. m_current_scatter_list = nullptr;
  94. complete_current_request(AsyncDeviceRequest::MemoryFault);
  95. return;
  96. }
  97. }
  98. m_current_scatter_list = nullptr;
  99. dbgln_if(AHCI_DEBUG, "AHCI Port {}: Request success", representative_port_index());
  100. complete_current_request(AsyncDeviceRequest::Success);
  101. });
  102. }
  103. }
  104. m_interrupt_status.clear();
  105. }
  106. bool AHCIPort::is_interrupts_enabled() const
  107. {
  108. return !m_interrupt_enable.is_cleared();
  109. }
  110. void AHCIPort::recover_from_fatal_error()
  111. {
  112. MutexLocker locker(m_lock);
  113. SpinlockLocker lock(m_hard_lock);
  114. dmesgln("{}: AHCI Port {} fatal error, shutting down!", m_parent_handler->hba_controller()->pci_address(), representative_port_index());
  115. dmesgln("{}: AHCI Port {} fatal error, SError {}", m_parent_handler->hba_controller()->pci_address(), representative_port_index(), (u32)m_port_registers.serr);
  116. stop_command_list_processing();
  117. stop_fis_receiving();
  118. m_interrupt_enable.clear();
  119. }
  120. void AHCIPort::eject()
  121. {
  122. // FIXME: This operation (meant to be used on optical drives) doesn't work yet when I tested it on real hardware
  123. TODO();
  124. VERIFY(m_lock.is_locked());
  125. VERIFY(is_atapi_attached());
  126. VERIFY(is_operable());
  127. clear_sata_error_register();
  128. if (!spin_until_ready())
  129. return;
  130. auto unused_command_header = try_to_find_unused_command_header();
  131. VERIFY(unused_command_header.has_value());
  132. auto* command_list_entries = (volatile AHCI::CommandHeader*)m_command_list_region->vaddr().as_ptr();
  133. command_list_entries[unused_command_header.value()].ctba = m_command_table_pages[unused_command_header.value()].paddr().get();
  134. command_list_entries[unused_command_header.value()].ctbau = 0;
  135. command_list_entries[unused_command_header.value()].prdbc = 0;
  136. command_list_entries[unused_command_header.value()].prdtl = 0;
  137. // Note: we must set the correct Dword count in this register. Real hardware
  138. // AHCI controllers do care about this field! QEMU doesn't care if we don't
  139. // set the correct CFL field in this register, real hardware will set an
  140. // handshake error bit in PxSERR register if CFL is incorrect.
  141. command_list_entries[unused_command_header.value()].attributes = (size_t)FIS::DwordCount::RegisterHostToDevice | AHCI::CommandHeaderAttributes::P | AHCI::CommandHeaderAttributes::C | AHCI::CommandHeaderAttributes::A;
  142. auto command_table_region = MM.allocate_kernel_region(m_command_table_pages[unused_command_header.value()].paddr().page_base(), Memory::page_round_up(sizeof(AHCI::CommandTable)), "AHCI Command Table", Memory::Region::Access::ReadWrite, Memory::Region::Cacheable::No);
  143. auto& command_table = *(volatile AHCI::CommandTable*)command_table_region->vaddr().as_ptr();
  144. memset(const_cast<u8*>(command_table.command_fis), 0, 64);
  145. auto& fis = *(volatile FIS::HostToDevice::Register*)command_table.command_fis;
  146. fis.header.fis_type = (u8)FIS::Type::RegisterHostToDevice;
  147. fis.command = ATA_CMD_PACKET;
  148. full_memory_barrier();
  149. memset(const_cast<u8*>(command_table.atapi_command), 0, 32);
  150. full_memory_barrier();
  151. command_table.atapi_command[0] = ATAPI_CMD_EJECT;
  152. command_table.atapi_command[1] = 0;
  153. command_table.atapi_command[2] = 0;
  154. command_table.atapi_command[3] = 0;
  155. command_table.atapi_command[4] = 0b10;
  156. command_table.atapi_command[5] = 0;
  157. command_table.atapi_command[6] = 0;
  158. command_table.atapi_command[7] = 0;
  159. command_table.atapi_command[8] = 0;
  160. command_table.atapi_command[9] = 0;
  161. command_table.atapi_command[10] = 0;
  162. command_table.atapi_command[11] = 0;
  163. fis.device = 0;
  164. fis.header.port_muliplier = fis.header.port_muliplier | (u8)FIS::HeaderAttributes::C;
  165. // The below loop waits until the port is no longer busy before issuing a new command
  166. if (!spin_until_ready())
  167. return;
  168. full_memory_barrier();
  169. mark_command_header_ready_to_process(unused_command_header.value());
  170. full_memory_barrier();
  171. while (1) {
  172. if (m_port_registers.serr != 0) {
  173. dbgln_if(AHCI_DEBUG, "AHCI Port {}: Eject Drive failed, SError {:#08x}", representative_port_index(), (u32)m_port_registers.serr);
  174. try_disambiguate_sata_error();
  175. VERIFY_NOT_REACHED();
  176. }
  177. }
  178. dbgln("AHCI Port {}: Eject Drive", representative_port_index());
  179. return;
  180. }
  181. bool AHCIPort::reset()
  182. {
  183. MutexLocker locker(m_lock);
  184. SpinlockLocker lock(m_hard_lock);
  185. dbgln_if(AHCI_DEBUG, "AHCI Port {}: Resetting", representative_port_index());
  186. if (m_disabled_by_firmware) {
  187. dmesgln("AHCI Port {}: Disabled by firmware ", representative_port_index());
  188. return false;
  189. }
  190. full_memory_barrier();
  191. m_interrupt_enable.clear();
  192. m_interrupt_status.clear();
  193. full_memory_barrier();
  194. start_fis_receiving();
  195. full_memory_barrier();
  196. clear_sata_error_register();
  197. full_memory_barrier();
  198. if (!initiate_sata_reset(lock)) {
  199. return false;
  200. }
  201. return initialize(lock);
  202. }
  203. bool AHCIPort::initialize_without_reset()
  204. {
  205. MutexLocker locker(m_lock);
  206. SpinlockLocker lock(m_hard_lock);
  207. dmesgln("AHCI Port {}: {}", representative_port_index(), try_disambiguate_sata_status());
  208. return initialize(lock);
  209. }
  210. bool AHCIPort::initialize(SpinlockLocker<Spinlock<u8>>& main_lock)
  211. {
  212. VERIFY(m_lock.is_locked());
  213. dbgln_if(AHCI_DEBUG, "AHCI Port {}: Initialization. Signature = {:#08x}", representative_port_index(), static_cast<u32>(m_port_registers.sig));
  214. if (!is_phy_enabled()) {
  215. // Note: If PHY is not enabled, just clear the interrupt status and enable interrupts, in case
  216. // we are going to hotplug a device later.
  217. m_interrupt_status.clear();
  218. m_interrupt_enable.set_all();
  219. dbgln_if(AHCI_DEBUG, "AHCI Port {}: Bailing initialization, Phy is not enabled.", representative_port_index());
  220. return false;
  221. }
  222. rebase();
  223. power_on();
  224. spin_up();
  225. clear_sata_error_register();
  226. start_fis_receiving();
  227. set_active_state();
  228. m_interrupt_status.clear();
  229. m_interrupt_enable.set_all();
  230. full_memory_barrier();
  231. // This actually enables the port...
  232. start_command_list_processing();
  233. full_memory_barrier();
  234. size_t logical_sector_size = 512;
  235. size_t physical_sector_size = 512;
  236. u64 max_addressable_sector = 0;
  237. if (identify_device(main_lock)) {
  238. auto identify_block = Memory::map_typed<ATAIdentifyBlock>(m_parent_handler->get_identify_metadata_physical_region(m_port_index));
  239. // Check if word 106 is valid before using it!
  240. if ((identify_block->physical_sector_size_to_logical_sector_size >> 14) == 1) {
  241. if (identify_block->physical_sector_size_to_logical_sector_size & (1 << 12)) {
  242. VERIFY(identify_block->logical_sector_size != 0);
  243. logical_sector_size = identify_block->logical_sector_size;
  244. }
  245. if (identify_block->physical_sector_size_to_logical_sector_size & (1 << 13)) {
  246. physical_sector_size = logical_sector_size << (identify_block->physical_sector_size_to_logical_sector_size & 0xf);
  247. }
  248. }
  249. // Check if the device supports LBA48 mode
  250. if (identify_block->commands_and_feature_sets_supported[1] & (1 << 10)) {
  251. max_addressable_sector = identify_block->user_addressable_logical_sectors_count;
  252. } else {
  253. max_addressable_sector = identify_block->max_28_bit_addressable_logical_sector;
  254. }
  255. if (is_atapi_attached()) {
  256. m_port_registers.cmd = m_port_registers.cmd | (1 << 24);
  257. }
  258. dmesgln("AHCI Port {}: Device found, Capacity={}, Bytes per logical sector={}, Bytes per physical sector={}", representative_port_index(), max_addressable_sector * logical_sector_size, logical_sector_size, physical_sector_size);
  259. // FIXME: We don't support ATAPI devices yet, so for now we don't "create" them
  260. if (!is_atapi_attached()) {
  261. m_connected_device = SATADiskDevice::create(m_parent_handler->hba_controller(), *this, logical_sector_size, max_addressable_sector);
  262. } else {
  263. dbgln("AHCI Port {}: Ignoring ATAPI devices for now as we don't currently support them.", representative_port_index());
  264. }
  265. }
  266. return true;
  267. }
  268. const char* AHCIPort::try_disambiguate_sata_status()
  269. {
  270. switch (m_port_registers.ssts & 0xf) {
  271. case 0:
  272. return "Device not detected, Phy not enabled";
  273. case 1:
  274. return "Device detected, Phy disabled";
  275. case 3:
  276. return "Device detected, Phy enabled";
  277. case 4:
  278. return "interface disabled";
  279. }
  280. VERIFY_NOT_REACHED();
  281. }
  282. void AHCIPort::try_disambiguate_sata_error()
  283. {
  284. dmesgln("AHCI Port {}: SErr breakdown:", representative_port_index());
  285. dmesgln("AHCI Port {}: Diagnostics:", representative_port_index());
  286. constexpr u32 diagnostics_bitfield = 0xFFFF0000;
  287. if ((m_port_registers.serr & diagnostics_bitfield) > 0) {
  288. if (m_port_registers.serr & AHCI::SErr::DIAG_X)
  289. dmesgln("AHCI Port {}: - Exchanged", representative_port_index());
  290. if (m_port_registers.serr & AHCI::SErr::DIAG_F)
  291. dmesgln("AHCI Port {}: - Unknown FIS Type", representative_port_index());
  292. if (m_port_registers.serr & AHCI::SErr::DIAG_T)
  293. dmesgln("AHCI Port {}: - Transport state transition error", representative_port_index());
  294. if (m_port_registers.serr & AHCI::SErr::DIAG_S)
  295. dmesgln("AHCI Port {}: - Link sequence error", representative_port_index());
  296. if (m_port_registers.serr & AHCI::SErr::DIAG_H)
  297. dmesgln("AHCI Port {}: - Handshake error", representative_port_index());
  298. if (m_port_registers.serr & AHCI::SErr::DIAG_C)
  299. dmesgln("AHCI Port {}: - CRC error", representative_port_index());
  300. if (m_port_registers.serr & AHCI::SErr::DIAG_D)
  301. dmesgln("AHCI Port {}: - Disparity error", representative_port_index());
  302. if (m_port_registers.serr & AHCI::SErr::DIAG_B)
  303. dmesgln("AHCI Port {}: - 10B to 8B decode error", representative_port_index());
  304. if (m_port_registers.serr & AHCI::SErr::DIAG_W)
  305. dmesgln("AHCI Port {}: - Comm Wake", representative_port_index());
  306. if (m_port_registers.serr & AHCI::SErr::DIAG_I)
  307. dmesgln("AHCI Port {}: - Phy Internal Error", representative_port_index());
  308. if (m_port_registers.serr & AHCI::SErr::DIAG_N)
  309. dmesgln("AHCI Port {}: - PhyRdy Change", representative_port_index());
  310. } else {
  311. dmesgln("AHCI Port {}: - No diagnostic information provided.", representative_port_index());
  312. }
  313. dmesgln("AHCI Port {}: Error(s):", representative_port_index());
  314. constexpr u32 error_bitfield = 0xFFFF;
  315. if ((m_port_registers.serr & error_bitfield) > 0) {
  316. if (m_port_registers.serr & AHCI::SErr::ERR_E)
  317. dmesgln("AHCI Port {}: - Internal error", representative_port_index());
  318. if (m_port_registers.serr & AHCI::SErr::ERR_P)
  319. dmesgln("AHCI Port {}: - Protocol error", representative_port_index());
  320. if (m_port_registers.serr & AHCI::SErr::ERR_C)
  321. dmesgln("AHCI Port {}: - Persistent communication or data integrity error", representative_port_index());
  322. if (m_port_registers.serr & AHCI::SErr::ERR_T)
  323. dmesgln("AHCI Port {}: - Transient data integrity error", representative_port_index());
  324. if (m_port_registers.serr & AHCI::SErr::ERR_M)
  325. dmesgln("AHCI Port {}: - Recovered communications error", representative_port_index());
  326. if (m_port_registers.serr & AHCI::SErr::ERR_I)
  327. dmesgln("AHCI Port {}: - Recovered data integrity error", representative_port_index());
  328. } else {
  329. dmesgln("AHCI Port {}: - No error information provided.", representative_port_index());
  330. }
  331. }
  332. void AHCIPort::rebase()
  333. {
  334. VERIFY(m_lock.is_locked());
  335. VERIFY(m_hard_lock.is_locked());
  336. VERIFY(!m_command_list_page.is_null() && !m_fis_receive_page.is_null());
  337. dbgln_if(AHCI_DEBUG, "AHCI Port {}: Rebasing.", representative_port_index());
  338. full_memory_barrier();
  339. stop_command_list_processing();
  340. stop_fis_receiving();
  341. full_memory_barrier();
  342. size_t retry = 0;
  343. // Try to wait 1 second for HBA to clear Command List Running and FIS Receive Running
  344. while (retry < 1000) {
  345. if (!(m_port_registers.cmd & (1 << 15)) && !(m_port_registers.cmd & (1 << 14)))
  346. break;
  347. IO::delay(1000);
  348. retry++;
  349. }
  350. full_memory_barrier();
  351. m_port_registers.clbu = 0;
  352. m_port_registers.clb = m_command_list_page->paddr().get();
  353. m_port_registers.fbu = 0;
  354. m_port_registers.fb = m_fis_receive_page->paddr().get();
  355. }
  356. bool AHCIPort::is_operable() const
  357. {
  358. // Note: The definition of "operable" is somewhat ambiguous, but we determine it
  359. // by 3 parameters as shown below.
  360. return (!m_command_list_page.is_null())
  361. && (!m_fis_receive_page.is_null())
  362. && ((m_port_registers.cmd & (1 << 14)) != 0);
  363. }
  364. void AHCIPort::set_active_state() const
  365. {
  366. VERIFY(m_lock.is_locked());
  367. VERIFY(m_hard_lock.is_locked());
  368. dbgln_if(AHCI_DEBUG, "AHCI Port {}: Switching to active state.", representative_port_index());
  369. m_port_registers.cmd = (m_port_registers.cmd & 0x0ffffff) | (1 << 28);
  370. }
  371. void AHCIPort::set_sleep_state() const
  372. {
  373. VERIFY(m_lock.is_locked());
  374. VERIFY(m_hard_lock.is_locked());
  375. m_port_registers.cmd = (m_port_registers.cmd & 0x0ffffff) | (0b1000 << 28);
  376. }
  377. size_t AHCIPort::calculate_descriptors_count(size_t block_count) const
  378. {
  379. VERIFY(m_connected_device);
  380. size_t needed_dma_regions_count = Memory::page_round_up((block_count * m_connected_device->block_size())) / PAGE_SIZE;
  381. VERIFY(needed_dma_regions_count <= m_dma_buffers.size());
  382. return needed_dma_regions_count;
  383. }
  384. Optional<AsyncDeviceRequest::RequestResult> AHCIPort::prepare_and_set_scatter_list(AsyncBlockDeviceRequest& request)
  385. {
  386. VERIFY(m_lock.is_locked());
  387. VERIFY(request.block_count() > 0);
  388. NonnullRefPtrVector<Memory::PhysicalPage> allocated_dma_regions;
  389. for (size_t index = 0; index < calculate_descriptors_count(request.block_count()); index++) {
  390. allocated_dma_regions.append(m_dma_buffers.at(index));
  391. }
  392. m_current_scatter_list = Memory::ScatterGatherList::try_create(request, allocated_dma_regions.span(), m_connected_device->block_size());
  393. if (!m_current_scatter_list)
  394. return AsyncDeviceRequest::Failure;
  395. if (request.request_type() == AsyncBlockDeviceRequest::Write) {
  396. if (!request.read_from_buffer(request.buffer(), m_current_scatter_list->dma_region().as_ptr(), m_connected_device->block_size() * request.block_count())) {
  397. return AsyncDeviceRequest::MemoryFault;
  398. }
  399. }
  400. return {};
  401. }
  402. void AHCIPort::start_request(AsyncBlockDeviceRequest& request)
  403. {
  404. MutexLocker locker(m_lock);
  405. dbgln_if(AHCI_DEBUG, "AHCI Port {}: Request start", representative_port_index());
  406. VERIFY(!m_current_request);
  407. VERIFY(!m_current_scatter_list);
  408. m_current_request = request;
  409. auto result = prepare_and_set_scatter_list(request);
  410. if (result.has_value()) {
  411. dbgln_if(AHCI_DEBUG, "AHCI Port {}: Request failure.", representative_port_index());
  412. locker.unlock();
  413. complete_current_request(result.value());
  414. return;
  415. }
  416. auto success = access_device(request.request_type(), request.block_index(), request.block_count());
  417. if (!success) {
  418. dbgln_if(AHCI_DEBUG, "AHCI Port {}: Request failure.", representative_port_index());
  419. locker.unlock();
  420. complete_current_request(AsyncDeviceRequest::Failure);
  421. return;
  422. }
  423. }
  424. void AHCIPort::complete_current_request(AsyncDeviceRequest::RequestResult result)
  425. {
  426. VERIFY(m_current_request);
  427. auto current_request = m_current_request;
  428. m_current_request.clear();
  429. current_request->complete(result);
  430. }
  431. bool AHCIPort::spin_until_ready() const
  432. {
  433. VERIFY(m_lock.is_locked());
  434. size_t spin = 0;
  435. dbgln_if(AHCI_DEBUG, "AHCI Port {}: Spinning until ready.", representative_port_index());
  436. while ((m_port_registers.tfd & (ATA_SR_BSY | ATA_SR_DRQ)) && spin <= 100) {
  437. IO::delay(1000);
  438. spin++;
  439. }
  440. if (spin == 100) {
  441. dbgln_if(AHCI_DEBUG, "AHCI Port {}: SPIN exceeded 100 milliseconds threshold", representative_port_index());
  442. return false;
  443. }
  444. return true;
  445. }
  446. bool AHCIPort::access_device(AsyncBlockDeviceRequest::RequestType direction, u64 lba, u8 block_count)
  447. {
  448. VERIFY(m_connected_device);
  449. VERIFY(is_operable());
  450. VERIFY(m_lock.is_locked());
  451. VERIFY(m_current_scatter_list);
  452. SpinlockLocker lock(m_hard_lock);
  453. dbgln_if(AHCI_DEBUG, "AHCI Port {}: Do a {}, lba {}, block count {}", representative_port_index(), direction == AsyncBlockDeviceRequest::RequestType::Write ? "write" : "read", lba, block_count);
  454. if (!spin_until_ready())
  455. return false;
  456. auto unused_command_header = try_to_find_unused_command_header();
  457. VERIFY(unused_command_header.has_value());
  458. auto* command_list_entries = (volatile AHCI::CommandHeader*)m_command_list_region->vaddr().as_ptr();
  459. command_list_entries[unused_command_header.value()].ctba = m_command_table_pages[unused_command_header.value()].paddr().get();
  460. command_list_entries[unused_command_header.value()].ctbau = 0;
  461. command_list_entries[unused_command_header.value()].prdbc = 0;
  462. command_list_entries[unused_command_header.value()].prdtl = m_current_scatter_list->scatters_count();
  463. // Note: we must set the correct Dword count in this register. Real hardware
  464. // AHCI controllers do care about this field! QEMU doesn't care if we don't
  465. // set the correct CFL field in this register, real hardware will set an
  466. // handshake error bit in PxSERR register if CFL is incorrect.
  467. command_list_entries[unused_command_header.value()].attributes = (size_t)FIS::DwordCount::RegisterHostToDevice | AHCI::CommandHeaderAttributes::P | (is_atapi_attached() ? AHCI::CommandHeaderAttributes::A : 0) | (direction == AsyncBlockDeviceRequest::RequestType::Write ? AHCI::CommandHeaderAttributes::W : 0);
  468. dbgln_if(AHCI_DEBUG, "AHCI Port {}: CLE: ctba={:#08x}, ctbau={:#08x}, prdbc={:#08x}, prdtl={:#04x}, attributes={:#04x}", representative_port_index(), (u32)command_list_entries[unused_command_header.value()].ctba, (u32)command_list_entries[unused_command_header.value()].ctbau, (u32)command_list_entries[unused_command_header.value()].prdbc, (u16)command_list_entries[unused_command_header.value()].prdtl, (u16)command_list_entries[unused_command_header.value()].attributes);
  469. auto command_table_region = MM.allocate_kernel_region(m_command_table_pages[unused_command_header.value()].paddr().page_base(), Memory::page_round_up(sizeof(AHCI::CommandTable)), "AHCI Command Table", Memory::Region::Access::ReadWrite, Memory::Region::Cacheable::No);
  470. auto& command_table = *(volatile AHCI::CommandTable*)command_table_region->vaddr().as_ptr();
  471. dbgln_if(AHCI_DEBUG, "AHCI Port {}: Allocated command table at {}", representative_port_index(), command_table_region->vaddr());
  472. memset(const_cast<u8*>(command_table.command_fis), 0, 64);
  473. size_t scatter_entry_index = 0;
  474. size_t data_transfer_count = (block_count * m_connected_device->block_size());
  475. for (auto scatter_page : m_current_scatter_list->vmobject().physical_pages()) {
  476. VERIFY(data_transfer_count != 0);
  477. VERIFY(scatter_page);
  478. dbgln_if(AHCI_DEBUG, "AHCI Port {}: Add a transfer scatter entry @ {}", representative_port_index(), scatter_page->paddr());
  479. command_table.descriptors[scatter_entry_index].base_high = 0;
  480. command_table.descriptors[scatter_entry_index].base_low = scatter_page->paddr().get();
  481. if (data_transfer_count <= PAGE_SIZE) {
  482. command_table.descriptors[scatter_entry_index].byte_count = data_transfer_count - 1;
  483. data_transfer_count = 0;
  484. } else {
  485. command_table.descriptors[scatter_entry_index].byte_count = PAGE_SIZE - 1;
  486. data_transfer_count -= PAGE_SIZE;
  487. }
  488. scatter_entry_index++;
  489. }
  490. command_table.descriptors[scatter_entry_index].byte_count = (PAGE_SIZE - 1) | (1 << 31);
  491. memset(const_cast<u8*>(command_table.atapi_command), 0, 32);
  492. auto& fis = *(volatile FIS::HostToDevice::Register*)command_table.command_fis;
  493. fis.header.fis_type = (u8)FIS::Type::RegisterHostToDevice;
  494. if (is_atapi_attached()) {
  495. fis.command = ATA_CMD_PACKET;
  496. TODO();
  497. } else {
  498. if (direction == AsyncBlockDeviceRequest::RequestType::Write)
  499. fis.command = ATA_CMD_WRITE_DMA_EXT;
  500. else
  501. fis.command = ATA_CMD_READ_DMA_EXT;
  502. }
  503. full_memory_barrier();
  504. fis.device = ATA_USE_LBA_ADDRESSING;
  505. fis.header.port_muliplier = (u8)FIS::HeaderAttributes::C;
  506. fis.lba_high[0] = (lba >> 24) & 0xff;
  507. fis.lba_high[1] = (lba >> 32) & 0xff;
  508. fis.lba_high[2] = (lba >> 40) & 0xff;
  509. fis.lba_low[0] = lba & 0xff;
  510. fis.lba_low[1] = (lba >> 8) & 0xff;
  511. fis.lba_low[2] = (lba >> 16) & 0xff;
  512. fis.count = (block_count);
  513. // The below loop waits until the port is no longer busy before issuing a new command
  514. if (!spin_until_ready())
  515. return false;
  516. full_memory_barrier();
  517. mark_command_header_ready_to_process(unused_command_header.value());
  518. full_memory_barrier();
  519. dbgln_if(AHCI_DEBUG, "AHCI Port {}: Do a {}, lba {}, block count {} @ {}, ended", representative_port_index(), direction == AsyncBlockDeviceRequest::RequestType::Write ? "write" : "read", lba, block_count, m_dma_buffers[0].paddr());
  520. return true;
  521. }
  522. bool AHCIPort::identify_device(SpinlockLocker<Spinlock<u8>>& main_lock)
  523. {
  524. VERIFY(m_lock.is_locked());
  525. VERIFY(is_operable());
  526. if (!spin_until_ready())
  527. return false;
  528. auto unused_command_header = try_to_find_unused_command_header();
  529. VERIFY(unused_command_header.has_value());
  530. auto* command_list_entries = (volatile AHCI::CommandHeader*)m_command_list_region->vaddr().as_ptr();
  531. command_list_entries[unused_command_header.value()].ctba = m_command_table_pages[unused_command_header.value()].paddr().get();
  532. command_list_entries[unused_command_header.value()].ctbau = 0;
  533. command_list_entries[unused_command_header.value()].prdbc = 512;
  534. command_list_entries[unused_command_header.value()].prdtl = 1;
  535. // Note: we must set the correct Dword count in this register. Real hardware AHCI controllers do care about this field!
  536. // QEMU doesn't care if we don't set the correct CFL field in this register, real hardware will set an handshake error bit in PxSERR register.
  537. command_list_entries[unused_command_header.value()].attributes = (size_t)FIS::DwordCount::RegisterHostToDevice | AHCI::CommandHeaderAttributes::P;
  538. auto command_table_region = MM.allocate_kernel_region(m_command_table_pages[unused_command_header.value()].paddr().page_base(), Memory::page_round_up(sizeof(AHCI::CommandTable)), "AHCI Command Table", Memory::Region::Access::ReadWrite);
  539. auto& command_table = *(volatile AHCI::CommandTable*)command_table_region->vaddr().as_ptr();
  540. memset(const_cast<u8*>(command_table.command_fis), 0, 64);
  541. command_table.descriptors[0].base_high = 0;
  542. command_table.descriptors[0].base_low = m_parent_handler->get_identify_metadata_physical_region(m_port_index).get();
  543. command_table.descriptors[0].byte_count = 512 - 1;
  544. auto& fis = *(volatile FIS::HostToDevice::Register*)command_table.command_fis;
  545. fis.header.fis_type = (u8)FIS::Type::RegisterHostToDevice;
  546. fis.command = m_port_registers.sig == AHCI::DeviceSignature::ATAPI ? ATA_CMD_IDENTIFY_PACKET : ATA_CMD_IDENTIFY;
  547. fis.device = 0;
  548. fis.header.port_muliplier = fis.header.port_muliplier | (u8)FIS::HeaderAttributes::C;
  549. // The below loop waits until the port is no longer busy before issuing a new command
  550. if (!spin_until_ready())
  551. return false;
  552. // FIXME: Find a better way to send IDENTIFY DEVICE and getting an interrupt!
  553. {
  554. main_lock.unlock();
  555. VERIFY_INTERRUPTS_ENABLED();
  556. full_memory_barrier();
  557. m_wait_for_completion = true;
  558. dbgln_if(AHCI_DEBUG, "AHCI Port {}: Marking command header at index {} as ready to identify device", representative_port_index(), unused_command_header.value());
  559. m_port_registers.ci = 1 << unused_command_header.value();
  560. full_memory_barrier();
  561. while (1) {
  562. if (m_port_registers.serr != 0) {
  563. dbgln("AHCI Port {}: Identify failed, SError {:#08x}", representative_port_index(), (u32)m_port_registers.serr);
  564. try_disambiguate_sata_error();
  565. return false;
  566. }
  567. if (!m_wait_for_completion)
  568. break;
  569. }
  570. main_lock.lock();
  571. }
  572. return true;
  573. }
  574. bool AHCIPort::shutdown()
  575. {
  576. MutexLocker locker(m_lock);
  577. SpinlockLocker lock(m_hard_lock);
  578. rebase();
  579. set_interface_state(AHCI::DeviceDetectionInitialization::DisableInterface);
  580. return true;
  581. }
  582. Optional<u8> AHCIPort::try_to_find_unused_command_header()
  583. {
  584. VERIFY(m_lock.is_locked());
  585. u32 commands_issued = m_port_registers.ci;
  586. for (size_t index = 0; index < 32; index++) {
  587. if (!(commands_issued & 1)) {
  588. dbgln_if(AHCI_DEBUG, "AHCI Port {}: unused command header at index {}", representative_port_index(), index);
  589. return index;
  590. }
  591. commands_issued >>= 1;
  592. }
  593. return {};
  594. }
  595. void AHCIPort::start_command_list_processing() const
  596. {
  597. VERIFY(m_lock.is_locked());
  598. VERIFY(m_hard_lock.is_locked());
  599. VERIFY(is_operable());
  600. dbgln_if(AHCI_DEBUG, "AHCI Port {}: Starting command list processing.", representative_port_index());
  601. m_port_registers.cmd = m_port_registers.cmd | 1;
  602. }
  603. void AHCIPort::mark_command_header_ready_to_process(u8 command_header_index) const
  604. {
  605. VERIFY(m_lock.is_locked());
  606. VERIFY(m_hard_lock.is_locked());
  607. VERIFY(is_operable());
  608. VERIFY(!m_wait_for_completion);
  609. m_wait_for_completion = true;
  610. dbgln_if(AHCI_DEBUG, "AHCI Port {}: Marking command header at index {} as ready to process.", representative_port_index(), command_header_index);
  611. m_port_registers.ci = 1 << command_header_index;
  612. }
  613. void AHCIPort::stop_command_list_processing() const
  614. {
  615. VERIFY(m_lock.is_locked());
  616. VERIFY(m_hard_lock.is_locked());
  617. dbgln_if(AHCI_DEBUG, "AHCI Port {}: Stopping command list processing.", representative_port_index());
  618. m_port_registers.cmd = m_port_registers.cmd & 0xfffffffe;
  619. }
  620. void AHCIPort::start_fis_receiving() const
  621. {
  622. VERIFY(m_lock.is_locked());
  623. VERIFY(m_hard_lock.is_locked());
  624. dbgln_if(AHCI_DEBUG, "AHCI Port {}: Starting FIS receiving.", representative_port_index());
  625. m_port_registers.cmd = m_port_registers.cmd | (1 << 4);
  626. }
  627. void AHCIPort::power_on() const
  628. {
  629. VERIFY(m_lock.is_locked());
  630. VERIFY(m_hard_lock.is_locked());
  631. dbgln_if(AHCI_DEBUG, "AHCI Port {}: Power on. Cold presence detection? {}", representative_port_index(), (bool)(m_port_registers.cmd & (1 << 20)));
  632. if (!(m_port_registers.cmd & (1 << 20)))
  633. return;
  634. dbgln_if(AHCI_DEBUG, "AHCI Port {}: Powering on device.", representative_port_index());
  635. m_port_registers.cmd = m_port_registers.cmd | (1 << 2);
  636. }
  637. void AHCIPort::spin_up() const
  638. {
  639. VERIFY(m_lock.is_locked());
  640. VERIFY(m_hard_lock.is_locked());
  641. dbgln_if(AHCI_DEBUG, "AHCI Port {}: Spin up. Staggered spin up? {}", representative_port_index(), m_parent_handler->hba_capabilities().staggered_spin_up_supported);
  642. if (!m_parent_handler->hba_capabilities().staggered_spin_up_supported)
  643. return;
  644. dbgln_if(AHCI_DEBUG, "AHCI Port {}: Spinning up device.", representative_port_index());
  645. m_port_registers.cmd = m_port_registers.cmd | (1 << 1);
  646. }
  647. void AHCIPort::stop_fis_receiving() const
  648. {
  649. VERIFY(m_lock.is_locked());
  650. VERIFY(m_hard_lock.is_locked());
  651. dbgln_if(AHCI_DEBUG, "AHCI Port {}: Stopping FIS receiving.", representative_port_index());
  652. m_port_registers.cmd = m_port_registers.cmd & 0xFFFFFFEF;
  653. }
  654. bool AHCIPort::initiate_sata_reset(SpinlockLocker<Spinlock<u8>>& main_lock)
  655. {
  656. VERIFY(m_lock.is_locked());
  657. VERIFY(m_hard_lock.is_locked());
  658. dbgln_if(AHCI_DEBUG, "AHCI Port {}: Initiate SATA reset", representative_port_index());
  659. stop_command_list_processing();
  660. full_memory_barrier();
  661. size_t retry = 0;
  662. // Try to wait 1 second for HBA to clear Command List Running
  663. while (retry < 5000) {
  664. if (!(m_port_registers.cmd & (1 << 15)))
  665. break;
  666. // The AHCI specification says to wait now a 500 milliseconds
  667. IO::delay(100);
  668. retry++;
  669. }
  670. full_memory_barrier();
  671. spin_up();
  672. full_memory_barrier();
  673. set_interface_state(AHCI::DeviceDetectionInitialization::PerformInterfaceInitializationSequence);
  674. // The AHCI specification says to wait now a 1 millisecond
  675. IO::delay(1000);
  676. // FIXME: Find a better way to opt-out temporarily from Scoped locking!
  677. {
  678. main_lock.unlock();
  679. VERIFY_INTERRUPTS_ENABLED();
  680. full_memory_barrier();
  681. set_interface_state(AHCI::DeviceDetectionInitialization::NoActionRequested);
  682. full_memory_barrier();
  683. if (m_wait_connect_for_completion) {
  684. retry = 0;
  685. while (retry < 100000) {
  686. if (is_phy_enabled())
  687. break;
  688. IO::delay(10);
  689. retry++;
  690. }
  691. }
  692. main_lock.lock();
  693. }
  694. dmesgln("AHCI Port {}: {}", representative_port_index(), try_disambiguate_sata_status());
  695. full_memory_barrier();
  696. clear_sata_error_register();
  697. return (m_port_registers.ssts & 0xf) == 3;
  698. }
  699. void AHCIPort::set_interface_state(AHCI::DeviceDetectionInitialization requested_action)
  700. {
  701. switch (requested_action) {
  702. case AHCI::DeviceDetectionInitialization::NoActionRequested:
  703. m_port_registers.sctl = (m_port_registers.sctl & 0xfffffff0);
  704. return;
  705. case AHCI::DeviceDetectionInitialization::PerformInterfaceInitializationSequence:
  706. m_port_registers.sctl = (m_port_registers.sctl & 0xfffffff0) | 1;
  707. return;
  708. case AHCI::DeviceDetectionInitialization::DisableInterface:
  709. m_port_registers.sctl = (m_port_registers.sctl & 0xfffffff0) | 4;
  710. return;
  711. }
  712. VERIFY_NOT_REACHED();
  713. }
  714. }