Ext2FileSystem.cpp 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144
  1. #include "Ext2FileSystem.h"
  2. #include "ext2_fs.h"
  3. #include "UnixTypes.h"
  4. #include <AK/Bitmap.h>
  5. #include <AK/StdLibExtras.h>
  6. #include <AK/kmalloc.h>
  7. #include <AK/ktime.h>
  8. #include <AK/kstdio.h>
  9. #include <AK/BufferStream.h>
  10. #include <LibC/errno_numbers.h>
  11. //#define EXT2_DEBUG
  12. RetainPtr<Ext2FS> Ext2FS::create(RetainPtr<DiskDevice>&& device)
  13. {
  14. return adopt(*new Ext2FS(move(device)));
  15. }
  16. Ext2FS::Ext2FS(RetainPtr<DiskDevice>&& device)
  17. : DiskBackedFS(move(device))
  18. {
  19. }
  20. Ext2FS::~Ext2FS()
  21. {
  22. }
  23. ByteBuffer Ext2FS::read_super_block() const
  24. {
  25. auto buffer = ByteBuffer::createUninitialized(1024);
  26. device().read_block(2, buffer.pointer());
  27. device().read_block(3, buffer.offsetPointer(512));
  28. return buffer;
  29. }
  30. bool Ext2FS::write_super_block(const ext2_super_block& sb)
  31. {
  32. const byte* raw = (const byte*)&sb;
  33. bool success;
  34. success = device().write_block(2, raw);
  35. ASSERT(success);
  36. success = device().write_block(3, raw + 512);
  37. ASSERT(success);
  38. // FIXME: This is an ugly way to refresh the superblock cache. :-|
  39. super_block();
  40. return true;
  41. }
  42. unsigned Ext2FS::first_block_of_group(unsigned groupIndex) const
  43. {
  44. return super_block().s_first_data_block + (groupIndex * super_block().s_blocks_per_group);
  45. }
  46. const ext2_super_block& Ext2FS::super_block() const
  47. {
  48. if (!m_cached_super_block)
  49. m_cached_super_block = read_super_block();
  50. return *reinterpret_cast<ext2_super_block*>(m_cached_super_block.pointer());
  51. }
  52. const ext2_group_desc& Ext2FS::group_descriptor(unsigned groupIndex) const
  53. {
  54. // FIXME: Should this fail gracefully somehow?
  55. ASSERT(groupIndex <= m_blockGroupCount);
  56. if (!m_cached_group_descriptor_table) {
  57. unsigned blocksToRead = ceilDiv(m_blockGroupCount * (unsigned)sizeof(ext2_group_desc), blockSize());
  58. unsigned firstBlockOfBGDT = blockSize() == 1024 ? 2 : 1;
  59. #ifdef EXT2_DEBUG
  60. kprintf("ext2fs: block group count: %u, blocks-to-read: %u\n", m_blockGroupCount, blocksToRead);
  61. kprintf("ext2fs: first block of BGDT: %u\n", firstBlockOfBGDT);
  62. #endif
  63. m_cached_group_descriptor_table = readBlocks(firstBlockOfBGDT, blocksToRead);
  64. }
  65. return reinterpret_cast<ext2_group_desc*>(m_cached_group_descriptor_table.pointer())[groupIndex - 1];
  66. }
  67. bool Ext2FS::initialize()
  68. {
  69. auto& superBlock = this->super_block();
  70. #ifdef EXT2_DEBUG
  71. kprintf("ext2fs: super block magic: %x (super block size: %u)\n", superBlock.s_magic, sizeof(ext2_super_block));
  72. #endif
  73. if (superBlock.s_magic != EXT2_SUPER_MAGIC)
  74. return false;
  75. #ifdef EXT2_DEBUG
  76. kprintf("ext2fs: %u inodes, %u blocks\n", superBlock.s_inodes_count, superBlock.s_blocks_count);
  77. kprintf("ext2fs: block size = %u\n", EXT2_BLOCK_SIZE(&superBlock));
  78. kprintf("ext2fs: first data block = %u\n", superBlock.s_first_data_block);
  79. kprintf("ext2fs: inodes per block = %u\n", inodesPerBlock());
  80. kprintf("ext2fs: inodes per group = %u\n", inodesPerGroup());
  81. kprintf("ext2fs: free inodes = %u\n", superBlock.s_free_inodes_count);
  82. kprintf("ext2fs: desc per block = %u\n", EXT2_DESC_PER_BLOCK(&superBlock));
  83. kprintf("ext2fs: desc size = %u\n", EXT2_DESC_SIZE(&superBlock));
  84. #endif
  85. setBlockSize(EXT2_BLOCK_SIZE(&superBlock));
  86. m_blockGroupCount = ceilDiv(superBlock.s_blocks_count, superBlock.s_blocks_per_group);
  87. if (m_blockGroupCount == 0) {
  88. kprintf("ext2fs: no block groups :(\n");
  89. return false;
  90. }
  91. // Preheat the BGD cache.
  92. group_descriptor(0);
  93. #ifdef EXT2_DEBUG
  94. for (unsigned i = 1; i <= m_blockGroupCount; ++i) {
  95. auto& group = blockGroupDescriptor(i);
  96. kprintf("ext2fs: group[%u] { block_bitmap: %u, inode_bitmap: %u, inode_table: %u }\n",
  97. i,
  98. group.bg_block_bitmap,
  99. group.bg_inode_bitmap,
  100. group.bg_inode_table);
  101. }
  102. #endif
  103. return true;
  104. }
  105. const char* Ext2FS::class_name() const
  106. {
  107. return "ext2fs";
  108. }
  109. InodeIdentifier Ext2FS::root_inode() const
  110. {
  111. return { id(), EXT2_ROOT_INO };
  112. }
  113. #ifdef EXT2_DEBUG
  114. static void dumpExt2Inode(const ext2_inode& inode)
  115. {
  116. kprintf("Dump of ext2_inode:\n");
  117. kprintf(" i_size: %u\n", inode.i_size);
  118. kprintf(" i_mode: %u\n", inode.i_mode);
  119. kprintf(" i_blocks: %u\n", inode.i_blocks);
  120. kprintf(" i_uid: %u\n", inode.i_uid);
  121. kprintf(" i_gid: %u\n", inode.i_gid);
  122. }
  123. #endif
  124. ByteBuffer Ext2FS::read_block_containing_inode(unsigned inode, unsigned& blockIndex, unsigned& offset) const
  125. {
  126. auto& superBlock = this->super_block();
  127. if (inode != EXT2_ROOT_INO && inode < EXT2_FIRST_INO(&superBlock))
  128. return { };
  129. if (inode > superBlock.s_inodes_count)
  130. return { };
  131. auto& bgd = group_descriptor(group_index_from_inode(inode));
  132. offset = ((inode - 1) % inodes_per_group()) * inode_size();
  133. blockIndex = bgd.bg_inode_table + (offset >> EXT2_BLOCK_SIZE_BITS(&superBlock));
  134. offset &= blockSize() - 1;
  135. return readBlock(blockIndex);
  136. }
  137. OwnPtr<ext2_inode> Ext2FS::lookup_ext2_inode(unsigned inode) const
  138. {
  139. unsigned blockIndex;
  140. unsigned offset;
  141. auto block = read_block_containing_inode(inode, blockIndex, offset);
  142. if (!block)
  143. return { };
  144. auto* e2inode = reinterpret_cast<ext2_inode*>(kmalloc(inode_size()));
  145. memcpy(e2inode, reinterpret_cast<ext2_inode*>(block.offsetPointer(offset)), inode_size());
  146. #ifdef EXT2_DEBUG
  147. dumpExt2Inode(*e2inode);
  148. #endif
  149. return OwnPtr<ext2_inode>(e2inode);
  150. }
  151. InodeMetadata Ext2FS::inode_metadata(InodeIdentifier inode) const
  152. {
  153. ASSERT(inode.fsid() == id());
  154. auto e2inode = lookup_ext2_inode(inode.index());
  155. if (!e2inode)
  156. return InodeMetadata();
  157. InodeMetadata metadata;
  158. metadata.inode = inode;
  159. metadata.size = e2inode->i_size;
  160. metadata.mode = e2inode->i_mode;
  161. metadata.uid = e2inode->i_uid;
  162. metadata.gid = e2inode->i_gid;
  163. metadata.linkCount = e2inode->i_links_count;
  164. metadata.atime = e2inode->i_atime;
  165. metadata.ctime = e2inode->i_ctime;
  166. metadata.mtime = e2inode->i_mtime;
  167. metadata.dtime = e2inode->i_dtime;
  168. metadata.blockSize = blockSize();
  169. metadata.blockCount = e2inode->i_blocks;
  170. if (isBlockDevice(e2inode->i_mode) || isCharacterDevice(e2inode->i_mode)) {
  171. unsigned dev = e2inode->i_block[0];
  172. metadata.majorDevice = (dev & 0xfff00) >> 8;
  173. metadata.minorDevice= (dev & 0xff) | ((dev >> 12) & 0xfff00);
  174. }
  175. return metadata;
  176. }
  177. Vector<unsigned> Ext2FS::block_list_for_inode(const ext2_inode& e2inode) const
  178. {
  179. unsigned entriesPerBlock = EXT2_ADDR_PER_BLOCK(&super_block());
  180. // NOTE: i_blocks is number of 512-byte blocks, not number of fs-blocks.
  181. unsigned blockCount = e2inode.i_blocks / (blockSize() / 512);
  182. unsigned blocksRemaining = blockCount;
  183. Vector<unsigned> list;
  184. list.ensureCapacity(blocksRemaining);
  185. unsigned directCount = min(blockCount, (unsigned)EXT2_NDIR_BLOCKS);
  186. for (unsigned i = 0; i < directCount; ++i) {
  187. list.unchecked_append(e2inode.i_block[i]);
  188. --blocksRemaining;
  189. }
  190. if (!blocksRemaining)
  191. return list;
  192. auto processBlockArray = [&] (unsigned arrayBlockIndex, auto&& callback) {
  193. auto arrayBlock = readBlock(arrayBlockIndex);
  194. ASSERT(arrayBlock);
  195. auto* array = reinterpret_cast<const __u32*>(arrayBlock.pointer());
  196. unsigned count = min(blocksRemaining, entriesPerBlock);
  197. for (unsigned i = 0; i < count; ++i) {
  198. if (!array[i]) {
  199. blocksRemaining = 0;
  200. return;
  201. }
  202. callback(array[i]);
  203. --blocksRemaining;
  204. }
  205. };
  206. processBlockArray(e2inode.i_block[EXT2_IND_BLOCK], [&] (unsigned entry) {
  207. list.unchecked_append(entry);
  208. });
  209. if (!blocksRemaining)
  210. return list;
  211. processBlockArray(e2inode.i_block[EXT2_DIND_BLOCK], [&] (unsigned entry) {
  212. processBlockArray(entry, [&] (unsigned entry) {
  213. list.unchecked_append(entry);
  214. });
  215. });
  216. if (!blocksRemaining)
  217. return list;
  218. processBlockArray(e2inode.i_block[EXT2_TIND_BLOCK], [&] (unsigned entry) {
  219. processBlockArray(entry, [&] (unsigned entry) {
  220. processBlockArray(entry, [&] (unsigned entry) {
  221. list.unchecked_append(entry);
  222. });
  223. });
  224. });
  225. return list;
  226. }
  227. Ext2FSInode::Ext2FSInode(Ext2FS& fs, unsigned index, const ext2_inode& raw_inode)
  228. : CoreInode(fs, index)
  229. , m_raw_inode(raw_inode)
  230. {
  231. }
  232. Ext2FSInode::~Ext2FSInode()
  233. {
  234. }
  235. void Ext2FSInode::populate_metadata() const
  236. {
  237. m_metadata.inode = identifier();
  238. m_metadata.size = m_raw_inode.i_size;
  239. m_metadata.mode = m_raw_inode.i_mode;
  240. m_metadata.uid = m_raw_inode.i_uid;
  241. m_metadata.gid = m_raw_inode.i_gid;
  242. m_metadata.linkCount = m_raw_inode.i_links_count;
  243. m_metadata.atime = m_raw_inode.i_atime;
  244. m_metadata.ctime = m_raw_inode.i_ctime;
  245. m_metadata.mtime = m_raw_inode.i_mtime;
  246. m_metadata.dtime = m_raw_inode.i_dtime;
  247. m_metadata.blockSize = fs().blockSize();
  248. m_metadata.blockCount = m_raw_inode.i_blocks;
  249. if (isBlockDevice(m_raw_inode.i_mode) || isCharacterDevice(m_raw_inode.i_mode)) {
  250. unsigned dev = m_raw_inode.i_block[0];
  251. m_metadata.majorDevice = (dev & 0xfff00) >> 8;
  252. m_metadata.minorDevice= (dev & 0xff) | ((dev >> 12) & 0xfff00);
  253. }
  254. }
  255. RetainPtr<CoreInode> Ext2FS::get_inode(InodeIdentifier inode) const
  256. {
  257. ASSERT(inode.fsid() == id());
  258. {
  259. LOCKER(m_inode_cache_lock);
  260. auto it = m_inode_cache.find(inode.index());
  261. if (it != m_inode_cache.end())
  262. return (*it).value;
  263. }
  264. auto raw_inode = lookup_ext2_inode(inode.index());
  265. if (!raw_inode)
  266. return nullptr;
  267. LOCKER(m_inode_cache_lock);
  268. auto it = m_inode_cache.find(inode.index());
  269. if (it != m_inode_cache.end())
  270. return (*it).value;
  271. auto new_inode = adopt(*new Ext2FSInode(const_cast<Ext2FS&>(*this), inode.index(), *raw_inode));
  272. m_inode_cache.set(inode.index(), new_inode.copyRef());
  273. return new_inode;
  274. }
  275. ssize_t Ext2FSInode::read_bytes(Unix::off_t offset, size_t count, byte* buffer, FileDescriptor*)
  276. {
  277. ASSERT(offset >= 0);
  278. if (m_raw_inode.i_size == 0)
  279. return 0;
  280. // Symbolic links shorter than 60 characters are store inline inside the i_block array.
  281. // This avoids wasting an entire block on short links. (Most links are short.)
  282. static const unsigned max_inline_symlink_length = 60;
  283. if (is_symlink() && size() < max_inline_symlink_length) {
  284. ssize_t nread = min((Unix::off_t)size() - offset, static_cast<Unix::off_t>(count));
  285. memcpy(buffer, m_raw_inode.i_block + offset, nread);
  286. return nread;
  287. }
  288. if (m_block_list.isEmpty()) {
  289. auto block_list = fs().block_list_for_inode(m_raw_inode);
  290. LOCKER(m_lock);
  291. if (m_block_list.size() != block_list.size())
  292. m_block_list = move(block_list);
  293. }
  294. if (m_block_list.isEmpty()) {
  295. kprintf("ext2fs: read_bytes: empty block list for inode %u\n", index());
  296. return -EIO;
  297. }
  298. const size_t block_size = fs().blockSize();
  299. dword first_block_logical_index = offset / block_size;
  300. dword last_block_logical_index = (offset + count) / block_size;
  301. if (last_block_logical_index >= m_block_list.size())
  302. last_block_logical_index = m_block_list.size() - 1;
  303. dword offset_into_first_block = offset % block_size;
  304. ssize_t nread = 0;
  305. size_t remaining_count = min((Unix::off_t)count, (Unix::off_t)size() - offset);
  306. byte* out = buffer;
  307. #ifdef EXT2_DEBUG
  308. kprintf("ok let's do it, read(%llu, %u) -> blocks %u thru %u, oifb: %u\n", offset, count, firstBlockLogicalIndex, lastBlockLogicalIndex, offsetIntoFirstBlock);
  309. #endif
  310. for (dword bi = first_block_logical_index; remaining_count && bi <= last_block_logical_index; ++bi) {
  311. auto block = fs().readBlock(m_block_list[bi]);
  312. if (!block) {
  313. kprintf("ext2fs: read_bytes: readBlock(%u) failed (lbi: %u)\n", m_block_list[bi], bi);
  314. return -EIO;
  315. }
  316. dword offset_into_block = (bi == first_block_logical_index) ? offset_into_first_block : 0;
  317. dword num_bytes_to_copy = min(block_size - offset_into_block, remaining_count);
  318. memcpy(out, block.pointer() + offset_into_block, num_bytes_to_copy);
  319. remaining_count -= num_bytes_to_copy;
  320. nread += num_bytes_to_copy;
  321. out += num_bytes_to_copy;
  322. }
  323. return nread;
  324. }
  325. ssize_t Ext2FS::read_inode_bytes(InodeIdentifier inode, Unix::off_t offset, size_t count, byte* buffer, FileDescriptor*) const
  326. {
  327. ASSERT(offset >= 0);
  328. ASSERT(inode.fsid() == id());
  329. auto e2inode = lookup_ext2_inode(inode.index());
  330. if (!e2inode) {
  331. kprintf("ext2fs: readInodeBytes: metadata lookup for inode %u failed\n", inode.index());
  332. return -EIO;
  333. }
  334. #if 0
  335. // FIXME: We can't fail here while the directory traversal depends on this function. :]
  336. if (isDirectory(e2inode->i_mode))
  337. return -EISDIR;
  338. #endif
  339. if (e2inode->i_size == 0)
  340. return 0;
  341. // Symbolic links shorter than 60 characters are store inline inside the i_block array.
  342. // This avoids wasting an entire block on short links. (Most links are short.)
  343. static const unsigned maxInlineSymlinkLength = 60;
  344. if (isSymbolicLink(e2inode->i_mode) && e2inode->i_size < maxInlineSymlinkLength) {
  345. ssize_t nread = min((Unix::off_t)e2inode->i_size - offset, static_cast<Unix::off_t>(count));
  346. memcpy(buffer, e2inode->i_block + offset, nread);
  347. return nread;
  348. }
  349. // FIXME: It's grossly inefficient to fetch the blocklist on every call to readInodeBytes().
  350. // It needs to be cached!
  351. auto list = block_list_for_inode(*e2inode);
  352. if (list.isEmpty()) {
  353. kprintf("ext2fs: readInodeBytes: empty block list for inode %u\n", inode.index());
  354. return -EIO;
  355. }
  356. dword firstBlockLogicalIndex = offset / blockSize();
  357. dword lastBlockLogicalIndex = (offset + count) / blockSize();
  358. if (lastBlockLogicalIndex >= list.size())
  359. lastBlockLogicalIndex = list.size() - 1;
  360. dword offsetIntoFirstBlock = offset % blockSize();
  361. ssize_t nread = 0;
  362. size_t remainingCount = min((Unix::off_t)count, (Unix::off_t)e2inode->i_size - offset);
  363. byte* out = buffer;
  364. #ifdef EXT2_DEBUG
  365. kprintf("ok let's do it, read(%llu, %u) -> blocks %u thru %u, oifb: %u\n", offset, count, firstBlockLogicalIndex, lastBlockLogicalIndex, offsetIntoFirstBlock);
  366. #endif
  367. for (dword bi = firstBlockLogicalIndex; bi <= lastBlockLogicalIndex; ++bi) {
  368. auto block = readBlock(list[bi]);
  369. if (!block) {
  370. kprintf("ext2fs: readInodeBytes: readBlock(%u) failed (lbi: %u)\n", list[bi], bi);
  371. return -EIO;
  372. }
  373. dword offsetIntoBlock;
  374. if (bi == firstBlockLogicalIndex)
  375. offsetIntoBlock = offsetIntoFirstBlock;
  376. else
  377. offsetIntoBlock = 0;
  378. size_t numBytesToCopy = min(blockSize() - offsetIntoBlock, remainingCount);
  379. memcpy(out, block.pointer() + offsetIntoBlock, numBytesToCopy);
  380. remainingCount -= numBytesToCopy;
  381. nread += numBytesToCopy;
  382. out += numBytesToCopy;
  383. }
  384. return nread;
  385. }
  386. bool Ext2FS::write_inode(InodeIdentifier inode, const ByteBuffer& data)
  387. {
  388. ASSERT(inode.fsid() == id());
  389. auto e2inode = lookup_ext2_inode(inode.index());
  390. if (!e2inode) {
  391. kprintf("ext2fs: writeInode: metadata lookup for inode %u failed\n", inode.index());
  392. return false;
  393. }
  394. // FIXME: Support writing to symlink inodes.
  395. ASSERT(!isSymbolicLink(e2inode->i_mode));
  396. unsigned blocksNeededBefore = ceilDiv(e2inode->i_size, blockSize());
  397. unsigned blocksNeededAfter = ceilDiv((unsigned)data.size(), blockSize());
  398. // FIXME: Support growing or shrinking the block list.
  399. ASSERT(blocksNeededBefore == blocksNeededAfter);
  400. auto list = block_list_for_inode(*e2inode);
  401. if (list.isEmpty()) {
  402. kprintf("ext2fs: writeInode: empty block list for inode %u\n", inode.index());
  403. return false;
  404. }
  405. for (unsigned i = 0; i < list.size(); ++i) {
  406. auto section = data.slice(i * blockSize(), blockSize());
  407. //kprintf("section = %p (%u)\n", section.pointer(), section.size());
  408. bool success = writeBlock(list[i], section);
  409. ASSERT(success);
  410. }
  411. return true;
  412. }
  413. bool Ext2FSInode::traverse_as_directory(Function<bool(const FS::DirectoryEntry&)> callback)
  414. {
  415. ASSERT(metadata().isDirectory());
  416. #ifdef EXT2_DEBUG
  417. kprintf("Ext2Inode::traverse_as_directory: inode=%u:\n", index());
  418. #endif
  419. auto buffer = read_entire();
  420. ASSERT(buffer);
  421. auto* entry = reinterpret_cast<ext2_dir_entry_2*>(buffer.pointer());
  422. while (entry < buffer.endPointer()) {
  423. if (entry->inode != 0) {
  424. #ifdef EXT2_DEBUG
  425. kprintf("Ext2Inode::traverse_as_directory: %u, name_len: %u, rec_len: %u, file_type: %u, name: %s\n", entry->inode, entry->name_len, entry->rec_len, entry->file_type, namebuf);
  426. #endif
  427. if (!callback({ entry->name, entry->name_len, { fsid(), entry->inode }, entry->file_type }))
  428. break;
  429. }
  430. entry = (ext2_dir_entry_2*)((char*)entry + entry->rec_len);
  431. }
  432. return true;
  433. }
  434. bool Ext2FS::add_inode_to_directory(InodeIndex parent, InodeIndex child, const String& name, byte fileType, int& error)
  435. {
  436. auto e2inodeForDirectory = lookup_ext2_inode(parent);
  437. ASSERT(e2inodeForDirectory);
  438. ASSERT(isDirectory(e2inodeForDirectory->i_mode));
  439. //#ifdef EXT2_DEBUG
  440. dbgprintf("Ext2FS: Adding inode %u with name '%s' to directory %u\n", child, name.characters(), parent);
  441. //#endif
  442. Vector<DirectoryEntry> entries;
  443. bool nameAlreadyExists = false;
  444. auto directory = get_inode({ id(), parent });
  445. directory->traverse_as_directory([&] (auto& entry) {
  446. if (!strcmp(entry.name, name.characters())) {
  447. nameAlreadyExists = true;
  448. return false;
  449. }
  450. entries.append(entry);
  451. return true;
  452. });
  453. if (nameAlreadyExists) {
  454. kprintf("Ext2FS: Name '%s' already exists in directory inode %u\n", name.characters(), parent);
  455. error = -EEXIST;
  456. return false;
  457. }
  458. entries.append({ name.characters(), name.length(), { id(), child }, fileType });
  459. return write_directory_inode(parent, move(entries));
  460. }
  461. bool Ext2FS::write_directory_inode(unsigned directoryInode, Vector<DirectoryEntry>&& entries)
  462. {
  463. dbgprintf("Ext2FS: New directory inode %u contents to write:\n", directoryInode);
  464. unsigned directorySize = 0;
  465. for (auto& entry : entries) {
  466. //kprintf(" - %08u %s\n", entry.inode.index(), entry.name);
  467. directorySize += EXT2_DIR_REC_LEN(entry.name_length);
  468. }
  469. unsigned blocksNeeded = ceilDiv(directorySize, blockSize());
  470. unsigned occupiedSize = blocksNeeded * blockSize();
  471. dbgprintf("Ext2FS: directory size: %u (occupied: %u)\n", directorySize, occupiedSize);
  472. auto directoryData = ByteBuffer::createUninitialized(occupiedSize);
  473. BufferStream stream(directoryData);
  474. for (unsigned i = 0; i < entries.size(); ++i) {
  475. auto& entry = entries[i];
  476. unsigned recordLength = EXT2_DIR_REC_LEN(entry.name_length);
  477. if (i == entries.size() - 1)
  478. recordLength += occupiedSize - directorySize;
  479. dbgprintf("* inode: %u", entry.inode.index());
  480. dbgprintf(", name_len: %u", word(entry.name_length));
  481. dbgprintf(", rec_len: %u", word(recordLength));
  482. dbgprintf(", file_type: %u", byte(entry.fileType));
  483. dbgprintf(", name: %s\n", entry.name);
  484. stream << dword(entry.inode.index());
  485. stream << word(recordLength);
  486. stream << byte(entry.name_length);
  487. stream << byte(entry.fileType);
  488. stream << entry.name;
  489. unsigned padding = recordLength - entry.name_length - 8;
  490. //dbgprintf(" *** pad %u bytes\n", padding);
  491. for (unsigned j = 0; j < padding; ++j) {
  492. stream << byte(0);
  493. }
  494. }
  495. stream.fillToEnd(0);
  496. #if 0
  497. kprintf("data to write (%u):\n", directoryData.size());
  498. for (unsigned i = 0; i < directoryData.size(); ++i) {
  499. kprintf("%02x ", directoryData[i]);
  500. if ((i + 1) % 8 == 0)
  501. kprintf(" ");
  502. if ((i + 1) % 16 == 0)
  503. kprintf("\n");
  504. }
  505. kprintf("\n");
  506. #endif
  507. write_inode({ id(), directoryInode }, directoryData);
  508. return true;
  509. }
  510. unsigned Ext2FS::inodes_per_block() const
  511. {
  512. return EXT2_INODES_PER_BLOCK(&super_block());
  513. }
  514. unsigned Ext2FS::inodes_per_group() const
  515. {
  516. return EXT2_INODES_PER_GROUP(&super_block());
  517. }
  518. unsigned Ext2FS::inode_size() const
  519. {
  520. return EXT2_INODE_SIZE(&super_block());
  521. }
  522. unsigned Ext2FS::blocks_per_group() const
  523. {
  524. return EXT2_BLOCKS_PER_GROUP(&super_block());
  525. }
  526. void Ext2FS::dump_block_bitmap(unsigned groupIndex) const
  527. {
  528. ASSERT(groupIndex <= m_blockGroupCount);
  529. auto& bgd = group_descriptor(groupIndex);
  530. unsigned blocksInGroup = min(blocks_per_group(), super_block().s_blocks_count);
  531. unsigned blockCount = ceilDiv(blocksInGroup, 8u);
  532. auto bitmapBlocks = readBlocks(bgd.bg_block_bitmap, blockCount);
  533. ASSERT(bitmapBlocks);
  534. kprintf("ext2fs: group[%u] block bitmap (bitmap occupies %u blocks):\n", groupIndex, blockCount);
  535. auto bitmap = Bitmap::wrap(bitmapBlocks.pointer(), blocksInGroup);
  536. for (unsigned i = 0; i < blocksInGroup; ++i) {
  537. kprintf("%c", bitmap.get(i) ? '1' : '0');
  538. }
  539. kprintf("\n");
  540. }
  541. void Ext2FS::dump_inode_bitmap(unsigned groupIndex) const
  542. {
  543. traverse_inode_bitmap(groupIndex, [] (unsigned, const Bitmap& bitmap) {
  544. for (unsigned i = 0; i < bitmap.size(); ++i)
  545. kprintf("%c", bitmap.get(i) ? '1' : '0');
  546. return true;
  547. });
  548. }
  549. template<typename F>
  550. void Ext2FS::traverse_inode_bitmap(unsigned groupIndex, F callback) const
  551. {
  552. ASSERT(groupIndex <= m_blockGroupCount);
  553. auto& bgd = group_descriptor(groupIndex);
  554. unsigned inodesInGroup = min(inodes_per_group(), super_block().s_inodes_count);
  555. unsigned blockCount = ceilDiv(inodesInGroup, 8u);
  556. for (unsigned i = 0; i < blockCount; ++i) {
  557. auto block = readBlock(bgd.bg_inode_bitmap + i);
  558. ASSERT(block);
  559. bool shouldContinue = callback(i * (blockSize() / 8) + 1, Bitmap::wrap(block.pointer(), inodesInGroup));
  560. if (!shouldContinue)
  561. break;
  562. }
  563. }
  564. template<typename F>
  565. void Ext2FS::traverse_block_bitmap(unsigned groupIndex, F callback) const
  566. {
  567. ASSERT(groupIndex <= m_blockGroupCount);
  568. auto& bgd = group_descriptor(groupIndex);
  569. unsigned blocksInGroup = min(blocks_per_group(), super_block().s_blocks_count);
  570. unsigned blockCount = ceilDiv(blocksInGroup, 8u);
  571. for (unsigned i = 0; i < blockCount; ++i) {
  572. auto block = readBlock(bgd.bg_block_bitmap + i);
  573. ASSERT(block);
  574. bool shouldContinue = callback(i * (blockSize() / 8) + 1, Bitmap::wrap(block.pointer(), blocksInGroup));
  575. if (!shouldContinue)
  576. break;
  577. }
  578. }
  579. bool Ext2FS::modify_link_count(InodeIndex inode, int delta)
  580. {
  581. ASSERT(inode);
  582. auto e2inode = lookup_ext2_inode(inode);
  583. if (!e2inode)
  584. return false;
  585. auto newLinkCount = e2inode->i_links_count + delta;
  586. dbgprintf("Ext2FS: changing inode %u link count from %u to %u\n", inode, e2inode->i_links_count, newLinkCount);
  587. e2inode->i_links_count = newLinkCount;
  588. return write_ext2_inode(inode, *e2inode);
  589. }
  590. int Ext2FS::set_atime_and_mtime(InodeIdentifier inode, dword atime, dword mtime)
  591. {
  592. ASSERT(inode.fsid() == id());
  593. auto e2inode = lookup_ext2_inode(inode.index());
  594. if (!e2inode)
  595. return -EIO;
  596. dbgprintf("changing inode %u atime from %u to %u\n", inode.index(), e2inode->i_atime, atime);
  597. dbgprintf("changing inode %u mtime from %u to %u\n", inode.index(), e2inode->i_mtime, mtime);
  598. e2inode->i_mtime = mtime;
  599. e2inode->i_atime = atime;
  600. return write_ext2_inode(inode.index(), *e2inode);
  601. }
  602. bool Ext2FS::write_ext2_inode(unsigned inode, const ext2_inode& e2inode)
  603. {
  604. unsigned blockIndex;
  605. unsigned offset;
  606. auto block = read_block_containing_inode(inode, blockIndex, offset);
  607. if (!block)
  608. return false;
  609. {
  610. LOCKER(m_inode_cache_lock);
  611. auto it = m_inode_cache.find(inode);
  612. if (it != m_inode_cache.end()) {
  613. auto& cached_inode = *(*it).value;
  614. LOCKER(cached_inode.m_lock);
  615. cached_inode.m_raw_inode = e2inode;
  616. cached_inode.populate_metadata();
  617. if (cached_inode.is_directory())
  618. cached_inode.m_lookup_cache.clear();
  619. }
  620. }
  621. memcpy(reinterpret_cast<ext2_inode*>(block.offsetPointer(offset)), &e2inode, inode_size());
  622. writeBlock(blockIndex, block);
  623. return true;
  624. }
  625. bool Ext2FS::is_directory_inode(unsigned inode) const
  626. {
  627. if (auto e2inode = lookup_ext2_inode(inode))
  628. return isDirectory(e2inode->i_mode);
  629. return false;
  630. }
  631. Vector<Ext2FS::BlockIndex> Ext2FS::allocate_blocks(unsigned group, unsigned count)
  632. {
  633. dbgprintf("Ext2FS: allocateBlocks(group: %u, count: %u)\n", group, count);
  634. auto& bgd = group_descriptor(group);
  635. if (bgd.bg_free_blocks_count < count) {
  636. kprintf("ExtFS: allocateBlocks can't allocate out of group %u, wanted %u but only %u available\n", group, count, bgd.bg_free_blocks_count);
  637. return { };
  638. }
  639. // FIXME: Implement a scan that finds consecutive blocks if possible.
  640. Vector<BlockIndex> blocks;
  641. traverse_block_bitmap(group, [&blocks, count] (unsigned firstBlockInBitmap, const Bitmap& bitmap) {
  642. for (unsigned i = 0; i < bitmap.size(); ++i) {
  643. if (!bitmap.get(i)) {
  644. blocks.append(firstBlockInBitmap + i);
  645. if (blocks.size() == count)
  646. return false;
  647. }
  648. }
  649. return true;
  650. });
  651. dbgprintf("Ext2FS: allocateBlock found these blocks:\n");
  652. for (auto& bi : blocks) {
  653. dbgprintf(" > %u\n", bi);
  654. }
  655. return blocks;
  656. }
  657. unsigned Ext2FS::allocate_inode(unsigned preferredGroup, unsigned expectedSize)
  658. {
  659. dbgprintf("Ext2FS: allocateInode(preferredGroup: %u, expectedSize: %u)\n", preferredGroup, expectedSize);
  660. unsigned neededBlocks = ceilDiv(expectedSize, blockSize());
  661. dbgprintf("Ext2FS: minimum needed blocks: %u\n", neededBlocks);
  662. unsigned groupIndex = 0;
  663. auto isSuitableGroup = [this, neededBlocks] (unsigned groupIndex) {
  664. auto& bgd = group_descriptor(groupIndex);
  665. return bgd.bg_free_inodes_count && bgd.bg_free_blocks_count >= neededBlocks;
  666. };
  667. if (preferredGroup && isSuitableGroup(preferredGroup)) {
  668. groupIndex = preferredGroup;
  669. } else {
  670. for (unsigned i = 1; i <= m_blockGroupCount; ++i) {
  671. if (isSuitableGroup(i))
  672. groupIndex = i;
  673. }
  674. }
  675. if (!groupIndex) {
  676. kprintf("Ext2FS: allocateInode: no suitable group found for new inode with %u blocks needed :(\n", neededBlocks);
  677. return 0;
  678. }
  679. dbgprintf("Ext2FS: allocateInode: found suitable group [%u] for new inode with %u blocks needed :^)\n", groupIndex, neededBlocks);
  680. unsigned firstFreeInodeInGroup = 0;
  681. traverse_inode_bitmap(groupIndex, [&firstFreeInodeInGroup] (unsigned firstInodeInBitmap, const Bitmap& bitmap) {
  682. for (unsigned i = 0; i < bitmap.size(); ++i) {
  683. if (!bitmap.get(i)) {
  684. firstFreeInodeInGroup = firstInodeInBitmap + i;
  685. return false;
  686. }
  687. }
  688. return true;
  689. });
  690. if (!firstFreeInodeInGroup) {
  691. kprintf("Ext2FS: firstFreeInodeInGroup returned no inode, despite bgd claiming there are inodes :(\n");
  692. return 0;
  693. }
  694. unsigned inode = firstFreeInodeInGroup;
  695. dbgprintf("Ext2FS: found suitable inode %u\n", inode);
  696. // FIXME: allocate blocks if needed!
  697. return inode;
  698. }
  699. unsigned Ext2FS::group_index_from_inode(unsigned inode) const
  700. {
  701. if (!inode)
  702. return 0;
  703. return (inode - 1) / inodes_per_group() + 1;
  704. }
  705. bool Ext2FS::set_inode_allocation_state(unsigned inode, bool newState)
  706. {
  707. auto& bgd = group_descriptor(group_index_from_inode(inode));
  708. // Update inode bitmap
  709. unsigned inodesPerBitmapBlock = blockSize() * 8;
  710. unsigned bitmapBlockIndex = (inode - 1) / inodesPerBitmapBlock;
  711. unsigned bitIndex = (inode - 1) % inodesPerBitmapBlock;
  712. auto block = readBlock(bgd.bg_inode_bitmap + bitmapBlockIndex);
  713. ASSERT(block);
  714. auto bitmap = Bitmap::wrap(block.pointer(), block.size());
  715. bool currentState = bitmap.get(bitIndex);
  716. dbgprintf("ext2fs: setInodeAllocationState(%u) %u -> %u\n", inode, currentState, newState);
  717. if (currentState == newState)
  718. return true;
  719. bitmap.set(bitIndex, newState);
  720. writeBlock(bgd.bg_inode_bitmap + bitmapBlockIndex, block);
  721. // Update superblock
  722. auto& sb = *reinterpret_cast<ext2_super_block*>(m_cached_super_block.pointer());
  723. dbgprintf("Ext2FS: superblock free inode count %u -> %u\n", sb.s_free_inodes_count, sb.s_free_inodes_count - 1);
  724. if (newState)
  725. --sb.s_free_inodes_count;
  726. else
  727. ++sb.s_free_inodes_count;
  728. write_super_block(sb);
  729. // Update BGD
  730. auto& mutableBGD = const_cast<ext2_group_desc&>(bgd);
  731. if (newState)
  732. --mutableBGD.bg_free_inodes_count;
  733. else
  734. ++mutableBGD.bg_free_inodes_count;
  735. dbgprintf("Ext2FS: group free inode count %u -> %u\n", bgd.bg_free_inodes_count, bgd.bg_free_inodes_count - 1);
  736. unsigned blocksToWrite = ceilDiv(m_blockGroupCount * (unsigned)sizeof(ext2_group_desc), blockSize());
  737. unsigned firstBlockOfBGDT = blockSize() == 1024 ? 2 : 1;
  738. writeBlocks(firstBlockOfBGDT, blocksToWrite, m_cached_group_descriptor_table);
  739. return true;
  740. }
  741. bool Ext2FS::set_block_allocation_state(GroupIndex group, BlockIndex bi, bool newState)
  742. {
  743. auto& bgd = group_descriptor(group);
  744. // Update block bitmap
  745. unsigned blocksPerBitmapBlock = blockSize() * 8;
  746. unsigned bitmapBlockIndex = (bi - 1) / blocksPerBitmapBlock;
  747. unsigned bitIndex = (bi - 1) % blocksPerBitmapBlock;
  748. auto block = readBlock(bgd.bg_block_bitmap + bitmapBlockIndex);
  749. ASSERT(block);
  750. auto bitmap = Bitmap::wrap(block.pointer(), block.size());
  751. bool currentState = bitmap.get(bitIndex);
  752. dbgprintf("Ext2FS: setBlockAllocationState(%u) %u -> %u\n", bi, currentState, newState);
  753. if (currentState == newState)
  754. return true;
  755. bitmap.set(bitIndex, newState);
  756. writeBlock(bgd.bg_block_bitmap + bitmapBlockIndex, block);
  757. // Update superblock
  758. auto& sb = *reinterpret_cast<ext2_super_block*>(m_cached_super_block.pointer());
  759. dbgprintf("Ext2FS: superblock free block count %u -> %u\n", sb.s_free_blocks_count, sb.s_free_blocks_count - 1);
  760. if (newState)
  761. --sb.s_free_blocks_count;
  762. else
  763. ++sb.s_free_blocks_count;
  764. write_super_block(sb);
  765. // Update BGD
  766. auto& mutableBGD = const_cast<ext2_group_desc&>(bgd);
  767. if (newState)
  768. --mutableBGD.bg_free_blocks_count;
  769. else
  770. ++mutableBGD.bg_free_blocks_count;
  771. dbgprintf("Ext2FS: group free block count %u -> %u\n", bgd.bg_free_blocks_count, bgd.bg_free_blocks_count - 1);
  772. unsigned blocksToWrite = ceilDiv(m_blockGroupCount * (unsigned)sizeof(ext2_group_desc), blockSize());
  773. unsigned firstBlockOfBGDT = blockSize() == 1024 ? 2 : 1;
  774. writeBlocks(firstBlockOfBGDT, blocksToWrite, m_cached_group_descriptor_table);
  775. return true;
  776. }
  777. InodeIdentifier Ext2FS::create_directory(InodeIdentifier parentInode, const String& name, Unix::mode_t mode, int& error)
  778. {
  779. ASSERT(parentInode.fsid() == id());
  780. ASSERT(is_directory_inode(parentInode.index()));
  781. // Fix up the mode to definitely be a directory.
  782. // FIXME: This is a bit on the hackish side.
  783. mode &= ~0170000;
  784. mode |= 0040000;
  785. // NOTE: When creating a new directory, make the size 1 block.
  786. // There's probably a better strategy here, but this works for now.
  787. auto inode = create_inode(parentInode, name, mode, blockSize(), error);
  788. if (!inode.is_valid())
  789. return { };
  790. dbgprintf("Ext2FS: create_directory: created new directory named '%s' with inode %u\n", name.characters(), inode.index());
  791. Vector<DirectoryEntry> entries;
  792. entries.append({ ".", inode, EXT2_FT_DIR });
  793. entries.append({ "..", parentInode, EXT2_FT_DIR });
  794. bool success = write_directory_inode(inode.index(), move(entries));
  795. ASSERT(success);
  796. success = modify_link_count(parentInode.index(), 1);
  797. ASSERT(success);
  798. auto& bgd = const_cast<ext2_group_desc&>(group_descriptor(group_index_from_inode(inode.index())));
  799. ++bgd.bg_used_dirs_count;
  800. dbgprintf("Ext2FS: incremented bg_used_dirs_count %u -> %u\n", bgd.bg_used_dirs_count - 1, bgd.bg_used_dirs_count);
  801. unsigned blocksToWrite = ceilDiv(m_blockGroupCount * (unsigned)sizeof(ext2_group_desc), blockSize());
  802. unsigned firstBlockOfBGDT = blockSize() == 1024 ? 2 : 1;
  803. writeBlocks(firstBlockOfBGDT, blocksToWrite, m_cached_group_descriptor_table);
  804. error = 0;
  805. return inode;
  806. }
  807. InodeIdentifier Ext2FS::create_inode(InodeIdentifier parentInode, const String& name, Unix::mode_t mode, unsigned size, int& error)
  808. {
  809. ASSERT(parentInode.fsid() == id());
  810. ASSERT(is_directory_inode(parentInode.index()));
  811. dbgprintf("Ext2FS: Adding inode '%s' (mode %u) to parent directory %u:\n", name.characters(), mode, parentInode.index());
  812. // NOTE: This doesn't commit the inode allocation just yet!
  813. auto inode = allocate_inode(0, 0);
  814. if (!inode) {
  815. kprintf("Ext2FS: createInode: allocateInode failed\n");
  816. error = -ENOSPC;
  817. return { };
  818. }
  819. auto blocks = allocate_blocks(group_index_from_inode(inode), ceilDiv(size, blockSize()));
  820. if (blocks.isEmpty()) {
  821. kprintf("Ext2FS: createInode: allocateBlocks failed\n");
  822. error = -ENOSPC;
  823. return { };
  824. }
  825. byte fileType = 0;
  826. if (isRegularFile(mode))
  827. fileType = EXT2_FT_REG_FILE;
  828. else if (isDirectory(mode))
  829. fileType = EXT2_FT_DIR;
  830. else if (isCharacterDevice(mode))
  831. fileType = EXT2_FT_CHRDEV;
  832. else if (isBlockDevice(mode))
  833. fileType = EXT2_FT_BLKDEV;
  834. else if (isFIFO(mode))
  835. fileType = EXT2_FT_FIFO;
  836. else if (isSocket(mode))
  837. fileType = EXT2_FT_SOCK;
  838. else if (isSymbolicLink(mode))
  839. fileType = EXT2_FT_SYMLINK;
  840. // Try adding it to the directory first, in case the name is already in use.
  841. bool success = add_inode_to_directory(parentInode.index(), inode, name, fileType, error);
  842. if (!success)
  843. return { };
  844. // Looks like we're good, time to update the inode bitmap and group+global inode counters.
  845. success = set_inode_allocation_state(inode, true);
  846. ASSERT(success);
  847. for (auto bi : blocks) {
  848. success = set_block_allocation_state(group_index_from_inode(inode), bi, true);
  849. ASSERT(success);
  850. }
  851. unsigned initialLinksCount;
  852. if (isDirectory(mode))
  853. initialLinksCount = 2; // (parent directory + "." entry in self)
  854. else
  855. initialLinksCount = 1;
  856. auto timestamp = ktime(nullptr);
  857. auto e2inode = make<ext2_inode>();
  858. memset(e2inode.ptr(), 0, sizeof(ext2_inode));
  859. e2inode->i_mode = mode;
  860. e2inode->i_uid = 0;
  861. e2inode->i_size = size;
  862. e2inode->i_atime = timestamp;
  863. e2inode->i_ctime = timestamp;
  864. e2inode->i_mtime = timestamp;
  865. e2inode->i_dtime = 0;
  866. e2inode->i_gid = 0;
  867. e2inode->i_links_count = initialLinksCount;
  868. e2inode->i_blocks = blocks.size() * (blockSize() / 512);
  869. // FIXME: Implement writing out indirect blocks!
  870. ASSERT(blocks.size() < EXT2_NDIR_BLOCKS);
  871. dbgprintf("Ext2FS: writing %zu blocks to i_block array\n", min((size_t)EXT2_NDIR_BLOCKS, blocks.size()));
  872. for (unsigned i = 0; i < min((size_t)EXT2_NDIR_BLOCKS, blocks.size()); ++i) {
  873. e2inode->i_block[i] = blocks[i];
  874. }
  875. e2inode->i_flags = 0;
  876. success = write_ext2_inode(inode, *e2inode);
  877. ASSERT(success);
  878. return { id(), inode };
  879. }
  880. InodeIdentifier Ext2FS::find_parent_of_inode(InodeIdentifier inode_id) const
  881. {
  882. auto inode = get_inode(inode_id);
  883. ASSERT(inode);
  884. unsigned groupIndex = group_index_from_inode(inode->index());
  885. unsigned firstInodeInGroup = inodes_per_group() * (groupIndex - 1);
  886. Vector<RetainPtr<Ext2FSInode>> directories_in_group;
  887. for (unsigned i = 0; i < inodes_per_group(); ++i) {
  888. auto group_member = get_inode({ id(), firstInodeInGroup + i });
  889. if (!group_member)
  890. continue;
  891. if (group_member->is_directory())
  892. directories_in_group.append(move(group_member));
  893. }
  894. InodeIdentifier foundParent;
  895. for (auto& directory : directories_in_group) {
  896. if (!directory->reverse_lookup(inode->identifier()).isNull()) {
  897. foundParent = directory->identifier();
  898. break;
  899. }
  900. }
  901. return foundParent;
  902. }
  903. void Ext2FSInode::populate_lookup_cache()
  904. {
  905. {
  906. LOCKER(m_lock);
  907. if (!m_lookup_cache.isEmpty())
  908. return;
  909. }
  910. HashMap<String, unsigned> children;
  911. traverse_as_directory([&children] (auto& entry) {
  912. children.set(String(entry.name, entry.name_length), entry.inode.index());
  913. return true;
  914. });
  915. LOCKER(m_lock);
  916. if (!m_lookup_cache.isEmpty())
  917. return;
  918. m_lookup_cache = move(children);
  919. }
  920. InodeIdentifier Ext2FSInode::lookup(const String& name)
  921. {
  922. ASSERT(is_directory());
  923. populate_lookup_cache();
  924. LOCKER(m_lock);
  925. auto it = m_lookup_cache.find(name);
  926. if (it != m_lookup_cache.end())
  927. return { fsid(), (*it).value };
  928. return { };
  929. }
  930. String Ext2FSInode::reverse_lookup(InodeIdentifier child_id)
  931. {
  932. ASSERT(is_directory());
  933. ASSERT(child_id.fsid() == fsid());
  934. populate_lookup_cache();
  935. LOCKER(m_lock);
  936. for (auto it : m_lookup_cache) {
  937. if (it.value == child_id.index())
  938. return it.key;
  939. }
  940. return { };
  941. }