NVMeController.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  1. /*
  2. * Copyright (c) 2021, Pankaj R <pankydev8@gmail.com>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include "NVMeController.h"
  7. #include "AK/Format.h"
  8. #include <AK/RefPtr.h>
  9. #include <AK/Types.h>
  10. #include <Kernel/Arch/x86/IO.h>
  11. #include <Kernel/Arch/x86/Processor.h>
  12. #include <Kernel/Bus/PCI/API.h>
  13. #include <Kernel/Devices/Device.h>
  14. #include <Kernel/FileSystem/ProcFS.h>
  15. #include <Kernel/Sections.h>
  16. namespace Kernel {
  17. Atomic<u8> NVMeController::controller_id {};
  18. UNMAP_AFTER_INIT ErrorOr<NonnullRefPtr<NVMeController>> NVMeController::try_initialize(const Kernel::PCI::DeviceIdentifier& device_identifier)
  19. {
  20. auto controller = TRY(adopt_nonnull_ref_or_enomem(new NVMeController(device_identifier)));
  21. TRY(controller->initialize());
  22. NVMeController::controller_id++;
  23. return controller;
  24. }
  25. UNMAP_AFTER_INIT NVMeController::NVMeController(const PCI::DeviceIdentifier& device_identifier)
  26. : PCI::Device(device_identifier.address())
  27. , m_pci_device_id(device_identifier)
  28. {
  29. }
  30. UNMAP_AFTER_INIT ErrorOr<void> NVMeController::initialize()
  31. {
  32. // Nr of queues = one queue per core
  33. auto nr_of_queues = Processor::count();
  34. auto irq = m_pci_device_id.interrupt_line().value();
  35. PCI::enable_memory_space(m_pci_device_id.address());
  36. PCI::enable_bus_mastering(m_pci_device_id.address());
  37. m_bar = PCI::get_BAR0(m_pci_device_id.address()) & BAR_ADDR_MASK;
  38. static_assert(sizeof(ControllerRegister) == REG_SQ0TDBL_START);
  39. // Map only until doorbell register for the controller
  40. // Queues will individually map the doorbell register respectively
  41. m_controller_regs = TRY(Memory::map_typed_writable<volatile ControllerRegister>(PhysicalAddress(m_bar)));
  42. auto caps = m_controller_regs->cap;
  43. m_ready_timeout = Time::from_milliseconds(CAP_TO(caps) * 500); // CAP.TO is in 500ms units
  44. calculate_doorbell_stride();
  45. TRY(create_admin_queue(irq));
  46. VERIFY(m_admin_queue_ready == true);
  47. VERIFY(IO_QUEUE_SIZE < MQES(caps));
  48. dbgln_if(NVME_DEBUG, "NVMe: IO queue depth is: {}", IO_QUEUE_SIZE);
  49. // Create an IO queue per core
  50. for (u32 cpuid = 0; cpuid < nr_of_queues; ++cpuid) {
  51. // qid is zero is used for admin queue
  52. TRY(create_io_queue(irq, cpuid + 1));
  53. }
  54. TRY(identify_and_init_namespaces());
  55. return {};
  56. }
  57. bool NVMeController::wait_for_ready(bool expected_ready_bit_value)
  58. {
  59. static constexpr size_t one_ms_io_delay = 1000;
  60. auto wait_iterations = max(1, m_ready_timeout.to_milliseconds());
  61. u32 expected_rdy = expected_ready_bit_value ? 1 : 0;
  62. while (((m_controller_regs->csts >> CSTS_RDY_BIT) & 0x1) != expected_rdy) {
  63. IO::delay(one_ms_io_delay);
  64. if (--wait_iterations == 0) {
  65. if (((m_controller_regs->csts >> CSTS_RDY_BIT) & 0x1) != expected_rdy) {
  66. dbgln_if(NVME_DEBUG, "NVMEController: CSTS.RDY still not set to {} after {} ms", expected_rdy, m_ready_timeout.to_milliseconds());
  67. return false;
  68. }
  69. break;
  70. }
  71. }
  72. return true;
  73. }
  74. bool NVMeController::reset_controller()
  75. {
  76. if ((m_controller_regs->cc & (1 << CC_EN_BIT)) != 0) {
  77. // If the EN bit is already set, we need to wait
  78. // until the RDY bit is 1, otherwise the behavior is undefined
  79. if (!wait_for_ready(true))
  80. return false;
  81. }
  82. auto cc = m_controller_regs->cc;
  83. cc = cc & ~(1 << CC_EN_BIT);
  84. m_controller_regs->cc = cc;
  85. full_memory_barrier();
  86. // Wait until the RDY bit is cleared
  87. if (!wait_for_ready(false))
  88. return false;
  89. return true;
  90. }
  91. bool NVMeController::start_controller()
  92. {
  93. if (!(m_controller_regs->cc & (1 << CC_EN_BIT))) {
  94. // If the EN bit is not already set, we need to wait
  95. // until the RDY bit is 0, otherwise the behavior is undefined
  96. if (!wait_for_ready(false))
  97. return false;
  98. }
  99. auto cc = m_controller_regs->cc;
  100. cc = cc | (1 << CC_EN_BIT);
  101. cc = cc | (CQ_WIDTH << CC_IOCQES_BIT);
  102. cc = cc | (SQ_WIDTH << CC_IOSQES_BIT);
  103. m_controller_regs->cc = cc;
  104. full_memory_barrier();
  105. // Wait until the RDY bit is set
  106. if (!wait_for_ready(true))
  107. return false;
  108. return true;
  109. }
  110. UNMAP_AFTER_INIT u32 NVMeController::get_admin_q_dept()
  111. {
  112. u32 aqa = m_controller_regs->aqa;
  113. // Queue depth is 0 based
  114. u32 q_depth = min(ACQ_SIZE(aqa), ASQ_SIZE(aqa)) + 1;
  115. dbgln_if(NVME_DEBUG, "NVMe: Admin queue depth is {}", q_depth);
  116. return q_depth;
  117. }
  118. UNMAP_AFTER_INIT ErrorOr<void> NVMeController::identify_and_init_namespaces()
  119. {
  120. RefPtr<Memory::PhysicalPage> prp_dma_buffer;
  121. OwnPtr<Memory::Region> prp_dma_region;
  122. auto namespace_data_struct = ByteBuffer::create_zeroed(NVMe_IDENTIFY_SIZE).release_value();
  123. u32 active_namespace_list[NVMe_IDENTIFY_SIZE / sizeof(u32)];
  124. {
  125. auto buffer = TRY(MM.allocate_dma_buffer_page("Identify PRP", Memory::Region::Access::ReadWrite, prp_dma_buffer));
  126. prp_dma_region = move(buffer);
  127. }
  128. // Get the active namespace
  129. {
  130. NVMeSubmission sub {};
  131. u16 status = 0;
  132. sub.op = OP_ADMIN_IDENTIFY;
  133. sub.data_ptr.prp1 = reinterpret_cast<u64>(AK::convert_between_host_and_little_endian(prp_dma_buffer->paddr().as_ptr()));
  134. sub.cdw10 = NVMe_CNS_ID_ACTIVE_NS & 0xff;
  135. status = submit_admin_command(sub, true);
  136. if (status) {
  137. dmesgln("Failed to identify active namespace command");
  138. return EFAULT;
  139. }
  140. if (void* fault_at; !safe_memcpy(active_namespace_list, prp_dma_region->vaddr().as_ptr(), NVMe_IDENTIFY_SIZE, fault_at)) {
  141. return EFAULT;
  142. }
  143. }
  144. // Get the NAMESPACE attributes
  145. {
  146. NVMeSubmission sub {};
  147. IdentifyNamespace id_ns {};
  148. u16 status = 0;
  149. for (auto nsid : active_namespace_list) {
  150. memset(prp_dma_region->vaddr().as_ptr(), 0, NVMe_IDENTIFY_SIZE);
  151. // Invalid NS
  152. if (nsid == 0)
  153. break;
  154. sub.op = OP_ADMIN_IDENTIFY;
  155. sub.data_ptr.prp1 = reinterpret_cast<u64>(AK::convert_between_host_and_little_endian(prp_dma_buffer->paddr().as_ptr()));
  156. sub.cdw10 = NVMe_CNS_ID_NS & 0xff;
  157. sub.nsid = nsid;
  158. status = submit_admin_command(sub, true);
  159. if (status) {
  160. dmesgln("Failed identify namespace with nsid {}", nsid);
  161. return EFAULT;
  162. }
  163. static_assert(sizeof(IdentifyNamespace) == NVMe_IDENTIFY_SIZE);
  164. if (void* fault_at; !safe_memcpy(&id_ns, prp_dma_region->vaddr().as_ptr(), NVMe_IDENTIFY_SIZE, fault_at)) {
  165. return EFAULT;
  166. }
  167. auto val = get_ns_features(id_ns);
  168. auto block_counts = val.get<0>();
  169. auto block_size = 1 << val.get<1>();
  170. dbgln_if(NVME_DEBUG, "NVMe: Block count is {} and Block size is {}", block_counts, block_size);
  171. m_namespaces.append(TRY(NVMeNameSpace::try_create(m_queues, controller_id.load(), nsid, block_counts, block_size)));
  172. m_device_count++;
  173. dbgln_if(NVME_DEBUG, "NVMe: Initialized namespace with NSID: {}", nsid);
  174. }
  175. }
  176. return {};
  177. }
  178. UNMAP_AFTER_INIT Tuple<u64, u8> NVMeController::get_ns_features(IdentifyNamespace& identify_data_struct)
  179. {
  180. auto flbas = identify_data_struct.flbas & FLBA_SIZE_MASK;
  181. auto namespace_size = identify_data_struct.nsze;
  182. auto lba_format = identify_data_struct.lbaf[flbas];
  183. auto lba_size = (lba_format & LBA_SIZE_MASK) >> 16;
  184. return Tuple<u64, u8>(namespace_size, lba_size);
  185. }
  186. RefPtr<StorageDevice> NVMeController::device(u32 index) const
  187. {
  188. return m_namespaces.at(index);
  189. }
  190. size_t NVMeController::devices_count() const
  191. {
  192. return m_device_count;
  193. }
  194. bool NVMeController::reset()
  195. {
  196. if (!reset_controller())
  197. return false;
  198. if (!start_controller())
  199. return false;
  200. return true;
  201. }
  202. bool NVMeController::shutdown()
  203. {
  204. TODO();
  205. return false;
  206. }
  207. void NVMeController::complete_current_request([[maybe_unused]] AsyncDeviceRequest::RequestResult result)
  208. {
  209. VERIFY_NOT_REACHED();
  210. }
  211. UNMAP_AFTER_INIT ErrorOr<void> NVMeController::create_admin_queue(u8 irq)
  212. {
  213. auto qdepth = get_admin_q_dept();
  214. OwnPtr<Memory::Region> cq_dma_region;
  215. NonnullRefPtrVector<Memory::PhysicalPage> cq_dma_pages;
  216. OwnPtr<Memory::Region> sq_dma_region;
  217. NonnullRefPtrVector<Memory::PhysicalPage> sq_dma_pages;
  218. auto cq_size = round_up_to_power_of_two(CQ_SIZE(qdepth), 4096);
  219. auto sq_size = round_up_to_power_of_two(SQ_SIZE(qdepth), 4096);
  220. if (!reset_controller()) {
  221. dmesgln("Failed to reset the NVMe controller");
  222. return EFAULT;
  223. }
  224. {
  225. auto buffer = TRY(MM.allocate_dma_buffer_pages(cq_size, "Admin CQ queue", Memory::Region::Access::ReadWrite, cq_dma_pages));
  226. cq_dma_region = move(buffer);
  227. }
  228. // Phase bit is important to determine completion, so zero out the space
  229. // so that we don't get any garbage phase bit value
  230. memset(cq_dma_region->vaddr().as_ptr(), 0, cq_size);
  231. {
  232. auto buffer = TRY(MM.allocate_dma_buffer_pages(sq_size, "Admin SQ queue", Memory::Region::Access::ReadWrite, sq_dma_pages));
  233. sq_dma_region = move(buffer);
  234. }
  235. auto doorbell_regs = TRY(Memory::map_typed_writable<volatile DoorbellRegister>(PhysicalAddress(m_bar + REG_SQ0TDBL_START)));
  236. m_admin_queue = TRY(NVMeQueue::try_create(0, irq, qdepth, move(cq_dma_region), cq_dma_pages, move(sq_dma_region), sq_dma_pages, move(doorbell_regs)));
  237. m_controller_regs->acq = reinterpret_cast<u64>(AK::convert_between_host_and_little_endian(cq_dma_pages.first().paddr().as_ptr()));
  238. m_controller_regs->asq = reinterpret_cast<u64>(AK::convert_between_host_and_little_endian(sq_dma_pages.first().paddr().as_ptr()));
  239. if (!start_controller()) {
  240. dmesgln("Failed to restart the NVMe controller");
  241. return EFAULT;
  242. }
  243. set_admin_queue_ready_flag();
  244. m_admin_queue->enable_interrupts();
  245. dbgln_if(NVME_DEBUG, "NVMe: Admin queue created");
  246. return {};
  247. }
  248. UNMAP_AFTER_INIT ErrorOr<void> NVMeController::create_io_queue(u8 irq, u8 qid)
  249. {
  250. NVMeSubmission sub {};
  251. OwnPtr<Memory::Region> cq_dma_region;
  252. NonnullRefPtrVector<Memory::PhysicalPage> cq_dma_pages;
  253. OwnPtr<Memory::Region> sq_dma_region;
  254. NonnullRefPtrVector<Memory::PhysicalPage> sq_dma_pages;
  255. auto cq_size = round_up_to_power_of_two(CQ_SIZE(IO_QUEUE_SIZE), 4096);
  256. auto sq_size = round_up_to_power_of_two(SQ_SIZE(IO_QUEUE_SIZE), 4096);
  257. static_assert(sizeof(NVMeSubmission) == (1 << SQ_WIDTH));
  258. {
  259. auto buffer = TRY(MM.allocate_dma_buffer_pages(cq_size, "IO CQ queue", Memory::Region::Access::ReadWrite, cq_dma_pages));
  260. cq_dma_region = move(buffer);
  261. }
  262. // Phase bit is important to determine completion, so zero out the space
  263. // so that we don't get any garbage phase bit value
  264. memset(cq_dma_region->vaddr().as_ptr(), 0, cq_size);
  265. {
  266. auto buffer = TRY(MM.allocate_dma_buffer_pages(sq_size, "IO SQ queue", Memory::Region::Access::ReadWrite, sq_dma_pages));
  267. sq_dma_region = move(buffer);
  268. }
  269. {
  270. sub.op = OP_ADMIN_CREATE_COMPLETION_QUEUE;
  271. sub.data_ptr.prp1 = reinterpret_cast<u64>(AK::convert_between_host_and_little_endian(cq_dma_pages.first().paddr().as_ptr()));
  272. // The queue size is 0 based
  273. sub.cdw10 = AK::convert_between_host_and_little_endian(((IO_QUEUE_SIZE - 1) << 16 | qid));
  274. auto flags = QUEUE_IRQ_ENABLED | QUEUE_PHY_CONTIGUOUS;
  275. // TODO: Eventually move to MSI.
  276. // For now using pin based interrupts. Clear the first 16 bits
  277. // to use pin-based interrupts.
  278. sub.cdw11 = AK::convert_between_host_and_little_endian(flags & 0xFFFF);
  279. submit_admin_command(sub, true);
  280. }
  281. {
  282. sub.op = OP_ADMIN_CREATE_SUBMISSION_QUEUE;
  283. sub.data_ptr.prp1 = reinterpret_cast<u64>(AK::convert_between_host_and_little_endian(sq_dma_pages.first().paddr().as_ptr()));
  284. // The queue size is 0 based
  285. sub.cdw10 = AK::convert_between_host_and_little_endian(((IO_QUEUE_SIZE - 1) << 16 | qid));
  286. auto flags = QUEUE_IRQ_ENABLED | QUEUE_PHY_CONTIGUOUS;
  287. // The qid used below points to the completion queue qid
  288. sub.cdw11 = AK::convert_between_host_and_little_endian(qid << 16 | flags);
  289. submit_admin_command(sub, true);
  290. }
  291. auto queue_doorbell_offset = REG_SQ0TDBL_START + ((2 * qid) * (4 << m_dbl_stride));
  292. auto doorbell_regs = TRY(Memory::map_typed_writable<volatile DoorbellRegister>(PhysicalAddress(m_bar + queue_doorbell_offset)));
  293. m_queues.append(TRY(NVMeQueue::try_create(qid, irq, IO_QUEUE_SIZE, move(cq_dma_region), cq_dma_pages, move(sq_dma_region), sq_dma_pages, move(doorbell_regs))));
  294. m_queues.last().enable_interrupts();
  295. dbgln_if(NVME_DEBUG, "NVMe: Created IO Queue with QID{}", m_queues.size());
  296. return {};
  297. }
  298. }