Ext2FileSystem.cpp 33 KB

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