Ext2FileSystem.cpp 25 KB

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