Ext2FileSystem.cpp 45 KB

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