NVMeController.cpp 13 KB

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