VirtualFileSystem.cpp 18 KB

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