Ext2FileSystem.cpp 55 KB

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