Ext2FileSystem.cpp 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400
  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)) {
  361. unsigned dev = m_raw_inode.i_block[0];
  362. metadata.major_device = (dev & 0xfff00) >> 8;
  363. metadata.minor_device = (dev & 0xff) | ((dev >> 12) & 0xfff00);
  364. }
  365. if (::is_block_device(m_raw_inode.i_mode)) {
  366. unsigned dev = m_raw_inode.i_block[1];
  367. metadata.major_device = (dev & 0xfff00) >> 8;
  368. metadata.minor_device = (dev & 0xff) | ((dev >> 12) & 0xfff00);
  369. }
  370. return metadata;
  371. }
  372. void Ext2FSInode::flush_metadata()
  373. {
  374. LOCKER(m_lock);
  375. #ifdef EXT2_DEBUG
  376. dbgprintf("Ext2FSInode: flush_metadata for inode %u\n", index());
  377. #endif
  378. fs().write_ext2_inode(index(), m_raw_inode);
  379. if (is_directory()) {
  380. // Unless we're about to go away permanently, invalidate the lookup cache.
  381. if (m_raw_inode.i_links_count != 0) {
  382. // FIXME: This invalidation is way too hardcore. It's sad to throw away the whole cache.
  383. m_lookup_cache.clear();
  384. }
  385. }
  386. set_metadata_dirty(false);
  387. }
  388. RefPtr<Inode> Ext2FS::get_inode(InodeIdentifier inode) const
  389. {
  390. LOCKER(m_lock);
  391. ASSERT(inode.fsid() == fsid());
  392. {
  393. auto it = m_inode_cache.find(inode.index());
  394. if (it != m_inode_cache.end())
  395. return (*it).value;
  396. }
  397. if (!get_inode_allocation_state(inode.index())) {
  398. m_inode_cache.set(inode.index(), nullptr);
  399. return nullptr;
  400. }
  401. unsigned block_index;
  402. unsigned offset;
  403. auto block = read_block_containing_inode(inode.index(), block_index, offset);
  404. if (!block)
  405. return {};
  406. auto it = m_inode_cache.find(inode.index());
  407. if (it != m_inode_cache.end())
  408. return (*it).value;
  409. auto new_inode = adopt(*new Ext2FSInode(const_cast<Ext2FS&>(*this), inode.index()));
  410. memcpy(&new_inode->m_raw_inode, reinterpret_cast<ext2_inode*>(block.offset_pointer(offset)), sizeof(ext2_inode));
  411. m_inode_cache.set(inode.index(), new_inode);
  412. return new_inode;
  413. }
  414. ssize_t Ext2FSInode::read_bytes(off_t offset, ssize_t count, u8* buffer, FileDescription*) const
  415. {
  416. Locker inode_locker(m_lock);
  417. ASSERT(offset >= 0);
  418. if (m_raw_inode.i_size == 0)
  419. return 0;
  420. // Symbolic links shorter than 60 characters are store inline inside the i_block array.
  421. // This avoids wasting an entire block on short links. (Most links are short.)
  422. if (is_symlink() && size() < max_inline_symlink_length) {
  423. ssize_t nread = min((off_t)size() - offset, static_cast<off_t>(count));
  424. memcpy(buffer, ((const u8*)m_raw_inode.i_block) + offset, (size_t)nread);
  425. return nread;
  426. }
  427. Locker fs_locker(fs().m_lock);
  428. if (m_block_list.is_empty()) {
  429. auto block_list = fs().block_list_for_inode(m_raw_inode);
  430. if (m_block_list.size() != block_list.size())
  431. m_block_list = move(block_list);
  432. }
  433. if (m_block_list.is_empty()) {
  434. kprintf("ext2fs: read_bytes: empty block list for inode %u\n", index());
  435. return -EIO;
  436. }
  437. const int block_size = fs().block_size();
  438. int first_block_logical_index = offset / block_size;
  439. int last_block_logical_index = (offset + count) / block_size;
  440. if (last_block_logical_index >= m_block_list.size())
  441. last_block_logical_index = m_block_list.size() - 1;
  442. int offset_into_first_block = offset % block_size;
  443. ssize_t nread = 0;
  444. int remaining_count = min((off_t)count, (off_t)size() - offset);
  445. u8* out = buffer;
  446. #ifdef EXT2_DEBUG
  447. kprintf("Ext2FS: Reading up to %u bytes %d bytes into inode %u:%u to %p\n", count, offset, identifier().fsid(), identifier().index(), buffer);
  448. //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);
  449. #endif
  450. for (int bi = first_block_logical_index; remaining_count && bi <= last_block_logical_index; ++bi) {
  451. auto block = fs().read_block(m_block_list[bi]);
  452. if (!block) {
  453. kprintf("ext2fs: read_bytes: read_block(%u) failed (lbi: %u)\n", m_block_list[bi], bi);
  454. return -EIO;
  455. }
  456. int offset_into_block = (bi == first_block_logical_index) ? offset_into_first_block : 0;
  457. int num_bytes_to_copy = min(block_size - offset_into_block, remaining_count);
  458. memcpy(out, block.pointer() + offset_into_block, num_bytes_to_copy);
  459. remaining_count -= num_bytes_to_copy;
  460. nread += num_bytes_to_copy;
  461. out += num_bytes_to_copy;
  462. }
  463. return nread;
  464. }
  465. bool Ext2FSInode::resize(u64 new_size)
  466. {
  467. u64 block_size = fs().block_size();
  468. u64 old_size = size();
  469. int blocks_needed_before = ceil_div(old_size, block_size);
  470. int blocks_needed_after = ceil_div(new_size, block_size);
  471. #ifdef EXT2_DEBUG
  472. dbgprintf("Ext2FSInode::resize(): blocks needed before (size was %Q): %d\n", old_size, blocks_needed_before);
  473. dbgprintf("Ext2FSInode::resize(): blocks needed after (size is %Q): %d\n", new_size, blocks_needed_after);
  474. #endif
  475. auto block_list = fs().block_list_for_inode(m_raw_inode);
  476. if (blocks_needed_after > blocks_needed_before) {
  477. auto new_blocks = fs().allocate_blocks(fs().group_index_from_inode(index()), blocks_needed_after - blocks_needed_before);
  478. for (auto new_block_index : new_blocks)
  479. fs().set_block_allocation_state(new_block_index, true);
  480. block_list.append(move(new_blocks));
  481. } else if (blocks_needed_after < blocks_needed_before) {
  482. #ifdef EXT2_DEBUG
  483. dbgprintf("Ext2FSInode::resize(): Shrinking. Old block list is %d entries:\n", block_list.size());
  484. for (auto block_index : block_list) {
  485. dbgprintf(" # %u\n", block_index);
  486. }
  487. #endif
  488. while (block_list.size() != blocks_needed_after) {
  489. auto block_index = block_list.take_last();
  490. fs().set_block_allocation_state(block_index, false);
  491. }
  492. }
  493. bool success = fs().write_block_list_for_inode(index(), m_raw_inode, block_list);
  494. if (!success)
  495. return false;
  496. m_raw_inode.i_size = new_size;
  497. set_metadata_dirty(true);
  498. m_block_list = move(block_list);
  499. return true;
  500. }
  501. ssize_t Ext2FSInode::write_bytes(off_t offset, ssize_t count, const u8* data, FileDescription*)
  502. {
  503. ASSERT(offset >= 0);
  504. ASSERT(count >= 0);
  505. Locker inode_locker(m_lock);
  506. Locker fs_locker(fs().m_lock);
  507. if (is_symlink()) {
  508. if ((offset + count) < max_inline_symlink_length) {
  509. #ifdef EXT2_DEBUG
  510. dbgprintf("Ext2FSInode: write_bytes poking into i_block array for inline symlink '%s' (%u bytes)\n", String((const char*)data, count).characters(), count);
  511. #endif
  512. memcpy(((u8*)m_raw_inode.i_block) + offset, data, (size_t)count);
  513. if ((offset + count) > (off_t)m_raw_inode.i_size)
  514. m_raw_inode.i_size = offset + count;
  515. set_metadata_dirty(true);
  516. return count;
  517. }
  518. }
  519. const ssize_t block_size = fs().block_size();
  520. u64 old_size = size();
  521. u64 new_size = max(static_cast<u64>(offset) + count, (u64)size());
  522. if (!resize(new_size))
  523. return -EIO;
  524. int first_block_logical_index = offset / block_size;
  525. int last_block_logical_index = (offset + count) / block_size;
  526. if (last_block_logical_index >= m_block_list.size())
  527. last_block_logical_index = m_block_list.size() - 1;
  528. int offset_into_first_block = offset % block_size;
  529. int last_logical_block_index_in_file = new_size / block_size;
  530. ssize_t nwritten = 0;
  531. int remaining_count = min((off_t)count, (off_t)new_size - offset);
  532. const u8* in = data;
  533. #ifdef EXT2_DEBUG
  534. dbgprintf("Ext2FSInode::write_bytes: Writing %u bytes %d bytes into inode %u:%u from %p\n", count, offset, fsid(), index(), data);
  535. #endif
  536. auto buffer_block = ByteBuffer::create_uninitialized(block_size);
  537. for (int bi = first_block_logical_index; remaining_count && bi <= last_block_logical_index; ++bi) {
  538. int offset_into_block = (bi == first_block_logical_index) ? offset_into_first_block : 0;
  539. int num_bytes_to_copy = min(block_size - offset_into_block, remaining_count);
  540. ByteBuffer block;
  541. if (offset_into_block != 0 || num_bytes_to_copy != block_size) {
  542. block = fs().read_block(m_block_list[bi]);
  543. if (!block) {
  544. kprintf("Ext2FSInode::write_bytes: read_block(%u) failed (lbi: %u)\n", m_block_list[bi], bi);
  545. return -EIO;
  546. }
  547. } else
  548. block = buffer_block;
  549. memcpy(block.pointer() + offset_into_block, in, num_bytes_to_copy);
  550. if (bi == last_logical_block_index_in_file && num_bytes_to_copy < block_size) {
  551. int padding_start = new_size % block_size;
  552. int padding_bytes = block_size - padding_start;
  553. #ifdef EXT2_DEBUG
  554. 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);
  555. #endif
  556. memset(block.pointer() + padding_start, 0, padding_bytes);
  557. }
  558. #ifdef EXT2_DEBUG
  559. dbgprintf("Ext2FSInode::write_bytes: writing block %u (offset_into_block: %u)\n", m_block_list[bi], offset_into_block);
  560. #endif
  561. bool success = fs().write_block(m_block_list[bi], block);
  562. if (!success) {
  563. kprintf("Ext2FSInode::write_bytes: write_block(%u) failed (lbi: %u)\n", m_block_list[bi], bi);
  564. ASSERT_NOT_REACHED();
  565. return -EIO;
  566. }
  567. remaining_count -= num_bytes_to_copy;
  568. nwritten += num_bytes_to_copy;
  569. in += num_bytes_to_copy;
  570. }
  571. #ifdef EXT2_DEBUG
  572. 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());
  573. #endif
  574. if (old_size != new_size)
  575. inode_size_changed(old_size, new_size);
  576. inode_contents_changed(offset, count, data);
  577. return nwritten;
  578. }
  579. bool Ext2FSInode::traverse_as_directory(Function<bool(const FS::DirectoryEntry&)> callback) const
  580. {
  581. LOCKER(m_lock);
  582. ASSERT(metadata().is_directory());
  583. #ifdef EXT2_DEBUG
  584. kprintf("Ext2Inode::traverse_as_directory: inode=%u:\n", index());
  585. #endif
  586. auto buffer = read_entire();
  587. ASSERT(buffer);
  588. auto* entry = reinterpret_cast<ext2_dir_entry_2*>(buffer.pointer());
  589. while (entry < buffer.end_pointer()) {
  590. if (entry->inode != 0) {
  591. #ifdef EXT2_DEBUG
  592. 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());
  593. #endif
  594. if (!callback({ entry->name, entry->name_len, { fsid(), entry->inode }, entry->file_type }))
  595. break;
  596. }
  597. entry = (ext2_dir_entry_2*)((char*)entry + entry->rec_len);
  598. }
  599. return true;
  600. }
  601. bool Ext2FSInode::write_directory(const Vector<FS::DirectoryEntry>& entries)
  602. {
  603. LOCKER(m_lock);
  604. #ifdef EXT2_DEBUG
  605. dbgprintf("Ext2FS: New directory inode %u contents to write:\n", index());
  606. #endif
  607. int directory_size = 0;
  608. for (auto& entry : entries) {
  609. //kprintf(" - %08u %s\n", entry.inode.index(), entry.name);
  610. directory_size += EXT2_DIR_REC_LEN(entry.name_length);
  611. }
  612. auto block_size = fs().block_size();
  613. int blocks_needed = ceil_div(directory_size, block_size);
  614. int occupied_size = blocks_needed * block_size;
  615. #ifdef EXT2_DEBUG
  616. dbgprintf("Ext2FS: directory size: %u (occupied: %u)\n", directory_size, occupied_size);
  617. #endif
  618. auto directory_data = ByteBuffer::create_uninitialized(occupied_size);
  619. BufferStream stream(directory_data);
  620. for (int i = 0; i < entries.size(); ++i) {
  621. auto& entry = entries[i];
  622. int record_length = EXT2_DIR_REC_LEN(entry.name_length);
  623. if (i == entries.size() - 1)
  624. record_length += occupied_size - directory_size;
  625. #ifdef EXT2_DEBUG
  626. dbgprintf("* inode: %u", entry.inode.index());
  627. dbgprintf(", name_len: %u", u16(entry.name_length));
  628. dbgprintf(", rec_len: %u", u16(record_length));
  629. dbgprintf(", file_type: %u", u8(entry.file_type));
  630. dbgprintf(", name: %s\n", entry.name);
  631. #endif
  632. stream << u32(entry.inode.index());
  633. stream << u16(record_length);
  634. stream << u8(entry.name_length);
  635. stream << u8(entry.file_type);
  636. stream << entry.name;
  637. int padding = record_length - entry.name_length - 8;
  638. for (int j = 0; j < padding; ++j)
  639. stream << u8(0);
  640. }
  641. stream.fill_to_end(0);
  642. ssize_t nwritten = write_bytes(0, directory_data.size(), directory_data.pointer(), nullptr);
  643. return nwritten == directory_data.size();
  644. }
  645. KResult Ext2FSInode::add_child(InodeIdentifier child_id, const StringView& name, mode_t mode)
  646. {
  647. LOCKER(m_lock);
  648. ASSERT(is_directory());
  649. #ifdef EXT2_DEBUG
  650. dbg() << "Ext2FSInode::add_child(): Adding inode " << child_id.index() << " with name '" << name << " and mode " << mode << " to directory " << index();
  651. #endif
  652. Vector<FS::DirectoryEntry> entries;
  653. bool name_already_exists = false;
  654. traverse_as_directory([&](auto& entry) {
  655. if (name == entry.name) {
  656. name_already_exists = true;
  657. return false;
  658. }
  659. entries.append(entry);
  660. return true;
  661. });
  662. if (name_already_exists) {
  663. dbg() << "Ext2FSInode::add_child(): Name '" << name << "' already exists in inode " << index();
  664. return KResult(-EEXIST);
  665. }
  666. auto child_inode = fs().get_inode(child_id);
  667. if (child_inode)
  668. child_inode->increment_link_count();
  669. entries.append({ name.characters_without_null_termination(), name.length(), child_id, to_ext2_file_type(mode) });
  670. bool success = write_directory(entries);
  671. if (success)
  672. m_lookup_cache.set(name, child_id.index());
  673. return KSuccess;
  674. }
  675. KResult Ext2FSInode::remove_child(const StringView& name)
  676. {
  677. LOCKER(m_lock);
  678. #ifdef EXT2_DEBUG
  679. dbg() << "Ext2FSInode::remove_child(" << name << ") in inode " << index();
  680. #endif
  681. ASSERT(is_directory());
  682. unsigned child_inode_index;
  683. auto it = m_lookup_cache.find(name);
  684. if (it == m_lookup_cache.end())
  685. return KResult(-ENOENT);
  686. child_inode_index = (*it).value;
  687. InodeIdentifier child_id { fsid(), child_inode_index };
  688. #ifdef EXT2_DEBUG
  689. dbg() << "Ext2FSInode::remove_child(): Removing '" << name << "' in directory " << index();
  690. #endif
  691. Vector<FS::DirectoryEntry> entries;
  692. traverse_as_directory([&](auto& entry) {
  693. if (name != entry.name)
  694. entries.append(entry);
  695. return true;
  696. });
  697. bool success = write_directory(entries);
  698. if (!success) {
  699. // FIXME: Plumb error from write_directory().
  700. return KResult(-EIO);
  701. }
  702. m_lookup_cache.remove(name);
  703. auto child_inode = fs().get_inode(child_id);
  704. child_inode->decrement_link_count();
  705. return KSuccess;
  706. }
  707. unsigned Ext2FS::inodes_per_block() const
  708. {
  709. return EXT2_INODES_PER_BLOCK(&super_block());
  710. }
  711. unsigned Ext2FS::inodes_per_group() const
  712. {
  713. return EXT2_INODES_PER_GROUP(&super_block());
  714. }
  715. unsigned Ext2FS::inode_size() const
  716. {
  717. return EXT2_INODE_SIZE(&super_block());
  718. }
  719. unsigned Ext2FS::blocks_per_group() const
  720. {
  721. return EXT2_BLOCKS_PER_GROUP(&super_block());
  722. }
  723. bool Ext2FS::write_ext2_inode(unsigned inode, const ext2_inode& e2inode)
  724. {
  725. LOCKER(m_lock);
  726. unsigned block_index;
  727. unsigned offset;
  728. auto block = read_block_containing_inode(inode, block_index, offset);
  729. if (!block)
  730. return false;
  731. memcpy(reinterpret_cast<ext2_inode*>(block.offset_pointer(offset)), &e2inode, inode_size());
  732. bool success = write_block(block_index, block);
  733. ASSERT(success);
  734. return success;
  735. }
  736. Vector<Ext2FS::BlockIndex> Ext2FS::allocate_blocks(GroupIndex group_index, int count)
  737. {
  738. LOCKER(m_lock);
  739. #ifdef EXT2_DEBUG
  740. dbgprintf("Ext2FS: allocate_blocks(group: %u, count: %u)\n", group_index, count);
  741. #endif
  742. if (count == 0)
  743. return {};
  744. auto& bgd = group_descriptor(group_index);
  745. if (bgd.bg_free_blocks_count < count) {
  746. 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);
  747. return {};
  748. }
  749. // FIXME: Implement a scan that finds consecutive blocks if possible.
  750. Vector<BlockIndex> blocks;
  751. auto bitmap_block = read_block(bgd.bg_block_bitmap);
  752. int blocks_in_group = min(blocks_per_group(), super_block().s_blocks_count);
  753. auto block_bitmap = Bitmap::wrap(bitmap_block.pointer(), blocks_in_group);
  754. BlockIndex first_block_in_group = (group_index - 1) * blocks_per_group() + 1;
  755. for (int i = 0; i < block_bitmap.size(); ++i) {
  756. if (!block_bitmap.get(i)) {
  757. blocks.append(first_block_in_group + i);
  758. if (blocks.size() == count)
  759. break;
  760. }
  761. }
  762. ASSERT(blocks.size() == count);
  763. dbgprintf("Ext2FS: allocate_block found these blocks:\n");
  764. for (auto& bi : blocks) {
  765. dbgprintf(" > %u\n", bi);
  766. }
  767. return blocks;
  768. }
  769. unsigned Ext2FS::allocate_inode(GroupIndex preferred_group, off_t expected_size)
  770. {
  771. LOCKER(m_lock);
  772. #ifdef EXT2_DEBUG
  773. dbgprintf("Ext2FS: allocate_inode(preferredGroup: %u, expected_size: %u)\n", preferred_group, expected_size);
  774. #endif
  775. unsigned needed_blocks = ceil_div(expected_size, block_size());
  776. #ifdef EXT2_DEBUG
  777. dbgprintf("Ext2FS: minimum needed blocks: %u\n", needed_blocks);
  778. #endif
  779. unsigned group_index = 0;
  780. auto is_suitable_group = [this, needed_blocks](GroupIndex group_index) {
  781. auto& bgd = group_descriptor(group_index);
  782. return bgd.bg_free_inodes_count && bgd.bg_free_blocks_count >= needed_blocks;
  783. };
  784. if (preferred_group && is_suitable_group(preferred_group)) {
  785. group_index = preferred_group;
  786. } else {
  787. for (unsigned i = 1; i <= m_block_group_count; ++i) {
  788. if (is_suitable_group(i))
  789. group_index = i;
  790. }
  791. }
  792. if (!group_index) {
  793. kprintf("Ext2FS: allocate_inode: no suitable group found for new inode with %u blocks needed :(\n", needed_blocks);
  794. return 0;
  795. }
  796. #ifdef EXT2_DEBUG
  797. dbgprintf("Ext2FS: allocate_inode: found suitable group [%u] for new inode with %u blocks needed :^)\n", group_index, needed_blocks);
  798. #endif
  799. auto& bgd = group_descriptor(group_index);
  800. unsigned inodes_in_group = min(inodes_per_group(), super_block().s_inodes_count);
  801. unsigned first_free_inode_in_group = 0;
  802. unsigned first_inode_in_group = (group_index - 1) * inodes_per_group() + 1;
  803. auto bitmap_block = read_block(bgd.bg_inode_bitmap);
  804. auto inode_bitmap = Bitmap::wrap(bitmap_block.data(), inodes_in_group);
  805. for (int i = 0; i < inode_bitmap.size(); ++i) {
  806. if (inode_bitmap.get(i))
  807. continue;
  808. first_free_inode_in_group = first_inode_in_group + i;
  809. break;
  810. }
  811. if (!first_free_inode_in_group) {
  812. kprintf("Ext2FS: first_free_inode_in_group returned no inode, despite bgd claiming there are inodes :(\n");
  813. return 0;
  814. }
  815. unsigned inode = first_free_inode_in_group;
  816. #ifdef EXT2_DEBUG
  817. dbgprintf("Ext2FS: found suitable inode %u\n", inode);
  818. #endif
  819. ASSERT(get_inode_allocation_state(inode) == false);
  820. // FIXME: allocate blocks if needed!
  821. return inode;
  822. }
  823. Ext2FS::GroupIndex Ext2FS::group_index_from_block_index(BlockIndex block_index) const
  824. {
  825. if (!block_index)
  826. return 0;
  827. return (block_index - 1) / blocks_per_group() + 1;
  828. }
  829. unsigned Ext2FS::group_index_from_inode(unsigned inode) const
  830. {
  831. if (!inode)
  832. return 0;
  833. return (inode - 1) / inodes_per_group() + 1;
  834. }
  835. bool Ext2FS::get_inode_allocation_state(InodeIndex index) const
  836. {
  837. LOCKER(m_lock);
  838. if (index == 0)
  839. return true;
  840. unsigned group_index = group_index_from_inode(index);
  841. auto& bgd = group_descriptor(group_index);
  842. unsigned index_in_group = index - ((group_index - 1) * inodes_per_group());
  843. unsigned bit_index = (index_in_group - 1) % inodes_per_group();
  844. auto block = read_block(bgd.bg_inode_bitmap);
  845. ASSERT(block);
  846. auto bitmap = Bitmap::wrap(block.pointer(), inodes_per_group());
  847. return bitmap.get(bit_index);
  848. }
  849. bool Ext2FS::set_inode_allocation_state(InodeIndex inode_index, bool new_state)
  850. {
  851. LOCKER(m_lock);
  852. unsigned group_index = group_index_from_inode(inode_index);
  853. auto& bgd = group_descriptor(group_index);
  854. unsigned index_in_group = inode_index - ((group_index - 1) * inodes_per_group());
  855. unsigned bit_index = (index_in_group - 1) % inodes_per_group();
  856. auto block = read_block(bgd.bg_inode_bitmap);
  857. ASSERT(block);
  858. auto bitmap = Bitmap::wrap(block.pointer(), inodes_per_group());
  859. bool current_state = bitmap.get(bit_index);
  860. #ifdef EXT2_DEBUG
  861. dbgprintf("Ext2FS: set_inode_allocation_state(%u) %u -> %u\n", inode_index, current_state, new_state);
  862. #endif
  863. if (current_state == new_state) {
  864. ASSERT_NOT_REACHED();
  865. return true;
  866. }
  867. bitmap.set(bit_index, new_state);
  868. bool success = write_block(bgd.bg_inode_bitmap, block);
  869. ASSERT(success);
  870. // Update superblock
  871. auto& sb = *reinterpret_cast<ext2_super_block*>(m_cached_super_block.pointer());
  872. #ifdef EXT2_DEBUG
  873. dbgprintf("Ext2FS: superblock free inode count %u -> %u\n", sb.s_free_inodes_count, sb.s_free_inodes_count - 1);
  874. #endif
  875. if (new_state)
  876. --sb.s_free_inodes_count;
  877. else
  878. ++sb.s_free_inodes_count;
  879. write_super_block(sb);
  880. // Update BGD
  881. auto& mutable_bgd = const_cast<ext2_group_desc&>(bgd);
  882. if (new_state)
  883. --mutable_bgd.bg_free_inodes_count;
  884. else
  885. ++mutable_bgd.bg_free_inodes_count;
  886. #ifdef EXT2_DEBUG
  887. dbgprintf("Ext2FS: group free inode count %u -> %u\n", bgd.bg_free_inodes_count, bgd.bg_free_inodes_count - 1);
  888. #endif
  889. flush_block_group_descriptor_table();
  890. return true;
  891. }
  892. bool Ext2FS::set_block_allocation_state(BlockIndex block_index, bool new_state)
  893. {
  894. LOCKER(m_lock);
  895. #ifdef EXT2_DEBUG
  896. dbgprintf("Ext2FS: set_block_allocation_state(block=%u, state=%u)\n", block_index, new_state);
  897. #endif
  898. unsigned group_index = group_index_from_block_index(block_index);
  899. auto& bgd = group_descriptor(group_index);
  900. BlockIndex index_in_group = (block_index - 1) - ((group_index - 1) * blocks_per_group());
  901. unsigned bit_index = index_in_group % blocks_per_group();
  902. #ifdef EXT2_DEBUG
  903. dbgprintf(" index_in_group: %u\n", index_in_group);
  904. dbgprintf(" blocks_per_group: %u\n", blocks_per_group());
  905. dbgprintf(" bit_index: %u\n", bit_index);
  906. dbgprintf(" read_block(%u)\n", bgd.bg_block_bitmap);
  907. #endif
  908. auto block = read_block(bgd.bg_block_bitmap);
  909. ASSERT(block);
  910. auto bitmap = Bitmap::wrap(block.pointer(), blocks_per_group());
  911. bool current_state = bitmap.get(bit_index);
  912. #ifdef EXT2_DEBUG
  913. dbgprintf("Ext2FS: block %u state: %u -> %u\n", block_index, current_state, new_state);
  914. #endif
  915. if (current_state == new_state) {
  916. ASSERT_NOT_REACHED();
  917. return true;
  918. }
  919. bitmap.set(bit_index, new_state);
  920. bool success = write_block(bgd.bg_block_bitmap, block);
  921. ASSERT(success);
  922. // Update superblock
  923. auto& sb = *reinterpret_cast<ext2_super_block*>(m_cached_super_block.pointer());
  924. #ifdef EXT2_DEBUG
  925. dbgprintf("Ext2FS: superblock free block count %u -> %u\n", sb.s_free_blocks_count, sb.s_free_blocks_count - 1);
  926. #endif
  927. if (new_state)
  928. --sb.s_free_blocks_count;
  929. else
  930. ++sb.s_free_blocks_count;
  931. write_super_block(sb);
  932. // Update BGD
  933. auto& mutable_bgd = const_cast<ext2_group_desc&>(bgd);
  934. if (new_state)
  935. --mutable_bgd.bg_free_blocks_count;
  936. else
  937. ++mutable_bgd.bg_free_blocks_count;
  938. #ifdef EXT2_DEBUG
  939. dbgprintf("Ext2FS: group %u free block count %u -> %u\n", group_index, bgd.bg_free_blocks_count, bgd.bg_free_blocks_count - 1);
  940. #endif
  941. flush_block_group_descriptor_table();
  942. return true;
  943. }
  944. RefPtr<Inode> Ext2FS::create_directory(InodeIdentifier parent_id, const String& name, mode_t mode, int& error)
  945. {
  946. LOCKER(m_lock);
  947. ASSERT(parent_id.fsid() == fsid());
  948. // Fix up the mode to definitely be a directory.
  949. // FIXME: This is a bit on the hackish side.
  950. mode &= ~0170000;
  951. mode |= 0040000;
  952. // NOTE: When creating a new directory, make the size 1 block.
  953. // There's probably a better strategy here, but this works for now.
  954. auto inode = create_inode(parent_id, name, mode, block_size(), 0, error);
  955. if (!inode)
  956. return nullptr;
  957. #ifdef EXT2_DEBUG
  958. dbgprintf("Ext2FS: create_directory: created new directory named '%s' with inode %u\n", name.characters(), inode->identifier().index());
  959. #endif
  960. Vector<DirectoryEntry> entries;
  961. entries.append({ ".", inode->identifier(), EXT2_FT_DIR });
  962. entries.append({ "..", parent_id, EXT2_FT_DIR });
  963. bool success = static_cast<Ext2FSInode&>(*inode).write_directory(entries);
  964. ASSERT(success);
  965. auto parent_inode = get_inode(parent_id);
  966. error = parent_inode->increment_link_count();
  967. if (error < 0)
  968. return nullptr;
  969. auto& bgd = const_cast<ext2_group_desc&>(group_descriptor(group_index_from_inode(inode->identifier().index())));
  970. ++bgd.bg_used_dirs_count;
  971. #ifdef EXT2_DEBUG
  972. dbgprintf("Ext2FS: incremented bg_used_dirs_count %u -> %u\n", bgd.bg_used_dirs_count - 1, bgd.bg_used_dirs_count);
  973. #endif
  974. flush_block_group_descriptor_table();
  975. error = 0;
  976. return inode;
  977. }
  978. RefPtr<Inode> Ext2FS::create_inode(InodeIdentifier parent_id, const String& name, mode_t mode, off_t size, dev_t dev, int& error)
  979. {
  980. LOCKER(m_lock);
  981. ASSERT(parent_id.fsid() == fsid());
  982. auto parent_inode = get_inode(parent_id);
  983. #ifdef EXT2_DEBUG
  984. dbgprintf("Ext2FS: Adding inode '%s' (mode %o) to parent directory %u:\n", name.characters(), mode, parent_inode->identifier().index());
  985. #endif
  986. // NOTE: This doesn't commit the inode allocation just yet!
  987. auto inode_id = allocate_inode(0, size);
  988. if (!inode_id) {
  989. kprintf("Ext2FS: create_inode: allocate_inode failed\n");
  990. error = -ENOSPC;
  991. return {};
  992. }
  993. auto needed_blocks = ceil_div(size, block_size());
  994. auto blocks = allocate_blocks(group_index_from_inode(inode_id), needed_blocks);
  995. if (blocks.size() != needed_blocks) {
  996. kprintf("Ext2FS: create_inode: allocate_blocks failed\n");
  997. error = -ENOSPC;
  998. return {};
  999. }
  1000. // Try adding it to the directory first, in case the name is already in use.
  1001. auto result = parent_inode->add_child({ fsid(), inode_id }, name, mode);
  1002. if (result.is_error()) {
  1003. error = result;
  1004. return {};
  1005. }
  1006. // Looks like we're good, time to update the inode bitmap and group+global inode counters.
  1007. bool success = set_inode_allocation_state(inode_id, true);
  1008. ASSERT(success);
  1009. for (auto block_index : blocks) {
  1010. success = set_block_allocation_state(block_index, true);
  1011. ASSERT(success);
  1012. }
  1013. unsigned initial_links_count;
  1014. if (is_directory(mode))
  1015. initial_links_count = 2; // (parent directory + "." entry in self)
  1016. else
  1017. initial_links_count = 1;
  1018. struct timeval now;
  1019. kgettimeofday(now);
  1020. ext2_inode e2inode;
  1021. memset(&e2inode, 0, sizeof(ext2_inode));
  1022. e2inode.i_mode = mode;
  1023. e2inode.i_uid = current->process().euid();
  1024. e2inode.i_gid = current->process().egid();
  1025. e2inode.i_size = size;
  1026. e2inode.i_atime = now.tv_sec;
  1027. e2inode.i_ctime = now.tv_sec;
  1028. e2inode.i_mtime = now.tv_sec;
  1029. e2inode.i_dtime = 0;
  1030. e2inode.i_links_count = initial_links_count;
  1031. if (is_character_device(mode))
  1032. e2inode.i_block[0] = dev;
  1033. else if (is_block_device(mode))
  1034. e2inode.i_block[1] = dev;
  1035. success = write_block_list_for_inode(inode_id, e2inode, blocks);
  1036. ASSERT(success);
  1037. #ifdef EXT2_DEBUG
  1038. dbgprintf("Ext2FS: writing initial metadata for inode %u\n", inode_id);
  1039. #endif
  1040. e2inode.i_flags = 0;
  1041. success = write_ext2_inode(inode_id, e2inode);
  1042. ASSERT(success);
  1043. // We might have cached the fact that this inode didn't exist. Wipe the slate.
  1044. m_inode_cache.remove(inode_id);
  1045. return get_inode({ fsid(), inode_id });
  1046. }
  1047. void Ext2FSInode::populate_lookup_cache() const
  1048. {
  1049. LOCKER(m_lock);
  1050. if (!m_lookup_cache.is_empty())
  1051. return;
  1052. HashMap<String, unsigned> children;
  1053. traverse_as_directory([&children](auto& entry) {
  1054. children.set(String(entry.name, entry.name_length), entry.inode.index());
  1055. return true;
  1056. });
  1057. if (!m_lookup_cache.is_empty())
  1058. return;
  1059. m_lookup_cache = move(children);
  1060. }
  1061. InodeIdentifier Ext2FSInode::lookup(StringView name)
  1062. {
  1063. ASSERT(is_directory());
  1064. populate_lookup_cache();
  1065. LOCKER(m_lock);
  1066. auto it = m_lookup_cache.find(name);
  1067. if (it != m_lookup_cache.end())
  1068. return { fsid(), (*it).value };
  1069. return {};
  1070. }
  1071. void Ext2FSInode::one_ref_left()
  1072. {
  1073. // FIXME: I would like to not live forever, but uncached Ext2FS is fucking painful right now.
  1074. }
  1075. int Ext2FSInode::set_atime(time_t t)
  1076. {
  1077. LOCKER(m_lock);
  1078. if (fs().is_readonly())
  1079. return -EROFS;
  1080. m_raw_inode.i_atime = t;
  1081. set_metadata_dirty(true);
  1082. return 0;
  1083. }
  1084. int Ext2FSInode::set_ctime(time_t t)
  1085. {
  1086. LOCKER(m_lock);
  1087. if (fs().is_readonly())
  1088. return -EROFS;
  1089. m_raw_inode.i_ctime = t;
  1090. set_metadata_dirty(true);
  1091. return 0;
  1092. }
  1093. int Ext2FSInode::set_mtime(time_t t)
  1094. {
  1095. LOCKER(m_lock);
  1096. if (fs().is_readonly())
  1097. return -EROFS;
  1098. m_raw_inode.i_mtime = t;
  1099. set_metadata_dirty(true);
  1100. return 0;
  1101. }
  1102. int Ext2FSInode::increment_link_count()
  1103. {
  1104. LOCKER(m_lock);
  1105. if (fs().is_readonly())
  1106. return -EROFS;
  1107. ++m_raw_inode.i_links_count;
  1108. set_metadata_dirty(true);
  1109. return 0;
  1110. }
  1111. int Ext2FSInode::decrement_link_count()
  1112. {
  1113. LOCKER(m_lock);
  1114. if (fs().is_readonly())
  1115. return -EROFS;
  1116. ASSERT(m_raw_inode.i_links_count);
  1117. --m_raw_inode.i_links_count;
  1118. if (m_raw_inode.i_links_count == 0)
  1119. fs().uncache_inode(index());
  1120. set_metadata_dirty(true);
  1121. return 0;
  1122. }
  1123. void Ext2FS::uncache_inode(InodeIndex index)
  1124. {
  1125. LOCKER(m_lock);
  1126. m_inode_cache.remove(index);
  1127. }
  1128. size_t Ext2FSInode::directory_entry_count() const
  1129. {
  1130. ASSERT(is_directory());
  1131. LOCKER(m_lock);
  1132. populate_lookup_cache();
  1133. return m_lookup_cache.size();
  1134. }
  1135. KResult Ext2FSInode::chmod(mode_t mode)
  1136. {
  1137. LOCKER(m_lock);
  1138. if (m_raw_inode.i_mode == mode)
  1139. return KSuccess;
  1140. m_raw_inode.i_mode = mode;
  1141. set_metadata_dirty(true);
  1142. return KSuccess;
  1143. }
  1144. KResult Ext2FSInode::chown(uid_t uid, gid_t gid)
  1145. {
  1146. LOCKER(m_lock);
  1147. if (m_raw_inode.i_uid == uid && m_raw_inode.i_gid == gid)
  1148. return KSuccess;
  1149. m_raw_inode.i_uid = uid;
  1150. m_raw_inode.i_gid = gid;
  1151. set_metadata_dirty(true);
  1152. return KSuccess;
  1153. }
  1154. KResult Ext2FSInode::truncate(off_t size)
  1155. {
  1156. LOCKER(m_lock);
  1157. if ((off_t)m_raw_inode.i_size == size)
  1158. return KSuccess;
  1159. resize(size);
  1160. set_metadata_dirty(true);
  1161. return KSuccess;
  1162. }
  1163. unsigned Ext2FS::total_block_count() const
  1164. {
  1165. LOCKER(m_lock);
  1166. return super_block().s_blocks_count;
  1167. }
  1168. unsigned Ext2FS::free_block_count() const
  1169. {
  1170. LOCKER(m_lock);
  1171. return super_block().s_free_blocks_count;
  1172. }
  1173. unsigned Ext2FS::total_inode_count() const
  1174. {
  1175. LOCKER(m_lock);
  1176. return super_block().s_inodes_count;
  1177. }
  1178. unsigned Ext2FS::free_inode_count() const
  1179. {
  1180. LOCKER(m_lock);
  1181. return super_block().s_free_inodes_count;
  1182. }