Ext2FileSystem.cpp 50 KB

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