StorageManagement.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  1. /*
  2. * Copyright (c) 2020-2022, Liav A. <liavalb@hotmail.co.il>
  3. * Copyright (c) 2022, the SerenityOS developers.
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/IterationDecision.h>
  8. #include <AK/Platform.h>
  9. #include <AK/Singleton.h>
  10. #include <AK/StringView.h>
  11. #include <AK/UUID.h>
  12. #if ARCH(I386) || ARCH(X86_64)
  13. # include <Kernel/Arch/x86/ISABus/IDEController.h>
  14. # include <Kernel/Arch/x86/PCI/IDELegacyModeController.h>
  15. #endif
  16. #include <Kernel/Bus/PCI/API.h>
  17. #include <Kernel/Bus/PCI/Access.h>
  18. #include <Kernel/Bus/PCI/Controller/VolumeManagementDevice.h>
  19. #include <Kernel/CommandLine.h>
  20. #include <Kernel/Devices/BlockDevice.h>
  21. #include <Kernel/Devices/DeviceManagement.h>
  22. #include <Kernel/FileSystem/Ext2FS/FileSystem.h>
  23. #include <Kernel/FileSystem/VirtualFileSystem.h>
  24. #include <Kernel/Panic.h>
  25. #include <Kernel/Storage/ATA/AHCI/Controller.h>
  26. #include <Kernel/Storage/ATA/GenericIDE/Controller.h>
  27. #include <Kernel/Storage/NVMe/NVMeController.h>
  28. #include <Kernel/Storage/StorageManagement.h>
  29. #include <LibPartition/EBRPartitionTable.h>
  30. #include <LibPartition/GUIDPartitionTable.h>
  31. #include <LibPartition/MBRPartitionTable.h>
  32. namespace Kernel {
  33. static Singleton<StorageManagement> s_the;
  34. static Atomic<u32> s_storage_device_minor_number;
  35. static Atomic<u32> s_partition_device_minor_number;
  36. static Atomic<u32> s_controller_id;
  37. static Atomic<u32> s_relative_ata_controller_id;
  38. static Atomic<u32> s_relative_nvme_controller_id;
  39. static constexpr StringView partition_uuid_prefix = "PARTUUID:"sv;
  40. static constexpr StringView partition_number_prefix = "part"sv;
  41. static constexpr StringView block_device_prefix = "block"sv;
  42. static constexpr StringView ata_device_prefix = "ata"sv;
  43. static constexpr StringView nvme_device_prefix = "nvme"sv;
  44. static constexpr StringView logical_unit_number_device_prefix = "lun"sv;
  45. UNMAP_AFTER_INIT StorageManagement::StorageManagement()
  46. {
  47. }
  48. u32 StorageManagement::generate_relative_nvme_controller_id(Badge<NVMeController>)
  49. {
  50. auto controller_id = s_relative_nvme_controller_id.load();
  51. s_relative_nvme_controller_id++;
  52. return controller_id;
  53. }
  54. u32 StorageManagement::generate_relative_ata_controller_id(Badge<ATAController>)
  55. {
  56. auto controller_id = s_relative_ata_controller_id.load();
  57. s_relative_ata_controller_id++;
  58. return controller_id;
  59. }
  60. void StorageManagement::remove_device(StorageDevice& device)
  61. {
  62. m_storage_devices.remove(device);
  63. }
  64. UNMAP_AFTER_INIT void StorageManagement::enumerate_pci_controllers(bool force_pio, bool nvme_poll)
  65. {
  66. VERIFY(m_controllers.is_empty());
  67. using SubclassID = PCI::MassStorage::SubclassID;
  68. if (!kernel_command_line().disable_physical_storage()) {
  69. MUST(PCI::enumerate([&](PCI::DeviceIdentifier const& device_identifier) -> void {
  70. if (device_identifier.class_code().value() != to_underlying(PCI::ClassID::MassStorage)) {
  71. return;
  72. }
  73. {
  74. constexpr PCI::HardwareID vmd_device = { 0x8086, 0x9a0b };
  75. if (device_identifier.hardware_id() == vmd_device) {
  76. auto controller = PCI::VolumeManagementDevice::must_create(device_identifier);
  77. MUST(PCI::Access::the().add_host_controller_and_enumerate_attached_devices(move(controller), [this, nvme_poll](PCI::DeviceIdentifier const& device_identifier) -> void {
  78. auto subclass_code = static_cast<SubclassID>(device_identifier.subclass_code().value());
  79. if (subclass_code == SubclassID::NVMeController) {
  80. auto controller = NVMeController::try_initialize(device_identifier, nvme_poll);
  81. if (controller.is_error()) {
  82. dmesgln("Unable to initialize NVMe controller: {}", controller.error());
  83. } else {
  84. m_controllers.append(controller.release_value());
  85. }
  86. }
  87. }));
  88. }
  89. }
  90. auto subclass_code = static_cast<SubclassID>(device_identifier.subclass_code().value());
  91. #if ARCH(I386) || ARCH(X86_64)
  92. if (subclass_code == SubclassID::IDEController && kernel_command_line().is_ide_enabled()) {
  93. m_controllers.append(PCIIDELegacyModeController::initialize(device_identifier, force_pio));
  94. }
  95. #elif ARCH(AARCH64)
  96. (void)force_pio;
  97. TODO_AARCH64();
  98. #else
  99. # error Unknown architecture
  100. #endif
  101. if (subclass_code == SubclassID::SATAController
  102. && device_identifier.prog_if().value() == to_underlying(PCI::MassStorage::SATAProgIF::AHCI)) {
  103. m_controllers.append(AHCIController::initialize(device_identifier));
  104. }
  105. if (subclass_code == SubclassID::NVMeController) {
  106. auto controller = NVMeController::try_initialize(device_identifier, nvme_poll);
  107. if (controller.is_error()) {
  108. dmesgln("Unable to initialize NVMe controller: {}", controller.error());
  109. } else {
  110. m_controllers.append(controller.release_value());
  111. }
  112. }
  113. }));
  114. }
  115. }
  116. UNMAP_AFTER_INIT void StorageManagement::enumerate_storage_devices()
  117. {
  118. VERIFY(!m_controllers.is_empty());
  119. for (auto& controller : m_controllers) {
  120. for (size_t device_index = 0; device_index < controller.devices_count(); device_index++) {
  121. auto device = controller.device(device_index);
  122. if (device.is_null())
  123. continue;
  124. m_storage_devices.append(device.release_nonnull());
  125. }
  126. }
  127. }
  128. UNMAP_AFTER_INIT void StorageManagement::dump_storage_devices_and_partitions() const
  129. {
  130. dbgln("StorageManagement: Detected {} storage devices", m_storage_devices.size_slow());
  131. for (auto const& storage_device : m_storage_devices) {
  132. auto const& partitions = storage_device.partitions();
  133. if (partitions.is_empty()) {
  134. dbgln(" Device: block{}:{} (no partitions)", storage_device.major(), storage_device.minor());
  135. } else {
  136. dbgln(" Device: block{}:{} ({} partitions)", storage_device.major(), storage_device.minor(), partitions.size());
  137. unsigned partition_number = 1;
  138. for (auto const& partition : partitions) {
  139. dbgln(" Partition: {}, block{}:{} (UUID {})", partition_number, partition.major(), partition.minor(), partition.metadata().unique_guid().to_string());
  140. partition_number++;
  141. }
  142. }
  143. }
  144. }
  145. UNMAP_AFTER_INIT ErrorOr<NonnullOwnPtr<Partition::PartitionTable>> StorageManagement::try_to_initialize_partition_table(StorageDevice const& device) const
  146. {
  147. auto mbr_table_or_error = Partition::MBRPartitionTable::try_to_initialize(device);
  148. if (!mbr_table_or_error.is_error())
  149. return mbr_table_or_error.release_value();
  150. auto ebr_table_or_error = Partition::EBRPartitionTable::try_to_initialize(device);
  151. if (!ebr_table_or_error.is_error()) {
  152. return ebr_table_or_error.release_value();
  153. }
  154. return TRY(Partition::GUIDPartitionTable::try_to_initialize(device));
  155. }
  156. UNMAP_AFTER_INIT void StorageManagement::enumerate_disk_partitions()
  157. {
  158. VERIFY(!m_storage_devices.is_empty());
  159. for (auto& device : m_storage_devices) {
  160. auto partition_table_or_error = try_to_initialize_partition_table(device);
  161. if (partition_table_or_error.is_error())
  162. continue;
  163. auto partition_table = partition_table_or_error.release_value();
  164. for (size_t partition_index = 0; partition_index < partition_table->partitions_count(); partition_index++) {
  165. auto partition_metadata = partition_table->partition(partition_index);
  166. if (!partition_metadata.has_value())
  167. continue;
  168. auto disk_partition = DiskPartition::create(device, generate_partition_minor_number(), partition_metadata.value());
  169. device.add_partition(disk_partition);
  170. }
  171. }
  172. }
  173. UNMAP_AFTER_INIT Optional<unsigned> StorageManagement::extract_boot_device_partition_number_parameter(StringView device_prefix)
  174. {
  175. VERIFY(m_boot_argument.starts_with(device_prefix));
  176. VERIFY(!m_boot_argument.starts_with(partition_uuid_prefix));
  177. auto storage_device_relative_address_view = m_boot_argument.substring_view(device_prefix.length());
  178. auto parameter_view = storage_device_relative_address_view.find_last_split_view(';');
  179. if (parameter_view == storage_device_relative_address_view)
  180. return {};
  181. if (!parameter_view.starts_with(partition_number_prefix)) {
  182. PANIC("StorageManagement: Invalid root boot parameter.");
  183. }
  184. auto parameter_number = parameter_view.substring_view(partition_number_prefix.length()).to_uint<unsigned>();
  185. if (!parameter_number.has_value()) {
  186. PANIC("StorageManagement: Invalid root boot parameter.");
  187. }
  188. return parameter_number.value();
  189. }
  190. UNMAP_AFTER_INIT Array<unsigned, 3> StorageManagement::extract_boot_device_address_parameters(StringView device_prefix)
  191. {
  192. VERIFY(!m_boot_argument.starts_with(partition_uuid_prefix));
  193. Array<unsigned, 3> address_parameters;
  194. auto parameters_view = m_boot_argument.substring_view(device_prefix.length()).find_first_split_view(';');
  195. size_t parts_count = 0;
  196. bool parse_failure = false;
  197. parameters_view.for_each_split_view(':', SplitBehavior::Nothing, [&](StringView parameter_view) {
  198. if (parse_failure)
  199. return;
  200. if (parts_count > 2)
  201. return;
  202. auto parameter_number = parameter_view.to_uint<unsigned>();
  203. if (!parameter_number.has_value()) {
  204. parse_failure = true;
  205. return;
  206. }
  207. address_parameters[parts_count] = parameter_number.value();
  208. parts_count++;
  209. });
  210. if (parts_count > 3) {
  211. dbgln("StorageManagement: Detected {} parts in boot device parameter.", parts_count);
  212. PANIC("StorageManagement: Invalid root boot parameter.");
  213. }
  214. if (parse_failure) {
  215. PANIC("StorageManagement: Invalid root boot parameter.");
  216. }
  217. return address_parameters;
  218. }
  219. UNMAP_AFTER_INIT void StorageManagement::resolve_partition_from_boot_device_parameter(StorageDevice const& chosen_storage_device, StringView boot_device_prefix)
  220. {
  221. auto possible_partition_number = extract_boot_device_partition_number_parameter(boot_device_prefix);
  222. if (!possible_partition_number.has_value())
  223. return;
  224. auto partition_number = possible_partition_number.value();
  225. if (chosen_storage_device.partitions().size() <= partition_number)
  226. PANIC("StorageManagement: Invalid partition number parameter.");
  227. m_boot_block_device = chosen_storage_device.partitions()[partition_number];
  228. }
  229. UNMAP_AFTER_INIT void StorageManagement::determine_hardware_relative_boot_device(StringView relative_hardware_prefix, Function<bool(StorageDevice const&)> filter_device_callback)
  230. {
  231. VERIFY(m_boot_argument.starts_with(relative_hardware_prefix));
  232. auto address_parameters = extract_boot_device_address_parameters(relative_hardware_prefix);
  233. RefPtr<StorageDevice> chosen_storage_device;
  234. for (auto& storage_device : m_storage_devices) {
  235. if (!filter_device_callback(storage_device))
  236. continue;
  237. auto storage_device_lun = storage_device.logical_unit_number_address();
  238. if (storage_device.parent_controller_hardware_relative_id() == address_parameters[0]
  239. && storage_device_lun.target_id == address_parameters[1]
  240. && storage_device_lun.disk_id == address_parameters[2]) {
  241. m_boot_block_device = storage_device;
  242. chosen_storage_device = storage_device;
  243. break;
  244. }
  245. }
  246. if (chosen_storage_device)
  247. resolve_partition_from_boot_device_parameter(*chosen_storage_device, relative_hardware_prefix);
  248. }
  249. UNMAP_AFTER_INIT void StorageManagement::determine_ata_boot_device()
  250. {
  251. determine_hardware_relative_boot_device(ata_device_prefix, [](StorageDevice const& device) -> bool {
  252. return device.command_set() == StorageDevice::CommandSet::ATA;
  253. });
  254. }
  255. UNMAP_AFTER_INIT void StorageManagement::determine_nvme_boot_device()
  256. {
  257. determine_hardware_relative_boot_device(nvme_device_prefix, [](StorageDevice const& device) -> bool {
  258. return device.command_set() == StorageDevice::CommandSet::NVMe;
  259. });
  260. }
  261. UNMAP_AFTER_INIT void StorageManagement::determine_block_boot_device()
  262. {
  263. VERIFY(m_boot_argument.starts_with(block_device_prefix));
  264. auto parameters_view = extract_boot_device_address_parameters(block_device_prefix);
  265. // Note: We simply fetch the corresponding BlockDevice with the major and minor parameters.
  266. // We don't try to accept and resolve a partition number as it will make this code much more
  267. // complicated. This rule is also explained in the boot_device_addressing(7) manual page.
  268. LockRefPtr<Device> device = DeviceManagement::the().get_device(parameters_view[0], parameters_view[1]);
  269. if (device && device->is_block_device())
  270. m_boot_block_device = static_ptr_cast<BlockDevice>(device);
  271. }
  272. UNMAP_AFTER_INIT void StorageManagement::determine_boot_device_with_logical_unit_number()
  273. {
  274. VERIFY(m_boot_argument.starts_with(logical_unit_number_device_prefix));
  275. auto address_parameters = extract_boot_device_address_parameters(logical_unit_number_device_prefix);
  276. RefPtr<StorageDevice> chosen_storage_device;
  277. for (auto& storage_device : m_storage_devices) {
  278. auto storage_device_lun = storage_device.logical_unit_number_address();
  279. if (storage_device_lun.controller_id == address_parameters[0]
  280. && storage_device_lun.target_id == address_parameters[1]
  281. && storage_device_lun.disk_id == address_parameters[2]) {
  282. m_boot_block_device = storage_device;
  283. chosen_storage_device = storage_device;
  284. break;
  285. }
  286. }
  287. if (chosen_storage_device)
  288. resolve_partition_from_boot_device_parameter(*chosen_storage_device, logical_unit_number_device_prefix);
  289. }
  290. UNMAP_AFTER_INIT void StorageManagement::determine_boot_device()
  291. {
  292. VERIFY(!m_controllers.is_empty());
  293. if (m_boot_argument.starts_with(block_device_prefix)) {
  294. determine_block_boot_device();
  295. return;
  296. }
  297. if (m_boot_argument.starts_with(partition_uuid_prefix)) {
  298. determine_boot_device_with_partition_uuid();
  299. return;
  300. }
  301. if (m_boot_argument.starts_with(logical_unit_number_device_prefix)) {
  302. determine_boot_device_with_logical_unit_number();
  303. return;
  304. }
  305. if (m_boot_argument.starts_with(ata_device_prefix)) {
  306. determine_ata_boot_device();
  307. return;
  308. }
  309. if (m_boot_argument.starts_with(nvme_device_prefix)) {
  310. determine_nvme_boot_device();
  311. return;
  312. }
  313. PANIC("StorageManagement: Invalid root boot parameter.");
  314. }
  315. UNMAP_AFTER_INIT void StorageManagement::determine_boot_device_with_partition_uuid()
  316. {
  317. VERIFY(!m_storage_devices.is_empty());
  318. VERIFY(m_boot_argument.starts_with(partition_uuid_prefix));
  319. auto partition_uuid = UUID(m_boot_argument.substring_view(partition_uuid_prefix.length()), UUID::Endianness::Mixed);
  320. for (auto& storage_device : m_storage_devices) {
  321. for (auto& partition : storage_device.partitions()) {
  322. if (partition.metadata().unique_guid().is_zero())
  323. continue;
  324. if (partition.metadata().unique_guid() == partition_uuid) {
  325. m_boot_block_device = partition;
  326. break;
  327. }
  328. }
  329. }
  330. }
  331. LockRefPtr<BlockDevice> StorageManagement::boot_block_device() const
  332. {
  333. return m_boot_block_device.strong_ref();
  334. }
  335. MajorNumber StorageManagement::storage_type_major_number()
  336. {
  337. return 3;
  338. }
  339. MinorNumber StorageManagement::generate_storage_minor_number()
  340. {
  341. return s_storage_device_minor_number.fetch_add(1);
  342. }
  343. MinorNumber StorageManagement::generate_partition_minor_number()
  344. {
  345. return s_partition_device_minor_number.fetch_add(1);
  346. }
  347. u32 StorageManagement::generate_controller_id()
  348. {
  349. return s_controller_id.fetch_add(1);
  350. }
  351. NonnullLockRefPtr<FileSystem> StorageManagement::root_filesystem() const
  352. {
  353. auto boot_device_description = boot_block_device();
  354. if (!boot_device_description) {
  355. dump_storage_devices_and_partitions();
  356. PANIC("StorageManagement: Couldn't find a suitable device to boot from");
  357. }
  358. auto description_or_error = OpenFileDescription::try_create(boot_device_description.release_nonnull());
  359. VERIFY(!description_or_error.is_error());
  360. auto file_system = Ext2FS::try_create(description_or_error.release_value()).release_value();
  361. if (auto result = file_system->initialize(); result.is_error()) {
  362. dump_storage_devices_and_partitions();
  363. PANIC("StorageManagement: Couldn't open root filesystem: {}", result.error());
  364. }
  365. return file_system;
  366. }
  367. UNMAP_AFTER_INIT void StorageManagement::initialize(StringView root_device, bool force_pio, bool poll)
  368. {
  369. VERIFY(s_storage_device_minor_number == 0);
  370. m_boot_argument = root_device;
  371. if (PCI::Access::is_disabled()) {
  372. #if ARCH(I386) || ARCH(X86_64)
  373. // Note: If PCI is disabled, we assume that at least we have an ISA IDE controller
  374. // to probe and use
  375. m_controllers.append(ISAIDEController::initialize());
  376. #endif
  377. } else {
  378. enumerate_pci_controllers(force_pio, poll);
  379. }
  380. enumerate_storage_devices();
  381. enumerate_disk_partitions();
  382. determine_boot_device();
  383. if (m_boot_block_device.is_null()) {
  384. dump_storage_devices_and_partitions();
  385. PANIC("StorageManagement: boot device {} not found", m_boot_argument);
  386. }
  387. }
  388. StorageManagement& StorageManagement::the()
  389. {
  390. return *s_the;
  391. }
  392. }