Ext2FileSystem.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749
  1. #include "Ext2FileSystem.h"
  2. #include "ext2_fs.h"
  3. #include <AK/Bitmap.h>
  4. #include <AK/StdLib.h>
  5. #include <cstdio>
  6. #include <cstring>
  7. #include <AK/kmalloc.h>
  8. //#define EXT2_DEBUG
  9. RetainPtr<Ext2FileSystem> Ext2FileSystem::create(RetainPtr<BlockDevice> device)
  10. {
  11. return adopt(*new Ext2FileSystem(std::move(device)));
  12. }
  13. Ext2FileSystem::Ext2FileSystem(RetainPtr<BlockDevice> device)
  14. : DeviceBackedFileSystem(std::move(device))
  15. {
  16. }
  17. Ext2FileSystem::~Ext2FileSystem()
  18. {
  19. }
  20. ByteBuffer Ext2FileSystem::readSuperBlock() const
  21. {
  22. auto buffer = ByteBuffer::createUninitialized(1024);
  23. device().readBlock(2, buffer.pointer());
  24. device().readBlock(3, buffer.offsetPointer(512));
  25. return buffer;
  26. }
  27. bool Ext2FileSystem::writeSuperBlock(const ext2_super_block& sb)
  28. {
  29. const byte* raw = (const byte*)&sb;
  30. bool success;
  31. success = device().writeBlock(2, raw);
  32. ASSERT(success);
  33. success = device().writeBlock(3, raw + 512);
  34. ASSERT(success);
  35. // FIXME: This is an ugly way to refresh the superblock cache. :-|
  36. superBlock();
  37. return true;
  38. }
  39. unsigned Ext2FileSystem::firstBlockOfGroup(unsigned groupIndex) const
  40. {
  41. return superBlock().s_first_data_block + (groupIndex * superBlock().s_blocks_per_group);
  42. }
  43. const ext2_super_block& Ext2FileSystem::superBlock() const
  44. {
  45. if (!m_cachedSuperBlock)
  46. m_cachedSuperBlock = readSuperBlock();
  47. return *reinterpret_cast<ext2_super_block*>(m_cachedSuperBlock.pointer());
  48. }
  49. const ext2_group_desc& Ext2FileSystem::blockGroupDescriptor(unsigned groupIndex) const
  50. {
  51. // FIXME: Should this fail gracefully somehow?
  52. ASSERT(groupIndex <= m_blockGroupCount);
  53. if (!m_cachedBlockGroupDescriptorTable) {
  54. unsigned blocksToRead = ceilDiv(m_blockGroupCount * sizeof(ext2_group_desc), blockSize());
  55. printf("[ext2fs] block group count: %u, blocks-to-read: %u\n", m_blockGroupCount, blocksToRead);
  56. unsigned firstBlockOfBGDT = blockSize() == 1024 ? 2 : 1;
  57. printf("[ext2fs] first block of BGDT: %u\n", firstBlockOfBGDT);
  58. m_cachedBlockGroupDescriptorTable = readBlocks(firstBlockOfBGDT, blocksToRead);
  59. }
  60. return reinterpret_cast<ext2_group_desc*>(m_cachedBlockGroupDescriptorTable.pointer())[groupIndex - 1];
  61. }
  62. bool Ext2FileSystem::initialize()
  63. {
  64. auto& superBlock = this->superBlock();
  65. printf("[ext2fs] super block magic: %04x (super block size: %u)\n", superBlock.s_magic, sizeof(ext2_super_block));
  66. if (superBlock.s_magic != EXT2_SUPER_MAGIC)
  67. return false;
  68. printf("[ext2fs] %u inodes, %u blocks\n", superBlock.s_inodes_count, superBlock.s_blocks_count);
  69. printf("[ext2fs] block size = %u\n", EXT2_BLOCK_SIZE(&superBlock));
  70. printf("[ext2fs] first data block = %u\n", superBlock.s_first_data_block);
  71. printf("[ext2fs] inodes per block = %u\n", inodesPerBlock());
  72. printf("[ext2fs] inodes per group = %u\n", inodesPerGroup());
  73. printf("[ext2fs] free inodes = %u\n", superBlock.s_free_inodes_count);
  74. printf("[ext2fs] desc per block = %u\n", EXT2_DESC_PER_BLOCK(&superBlock));
  75. printf("[ext2fs] desc size = %u\n", EXT2_DESC_SIZE(&superBlock));
  76. setBlockSize(EXT2_BLOCK_SIZE(&superBlock));
  77. m_blockGroupCount = ceilDiv(superBlock.s_blocks_count, superBlock.s_blocks_per_group);
  78. if (m_blockGroupCount == 0) {
  79. printf("[ext2fs] no block groups :(\n");
  80. return false;
  81. }
  82. for (unsigned i = 1; i <= m_blockGroupCount; ++i) {
  83. auto& group = blockGroupDescriptor(i);
  84. printf("[ext2fs] group[%u] { block_bitmap: %u, inode_bitmap: %u, inode_table: %u }\n",
  85. i,
  86. group.bg_block_bitmap,
  87. group.bg_inode_bitmap,
  88. group.bg_inode_table);
  89. }
  90. return true;
  91. }
  92. const char* Ext2FileSystem::className() const
  93. {
  94. return "ext2fs";
  95. }
  96. InodeIdentifier Ext2FileSystem::rootInode() const
  97. {
  98. return { id(), EXT2_ROOT_INO };
  99. }
  100. #ifdef EXT2_DEBUG
  101. static void dumpExt2Inode(const ext2_inode& inode)
  102. {
  103. printf("Dump of ext2_inode:\n");
  104. printf(" i_size: %u\n", inode.i_size);
  105. printf(" i_mode: %u\n", inode.i_mode);
  106. printf(" i_blocks: %u\n", inode.i_blocks);
  107. printf(" i_uid: %u\n", inode.i_uid);
  108. printf(" i_gid: %u\n", inode.i_gid);
  109. }
  110. #endif
  111. ByteBuffer Ext2FileSystem::readBlockContainingInode(unsigned inode, unsigned& blockIndex, unsigned& offset) const
  112. {
  113. auto& superBlock = this->superBlock();
  114. if (inode != EXT2_ROOT_INO && inode < EXT2_FIRST_INO(&superBlock))
  115. return { };
  116. if (inode > superBlock.s_inodes_count)
  117. return { };
  118. auto& bgd = blockGroupDescriptor(groupIndexFromInode(inode));
  119. offset = ((inode - 1) % inodesPerGroup()) * inodeSize();
  120. blockIndex = bgd.bg_inode_table + (offset >> EXT2_BLOCK_SIZE_BITS(&superBlock));
  121. offset &= blockSize() - 1;
  122. return readBlock(blockIndex);
  123. }
  124. OwnPtr<ext2_inode> Ext2FileSystem::lookupExt2Inode(unsigned inode) const
  125. {
  126. unsigned blockIndex;
  127. unsigned offset;
  128. auto block = readBlockContainingInode(inode, blockIndex, offset);
  129. if (!block)
  130. return nullptr;
  131. auto* e2inode = reinterpret_cast<ext2_inode*>(kmalloc(inodeSize()));
  132. memcpy(e2inode, reinterpret_cast<ext2_inode*>(block.offsetPointer(offset)), inodeSize());
  133. #ifdef EXT2_DEBUG
  134. dumpExt2Inode(*e2inode);
  135. #endif
  136. return OwnPtr<ext2_inode>(e2inode);
  137. }
  138. InodeMetadata Ext2FileSystem::inodeMetadata(InodeIdentifier inode) const
  139. {
  140. ASSERT(inode.fileSystemID() == id());
  141. auto e2inode = lookupExt2Inode(inode.index());
  142. if (!e2inode)
  143. return InodeMetadata();
  144. InodeMetadata metadata;
  145. metadata.inode = inode;
  146. metadata.size = e2inode->i_size;
  147. metadata.mode = e2inode->i_mode;
  148. metadata.uid = e2inode->i_uid;
  149. metadata.gid = e2inode->i_gid;
  150. metadata.linkCount = e2inode->i_links_count;
  151. metadata.atime = e2inode->i_atime;
  152. metadata.ctime = e2inode->i_ctime;
  153. metadata.mtime = e2inode->i_mtime;
  154. metadata.dtime = e2inode->i_dtime;
  155. return metadata;
  156. }
  157. Vector<unsigned> Ext2FileSystem::blockListForInode(const ext2_inode& e2inode) const
  158. {
  159. unsigned entriesPerBlock = EXT2_ADDR_PER_BLOCK(&superBlock());
  160. // NOTE: i_blocks is number of 512-byte blocks, not number of fs-blocks.
  161. unsigned blockCount = e2inode.i_blocks / (blockSize() / 512);
  162. unsigned blocksRemaining = blockCount;
  163. Vector<unsigned> list;
  164. list.ensureCapacity(blocksRemaining);
  165. unsigned directCount = min(blockCount, (unsigned)EXT2_NDIR_BLOCKS);
  166. for (unsigned i = 0; i < directCount; ++i) {
  167. list.append(e2inode.i_block[i]);
  168. --blocksRemaining;
  169. }
  170. if (!blocksRemaining)
  171. return list;
  172. auto processBlockArray = [&] (unsigned arrayBlockIndex, std::function<void(unsigned)> callback) {
  173. auto arrayBlock = readBlock(arrayBlockIndex);
  174. ASSERT(arrayBlock);
  175. auto* array = reinterpret_cast<const __u32*>(arrayBlock.pointer());
  176. unsigned count = min(blocksRemaining, entriesPerBlock);
  177. for (unsigned i = 0; i < count; ++i) {
  178. if (!array[i]) {
  179. blocksRemaining = 0;
  180. return;
  181. }
  182. callback(array[i]);
  183. --blocksRemaining;
  184. }
  185. };
  186. processBlockArray(e2inode.i_block[EXT2_IND_BLOCK], [&] (unsigned entry) {
  187. list.append(entry);
  188. });
  189. if (!blocksRemaining)
  190. return list;
  191. processBlockArray(e2inode.i_block[EXT2_DIND_BLOCK], [&] (unsigned entry) {
  192. processBlockArray(entry, [&] (unsigned entry) {
  193. list.append(entry);
  194. });
  195. });
  196. if (!blocksRemaining)
  197. return list;
  198. processBlockArray(e2inode.i_block[EXT2_TIND_BLOCK], [&] (unsigned entry) {
  199. processBlockArray(entry, [&] (unsigned entry) {
  200. processBlockArray(entry, [&] (unsigned entry) {
  201. list.append(entry);
  202. });
  203. });
  204. });
  205. return list;
  206. }
  207. ByteBuffer Ext2FileSystem::readInode(InodeIdentifier inode) const
  208. {
  209. ASSERT(inode.fileSystemID() == id());
  210. auto e2inode = lookupExt2Inode(inode.index());
  211. if (!e2inode) {
  212. printf("[ext2fs] readInode: metadata lookup for inode %u failed\n", inode.index());
  213. return nullptr;
  214. }
  215. if (e2inode->i_size == 0)
  216. return ByteBuffer::createEmpty();
  217. // Symbolic links shorter than 60 characters are store inline inside the i_block array.
  218. // This avoids wasting an entire block on short links. (Most links are short.)
  219. static const unsigned maxInlineSymlinkLength = 60;
  220. if (isSymbolicLink(e2inode->i_mode) && e2inode->i_size < maxInlineSymlinkLength) {
  221. auto inlineSymlink = ByteBuffer::createUninitialized(e2inode->i_size);
  222. memcpy(inlineSymlink.pointer(), e2inode->i_block, e2inode->i_size);
  223. return inlineSymlink;
  224. }
  225. auto list = blockListForInode(*e2inode);
  226. if (list.isEmpty()) {
  227. printf("[ext2fs] readInode: empty block list for inode %u\n", inode.index());
  228. return nullptr;
  229. }
  230. auto contents = ByteBuffer::createUninitialized(list.size() * blockSize());
  231. auto* out = contents.pointer();
  232. for (unsigned i = 0; i < list.size(); ++i) {
  233. auto block = readBlock(list[i]);
  234. if (!block) {
  235. printf("[ext2fs] readInode: readBlock(%u) failed\n", list[i]);
  236. return nullptr;
  237. }
  238. memcpy(out, block.pointer(), block.size());
  239. out += blockSize();
  240. }
  241. #ifdef EXT2_DEBUG
  242. printf("trim from %u to %u\n", contents.size(), e2inode->i_size);
  243. #endif
  244. contents.trim(e2inode->i_size);
  245. return contents;
  246. }
  247. bool Ext2FileSystem::writeInode(InodeIdentifier inode, const ByteBuffer& data)
  248. {
  249. ASSERT(inode.fileSystemID() == id());
  250. auto e2inode = lookupExt2Inode(inode.index());
  251. if (!e2inode) {
  252. printf("[ext2fs] writeInode: metadata lookup for inode %u failed\n", inode.index());
  253. return false;
  254. }
  255. // FIXME: Support writing to symlink inodes.
  256. ASSERT(!isSymbolicLink(e2inode->i_mode));
  257. unsigned blocksNeededBefore = ceilDiv(e2inode->i_size, blockSize());
  258. unsigned blocksNeededAfter = ceilDiv(data.size(), blockSize());
  259. // FIXME: Support growing or shrinking the block list.
  260. ASSERT(blocksNeededBefore == blocksNeededAfter);
  261. auto list = blockListForInode(*e2inode);
  262. if (list.isEmpty()) {
  263. printf("[ext2fs] writeInode: empty block list for inode %u\n", inode.index());
  264. return false;
  265. }
  266. for (unsigned i = 0; i < list.size(); ++i) {
  267. auto section = data.slice(i * blockSize(), blockSize());
  268. printf("section = %p (%u)\n", section.pointer(), section.size());
  269. bool success = writeBlock(list[i], section);
  270. ASSERT(success);
  271. }
  272. return true;
  273. }
  274. bool Ext2FileSystem::enumerateDirectoryInode(InodeIdentifier inode, std::function<bool(const DirectoryEntry&)> callback) const
  275. {
  276. ASSERT(inode.fileSystemID() == id());
  277. ASSERT(isDirectoryInode(inode.index()));
  278. #ifdef EXT2_DEBUG
  279. printf("[ext2fs] Enumerating directory contents of inode %u:\n", inode.index());
  280. #endif
  281. auto buffer = readInode(inode);
  282. ASSERT(buffer);
  283. auto* entry = reinterpret_cast<ext2_dir_entry_2*>(buffer.pointer());
  284. char namebuf[EXT2_NAME_LEN + 1];
  285. while (entry < buffer.endPointer()) {
  286. if (entry->inode != 0) {
  287. memcpy(namebuf, entry->name, entry->name_len);
  288. namebuf[entry->name_len] = 0;
  289. #ifdef EXT2_DEBUG
  290. printf("inode: %u, name_len: %u, rec_len: %u, name: %s\n", entry->inode, entry->name_len, entry->rec_len, namebuf);
  291. #endif
  292. if (!callback({ namebuf, { id(), entry->inode }, entry->file_type }))
  293. break;
  294. }
  295. entry = (ext2_dir_entry_2*)((char*)entry + entry->rec_len);
  296. }
  297. return true;
  298. }
  299. bool Ext2FileSystem::addInodeToDirectory(unsigned directoryInode, unsigned inode, const String& name)
  300. {
  301. auto e2inodeForDirectory = lookupExt2Inode(directoryInode);
  302. ASSERT(e2inodeForDirectory);
  303. ASSERT(isDirectory(e2inodeForDirectory->i_mode));
  304. //#ifdef EXT2_DEBUG
  305. printf("[ext2fs] Adding inode %u with name '%s' to directory %u\n", inode, name.characters(), directoryInode);
  306. //#endif
  307. Vector<DirectoryEntry> entries;
  308. bool nameAlreadyExists = false;
  309. enumerateDirectoryInode({ id(), directoryInode }, [&] (const DirectoryEntry& entry) {
  310. if (entry.name == name) {
  311. nameAlreadyExists = true;
  312. return false;
  313. }
  314. entries.append(entry);
  315. return true;
  316. });
  317. if (nameAlreadyExists) {
  318. printf("[ext2fs] Name '%s' already exists in directory inode %u\n", name.characters(), directoryInode);
  319. return false;
  320. }
  321. entries.append({ name, { id(), inode } });
  322. return writeDirectoryInode(directoryInode, std::move(entries));
  323. }
  324. class BufferStream {
  325. public:
  326. explicit BufferStream(ByteBuffer& buffer)
  327. : m_buffer(buffer)
  328. {
  329. }
  330. void operator<<(byte value)
  331. {
  332. m_buffer[m_offset++] = value & 0xffu;
  333. }
  334. void operator<<(word value)
  335. {
  336. m_buffer[m_offset++] = value & 0xffu;
  337. m_buffer[m_offset++] = (byte)(value >> 8) & 0xffu;
  338. }
  339. void operator<<(dword value)
  340. {
  341. m_buffer[m_offset++] = value & 0xffu;
  342. m_buffer[m_offset++] = (byte)(value >> 8) & 0xffu;
  343. m_buffer[m_offset++] = (byte)(value >> 16) & 0xffu;
  344. m_buffer[m_offset++] = (byte)(value >> 24) & 0xffu;
  345. }
  346. void operator<<(const String& value)
  347. {
  348. for (unsigned i = 0; i < value.length(); ++i)
  349. m_buffer[m_offset++] = value[i];
  350. }
  351. void fillToEnd(byte ch)
  352. {
  353. while (m_offset < m_buffer.size())
  354. m_buffer[m_offset++] = ch;
  355. }
  356. private:
  357. ByteBuffer& m_buffer;
  358. size_t m_offset { 0 };
  359. };
  360. bool Ext2FileSystem::writeDirectoryInode(unsigned directoryInode, Vector<DirectoryEntry>&& entries)
  361. {
  362. printf("[ext2fs] New directory inode %u contents to write:\n", directoryInode);
  363. unsigned directorySize = 0;
  364. for (auto& entry : entries) {
  365. printf(" - %08u %s\n", entry.inode.index(), entry.name.characters());
  366. directorySize += EXT2_DIR_REC_LEN(entry.name.length());
  367. }
  368. unsigned blocksNeeded = ceilDiv(directorySize, blockSize());
  369. unsigned occupiedSize = blocksNeeded * blockSize();
  370. printf("[ext2fs] directory size: %u (occupied: %u)\n", directorySize, occupiedSize);
  371. auto directoryData = ByteBuffer::createUninitialized(occupiedSize);
  372. BufferStream stream(directoryData);
  373. for (unsigned i = 0; i < entries.size(); ++i) {
  374. auto& entry = entries[i];
  375. unsigned recordLength = EXT2_DIR_REC_LEN(entry.name.length());
  376. if (i == entries.size() - 1)
  377. recordLength += occupiedSize - directorySize;
  378. printf("* inode: %u", entry.inode.index());
  379. printf(", name_len: %u", word(entry.name.length()));
  380. printf(", rec_len: %u", word(recordLength));
  381. printf(", name: %s\n", entry.name.characters());
  382. stream << dword(entry.inode.index());
  383. stream << word(recordLength);
  384. stream << byte(entry.name.length());
  385. stream << byte(entry.fileType);
  386. stream << entry.name;
  387. unsigned padding = recordLength - entry.name.length() - 8;
  388. printf(" *** pad %u bytes\n", padding);
  389. for (unsigned j = 0; j < padding; ++j) {
  390. stream << byte(0);
  391. }
  392. }
  393. stream.fillToEnd(0);
  394. #if 0
  395. printf("data to write (%u):\n", directoryData.size());
  396. for (unsigned i = 0; i < directoryData.size(); ++i) {
  397. printf("%02x ", directoryData[i]);
  398. if ((i + 1) % 8 == 0)
  399. printf(" ");
  400. if ((i + 1) % 16 == 0)
  401. printf("\n");
  402. }
  403. printf("\n");
  404. #endif
  405. writeInode({ id(), directoryInode }, directoryData);
  406. return true;
  407. }
  408. unsigned Ext2FileSystem::inodesPerBlock() const
  409. {
  410. return EXT2_INODES_PER_BLOCK(&superBlock());
  411. }
  412. unsigned Ext2FileSystem::inodesPerGroup() const
  413. {
  414. return EXT2_INODES_PER_GROUP(&superBlock());
  415. }
  416. unsigned Ext2FileSystem::inodeSize() const
  417. {
  418. return EXT2_INODE_SIZE(&superBlock());
  419. }
  420. unsigned Ext2FileSystem::blocksPerGroup() const
  421. {
  422. return EXT2_BLOCKS_PER_GROUP(&superBlock());
  423. }
  424. void Ext2FileSystem::dumpBlockBitmap(unsigned groupIndex) const
  425. {
  426. ASSERT(groupIndex <= m_blockGroupCount);
  427. auto& bgd = blockGroupDescriptor(groupIndex);
  428. unsigned blocksInGroup = min(blocksPerGroup(), superBlock().s_blocks_count);
  429. unsigned blockCount = ceilDiv(blocksInGroup, 8u);
  430. auto bitmapBlocks = readBlocks(bgd.bg_block_bitmap, blockCount);
  431. ASSERT(bitmapBlocks);
  432. printf("[ext2fs] group[%u] block bitmap (bitmap occupies %u blocks):\n", groupIndex, blockCount);
  433. auto bitmap = Bitmap::wrap(bitmapBlocks.pointer(), blocksInGroup);
  434. for (unsigned i = 0; i < blocksInGroup; ++i) {
  435. printf("%c", bitmap.get(i) ? '1' : '0');
  436. }
  437. printf("\n");
  438. }
  439. void Ext2FileSystem::dumpInodeBitmap(unsigned groupIndex) const
  440. {
  441. traverseInodeBitmap(groupIndex, [] (unsigned, const Bitmap& bitmap) {
  442. for (unsigned i = 0; i < bitmap.size(); ++i)
  443. printf("%c", bitmap.get(i) ? '1' : '0');
  444. return true;
  445. });
  446. }
  447. template<typename F>
  448. void Ext2FileSystem::traverseInodeBitmap(unsigned groupIndex, F callback) const
  449. {
  450. ASSERT(groupIndex <= m_blockGroupCount);
  451. auto& bgd = blockGroupDescriptor(groupIndex);
  452. unsigned inodesInGroup = min(inodesPerGroup(), superBlock().s_inodes_count);
  453. unsigned blockCount = ceilDiv(inodesInGroup, 8u);
  454. for (unsigned i = 0; i < blockCount; ++i) {
  455. auto block = readBlock(bgd.bg_inode_bitmap + i);
  456. ASSERT(block);
  457. bool shouldContinue = callback(i * (blockSize() / 8), Bitmap::wrap(block.pointer(), inodesInGroup));
  458. if (!shouldContinue)
  459. break;
  460. }
  461. }
  462. bool Ext2FileSystem::setModificationTime(InodeIdentifier inode, dword timestamp)
  463. {
  464. ASSERT(inode.fileSystemID() == id());
  465. auto e2inode = lookupExt2Inode(inode.index());
  466. if (!e2inode)
  467. return false;
  468. printf("changing inode %u mtime from %u to %u\n", inode.index(), e2inode->i_mtime, timestamp);
  469. e2inode->i_mtime = timestamp;
  470. return writeExt2Inode(inode.index(), *e2inode);
  471. }
  472. bool Ext2FileSystem::writeExt2Inode(unsigned inode, const ext2_inode& e2inode)
  473. {
  474. unsigned blockIndex;
  475. unsigned offset;
  476. auto block = readBlockContainingInode(inode, blockIndex, offset);
  477. if (!block)
  478. return false;
  479. memcpy(reinterpret_cast<ext2_inode*>(block.offsetPointer(offset)), &e2inode, inodeSize());
  480. writeBlock(blockIndex, block);
  481. return true;
  482. }
  483. bool Ext2FileSystem::isDirectoryInode(unsigned inode) const
  484. {
  485. if (auto e2inode = lookupExt2Inode(inode))
  486. return isDirectory(e2inode->i_mode);
  487. return false;
  488. }
  489. unsigned Ext2FileSystem::allocateInode(unsigned preferredGroup, unsigned expectedSize)
  490. {
  491. printf("[ext2fs] allocateInode(preferredGroup: %u, expectedSize: %u)\n", preferredGroup, expectedSize);
  492. unsigned neededBlocks = ceilDiv(expectedSize, blockSize());
  493. printf("[ext2fs] minimum needed blocks: %u\n", neededBlocks);
  494. unsigned groupIndex = 0;
  495. auto isSuitableGroup = [this, neededBlocks] (unsigned groupIndex) {
  496. auto& bgd = blockGroupDescriptor(groupIndex);
  497. return bgd.bg_free_inodes_count && bgd.bg_free_blocks_count >= neededBlocks;
  498. };
  499. if (preferredGroup && isSuitableGroup(preferredGroup)) {
  500. groupIndex = preferredGroup;
  501. } else {
  502. for (unsigned i = 1; i <= m_blockGroupCount; ++i) {
  503. if (isSuitableGroup(i))
  504. groupIndex = i;
  505. }
  506. }
  507. if (!groupIndex) {
  508. printf("[ext2fs] allocateInode: no suitable group found for new inode with %u blocks needed :(\n", neededBlocks);
  509. return 0;
  510. }
  511. printf("[ext2fs] allocateInode: found suitable group [%u] for new inode with %u blocks needed :^)\n", groupIndex, neededBlocks);
  512. unsigned firstFreeInodeInGroup = 0;
  513. traverseInodeBitmap(groupIndex, [&firstFreeInodeInGroup] (unsigned firstInodeInBitmap, const Bitmap& bitmap) {
  514. for (unsigned i = 0; i < bitmap.size(); ++i) {
  515. if (!bitmap.get(i)) {
  516. firstFreeInodeInGroup = firstInodeInBitmap + i;
  517. return false;
  518. }
  519. }
  520. return true;
  521. });
  522. if (!firstFreeInodeInGroup) {
  523. printf("[ext2fs] firstFreeInodeInGroup returned no inode, despite bgd claiming there are inodes :(\n");
  524. return 0;
  525. }
  526. unsigned inode = firstFreeInodeInGroup;
  527. printf("[ext2fs] found suitable inode %u\n", inode);
  528. // FIXME: allocate blocks if needed!
  529. return inode;
  530. }
  531. unsigned Ext2FileSystem::groupIndexFromInode(unsigned inode) const
  532. {
  533. if (!inode)
  534. return 0;
  535. return (inode - 1) / inodesPerGroup() + 1;
  536. }
  537. bool Ext2FileSystem::setInodeAllocationState(unsigned inode, bool newState)
  538. {
  539. auto& bgd = blockGroupDescriptor(groupIndexFromInode(inode));
  540. // Update inode bitmap
  541. unsigned inodesPerBitmapBlock = blockSize() * 8;
  542. unsigned bitmapBlockIndex = (inode - 1) / inodesPerBitmapBlock;
  543. unsigned bitIndex = (inode - 1) % inodesPerBitmapBlock;
  544. auto block = readBlock(bgd.bg_inode_bitmap + bitmapBlockIndex);
  545. ASSERT(block);
  546. auto bitmap = Bitmap::wrap(block.pointer(), block.size());
  547. bool currentState = bitmap.get(bitIndex);
  548. printf("[ext2fs] setInodeAllocationState(%u) %u -> %u\n", inode, currentState, newState);
  549. if (currentState == newState)
  550. return true;
  551. bitmap.set(bitIndex, newState);
  552. writeBlock(bgd.bg_inode_bitmap + bitmapBlockIndex, block);
  553. // Update superblock
  554. auto& sb = *reinterpret_cast<ext2_super_block*>(m_cachedSuperBlock.pointer());
  555. printf("[ext2fs] superblock free inode count %u -> %u\n", sb.s_free_inodes_count, sb.s_free_inodes_count - 1);
  556. if (newState)
  557. --sb.s_free_inodes_count;
  558. else
  559. ++sb.s_free_inodes_count;
  560. writeSuperBlock(sb);
  561. // Update BGD
  562. auto& mutableBGD = const_cast<ext2_group_desc&>(bgd);
  563. if (newState)
  564. --mutableBGD.bg_free_inodes_count;
  565. else
  566. ++mutableBGD.bg_free_inodes_count;
  567. printf("[ext2fs] group free inode count %u -> %u\n", bgd.bg_free_inodes_count, bgd.bg_free_inodes_count - 1);
  568. unsigned blocksToWrite = ceilDiv(m_blockGroupCount * sizeof(ext2_group_desc), blockSize());
  569. unsigned firstBlockOfBGDT = blockSize() == 1024 ? 2 : 1;
  570. writeBlocks(firstBlockOfBGDT, blocksToWrite, m_cachedBlockGroupDescriptorTable);
  571. return true;
  572. }
  573. InodeIdentifier Ext2FileSystem::createInode(InodeIdentifier parentInode, const String& name, word mode)
  574. {
  575. ASSERT(parentInode.fileSystemID() == id());
  576. ASSERT(isDirectoryInode(parentInode.index()));
  577. //#ifdef EXT2_DEBUG
  578. printf("[ext2fs] Adding inode '%s' (mode %o) to parent directory %u:\n", name.characters(), mode, parentInode.index());
  579. //#endif
  580. // NOTE: This doesn't commit the inode allocation just yet!
  581. auto inode = allocateInode(0, 0);
  582. // Try adding it to the directory first, in case the name is already in use.
  583. bool success = addInodeToDirectory(parentInode.index(), inode, name);
  584. if (!success) {
  585. printf("[ext2fs] failed to add inode to directory :(\n");
  586. return { };
  587. }
  588. // Looks like we're good, time to update the inode bitmap and group+global inode counters.
  589. success = setInodeAllocationState(inode, true);
  590. ASSERT(success);
  591. auto timestamp = time(nullptr);
  592. auto e2inode = make<ext2_inode>();
  593. memset(e2inode.ptr(), 0, sizeof(ext2_inode));
  594. e2inode->i_mode = mode;
  595. e2inode->i_uid = 0;
  596. e2inode->i_size = 0;
  597. e2inode->i_atime = timestamp;
  598. e2inode->i_ctime = timestamp;
  599. e2inode->i_mtime = timestamp;
  600. e2inode->i_dtime = 0;
  601. e2inode->i_gid = 0;
  602. e2inode->i_links_count = 2;
  603. e2inode->i_blocks = 0;
  604. e2inode->i_flags = 0;
  605. success = writeExt2Inode(inode, *e2inode);
  606. ASSERT(success);
  607. return { id(), inode };
  608. }