Ext2FileSystem.cpp 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145
  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::create_uninitialized(1024);
  26. device().read_block(2, buffer.pointer());
  27. device().read_block(3, buffer.offset_pointer(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.offset_pointer(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. : Inode(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. void Ext2FSInode::flush_metadata()
  256. {
  257. dbgprintf("Ext2FSInode: flush_metadata for inode %u\n", index());
  258. m_raw_inode.i_size = m_metadata.size;
  259. m_raw_inode.i_mode = m_metadata.mode;
  260. m_raw_inode.i_uid = m_metadata.uid;
  261. m_raw_inode.i_gid = m_metadata.gid;
  262. m_raw_inode.i_links_count = m_metadata.linkCount;
  263. m_raw_inode.i_atime = m_metadata.atime;
  264. m_raw_inode.i_ctime = m_metadata.ctime;
  265. m_raw_inode.i_mtime = m_metadata.mtime;
  266. m_raw_inode.i_dtime = m_metadata.dtime;
  267. m_raw_inode.i_blocks = m_metadata.blockCount;
  268. fs().write_ext2_inode(index(), m_raw_inode);
  269. set_metadata_dirty(false);
  270. }
  271. RetainPtr<Inode> Ext2FS::get_inode(InodeIdentifier inode) const
  272. {
  273. ASSERT(inode.fsid() == id());
  274. {
  275. LOCKER(m_inode_cache_lock);
  276. auto it = m_inode_cache.find(inode.index());
  277. if (it != m_inode_cache.end())
  278. return (*it).value;
  279. }
  280. auto raw_inode = lookup_ext2_inode(inode.index());
  281. if (!raw_inode)
  282. return nullptr;
  283. LOCKER(m_inode_cache_lock);
  284. auto it = m_inode_cache.find(inode.index());
  285. if (it != m_inode_cache.end())
  286. return (*it).value;
  287. auto new_inode = adopt(*new Ext2FSInode(const_cast<Ext2FS&>(*this), inode.index(), *raw_inode));
  288. m_inode_cache.set(inode.index(), new_inode.copyRef());
  289. return new_inode;
  290. }
  291. ssize_t Ext2FSInode::read_bytes(Unix::off_t offset, size_t count, byte* buffer, FileDescriptor*)
  292. {
  293. ASSERT(offset >= 0);
  294. if (m_raw_inode.i_size == 0)
  295. return 0;
  296. // Symbolic links shorter than 60 characters are store inline inside the i_block array.
  297. // This avoids wasting an entire block on short links. (Most links are short.)
  298. static const unsigned max_inline_symlink_length = 60;
  299. if (is_symlink() && size() < max_inline_symlink_length) {
  300. ssize_t nread = min((Unix::off_t)size() - offset, static_cast<Unix::off_t>(count));
  301. memcpy(buffer, m_raw_inode.i_block + offset, nread);
  302. return nread;
  303. }
  304. if (m_block_list.is_empty()) {
  305. auto block_list = fs().block_list_for_inode(m_raw_inode);
  306. LOCKER(m_lock);
  307. if (m_block_list.size() != block_list.size())
  308. m_block_list = move(block_list);
  309. }
  310. if (m_block_list.is_empty()) {
  311. kprintf("ext2fs: read_bytes: empty block list for inode %u\n", index());
  312. return -EIO;
  313. }
  314. const size_t block_size = fs().blockSize();
  315. dword first_block_logical_index = offset / block_size;
  316. dword last_block_logical_index = (offset + count) / block_size;
  317. if (last_block_logical_index >= m_block_list.size())
  318. last_block_logical_index = m_block_list.size() - 1;
  319. dword offset_into_first_block = offset % block_size;
  320. ssize_t nread = 0;
  321. size_t remaining_count = min((Unix::off_t)count, (Unix::off_t)size() - offset);
  322. byte* out = buffer;
  323. #ifdef EXT2_DEBUG
  324. kprintf("ok let's do it, read(%llu, %u) -> blocks %u thru %u, oifb: %u\n", offset, count, firstBlockLogicalIndex, lastBlockLogicalIndex, offsetIntoFirstBlock);
  325. #endif
  326. for (dword bi = first_block_logical_index; remaining_count && bi <= last_block_logical_index; ++bi) {
  327. auto block = fs().readBlock(m_block_list[bi]);
  328. if (!block) {
  329. kprintf("ext2fs: read_bytes: readBlock(%u) failed (lbi: %u)\n", m_block_list[bi], bi);
  330. return -EIO;
  331. }
  332. dword offset_into_block = (bi == first_block_logical_index) ? offset_into_first_block : 0;
  333. dword num_bytes_to_copy = min(block_size - offset_into_block, remaining_count);
  334. memcpy(out, block.pointer() + offset_into_block, num_bytes_to_copy);
  335. remaining_count -= num_bytes_to_copy;
  336. nread += num_bytes_to_copy;
  337. out += num_bytes_to_copy;
  338. }
  339. return nread;
  340. }
  341. ssize_t Ext2FS::read_inode_bytes(InodeIdentifier inode, Unix::off_t offset, size_t count, byte* buffer, FileDescriptor*) const
  342. {
  343. ASSERT(offset >= 0);
  344. ASSERT(inode.fsid() == id());
  345. auto e2inode = lookup_ext2_inode(inode.index());
  346. if (!e2inode) {
  347. kprintf("ext2fs: readInodeBytes: metadata lookup for inode %u failed\n", inode.index());
  348. return -EIO;
  349. }
  350. #if 0
  351. // FIXME: We can't fail here while the directory traversal depends on this function. :]
  352. if (isDirectory(e2inode->i_mode))
  353. return -EISDIR;
  354. #endif
  355. if (e2inode->i_size == 0)
  356. return 0;
  357. // Symbolic links shorter than 60 characters are store inline inside the i_block array.
  358. // This avoids wasting an entire block on short links. (Most links are short.)
  359. static const unsigned maxInlineSymlinkLength = 60;
  360. if (isSymbolicLink(e2inode->i_mode) && e2inode->i_size < maxInlineSymlinkLength) {
  361. ssize_t nread = min((Unix::off_t)e2inode->i_size - offset, static_cast<Unix::off_t>(count));
  362. memcpy(buffer, e2inode->i_block + offset, nread);
  363. return nread;
  364. }
  365. // FIXME: It's grossly inefficient to fetch the blocklist on every call to readInodeBytes().
  366. // It needs to be cached!
  367. auto list = block_list_for_inode(*e2inode);
  368. if (list.is_empty()) {
  369. kprintf("ext2fs: readInodeBytes: empty block list for inode %u\n", inode.index());
  370. return -EIO;
  371. }
  372. dword firstBlockLogicalIndex = offset / blockSize();
  373. dword lastBlockLogicalIndex = (offset + count) / blockSize();
  374. if (lastBlockLogicalIndex >= list.size())
  375. lastBlockLogicalIndex = list.size() - 1;
  376. dword offsetIntoFirstBlock = offset % blockSize();
  377. ssize_t nread = 0;
  378. size_t remainingCount = min((Unix::off_t)count, (Unix::off_t)e2inode->i_size - offset);
  379. byte* out = buffer;
  380. #ifdef EXT2_DEBUG
  381. kprintf("ok let's do it, read(%llu, %u) -> blocks %u thru %u, oifb: %u\n", offset, count, firstBlockLogicalIndex, lastBlockLogicalIndex, offsetIntoFirstBlock);
  382. #endif
  383. for (dword bi = firstBlockLogicalIndex; bi <= lastBlockLogicalIndex; ++bi) {
  384. auto block = readBlock(list[bi]);
  385. if (!block) {
  386. kprintf("ext2fs: readInodeBytes: readBlock(%u) failed (lbi: %u)\n", list[bi], bi);
  387. return -EIO;
  388. }
  389. dword offsetIntoBlock;
  390. if (bi == firstBlockLogicalIndex)
  391. offsetIntoBlock = offsetIntoFirstBlock;
  392. else
  393. offsetIntoBlock = 0;
  394. size_t numBytesToCopy = min(blockSize() - offsetIntoBlock, remainingCount);
  395. memcpy(out, block.pointer() + offsetIntoBlock, numBytesToCopy);
  396. remainingCount -= numBytesToCopy;
  397. nread += numBytesToCopy;
  398. out += numBytesToCopy;
  399. }
  400. return nread;
  401. }
  402. bool Ext2FS::write_inode(InodeIdentifier inode, const ByteBuffer& data)
  403. {
  404. ASSERT(inode.fsid() == id());
  405. auto e2inode = lookup_ext2_inode(inode.index());
  406. if (!e2inode) {
  407. kprintf("ext2fs: writeInode: metadata lookup for inode %u failed\n", inode.index());
  408. return false;
  409. }
  410. // FIXME: Support writing to symlink inodes.
  411. ASSERT(!isSymbolicLink(e2inode->i_mode));
  412. unsigned blocksNeededBefore = ceilDiv(e2inode->i_size, blockSize());
  413. unsigned blocksNeededAfter = ceilDiv((unsigned)data.size(), blockSize());
  414. // FIXME: Support growing or shrinking the block list.
  415. ASSERT(blocksNeededBefore == blocksNeededAfter);
  416. auto list = block_list_for_inode(*e2inode);
  417. if (list.is_empty()) {
  418. kprintf("ext2fs: writeInode: empty block list for inode %u\n", inode.index());
  419. return false;
  420. }
  421. for (unsigned i = 0; i < list.size(); ++i) {
  422. auto section = data.slice(i * blockSize(), blockSize());
  423. //kprintf("section = %p (%u)\n", section.pointer(), section.size());
  424. bool success = writeBlock(list[i], section);
  425. ASSERT(success);
  426. }
  427. return true;
  428. }
  429. bool Ext2FSInode::traverse_as_directory(Function<bool(const FS::DirectoryEntry&)> callback)
  430. {
  431. ASSERT(metadata().isDirectory());
  432. #ifdef EXT2_DEBUG
  433. kprintf("Ext2Inode::traverse_as_directory: inode=%u:\n", index());
  434. #endif
  435. auto buffer = read_entire();
  436. ASSERT(buffer);
  437. auto* entry = reinterpret_cast<ext2_dir_entry_2*>(buffer.pointer());
  438. while (entry < buffer.end_pointer()) {
  439. if (entry->inode != 0) {
  440. #ifdef EXT2_DEBUG
  441. 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);
  442. #endif
  443. if (!callback({ entry->name, entry->name_len, { fsid(), entry->inode }, entry->file_type }))
  444. break;
  445. }
  446. entry = (ext2_dir_entry_2*)((char*)entry + entry->rec_len);
  447. }
  448. return true;
  449. }
  450. bool Ext2FS::add_inode_to_directory(InodeIndex parent, InodeIndex child, const String& name, byte fileType, int& error)
  451. {
  452. auto e2inodeForDirectory = lookup_ext2_inode(parent);
  453. ASSERT(e2inodeForDirectory);
  454. ASSERT(isDirectory(e2inodeForDirectory->i_mode));
  455. //#ifdef EXT2_DEBUG
  456. dbgprintf("Ext2FS: Adding inode %u with name '%s' to directory %u\n", child, name.characters(), parent);
  457. //#endif
  458. Vector<DirectoryEntry> entries;
  459. bool nameAlreadyExists = false;
  460. auto directory = get_inode({ id(), parent });
  461. directory->traverse_as_directory([&] (auto& entry) {
  462. if (!strcmp(entry.name, name.characters())) {
  463. nameAlreadyExists = true;
  464. return false;
  465. }
  466. entries.append(entry);
  467. return true;
  468. });
  469. if (nameAlreadyExists) {
  470. kprintf("Ext2FS: Name '%s' already exists in directory inode %u\n", name.characters(), parent);
  471. error = -EEXIST;
  472. return false;
  473. }
  474. entries.append({ name.characters(), name.length(), { id(), child }, fileType });
  475. return write_directory_inode(parent, move(entries));
  476. }
  477. bool Ext2FS::write_directory_inode(unsigned directoryInode, Vector<DirectoryEntry>&& entries)
  478. {
  479. dbgprintf("Ext2FS: New directory inode %u contents to write:\n", directoryInode);
  480. unsigned directorySize = 0;
  481. for (auto& entry : entries) {
  482. //kprintf(" - %08u %s\n", entry.inode.index(), entry.name);
  483. directorySize += EXT2_DIR_REC_LEN(entry.name_length);
  484. }
  485. unsigned blocksNeeded = ceilDiv(directorySize, blockSize());
  486. unsigned occupiedSize = blocksNeeded * blockSize();
  487. dbgprintf("Ext2FS: directory size: %u (occupied: %u)\n", directorySize, occupiedSize);
  488. auto directoryData = ByteBuffer::create_uninitialized(occupiedSize);
  489. BufferStream stream(directoryData);
  490. for (unsigned i = 0; i < entries.size(); ++i) {
  491. auto& entry = entries[i];
  492. unsigned recordLength = EXT2_DIR_REC_LEN(entry.name_length);
  493. if (i == entries.size() - 1)
  494. recordLength += occupiedSize - directorySize;
  495. dbgprintf("* inode: %u", entry.inode.index());
  496. dbgprintf(", name_len: %u", word(entry.name_length));
  497. dbgprintf(", rec_len: %u", word(recordLength));
  498. dbgprintf(", file_type: %u", byte(entry.fileType));
  499. dbgprintf(", name: %s\n", entry.name);
  500. stream << dword(entry.inode.index());
  501. stream << word(recordLength);
  502. stream << byte(entry.name_length);
  503. stream << byte(entry.fileType);
  504. stream << entry.name;
  505. unsigned padding = recordLength - entry.name_length - 8;
  506. //dbgprintf(" *** pad %u bytes\n", padding);
  507. for (unsigned j = 0; j < padding; ++j) {
  508. stream << byte(0);
  509. }
  510. }
  511. stream.fillToEnd(0);
  512. #if 0
  513. kprintf("data to write (%u):\n", directoryData.size());
  514. for (unsigned i = 0; i < directoryData.size(); ++i) {
  515. kprintf("%02x ", directoryData[i]);
  516. if ((i + 1) % 8 == 0)
  517. kprintf(" ");
  518. if ((i + 1) % 16 == 0)
  519. kprintf("\n");
  520. }
  521. kprintf("\n");
  522. #endif
  523. write_inode({ id(), directoryInode }, directoryData);
  524. return true;
  525. }
  526. unsigned Ext2FS::inodes_per_block() const
  527. {
  528. return EXT2_INODES_PER_BLOCK(&super_block());
  529. }
  530. unsigned Ext2FS::inodes_per_group() const
  531. {
  532. return EXT2_INODES_PER_GROUP(&super_block());
  533. }
  534. unsigned Ext2FS::inode_size() const
  535. {
  536. return EXT2_INODE_SIZE(&super_block());
  537. }
  538. unsigned Ext2FS::blocks_per_group() const
  539. {
  540. return EXT2_BLOCKS_PER_GROUP(&super_block());
  541. }
  542. void Ext2FS::dump_block_bitmap(unsigned groupIndex) const
  543. {
  544. ASSERT(groupIndex <= m_blockGroupCount);
  545. auto& bgd = group_descriptor(groupIndex);
  546. unsigned blocksInGroup = min(blocks_per_group(), super_block().s_blocks_count);
  547. unsigned blockCount = ceilDiv(blocksInGroup, 8u);
  548. auto bitmapBlocks = readBlocks(bgd.bg_block_bitmap, blockCount);
  549. ASSERT(bitmapBlocks);
  550. kprintf("ext2fs: group[%u] block bitmap (bitmap occupies %u blocks):\n", groupIndex, blockCount);
  551. auto bitmap = Bitmap::wrap(bitmapBlocks.pointer(), blocksInGroup);
  552. for (unsigned i = 0; i < blocksInGroup; ++i) {
  553. kprintf("%c", bitmap.get(i) ? '1' : '0');
  554. }
  555. kprintf("\n");
  556. }
  557. void Ext2FS::dump_inode_bitmap(unsigned groupIndex) const
  558. {
  559. traverse_inode_bitmap(groupIndex, [] (unsigned, const Bitmap& bitmap) {
  560. for (unsigned i = 0; i < bitmap.size(); ++i)
  561. kprintf("%c", bitmap.get(i) ? '1' : '0');
  562. return true;
  563. });
  564. }
  565. template<typename F>
  566. void Ext2FS::traverse_inode_bitmap(unsigned groupIndex, F callback) const
  567. {
  568. ASSERT(groupIndex <= m_blockGroupCount);
  569. auto& bgd = group_descriptor(groupIndex);
  570. unsigned inodesInGroup = min(inodes_per_group(), super_block().s_inodes_count);
  571. unsigned blockCount = ceilDiv(inodesInGroup, 8u);
  572. for (unsigned i = 0; i < blockCount; ++i) {
  573. auto block = readBlock(bgd.bg_inode_bitmap + i);
  574. ASSERT(block);
  575. bool shouldContinue = callback(i * (blockSize() / 8) + 1, Bitmap::wrap(block.pointer(), inodesInGroup));
  576. if (!shouldContinue)
  577. break;
  578. }
  579. }
  580. template<typename F>
  581. void Ext2FS::traverse_block_bitmap(unsigned groupIndex, F callback) const
  582. {
  583. ASSERT(groupIndex <= m_blockGroupCount);
  584. auto& bgd = group_descriptor(groupIndex);
  585. unsigned blocksInGroup = min(blocks_per_group(), super_block().s_blocks_count);
  586. unsigned blockCount = ceilDiv(blocksInGroup, 8u);
  587. for (unsigned i = 0; i < blockCount; ++i) {
  588. auto block = readBlock(bgd.bg_block_bitmap + i);
  589. ASSERT(block);
  590. bool shouldContinue = callback(i * (blockSize() / 8) + 1, Bitmap::wrap(block.pointer(), blocksInGroup));
  591. if (!shouldContinue)
  592. break;
  593. }
  594. }
  595. bool Ext2FS::modify_link_count(InodeIndex inode, int delta)
  596. {
  597. ASSERT(inode);
  598. auto e2inode = lookup_ext2_inode(inode);
  599. if (!e2inode)
  600. return false;
  601. auto newLinkCount = e2inode->i_links_count + delta;
  602. dbgprintf("Ext2FS: changing inode %u link count from %u to %u\n", inode, e2inode->i_links_count, newLinkCount);
  603. e2inode->i_links_count = newLinkCount;
  604. return write_ext2_inode(inode, *e2inode);
  605. }
  606. bool Ext2FS::write_ext2_inode(unsigned inode, const ext2_inode& e2inode)
  607. {
  608. unsigned blockIndex;
  609. unsigned offset;
  610. auto block = read_block_containing_inode(inode, blockIndex, offset);
  611. if (!block)
  612. return false;
  613. {
  614. LOCKER(m_inode_cache_lock);
  615. auto it = m_inode_cache.find(inode);
  616. if (it != m_inode_cache.end()) {
  617. auto& cached_inode = *(*it).value;
  618. LOCKER(cached_inode.m_lock);
  619. cached_inode.m_raw_inode = e2inode;
  620. cached_inode.populate_metadata();
  621. if (cached_inode.is_directory())
  622. cached_inode.m_lookup_cache.clear();
  623. }
  624. }
  625. memcpy(reinterpret_cast<ext2_inode*>(block.offset_pointer(offset)), &e2inode, inode_size());
  626. writeBlock(blockIndex, block);
  627. return true;
  628. }
  629. bool Ext2FS::is_directory_inode(unsigned inode) const
  630. {
  631. if (auto e2inode = lookup_ext2_inode(inode))
  632. return isDirectory(e2inode->i_mode);
  633. return false;
  634. }
  635. Vector<Ext2FS::BlockIndex> Ext2FS::allocate_blocks(unsigned group, unsigned count)
  636. {
  637. dbgprintf("Ext2FS: allocateBlocks(group: %u, count: %u)\n", group, count);
  638. auto& bgd = group_descriptor(group);
  639. if (bgd.bg_free_blocks_count < count) {
  640. kprintf("ExtFS: allocateBlocks can't allocate out of group %u, wanted %u but only %u available\n", group, count, bgd.bg_free_blocks_count);
  641. return { };
  642. }
  643. // FIXME: Implement a scan that finds consecutive blocks if possible.
  644. Vector<BlockIndex> blocks;
  645. traverse_block_bitmap(group, [&blocks, count] (unsigned firstBlockInBitmap, const Bitmap& bitmap) {
  646. for (unsigned i = 0; i < bitmap.size(); ++i) {
  647. if (!bitmap.get(i)) {
  648. blocks.append(firstBlockInBitmap + i);
  649. if (blocks.size() == count)
  650. return false;
  651. }
  652. }
  653. return true;
  654. });
  655. dbgprintf("Ext2FS: allocateBlock found these blocks:\n");
  656. for (auto& bi : blocks) {
  657. dbgprintf(" > %u\n", bi);
  658. }
  659. return blocks;
  660. }
  661. unsigned Ext2FS::allocate_inode(unsigned preferredGroup, unsigned expectedSize)
  662. {
  663. dbgprintf("Ext2FS: allocateInode(preferredGroup: %u, expectedSize: %u)\n", preferredGroup, expectedSize);
  664. unsigned neededBlocks = ceilDiv(expectedSize, blockSize());
  665. dbgprintf("Ext2FS: minimum needed blocks: %u\n", neededBlocks);
  666. unsigned groupIndex = 0;
  667. auto isSuitableGroup = [this, neededBlocks] (unsigned groupIndex) {
  668. auto& bgd = group_descriptor(groupIndex);
  669. return bgd.bg_free_inodes_count && bgd.bg_free_blocks_count >= neededBlocks;
  670. };
  671. if (preferredGroup && isSuitableGroup(preferredGroup)) {
  672. groupIndex = preferredGroup;
  673. } else {
  674. for (unsigned i = 1; i <= m_blockGroupCount; ++i) {
  675. if (isSuitableGroup(i))
  676. groupIndex = i;
  677. }
  678. }
  679. if (!groupIndex) {
  680. kprintf("Ext2FS: allocateInode: no suitable group found for new inode with %u blocks needed :(\n", neededBlocks);
  681. return 0;
  682. }
  683. dbgprintf("Ext2FS: allocateInode: found suitable group [%u] for new inode with %u blocks needed :^)\n", groupIndex, neededBlocks);
  684. unsigned firstFreeInodeInGroup = 0;
  685. traverse_inode_bitmap(groupIndex, [&firstFreeInodeInGroup] (unsigned firstInodeInBitmap, const Bitmap& bitmap) {
  686. for (unsigned i = 0; i < bitmap.size(); ++i) {
  687. if (!bitmap.get(i)) {
  688. firstFreeInodeInGroup = firstInodeInBitmap + i;
  689. return false;
  690. }
  691. }
  692. return true;
  693. });
  694. if (!firstFreeInodeInGroup) {
  695. kprintf("Ext2FS: firstFreeInodeInGroup returned no inode, despite bgd claiming there are inodes :(\n");
  696. return 0;
  697. }
  698. unsigned inode = firstFreeInodeInGroup;
  699. dbgprintf("Ext2FS: found suitable inode %u\n", inode);
  700. // FIXME: allocate blocks if needed!
  701. return inode;
  702. }
  703. unsigned Ext2FS::group_index_from_inode(unsigned inode) const
  704. {
  705. if (!inode)
  706. return 0;
  707. return (inode - 1) / inodes_per_group() + 1;
  708. }
  709. bool Ext2FS::set_inode_allocation_state(unsigned inode, bool newState)
  710. {
  711. auto& bgd = group_descriptor(group_index_from_inode(inode));
  712. // Update inode bitmap
  713. unsigned inodesPerBitmapBlock = blockSize() * 8;
  714. unsigned bitmapBlockIndex = (inode - 1) / inodesPerBitmapBlock;
  715. unsigned bitIndex = (inode - 1) % inodesPerBitmapBlock;
  716. auto block = readBlock(bgd.bg_inode_bitmap + bitmapBlockIndex);
  717. ASSERT(block);
  718. auto bitmap = Bitmap::wrap(block.pointer(), block.size());
  719. bool currentState = bitmap.get(bitIndex);
  720. dbgprintf("ext2fs: setInodeAllocationState(%u) %u -> %u\n", inode, currentState, newState);
  721. if (currentState == newState)
  722. return true;
  723. bitmap.set(bitIndex, newState);
  724. writeBlock(bgd.bg_inode_bitmap + bitmapBlockIndex, block);
  725. // Update superblock
  726. auto& sb = *reinterpret_cast<ext2_super_block*>(m_cached_super_block.pointer());
  727. dbgprintf("Ext2FS: superblock free inode count %u -> %u\n", sb.s_free_inodes_count, sb.s_free_inodes_count - 1);
  728. if (newState)
  729. --sb.s_free_inodes_count;
  730. else
  731. ++sb.s_free_inodes_count;
  732. write_super_block(sb);
  733. // Update BGD
  734. auto& mutableBGD = const_cast<ext2_group_desc&>(bgd);
  735. if (newState)
  736. --mutableBGD.bg_free_inodes_count;
  737. else
  738. ++mutableBGD.bg_free_inodes_count;
  739. dbgprintf("Ext2FS: group free inode count %u -> %u\n", bgd.bg_free_inodes_count, bgd.bg_free_inodes_count - 1);
  740. unsigned blocksToWrite = ceilDiv(m_blockGroupCount * (unsigned)sizeof(ext2_group_desc), blockSize());
  741. unsigned firstBlockOfBGDT = blockSize() == 1024 ? 2 : 1;
  742. writeBlocks(firstBlockOfBGDT, blocksToWrite, m_cached_group_descriptor_table);
  743. return true;
  744. }
  745. bool Ext2FS::set_block_allocation_state(GroupIndex group, BlockIndex bi, bool newState)
  746. {
  747. auto& bgd = group_descriptor(group);
  748. // Update block bitmap
  749. unsigned blocksPerBitmapBlock = blockSize() * 8;
  750. unsigned bitmapBlockIndex = (bi - 1) / blocksPerBitmapBlock;
  751. unsigned bitIndex = (bi - 1) % blocksPerBitmapBlock;
  752. auto block = readBlock(bgd.bg_block_bitmap + bitmapBlockIndex);
  753. ASSERT(block);
  754. auto bitmap = Bitmap::wrap(block.pointer(), block.size());
  755. bool currentState = bitmap.get(bitIndex);
  756. dbgprintf("Ext2FS: setBlockAllocationState(%u) %u -> %u\n", bi, currentState, newState);
  757. if (currentState == newState)
  758. return true;
  759. bitmap.set(bitIndex, newState);
  760. writeBlock(bgd.bg_block_bitmap + bitmapBlockIndex, block);
  761. // Update superblock
  762. auto& sb = *reinterpret_cast<ext2_super_block*>(m_cached_super_block.pointer());
  763. dbgprintf("Ext2FS: superblock free block count %u -> %u\n", sb.s_free_blocks_count, sb.s_free_blocks_count - 1);
  764. if (newState)
  765. --sb.s_free_blocks_count;
  766. else
  767. ++sb.s_free_blocks_count;
  768. write_super_block(sb);
  769. // Update BGD
  770. auto& mutableBGD = const_cast<ext2_group_desc&>(bgd);
  771. if (newState)
  772. --mutableBGD.bg_free_blocks_count;
  773. else
  774. ++mutableBGD.bg_free_blocks_count;
  775. dbgprintf("Ext2FS: group free block count %u -> %u\n", bgd.bg_free_blocks_count, bgd.bg_free_blocks_count - 1);
  776. unsigned blocksToWrite = ceilDiv(m_blockGroupCount * (unsigned)sizeof(ext2_group_desc), blockSize());
  777. unsigned firstBlockOfBGDT = blockSize() == 1024 ? 2 : 1;
  778. writeBlocks(firstBlockOfBGDT, blocksToWrite, m_cached_group_descriptor_table);
  779. return true;
  780. }
  781. InodeIdentifier Ext2FS::create_directory(InodeIdentifier parentInode, const String& name, Unix::mode_t mode, int& error)
  782. {
  783. ASSERT(parentInode.fsid() == id());
  784. ASSERT(is_directory_inode(parentInode.index()));
  785. // Fix up the mode to definitely be a directory.
  786. // FIXME: This is a bit on the hackish side.
  787. mode &= ~0170000;
  788. mode |= 0040000;
  789. // NOTE: When creating a new directory, make the size 1 block.
  790. // There's probably a better strategy here, but this works for now.
  791. auto inode = create_inode(parentInode, name, mode, blockSize(), error);
  792. if (!inode.is_valid())
  793. return { };
  794. dbgprintf("Ext2FS: create_directory: created new directory named '%s' with inode %u\n", name.characters(), inode.index());
  795. Vector<DirectoryEntry> entries;
  796. entries.append({ ".", inode, EXT2_FT_DIR });
  797. entries.append({ "..", parentInode, EXT2_FT_DIR });
  798. bool success = write_directory_inode(inode.index(), move(entries));
  799. ASSERT(success);
  800. success = modify_link_count(parentInode.index(), 1);
  801. ASSERT(success);
  802. auto& bgd = const_cast<ext2_group_desc&>(group_descriptor(group_index_from_inode(inode.index())));
  803. ++bgd.bg_used_dirs_count;
  804. dbgprintf("Ext2FS: incremented bg_used_dirs_count %u -> %u\n", bgd.bg_used_dirs_count - 1, bgd.bg_used_dirs_count);
  805. unsigned blocksToWrite = ceilDiv(m_blockGroupCount * (unsigned)sizeof(ext2_group_desc), blockSize());
  806. unsigned firstBlockOfBGDT = blockSize() == 1024 ? 2 : 1;
  807. writeBlocks(firstBlockOfBGDT, blocksToWrite, m_cached_group_descriptor_table);
  808. error = 0;
  809. return inode;
  810. }
  811. InodeIdentifier Ext2FS::create_inode(InodeIdentifier parentInode, const String& name, Unix::mode_t mode, unsigned size, int& error)
  812. {
  813. ASSERT(parentInode.fsid() == id());
  814. ASSERT(is_directory_inode(parentInode.index()));
  815. dbgprintf("Ext2FS: Adding inode '%s' (mode %u) to parent directory %u:\n", name.characters(), mode, parentInode.index());
  816. // NOTE: This doesn't commit the inode allocation just yet!
  817. auto inode = allocate_inode(0, 0);
  818. if (!inode) {
  819. kprintf("Ext2FS: createInode: allocateInode failed\n");
  820. error = -ENOSPC;
  821. return { };
  822. }
  823. auto blocks = allocate_blocks(group_index_from_inode(inode), ceilDiv(size, blockSize()));
  824. if (blocks.is_empty()) {
  825. kprintf("Ext2FS: createInode: allocateBlocks failed\n");
  826. error = -ENOSPC;
  827. return { };
  828. }
  829. byte fileType = 0;
  830. if (isRegularFile(mode))
  831. fileType = EXT2_FT_REG_FILE;
  832. else if (isDirectory(mode))
  833. fileType = EXT2_FT_DIR;
  834. else if (isCharacterDevice(mode))
  835. fileType = EXT2_FT_CHRDEV;
  836. else if (isBlockDevice(mode))
  837. fileType = EXT2_FT_BLKDEV;
  838. else if (isFIFO(mode))
  839. fileType = EXT2_FT_FIFO;
  840. else if (isSocket(mode))
  841. fileType = EXT2_FT_SOCK;
  842. else if (isSymbolicLink(mode))
  843. fileType = EXT2_FT_SYMLINK;
  844. // Try adding it to the directory first, in case the name is already in use.
  845. bool success = add_inode_to_directory(parentInode.index(), inode, name, fileType, error);
  846. if (!success)
  847. return { };
  848. // Looks like we're good, time to update the inode bitmap and group+global inode counters.
  849. success = set_inode_allocation_state(inode, true);
  850. ASSERT(success);
  851. for (auto bi : blocks) {
  852. success = set_block_allocation_state(group_index_from_inode(inode), bi, true);
  853. ASSERT(success);
  854. }
  855. unsigned initialLinksCount;
  856. if (isDirectory(mode))
  857. initialLinksCount = 2; // (parent directory + "." entry in self)
  858. else
  859. initialLinksCount = 1;
  860. auto timestamp = ktime(nullptr);
  861. auto e2inode = make<ext2_inode>();
  862. memset(e2inode.ptr(), 0, sizeof(ext2_inode));
  863. e2inode->i_mode = mode;
  864. e2inode->i_uid = 0;
  865. e2inode->i_size = size;
  866. e2inode->i_atime = timestamp;
  867. e2inode->i_ctime = timestamp;
  868. e2inode->i_mtime = timestamp;
  869. e2inode->i_dtime = 0;
  870. e2inode->i_gid = 0;
  871. e2inode->i_links_count = initialLinksCount;
  872. e2inode->i_blocks = blocks.size() * (blockSize() / 512);
  873. // FIXME: Implement writing out indirect blocks!
  874. ASSERT(blocks.size() < EXT2_NDIR_BLOCKS);
  875. dbgprintf("Ext2FS: writing %zu blocks to i_block array\n", min((size_t)EXT2_NDIR_BLOCKS, blocks.size()));
  876. for (unsigned i = 0; i < min((size_t)EXT2_NDIR_BLOCKS, blocks.size()); ++i) {
  877. e2inode->i_block[i] = blocks[i];
  878. }
  879. e2inode->i_flags = 0;
  880. success = write_ext2_inode(inode, *e2inode);
  881. ASSERT(success);
  882. return { id(), inode };
  883. }
  884. InodeIdentifier Ext2FS::find_parent_of_inode(InodeIdentifier inode_id) const
  885. {
  886. auto inode = get_inode(inode_id);
  887. ASSERT(inode);
  888. unsigned groupIndex = group_index_from_inode(inode->index());
  889. unsigned firstInodeInGroup = inodes_per_group() * (groupIndex - 1);
  890. Vector<RetainPtr<Ext2FSInode>> directories_in_group;
  891. for (unsigned i = 0; i < inodes_per_group(); ++i) {
  892. auto group_member = get_inode({ id(), firstInodeInGroup + i });
  893. if (!group_member)
  894. continue;
  895. if (group_member->is_directory())
  896. directories_in_group.append(move(group_member));
  897. }
  898. InodeIdentifier foundParent;
  899. for (auto& directory : directories_in_group) {
  900. if (!directory->reverse_lookup(inode->identifier()).is_null()) {
  901. foundParent = directory->identifier();
  902. break;
  903. }
  904. }
  905. return foundParent;
  906. }
  907. void Ext2FSInode::populate_lookup_cache()
  908. {
  909. {
  910. LOCKER(m_lock);
  911. if (!m_lookup_cache.is_empty())
  912. return;
  913. }
  914. HashMap<String, unsigned> children;
  915. traverse_as_directory([&children] (auto& entry) {
  916. children.set(String(entry.name, entry.name_length), entry.inode.index());
  917. return true;
  918. });
  919. LOCKER(m_lock);
  920. if (!m_lookup_cache.is_empty())
  921. return;
  922. m_lookup_cache = move(children);
  923. }
  924. InodeIdentifier Ext2FSInode::lookup(const String& name)
  925. {
  926. ASSERT(is_directory());
  927. populate_lookup_cache();
  928. LOCKER(m_lock);
  929. auto it = m_lookup_cache.find(name);
  930. if (it != m_lookup_cache.end())
  931. return { fsid(), (*it).value };
  932. return { };
  933. }
  934. String Ext2FSInode::reverse_lookup(InodeIdentifier child_id)
  935. {
  936. ASSERT(is_directory());
  937. ASSERT(child_id.fsid() == fsid());
  938. populate_lookup_cache();
  939. LOCKER(m_lock);
  940. for (auto it : m_lookup_cache) {
  941. if (it.value == child_id.index())
  942. return it.key;
  943. }
  944. return { };
  945. }