Ext2FileSystem.cpp 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013
  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() >= 128)
  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.unchecked_append(e2inode.i_block[i]);
  223. --blocksRemaining;
  224. }
  225. if (!blocksRemaining)
  226. return list;
  227. auto processBlockArray = [&] (unsigned arrayBlockIndex, auto&& 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.unchecked_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.unchecked_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.unchecked_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. while (entry < buffer.endPointer()) {
  361. if (entry->inode != 0) {
  362. #ifdef EXT2_DEBUG
  363. 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);
  364. #endif
  365. if (!callback({ entry->name, entry->name_len, { id(), entry->inode }, entry->file_type }))
  366. break;
  367. }
  368. entry = (ext2_dir_entry_2*)((char*)entry + entry->rec_len);
  369. }
  370. return true;
  371. }
  372. bool Ext2FileSystem::addInodeToDirectory(unsigned directoryInode, unsigned inode, const String& name, byte fileType)
  373. {
  374. auto e2inodeForDirectory = lookupExt2Inode(directoryInode);
  375. ASSERT(e2inodeForDirectory);
  376. ASSERT(isDirectory(e2inodeForDirectory->i_mode));
  377. //#ifdef EXT2_DEBUG
  378. kprintf("ext2fs: Adding inode %u with name '%s' to directory %u\n", inode, name.characters(), directoryInode);
  379. //#endif
  380. Vector<DirectoryEntry> entries;
  381. bool nameAlreadyExists = false;
  382. enumerateDirectoryInode({ id(), directoryInode }, [&] (const DirectoryEntry& entry) {
  383. if (!strcmp(entry.name, name.characters())) {
  384. nameAlreadyExists = true;
  385. return false;
  386. }
  387. entries.append(entry);
  388. return true;
  389. });
  390. if (nameAlreadyExists) {
  391. kprintf("ext2fs: Name '%s' already exists in directory inode %u\n", name.characters(), directoryInode);
  392. return false;
  393. }
  394. entries.append({ name.characters(), name.length(), { id(), inode }, fileType });
  395. return writeDirectoryInode(directoryInode, move(entries));
  396. }
  397. bool Ext2FileSystem::writeDirectoryInode(unsigned directoryInode, Vector<DirectoryEntry>&& entries)
  398. {
  399. kprintf("ext2fs: New directory inode %u contents to write:\n", directoryInode);
  400. unsigned directorySize = 0;
  401. for (auto& entry : entries) {
  402. kprintf(" - %08u %s\n", entry.inode.index(), entry.name);
  403. directorySize += EXT2_DIR_REC_LEN(entry.name_length);
  404. }
  405. unsigned blocksNeeded = ceilDiv(directorySize, blockSize());
  406. unsigned occupiedSize = blocksNeeded * blockSize();
  407. kprintf("ext2fs: directory size: %u (occupied: %u)\n", directorySize, occupiedSize);
  408. auto directoryData = ByteBuffer::createUninitialized(occupiedSize);
  409. BufferStream stream(directoryData);
  410. for (unsigned i = 0; i < entries.size(); ++i) {
  411. auto& entry = entries[i];
  412. unsigned recordLength = EXT2_DIR_REC_LEN(entry.name_length);
  413. if (i == entries.size() - 1)
  414. recordLength += occupiedSize - directorySize;
  415. kprintf("* inode: %u", entry.inode.index());
  416. kprintf(", name_len: %u", word(entry.name_length));
  417. kprintf(", rec_len: %u", word(recordLength));
  418. kprintf(", file_type: %u", byte(entry.fileType));
  419. kprintf(", name: %s\n", entry.name);
  420. stream << dword(entry.inode.index());
  421. stream << word(recordLength);
  422. stream << byte(entry.name_length);
  423. stream << byte(entry.fileType);
  424. stream << entry.name;
  425. unsigned padding = recordLength - entry.name_length - 8;
  426. kprintf(" *** pad %u bytes\n", padding);
  427. for (unsigned j = 0; j < padding; ++j) {
  428. stream << byte(0);
  429. }
  430. }
  431. stream.fillToEnd(0);
  432. #if 0
  433. kprintf("data to write (%u):\n", directoryData.size());
  434. for (unsigned i = 0; i < directoryData.size(); ++i) {
  435. kprintf("%02x ", directoryData[i]);
  436. if ((i + 1) % 8 == 0)
  437. kprintf(" ");
  438. if ((i + 1) % 16 == 0)
  439. kprintf("\n");
  440. }
  441. kprintf("\n");
  442. #endif
  443. writeInode({ id(), directoryInode }, directoryData);
  444. return true;
  445. }
  446. unsigned Ext2FileSystem::inodesPerBlock() const
  447. {
  448. return EXT2_INODES_PER_BLOCK(&superBlock());
  449. }
  450. unsigned Ext2FileSystem::inodesPerGroup() const
  451. {
  452. return EXT2_INODES_PER_GROUP(&superBlock());
  453. }
  454. unsigned Ext2FileSystem::inodeSize() const
  455. {
  456. return EXT2_INODE_SIZE(&superBlock());
  457. }
  458. unsigned Ext2FileSystem::blocksPerGroup() const
  459. {
  460. return EXT2_BLOCKS_PER_GROUP(&superBlock());
  461. }
  462. void Ext2FileSystem::dumpBlockBitmap(unsigned groupIndex) const
  463. {
  464. ASSERT(groupIndex <= m_blockGroupCount);
  465. auto& bgd = blockGroupDescriptor(groupIndex);
  466. unsigned blocksInGroup = min(blocksPerGroup(), superBlock().s_blocks_count);
  467. unsigned blockCount = ceilDiv(blocksInGroup, 8u);
  468. auto bitmapBlocks = readBlocks(bgd.bg_block_bitmap, blockCount);
  469. ASSERT(bitmapBlocks);
  470. kprintf("ext2fs: group[%u] block bitmap (bitmap occupies %u blocks):\n", groupIndex, blockCount);
  471. auto bitmap = Bitmap::wrap(bitmapBlocks.pointer(), blocksInGroup);
  472. for (unsigned i = 0; i < blocksInGroup; ++i) {
  473. kprintf("%c", bitmap.get(i) ? '1' : '0');
  474. }
  475. kprintf("\n");
  476. }
  477. void Ext2FileSystem::dumpInodeBitmap(unsigned groupIndex) const
  478. {
  479. traverseInodeBitmap(groupIndex, [] (unsigned, const Bitmap& bitmap) {
  480. for (unsigned i = 0; i < bitmap.size(); ++i)
  481. kprintf("%c", bitmap.get(i) ? '1' : '0');
  482. return true;
  483. });
  484. }
  485. template<typename F>
  486. void Ext2FileSystem::traverseInodeBitmap(unsigned groupIndex, F callback) const
  487. {
  488. ASSERT(groupIndex <= m_blockGroupCount);
  489. auto& bgd = blockGroupDescriptor(groupIndex);
  490. unsigned inodesInGroup = min(inodesPerGroup(), superBlock().s_inodes_count);
  491. unsigned blockCount = ceilDiv(inodesInGroup, 8u);
  492. for (unsigned i = 0; i < blockCount; ++i) {
  493. auto block = readBlock(bgd.bg_inode_bitmap + i);
  494. ASSERT(block);
  495. bool shouldContinue = callback(i * (blockSize() / 8) + 1, Bitmap::wrap(block.pointer(), inodesInGroup));
  496. if (!shouldContinue)
  497. break;
  498. }
  499. }
  500. template<typename F>
  501. void Ext2FileSystem::traverseBlockBitmap(unsigned groupIndex, F callback) const
  502. {
  503. ASSERT(groupIndex <= m_blockGroupCount);
  504. auto& bgd = blockGroupDescriptor(groupIndex);
  505. unsigned blocksInGroup = min(blocksPerGroup(), superBlock().s_blocks_count);
  506. unsigned blockCount = ceilDiv(blocksInGroup, 8u);
  507. for (unsigned i = 0; i < blockCount; ++i) {
  508. auto block = readBlock(bgd.bg_block_bitmap + i);
  509. ASSERT(block);
  510. bool shouldContinue = callback(i * (blockSize() / 8) + 1, Bitmap::wrap(block.pointer(), blocksInGroup));
  511. if (!shouldContinue)
  512. break;
  513. }
  514. }
  515. bool Ext2FileSystem::modifyLinkCount(InodeIndex inode, int delta)
  516. {
  517. ASSERT(inode);
  518. auto e2inode = lookupExt2Inode(inode);
  519. if (!e2inode)
  520. return false;
  521. auto newLinkCount = e2inode->i_links_count + delta;
  522. kprintf("changing inode %u link count from %u to %u\n", inode, e2inode->i_links_count, newLinkCount);
  523. e2inode->i_links_count = newLinkCount;
  524. return writeExt2Inode(inode, *e2inode);
  525. }
  526. bool Ext2FileSystem::setModificationTime(InodeIdentifier inode, dword timestamp)
  527. {
  528. ASSERT(inode.fileSystemID() == id());
  529. auto e2inode = lookupExt2Inode(inode.index());
  530. if (!e2inode)
  531. return false;
  532. kprintf("changing inode %u mtime from %u to %u\n", inode.index(), e2inode->i_mtime, timestamp);
  533. e2inode->i_mtime = timestamp;
  534. return writeExt2Inode(inode.index(), *e2inode);
  535. }
  536. bool Ext2FileSystem::writeExt2Inode(unsigned inode, const ext2_inode& e2inode)
  537. {
  538. unsigned blockIndex;
  539. unsigned offset;
  540. auto block = readBlockContainingInode(inode, blockIndex, offset);
  541. if (!block)
  542. return false;
  543. memcpy(reinterpret_cast<ext2_inode*>(block.offsetPointer(offset)), &e2inode, inodeSize());
  544. writeBlock(blockIndex, block);
  545. return true;
  546. }
  547. bool Ext2FileSystem::isDirectoryInode(unsigned inode) const
  548. {
  549. if (auto e2inode = lookupExt2Inode(inode))
  550. return isDirectory(e2inode->i_mode);
  551. return false;
  552. }
  553. Vector<Ext2FileSystem::BlockIndex> Ext2FileSystem::allocateBlocks(unsigned group, unsigned count)
  554. {
  555. kprintf("ext2fs: allocateBlocks(group: %u, count: %u)\n", group, count);
  556. auto& bgd = blockGroupDescriptor(group);
  557. if (bgd.bg_free_blocks_count < count) {
  558. kprintf("ext2fs: allocateBlocks can't allocate out of group %u, wanted %u but only %u available\n", group, count, bgd.bg_free_blocks_count);
  559. return { };
  560. }
  561. // FIXME: Implement a scan that finds consecutive blocks if possible.
  562. Vector<BlockIndex> blocks;
  563. traverseBlockBitmap(group, [&blocks, count] (unsigned firstBlockInBitmap, const Bitmap& bitmap) {
  564. for (unsigned i = 0; i < bitmap.size(); ++i) {
  565. if (!bitmap.get(i)) {
  566. blocks.append(firstBlockInBitmap + i);
  567. if (blocks.size() == count)
  568. return false;
  569. }
  570. }
  571. return true;
  572. });
  573. kprintf("ext2fs: allocateBlock found these blocks:\n");
  574. for (auto& bi : blocks) {
  575. kprintf(" > %u\n", bi);
  576. }
  577. return blocks;
  578. }
  579. unsigned Ext2FileSystem::allocateInode(unsigned preferredGroup, unsigned expectedSize)
  580. {
  581. kprintf("ext2fs: allocateInode(preferredGroup: %u, expectedSize: %u)\n", preferredGroup, expectedSize);
  582. unsigned neededBlocks = ceilDiv(expectedSize, blockSize());
  583. kprintf("ext2fs: minimum needed blocks: %u\n", neededBlocks);
  584. unsigned groupIndex = 0;
  585. auto isSuitableGroup = [this, neededBlocks] (unsigned groupIndex) {
  586. auto& bgd = blockGroupDescriptor(groupIndex);
  587. return bgd.bg_free_inodes_count && bgd.bg_free_blocks_count >= neededBlocks;
  588. };
  589. if (preferredGroup && isSuitableGroup(preferredGroup)) {
  590. groupIndex = preferredGroup;
  591. } else {
  592. for (unsigned i = 1; i <= m_blockGroupCount; ++i) {
  593. if (isSuitableGroup(i))
  594. groupIndex = i;
  595. }
  596. }
  597. if (!groupIndex) {
  598. kprintf("ext2fs: allocateInode: no suitable group found for new inode with %u blocks needed :(\n", neededBlocks);
  599. return 0;
  600. }
  601. kprintf("ext2fs: allocateInode: found suitable group [%u] for new inode with %u blocks needed :^)\n", groupIndex, neededBlocks);
  602. unsigned firstFreeInodeInGroup = 0;
  603. traverseInodeBitmap(groupIndex, [&firstFreeInodeInGroup] (unsigned firstInodeInBitmap, const Bitmap& bitmap) {
  604. for (unsigned i = 0; i < bitmap.size(); ++i) {
  605. if (!bitmap.get(i)) {
  606. firstFreeInodeInGroup = firstInodeInBitmap + i;
  607. return false;
  608. }
  609. }
  610. return true;
  611. });
  612. if (!firstFreeInodeInGroup) {
  613. kprintf("ext2fs: firstFreeInodeInGroup returned no inode, despite bgd claiming there are inodes :(\n");
  614. return 0;
  615. }
  616. unsigned inode = firstFreeInodeInGroup;
  617. kprintf("ext2fs: found suitable inode %u\n", inode);
  618. // FIXME: allocate blocks if needed!
  619. return inode;
  620. }
  621. unsigned Ext2FileSystem::groupIndexFromInode(unsigned inode) const
  622. {
  623. if (!inode)
  624. return 0;
  625. return (inode - 1) / inodesPerGroup() + 1;
  626. }
  627. bool Ext2FileSystem::setInodeAllocationState(unsigned inode, bool newState)
  628. {
  629. auto& bgd = blockGroupDescriptor(groupIndexFromInode(inode));
  630. // Update inode bitmap
  631. unsigned inodesPerBitmapBlock = blockSize() * 8;
  632. unsigned bitmapBlockIndex = (inode - 1) / inodesPerBitmapBlock;
  633. unsigned bitIndex = (inode - 1) % inodesPerBitmapBlock;
  634. auto block = readBlock(bgd.bg_inode_bitmap + bitmapBlockIndex);
  635. ASSERT(block);
  636. auto bitmap = Bitmap::wrap(block.pointer(), block.size());
  637. bool currentState = bitmap.get(bitIndex);
  638. kprintf("ext2fs: setInodeAllocationState(%u) %u -> %u\n", inode, currentState, newState);
  639. if (currentState == newState)
  640. return true;
  641. bitmap.set(bitIndex, newState);
  642. writeBlock(bgd.bg_inode_bitmap + bitmapBlockIndex, block);
  643. // Update superblock
  644. auto& sb = *reinterpret_cast<ext2_super_block*>(m_cachedSuperBlock.pointer());
  645. kprintf("ext2fs: superblock free inode count %u -> %u\n", sb.s_free_inodes_count, sb.s_free_inodes_count - 1);
  646. if (newState)
  647. --sb.s_free_inodes_count;
  648. else
  649. ++sb.s_free_inodes_count;
  650. writeSuperBlock(sb);
  651. // Update BGD
  652. auto& mutableBGD = const_cast<ext2_group_desc&>(bgd);
  653. if (newState)
  654. --mutableBGD.bg_free_inodes_count;
  655. else
  656. ++mutableBGD.bg_free_inodes_count;
  657. kprintf("ext2fs: group free inode count %u -> %u\n", bgd.bg_free_inodes_count, bgd.bg_free_inodes_count - 1);
  658. unsigned blocksToWrite = ceilDiv(m_blockGroupCount * (unsigned)sizeof(ext2_group_desc), blockSize());
  659. unsigned firstBlockOfBGDT = blockSize() == 1024 ? 2 : 1;
  660. writeBlocks(firstBlockOfBGDT, blocksToWrite, m_cachedBlockGroupDescriptorTable);
  661. return true;
  662. }
  663. bool Ext2FileSystem::setBlockAllocationState(GroupIndex group, BlockIndex bi, bool newState)
  664. {
  665. auto& bgd = blockGroupDescriptor(group);
  666. // Update block bitmap
  667. unsigned blocksPerBitmapBlock = blockSize() * 8;
  668. unsigned bitmapBlockIndex = (bi - 1) / blocksPerBitmapBlock;
  669. unsigned bitIndex = (bi - 1) % blocksPerBitmapBlock;
  670. auto block = readBlock(bgd.bg_block_bitmap + bitmapBlockIndex);
  671. ASSERT(block);
  672. auto bitmap = Bitmap::wrap(block.pointer(), block.size());
  673. bool currentState = bitmap.get(bitIndex);
  674. kprintf("ext2fs: setBlockAllocationState(%u) %u -> %u\n", bi, currentState, newState);
  675. if (currentState == newState)
  676. return true;
  677. bitmap.set(bitIndex, newState);
  678. writeBlock(bgd.bg_block_bitmap + bitmapBlockIndex, block);
  679. // Update superblock
  680. auto& sb = *reinterpret_cast<ext2_super_block*>(m_cachedSuperBlock.pointer());
  681. kprintf("ext2fs: superblock free block count %u -> %u\n", sb.s_free_blocks_count, sb.s_free_blocks_count - 1);
  682. if (newState)
  683. --sb.s_free_blocks_count;
  684. else
  685. ++sb.s_free_blocks_count;
  686. writeSuperBlock(sb);
  687. // Update BGD
  688. auto& mutableBGD = const_cast<ext2_group_desc&>(bgd);
  689. if (newState)
  690. --mutableBGD.bg_free_blocks_count;
  691. else
  692. ++mutableBGD.bg_free_blocks_count;
  693. kprintf("ext2fs: group free block count %u -> %u\n", bgd.bg_free_blocks_count, bgd.bg_free_blocks_count - 1);
  694. unsigned blocksToWrite = ceilDiv(m_blockGroupCount * (unsigned)sizeof(ext2_group_desc), blockSize());
  695. unsigned firstBlockOfBGDT = blockSize() == 1024 ? 2 : 1;
  696. writeBlocks(firstBlockOfBGDT, blocksToWrite, m_cachedBlockGroupDescriptorTable);
  697. return true;
  698. }
  699. InodeIdentifier Ext2FileSystem::makeDirectory(InodeIdentifier parentInode, const String& name, Unix::mode_t mode)
  700. {
  701. ASSERT(parentInode.fileSystemID() == id());
  702. ASSERT(isDirectoryInode(parentInode.index()));
  703. // Fix up the mode to definitely be a directory.
  704. // FIXME: This is a bit on the hackish side.
  705. mode &= ~0170000;
  706. mode |= 0040000;
  707. // NOTE: When creating a new directory, make the size 1 block.
  708. // There's probably a better strategy here, but this works for now.
  709. auto inode = createInode(parentInode, name, mode, blockSize());
  710. if (!inode.isValid())
  711. return { };
  712. kprintf("ext2fs: makeDirectory: created new directory named '%s' with inode %u\n", name.characters(), inode.index());
  713. Vector<DirectoryEntry> entries;
  714. entries.append({ ".", inode, EXT2_FT_DIR });
  715. entries.append({ "..", parentInode, EXT2_FT_DIR });
  716. bool success = writeDirectoryInode(inode.index(), move(entries));
  717. ASSERT(success);
  718. success = modifyLinkCount(parentInode.index(), 1);
  719. ASSERT(success);
  720. auto& bgd = const_cast<ext2_group_desc&>(blockGroupDescriptor(groupIndexFromInode(inode.index())));
  721. ++bgd.bg_used_dirs_count;
  722. kprintf("ext2fs: incremented bg_used_dirs_count %u -> %u\n", bgd.bg_used_dirs_count - 1, bgd.bg_used_dirs_count);
  723. unsigned blocksToWrite = ceilDiv(m_blockGroupCount * (unsigned)sizeof(ext2_group_desc), blockSize());
  724. unsigned firstBlockOfBGDT = blockSize() == 1024 ? 2 : 1;
  725. writeBlocks(firstBlockOfBGDT, blocksToWrite, m_cachedBlockGroupDescriptorTable);
  726. return inode;
  727. }
  728. InodeIdentifier Ext2FileSystem::createInode(InodeIdentifier parentInode, const String& name, Unix::mode_t mode, unsigned size)
  729. {
  730. ASSERT(parentInode.fileSystemID() == id());
  731. ASSERT(isDirectoryInode(parentInode.index()));
  732. //#ifdef EXT2_DEBUG
  733. kprintf("ext2fs: Adding inode '%s' (mode %o) to parent directory %u:\n", name.characters(), mode, parentInode.index());
  734. //#endif
  735. // NOTE: This doesn't commit the inode allocation just yet!
  736. auto inode = allocateInode(0, 0);
  737. if (!inode) {
  738. kprintf("ext2fs: createInode: allocateInode failed\n");
  739. return { };
  740. }
  741. auto blocks = allocateBlocks(groupIndexFromInode(inode), ceilDiv(size, blockSize()));
  742. if (blocks.isEmpty()) {
  743. kprintf("ext2fs: createInode: allocateBlocks failed\n");
  744. return { };
  745. }
  746. byte fileType = 0;
  747. if (isRegularFile(mode))
  748. fileType = EXT2_FT_REG_FILE;
  749. else if (isDirectory(mode))
  750. fileType = EXT2_FT_DIR;
  751. else if (isCharacterDevice(mode))
  752. fileType = EXT2_FT_CHRDEV;
  753. else if (isBlockDevice(mode))
  754. fileType = EXT2_FT_BLKDEV;
  755. else if (isFIFO(mode))
  756. fileType = EXT2_FT_FIFO;
  757. else if (isSocket(mode))
  758. fileType = EXT2_FT_SOCK;
  759. else if (isSymbolicLink(mode))
  760. fileType = EXT2_FT_SYMLINK;
  761. // Try adding it to the directory first, in case the name is already in use.
  762. bool success = addInodeToDirectory(parentInode.index(), inode, name, fileType);
  763. if (!success) {
  764. kprintf("ext2fs: failed to add inode to directory :(\n");
  765. return { };
  766. }
  767. // Looks like we're good, time to update the inode bitmap and group+global inode counters.
  768. success = setInodeAllocationState(inode, true);
  769. ASSERT(success);
  770. for (auto bi : blocks) {
  771. success = setBlockAllocationState(groupIndexFromInode(inode), bi, true);
  772. ASSERT(success);
  773. }
  774. unsigned initialLinksCount;
  775. if (isDirectory(mode))
  776. initialLinksCount = 2; // (parent directory + "." entry in self)
  777. else
  778. initialLinksCount = 1;
  779. auto timestamp = ktime(nullptr);
  780. auto e2inode = make<ext2_inode>();
  781. memset(e2inode.ptr(), 0, sizeof(ext2_inode));
  782. e2inode->i_mode = mode;
  783. e2inode->i_uid = 0;
  784. e2inode->i_size = size;
  785. e2inode->i_atime = timestamp;
  786. e2inode->i_ctime = timestamp;
  787. e2inode->i_mtime = timestamp;
  788. e2inode->i_dtime = 0;
  789. e2inode->i_gid = 0;
  790. e2inode->i_links_count = initialLinksCount;
  791. e2inode->i_blocks = blocks.size() * (blockSize() / 512);
  792. // FIXME: Implement writing out indirect blocks!
  793. ASSERT(blocks.size() < EXT2_NDIR_BLOCKS);
  794. kprintf("[XXX] writing %zu blocks to i_block array\n", min((size_t)EXT2_NDIR_BLOCKS, blocks.size()));
  795. for (unsigned i = 0; i < min((size_t)EXT2_NDIR_BLOCKS, blocks.size()); ++i) {
  796. e2inode->i_block[i] = blocks[i];
  797. }
  798. e2inode->i_flags = 0;
  799. success = writeExt2Inode(inode, *e2inode);
  800. ASSERT(success);
  801. return { id(), inode };
  802. }
  803. InodeIdentifier Ext2FileSystem::findParentOfInode(InodeIdentifier inode) const
  804. {
  805. ASSERT(inode.fileSystemID() == id());
  806. unsigned groupIndex = groupIndexFromInode(inode.index());
  807. unsigned firstInodeInGroup = inodesPerGroup() * (groupIndex - 1);
  808. Vector<InodeIdentifier> directoriesInGroup;
  809. for (unsigned i = 0; i < inodesPerGroup(); ++i) {
  810. auto e2inode = lookupExt2Inode(firstInodeInGroup + i);
  811. if (!e2inode)
  812. continue;
  813. if (isDirectory(e2inode->i_mode)) {
  814. directoriesInGroup.append({ id(), firstInodeInGroup + i });
  815. }
  816. }
  817. InodeIdentifier foundParent;
  818. for (auto& directory : directoriesInGroup) {
  819. enumerateDirectoryInode(directory, [inode, directory, &foundParent] (auto& entry) {
  820. if (entry.inode == inode) {
  821. foundParent = directory;
  822. return false;
  823. }
  824. return true;
  825. });
  826. if (foundParent.isValid())
  827. break;
  828. }
  829. return foundParent;
  830. }