Ext2FileSystem.cpp 52 KB

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