Ext2FileSystem.cpp 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142
  1. #include "Ext2FileSystem.h"
  2. #include "ext2_fs.h"
  3. #include "UnixTypes.h"
  4. #include <AK/Bitmap.h>
  5. #include <AK/StdLib.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. bool Ext2FS::set_mtime(InodeIdentifier inode, dword timestamp)
  591. {
  592. ASSERT(inode.fsid() == id());
  593. auto e2inode = lookup_ext2_inode(inode.index());
  594. if (!e2inode)
  595. return false;
  596. kprintf("changing inode %u mtime from %u to %u\n", inode.index(), e2inode->i_mtime, timestamp);
  597. e2inode->i_mtime = timestamp;
  598. return write_ext2_inode(inode.index(), *e2inode);
  599. }
  600. bool Ext2FS::write_ext2_inode(unsigned inode, const ext2_inode& e2inode)
  601. {
  602. unsigned blockIndex;
  603. unsigned offset;
  604. auto block = read_block_containing_inode(inode, blockIndex, offset);
  605. if (!block)
  606. return false;
  607. {
  608. LOCKER(m_inode_cache_lock);
  609. auto it = m_inode_cache.find(inode);
  610. if (it != m_inode_cache.end()) {
  611. auto& cached_inode = *(*it).value;
  612. LOCKER(cached_inode.m_lock);
  613. cached_inode.m_raw_inode = e2inode;
  614. cached_inode.populate_metadata();
  615. if (cached_inode.is_directory())
  616. cached_inode.m_lookup_cache.clear();
  617. }
  618. }
  619. memcpy(reinterpret_cast<ext2_inode*>(block.offsetPointer(offset)), &e2inode, inode_size());
  620. writeBlock(blockIndex, block);
  621. return true;
  622. }
  623. bool Ext2FS::is_directory_inode(unsigned inode) const
  624. {
  625. if (auto e2inode = lookup_ext2_inode(inode))
  626. return isDirectory(e2inode->i_mode);
  627. return false;
  628. }
  629. Vector<Ext2FS::BlockIndex> Ext2FS::allocate_blocks(unsigned group, unsigned count)
  630. {
  631. dbgprintf("Ext2FS: allocateBlocks(group: %u, count: %u)\n", group, count);
  632. auto& bgd = group_descriptor(group);
  633. if (bgd.bg_free_blocks_count < count) {
  634. kprintf("ExtFS: allocateBlocks can't allocate out of group %u, wanted %u but only %u available\n", group, count, bgd.bg_free_blocks_count);
  635. return { };
  636. }
  637. // FIXME: Implement a scan that finds consecutive blocks if possible.
  638. Vector<BlockIndex> blocks;
  639. traverse_block_bitmap(group, [&blocks, count] (unsigned firstBlockInBitmap, const Bitmap& bitmap) {
  640. for (unsigned i = 0; i < bitmap.size(); ++i) {
  641. if (!bitmap.get(i)) {
  642. blocks.append(firstBlockInBitmap + i);
  643. if (blocks.size() == count)
  644. return false;
  645. }
  646. }
  647. return true;
  648. });
  649. dbgprintf("Ext2FS: allocateBlock found these blocks:\n");
  650. for (auto& bi : blocks) {
  651. dbgprintf(" > %u\n", bi);
  652. }
  653. return blocks;
  654. }
  655. unsigned Ext2FS::allocate_inode(unsigned preferredGroup, unsigned expectedSize)
  656. {
  657. dbgprintf("Ext2FS: allocateInode(preferredGroup: %u, expectedSize: %u)\n", preferredGroup, expectedSize);
  658. unsigned neededBlocks = ceilDiv(expectedSize, blockSize());
  659. dbgprintf("Ext2FS: minimum needed blocks: %u\n", neededBlocks);
  660. unsigned groupIndex = 0;
  661. auto isSuitableGroup = [this, neededBlocks] (unsigned groupIndex) {
  662. auto& bgd = group_descriptor(groupIndex);
  663. return bgd.bg_free_inodes_count && bgd.bg_free_blocks_count >= neededBlocks;
  664. };
  665. if (preferredGroup && isSuitableGroup(preferredGroup)) {
  666. groupIndex = preferredGroup;
  667. } else {
  668. for (unsigned i = 1; i <= m_blockGroupCount; ++i) {
  669. if (isSuitableGroup(i))
  670. groupIndex = i;
  671. }
  672. }
  673. if (!groupIndex) {
  674. kprintf("Ext2FS: allocateInode: no suitable group found for new inode with %u blocks needed :(\n", neededBlocks);
  675. return 0;
  676. }
  677. dbgprintf("Ext2FS: allocateInode: found suitable group [%u] for new inode with %u blocks needed :^)\n", groupIndex, neededBlocks);
  678. unsigned firstFreeInodeInGroup = 0;
  679. traverse_inode_bitmap(groupIndex, [&firstFreeInodeInGroup] (unsigned firstInodeInBitmap, const Bitmap& bitmap) {
  680. for (unsigned i = 0; i < bitmap.size(); ++i) {
  681. if (!bitmap.get(i)) {
  682. firstFreeInodeInGroup = firstInodeInBitmap + i;
  683. return false;
  684. }
  685. }
  686. return true;
  687. });
  688. if (!firstFreeInodeInGroup) {
  689. kprintf("Ext2FS: firstFreeInodeInGroup returned no inode, despite bgd claiming there are inodes :(\n");
  690. return 0;
  691. }
  692. unsigned inode = firstFreeInodeInGroup;
  693. dbgprintf("Ext2FS: found suitable inode %u\n", inode);
  694. // FIXME: allocate blocks if needed!
  695. return inode;
  696. }
  697. unsigned Ext2FS::group_index_from_inode(unsigned inode) const
  698. {
  699. if (!inode)
  700. return 0;
  701. return (inode - 1) / inodes_per_group() + 1;
  702. }
  703. bool Ext2FS::set_inode_allocation_state(unsigned inode, bool newState)
  704. {
  705. auto& bgd = group_descriptor(group_index_from_inode(inode));
  706. // Update inode bitmap
  707. unsigned inodesPerBitmapBlock = blockSize() * 8;
  708. unsigned bitmapBlockIndex = (inode - 1) / inodesPerBitmapBlock;
  709. unsigned bitIndex = (inode - 1) % inodesPerBitmapBlock;
  710. auto block = readBlock(bgd.bg_inode_bitmap + bitmapBlockIndex);
  711. ASSERT(block);
  712. auto bitmap = Bitmap::wrap(block.pointer(), block.size());
  713. bool currentState = bitmap.get(bitIndex);
  714. dbgprintf("ext2fs: setInodeAllocationState(%u) %u -> %u\n", inode, currentState, newState);
  715. if (currentState == newState)
  716. return true;
  717. bitmap.set(bitIndex, newState);
  718. writeBlock(bgd.bg_inode_bitmap + bitmapBlockIndex, block);
  719. // Update superblock
  720. auto& sb = *reinterpret_cast<ext2_super_block*>(m_cached_super_block.pointer());
  721. dbgprintf("Ext2FS: superblock free inode count %u -> %u\n", sb.s_free_inodes_count, sb.s_free_inodes_count - 1);
  722. if (newState)
  723. --sb.s_free_inodes_count;
  724. else
  725. ++sb.s_free_inodes_count;
  726. write_super_block(sb);
  727. // Update BGD
  728. auto& mutableBGD = const_cast<ext2_group_desc&>(bgd);
  729. if (newState)
  730. --mutableBGD.bg_free_inodes_count;
  731. else
  732. ++mutableBGD.bg_free_inodes_count;
  733. dbgprintf("Ext2FS: group free inode count %u -> %u\n", bgd.bg_free_inodes_count, bgd.bg_free_inodes_count - 1);
  734. unsigned blocksToWrite = ceilDiv(m_blockGroupCount * (unsigned)sizeof(ext2_group_desc), blockSize());
  735. unsigned firstBlockOfBGDT = blockSize() == 1024 ? 2 : 1;
  736. writeBlocks(firstBlockOfBGDT, blocksToWrite, m_cached_group_descriptor_table);
  737. return true;
  738. }
  739. bool Ext2FS::set_block_allocation_state(GroupIndex group, BlockIndex bi, bool newState)
  740. {
  741. auto& bgd = group_descriptor(group);
  742. // Update block bitmap
  743. unsigned blocksPerBitmapBlock = blockSize() * 8;
  744. unsigned bitmapBlockIndex = (bi - 1) / blocksPerBitmapBlock;
  745. unsigned bitIndex = (bi - 1) % blocksPerBitmapBlock;
  746. auto block = readBlock(bgd.bg_block_bitmap + bitmapBlockIndex);
  747. ASSERT(block);
  748. auto bitmap = Bitmap::wrap(block.pointer(), block.size());
  749. bool currentState = bitmap.get(bitIndex);
  750. dbgprintf("Ext2FS: setBlockAllocationState(%u) %u -> %u\n", bi, currentState, newState);
  751. if (currentState == newState)
  752. return true;
  753. bitmap.set(bitIndex, newState);
  754. writeBlock(bgd.bg_block_bitmap + bitmapBlockIndex, block);
  755. // Update superblock
  756. auto& sb = *reinterpret_cast<ext2_super_block*>(m_cached_super_block.pointer());
  757. dbgprintf("Ext2FS: superblock free block count %u -> %u\n", sb.s_free_blocks_count, sb.s_free_blocks_count - 1);
  758. if (newState)
  759. --sb.s_free_blocks_count;
  760. else
  761. ++sb.s_free_blocks_count;
  762. write_super_block(sb);
  763. // Update BGD
  764. auto& mutableBGD = const_cast<ext2_group_desc&>(bgd);
  765. if (newState)
  766. --mutableBGD.bg_free_blocks_count;
  767. else
  768. ++mutableBGD.bg_free_blocks_count;
  769. dbgprintf("Ext2FS: group free block count %u -> %u\n", bgd.bg_free_blocks_count, bgd.bg_free_blocks_count - 1);
  770. unsigned blocksToWrite = ceilDiv(m_blockGroupCount * (unsigned)sizeof(ext2_group_desc), blockSize());
  771. unsigned firstBlockOfBGDT = blockSize() == 1024 ? 2 : 1;
  772. writeBlocks(firstBlockOfBGDT, blocksToWrite, m_cached_group_descriptor_table);
  773. return true;
  774. }
  775. InodeIdentifier Ext2FS::create_directory(InodeIdentifier parentInode, const String& name, Unix::mode_t mode, int& error)
  776. {
  777. ASSERT(parentInode.fsid() == id());
  778. ASSERT(is_directory_inode(parentInode.index()));
  779. // Fix up the mode to definitely be a directory.
  780. // FIXME: This is a bit on the hackish side.
  781. mode &= ~0170000;
  782. mode |= 0040000;
  783. // NOTE: When creating a new directory, make the size 1 block.
  784. // There's probably a better strategy here, but this works for now.
  785. auto inode = create_inode(parentInode, name, mode, blockSize(), error);
  786. if (!inode.is_valid())
  787. return { };
  788. dbgprintf("Ext2FS: create_directory: created new directory named '%s' with inode %u\n", name.characters(), inode.index());
  789. Vector<DirectoryEntry> entries;
  790. entries.append({ ".", inode, EXT2_FT_DIR });
  791. entries.append({ "..", parentInode, EXT2_FT_DIR });
  792. bool success = write_directory_inode(inode.index(), move(entries));
  793. ASSERT(success);
  794. success = modify_link_count(parentInode.index(), 1);
  795. ASSERT(success);
  796. auto& bgd = const_cast<ext2_group_desc&>(group_descriptor(group_index_from_inode(inode.index())));
  797. ++bgd.bg_used_dirs_count;
  798. dbgprintf("Ext2FS: incremented bg_used_dirs_count %u -> %u\n", bgd.bg_used_dirs_count - 1, bgd.bg_used_dirs_count);
  799. unsigned blocksToWrite = ceilDiv(m_blockGroupCount * (unsigned)sizeof(ext2_group_desc), blockSize());
  800. unsigned firstBlockOfBGDT = blockSize() == 1024 ? 2 : 1;
  801. writeBlocks(firstBlockOfBGDT, blocksToWrite, m_cached_group_descriptor_table);
  802. error = 0;
  803. return inode;
  804. }
  805. InodeIdentifier Ext2FS::create_inode(InodeIdentifier parentInode, const String& name, Unix::mode_t mode, unsigned size, int& error)
  806. {
  807. ASSERT(parentInode.fsid() == id());
  808. ASSERT(is_directory_inode(parentInode.index()));
  809. dbgprintf("Ext2FS: Adding inode '%s' (mode %u) to parent directory %u:\n", name.characters(), mode, parentInode.index());
  810. // NOTE: This doesn't commit the inode allocation just yet!
  811. auto inode = allocate_inode(0, 0);
  812. if (!inode) {
  813. kprintf("Ext2FS: createInode: allocateInode failed\n");
  814. error = -ENOSPC;
  815. return { };
  816. }
  817. auto blocks = allocate_blocks(group_index_from_inode(inode), ceilDiv(size, blockSize()));
  818. if (blocks.isEmpty()) {
  819. kprintf("Ext2FS: createInode: allocateBlocks failed\n");
  820. error = -ENOSPC;
  821. return { };
  822. }
  823. byte fileType = 0;
  824. if (isRegularFile(mode))
  825. fileType = EXT2_FT_REG_FILE;
  826. else if (isDirectory(mode))
  827. fileType = EXT2_FT_DIR;
  828. else if (isCharacterDevice(mode))
  829. fileType = EXT2_FT_CHRDEV;
  830. else if (isBlockDevice(mode))
  831. fileType = EXT2_FT_BLKDEV;
  832. else if (isFIFO(mode))
  833. fileType = EXT2_FT_FIFO;
  834. else if (isSocket(mode))
  835. fileType = EXT2_FT_SOCK;
  836. else if (isSymbolicLink(mode))
  837. fileType = EXT2_FT_SYMLINK;
  838. // Try adding it to the directory first, in case the name is already in use.
  839. bool success = add_inode_to_directory(parentInode.index(), inode, name, fileType, error);
  840. if (!success)
  841. return { };
  842. // Looks like we're good, time to update the inode bitmap and group+global inode counters.
  843. success = set_inode_allocation_state(inode, true);
  844. ASSERT(success);
  845. for (auto bi : blocks) {
  846. success = set_block_allocation_state(group_index_from_inode(inode), bi, true);
  847. ASSERT(success);
  848. }
  849. unsigned initialLinksCount;
  850. if (isDirectory(mode))
  851. initialLinksCount = 2; // (parent directory + "." entry in self)
  852. else
  853. initialLinksCount = 1;
  854. auto timestamp = ktime(nullptr);
  855. auto e2inode = make<ext2_inode>();
  856. memset(e2inode.ptr(), 0, sizeof(ext2_inode));
  857. e2inode->i_mode = mode;
  858. e2inode->i_uid = 0;
  859. e2inode->i_size = size;
  860. e2inode->i_atime = timestamp;
  861. e2inode->i_ctime = timestamp;
  862. e2inode->i_mtime = timestamp;
  863. e2inode->i_dtime = 0;
  864. e2inode->i_gid = 0;
  865. e2inode->i_links_count = initialLinksCount;
  866. e2inode->i_blocks = blocks.size() * (blockSize() / 512);
  867. // FIXME: Implement writing out indirect blocks!
  868. ASSERT(blocks.size() < EXT2_NDIR_BLOCKS);
  869. dbgprintf("Ext2FS: writing %zu blocks to i_block array\n", min((size_t)EXT2_NDIR_BLOCKS, blocks.size()));
  870. for (unsigned i = 0; i < min((size_t)EXT2_NDIR_BLOCKS, blocks.size()); ++i) {
  871. e2inode->i_block[i] = blocks[i];
  872. }
  873. e2inode->i_flags = 0;
  874. success = write_ext2_inode(inode, *e2inode);
  875. ASSERT(success);
  876. return { id(), inode };
  877. }
  878. InodeIdentifier Ext2FS::find_parent_of_inode(InodeIdentifier inode_id) const
  879. {
  880. auto inode = get_inode(inode_id);
  881. ASSERT(inode);
  882. unsigned groupIndex = group_index_from_inode(inode->index());
  883. unsigned firstInodeInGroup = inodes_per_group() * (groupIndex - 1);
  884. Vector<RetainPtr<Ext2FSInode>> directories_in_group;
  885. for (unsigned i = 0; i < inodes_per_group(); ++i) {
  886. auto group_member = get_inode({ id(), firstInodeInGroup + i });
  887. if (!group_member)
  888. continue;
  889. if (group_member->is_directory())
  890. directories_in_group.append(move(group_member));
  891. }
  892. InodeIdentifier foundParent;
  893. for (auto& directory : directories_in_group) {
  894. if (!directory->reverse_lookup(inode->identifier()).isNull()) {
  895. foundParent = directory->identifier();
  896. break;
  897. }
  898. }
  899. return foundParent;
  900. }
  901. void Ext2FSInode::populate_lookup_cache()
  902. {
  903. {
  904. LOCKER(m_lock);
  905. if (!m_lookup_cache.isEmpty())
  906. return;
  907. }
  908. HashMap<String, unsigned> children;
  909. traverse_as_directory([&children] (auto& entry) {
  910. children.set(String(entry.name, entry.name_length), entry.inode.index());
  911. return true;
  912. });
  913. LOCKER(m_lock);
  914. if (!m_lookup_cache.isEmpty())
  915. return;
  916. m_lookup_cache = move(children);
  917. }
  918. InodeIdentifier Ext2FSInode::lookup(const String& name)
  919. {
  920. ASSERT(is_directory());
  921. populate_lookup_cache();
  922. LOCKER(m_lock);
  923. auto it = m_lookup_cache.find(name);
  924. if (it != m_lookup_cache.end())
  925. return { fsid(), (*it).value };
  926. return { };
  927. }
  928. String Ext2FSInode::reverse_lookup(InodeIdentifier child_id)
  929. {
  930. ASSERT(is_directory());
  931. ASSERT(child_id.fsid() == fsid());
  932. populate_lookup_cache();
  933. LOCKER(m_lock);
  934. for (auto it : m_lookup_cache) {
  935. if (it.value == child_id.index())
  936. return it.key;
  937. }
  938. return { };
  939. }