Ext2FileSystem.cpp 55 KB

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