Ext2FileSystem.cpp 33 KB

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