Ext2FileSystem.cpp 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301
  1. #include "Ext2FileSystem.h"
  2. #include "ext2_fs.h"
  3. #include "UnixTypes.h"
  4. #include "RTC.h"
  5. #include <AK/Bitmap.h>
  6. #include <AK/StdLibExtras.h>
  7. #include <AK/kmalloc.h>
  8. #include <AK/ktime.h>
  9. #include <AK/kstdio.h>
  10. #include <AK/BufferStream.h>
  11. #include <LibC/errno_numbers.h>
  12. //#define EXT2_DEBUG
  13. RetainPtr<Ext2FS> Ext2FS::create(RetainPtr<DiskDevice>&& device)
  14. {
  15. return adopt(*new Ext2FS(move(device)));
  16. }
  17. Ext2FS::Ext2FS(RetainPtr<DiskDevice>&& device)
  18. : DiskBackedFS(move(device))
  19. {
  20. }
  21. Ext2FS::~Ext2FS()
  22. {
  23. }
  24. ByteBuffer Ext2FS::read_super_block() const
  25. {
  26. auto buffer = ByteBuffer::create_uninitialized(1024);
  27. device().read_block(2, buffer.pointer());
  28. device().read_block(3, buffer.offset_pointer(512));
  29. return buffer;
  30. }
  31. bool Ext2FS::write_super_block(const ext2_super_block& sb)
  32. {
  33. const byte* raw = (const byte*)&sb;
  34. bool success;
  35. success = device().write_block(2, raw);
  36. ASSERT(success);
  37. success = device().write_block(3, raw + 512);
  38. ASSERT(success);
  39. // FIXME: This is an ugly way to refresh the superblock cache. :-|
  40. super_block();
  41. return true;
  42. }
  43. unsigned Ext2FS::first_block_of_group(unsigned groupIndex) const
  44. {
  45. return super_block().s_first_data_block + (groupIndex * super_block().s_blocks_per_group);
  46. }
  47. const ext2_super_block& Ext2FS::super_block() const
  48. {
  49. if (!m_cached_super_block)
  50. m_cached_super_block = read_super_block();
  51. return *reinterpret_cast<ext2_super_block*>(m_cached_super_block.pointer());
  52. }
  53. const ext2_group_desc& Ext2FS::group_descriptor(unsigned groupIndex) const
  54. {
  55. // FIXME: Should this fail gracefully somehow?
  56. ASSERT(groupIndex <= m_blockGroupCount);
  57. if (!m_cached_group_descriptor_table) {
  58. unsigned blocksToRead = ceilDiv(m_blockGroupCount * (unsigned)sizeof(ext2_group_desc), blockSize());
  59. unsigned firstBlockOfBGDT = blockSize() == 1024 ? 2 : 1;
  60. #ifdef EXT2_DEBUG
  61. kprintf("ext2fs: block group count: %u, blocks-to-read: %u\n", m_blockGroupCount, blocksToRead);
  62. kprintf("ext2fs: first block of BGDT: %u\n", firstBlockOfBGDT);
  63. #endif
  64. m_cached_group_descriptor_table = readBlocks(firstBlockOfBGDT, blocksToRead);
  65. }
  66. return reinterpret_cast<ext2_group_desc*>(m_cached_group_descriptor_table.pointer())[groupIndex - 1];
  67. }
  68. bool Ext2FS::initialize()
  69. {
  70. auto& superBlock = this->super_block();
  71. #ifdef EXT2_DEBUG
  72. kprintf("ext2fs: super block magic: %x (super block size: %u)\n", superBlock.s_magic, sizeof(ext2_super_block));
  73. #endif
  74. if (superBlock.s_magic != EXT2_SUPER_MAGIC)
  75. return false;
  76. #ifdef EXT2_DEBUG
  77. kprintf("ext2fs: %u inodes, %u blocks\n", superBlock.s_inodes_count, superBlock.s_blocks_count);
  78. kprintf("ext2fs: block size = %u\n", EXT2_BLOCK_SIZE(&superBlock));
  79. kprintf("ext2fs: first data block = %u\n", superBlock.s_first_data_block);
  80. kprintf("ext2fs: inodes per block = %u\n", inodes_per_block());
  81. kprintf("ext2fs: inodes per group = %u\n", inodes_per_group());
  82. kprintf("ext2fs: free inodes = %u\n", superBlock.s_free_inodes_count);
  83. kprintf("ext2fs: desc per block = %u\n", EXT2_DESC_PER_BLOCK(&superBlock));
  84. kprintf("ext2fs: desc size = %u\n", EXT2_DESC_SIZE(&superBlock));
  85. #endif
  86. setBlockSize(EXT2_BLOCK_SIZE(&superBlock));
  87. m_blockGroupCount = ceilDiv(superBlock.s_blocks_count, superBlock.s_blocks_per_group);
  88. if (m_blockGroupCount == 0) {
  89. kprintf("ext2fs: no block groups :(\n");
  90. return false;
  91. }
  92. // Preheat the BGD cache.
  93. group_descriptor(0);
  94. #ifdef EXT2_DEBUG
  95. for (unsigned i = 1; i <= m_blockGroupCount; ++i) {
  96. auto& group = group_descriptor(i);
  97. kprintf("ext2fs: group[%u] { block_bitmap: %u, inode_bitmap: %u, inode_table: %u }\n",
  98. i,
  99. group.bg_block_bitmap,
  100. group.bg_inode_bitmap,
  101. group.bg_inode_table);
  102. }
  103. #endif
  104. return true;
  105. }
  106. const char* Ext2FS::class_name() const
  107. {
  108. return "ext2fs";
  109. }
  110. InodeIdentifier Ext2FS::root_inode() const
  111. {
  112. return { fsid(), EXT2_ROOT_INO };
  113. }
  114. ByteBuffer Ext2FS::read_block_containing_inode(unsigned inode, unsigned& blockIndex, unsigned& offset) const
  115. {
  116. auto& superBlock = this->super_block();
  117. if (inode != EXT2_ROOT_INO && inode < EXT2_FIRST_INO(&superBlock))
  118. return { };
  119. if (inode > superBlock.s_inodes_count)
  120. return { };
  121. auto& bgd = group_descriptor(group_index_from_inode(inode));
  122. offset = ((inode - 1) % inodes_per_group()) * inode_size();
  123. blockIndex = bgd.bg_inode_table + (offset >> EXT2_BLOCK_SIZE_BITS(&superBlock));
  124. offset &= blockSize() - 1;
  125. return readBlock(blockIndex);
  126. }
  127. Ext2FS::BlockListShape Ext2FS::compute_block_list_shape(unsigned blocks)
  128. {
  129. BlockListShape shape;
  130. const unsigned entries_per_block = EXT2_ADDR_PER_BLOCK(&super_block());
  131. unsigned blocks_remaining = blocks;
  132. shape.direct_blocks = min((unsigned)EXT2_NDIR_BLOCKS, blocks_remaining);
  133. blocks_remaining -= shape.direct_blocks;
  134. if (!blocks_remaining)
  135. return shape;
  136. shape.indirect_blocks = min(blocks_remaining, entries_per_block);
  137. blocks_remaining -= shape.indirect_blocks;
  138. shape.meta_blocks += 1;
  139. if (!blocks_remaining)
  140. return shape;
  141. ASSERT_NOT_REACHED();
  142. // FIXME: Support dind/tind blocks.
  143. shape.doubly_indirect_blocks = min(blocks_remaining, entries_per_block * entries_per_block);
  144. blocks_remaining -= shape.doubly_indirect_blocks;
  145. if (!blocks_remaining)
  146. return shape;
  147. shape.triply_indirect_blocks = min(blocks_remaining, entries_per_block * entries_per_block * entries_per_block);
  148. blocks_remaining -= shape.triply_indirect_blocks;
  149. // FIXME: What do we do for files >= 16GB?
  150. ASSERT(!blocks_remaining);
  151. return shape;
  152. }
  153. bool Ext2FS::write_block_list_for_inode(InodeIndex inode_index, ext2_inode& e2inode, const Vector<BlockIndex>& blocks)
  154. {
  155. dbgprintf("Ext2FS: writing %u block(s) to i_block array\n", min((size_t)EXT2_NDIR_BLOCKS, blocks.size()));
  156. auto old_shape = compute_block_list_shape(e2inode.i_blocks / (2 << super_block().s_log_block_size));
  157. auto new_shape = compute_block_list_shape(blocks.size());
  158. Vector<BlockIndex> new_meta_blocks;
  159. if (new_shape.meta_blocks > old_shape.meta_blocks) {
  160. new_meta_blocks = allocate_blocks(group_index_from_inode(inode_index), new_shape.meta_blocks - old_shape.meta_blocks);
  161. for (auto bi : new_meta_blocks)
  162. set_block_allocation_state(group_index_from_inode(inode_index), bi, true);
  163. }
  164. e2inode.i_blocks = (blocks.size() + new_shape.meta_blocks) * (blockSize() / 512);
  165. unsigned output_block_index = 0;
  166. unsigned remaining_blocks = blocks.size();
  167. for (unsigned i = 0; i < new_shape.direct_blocks; ++i) {
  168. e2inode.i_block[i] = blocks[output_block_index++];
  169. --remaining_blocks;
  170. }
  171. write_ext2_inode(inode_index, e2inode);
  172. if (!remaining_blocks)
  173. return true;
  174. if (!e2inode.i_block[EXT2_IND_BLOCK]) {
  175. e2inode.i_block[EXT2_IND_BLOCK] = new_meta_blocks.take_last();
  176. write_ext2_inode(inode_index, e2inode);
  177. }
  178. {
  179. dbgprintf("Ext2FS: Writing out indirect blockptr block for inode %u\n", inode_index);
  180. auto block_contents = ByteBuffer::create_uninitialized(blockSize());
  181. BufferStream stream(block_contents);
  182. ASSERT(new_shape.indirect_blocks <= EXT2_ADDR_PER_BLOCK(&super_block()));
  183. for (unsigned i = 0; i < new_shape.indirect_blocks; ++i) {
  184. stream << blocks[output_block_index++];
  185. --remaining_blocks;
  186. }
  187. stream.fill_to_end(0);
  188. writeBlock(e2inode.i_block[EXT2_IND_BLOCK], block_contents);
  189. }
  190. if (!remaining_blocks)
  191. return true;
  192. // FIXME: Implement!
  193. ASSERT_NOT_REACHED();
  194. }
  195. Vector<unsigned> Ext2FS::block_list_for_inode(const ext2_inode& e2inode, bool include_block_list_blocks) const
  196. {
  197. unsigned entriesPerBlock = EXT2_ADDR_PER_BLOCK(&super_block());
  198. // NOTE: i_blocks is number of 512-byte blocks, not number of fs-blocks.
  199. unsigned blockCount = e2inode.i_blocks / (blockSize() / 512);
  200. unsigned blocksRemaining = blockCount;
  201. Vector<unsigned> list;
  202. if (include_block_list_blocks) {
  203. // This seems like an excessive over-estimate but w/e.
  204. list.ensure_capacity(blocksRemaining * 2);
  205. } else {
  206. list.ensure_capacity(blocksRemaining);
  207. }
  208. unsigned directCount = min(blockCount, (unsigned)EXT2_NDIR_BLOCKS);
  209. for (unsigned i = 0; i < directCount; ++i) {
  210. list.unchecked_append(e2inode.i_block[i]);
  211. --blocksRemaining;
  212. }
  213. if (!blocksRemaining)
  214. return list;
  215. auto processBlockArray = [&] (unsigned arrayBlockIndex, auto&& callback) {
  216. if (include_block_list_blocks)
  217. callback(arrayBlockIndex);
  218. auto arrayBlock = readBlock(arrayBlockIndex);
  219. ASSERT(arrayBlock);
  220. auto* array = reinterpret_cast<const __u32*>(arrayBlock.pointer());
  221. unsigned count = min(blocksRemaining, entriesPerBlock);
  222. for (unsigned i = 0; i < count; ++i) {
  223. if (!array[i]) {
  224. blocksRemaining = 0;
  225. return;
  226. }
  227. callback(array[i]);
  228. --blocksRemaining;
  229. }
  230. };
  231. processBlockArray(e2inode.i_block[EXT2_IND_BLOCK], [&] (unsigned entry) {
  232. list.unchecked_append(entry);
  233. });
  234. if (!blocksRemaining)
  235. return list;
  236. processBlockArray(e2inode.i_block[EXT2_DIND_BLOCK], [&] (unsigned entry) {
  237. processBlockArray(entry, [&] (unsigned entry) {
  238. list.unchecked_append(entry);
  239. });
  240. });
  241. if (!blocksRemaining)
  242. return list;
  243. processBlockArray(e2inode.i_block[EXT2_TIND_BLOCK], [&] (unsigned entry) {
  244. processBlockArray(entry, [&] (unsigned entry) {
  245. processBlockArray(entry, [&] (unsigned entry) {
  246. list.unchecked_append(entry);
  247. });
  248. });
  249. });
  250. return list;
  251. }
  252. void Ext2FS::free_inode(Ext2FSInode& inode)
  253. {
  254. ASSERT(inode.m_raw_inode.i_links_count == 0);
  255. dbgprintf("Ext2FS: inode %u has no more links, time to delete!\n", inode.index());
  256. inode.m_raw_inode.i_dtime = RTC::now();
  257. write_ext2_inode(inode.index(), inode.m_raw_inode);
  258. auto block_list = block_list_for_inode(inode.m_raw_inode, true);
  259. auto group_index = group_index_from_inode(inode.index());
  260. for (auto block_index : block_list)
  261. set_block_allocation_state(group_index, block_index, false);
  262. set_inode_allocation_state(inode.index(), false);
  263. if (inode.is_directory()) {
  264. auto& bgd = const_cast<ext2_group_desc&>(group_descriptor(group_index_from_inode(inode.index())));
  265. --bgd.bg_used_dirs_count;
  266. dbgprintf("Ext2FS: decremented bg_used_dirs_count %u -> %u\n", bgd.bg_used_dirs_count - 1, bgd.bg_used_dirs_count);
  267. flush_block_group_descriptor_table();
  268. }
  269. }
  270. void Ext2FS::flush_block_group_descriptor_table()
  271. {
  272. unsigned blocks_to_write = ceilDiv(m_blockGroupCount * (unsigned)sizeof(ext2_group_desc), blockSize());
  273. unsigned first_block_of_bgdt = blockSize() == 1024 ? 2 : 1;
  274. writeBlocks(first_block_of_bgdt, blocks_to_write, m_cached_group_descriptor_table);
  275. }
  276. Ext2FSInode::Ext2FSInode(Ext2FS& fs, unsigned index, const ext2_inode& raw_inode)
  277. : Inode(fs, index)
  278. , m_raw_inode(raw_inode)
  279. {
  280. }
  281. Ext2FSInode::~Ext2FSInode()
  282. {
  283. if (m_raw_inode.i_links_count == 0)
  284. fs().free_inode(*this);
  285. }
  286. InodeMetadata Ext2FSInode::metadata() const
  287. {
  288. InodeMetadata metadata;
  289. metadata.inode = identifier();
  290. metadata.size = m_raw_inode.i_size;
  291. metadata.mode = m_raw_inode.i_mode;
  292. metadata.uid = m_raw_inode.i_uid;
  293. metadata.gid = m_raw_inode.i_gid;
  294. metadata.linkCount = m_raw_inode.i_links_count;
  295. metadata.atime = m_raw_inode.i_atime;
  296. metadata.ctime = m_raw_inode.i_ctime;
  297. metadata.mtime = m_raw_inode.i_mtime;
  298. metadata.dtime = m_raw_inode.i_dtime;
  299. metadata.blockSize = fs().blockSize();
  300. metadata.blockCount = m_raw_inode.i_blocks;
  301. if (isBlockDevice(m_raw_inode.i_mode) || isCharacterDevice(m_raw_inode.i_mode)) {
  302. unsigned dev = m_raw_inode.i_block[0];
  303. metadata.majorDevice = (dev & 0xfff00) >> 8;
  304. metadata.minorDevice= (dev & 0xff) | ((dev >> 12) & 0xfff00);
  305. }
  306. return metadata;
  307. }
  308. void Ext2FSInode::flush_metadata()
  309. {
  310. dbgprintf("Ext2FSInode: flush_metadata for inode %u\n", index());
  311. fs().write_ext2_inode(index(), m_raw_inode);
  312. if (is_directory()) {
  313. // Unless we're about to go away permanently, invalidate the lookup cache.
  314. if (m_raw_inode.i_links_count != 0) {
  315. LOCKER(m_lock);
  316. // FIXME: This invalidation is way too hardcore. It's sad to throw away the whole cache.
  317. m_lookup_cache.clear();
  318. }
  319. }
  320. set_metadata_dirty(false);
  321. }
  322. RetainPtr<Inode> Ext2FS::get_inode(InodeIdentifier inode) const
  323. {
  324. ASSERT(inode.fsid() == fsid());
  325. {
  326. LOCKER(m_inode_cache_lock);
  327. auto it = m_inode_cache.find(inode.index());
  328. if (it != m_inode_cache.end())
  329. return (*it).value;
  330. }
  331. if (!get_inode_allocation_state(inode.index())) {
  332. LOCKER(m_inode_cache_lock);
  333. m_inode_cache.set(inode.index(), nullptr);
  334. return nullptr;
  335. }
  336. unsigned block_index;
  337. unsigned offset;
  338. auto block = read_block_containing_inode(inode.index(), block_index, offset);
  339. if (!block)
  340. return { };
  341. // FIXME: Avoid this extra allocation, copy the raw inode directly into the Ext2FSInode metadata somehow.
  342. auto* e2inode = reinterpret_cast<ext2_inode*>(kmalloc(inode_size()));
  343. memcpy(e2inode, reinterpret_cast<ext2_inode*>(block.offset_pointer(offset)), inode_size());
  344. auto raw_inode = OwnPtr<ext2_inode>(e2inode);
  345. if (!raw_inode)
  346. return nullptr;
  347. LOCKER(m_inode_cache_lock);
  348. auto it = m_inode_cache.find(inode.index());
  349. if (it != m_inode_cache.end())
  350. return (*it).value;
  351. auto new_inode = adopt(*new Ext2FSInode(const_cast<Ext2FS&>(*this), inode.index(), *raw_inode));
  352. m_inode_cache.set(inode.index(), new_inode.copyRef());
  353. return new_inode;
  354. }
  355. ssize_t Ext2FSInode::read_bytes(off_t offset, size_t count, byte* buffer, FileDescriptor*) const
  356. {
  357. ASSERT(offset >= 0);
  358. if (m_raw_inode.i_size == 0)
  359. return 0;
  360. // Symbolic links shorter than 60 characters are store inline inside the i_block array.
  361. // This avoids wasting an entire block on short links. (Most links are short.)
  362. static const unsigned max_inline_symlink_length = 60;
  363. if (is_symlink() && size() < max_inline_symlink_length) {
  364. ssize_t nread = min((off_t)size() - offset, static_cast<off_t>(count));
  365. memcpy(buffer, m_raw_inode.i_block + offset, nread);
  366. return nread;
  367. }
  368. if (m_block_list.is_empty()) {
  369. auto block_list = fs().block_list_for_inode(m_raw_inode);
  370. LOCKER(m_lock);
  371. if (m_block_list.size() != block_list.size())
  372. m_block_list = move(block_list);
  373. }
  374. if (m_block_list.is_empty()) {
  375. kprintf("ext2fs: read_bytes: empty block list for inode %u\n", index());
  376. return -EIO;
  377. }
  378. const size_t block_size = fs().blockSize();
  379. dword first_block_logical_index = offset / block_size;
  380. dword last_block_logical_index = (offset + count) / block_size;
  381. if (last_block_logical_index >= m_block_list.size())
  382. last_block_logical_index = m_block_list.size() - 1;
  383. dword offset_into_first_block = offset % block_size;
  384. ssize_t nread = 0;
  385. size_t remaining_count = min((off_t)count, (off_t)size() - offset);
  386. byte* out = buffer;
  387. #ifdef EXT2_DEBUG
  388. kprintf("Ext2FS: Reading up to %u bytes %d bytes into inode %u:%u to %p\n", count, offset, identifier().fsid(), identifier().index(), buffer);
  389. //kprintf("ok let's do it, read(%u, %u) -> blocks %u thru %u, oifb: %u\n", offset, count, first_block_logical_index, last_block_logical_index, offset_into_first_block);
  390. #endif
  391. for (dword bi = first_block_logical_index; remaining_count && bi <= last_block_logical_index; ++bi) {
  392. auto block = fs().readBlock(m_block_list[bi]);
  393. if (!block) {
  394. kprintf("ext2fs: read_bytes: readBlock(%u) failed (lbi: %u)\n", m_block_list[bi], bi);
  395. return -EIO;
  396. }
  397. dword offset_into_block = (bi == first_block_logical_index) ? offset_into_first_block : 0;
  398. dword num_bytes_to_copy = min(block_size - offset_into_block, remaining_count);
  399. memcpy(out, block.pointer() + offset_into_block, num_bytes_to_copy);
  400. remaining_count -= num_bytes_to_copy;
  401. nread += num_bytes_to_copy;
  402. out += num_bytes_to_copy;
  403. }
  404. return nread;
  405. }
  406. ssize_t Ext2FSInode::write_bytes(off_t offset, size_t count, const byte* data, FileDescriptor*)
  407. {
  408. LOCKER(m_lock);
  409. // FIXME: Support writing to symlink inodes.
  410. ASSERT(!is_symlink());
  411. ASSERT(offset >= 0);
  412. const size_t block_size = fs().blockSize();
  413. size_t new_size = max(static_cast<size_t>(offset) + count, size());
  414. unsigned blocks_needed_before = ceilDiv(size(), block_size);
  415. unsigned blocks_needed_after = ceilDiv(new_size, block_size);
  416. auto block_list = fs().block_list_for_inode(m_raw_inode);
  417. if (blocks_needed_after > blocks_needed_before) {
  418. auto new_blocks = fs().allocate_blocks(fs().group_index_from_inode(index()), blocks_needed_after - blocks_needed_before);
  419. for (auto new_block_index : new_blocks)
  420. fs().set_block_allocation_state(fs().group_index_from_inode(index()), new_block_index, true);
  421. block_list.append(move(new_blocks));
  422. } else if (blocks_needed_after < blocks_needed_before) {
  423. // FIXME: Implement block list shrinking!
  424. ASSERT_NOT_REACHED();
  425. }
  426. dword first_block_logical_index = offset / block_size;
  427. dword last_block_logical_index = (offset + count) / block_size;
  428. if (last_block_logical_index >= block_list.size())
  429. last_block_logical_index = block_list.size() - 1;
  430. dword offset_into_first_block = offset % block_size;
  431. ssize_t nwritten = 0;
  432. size_t remaining_count = min((off_t)count, (off_t)new_size - offset);
  433. const byte* in = data;
  434. #ifdef EXT2_DEBUG
  435. dbgprintf("Ext2FSInode::write_bytes: Writing %u bytes %d bytes into inode %u:%u from %p\n", count, offset, fsid(), index(), data);
  436. #endif
  437. auto buffer_block = ByteBuffer::create_uninitialized(block_size);
  438. for (dword bi = first_block_logical_index; remaining_count && bi <= last_block_logical_index; ++bi) {
  439. dword offset_into_block = (bi == first_block_logical_index) ? offset_into_first_block : 0;
  440. dword num_bytes_to_copy = min(block_size - offset_into_block, remaining_count);
  441. ByteBuffer block;
  442. if (offset_into_block != 0) {
  443. block = fs().readBlock(block_list[bi]);
  444. if (!block) {
  445. kprintf("Ext2FSInode::write_bytes: readBlock(%u) failed (lbi: %u)\n", block_list[bi], bi);
  446. return -EIO;
  447. }
  448. } else
  449. block = buffer_block;
  450. memcpy(block.pointer() + offset_into_block, in, num_bytes_to_copy);
  451. if (offset_into_block == 0 && !num_bytes_to_copy)
  452. memset(block.pointer() + num_bytes_to_copy, 0, block_size - num_bytes_to_copy);
  453. #ifdef EXT2_DEBUG
  454. dbgprintf("Ext2FSInode::write_bytes: writing block %u (offset_into_block: %u)\n", block_list[bi], offset_into_block);
  455. #endif
  456. bool success = fs().writeBlock(block_list[bi], block);
  457. if (!success) {
  458. kprintf("Ext2FSInode::write_bytes: writeBlock(%u) failed (lbi: %u)\n", block_list[bi], bi);
  459. return -EIO;
  460. }
  461. remaining_count -= num_bytes_to_copy;
  462. nwritten += num_bytes_to_copy;
  463. in += num_bytes_to_copy;
  464. }
  465. bool success = fs().write_block_list_for_inode(index(), m_raw_inode, block_list);
  466. ASSERT(success);
  467. m_raw_inode.i_size = new_size;
  468. fs().write_ext2_inode(index(), m_raw_inode);
  469. #ifdef EXT2_DEBUG
  470. dbgprintf("Ext2FSInode::write_bytes: after write, i_size=%u, i_blocks=%u (%u blocks in list)\n", m_raw_inode.i_size, m_raw_inode.i_blocks, block_list.size());
  471. #endif
  472. // NOTE: Make sure the cached block list is up to date!
  473. m_block_list = move(block_list);
  474. return nwritten;
  475. }
  476. bool Ext2FSInode::traverse_as_directory(Function<bool(const FS::DirectoryEntry&)> callback) const
  477. {
  478. ASSERT(metadata().isDirectory());
  479. #ifdef EXT2_DEBUG
  480. kprintf("Ext2Inode::traverse_as_directory: inode=%u:\n", index());
  481. #endif
  482. auto buffer = read_entire();
  483. ASSERT(buffer);
  484. auto* entry = reinterpret_cast<ext2_dir_entry_2*>(buffer.pointer());
  485. while (entry < buffer.end_pointer()) {
  486. if (entry->inode != 0) {
  487. #ifdef EXT2_DEBUG
  488. 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, String(entry->name, entry->name_len).characters());
  489. #endif
  490. if (!callback({ entry->name, entry->name_len, { fsid(), entry->inode }, entry->file_type }))
  491. break;
  492. }
  493. entry = (ext2_dir_entry_2*)((char*)entry + entry->rec_len);
  494. }
  495. return true;
  496. }
  497. bool Ext2FSInode::add_child(InodeIdentifier child_id, const String& name, byte file_type, int& error)
  498. {
  499. ASSERT(is_directory());
  500. //#ifdef EXT2_DEBUG
  501. dbgprintf("Ext2FS: Adding inode %u with name '%s' to directory %u\n", child_id.index(), name.characters(), index());
  502. //#endif
  503. Vector<FS::DirectoryEntry> entries;
  504. bool name_already_exists = false;
  505. traverse_as_directory([&] (auto& entry) {
  506. if (!strcmp(entry.name, name.characters())) {
  507. name_already_exists = true;
  508. return false;
  509. }
  510. entries.append(entry);
  511. return true;
  512. });
  513. if (name_already_exists) {
  514. kprintf("Ext2FS: Name '%s' already exists in directory inode %u\n", name.characters(), index());
  515. error = -EEXIST;
  516. return false;
  517. }
  518. entries.append({ name.characters(), name.length(), child_id, file_type });
  519. bool success = fs().write_directory_inode(index(), move(entries));
  520. if (success) {
  521. LOCKER(m_lock);
  522. m_lookup_cache.set(name, child_id.index());
  523. }
  524. return success;
  525. }
  526. bool Ext2FSInode::remove_child(const String& name, int& error)
  527. {
  528. #ifdef EXT2_DEBUG
  529. dbgprintf("Ext2FSInode::remove_child(%s) in inode %u\n", name.characters(), index());
  530. #endif
  531. ASSERT(is_directory());
  532. unsigned child_inode_index;
  533. {
  534. LOCKER(m_lock);
  535. auto it = m_lookup_cache.find(name);
  536. if (it == m_lookup_cache.end()) {
  537. error = -ENOENT;
  538. return false;
  539. }
  540. child_inode_index = (*it).value;
  541. }
  542. InodeIdentifier child_id { fsid(), child_inode_index };
  543. //#ifdef EXT2_DEBUG
  544. dbgprintf("Ext2FS: Removing '%s' in directory %u\n", name.characters(), index());
  545. //#endif
  546. Vector<FS::DirectoryEntry> entries;
  547. traverse_as_directory([&] (auto& entry) {
  548. if (entry.inode != child_id)
  549. entries.append(entry);
  550. return true;
  551. });
  552. bool success = fs().write_directory_inode(index(), move(entries));
  553. if (!success) {
  554. // FIXME: Plumb error from write_directory_inode().
  555. error = -EIO;
  556. return false;
  557. }
  558. {
  559. LOCKER(m_lock);
  560. m_lookup_cache.remove(name);
  561. }
  562. auto child_inode = fs().get_inode(child_id);
  563. child_inode->decrement_link_count();
  564. return success;
  565. }
  566. bool Ext2FS::write_directory_inode(unsigned directoryInode, Vector<DirectoryEntry>&& entries)
  567. {
  568. dbgprintf("Ext2FS: New directory inode %u contents to write:\n", directoryInode);
  569. unsigned directorySize = 0;
  570. for (auto& entry : entries) {
  571. //kprintf(" - %08u %s\n", entry.inode.index(), entry.name);
  572. directorySize += EXT2_DIR_REC_LEN(entry.name_length);
  573. }
  574. unsigned blocksNeeded = ceilDiv(directorySize, blockSize());
  575. unsigned occupiedSize = blocksNeeded * blockSize();
  576. dbgprintf("Ext2FS: directory size: %u (occupied: %u)\n", directorySize, occupiedSize);
  577. auto directoryData = ByteBuffer::create_uninitialized(occupiedSize);
  578. BufferStream stream(directoryData);
  579. for (unsigned i = 0; i < entries.size(); ++i) {
  580. auto& entry = entries[i];
  581. unsigned recordLength = EXT2_DIR_REC_LEN(entry.name_length);
  582. if (i == entries.size() - 1)
  583. recordLength += occupiedSize - directorySize;
  584. dbgprintf("* inode: %u", entry.inode.index());
  585. dbgprintf(", name_len: %u", word(entry.name_length));
  586. dbgprintf(", rec_len: %u", word(recordLength));
  587. dbgprintf(", file_type: %u", byte(entry.fileType));
  588. dbgprintf(", name: %s\n", entry.name);
  589. stream << dword(entry.inode.index());
  590. stream << word(recordLength);
  591. stream << byte(entry.name_length);
  592. stream << byte(entry.fileType);
  593. stream << entry.name;
  594. unsigned padding = recordLength - entry.name_length - 8;
  595. //dbgprintf(" *** pad %u bytes\n", padding);
  596. for (unsigned j = 0; j < padding; ++j) {
  597. stream << byte(0);
  598. }
  599. }
  600. stream.fill_to_end(0);
  601. #if 0
  602. kprintf("data to write (%u):\n", directoryData.size());
  603. for (unsigned i = 0; i < directoryData.size(); ++i) {
  604. kprintf("%02x ", directoryData[i]);
  605. if ((i + 1) % 8 == 0)
  606. kprintf(" ");
  607. if ((i + 1) % 16 == 0)
  608. kprintf("\n");
  609. }
  610. kprintf("\n");
  611. #endif
  612. auto directory_inode = get_inode({ fsid(), directoryInode });
  613. ssize_t nwritten = directory_inode->write_bytes(0, directoryData.size(), directoryData.pointer(), nullptr);
  614. return nwritten == directoryData.size();
  615. }
  616. unsigned Ext2FS::inodes_per_block() const
  617. {
  618. return EXT2_INODES_PER_BLOCK(&super_block());
  619. }
  620. unsigned Ext2FS::inodes_per_group() const
  621. {
  622. return EXT2_INODES_PER_GROUP(&super_block());
  623. }
  624. unsigned Ext2FS::inode_size() const
  625. {
  626. return EXT2_INODE_SIZE(&super_block());
  627. }
  628. unsigned Ext2FS::blocks_per_group() const
  629. {
  630. return EXT2_BLOCKS_PER_GROUP(&super_block());
  631. }
  632. void Ext2FS::dump_block_bitmap(unsigned groupIndex) const
  633. {
  634. ASSERT(groupIndex <= m_blockGroupCount);
  635. auto& bgd = group_descriptor(groupIndex);
  636. unsigned blocksInGroup = min(blocks_per_group(), super_block().s_blocks_count);
  637. unsigned blockCount = ceilDiv(blocksInGroup, 8u);
  638. auto bitmapBlocks = readBlocks(bgd.bg_block_bitmap, blockCount);
  639. ASSERT(bitmapBlocks);
  640. kprintf("ext2fs: group[%u] block bitmap (bitmap occupies %u blocks):\n", groupIndex, blockCount);
  641. auto bitmap = Bitmap::wrap(bitmapBlocks.pointer(), blocksInGroup);
  642. for (unsigned i = 0; i < blocksInGroup; ++i) {
  643. kprintf("%c", bitmap.get(i) ? '1' : '0');
  644. }
  645. kprintf("\n");
  646. }
  647. void Ext2FS::dump_inode_bitmap(unsigned groupIndex) const
  648. {
  649. traverse_inode_bitmap(groupIndex, [] (unsigned, const Bitmap& bitmap) {
  650. for (unsigned i = 0; i < bitmap.size(); ++i)
  651. kprintf("%c", bitmap.get(i) ? '1' : '0');
  652. return true;
  653. });
  654. }
  655. template<typename F>
  656. void Ext2FS::traverse_inode_bitmap(unsigned groupIndex, F callback) const
  657. {
  658. ASSERT(groupIndex <= m_blockGroupCount);
  659. auto& bgd = group_descriptor(groupIndex);
  660. unsigned inodesInGroup = min(inodes_per_group(), super_block().s_inodes_count);
  661. unsigned blockCount = ceilDiv(inodesInGroup, 8u);
  662. for (unsigned i = 0; i < blockCount; ++i) {
  663. auto block = readBlock(bgd.bg_inode_bitmap + i);
  664. ASSERT(block);
  665. bool shouldContinue = callback(i * (blockSize() / 8) + 1, Bitmap::wrap(block.pointer(), inodesInGroup));
  666. if (!shouldContinue)
  667. break;
  668. }
  669. }
  670. template<typename F>
  671. void Ext2FS::traverse_block_bitmap(unsigned groupIndex, F callback) const
  672. {
  673. ASSERT(groupIndex <= m_blockGroupCount);
  674. auto& bgd = group_descriptor(groupIndex);
  675. unsigned blocksInGroup = min(blocks_per_group(), super_block().s_blocks_count);
  676. unsigned blockCount = ceilDiv(blocksInGroup, 8u);
  677. for (unsigned i = 0; i < blockCount; ++i) {
  678. auto block = readBlock(bgd.bg_block_bitmap + i);
  679. ASSERT(block);
  680. bool shouldContinue = callback(i * (blockSize() / 8) + 1, Bitmap::wrap(block.pointer(), blocksInGroup));
  681. if (!shouldContinue)
  682. break;
  683. }
  684. }
  685. bool Ext2FS::write_ext2_inode(unsigned inode, const ext2_inode& e2inode)
  686. {
  687. unsigned blockIndex;
  688. unsigned offset;
  689. auto block = read_block_containing_inode(inode, blockIndex, offset);
  690. if (!block)
  691. return false;
  692. memcpy(reinterpret_cast<ext2_inode*>(block.offset_pointer(offset)), &e2inode, inode_size());
  693. writeBlock(blockIndex, block);
  694. return true;
  695. }
  696. Vector<Ext2FS::BlockIndex> Ext2FS::allocate_blocks(unsigned group, unsigned count)
  697. {
  698. dbgprintf("Ext2FS: allocate_blocks(group: %u, count: %u)\n", group, count);
  699. if (count == 0)
  700. return { };
  701. auto& bgd = group_descriptor(group);
  702. if (bgd.bg_free_blocks_count < count) {
  703. kprintf("Ext2FS: allocate_blocks can't allocate out of group %u, wanted %u but only %u available\n", group, count, bgd.bg_free_blocks_count);
  704. return { };
  705. }
  706. // FIXME: Implement a scan that finds consecutive blocks if possible.
  707. Vector<BlockIndex> blocks;
  708. traverse_block_bitmap(group, [&blocks, count] (unsigned first_block_in_bitmap, const Bitmap& bitmap) {
  709. for (unsigned i = 0; i < bitmap.size(); ++i) {
  710. if (!bitmap.get(i)) {
  711. blocks.append(first_block_in_bitmap + i);
  712. if (blocks.size() == count)
  713. return false;
  714. }
  715. }
  716. return true;
  717. });
  718. dbgprintf("Ext2FS: allocate_block found these blocks:\n");
  719. for (auto& bi : blocks) {
  720. dbgprintf(" > %u\n", bi);
  721. }
  722. return blocks;
  723. }
  724. unsigned Ext2FS::allocate_inode(unsigned preferredGroup, unsigned expectedSize)
  725. {
  726. dbgprintf("Ext2FS: allocate_inode(preferredGroup: %u, expectedSize: %u)\n", preferredGroup, expectedSize);
  727. unsigned neededBlocks = ceilDiv(expectedSize, blockSize());
  728. dbgprintf("Ext2FS: minimum needed blocks: %u\n", neededBlocks);
  729. unsigned groupIndex = 0;
  730. auto isSuitableGroup = [this, neededBlocks] (unsigned groupIndex) {
  731. auto& bgd = group_descriptor(groupIndex);
  732. return bgd.bg_free_inodes_count && bgd.bg_free_blocks_count >= neededBlocks;
  733. };
  734. if (preferredGroup && isSuitableGroup(preferredGroup)) {
  735. groupIndex = preferredGroup;
  736. } else {
  737. for (unsigned i = 1; i <= m_blockGroupCount; ++i) {
  738. if (isSuitableGroup(i))
  739. groupIndex = i;
  740. }
  741. }
  742. if (!groupIndex) {
  743. kprintf("Ext2FS: allocate_inode: no suitable group found for new inode with %u blocks needed :(\n", neededBlocks);
  744. return 0;
  745. }
  746. dbgprintf("Ext2FS: allocate_inode: found suitable group [%u] for new inode with %u blocks needed :^)\n", groupIndex, neededBlocks);
  747. unsigned firstFreeInodeInGroup = 0;
  748. traverse_inode_bitmap(groupIndex, [&firstFreeInodeInGroup] (unsigned firstInodeInBitmap, const Bitmap& bitmap) {
  749. for (unsigned i = 0; i < bitmap.size(); ++i) {
  750. if (!bitmap.get(i)) {
  751. firstFreeInodeInGroup = firstInodeInBitmap + i;
  752. return false;
  753. }
  754. }
  755. return true;
  756. });
  757. if (!firstFreeInodeInGroup) {
  758. kprintf("Ext2FS: first_free_inode_in_group returned no inode, despite bgd claiming there are inodes :(\n");
  759. return 0;
  760. }
  761. unsigned inode = firstFreeInodeInGroup;
  762. dbgprintf("Ext2FS: found suitable inode %u\n", inode);
  763. // FIXME: allocate blocks if needed!
  764. return inode;
  765. }
  766. unsigned Ext2FS::group_index_from_inode(unsigned inode) const
  767. {
  768. if (!inode)
  769. return 0;
  770. return (inode - 1) / inodes_per_group() + 1;
  771. }
  772. bool Ext2FS::get_inode_allocation_state(InodeIndex index) const
  773. {
  774. if (index == 0)
  775. return true;
  776. auto& bgd = group_descriptor(group_index_from_inode(index));
  777. unsigned inodes_per_bitmap_block = blockSize() * 8;
  778. unsigned bitmap_block_index = (index - 1) / inodes_per_bitmap_block;
  779. unsigned bit_index = (index - 1) % inodes_per_bitmap_block;
  780. auto block = readBlock(bgd.bg_inode_bitmap + bitmap_block_index);
  781. ASSERT(block);
  782. auto bitmap = Bitmap::wrap(block.pointer(), block.size());
  783. return bitmap.get(bit_index);
  784. }
  785. bool Ext2FS::set_inode_allocation_state(unsigned index, bool newState)
  786. {
  787. auto& bgd = group_descriptor(group_index_from_inode(index));
  788. // Update inode bitmap
  789. unsigned inodes_per_bitmap_block = blockSize() * 8;
  790. unsigned bitmap_block_index = (index - 1) / inodes_per_bitmap_block;
  791. unsigned bit_index = (index - 1) % inodes_per_bitmap_block;
  792. auto block = readBlock(bgd.bg_inode_bitmap + bitmap_block_index);
  793. ASSERT(block);
  794. auto bitmap = Bitmap::wrap(block.pointer(), block.size());
  795. bool currentState = bitmap.get(bit_index);
  796. dbgprintf("Ext2FS: set_inode_allocation_state(%u) %u -> %u\n", index, currentState, newState);
  797. if (currentState == newState)
  798. return true;
  799. bitmap.set(bit_index, newState);
  800. writeBlock(bgd.bg_inode_bitmap + bitmap_block_index, block);
  801. // Update superblock
  802. auto& sb = *reinterpret_cast<ext2_super_block*>(m_cached_super_block.pointer());
  803. dbgprintf("Ext2FS: superblock free inode count %u -> %u\n", sb.s_free_inodes_count, sb.s_free_inodes_count - 1);
  804. if (newState)
  805. --sb.s_free_inodes_count;
  806. else
  807. ++sb.s_free_inodes_count;
  808. write_super_block(sb);
  809. // Update BGD
  810. auto& mutableBGD = const_cast<ext2_group_desc&>(bgd);
  811. if (newState)
  812. --mutableBGD.bg_free_inodes_count;
  813. else
  814. ++mutableBGD.bg_free_inodes_count;
  815. dbgprintf("Ext2FS: group free inode count %u -> %u\n", bgd.bg_free_inodes_count, bgd.bg_free_inodes_count - 1);
  816. flush_block_group_descriptor_table();
  817. return true;
  818. }
  819. bool Ext2FS::set_block_allocation_state(GroupIndex group, BlockIndex bi, bool newState)
  820. {
  821. dbgprintf("Ext2FS: set_block_allocation_state(group=%u, block=%u, state=%u)\n", group, bi, newState);
  822. auto& bgd = group_descriptor(group);
  823. // Update block bitmap
  824. unsigned blocksPerBitmapBlock = blockSize() * 8;
  825. unsigned bitmapBlockIndex = (bi - 1) / blocksPerBitmapBlock;
  826. unsigned bitIndex = (bi - 1) % blocksPerBitmapBlock;
  827. auto block = readBlock(bgd.bg_block_bitmap + bitmapBlockIndex);
  828. ASSERT(block);
  829. auto bitmap = Bitmap::wrap(block.pointer(), blocksPerBitmapBlock);
  830. bool currentState = bitmap.get(bitIndex);
  831. dbgprintf("Ext2FS: block %u state: %u -> %u\n", bi, currentState, newState);
  832. if (currentState == newState)
  833. return true;
  834. bitmap.set(bitIndex, newState);
  835. writeBlock(bgd.bg_block_bitmap + bitmapBlockIndex, block);
  836. // Update superblock
  837. auto& sb = *reinterpret_cast<ext2_super_block*>(m_cached_super_block.pointer());
  838. dbgprintf("Ext2FS: superblock free block count %u -> %u\n", sb.s_free_blocks_count, sb.s_free_blocks_count - 1);
  839. if (newState)
  840. --sb.s_free_blocks_count;
  841. else
  842. ++sb.s_free_blocks_count;
  843. write_super_block(sb);
  844. // Update BGD
  845. auto& mutableBGD = const_cast<ext2_group_desc&>(bgd);
  846. if (newState)
  847. --mutableBGD.bg_free_blocks_count;
  848. else
  849. ++mutableBGD.bg_free_blocks_count;
  850. dbgprintf("Ext2FS: group free block count %u -> %u\n", bgd.bg_free_blocks_count, bgd.bg_free_blocks_count - 1);
  851. flush_block_group_descriptor_table();
  852. return true;
  853. }
  854. RetainPtr<Inode> Ext2FS::create_directory(InodeIdentifier parent_id, const String& name, mode_t mode, int& error)
  855. {
  856. ASSERT(parent_id.fsid() == fsid());
  857. // Fix up the mode to definitely be a directory.
  858. // FIXME: This is a bit on the hackish side.
  859. mode &= ~0170000;
  860. mode |= 0040000;
  861. // NOTE: When creating a new directory, make the size 1 block.
  862. // There's probably a better strategy here, but this works for now.
  863. auto inode = create_inode(parent_id, name, mode, blockSize(), error);
  864. if (!inode)
  865. return nullptr;
  866. dbgprintf("Ext2FS: create_directory: created new directory named '%s' with inode %u\n", name.characters(), inode->identifier().index());
  867. Vector<DirectoryEntry> entries;
  868. entries.append({ ".", inode->identifier(), EXT2_FT_DIR });
  869. entries.append({ "..", parent_id, EXT2_FT_DIR });
  870. bool success = write_directory_inode(inode->identifier().index(), move(entries));
  871. ASSERT(success);
  872. auto parent_inode = get_inode(parent_id);
  873. error = parent_inode->increment_link_count();
  874. if (error < 0)
  875. return nullptr;
  876. auto& bgd = const_cast<ext2_group_desc&>(group_descriptor(group_index_from_inode(inode->identifier().index())));
  877. ++bgd.bg_used_dirs_count;
  878. dbgprintf("Ext2FS: incremented bg_used_dirs_count %u -> %u\n", bgd.bg_used_dirs_count - 1, bgd.bg_used_dirs_count);
  879. flush_block_group_descriptor_table();
  880. error = 0;
  881. return inode;
  882. }
  883. RetainPtr<Inode> Ext2FS::create_inode(InodeIdentifier parent_id, const String& name, mode_t mode, unsigned size, int& error)
  884. {
  885. ASSERT(parent_id.fsid() == fsid());
  886. auto parent_inode = get_inode(parent_id);
  887. dbgprintf("Ext2FS: Adding inode '%s' (mode %u) to parent directory %u:\n", name.characters(), mode, parent_inode->identifier().index());
  888. // NOTE: This doesn't commit the inode allocation just yet!
  889. auto inode_id = allocate_inode(0, size);
  890. if (!inode_id) {
  891. kprintf("Ext2FS: create_inode: allocate_inode failed\n");
  892. error = -ENOSPC;
  893. return { };
  894. }
  895. auto needed_blocks = ceilDiv(size, blockSize());
  896. auto blocks = allocate_blocks(group_index_from_inode(inode_id), needed_blocks);
  897. if (blocks.size() != needed_blocks) {
  898. kprintf("Ext2FS: create_inode: allocate_blocks failed\n");
  899. error = -ENOSPC;
  900. return { };
  901. }
  902. byte fileType = 0;
  903. if (isRegularFile(mode))
  904. fileType = EXT2_FT_REG_FILE;
  905. else if (isDirectory(mode))
  906. fileType = EXT2_FT_DIR;
  907. else if (isCharacterDevice(mode))
  908. fileType = EXT2_FT_CHRDEV;
  909. else if (isBlockDevice(mode))
  910. fileType = EXT2_FT_BLKDEV;
  911. else if (isFIFO(mode))
  912. fileType = EXT2_FT_FIFO;
  913. else if (isSocket(mode))
  914. fileType = EXT2_FT_SOCK;
  915. else if (isSymbolicLink(mode))
  916. fileType = EXT2_FT_SYMLINK;
  917. // Try adding it to the directory first, in case the name is already in use.
  918. bool success = parent_inode->add_child({ fsid(), inode_id }, name, fileType, error);
  919. if (!success)
  920. return { };
  921. // Looks like we're good, time to update the inode bitmap and group+global inode counters.
  922. success = set_inode_allocation_state(inode_id, true);
  923. ASSERT(success);
  924. for (auto bi : blocks) {
  925. success = set_block_allocation_state(group_index_from_inode(inode_id), bi, true);
  926. ASSERT(success);
  927. }
  928. unsigned initialLinksCount;
  929. if (isDirectory(mode))
  930. initialLinksCount = 2; // (parent directory + "." entry in self)
  931. else
  932. initialLinksCount = 1;
  933. auto timestamp = RTC::now();
  934. auto e2inode = make<ext2_inode>();
  935. memset(e2inode.ptr(), 0, sizeof(ext2_inode));
  936. e2inode->i_mode = mode;
  937. e2inode->i_uid = 0;
  938. e2inode->i_size = size;
  939. e2inode->i_atime = timestamp;
  940. e2inode->i_ctime = timestamp;
  941. e2inode->i_mtime = timestamp;
  942. e2inode->i_dtime = 0;
  943. e2inode->i_gid = 0;
  944. e2inode->i_links_count = initialLinksCount;
  945. success = write_block_list_for_inode(inode_id, *e2inode, blocks);
  946. ASSERT(success);
  947. dbgprintf("Ext2FS: writing initial metadata for inode %u\n", inode_id);
  948. e2inode->i_flags = 0;
  949. success = write_ext2_inode(inode_id, *e2inode);
  950. ASSERT(success);
  951. {
  952. // We might have cached the fact that this inode didn't exist. Wipe the slate.
  953. LOCKER(m_inode_cache_lock);
  954. m_inode_cache.remove(inode_id);
  955. }
  956. return get_inode({ fsid(), inode_id });
  957. }
  958. RetainPtr<Inode> Ext2FSInode::parent() const
  959. {
  960. if (m_parent_id.is_valid())
  961. return fs().get_inode(m_parent_id);
  962. unsigned group_index = fs().group_index_from_inode(index());
  963. unsigned first_inode_in_group = fs().inodes_per_group() * (group_index - 1);
  964. Vector<RetainPtr<Ext2FSInode>> directories_in_group;
  965. for (unsigned i = 0; i < fs().inodes_per_group(); ++i) {
  966. auto group_member = fs().get_inode({ fsid(), first_inode_in_group + i });
  967. if (!group_member)
  968. continue;
  969. if (group_member->is_directory())
  970. directories_in_group.append(move(group_member));
  971. }
  972. for (auto& directory : directories_in_group) {
  973. if (!directory->reverse_lookup(identifier()).is_null()) {
  974. m_parent_id = directory->identifier();
  975. break;
  976. }
  977. }
  978. ASSERT(m_parent_id.is_valid());
  979. return fs().get_inode(m_parent_id);
  980. }
  981. void Ext2FSInode::populate_lookup_cache() const
  982. {
  983. {
  984. LOCKER(m_lock);
  985. if (!m_lookup_cache.is_empty())
  986. return;
  987. }
  988. HashMap<String, unsigned> children;
  989. traverse_as_directory([&children] (auto& entry) {
  990. children.set(String(entry.name, entry.name_length), entry.inode.index());
  991. return true;
  992. });
  993. LOCKER(m_lock);
  994. if (!m_lookup_cache.is_empty())
  995. return;
  996. m_lookup_cache = move(children);
  997. }
  998. InodeIdentifier Ext2FSInode::lookup(const String& name)
  999. {
  1000. ASSERT(is_directory());
  1001. populate_lookup_cache();
  1002. LOCKER(m_lock);
  1003. auto it = m_lookup_cache.find(name);
  1004. if (it != m_lookup_cache.end())
  1005. return { fsid(), (*it).value };
  1006. return { };
  1007. }
  1008. String Ext2FSInode::reverse_lookup(InodeIdentifier child_id)
  1009. {
  1010. ASSERT(is_directory());
  1011. ASSERT(child_id.fsid() == fsid());
  1012. populate_lookup_cache();
  1013. LOCKER(m_lock);
  1014. for (auto it : m_lookup_cache) {
  1015. if (it.value == child_id.index())
  1016. return it.key;
  1017. }
  1018. return { };
  1019. }
  1020. void Ext2FSInode::one_retain_left()
  1021. {
  1022. // FIXME: I would like to not live forever, but uncached Ext2FS is fucking painful right now.
  1023. }
  1024. int Ext2FSInode::set_atime(time_t t)
  1025. {
  1026. if (fs().is_readonly())
  1027. return -EROFS;
  1028. m_raw_inode.i_atime = t;
  1029. set_metadata_dirty(true);
  1030. return 0;
  1031. }
  1032. int Ext2FSInode::set_ctime(time_t t)
  1033. {
  1034. if (fs().is_readonly())
  1035. return -EROFS;
  1036. m_raw_inode.i_ctime = t;
  1037. set_metadata_dirty(true);
  1038. return 0;
  1039. }
  1040. int Ext2FSInode::set_mtime(time_t t)
  1041. {
  1042. if (fs().is_readonly())
  1043. return -EROFS;
  1044. m_raw_inode.i_mtime = t;
  1045. set_metadata_dirty(true);
  1046. return 0;
  1047. }
  1048. int Ext2FSInode::increment_link_count()
  1049. {
  1050. if (fs().is_readonly())
  1051. return -EROFS;
  1052. ++m_raw_inode.i_links_count;
  1053. set_metadata_dirty(true);
  1054. return 0;
  1055. }
  1056. int Ext2FSInode::decrement_link_count()
  1057. {
  1058. if (fs().is_readonly())
  1059. return -EROFS;
  1060. ASSERT(m_raw_inode.i_links_count);
  1061. --m_raw_inode.i_links_count;
  1062. if (m_raw_inode.i_links_count == 0)
  1063. fs().uncache_inode(index());
  1064. set_metadata_dirty(true);
  1065. return 0;
  1066. }
  1067. void Ext2FS::uncache_inode(InodeIndex index)
  1068. {
  1069. LOCKER(m_inode_cache_lock);
  1070. m_inode_cache.remove(index);
  1071. }
  1072. size_t Ext2FSInode::directory_entry_count() const
  1073. {
  1074. ASSERT(is_directory());
  1075. populate_lookup_cache();
  1076. LOCKER(m_lock);
  1077. return m_lookup_cache.size();
  1078. }
  1079. bool Ext2FSInode::chmod(mode_t mode, int& error)
  1080. {
  1081. error = 0;
  1082. if (m_raw_inode.i_mode == mode)
  1083. return true;
  1084. m_raw_inode.i_mode = mode;
  1085. set_metadata_dirty(true);
  1086. return true;
  1087. }