VirtualFileSystem.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618
  1. #include "VirtualFileSystem.h"
  2. #include "FileDescriptor.h"
  3. #include "FileSystem.h"
  4. #include <AK/StringBuilder.h>
  5. #include <AK/kmalloc.h>
  6. #include <AK/kstdio.h>
  7. #include <AK/ktime.h>
  8. #include "CharacterDevice.h"
  9. #include <LibC/errno_numbers.h>
  10. //#define VFS_DEBUG
  11. static VirtualFileSystem* s_the;
  12. #ifndef SERENITY
  13. typedef int InterruptDisabler;
  14. #endif
  15. VirtualFileSystem& VirtualFileSystem::the()
  16. {
  17. ASSERT(s_the);
  18. return *s_the;
  19. }
  20. void VirtualFileSystem::initializeGlobals()
  21. {
  22. s_the = nullptr;
  23. FileSystem::initializeGlobals();
  24. }
  25. VirtualFileSystem::VirtualFileSystem()
  26. {
  27. #ifdef VFS_DEBUG
  28. kprintf("VFS: Constructing VFS\n");
  29. #endif
  30. s_the = this;
  31. m_maxNodeCount = 16;
  32. m_nodes = reinterpret_cast<Node*>(kmalloc(sizeof(Node) * maxNodeCount()));
  33. memset(m_nodes, 0, sizeof(Node) * maxNodeCount());
  34. for (unsigned i = 0; i < m_maxNodeCount; ++i)
  35. m_nodeFreeList.append(&m_nodes[i]);
  36. }
  37. VirtualFileSystem::~VirtualFileSystem()
  38. {
  39. kprintf("VFS: ~VirtualFileSystem with %u nodes allocated\n", allocatedNodeCount());
  40. // FIXME: m_nodes is never freed. Does it matter though?
  41. }
  42. auto VirtualFileSystem::makeNode(InodeIdentifier inode) -> RetainPtr<Node>
  43. {
  44. auto metadata = inode.metadata();
  45. if (!metadata.isValid())
  46. return nullptr;
  47. auto core_inode = inode.fileSystem()->get_inode(inode);
  48. if (core_inode)
  49. core_inode->m_metadata = metadata;
  50. InterruptDisabler disabler;
  51. CharacterDevice* characterDevice = nullptr;
  52. if (metadata.isCharacterDevice()) {
  53. auto it = m_characterDevices.find(encodedDevice(metadata.majorDevice, metadata.minorDevice));
  54. if (it != m_characterDevices.end()) {
  55. characterDevice = (*it).value;
  56. } else {
  57. kprintf("VFS: makeNode() no such character device %u,%u\n", metadata.majorDevice, metadata.minorDevice);
  58. return nullptr;
  59. }
  60. }
  61. auto vnode = allocateNode();
  62. ASSERT(vnode);
  63. FileSystem* fileSystem = inode.fileSystem();
  64. fileSystem->retain();
  65. vnode->inode = inode;
  66. vnode->m_core_inode = move(core_inode);
  67. vnode->m_cachedMetadata = metadata;
  68. #ifdef VFS_DEBUG
  69. kprintf("makeNode: inode=%u, size=%u, mode=%o, uid=%u, gid=%u\n", inode.index(), metadata.size, metadata.mode, metadata.uid, metadata.gid);
  70. #endif
  71. m_inode2vnode.set(inode, vnode.ptr());
  72. vnode->m_characterDevice = characterDevice;
  73. return vnode;
  74. }
  75. auto VirtualFileSystem::makeNode(CharacterDevice& device) -> RetainPtr<Node>
  76. {
  77. InterruptDisabler disabler;
  78. auto vnode = allocateNode();
  79. ASSERT(vnode);
  80. #ifdef VFS_DEBUG
  81. kprintf("makeNode: device=%p (%u,%u)\n", &device, device.major(), device.minor());
  82. #endif
  83. m_device2vnode.set(encodedDevice(device.major(), device.minor()), vnode.ptr());
  84. vnode->m_characterDevice = &device;
  85. return vnode;
  86. }
  87. auto VirtualFileSystem::getOrCreateNode(InodeIdentifier inode) -> RetainPtr<Node>
  88. {
  89. {
  90. InterruptDisabler disabler;
  91. auto it = m_inode2vnode.find(inode);
  92. if (it != m_inode2vnode.end())
  93. return (*it).value;
  94. }
  95. return makeNode(inode);
  96. }
  97. auto VirtualFileSystem::getOrCreateNode(CharacterDevice& device) -> RetainPtr<Node>
  98. {
  99. {
  100. InterruptDisabler disabler;
  101. auto it = m_device2vnode.find(encodedDevice(device.major(), device.minor()));
  102. if (it != m_device2vnode.end())
  103. return (*it).value;
  104. }
  105. return makeNode(device);
  106. }
  107. bool VirtualFileSystem::mount(RetainPtr<FileSystem>&& fileSystem, const String& path)
  108. {
  109. ASSERT(fileSystem);
  110. int error;
  111. auto inode = resolvePath(path, error);
  112. if (!inode.isValid()) {
  113. kprintf("VFS: mount can't resolve mount point '%s'\n", path.characters());
  114. return false;
  115. }
  116. kprintf("VFS: mounting %s{%p} at %s (inode: %u)\n", fileSystem->className(), fileSystem.ptr(), path.characters(), inode.index());
  117. // FIXME: check that this is not already a mount point
  118. auto mount = make<Mount>(inode, move(fileSystem));
  119. m_mounts.append(move(mount));
  120. return true;
  121. }
  122. bool VirtualFileSystem::mountRoot(RetainPtr<FileSystem>&& fileSystem)
  123. {
  124. if (m_rootNode) {
  125. kprintf("VFS: mountRoot can't mount another root\n");
  126. return false;
  127. }
  128. auto mount = make<Mount>(InodeIdentifier(), move(fileSystem));
  129. auto node = makeNode(mount->guest());
  130. if (!node->inUse()) {
  131. kprintf("VFS: root inode for / is not in use :(\n");
  132. return false;
  133. }
  134. if (!node->metadata().isDirectory()) {
  135. kprintf("VFS: root inode for / is not a directory :(\n");
  136. return false;
  137. }
  138. m_rootNode = move(node);
  139. kprintf("VFS: mounted root on %s{%p}\n",
  140. m_rootNode->fileSystem()->className(),
  141. m_rootNode->fileSystem());
  142. m_mounts.append(move(mount));
  143. return true;
  144. }
  145. auto VirtualFileSystem::allocateNode() -> RetainPtr<Node>
  146. {
  147. if (m_nodeFreeList.isEmpty()) {
  148. kprintf("VFS: allocateNode has no nodes left\n");
  149. return nullptr;
  150. }
  151. auto* node = m_nodeFreeList.takeLast();
  152. ASSERT(node->retainCount == 0);
  153. node->retainCount = 1;
  154. node->m_vfs = this;
  155. node->m_vmo = nullptr;
  156. return adopt(*node);
  157. }
  158. void VirtualFileSystem::freeNode(Node* node)
  159. {
  160. InterruptDisabler disabler;
  161. ASSERT(node);
  162. ASSERT(node->inUse());
  163. if (node->inode.isValid()) {
  164. m_inode2vnode.remove(node->inode);
  165. node->inode.fileSystem()->release();
  166. node->inode = InodeIdentifier();
  167. }
  168. if (node->m_characterDevice) {
  169. m_device2vnode.remove(encodedDevice(node->m_characterDevice->major(), node->m_characterDevice->minor()));
  170. node->m_characterDevice = nullptr;
  171. }
  172. node->m_vfs = nullptr;
  173. node->m_vmo = nullptr;
  174. m_nodeFreeList.append(move(node));
  175. }
  176. #ifndef SERENITY
  177. bool VirtualFileSystem::isDirectory(const String& path, InodeIdentifier base)
  178. {
  179. int error;
  180. auto inode = resolvePath(path, error, base);
  181. if (!inode.isValid())
  182. return false;
  183. return inode.metadata().isDirectory();
  184. }
  185. #endif
  186. auto VirtualFileSystem::findMountForHost(InodeIdentifier inode) -> Mount*
  187. {
  188. for (auto& mount : m_mounts) {
  189. if (mount->host() == inode)
  190. return mount.ptr();
  191. }
  192. return nullptr;
  193. }
  194. auto VirtualFileSystem::findMountForGuest(InodeIdentifier inode) -> Mount*
  195. {
  196. for (auto& mount : m_mounts) {
  197. if (mount->guest() == inode)
  198. return mount.ptr();
  199. }
  200. return nullptr;
  201. }
  202. bool VirtualFileSystem::isRoot(InodeIdentifier inode) const
  203. {
  204. return inode == m_rootNode->inode;
  205. }
  206. void VirtualFileSystem::enumerateDirectoryInode(InodeIdentifier directoryInode, Function<bool(const FileSystem::DirectoryEntry&)> callback)
  207. {
  208. if (!directoryInode.isValid())
  209. return;
  210. directoryInode.fileSystem()->enumerateDirectoryInode(directoryInode, [&] (const FileSystem::DirectoryEntry& entry) {
  211. InodeIdentifier resolvedInode;
  212. if (auto mount = findMountForHost(entry.inode))
  213. resolvedInode = mount->guest();
  214. else
  215. resolvedInode = entry.inode;
  216. if (directoryInode.isRootInode() && !isRoot(directoryInode) && !strcmp(entry.name, "..")) {
  217. auto mount = findMountForGuest(entry.inode);
  218. ASSERT(mount);
  219. resolvedInode = mount->host();
  220. }
  221. callback(FileSystem::DirectoryEntry(entry.name, entry.name_length, resolvedInode, entry.fileType));
  222. return true;
  223. });
  224. }
  225. #ifndef SERENITY
  226. void VirtualFileSystem::listDirectory(const String& path, InodeIdentifier base)
  227. {
  228. int error;
  229. auto directoryInode = resolvePath(path, error, base);
  230. if (!directoryInode.isValid())
  231. return;
  232. kprintf("VFS: ls %s -> %s %02u:%08u\n", path.characters(), directoryInode.fileSystem()->className(), directoryInode.fileSystemID(), directoryInode.index());
  233. enumerateDirectoryInode(directoryInode, [&] (const FileSystem::DirectoryEntry& entry) {
  234. const char* nameColorBegin = "";
  235. const char* nameColorEnd = "";
  236. auto metadata = entry.inode.metadata();
  237. ASSERT(metadata.isValid());
  238. if (metadata.isDirectory()) {
  239. nameColorBegin = "\033[34;1m";
  240. nameColorEnd = "\033[0m";
  241. } else if (metadata.isSymbolicLink()) {
  242. nameColorBegin = "\033[36;1m";
  243. nameColorEnd = "\033[0m";
  244. }
  245. if (metadata.isSticky()) {
  246. nameColorBegin = "\033[42;30m";
  247. nameColorEnd = "\033[0m";
  248. }
  249. if (metadata.isCharacterDevice() || metadata.isBlockDevice()) {
  250. nameColorBegin = "\033[33;1m";
  251. nameColorEnd = "\033[0m";
  252. }
  253. kprintf("%02u:%08u ",
  254. metadata.inode.fileSystemID(),
  255. metadata.inode.index());
  256. if (metadata.isDirectory())
  257. kprintf("d");
  258. else if (metadata.isSymbolicLink())
  259. kprintf("l");
  260. else if (metadata.isBlockDevice())
  261. kprintf("b");
  262. else if (metadata.isCharacterDevice())
  263. kprintf("c");
  264. else if (metadata.isSocket())
  265. kprintf("s");
  266. else if (metadata.isFIFO())
  267. kprintf("f");
  268. else if (metadata.isRegularFile())
  269. kprintf("-");
  270. else
  271. kprintf("?");
  272. kprintf("%c%c%c%c%c%c%c%c",
  273. metadata.mode & 00400 ? 'r' : '-',
  274. metadata.mode & 00200 ? 'w' : '-',
  275. metadata.mode & 00100 ? 'x' : '-',
  276. metadata.mode & 00040 ? 'r' : '-',
  277. metadata.mode & 00020 ? 'w' : '-',
  278. metadata.mode & 00010 ? 'x' : '-',
  279. metadata.mode & 00004 ? 'r' : '-',
  280. metadata.mode & 00002 ? 'w' : '-'
  281. );
  282. if (metadata.isSticky())
  283. kprintf("t");
  284. else
  285. kprintf("%c", metadata.mode & 00001 ? 'x' : '-');
  286. if (metadata.isCharacterDevice() || metadata.isBlockDevice()) {
  287. char buf[16];
  288. ksprintf(buf, "%u, %u", metadata.majorDevice, metadata.minorDevice);
  289. kprintf("%12s ", buf);
  290. } else {
  291. kprintf("%12lld ", metadata.size);
  292. }
  293. kprintf("\033[30;1m");
  294. time_t mtime = metadata.mtime;
  295. auto tm = *klocaltime(&mtime);
  296. kprintf("%04u-%02u-%02u %02u:%02u:%02u ",
  297. tm.tm_year + 1900,
  298. tm.tm_mon + 1,
  299. tm.tm_mday,
  300. tm.tm_hour,
  301. tm.tm_min,
  302. tm.tm_sec);
  303. kprintf("\033[0m");
  304. kprintf("%s%s%s",
  305. nameColorBegin,
  306. entry.name,
  307. nameColorEnd);
  308. if (metadata.isDirectory()) {
  309. kprintf("/");
  310. } else if (metadata.isSymbolicLink()) {
  311. auto symlinkContents = directoryInode.fileSystem()->readEntireInode(metadata.inode);
  312. kprintf(" -> %s", String((const char*)symlinkContents.pointer(), symlinkContents.size()).characters());
  313. }
  314. kprintf("\n");
  315. return true;
  316. });
  317. }
  318. void VirtualFileSystem::listDirectoryRecursively(const String& path, InodeIdentifier base)
  319. {
  320. int error;
  321. auto directory = resolvePath(path, error, base);
  322. if (!directory.isValid())
  323. return;
  324. kprintf("%s\n", path.characters());
  325. enumerateDirectoryInode(directory, [&] (const FileSystem::DirectoryEntry& entry) {
  326. auto metadata = entry.inode.metadata();
  327. if (metadata.isDirectory()) {
  328. if (entry.name != "." && entry.name != "..") {
  329. char buf[4096];
  330. ksprintf(buf, "%s/%s", path.characters(), entry.name);
  331. listDirectoryRecursively(buf, base);
  332. }
  333. } else {
  334. kprintf("%s/%s\n", path.characters(), entry.name);
  335. }
  336. return true;
  337. });
  338. }
  339. #endif
  340. bool VirtualFileSystem::touch(const String& path)
  341. {
  342. int error;
  343. auto inode = resolvePath(path, error);
  344. if (!inode.isValid())
  345. return false;
  346. return inode.fileSystem()->setModificationTime(inode, ktime(nullptr));
  347. }
  348. RetainPtr<FileDescriptor> VirtualFileSystem::open(CharacterDevice& device, int options)
  349. {
  350. // FIXME: Respect options.
  351. (void) options;
  352. auto vnode = getOrCreateNode(device);
  353. if (!vnode)
  354. return nullptr;
  355. return FileDescriptor::create(move(vnode));
  356. }
  357. RetainPtr<FileDescriptor> VirtualFileSystem::open(const String& path, int& error, int options, InodeIdentifier base)
  358. {
  359. auto inode = resolvePath(path, error, base, options);
  360. if (!inode.isValid())
  361. return nullptr;
  362. auto vnode = getOrCreateNode(inode);
  363. if (!vnode)
  364. return nullptr;
  365. return FileDescriptor::create(move(vnode));
  366. }
  367. RetainPtr<FileDescriptor> VirtualFileSystem::create(const String& path, InodeIdentifier base)
  368. {
  369. // FIXME: Do the real thing, not just this fake thing!
  370. (void) path;
  371. (void) base;
  372. m_rootNode->fileSystem()->createInode(m_rootNode->fileSystem()->rootInode(), "empty", 0100644, 0);
  373. return nullptr;
  374. }
  375. RetainPtr<FileDescriptor> VirtualFileSystem::mkdir(const String& path, InodeIdentifier base)
  376. {
  377. // FIXME: Do the real thing, not just this fake thing!
  378. (void) path;
  379. (void) base;
  380. m_rootNode->fileSystem()->makeDirectory(m_rootNode->fileSystem()->rootInode(), "mydir", 0400755);
  381. return nullptr;
  382. }
  383. InodeIdentifier VirtualFileSystem::resolveSymbolicLink(InodeIdentifier base, InodeIdentifier symlinkInode, int& error)
  384. {
  385. auto symlinkContents = symlinkInode.readEntireFile();
  386. if (!symlinkContents)
  387. return { };
  388. auto linkee = String((const char*)symlinkContents.pointer(), symlinkContents.size());
  389. #ifdef VFS_DEBUG
  390. kprintf("linkee (%s)(%u) from %u:%u\n", linkee.characters(), linkee.length(), base.fileSystemID(), base.index());
  391. #endif
  392. return resolvePath(linkee, error, base);
  393. }
  394. RetainPtr<CoreInode> VirtualFileSystem::get_inode(InodeIdentifier inode_id)
  395. {
  396. if (!inode_id.isValid())
  397. return nullptr;
  398. return inode_id.fileSystem()->get_inode(inode_id);
  399. }
  400. String VirtualFileSystem::absolute_path(CoreInode& core_inode)
  401. {
  402. int error;
  403. Vector<InodeIdentifier> lineage;
  404. RetainPtr<CoreInode> inode = &core_inode;
  405. while (inode->identifier() != m_rootNode->inode) {
  406. if (auto* mount = findMountForGuest(inode->identifier()))
  407. lineage.append(mount->host());
  408. else
  409. lineage.append(inode->identifier());
  410. InodeIdentifier parent_id;
  411. if (inode->is_directory()) {
  412. parent_id = resolvePath("..", error, inode->identifier());
  413. } else {
  414. parent_id = inode->fs().findParentOfInode(inode->identifier());
  415. }
  416. ASSERT(parent_id.isValid());
  417. inode = get_inode(parent_id);
  418. }
  419. if (lineage.isEmpty())
  420. return "/";
  421. lineage.append(m_rootNode->inode);
  422. StringBuilder builder;
  423. for (size_t i = lineage.size() - 1; i >= 1; --i) {
  424. auto& child = lineage[i - 1];
  425. auto parent = lineage[i];
  426. if (auto* mount = findMountForHost(parent))
  427. parent = mount->guest();
  428. builder.append('/');
  429. builder.append(parent.fileSystem()->nameOfChildInDirectory(parent, child));
  430. }
  431. return builder.build();
  432. }
  433. InodeIdentifier VirtualFileSystem::resolvePath(const String& path, int& error, InodeIdentifier base, int options)
  434. {
  435. if (path.isEmpty())
  436. return { };
  437. auto parts = path.split('/');
  438. InodeIdentifier inode;
  439. if (path[0] == '/')
  440. inode = m_rootNode->inode;
  441. else
  442. inode = base.isValid() ? base : m_rootNode->inode;
  443. for (unsigned i = 0; i < parts.size(); ++i) {
  444. bool wasRootInodeAtHeadOfLoop = inode.isRootInode();
  445. auto& part = parts[i];
  446. if (part.isEmpty())
  447. break;
  448. auto metadata = inode.metadata();
  449. if (!metadata.isValid()) {
  450. #ifdef VFS_DEBUG
  451. kprintf("invalid metadata\n");
  452. #endif
  453. error = -EIO;
  454. return { };
  455. }
  456. if (!metadata.isDirectory()) {
  457. #ifdef VFS_DEBUG
  458. kprintf("parent of <%s> not directory, it's inode %u:%u / %u:%u, mode: %u, size: %u\n", part.characters(), inode.fileSystemID(), inode.index(), metadata.inode.fileSystemID(), metadata.inode.index(), metadata.mode, metadata.size);
  459. #endif
  460. error = -EIO;
  461. return { };
  462. }
  463. auto parent = inode;
  464. inode = inode.fileSystem()->childOfDirectoryInodeWithName(inode, part);
  465. if (!inode.isValid()) {
  466. #ifdef VFS_DEBUG
  467. kprintf("child <%s>(%u) not found in directory, %02u:%08u\n", part.characters(), part.length(), parent.fileSystemID(), parent.index());
  468. #endif
  469. error = -ENOENT;
  470. return { };
  471. }
  472. #ifdef VFS_DEBUG
  473. kprintf("<%s> %u:%u\n", part.characters(), inode.fileSystemID(), inode.index());
  474. #endif
  475. if (auto mount = findMountForHost(inode)) {
  476. #ifdef VFS_DEBUG
  477. kprintf(" -- is host\n");
  478. #endif
  479. inode = mount->guest();
  480. }
  481. if (wasRootInodeAtHeadOfLoop && inode.isRootInode() && !isRoot(inode) && part == "..") {
  482. #ifdef VFS_DEBUG
  483. kprintf(" -- is guest\n");
  484. #endif
  485. auto mount = findMountForGuest(inode);
  486. inode = mount->host();
  487. inode = inode.fileSystem()->childOfDirectoryInodeWithName(inode, "..");
  488. }
  489. metadata = inode.metadata();
  490. if (metadata.isSymbolicLink()) {
  491. if (i == parts.size() - 1) {
  492. if (options & O_NOFOLLOW) {
  493. error = -ELOOP;
  494. return { };
  495. }
  496. if (options & O_NOFOLLOW_NOERROR)
  497. return inode;
  498. }
  499. inode = resolveSymbolicLink(parent, inode, error);
  500. if (!inode.isValid()) {
  501. kprintf("Symbolic link resolution failed :(\n");
  502. return { };
  503. }
  504. }
  505. }
  506. return inode;
  507. }
  508. void VirtualFileSystem::Node::retain()
  509. {
  510. InterruptDisabler disabler; // FIXME: Make a Retainable with atomic retain count instead.
  511. ++retainCount;
  512. }
  513. void VirtualFileSystem::Node::release()
  514. {
  515. InterruptDisabler disabler; // FIXME: Make a Retainable with atomic retain count instead.
  516. ASSERT(retainCount);
  517. if (--retainCount == 0) {
  518. m_vfs->freeNode(this);
  519. }
  520. }
  521. const InodeMetadata& VirtualFileSystem::Node::metadata() const
  522. {
  523. if (m_core_inode)
  524. return m_core_inode->metadata();
  525. if (!m_cachedMetadata.isValid())
  526. m_cachedMetadata = inode.metadata();
  527. return m_cachedMetadata;
  528. }
  529. VirtualFileSystem::Mount::Mount(InodeIdentifier host, RetainPtr<FileSystem>&& guestFileSystem)
  530. : m_host(host)
  531. , m_guest(guestFileSystem->rootInode())
  532. , m_fileSystem(move(guestFileSystem))
  533. {
  534. }
  535. void VirtualFileSystem::registerCharacterDevice(CharacterDevice& device)
  536. {
  537. m_characterDevices.set(encodedDevice(device.major(), device.minor()), &device);
  538. }
  539. void VirtualFileSystem::forEachMount(Function<void(const Mount&)> callback) const
  540. {
  541. for (auto& mount : m_mounts) {
  542. callback(*mount);
  543. }
  544. }