Ext2FileSystem.cpp 55 KB

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