VirtualFileSystem.cpp 18 KB

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