StorageManagement.cpp 20 KB

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