NVMeController.cpp 13 KB

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