VirtualFileSystem.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  1. #include "VirtualFileSystem.h"
  2. #include "FileHandle.h"
  3. #include "FileSystem.h"
  4. #include <AK/kmalloc.h>
  5. #include <AK/kstdio.h>
  6. #include <AK/ktime.h>
  7. //#define VFS_DEBUG
  8. static dword encodedDevice(unsigned major, unsigned minor)
  9. {
  10. return (minor & 0xff) | (major << 8) | ((minor & ~0xff) << 12);
  11. }
  12. static VirtualFileSystem* s_the;
  13. VirtualFileSystem& VirtualFileSystem::the()
  14. {
  15. ASSERT(s_the);
  16. return *s_the;
  17. }
  18. static SpinLock* s_vfsLock;
  19. SpinLock& VirtualFileSystem::lock()
  20. {
  21. ASSERT(s_vfsLock);
  22. return *s_vfsLock;
  23. }
  24. void VirtualFileSystem::initializeGlobals()
  25. {
  26. s_the = nullptr;
  27. s_vfsLock = new SpinLock;
  28. FileSystem::initializeGlobals();
  29. }
  30. VirtualFileSystem::VirtualFileSystem()
  31. {
  32. #ifdef VFS_DEBUG
  33. kprintf("[VFS] Constructing VFS\n");
  34. #endif
  35. s_the = this;
  36. m_maxNodeCount = 16;
  37. m_nodes = reinterpret_cast<Node*>(kmalloc(sizeof(Node) * maxNodeCount()));
  38. memset(m_nodes, 0, sizeof(Node) * maxNodeCount());
  39. for (unsigned i = 0; i < m_maxNodeCount; ++i)
  40. m_nodeFreeList.append(&m_nodes[i]);
  41. }
  42. VirtualFileSystem::~VirtualFileSystem()
  43. {
  44. kprintf("[VFS] ~VirtualFileSystem with %u nodes allocated\n", allocatedNodeCount());
  45. // FIXME: m_nodes is never freed. Does it matter though?
  46. }
  47. auto VirtualFileSystem::makeNode(InodeIdentifier inode) -> RetainPtr<Node>
  48. {
  49. auto metadata = inode.metadata();
  50. if (!metadata.isValid())
  51. return nullptr;
  52. CharacterDevice* characterDevice = nullptr;
  53. if (metadata.isCharacterDevice()) {
  54. auto it = m_characterDevices.find(encodedDevice(metadata.majorDevice, metadata.minorDevice));
  55. if (it != m_characterDevices.end()) {
  56. characterDevice = (*it).value;
  57. } else {
  58. kprintf("[VFS] makeNode() no such character device %u,%u\n", metadata.majorDevice, metadata.minorDevice);
  59. return nullptr;
  60. }
  61. }
  62. auto vnode = allocateNode();
  63. ASSERT(vnode);
  64. FileSystem* fileSystem = inode.fileSystem();
  65. fileSystem->retain();
  66. vnode->inode = inode;
  67. vnode->m_cachedMetadata = { };
  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::getOrCreateNode(InodeIdentifier inode) -> RetainPtr<Node>
  76. {
  77. auto it = m_inode2vnode.find(inode);
  78. if (it != m_inode2vnode.end())
  79. return (*it).value;
  80. return makeNode(inode);
  81. }
  82. bool VirtualFileSystem::mount(RetainPtr<FileSystem>&& fileSystem, const String& path)
  83. {
  84. ASSERT(fileSystem);
  85. auto inode = resolvePath(path);
  86. if (!inode.isValid()) {
  87. kprintf("[VFS] mount can't resolve mount point '%s'\n", path.characters());
  88. return false;
  89. }
  90. kprintf("mounting %s{%p} at %s (inode: %u)\n", fileSystem->className(), fileSystem.ptr(), path.characters(), inode.index());
  91. // FIXME: check that this is not already a mount point
  92. auto mount = make<Mount>(inode, move(fileSystem));
  93. m_mounts.append(move(mount));
  94. return true;
  95. }
  96. bool VirtualFileSystem::mountRoot(RetainPtr<FileSystem>&& fileSystem)
  97. {
  98. if (m_rootNode) {
  99. kprintf("[VFS] mountRoot can't mount another root\n");
  100. return false;
  101. }
  102. auto mount = make<Mount>(InodeIdentifier(), move(fileSystem));
  103. auto node = makeNode(mount->guest());
  104. if (!node->inUse()) {
  105. kprintf("[VFS] root inode for / is not in use :(\n");
  106. return false;
  107. }
  108. if (!node->inode.metadata().isDirectory()) {
  109. kprintf("[VFS] root inode for / is not in use :(\n");
  110. return false;
  111. }
  112. m_rootNode = move(node);
  113. kprintf("[VFS] mountRoot mounted %s{%p}\n",
  114. m_rootNode->fileSystem()->className(),
  115. m_rootNode->fileSystem());
  116. m_mounts.append(move(mount));
  117. return true;
  118. }
  119. auto VirtualFileSystem::allocateNode() -> RetainPtr<Node>
  120. {
  121. if (m_nodeFreeList.isEmpty()) {
  122. kprintf("[VFS] allocateNode has no nodes left\n");
  123. return nullptr;
  124. }
  125. auto* node = m_nodeFreeList.takeLast();
  126. ASSERT(node->retainCount == 0);
  127. node->retainCount = 1;
  128. node->m_vfs = this;
  129. return adopt(*node);
  130. }
  131. void VirtualFileSystem::freeNode(Node* node)
  132. {
  133. ASSERT(node);
  134. ASSERT(node->inUse());
  135. m_inode2vnode.remove(node->inode);
  136. node->inode.fileSystem()->release();
  137. node->inode = InodeIdentifier();
  138. node->m_characterDevice = nullptr;
  139. m_nodeFreeList.append(move(node));
  140. }
  141. bool VirtualFileSystem::isDirectory(const String& path, Node* base)
  142. {
  143. auto inode = resolvePath(path, base);
  144. if (!inode.isValid())
  145. return false;
  146. return inode.metadata().isDirectory();
  147. }
  148. auto VirtualFileSystem::findMountForHost(InodeIdentifier inode) -> Mount*
  149. {
  150. for (auto& mount : m_mounts) {
  151. if (mount->host() == inode)
  152. return mount.ptr();
  153. }
  154. return nullptr;
  155. }
  156. auto VirtualFileSystem::findMountForGuest(InodeIdentifier inode) -> Mount*
  157. {
  158. for (auto& mount : m_mounts) {
  159. if (mount->guest() == inode)
  160. return mount.ptr();
  161. }
  162. return nullptr;
  163. }
  164. bool VirtualFileSystem::isRoot(InodeIdentifier inode) const
  165. {
  166. return inode == m_rootNode->inode;
  167. }
  168. void VirtualFileSystem::enumerateDirectoryInode(InodeIdentifier directoryInode, Function<bool(const FileSystem::DirectoryEntry&)> callback)
  169. {
  170. if (!directoryInode.isValid())
  171. return;
  172. directoryInode.fileSystem()->enumerateDirectoryInode(directoryInode, [&] (const FileSystem::DirectoryEntry& entry) {
  173. InodeIdentifier resolvedInode;
  174. if (auto mount = findMountForHost(entry.inode))
  175. resolvedInode = mount->guest();
  176. else
  177. resolvedInode = entry.inode;
  178. if (directoryInode.isRootInode() && !isRoot(directoryInode) && entry.name == "..") {
  179. auto mount = findMountForGuest(entry.inode);
  180. ASSERT(mount);
  181. resolvedInode = mount->host();
  182. }
  183. callback({ entry.name, resolvedInode });
  184. return true;
  185. });
  186. }
  187. void VirtualFileSystem::listDirectory(const String& path)
  188. {
  189. auto directoryInode = resolvePath(path);
  190. if (!directoryInode.isValid())
  191. return;
  192. kprintf("[VFS] ls %s -> %s %02u:%08u\n", path.characters(), directoryInode.fileSystem()->className(), directoryInode.fileSystemID(), directoryInode.index());
  193. enumerateDirectoryInode(directoryInode, [&] (const FileSystem::DirectoryEntry& entry) {
  194. const char* nameColorBegin = "";
  195. const char* nameColorEnd = "";
  196. auto metadata = entry.inode.metadata();
  197. ASSERT(metadata.isValid());
  198. if (metadata.isDirectory()) {
  199. nameColorBegin = "\033[34;1m";
  200. nameColorEnd = "\033[0m";
  201. } else if (metadata.isSymbolicLink()) {
  202. nameColorBegin = "\033[36;1m";
  203. nameColorEnd = "\033[0m";
  204. }
  205. if (metadata.isSticky()) {
  206. nameColorBegin = "\033[42;30m";
  207. nameColorEnd = "\033[0m";
  208. }
  209. if (metadata.isCharacterDevice() || metadata.isBlockDevice()) {
  210. nameColorBegin = "\033[33;1m";
  211. nameColorEnd = "\033[0m";
  212. }
  213. kprintf("%02u:%08u ",
  214. metadata.inode.fileSystemID(),
  215. metadata.inode.index());
  216. if (metadata.isDirectory())
  217. kprintf("d");
  218. else if (metadata.isSymbolicLink())
  219. kprintf("l");
  220. else if (metadata.isBlockDevice())
  221. kprintf("b");
  222. else if (metadata.isCharacterDevice())
  223. kprintf("c");
  224. else if (metadata.isSocket())
  225. kprintf("s");
  226. else if (metadata.isFIFO())
  227. kprintf("f");
  228. else if (metadata.isRegularFile())
  229. kprintf("-");
  230. else
  231. kprintf("?");
  232. kprintf("%c%c%c%c%c%c%c%c",
  233. metadata.mode & 00400 ? 'r' : '-',
  234. metadata.mode & 00200 ? 'w' : '-',
  235. metadata.mode & 00100 ? 'x' : '-',
  236. metadata.mode & 00040 ? 'r' : '-',
  237. metadata.mode & 00020 ? 'w' : '-',
  238. metadata.mode & 00010 ? 'x' : '-',
  239. metadata.mode & 00004 ? 'r' : '-',
  240. metadata.mode & 00002 ? 'w' : '-'
  241. );
  242. if (metadata.isSticky())
  243. kprintf("t");
  244. else
  245. kprintf("%c", metadata.mode & 00001 ? 'x' : '-');
  246. if (metadata.isCharacterDevice() || metadata.isBlockDevice()) {
  247. char buf[16];
  248. ksprintf(buf, "%u, %u", metadata.majorDevice, metadata.minorDevice);
  249. kprintf("%12s ", buf);
  250. } else {
  251. kprintf("%12lld ", metadata.size);
  252. }
  253. kprintf("\033[30;1m");
  254. time_t mtime = metadata.mtime;
  255. auto tm = *klocaltime(&mtime);
  256. kprintf("%04u-%02u-%02u %02u:%02u:%02u ",
  257. tm.tm_year + 1900,
  258. tm.tm_mon + 1,
  259. tm.tm_mday,
  260. tm.tm_hour,
  261. tm.tm_min,
  262. tm.tm_sec);
  263. kprintf("\033[0m");
  264. kprintf("%s%s%s",
  265. nameColorBegin,
  266. entry.name.characters(),
  267. nameColorEnd);
  268. if (metadata.isDirectory()) {
  269. kprintf("/");
  270. } else if (metadata.isSymbolicLink()) {
  271. auto symlinkContents = directoryInode.fileSystem()->readEntireInode(metadata.inode);
  272. kprintf(" -> %s", String((const char*)symlinkContents.pointer(), symlinkContents.size()).characters());
  273. }
  274. kprintf("\n");
  275. return true;
  276. });
  277. }
  278. void VirtualFileSystem::listDirectoryRecursively(const String& path)
  279. {
  280. auto directory = resolvePath(path);
  281. if (!directory.isValid())
  282. return;
  283. kprintf("%s\n", path.characters());
  284. enumerateDirectoryInode(directory, [&] (const FileSystem::DirectoryEntry& entry) {
  285. auto metadata = entry.inode.metadata();
  286. if (metadata.isDirectory()) {
  287. if (entry.name != "." && entry.name != "..") {
  288. char buf[4096];
  289. ksprintf(buf, "%s/%s", path.characters(), entry.name.characters());
  290. listDirectoryRecursively(buf);
  291. }
  292. } else {
  293. kprintf("%s/%s\n", path.characters(), entry.name.characters());
  294. }
  295. return true;
  296. });
  297. }
  298. bool VirtualFileSystem::touch(const String& path)
  299. {
  300. Locker locker(VirtualFileSystem::lock());
  301. auto inode = resolvePath(path);
  302. if (!inode.isValid())
  303. return false;
  304. return inode.fileSystem()->setModificationTime(inode, ktime(nullptr));
  305. }
  306. OwnPtr<FileHandle> VirtualFileSystem::open(const String& path, Node* base)
  307. {
  308. Locker locker(VirtualFileSystem::lock());
  309. auto inode = resolvePath(path, base);
  310. if (!inode.isValid())
  311. return nullptr;
  312. auto vnode = getOrCreateNode(inode);
  313. if (!vnode)
  314. return nullptr;
  315. return make<FileHandle>(move(vnode));
  316. }
  317. OwnPtr<FileHandle> VirtualFileSystem::create(const String& path, Node* base)
  318. {
  319. Locker locker(VirtualFileSystem::lock());
  320. // FIXME: Do the real thing, not just this fake thing!
  321. (void) path;
  322. m_rootNode->fileSystem()->createInode(m_rootNode->fileSystem()->rootInode(), "empty", 0100644, 0);
  323. return nullptr;
  324. }
  325. OwnPtr<FileHandle> VirtualFileSystem::mkdir(const String& path, Node* base)
  326. {
  327. Locker locker(VirtualFileSystem::lock());
  328. // FIXME: Do the real thing, not just this fake thing!
  329. (void) path;
  330. m_rootNode->fileSystem()->makeDirectory(m_rootNode->fileSystem()->rootInode(), "mydir", 0400755);
  331. return nullptr;
  332. }
  333. InodeIdentifier VirtualFileSystem::resolveSymbolicLink(const String& basePath, InodeIdentifier symlinkInode)
  334. {
  335. auto symlinkContents = symlinkInode.readEntireFile();
  336. if (!symlinkContents)
  337. return { };
  338. char buf[4096];
  339. ksprintf(buf, "/%s/%s", basePath.characters(), String((const char*)symlinkContents.pointer(), symlinkContents.size()).characters());
  340. return resolvePath(buf);
  341. }
  342. InodeIdentifier VirtualFileSystem::resolvePath(const String& path, Node* base)
  343. {
  344. if (path.isEmpty())
  345. return { };
  346. auto parts = path.split('/');
  347. InodeIdentifier inode;
  348. if (path[0] == '/')
  349. inode = m_rootNode->inode;
  350. else
  351. inode = base ? base->inode : m_rootNode->inode;
  352. for (unsigned i = 0; i < parts.size(); ++i) {
  353. auto& part = parts[i];
  354. auto metadata = inode.metadata();
  355. if (!metadata.isValid()) {
  356. #ifdef VFS_DEBUG
  357. kprintf("invalid metadata\n");
  358. #endif
  359. return InodeIdentifier();
  360. }
  361. if (!metadata.isDirectory()) {
  362. #ifdef VFS_DEBUG
  363. kprintf("not directory\n");
  364. #endif
  365. return InodeIdentifier();
  366. }
  367. inode = inode.fileSystem()->childOfDirectoryInodeWithName(inode, part);
  368. if (!inode.isValid()) {
  369. #ifdef VFS_DEBUG
  370. kprintf("bad child\n");
  371. #endif
  372. return InodeIdentifier();
  373. }
  374. #ifdef VFS_DEBUG
  375. kprintf("<%s> %02u:%08u\n", part.characters(), inode.fileSystemID(), inode.index());
  376. #endif
  377. if (auto mount = findMountForHost(inode)) {
  378. #ifdef VFS_DEBUG
  379. kprintf(" -- is host\n");
  380. #endif
  381. inode = mount->guest();
  382. }
  383. if (inode.isRootInode() && !isRoot(inode) && part == "..") {
  384. #ifdef VFS_DEBUG
  385. kprintf(" -- is guest\n");
  386. #endif
  387. auto mount = findMountForGuest(inode);
  388. inode = mount->host();
  389. inode = inode.fileSystem()->childOfDirectoryInodeWithName(inode, "..");
  390. }
  391. metadata = inode.metadata();
  392. if (metadata.isSymbolicLink()) {
  393. char buf[4096] = "";
  394. char* p = buf;
  395. for (unsigned j = 0; j < i; ++j) {
  396. p += ksprintf(p, "/%s", parts[j].characters());
  397. }
  398. inode = resolveSymbolicLink(buf, inode);
  399. if (!inode.isValid()) {
  400. kprintf("Symbolic link resolution failed :(\n");
  401. return { };
  402. }
  403. }
  404. }
  405. return inode;
  406. }
  407. void VirtualFileSystem::Node::retain()
  408. {
  409. ++retainCount;
  410. }
  411. void VirtualFileSystem::Node::release()
  412. {
  413. ASSERT(retainCount);
  414. if (--retainCount == 0) {
  415. m_vfs->freeNode(this);
  416. }
  417. }
  418. const InodeMetadata& VirtualFileSystem::Node::metadata() const
  419. {
  420. if (!m_cachedMetadata.isValid())
  421. m_cachedMetadata = inode.metadata();
  422. return m_cachedMetadata;
  423. }
  424. VirtualFileSystem::Mount::Mount(InodeIdentifier host, RetainPtr<FileSystem>&& guestFileSystem)
  425. : m_host(host)
  426. , m_guest(guestFileSystem->rootInode())
  427. , m_fileSystem(move(guestFileSystem))
  428. {
  429. }
  430. void VirtualFileSystem::registerCharacterDevice(unsigned major, unsigned minor, CharacterDevice& device)
  431. {
  432. m_characterDevices.set(encodedDevice(major, minor), &device);
  433. }