NVMeController.cpp 13 KB

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