Ext2FileSystem.cpp 55 KB

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