Ext2FileSystem.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819
  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. ByteBuffer Ext2FileSystem::readInode(InodeIdentifier inode) const
  278. {
  279. ASSERT(inode.fileSystemID() == id());
  280. auto e2inode = lookupExt2Inode(inode.index());
  281. if (!e2inode) {
  282. printf("[ext2fs] readInode: metadata lookup for inode %u failed\n", inode.index());
  283. return nullptr;
  284. }
  285. auto contents = ByteBuffer::createUninitialized(e2inode->i_size);
  286. Unix::ssize_t nread;
  287. byte buffer[512];
  288. byte* out = contents.pointer();
  289. Unix::off_t offset = 0;
  290. for (;;) {
  291. nread = readInodeBytes(inode, offset, sizeof(buffer), buffer);
  292. if (nread <= 0)
  293. break;
  294. memcpy(out, buffer, nread);
  295. out += nread;
  296. offset += nread;
  297. }
  298. if (nread < 0) {
  299. printf("[ext2fs] readInode: ERROR: %d\n", nread);
  300. return nullptr;
  301. }
  302. return contents;
  303. }
  304. bool Ext2FileSystem::writeInode(InodeIdentifier inode, const ByteBuffer& data)
  305. {
  306. ASSERT(inode.fileSystemID() == id());
  307. auto e2inode = lookupExt2Inode(inode.index());
  308. if (!e2inode) {
  309. printf("[ext2fs] writeInode: metadata lookup for inode %u failed\n", inode.index());
  310. return false;
  311. }
  312. // FIXME: Support writing to symlink inodes.
  313. ASSERT(!isSymbolicLink(e2inode->i_mode));
  314. unsigned blocksNeededBefore = ceilDiv(e2inode->i_size, blockSize());
  315. unsigned blocksNeededAfter = ceilDiv(data.size(), blockSize());
  316. // FIXME: Support growing or shrinking the block list.
  317. ASSERT(blocksNeededBefore == blocksNeededAfter);
  318. auto list = blockListForInode(*e2inode);
  319. if (list.isEmpty()) {
  320. printf("[ext2fs] writeInode: empty block list for inode %u\n", inode.index());
  321. return false;
  322. }
  323. for (unsigned i = 0; i < list.size(); ++i) {
  324. auto section = data.slice(i * blockSize(), blockSize());
  325. printf("section = %p (%u)\n", section.pointer(), section.size());
  326. bool success = writeBlock(list[i], section);
  327. ASSERT(success);
  328. }
  329. return true;
  330. }
  331. bool Ext2FileSystem::enumerateDirectoryInode(InodeIdentifier inode, std::function<bool(const DirectoryEntry&)> callback) const
  332. {
  333. ASSERT(inode.fileSystemID() == id());
  334. ASSERT(isDirectoryInode(inode.index()));
  335. #ifdef EXT2_DEBUG
  336. printf("[ext2fs] Enumerating directory contents of inode %u:\n", inode.index());
  337. #endif
  338. auto buffer = readInode(inode);
  339. ASSERT(buffer);
  340. auto* entry = reinterpret_cast<ext2_dir_entry_2*>(buffer.pointer());
  341. char namebuf[EXT2_NAME_LEN + 1];
  342. while (entry < buffer.endPointer()) {
  343. if (entry->inode != 0) {
  344. memcpy(namebuf, entry->name, entry->name_len);
  345. namebuf[entry->name_len] = 0;
  346. #ifdef EXT2_DEBUG
  347. printf("inode: %u, name_len: %u, rec_len: %u, name: %s\n", entry->inode, entry->name_len, entry->rec_len, namebuf);
  348. #endif
  349. if (!callback({ namebuf, { id(), entry->inode }, entry->file_type }))
  350. break;
  351. }
  352. entry = (ext2_dir_entry_2*)((char*)entry + entry->rec_len);
  353. }
  354. return true;
  355. }
  356. bool Ext2FileSystem::addInodeToDirectory(unsigned directoryInode, unsigned inode, const String& name)
  357. {
  358. auto e2inodeForDirectory = lookupExt2Inode(directoryInode);
  359. ASSERT(e2inodeForDirectory);
  360. ASSERT(isDirectory(e2inodeForDirectory->i_mode));
  361. //#ifdef EXT2_DEBUG
  362. printf("[ext2fs] Adding inode %u with name '%s' to directory %u\n", inode, name.characters(), directoryInode);
  363. //#endif
  364. Vector<DirectoryEntry> entries;
  365. bool nameAlreadyExists = false;
  366. enumerateDirectoryInode({ id(), directoryInode }, [&] (const DirectoryEntry& entry) {
  367. if (entry.name == name) {
  368. nameAlreadyExists = true;
  369. return false;
  370. }
  371. entries.append(entry);
  372. return true;
  373. });
  374. if (nameAlreadyExists) {
  375. printf("[ext2fs] Name '%s' already exists in directory inode %u\n", name.characters(), directoryInode);
  376. return false;
  377. }
  378. entries.append({ name, { id(), inode } });
  379. return writeDirectoryInode(directoryInode, std::move(entries));
  380. }
  381. class BufferStream {
  382. public:
  383. explicit BufferStream(ByteBuffer& buffer)
  384. : m_buffer(buffer)
  385. {
  386. }
  387. void operator<<(byte value)
  388. {
  389. m_buffer[m_offset++] = value & 0xffu;
  390. }
  391. void operator<<(word value)
  392. {
  393. m_buffer[m_offset++] = value & 0xffu;
  394. m_buffer[m_offset++] = (byte)(value >> 8) & 0xffu;
  395. }
  396. void operator<<(dword value)
  397. {
  398. m_buffer[m_offset++] = value & 0xffu;
  399. m_buffer[m_offset++] = (byte)(value >> 8) & 0xffu;
  400. m_buffer[m_offset++] = (byte)(value >> 16) & 0xffu;
  401. m_buffer[m_offset++] = (byte)(value >> 24) & 0xffu;
  402. }
  403. void operator<<(const String& value)
  404. {
  405. for (unsigned i = 0; i < value.length(); ++i)
  406. m_buffer[m_offset++] = value[i];
  407. }
  408. void fillToEnd(byte ch)
  409. {
  410. while (m_offset < m_buffer.size())
  411. m_buffer[m_offset++] = ch;
  412. }
  413. private:
  414. ByteBuffer& m_buffer;
  415. Unix::size_t m_offset { 0 };
  416. };
  417. bool Ext2FileSystem::writeDirectoryInode(unsigned directoryInode, Vector<DirectoryEntry>&& entries)
  418. {
  419. printf("[ext2fs] New directory inode %u contents to write:\n", directoryInode);
  420. unsigned directorySize = 0;
  421. for (auto& entry : entries) {
  422. printf(" - %08u %s\n", entry.inode.index(), entry.name.characters());
  423. directorySize += EXT2_DIR_REC_LEN(entry.name.length());
  424. }
  425. unsigned blocksNeeded = ceilDiv(directorySize, blockSize());
  426. unsigned occupiedSize = blocksNeeded * blockSize();
  427. printf("[ext2fs] directory size: %u (occupied: %u)\n", directorySize, occupiedSize);
  428. auto directoryData = ByteBuffer::createUninitialized(occupiedSize);
  429. BufferStream stream(directoryData);
  430. for (unsigned i = 0; i < entries.size(); ++i) {
  431. auto& entry = entries[i];
  432. unsigned recordLength = EXT2_DIR_REC_LEN(entry.name.length());
  433. if (i == entries.size() - 1)
  434. recordLength += occupiedSize - directorySize;
  435. printf("* inode: %u", entry.inode.index());
  436. printf(", name_len: %u", word(entry.name.length()));
  437. printf(", rec_len: %u", word(recordLength));
  438. printf(", name: %s\n", entry.name.characters());
  439. stream << dword(entry.inode.index());
  440. stream << word(recordLength);
  441. stream << byte(entry.name.length());
  442. stream << byte(entry.fileType);
  443. stream << entry.name;
  444. unsigned padding = recordLength - entry.name.length() - 8;
  445. printf(" *** pad %u bytes\n", padding);
  446. for (unsigned j = 0; j < padding; ++j) {
  447. stream << byte(0);
  448. }
  449. }
  450. stream.fillToEnd(0);
  451. #if 0
  452. printf("data to write (%u):\n", directoryData.size());
  453. for (unsigned i = 0; i < directoryData.size(); ++i) {
  454. printf("%02x ", directoryData[i]);
  455. if ((i + 1) % 8 == 0)
  456. printf(" ");
  457. if ((i + 1) % 16 == 0)
  458. printf("\n");
  459. }
  460. printf("\n");
  461. #endif
  462. writeInode({ id(), directoryInode }, directoryData);
  463. return true;
  464. }
  465. unsigned Ext2FileSystem::inodesPerBlock() const
  466. {
  467. return EXT2_INODES_PER_BLOCK(&superBlock());
  468. }
  469. unsigned Ext2FileSystem::inodesPerGroup() const
  470. {
  471. return EXT2_INODES_PER_GROUP(&superBlock());
  472. }
  473. unsigned Ext2FileSystem::inodeSize() const
  474. {
  475. return EXT2_INODE_SIZE(&superBlock());
  476. }
  477. unsigned Ext2FileSystem::blocksPerGroup() const
  478. {
  479. return EXT2_BLOCKS_PER_GROUP(&superBlock());
  480. }
  481. void Ext2FileSystem::dumpBlockBitmap(unsigned groupIndex) const
  482. {
  483. ASSERT(groupIndex <= m_blockGroupCount);
  484. auto& bgd = blockGroupDescriptor(groupIndex);
  485. unsigned blocksInGroup = min(blocksPerGroup(), superBlock().s_blocks_count);
  486. unsigned blockCount = ceilDiv(blocksInGroup, 8u);
  487. auto bitmapBlocks = readBlocks(bgd.bg_block_bitmap, blockCount);
  488. ASSERT(bitmapBlocks);
  489. printf("[ext2fs] group[%u] block bitmap (bitmap occupies %u blocks):\n", groupIndex, blockCount);
  490. auto bitmap = Bitmap::wrap(bitmapBlocks.pointer(), blocksInGroup);
  491. for (unsigned i = 0; i < blocksInGroup; ++i) {
  492. printf("%c", bitmap.get(i) ? '1' : '0');
  493. }
  494. printf("\n");
  495. }
  496. void Ext2FileSystem::dumpInodeBitmap(unsigned groupIndex) const
  497. {
  498. traverseInodeBitmap(groupIndex, [] (unsigned, const Bitmap& bitmap) {
  499. for (unsigned i = 0; i < bitmap.size(); ++i)
  500. printf("%c", bitmap.get(i) ? '1' : '0');
  501. return true;
  502. });
  503. }
  504. template<typename F>
  505. void Ext2FileSystem::traverseInodeBitmap(unsigned groupIndex, F callback) const
  506. {
  507. ASSERT(groupIndex <= m_blockGroupCount);
  508. auto& bgd = blockGroupDescriptor(groupIndex);
  509. unsigned inodesInGroup = min(inodesPerGroup(), superBlock().s_inodes_count);
  510. unsigned blockCount = ceilDiv(inodesInGroup, 8u);
  511. for (unsigned i = 0; i < blockCount; ++i) {
  512. auto block = readBlock(bgd.bg_inode_bitmap + i);
  513. ASSERT(block);
  514. bool shouldContinue = callback(i * (blockSize() / 8), Bitmap::wrap(block.pointer(), inodesInGroup));
  515. if (!shouldContinue)
  516. break;
  517. }
  518. }
  519. bool Ext2FileSystem::setModificationTime(InodeIdentifier inode, dword timestamp)
  520. {
  521. ASSERT(inode.fileSystemID() == id());
  522. auto e2inode = lookupExt2Inode(inode.index());
  523. if (!e2inode)
  524. return false;
  525. printf("changing inode %u mtime from %u to %u\n", inode.index(), e2inode->i_mtime, timestamp);
  526. e2inode->i_mtime = timestamp;
  527. return writeExt2Inode(inode.index(), *e2inode);
  528. }
  529. bool Ext2FileSystem::writeExt2Inode(unsigned inode, const ext2_inode& e2inode)
  530. {
  531. unsigned blockIndex;
  532. unsigned offset;
  533. auto block = readBlockContainingInode(inode, blockIndex, offset);
  534. if (!block)
  535. return false;
  536. memcpy(reinterpret_cast<ext2_inode*>(block.offsetPointer(offset)), &e2inode, inodeSize());
  537. writeBlock(blockIndex, block);
  538. return true;
  539. }
  540. bool Ext2FileSystem::isDirectoryInode(unsigned inode) const
  541. {
  542. if (auto e2inode = lookupExt2Inode(inode))
  543. return isDirectory(e2inode->i_mode);
  544. return false;
  545. }
  546. unsigned Ext2FileSystem::allocateInode(unsigned preferredGroup, unsigned expectedSize)
  547. {
  548. printf("[ext2fs] allocateInode(preferredGroup: %u, expectedSize: %u)\n", preferredGroup, expectedSize);
  549. unsigned neededBlocks = ceilDiv(expectedSize, blockSize());
  550. printf("[ext2fs] minimum needed blocks: %u\n", neededBlocks);
  551. unsigned groupIndex = 0;
  552. auto isSuitableGroup = [this, neededBlocks] (unsigned groupIndex) {
  553. auto& bgd = blockGroupDescriptor(groupIndex);
  554. return bgd.bg_free_inodes_count && bgd.bg_free_blocks_count >= neededBlocks;
  555. };
  556. if (preferredGroup && isSuitableGroup(preferredGroup)) {
  557. groupIndex = preferredGroup;
  558. } else {
  559. for (unsigned i = 1; i <= m_blockGroupCount; ++i) {
  560. if (isSuitableGroup(i))
  561. groupIndex = i;
  562. }
  563. }
  564. if (!groupIndex) {
  565. printf("[ext2fs] allocateInode: no suitable group found for new inode with %u blocks needed :(\n", neededBlocks);
  566. return 0;
  567. }
  568. printf("[ext2fs] allocateInode: found suitable group [%u] for new inode with %u blocks needed :^)\n", groupIndex, neededBlocks);
  569. unsigned firstFreeInodeInGroup = 0;
  570. traverseInodeBitmap(groupIndex, [&firstFreeInodeInGroup] (unsigned firstInodeInBitmap, const Bitmap& bitmap) {
  571. for (unsigned i = 0; i < bitmap.size(); ++i) {
  572. if (!bitmap.get(i)) {
  573. firstFreeInodeInGroup = firstInodeInBitmap + i;
  574. return false;
  575. }
  576. }
  577. return true;
  578. });
  579. if (!firstFreeInodeInGroup) {
  580. printf("[ext2fs] firstFreeInodeInGroup returned no inode, despite bgd claiming there are inodes :(\n");
  581. return 0;
  582. }
  583. unsigned inode = firstFreeInodeInGroup;
  584. printf("[ext2fs] found suitable inode %u\n", inode);
  585. // FIXME: allocate blocks if needed!
  586. return inode;
  587. }
  588. unsigned Ext2FileSystem::groupIndexFromInode(unsigned inode) const
  589. {
  590. if (!inode)
  591. return 0;
  592. return (inode - 1) / inodesPerGroup() + 1;
  593. }
  594. bool Ext2FileSystem::setInodeAllocationState(unsigned inode, bool newState)
  595. {
  596. auto& bgd = blockGroupDescriptor(groupIndexFromInode(inode));
  597. // Update inode bitmap
  598. unsigned inodesPerBitmapBlock = blockSize() * 8;
  599. unsigned bitmapBlockIndex = (inode - 1) / inodesPerBitmapBlock;
  600. unsigned bitIndex = (inode - 1) % inodesPerBitmapBlock;
  601. auto block = readBlock(bgd.bg_inode_bitmap + bitmapBlockIndex);
  602. ASSERT(block);
  603. auto bitmap = Bitmap::wrap(block.pointer(), block.size());
  604. bool currentState = bitmap.get(bitIndex);
  605. printf("[ext2fs] setInodeAllocationState(%u) %u -> %u\n", inode, currentState, newState);
  606. if (currentState == newState)
  607. return true;
  608. bitmap.set(bitIndex, newState);
  609. writeBlock(bgd.bg_inode_bitmap + bitmapBlockIndex, block);
  610. // Update superblock
  611. auto& sb = *reinterpret_cast<ext2_super_block*>(m_cachedSuperBlock.pointer());
  612. printf("[ext2fs] superblock free inode count %u -> %u\n", sb.s_free_inodes_count, sb.s_free_inodes_count - 1);
  613. if (newState)
  614. --sb.s_free_inodes_count;
  615. else
  616. ++sb.s_free_inodes_count;
  617. writeSuperBlock(sb);
  618. // Update BGD
  619. auto& mutableBGD = const_cast<ext2_group_desc&>(bgd);
  620. if (newState)
  621. --mutableBGD.bg_free_inodes_count;
  622. else
  623. ++mutableBGD.bg_free_inodes_count;
  624. printf("[ext2fs] group free inode count %u -> %u\n", bgd.bg_free_inodes_count, bgd.bg_free_inodes_count - 1);
  625. unsigned blocksToWrite = ceilDiv(m_blockGroupCount * sizeof(ext2_group_desc), blockSize());
  626. unsigned firstBlockOfBGDT = blockSize() == 1024 ? 2 : 1;
  627. writeBlocks(firstBlockOfBGDT, blocksToWrite, m_cachedBlockGroupDescriptorTable);
  628. return true;
  629. }
  630. InodeIdentifier Ext2FileSystem::createInode(InodeIdentifier parentInode, const String& name, word mode)
  631. {
  632. ASSERT(parentInode.fileSystemID() == id());
  633. ASSERT(isDirectoryInode(parentInode.index()));
  634. //#ifdef EXT2_DEBUG
  635. printf("[ext2fs] Adding inode '%s' (mode %o) to parent directory %u:\n", name.characters(), mode, parentInode.index());
  636. //#endif
  637. // NOTE: This doesn't commit the inode allocation just yet!
  638. auto inode = allocateInode(0, 0);
  639. // Try adding it to the directory first, in case the name is already in use.
  640. bool success = addInodeToDirectory(parentInode.index(), inode, name);
  641. if (!success) {
  642. printf("[ext2fs] failed to add inode to directory :(\n");
  643. return { };
  644. }
  645. // Looks like we're good, time to update the inode bitmap and group+global inode counters.
  646. success = setInodeAllocationState(inode, true);
  647. ASSERT(success);
  648. auto timestamp = time(nullptr);
  649. auto e2inode = make<ext2_inode>();
  650. memset(e2inode.ptr(), 0, sizeof(ext2_inode));
  651. e2inode->i_mode = mode;
  652. e2inode->i_uid = 0;
  653. e2inode->i_size = 0;
  654. e2inode->i_atime = timestamp;
  655. e2inode->i_ctime = timestamp;
  656. e2inode->i_mtime = timestamp;
  657. e2inode->i_dtime = 0;
  658. e2inode->i_gid = 0;
  659. e2inode->i_links_count = 2;
  660. e2inode->i_blocks = 0;
  661. e2inode->i_flags = 0;
  662. success = writeExt2Inode(inode, *e2inode);
  663. ASSERT(success);
  664. return { id(), inode };
  665. }