Port.cpp 38 KB

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