NVMeController.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  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. IO::delay(10);
  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. IO::delay(10);
  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 = ByteBuffer::create_zeroed(NVMe_IDENTIFY_SIZE).release_value();
  125. u32 active_namespace_list[NVMe_IDENTIFY_SIZE / sizeof(u32)];
  126. {
  127. auto buffer = TRY(MM.allocate_dma_buffer_page("Identify PRP", 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.data_ptr.prp1 = reinterpret_cast<u64>(AK::convert_between_host_and_little_endian(prp_dma_buffer->paddr().as_ptr()));
  136. sub.cdw10 = NVMe_CNS_ID_ACTIVE_NS & 0xff;
  137. status = submit_admin_command(sub, true);
  138. if (status) {
  139. dmesgln("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.data_ptr.prp1 = reinterpret_cast<u64>(AK::convert_between_host_and_little_endian(prp_dma_buffer->paddr().as_ptr()));
  158. sub.cdw10 = NVMe_CNS_ID_NS & 0xff;
  159. sub.nsid = nsid;
  160. status = submit_admin_command(sub, true);
  161. if (status) {
  162. dmesgln("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(m_queues, controller_id.load(), 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. RefPtr<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(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("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", 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", Memory::Region::Access::ReadWrite, sq_dma_pages));
  235. sq_dma_region = move(buffer);
  236. }
  237. auto doorbell_regs = TRY(Memory::map_typed_writable<volatile DoorbellRegister>(PhysicalAddress(m_bar + REG_SQ0TDBL_START)));
  238. 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)));
  239. m_controller_regs->acq = reinterpret_cast<u64>(AK::convert_between_host_and_little_endian(cq_dma_pages.first().paddr().as_ptr()));
  240. m_controller_regs->asq = reinterpret_cast<u64>(AK::convert_between_host_and_little_endian(sq_dma_pages.first().paddr().as_ptr()));
  241. if (!start_controller()) {
  242. dmesgln("Failed to restart the NVMe controller");
  243. return EFAULT;
  244. }
  245. set_admin_queue_ready_flag();
  246. m_admin_queue->enable_interrupts();
  247. dbgln_if(NVME_DEBUG, "NVMe: Admin queue created");
  248. return {};
  249. }
  250. UNMAP_AFTER_INIT ErrorOr<void> NVMeController::create_io_queue(u8 irq, u8 qid)
  251. {
  252. NVMeSubmission sub {};
  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. static_assert(sizeof(NVMeSubmission) == (1 << SQ_WIDTH));
  260. {
  261. auto buffer = TRY(MM.allocate_dma_buffer_pages(cq_size, "IO CQ queue", Memory::Region::Access::ReadWrite, cq_dma_pages));
  262. cq_dma_region = move(buffer);
  263. }
  264. // Phase bit is important to determine completion, so zero out the space
  265. // so that we don't get any garbage phase bit value
  266. memset(cq_dma_region->vaddr().as_ptr(), 0, cq_size);
  267. {
  268. auto buffer = TRY(MM.allocate_dma_buffer_pages(sq_size, "IO SQ queue", Memory::Region::Access::ReadWrite, sq_dma_pages));
  269. sq_dma_region = move(buffer);
  270. }
  271. {
  272. sub.op = OP_ADMIN_CREATE_COMPLETION_QUEUE;
  273. sub.data_ptr.prp1 = reinterpret_cast<u64>(AK::convert_between_host_and_little_endian(cq_dma_pages.first().paddr().as_ptr()));
  274. // The queue size is 0 based
  275. sub.cdw10 = AK::convert_between_host_and_little_endian(((IO_QUEUE_SIZE - 1) << 16 | qid));
  276. auto flags = QUEUE_IRQ_ENABLED | 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.cdw11 = AK::convert_between_host_and_little_endian(flags & 0xFFFF);
  281. submit_admin_command(sub, true);
  282. }
  283. {
  284. sub.op = OP_ADMIN_CREATE_SUBMISSION_QUEUE;
  285. sub.data_ptr.prp1 = reinterpret_cast<u64>(AK::convert_between_host_and_little_endian(sq_dma_pages.first().paddr().as_ptr()));
  286. // The queue size is 0 based
  287. sub.cdw10 = AK::convert_between_host_and_little_endian(((IO_QUEUE_SIZE - 1) << 16 | qid));
  288. auto flags = QUEUE_IRQ_ENABLED | QUEUE_PHY_CONTIGUOUS;
  289. // The qid used below points to the completion queue qid
  290. sub.cdw11 = AK::convert_between_host_and_little_endian(qid << 16 | flags);
  291. submit_admin_command(sub, true);
  292. }
  293. auto queue_doorbell_offset = REG_SQ0TDBL_START + ((2 * qid) * (4 << m_dbl_stride));
  294. auto doorbell_regs = TRY(Memory::map_typed_writable<volatile DoorbellRegister>(PhysicalAddress(m_bar + queue_doorbell_offset)));
  295. 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))));
  296. m_queues.last().enable_interrupts();
  297. dbgln_if(NVME_DEBUG, "NVMe: Created IO Queue with QID{}", m_queues.size());
  298. return {};
  299. }
  300. }