Ext2FileSystem.cpp 25 KB

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