AHCIPort.cpp 33 KB

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