StorageManagement.cpp 18 KB

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