StorageManagement.cpp 20 KB

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