Ext2FileSystem.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815
  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. if (isBlockDevice(e2inode->i_mode) || isCharacterDevice(e2inode->i_mode)) {
  156. unsigned dev = e2inode->i_block[0];
  157. metadata.majorDevice = (dev & 0xfff00) >> 8;
  158. metadata.minorDevice= (dev & 0xff) | ((dev >> 12) & 0xfff00);
  159. }
  160. return metadata;
  161. }
  162. Vector<unsigned> Ext2FileSystem::blockListForInode(const ext2_inode& e2inode) const
  163. {
  164. unsigned entriesPerBlock = EXT2_ADDR_PER_BLOCK(&superBlock());
  165. // NOTE: i_blocks is number of 512-byte blocks, not number of fs-blocks.
  166. unsigned blockCount = e2inode.i_blocks / (blockSize() / 512);
  167. unsigned blocksRemaining = blockCount;
  168. Vector<unsigned> list;
  169. list.ensureCapacity(blocksRemaining);
  170. unsigned directCount = min(blockCount, (unsigned)EXT2_NDIR_BLOCKS);
  171. for (unsigned i = 0; i < directCount; ++i) {
  172. list.append(e2inode.i_block[i]);
  173. --blocksRemaining;
  174. }
  175. if (!blocksRemaining)
  176. return list;
  177. auto processBlockArray = [&] (unsigned arrayBlockIndex, std::function<void(unsigned)> callback) {
  178. auto arrayBlock = readBlock(arrayBlockIndex);
  179. ASSERT(arrayBlock);
  180. auto* array = reinterpret_cast<const __u32*>(arrayBlock.pointer());
  181. unsigned count = min(blocksRemaining, entriesPerBlock);
  182. for (unsigned i = 0; i < count; ++i) {
  183. if (!array[i]) {
  184. blocksRemaining = 0;
  185. return;
  186. }
  187. callback(array[i]);
  188. --blocksRemaining;
  189. }
  190. };
  191. processBlockArray(e2inode.i_block[EXT2_IND_BLOCK], [&] (unsigned entry) {
  192. list.append(entry);
  193. });
  194. if (!blocksRemaining)
  195. return list;
  196. processBlockArray(e2inode.i_block[EXT2_DIND_BLOCK], [&] (unsigned entry) {
  197. processBlockArray(entry, [&] (unsigned entry) {
  198. list.append(entry);
  199. });
  200. });
  201. if (!blocksRemaining)
  202. return list;
  203. processBlockArray(e2inode.i_block[EXT2_TIND_BLOCK], [&] (unsigned entry) {
  204. processBlockArray(entry, [&] (unsigned entry) {
  205. processBlockArray(entry, [&] (unsigned entry) {
  206. list.append(entry);
  207. });
  208. });
  209. });
  210. return list;
  211. }
  212. ssize_t Ext2FileSystem::readInodeBytes(InodeIdentifier inode, FileOffset offset, size_t count, byte* buffer) const
  213. {
  214. ASSERT(offset >= 0);
  215. ASSERT(inode.fileSystemID() == id());
  216. auto e2inode = lookupExt2Inode(inode.index());
  217. if (!e2inode) {
  218. printf("[ext2fs] readInodeBytes: metadata lookup for inode %u failed\n", inode.index());
  219. return -EIO;
  220. }
  221. #if 0
  222. // FIXME: We can't fail here while the directory traversal depends on this function. :]
  223. if (isDirectory(e2inode->i_mode))
  224. return -EISDIR;
  225. #endif
  226. if (e2inode->i_size == 0)
  227. return 0;
  228. // Symbolic links shorter than 60 characters are store inline inside the i_block array.
  229. // This avoids wasting an entire block on short links. (Most links are short.)
  230. static const unsigned maxInlineSymlinkLength = 60;
  231. if (isSymbolicLink(e2inode->i_mode) && e2inode->i_size < maxInlineSymlinkLength) {
  232. ssize_t nread = min(e2inode->i_size - offset, static_cast<FileOffset>(count));
  233. memcpy(buffer, e2inode->i_block + offset, nread);
  234. return nread;
  235. }
  236. // FIXME: It's grossly inefficient to fetch the blocklist on every call to readInodeBytes().
  237. // It needs to be cached!
  238. auto list = blockListForInode(*e2inode);
  239. if (list.isEmpty()) {
  240. printf("[ext2fs] readInodeBytes: empty block list for inode %u\n", inode.index());
  241. return -EIO;
  242. }
  243. dword firstBlockLogicalIndex = offset / blockSize();
  244. dword lastBlockLogicalIndex = (offset + count) / blockSize();
  245. if (lastBlockLogicalIndex >= list.size())
  246. lastBlockLogicalIndex = list.size() - 1;
  247. dword offsetIntoFirstBlock = offset % blockSize();
  248. ssize_t nread = 0;
  249. size_t remainingCount = min((FileOffset)count, e2inode->i_size - offset);
  250. byte* out = buffer;
  251. #ifdef EXT2_DEBUG
  252. printf("ok let's do it, read(%llu, %u) -> blocks %u thru %u, oifb: %u\n", offset, count, firstBlockLogicalIndex, lastBlockLogicalIndex, offsetIntoFirstBlock);
  253. #endif
  254. for (dword bi = firstBlockLogicalIndex; bi <= lastBlockLogicalIndex; ++bi) {
  255. auto block = readBlock(list[bi]);
  256. if (!block) {
  257. printf("[ext2fs] readInodeBytes: readBlock(%u) failed (lbi: %u)\n", list[bi], bi);
  258. return -EIO;
  259. }
  260. dword offsetIntoBlock;
  261. if (bi == firstBlockLogicalIndex)
  262. offsetIntoBlock = offsetIntoFirstBlock;
  263. else
  264. offsetIntoBlock = 0;
  265. dword numBytesToCopy = min(blockSize() - offsetIntoBlock, remainingCount);
  266. memcpy(out, block.pointer() + offsetIntoBlock, numBytesToCopy);
  267. remainingCount -= numBytesToCopy;
  268. nread += numBytesToCopy;
  269. out += numBytesToCopy;
  270. }
  271. return nread;
  272. }
  273. ByteBuffer Ext2FileSystem::readInode(InodeIdentifier inode) const
  274. {
  275. ASSERT(inode.fileSystemID() == id());
  276. auto e2inode = lookupExt2Inode(inode.index());
  277. if (!e2inode) {
  278. printf("[ext2fs] readInode: metadata lookup for inode %u failed\n", inode.index());
  279. return nullptr;
  280. }
  281. auto contents = ByteBuffer::createUninitialized(e2inode->i_size);
  282. ssize_t nread;
  283. byte buffer[512];
  284. byte* out = contents.pointer();
  285. FileOffset offset = 0;
  286. for (;;) {
  287. nread = readInodeBytes(inode, offset, sizeof(buffer), buffer);
  288. if (nread <= 0)
  289. break;
  290. memcpy(out, buffer, nread);
  291. out += nread;
  292. offset += nread;
  293. }
  294. if (nread < 0) {
  295. printf("[ext2fs] readInode: ERROR: %d\n", nread);
  296. return nullptr;
  297. }
  298. return contents;
  299. }
  300. bool Ext2FileSystem::writeInode(InodeIdentifier inode, const ByteBuffer& data)
  301. {
  302. ASSERT(inode.fileSystemID() == id());
  303. auto e2inode = lookupExt2Inode(inode.index());
  304. if (!e2inode) {
  305. printf("[ext2fs] writeInode: metadata lookup for inode %u failed\n", inode.index());
  306. return false;
  307. }
  308. // FIXME: Support writing to symlink inodes.
  309. ASSERT(!isSymbolicLink(e2inode->i_mode));
  310. unsigned blocksNeededBefore = ceilDiv(e2inode->i_size, blockSize());
  311. unsigned blocksNeededAfter = ceilDiv(data.size(), blockSize());
  312. // FIXME: Support growing or shrinking the block list.
  313. ASSERT(blocksNeededBefore == blocksNeededAfter);
  314. auto list = blockListForInode(*e2inode);
  315. if (list.isEmpty()) {
  316. printf("[ext2fs] writeInode: empty block list for inode %u\n", inode.index());
  317. return false;
  318. }
  319. for (unsigned i = 0; i < list.size(); ++i) {
  320. auto section = data.slice(i * blockSize(), blockSize());
  321. printf("section = %p (%u)\n", section.pointer(), section.size());
  322. bool success = writeBlock(list[i], section);
  323. ASSERT(success);
  324. }
  325. return true;
  326. }
  327. bool Ext2FileSystem::enumerateDirectoryInode(InodeIdentifier inode, std::function<bool(const DirectoryEntry&)> callback) const
  328. {
  329. ASSERT(inode.fileSystemID() == id());
  330. ASSERT(isDirectoryInode(inode.index()));
  331. #ifdef EXT2_DEBUG
  332. printf("[ext2fs] Enumerating directory contents of inode %u:\n", inode.index());
  333. #endif
  334. auto buffer = readInode(inode);
  335. ASSERT(buffer);
  336. auto* entry = reinterpret_cast<ext2_dir_entry_2*>(buffer.pointer());
  337. char namebuf[EXT2_NAME_LEN + 1];
  338. while (entry < buffer.endPointer()) {
  339. if (entry->inode != 0) {
  340. memcpy(namebuf, entry->name, entry->name_len);
  341. namebuf[entry->name_len] = 0;
  342. #ifdef EXT2_DEBUG
  343. printf("inode: %u, name_len: %u, rec_len: %u, name: %s\n", entry->inode, entry->name_len, entry->rec_len, namebuf);
  344. #endif
  345. if (!callback({ namebuf, { id(), entry->inode }, entry->file_type }))
  346. break;
  347. }
  348. entry = (ext2_dir_entry_2*)((char*)entry + entry->rec_len);
  349. }
  350. return true;
  351. }
  352. bool Ext2FileSystem::addInodeToDirectory(unsigned directoryInode, unsigned inode, const String& name)
  353. {
  354. auto e2inodeForDirectory = lookupExt2Inode(directoryInode);
  355. ASSERT(e2inodeForDirectory);
  356. ASSERT(isDirectory(e2inodeForDirectory->i_mode));
  357. //#ifdef EXT2_DEBUG
  358. printf("[ext2fs] Adding inode %u with name '%s' to directory %u\n", inode, name.characters(), directoryInode);
  359. //#endif
  360. Vector<DirectoryEntry> entries;
  361. bool nameAlreadyExists = false;
  362. enumerateDirectoryInode({ id(), directoryInode }, [&] (const DirectoryEntry& entry) {
  363. if (entry.name == name) {
  364. nameAlreadyExists = true;
  365. return false;
  366. }
  367. entries.append(entry);
  368. return true;
  369. });
  370. if (nameAlreadyExists) {
  371. printf("[ext2fs] Name '%s' already exists in directory inode %u\n", name.characters(), directoryInode);
  372. return false;
  373. }
  374. entries.append({ name, { id(), inode } });
  375. return writeDirectoryInode(directoryInode, std::move(entries));
  376. }
  377. class BufferStream {
  378. public:
  379. explicit BufferStream(ByteBuffer& buffer)
  380. : m_buffer(buffer)
  381. {
  382. }
  383. void operator<<(byte value)
  384. {
  385. m_buffer[m_offset++] = value & 0xffu;
  386. }
  387. void operator<<(word value)
  388. {
  389. m_buffer[m_offset++] = value & 0xffu;
  390. m_buffer[m_offset++] = (byte)(value >> 8) & 0xffu;
  391. }
  392. void operator<<(dword value)
  393. {
  394. m_buffer[m_offset++] = value & 0xffu;
  395. m_buffer[m_offset++] = (byte)(value >> 8) & 0xffu;
  396. m_buffer[m_offset++] = (byte)(value >> 16) & 0xffu;
  397. m_buffer[m_offset++] = (byte)(value >> 24) & 0xffu;
  398. }
  399. void operator<<(const String& value)
  400. {
  401. for (unsigned i = 0; i < value.length(); ++i)
  402. m_buffer[m_offset++] = value[i];
  403. }
  404. void fillToEnd(byte ch)
  405. {
  406. while (m_offset < m_buffer.size())
  407. m_buffer[m_offset++] = ch;
  408. }
  409. private:
  410. ByteBuffer& m_buffer;
  411. size_t m_offset { 0 };
  412. };
  413. bool Ext2FileSystem::writeDirectoryInode(unsigned directoryInode, Vector<DirectoryEntry>&& entries)
  414. {
  415. printf("[ext2fs] New directory inode %u contents to write:\n", directoryInode);
  416. unsigned directorySize = 0;
  417. for (auto& entry : entries) {
  418. printf(" - %08u %s\n", entry.inode.index(), entry.name.characters());
  419. directorySize += EXT2_DIR_REC_LEN(entry.name.length());
  420. }
  421. unsigned blocksNeeded = ceilDiv(directorySize, blockSize());
  422. unsigned occupiedSize = blocksNeeded * blockSize();
  423. printf("[ext2fs] directory size: %u (occupied: %u)\n", directorySize, occupiedSize);
  424. auto directoryData = ByteBuffer::createUninitialized(occupiedSize);
  425. BufferStream stream(directoryData);
  426. for (unsigned i = 0; i < entries.size(); ++i) {
  427. auto& entry = entries[i];
  428. unsigned recordLength = EXT2_DIR_REC_LEN(entry.name.length());
  429. if (i == entries.size() - 1)
  430. recordLength += occupiedSize - directorySize;
  431. printf("* inode: %u", entry.inode.index());
  432. printf(", name_len: %u", word(entry.name.length()));
  433. printf(", rec_len: %u", word(recordLength));
  434. printf(", name: %s\n", entry.name.characters());
  435. stream << dword(entry.inode.index());
  436. stream << word(recordLength);
  437. stream << byte(entry.name.length());
  438. stream << byte(entry.fileType);
  439. stream << entry.name;
  440. unsigned padding = recordLength - entry.name.length() - 8;
  441. printf(" *** pad %u bytes\n", padding);
  442. for (unsigned j = 0; j < padding; ++j) {
  443. stream << byte(0);
  444. }
  445. }
  446. stream.fillToEnd(0);
  447. #if 0
  448. printf("data to write (%u):\n", directoryData.size());
  449. for (unsigned i = 0; i < directoryData.size(); ++i) {
  450. printf("%02x ", directoryData[i]);
  451. if ((i + 1) % 8 == 0)
  452. printf(" ");
  453. if ((i + 1) % 16 == 0)
  454. printf("\n");
  455. }
  456. printf("\n");
  457. #endif
  458. writeInode({ id(), directoryInode }, directoryData);
  459. return true;
  460. }
  461. unsigned Ext2FileSystem::inodesPerBlock() const
  462. {
  463. return EXT2_INODES_PER_BLOCK(&superBlock());
  464. }
  465. unsigned Ext2FileSystem::inodesPerGroup() const
  466. {
  467. return EXT2_INODES_PER_GROUP(&superBlock());
  468. }
  469. unsigned Ext2FileSystem::inodeSize() const
  470. {
  471. return EXT2_INODE_SIZE(&superBlock());
  472. }
  473. unsigned Ext2FileSystem::blocksPerGroup() const
  474. {
  475. return EXT2_BLOCKS_PER_GROUP(&superBlock());
  476. }
  477. void Ext2FileSystem::dumpBlockBitmap(unsigned groupIndex) const
  478. {
  479. ASSERT(groupIndex <= m_blockGroupCount);
  480. auto& bgd = blockGroupDescriptor(groupIndex);
  481. unsigned blocksInGroup = min(blocksPerGroup(), superBlock().s_blocks_count);
  482. unsigned blockCount = ceilDiv(blocksInGroup, 8u);
  483. auto bitmapBlocks = readBlocks(bgd.bg_block_bitmap, blockCount);
  484. ASSERT(bitmapBlocks);
  485. printf("[ext2fs] group[%u] block bitmap (bitmap occupies %u blocks):\n", groupIndex, blockCount);
  486. auto bitmap = Bitmap::wrap(bitmapBlocks.pointer(), blocksInGroup);
  487. for (unsigned i = 0; i < blocksInGroup; ++i) {
  488. printf("%c", bitmap.get(i) ? '1' : '0');
  489. }
  490. printf("\n");
  491. }
  492. void Ext2FileSystem::dumpInodeBitmap(unsigned groupIndex) const
  493. {
  494. traverseInodeBitmap(groupIndex, [] (unsigned, const Bitmap& bitmap) {
  495. for (unsigned i = 0; i < bitmap.size(); ++i)
  496. printf("%c", bitmap.get(i) ? '1' : '0');
  497. return true;
  498. });
  499. }
  500. template<typename F>
  501. void Ext2FileSystem::traverseInodeBitmap(unsigned groupIndex, F callback) const
  502. {
  503. ASSERT(groupIndex <= m_blockGroupCount);
  504. auto& bgd = blockGroupDescriptor(groupIndex);
  505. unsigned inodesInGroup = min(inodesPerGroup(), superBlock().s_inodes_count);
  506. unsigned blockCount = ceilDiv(inodesInGroup, 8u);
  507. for (unsigned i = 0; i < blockCount; ++i) {
  508. auto block = readBlock(bgd.bg_inode_bitmap + i);
  509. ASSERT(block);
  510. bool shouldContinue = callback(i * (blockSize() / 8), Bitmap::wrap(block.pointer(), inodesInGroup));
  511. if (!shouldContinue)
  512. break;
  513. }
  514. }
  515. bool Ext2FileSystem::setModificationTime(InodeIdentifier inode, dword timestamp)
  516. {
  517. ASSERT(inode.fileSystemID() == id());
  518. auto e2inode = lookupExt2Inode(inode.index());
  519. if (!e2inode)
  520. return false;
  521. printf("changing inode %u mtime from %u to %u\n", inode.index(), e2inode->i_mtime, timestamp);
  522. e2inode->i_mtime = timestamp;
  523. return writeExt2Inode(inode.index(), *e2inode);
  524. }
  525. bool Ext2FileSystem::writeExt2Inode(unsigned inode, const ext2_inode& e2inode)
  526. {
  527. unsigned blockIndex;
  528. unsigned offset;
  529. auto block = readBlockContainingInode(inode, blockIndex, offset);
  530. if (!block)
  531. return false;
  532. memcpy(reinterpret_cast<ext2_inode*>(block.offsetPointer(offset)), &e2inode, inodeSize());
  533. writeBlock(blockIndex, block);
  534. return true;
  535. }
  536. bool Ext2FileSystem::isDirectoryInode(unsigned inode) const
  537. {
  538. if (auto e2inode = lookupExt2Inode(inode))
  539. return isDirectory(e2inode->i_mode);
  540. return false;
  541. }
  542. unsigned Ext2FileSystem::allocateInode(unsigned preferredGroup, unsigned expectedSize)
  543. {
  544. printf("[ext2fs] allocateInode(preferredGroup: %u, expectedSize: %u)\n", preferredGroup, expectedSize);
  545. unsigned neededBlocks = ceilDiv(expectedSize, blockSize());
  546. printf("[ext2fs] minimum needed blocks: %u\n", neededBlocks);
  547. unsigned groupIndex = 0;
  548. auto isSuitableGroup = [this, neededBlocks] (unsigned groupIndex) {
  549. auto& bgd = blockGroupDescriptor(groupIndex);
  550. return bgd.bg_free_inodes_count && bgd.bg_free_blocks_count >= neededBlocks;
  551. };
  552. if (preferredGroup && isSuitableGroup(preferredGroup)) {
  553. groupIndex = preferredGroup;
  554. } else {
  555. for (unsigned i = 1; i <= m_blockGroupCount; ++i) {
  556. if (isSuitableGroup(i))
  557. groupIndex = i;
  558. }
  559. }
  560. if (!groupIndex) {
  561. printf("[ext2fs] allocateInode: no suitable group found for new inode with %u blocks needed :(\n", neededBlocks);
  562. return 0;
  563. }
  564. printf("[ext2fs] allocateInode: found suitable group [%u] for new inode with %u blocks needed :^)\n", groupIndex, neededBlocks);
  565. unsigned firstFreeInodeInGroup = 0;
  566. traverseInodeBitmap(groupIndex, [&firstFreeInodeInGroup] (unsigned firstInodeInBitmap, const Bitmap& bitmap) {
  567. for (unsigned i = 0; i < bitmap.size(); ++i) {
  568. if (!bitmap.get(i)) {
  569. firstFreeInodeInGroup = firstInodeInBitmap + i;
  570. return false;
  571. }
  572. }
  573. return true;
  574. });
  575. if (!firstFreeInodeInGroup) {
  576. printf("[ext2fs] firstFreeInodeInGroup returned no inode, despite bgd claiming there are inodes :(\n");
  577. return 0;
  578. }
  579. unsigned inode = firstFreeInodeInGroup;
  580. printf("[ext2fs] found suitable inode %u\n", inode);
  581. // FIXME: allocate blocks if needed!
  582. return inode;
  583. }
  584. unsigned Ext2FileSystem::groupIndexFromInode(unsigned inode) const
  585. {
  586. if (!inode)
  587. return 0;
  588. return (inode - 1) / inodesPerGroup() + 1;
  589. }
  590. bool Ext2FileSystem::setInodeAllocationState(unsigned inode, bool newState)
  591. {
  592. auto& bgd = blockGroupDescriptor(groupIndexFromInode(inode));
  593. // Update inode bitmap
  594. unsigned inodesPerBitmapBlock = blockSize() * 8;
  595. unsigned bitmapBlockIndex = (inode - 1) / inodesPerBitmapBlock;
  596. unsigned bitIndex = (inode - 1) % inodesPerBitmapBlock;
  597. auto block = readBlock(bgd.bg_inode_bitmap + bitmapBlockIndex);
  598. ASSERT(block);
  599. auto bitmap = Bitmap::wrap(block.pointer(), block.size());
  600. bool currentState = bitmap.get(bitIndex);
  601. printf("[ext2fs] setInodeAllocationState(%u) %u -> %u\n", inode, currentState, newState);
  602. if (currentState == newState)
  603. return true;
  604. bitmap.set(bitIndex, newState);
  605. writeBlock(bgd.bg_inode_bitmap + bitmapBlockIndex, block);
  606. // Update superblock
  607. auto& sb = *reinterpret_cast<ext2_super_block*>(m_cachedSuperBlock.pointer());
  608. printf("[ext2fs] superblock free inode count %u -> %u\n", sb.s_free_inodes_count, sb.s_free_inodes_count - 1);
  609. if (newState)
  610. --sb.s_free_inodes_count;
  611. else
  612. ++sb.s_free_inodes_count;
  613. writeSuperBlock(sb);
  614. // Update BGD
  615. auto& mutableBGD = const_cast<ext2_group_desc&>(bgd);
  616. if (newState)
  617. --mutableBGD.bg_free_inodes_count;
  618. else
  619. ++mutableBGD.bg_free_inodes_count;
  620. printf("[ext2fs] group free inode count %u -> %u\n", bgd.bg_free_inodes_count, bgd.bg_free_inodes_count - 1);
  621. unsigned blocksToWrite = ceilDiv(m_blockGroupCount * sizeof(ext2_group_desc), blockSize());
  622. unsigned firstBlockOfBGDT = blockSize() == 1024 ? 2 : 1;
  623. writeBlocks(firstBlockOfBGDT, blocksToWrite, m_cachedBlockGroupDescriptorTable);
  624. return true;
  625. }
  626. InodeIdentifier Ext2FileSystem::createInode(InodeIdentifier parentInode, const String& name, word mode)
  627. {
  628. ASSERT(parentInode.fileSystemID() == id());
  629. ASSERT(isDirectoryInode(parentInode.index()));
  630. //#ifdef EXT2_DEBUG
  631. printf("[ext2fs] Adding inode '%s' (mode %o) to parent directory %u:\n", name.characters(), mode, parentInode.index());
  632. //#endif
  633. // NOTE: This doesn't commit the inode allocation just yet!
  634. auto inode = allocateInode(0, 0);
  635. // Try adding it to the directory first, in case the name is already in use.
  636. bool success = addInodeToDirectory(parentInode.index(), inode, name);
  637. if (!success) {
  638. printf("[ext2fs] failed to add inode to directory :(\n");
  639. return { };
  640. }
  641. // Looks like we're good, time to update the inode bitmap and group+global inode counters.
  642. success = setInodeAllocationState(inode, true);
  643. ASSERT(success);
  644. auto timestamp = time(nullptr);
  645. auto e2inode = make<ext2_inode>();
  646. memset(e2inode.ptr(), 0, sizeof(ext2_inode));
  647. e2inode->i_mode = mode;
  648. e2inode->i_uid = 0;
  649. e2inode->i_size = 0;
  650. e2inode->i_atime = timestamp;
  651. e2inode->i_ctime = timestamp;
  652. e2inode->i_mtime = timestamp;
  653. e2inode->i_dtime = 0;
  654. e2inode->i_gid = 0;
  655. e2inode->i_links_count = 2;
  656. e2inode->i_blocks = 0;
  657. e2inode->i_flags = 0;
  658. success = writeExt2Inode(inode, *e2inode);
  659. ASSERT(success);
  660. return { id(), inode };
  661. }