VirtualFileSystem.cpp 18 KB

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