Ext2FileSystem.cpp 31 KB

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