AHCIPort.cpp 38 KB

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