Ext2FileSystem.cpp 33 KB

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