Ext2FileSystem.cpp 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637
  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(BlockDevice& device)
  62. {
  63. return adopt(*new Ext2FS(device));
  64. }
  65. Ext2FS::Ext2FS(BlockDevice& device)
  66. : DiskBackedFS(device)
  67. {
  68. }
  69. Ext2FS::~Ext2FS()
  70. {
  71. }
  72. bool Ext2FS::flush_super_block()
  73. {
  74. LOCKER(m_lock);
  75. bool success = device().write_blocks(2, 1, (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 = const_cast<BlockDevice&>(device()).read_blocks(2, 1, (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. #ifdef EXT2_DEBUG
  344. dbg() << "Ext2FS::block_list_for_inode(): i_size=" << e2inode.i_size << ", i_blocks=" << e2inode.i_blocks << ", block_count=" << block_count;
  345. #endif
  346. unsigned blocks_remaining = block_count;
  347. Vector<BlockIndex> list;
  348. auto add_block = [&](BlockIndex bi) {
  349. if (blocks_remaining) {
  350. list.append(bi);
  351. --blocks_remaining;
  352. }
  353. };
  354. if (include_block_list_blocks) {
  355. // This seems like an excessive over-estimate but w/e.
  356. list.ensure_capacity(blocks_remaining * 2);
  357. } else {
  358. list.ensure_capacity(blocks_remaining);
  359. }
  360. unsigned direct_count = min(block_count, (unsigned)EXT2_NDIR_BLOCKS);
  361. for (unsigned i = 0; i < direct_count; ++i) {
  362. auto block_index = e2inode.i_block[i];
  363. add_block(block_index);
  364. }
  365. if (!blocks_remaining)
  366. return list;
  367. auto process_block_array = [&](unsigned array_block_index, auto&& callback) {
  368. if (include_block_list_blocks)
  369. callback(array_block_index);
  370. auto array_block = ByteBuffer::create_uninitialized(block_size());
  371. read_block(array_block_index, array_block.data());
  372. ASSERT(array_block);
  373. auto* array = reinterpret_cast<const __u32*>(array_block.data());
  374. unsigned count = min(blocks_remaining, entries_per_block);
  375. for (BlockIndex i = 0; i < count; ++i)
  376. callback(array[i]);
  377. };
  378. process_block_array(e2inode.i_block[EXT2_IND_BLOCK], [&](unsigned block_index) {
  379. add_block(block_index);
  380. });
  381. if (!blocks_remaining)
  382. return list;
  383. process_block_array(e2inode.i_block[EXT2_DIND_BLOCK], [&](unsigned block_index) {
  384. process_block_array(block_index, [&](unsigned block_index2) {
  385. add_block(block_index2);
  386. });
  387. });
  388. if (!blocks_remaining)
  389. return list;
  390. process_block_array(e2inode.i_block[EXT2_TIND_BLOCK], [&](unsigned block_index) {
  391. process_block_array(block_index, [&](unsigned block_index2) {
  392. process_block_array(block_index2, [&](unsigned block_index3) {
  393. add_block(block_index3);
  394. });
  395. });
  396. });
  397. return list;
  398. }
  399. void Ext2FS::free_inode(Ext2FSInode& inode)
  400. {
  401. LOCKER(m_lock);
  402. ASSERT(inode.m_raw_inode.i_links_count == 0);
  403. #ifdef EXT2_DEBUG
  404. dbg() << "Ext2FS: Inode " << inode.identifier() << " has no more links, time to delete!";
  405. #endif
  406. struct timeval now;
  407. kgettimeofday(now);
  408. inode.m_raw_inode.i_dtime = now.tv_sec;
  409. write_ext2_inode(inode.index(), inode.m_raw_inode);
  410. auto block_list = block_list_for_inode(inode.m_raw_inode, true);
  411. for (auto block_index : block_list) {
  412. if (block_index)
  413. set_block_allocation_state(block_index, false);
  414. }
  415. set_inode_allocation_state(inode.index(), false);
  416. if (inode.is_directory()) {
  417. auto& bgd = const_cast<ext2_group_desc&>(group_descriptor(group_index_from_inode(inode.index())));
  418. --bgd.bg_used_dirs_count;
  419. dbg() << "Ext2FS: Decremented bg_used_dirs_count to " << bgd.bg_used_dirs_count;
  420. m_block_group_descriptors_dirty = true;
  421. }
  422. }
  423. void Ext2FS::flush_block_group_descriptor_table()
  424. {
  425. LOCKER(m_lock);
  426. unsigned blocks_to_write = ceil_div(m_block_group_count * (unsigned)sizeof(ext2_group_desc), block_size());
  427. unsigned first_block_of_bgdt = block_size() == 1024 ? 2 : 1;
  428. write_blocks(first_block_of_bgdt, blocks_to_write, (const u8*)block_group_descriptors());
  429. }
  430. void Ext2FS::flush_writes()
  431. {
  432. LOCKER(m_lock);
  433. if (m_super_block_dirty) {
  434. flush_super_block();
  435. m_super_block_dirty = false;
  436. }
  437. if (m_block_group_descriptors_dirty) {
  438. flush_block_group_descriptor_table();
  439. m_block_group_descriptors_dirty = false;
  440. }
  441. for (auto& cached_bitmap : m_cached_bitmaps) {
  442. if (cached_bitmap->dirty) {
  443. write_block(cached_bitmap->bitmap_block_index, cached_bitmap->buffer.data());
  444. cached_bitmap->dirty = false;
  445. #ifdef EXT2_DEBUG
  446. dbg() << "Flushed bitmap block " << cached_bitmap->bitmap_block_index;
  447. #endif
  448. }
  449. }
  450. DiskBackedFS::flush_writes();
  451. // Uncache Inodes that are only kept alive by the index-to-inode lookup cache.
  452. // We don't uncache Inodes that are being watched by at least one InodeWatcher.
  453. // FIXME: It would be better to keep a capped number of Inodes around.
  454. // The problem is that they are quite heavy objects, and use a lot of heap memory
  455. // for their (child name lookup) and (block list) caches.
  456. Vector<InodeIndex> unused_inodes;
  457. for (auto& it : m_inode_cache) {
  458. if (it.value->ref_count() != 1)
  459. continue;
  460. if (it.value->has_watchers())
  461. continue;
  462. unused_inodes.append(it.key);
  463. }
  464. for (auto index : unused_inodes)
  465. uncache_inode(index);
  466. }
  467. Ext2FSInode::Ext2FSInode(Ext2FS& fs, unsigned index)
  468. : Inode(fs, index)
  469. {
  470. }
  471. Ext2FSInode::~Ext2FSInode()
  472. {
  473. if (m_raw_inode.i_links_count == 0)
  474. fs().free_inode(*this);
  475. }
  476. InodeMetadata Ext2FSInode::metadata() const
  477. {
  478. LOCKER(m_lock);
  479. InodeMetadata metadata;
  480. metadata.inode = identifier();
  481. metadata.size = m_raw_inode.i_size;
  482. metadata.mode = m_raw_inode.i_mode;
  483. metadata.uid = m_raw_inode.i_uid;
  484. metadata.gid = m_raw_inode.i_gid;
  485. metadata.link_count = m_raw_inode.i_links_count;
  486. metadata.atime = m_raw_inode.i_atime;
  487. metadata.ctime = m_raw_inode.i_ctime;
  488. metadata.mtime = m_raw_inode.i_mtime;
  489. metadata.dtime = m_raw_inode.i_dtime;
  490. metadata.block_size = fs().block_size();
  491. metadata.block_count = m_raw_inode.i_blocks;
  492. if (Kernel::is_character_device(m_raw_inode.i_mode) || Kernel::is_block_device(m_raw_inode.i_mode)) {
  493. unsigned dev = m_raw_inode.i_block[0];
  494. if (!dev)
  495. dev = m_raw_inode.i_block[1];
  496. metadata.major_device = (dev & 0xfff00) >> 8;
  497. metadata.minor_device = (dev & 0xff) | ((dev >> 12) & 0xfff00);
  498. }
  499. return metadata;
  500. }
  501. void Ext2FSInode::flush_metadata()
  502. {
  503. LOCKER(m_lock);
  504. #ifdef EXT2_DEBUG
  505. dbg() << "Ext2FS: flush_metadata for inode " << identifier();
  506. #endif
  507. fs().write_ext2_inode(index(), m_raw_inode);
  508. if (is_directory()) {
  509. // Unless we're about to go away permanently, invalidate the lookup cache.
  510. if (m_raw_inode.i_links_count != 0) {
  511. // FIXME: This invalidation is way too hardcore. It's sad to throw away the whole cache.
  512. m_lookup_cache.clear();
  513. }
  514. }
  515. set_metadata_dirty(false);
  516. }
  517. RefPtr<Inode> Ext2FS::get_inode(InodeIdentifier inode) const
  518. {
  519. LOCKER(m_lock);
  520. ASSERT(inode.fsid() == fsid());
  521. {
  522. auto it = m_inode_cache.find(inode.index());
  523. if (it != m_inode_cache.end())
  524. return (*it).value;
  525. }
  526. if (!get_inode_allocation_state(inode.index())) {
  527. m_inode_cache.set(inode.index(), nullptr);
  528. return nullptr;
  529. }
  530. unsigned block_index;
  531. unsigned offset;
  532. u8 block[max_block_size];
  533. if (!read_block_containing_inode(inode.index(), block_index, offset, block))
  534. return {};
  535. auto new_inode = adopt(*new Ext2FSInode(const_cast<Ext2FS&>(*this), inode.index()));
  536. memcpy(&new_inode->m_raw_inode, reinterpret_cast<ext2_inode*>(block + offset), sizeof(ext2_inode));
  537. m_inode_cache.set(inode.index(), new_inode);
  538. return new_inode;
  539. }
  540. ssize_t Ext2FSInode::read_bytes(off_t offset, ssize_t count, u8* buffer, FileDescription* description) const
  541. {
  542. Locker inode_locker(m_lock);
  543. ASSERT(offset >= 0);
  544. if (m_raw_inode.i_size == 0)
  545. return 0;
  546. // Symbolic links shorter than 60 characters are store inline inside the i_block array.
  547. // This avoids wasting an entire block on short links. (Most links are short.)
  548. if (is_symlink() && size() < max_inline_symlink_length) {
  549. ASSERT(offset == 0);
  550. ssize_t nread = min((off_t)size() - offset, static_cast<off_t>(count));
  551. memcpy(buffer, ((const u8*)m_raw_inode.i_block) + offset, (size_t)nread);
  552. return nread;
  553. }
  554. Locker fs_locker(fs().m_lock);
  555. if (m_block_list.is_empty())
  556. m_block_list = fs().block_list_for_inode(m_raw_inode);
  557. if (m_block_list.is_empty()) {
  558. klog() << "ext2fs: read_bytes: empty block list for inode " << index();
  559. return -EIO;
  560. }
  561. const int block_size = fs().block_size();
  562. size_t first_block_logical_index = offset / block_size;
  563. size_t last_block_logical_index = (offset + count) / block_size;
  564. if (last_block_logical_index >= m_block_list.size())
  565. last_block_logical_index = m_block_list.size() - 1;
  566. int offset_into_first_block = offset % block_size;
  567. ssize_t nread = 0;
  568. size_t remaining_count = min((off_t)count, (off_t)size() - offset);
  569. u8* out = buffer;
  570. #ifdef EXT2_DEBUG
  571. dbg() << "Ext2FS: Reading up to " << count << " bytes " << offset << " bytes into inode " << identifier() << " to " << (const void*)buffer;
  572. #endif
  573. u8 block[max_block_size];
  574. for (size_t bi = first_block_logical_index; remaining_count && bi <= last_block_logical_index; ++bi) {
  575. auto block_index = m_block_list[bi];
  576. ASSERT(block_index);
  577. bool success = fs().read_block(block_index, block, description);
  578. if (!success) {
  579. klog() << "ext2fs: read_bytes: read_block(" << block_index << ") failed (lbi: " << bi << ")";
  580. return -EIO;
  581. }
  582. size_t offset_into_block = (bi == first_block_logical_index) ? offset_into_first_block : 0;
  583. size_t num_bytes_to_copy = min(block_size - offset_into_block, remaining_count);
  584. memcpy(out, block + offset_into_block, num_bytes_to_copy);
  585. remaining_count -= num_bytes_to_copy;
  586. nread += num_bytes_to_copy;
  587. out += num_bytes_to_copy;
  588. }
  589. return nread;
  590. }
  591. KResult Ext2FSInode::resize(u64 new_size)
  592. {
  593. u64 old_size = size();
  594. if (old_size == new_size)
  595. return KSuccess;
  596. u64 block_size = fs().block_size();
  597. size_t blocks_needed_before = ceil_div(old_size, block_size);
  598. size_t blocks_needed_after = ceil_div(new_size, block_size);
  599. #ifdef EXT2_DEBUG
  600. dbg() << "Ext2FSInode::resize(): blocks needed before (size was " << old_size << "): " << blocks_needed_before;
  601. dbg() << "Ext2FSInode::resize(): blocks needed after (size is " << new_size << "): " << blocks_needed_after;
  602. #endif
  603. if (blocks_needed_after > blocks_needed_before) {
  604. u32 additional_blocks_needed = blocks_needed_after - blocks_needed_before;
  605. if (additional_blocks_needed > fs().super_block().s_free_blocks_count)
  606. return KResult(-ENOSPC);
  607. }
  608. auto block_list = fs().block_list_for_inode(m_raw_inode);
  609. if (blocks_needed_after > blocks_needed_before) {
  610. auto new_blocks = fs().allocate_blocks(fs().group_index_from_inode(index()), blocks_needed_after - blocks_needed_before);
  611. block_list.append(move(new_blocks));
  612. } else if (blocks_needed_after < blocks_needed_before) {
  613. #ifdef EXT2_DEBUG
  614. dbg() << "Ext2FS: Shrinking inode " << identifier() << ". Old block list is " << block_list.size() << " entries:";
  615. for (auto block_index : block_list) {
  616. dbg() << " # " << block_index;
  617. }
  618. #endif
  619. while (block_list.size() != blocks_needed_after) {
  620. auto block_index = block_list.take_last();
  621. if (block_index)
  622. fs().set_block_allocation_state(block_index, false);
  623. }
  624. }
  625. bool success = fs().write_block_list_for_inode(index(), m_raw_inode, block_list);
  626. if (!success)
  627. return KResult(-EIO);
  628. m_raw_inode.i_size = new_size;
  629. set_metadata_dirty(true);
  630. m_block_list = move(block_list);
  631. return KSuccess;
  632. }
  633. ssize_t Ext2FSInode::write_bytes(off_t offset, ssize_t count, const u8* data, FileDescription* description)
  634. {
  635. ASSERT(offset >= 0);
  636. ASSERT(count >= 0);
  637. Locker inode_locker(m_lock);
  638. Locker fs_locker(fs().m_lock);
  639. auto result = prepare_to_write_data();
  640. if (result.is_error())
  641. return result;
  642. if (is_symlink()) {
  643. ASSERT(offset == 0);
  644. if (max((size_t)(offset + count), (size_t)m_raw_inode.i_size) < max_inline_symlink_length) {
  645. #ifdef EXT2_DEBUG
  646. dbg() << "Ext2FS: write_bytes poking into i_block array for inline symlink '" << StringView(data, count) << " ' (" << count << " bytes)";
  647. #endif
  648. memcpy(((u8*)m_raw_inode.i_block) + offset, data, (size_t)count);
  649. if ((size_t)(offset + count) > (size_t)m_raw_inode.i_size)
  650. m_raw_inode.i_size = offset + count;
  651. set_metadata_dirty(true);
  652. return count;
  653. }
  654. }
  655. const size_t block_size = fs().block_size();
  656. u64 old_size = size();
  657. u64 new_size = max(static_cast<u64>(offset) + count, (u64)size());
  658. auto resize_result = resize(new_size);
  659. if (resize_result.is_error())
  660. return resize_result;
  661. if (m_block_list.is_empty())
  662. m_block_list = fs().block_list_for_inode(m_raw_inode);
  663. if (m_block_list.is_empty()) {
  664. dbg() << "Ext2FSInode::write_bytes(): empty block list for inode " << index();
  665. return -EIO;
  666. }
  667. size_t first_block_logical_index = offset / block_size;
  668. size_t last_block_logical_index = (offset + count) / block_size;
  669. if (last_block_logical_index >= m_block_list.size())
  670. last_block_logical_index = m_block_list.size() - 1;
  671. size_t offset_into_first_block = offset % block_size;
  672. size_t last_logical_block_index_in_file = new_size / block_size;
  673. ssize_t nwritten = 0;
  674. size_t remaining_count = min((off_t)count, (off_t)new_size - offset);
  675. const u8* in = data;
  676. #ifdef EXT2_DEBUG
  677. dbg() << "Ext2FS: Writing " << count << " bytes " << offset << " bytes into inode " << identifier() << " from " << (const void*)data;
  678. #endif
  679. auto buffer_block = ByteBuffer::create_uninitialized(block_size);
  680. for (size_t bi = first_block_logical_index; remaining_count && bi <= last_block_logical_index; ++bi) {
  681. size_t offset_into_block = (bi == first_block_logical_index) ? offset_into_first_block : 0;
  682. size_t num_bytes_to_copy = min(block_size - offset_into_block, remaining_count);
  683. ByteBuffer block;
  684. if (offset_into_block != 0 || num_bytes_to_copy != block_size) {
  685. block = ByteBuffer::create_uninitialized(block_size);
  686. bool success = fs().read_block(m_block_list[bi], block.data(), description);
  687. if (!success) {
  688. dbg() << "Ext2FS: In write_bytes, read_block(" << m_block_list[bi] << ") failed (bi: " << bi << ")";
  689. return -EIO;
  690. }
  691. } else
  692. block = buffer_block;
  693. memcpy(block.data() + offset_into_block, in, num_bytes_to_copy);
  694. if (bi == last_logical_block_index_in_file && num_bytes_to_copy < block_size) {
  695. size_t padding_start = new_size % block_size;
  696. size_t padding_bytes = block_size - padding_start;
  697. #ifdef EXT2_DEBUG
  698. 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 << ")";
  699. #endif
  700. memset(block.data() + padding_start, 0, padding_bytes);
  701. }
  702. #ifdef EXT2_DEBUG
  703. dbg() << "Ext2FS: Writing block " << m_block_list[bi] << " (offset_into_block: " << offset_into_block << ")";
  704. #endif
  705. bool success = fs().write_block(m_block_list[bi], block.data(), description);
  706. if (!success) {
  707. dbg() << "Ext2FS: write_block(" << m_block_list[bi] << ") failed (bi: " << bi << ")";
  708. ASSERT_NOT_REACHED();
  709. return -EIO;
  710. }
  711. remaining_count -= num_bytes_to_copy;
  712. nwritten += num_bytes_to_copy;
  713. in += num_bytes_to_copy;
  714. }
  715. #ifdef EXT2_DEBUG
  716. 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)";
  717. #endif
  718. if (old_size != new_size)
  719. inode_size_changed(old_size, new_size);
  720. inode_contents_changed(offset, count, data);
  721. return nwritten;
  722. }
  723. bool Ext2FSInode::traverse_as_directory(Function<bool(const FS::DirectoryEntry&)> callback) const
  724. {
  725. LOCKER(m_lock);
  726. ASSERT(is_directory());
  727. #ifdef EXT2_DEBUG
  728. dbg() << "Ext2FS: Traversing as directory: " << identifier();
  729. #endif
  730. auto buffer = read_entire();
  731. ASSERT(buffer);
  732. auto* entry = reinterpret_cast<ext2_dir_entry_2*>(buffer.data());
  733. while (entry < buffer.end_pointer()) {
  734. if (entry->inode != 0) {
  735. #ifdef EXT2_DEBUG
  736. 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);
  737. #endif
  738. if (!callback({ entry->name, entry->name_len, { fsid(), entry->inode }, entry->file_type }))
  739. break;
  740. }
  741. entry = (ext2_dir_entry_2*)((char*)entry + entry->rec_len);
  742. }
  743. return true;
  744. }
  745. bool Ext2FSInode::write_directory(const Vector<FS::DirectoryEntry>& entries)
  746. {
  747. LOCKER(m_lock);
  748. int directory_size = 0;
  749. for (auto& entry : entries)
  750. directory_size += EXT2_DIR_REC_LEN(entry.name_length);
  751. auto block_size = fs().block_size();
  752. int blocks_needed = ceil_div(directory_size, block_size);
  753. int occupied_size = blocks_needed * block_size;
  754. #ifdef EXT2_DEBUG
  755. dbg() << "Ext2FS: New directory inode " << identifier() << " contents to write (size " << directory_size << ", occupied " << occupied_size << "):";
  756. #endif
  757. auto directory_data = ByteBuffer::create_uninitialized(occupied_size);
  758. BufferStream stream(directory_data);
  759. for (size_t i = 0; i < entries.size(); ++i) {
  760. auto& entry = entries[i];
  761. int record_length = EXT2_DIR_REC_LEN(entry.name_length);
  762. if (i == entries.size() - 1)
  763. record_length += occupied_size - directory_size;
  764. #ifdef EXT2_DEBUG
  765. dbg() << "* Inode: " << entry.inode
  766. << ", name_len: " << u16(entry.name_length)
  767. << ", rec_len: " << u16(record_length)
  768. << ", file_type: " << u8(entry.file_type)
  769. << ", name: " << entry.name;
  770. #endif
  771. stream << u32(entry.inode.index());
  772. stream << u16(record_length);
  773. stream << u8(entry.name_length);
  774. stream << u8(entry.file_type);
  775. stream << entry.name;
  776. int padding = record_length - entry.name_length - 8;
  777. for (int j = 0; j < padding; ++j)
  778. stream << u8(0);
  779. }
  780. stream.fill_to_end(0);
  781. ssize_t nwritten = write_bytes(0, directory_data.size(), directory_data.data(), nullptr);
  782. if (nwritten < 0)
  783. return false;
  784. set_metadata_dirty(true);
  785. return static_cast<size_t>(nwritten) == directory_data.size();
  786. }
  787. KResult Ext2FSInode::add_child(InodeIdentifier child_id, const StringView& name, mode_t mode)
  788. {
  789. LOCKER(m_lock);
  790. ASSERT(is_directory());
  791. if (name.length() > EXT2_NAME_LEN)
  792. return KResult(-ENAMETOOLONG);
  793. #ifdef EXT2_DEBUG
  794. dbg() << "Ext2FSInode::add_child(): Adding inode " << child_id.index() << " with name '" << name << " and mode " << mode << " to directory " << index();
  795. #endif
  796. Vector<FS::DirectoryEntry> entries;
  797. bool name_already_exists = false;
  798. traverse_as_directory([&](auto& entry) {
  799. if (name == entry.name) {
  800. name_already_exists = true;
  801. return false;
  802. }
  803. entries.append(entry);
  804. return true;
  805. });
  806. if (name_already_exists) {
  807. dbg() << "Ext2FSInode::add_child(): Name '" << name << "' already exists in inode " << index();
  808. return KResult(-EEXIST);
  809. }
  810. auto child_inode = fs().get_inode(child_id);
  811. if (child_inode) {
  812. auto result = child_inode->increment_link_count();
  813. if (result.is_error())
  814. return result;
  815. }
  816. entries.empend(name.characters_without_null_termination(), name.length(), child_id, to_ext2_file_type(mode));
  817. bool success = write_directory(entries);
  818. if (success)
  819. m_lookup_cache.set(name, child_id.index());
  820. return KSuccess;
  821. }
  822. KResult Ext2FSInode::remove_child(const StringView& name)
  823. {
  824. LOCKER(m_lock);
  825. #ifdef EXT2_DEBUG
  826. dbg() << "Ext2FSInode::remove_child(" << name << ") in inode " << index();
  827. #endif
  828. ASSERT(is_directory());
  829. auto it = m_lookup_cache.find(name);
  830. if (it == m_lookup_cache.end())
  831. return KResult(-ENOENT);
  832. auto child_inode_index = (*it).value;
  833. InodeIdentifier child_id { fsid(), child_inode_index };
  834. #ifdef EXT2_DEBUG
  835. dbg() << "Ext2FSInode::remove_child(): Removing '" << name << "' in directory " << index();
  836. #endif
  837. Vector<FS::DirectoryEntry> entries;
  838. traverse_as_directory([&](auto& entry) {
  839. if (name != entry.name)
  840. entries.append(entry);
  841. return true;
  842. });
  843. bool success = write_directory(entries);
  844. if (!success) {
  845. // FIXME: Plumb error from write_directory().
  846. return KResult(-EIO);
  847. }
  848. m_lookup_cache.remove(name);
  849. auto child_inode = fs().get_inode(child_id);
  850. child_inode->decrement_link_count();
  851. return KSuccess;
  852. }
  853. unsigned Ext2FS::inodes_per_block() const
  854. {
  855. return EXT2_INODES_PER_BLOCK(&super_block());
  856. }
  857. unsigned Ext2FS::inodes_per_group() const
  858. {
  859. return EXT2_INODES_PER_GROUP(&super_block());
  860. }
  861. unsigned Ext2FS::inode_size() const
  862. {
  863. return EXT2_INODE_SIZE(&super_block());
  864. }
  865. unsigned Ext2FS::blocks_per_group() const
  866. {
  867. return EXT2_BLOCKS_PER_GROUP(&super_block());
  868. }
  869. bool Ext2FS::write_ext2_inode(unsigned inode, const ext2_inode& e2inode)
  870. {
  871. LOCKER(m_lock);
  872. unsigned block_index;
  873. unsigned offset;
  874. u8 block[max_block_size];
  875. if (!read_block_containing_inode(inode, block_index, offset, block))
  876. return false;
  877. memcpy(reinterpret_cast<ext2_inode*>(block + offset), &e2inode, inode_size());
  878. bool success = write_block(block_index, block);
  879. ASSERT(success);
  880. return success;
  881. }
  882. Vector<Ext2FS::BlockIndex> Ext2FS::allocate_blocks(GroupIndex preferred_group_index, size_t count)
  883. {
  884. LOCKER(m_lock);
  885. #ifdef EXT2_DEBUG
  886. dbg() << "Ext2FS: allocate_blocks(preferred group: " << preferred_group_index << ", count: " << count << ")";
  887. #endif
  888. if (count == 0)
  889. return {};
  890. Vector<BlockIndex> blocks;
  891. #ifdef EXT2_DEBUG
  892. dbg() << "Ext2FS: allocate_blocks:";
  893. #endif
  894. blocks.ensure_capacity(count);
  895. GroupIndex group_index = preferred_group_index;
  896. if (!group_descriptor(preferred_group_index).bg_free_blocks_count) {
  897. group_index = 1;
  898. }
  899. while (blocks.size() < count) {
  900. bool found_a_group = false;
  901. if (group_descriptor(group_index).bg_free_blocks_count) {
  902. found_a_group = true;
  903. } else {
  904. if (group_index == preferred_group_index)
  905. group_index = 1;
  906. for (; group_index < m_block_group_count; ++group_index) {
  907. if (group_descriptor(group_index).bg_free_blocks_count) {
  908. found_a_group = true;
  909. break;
  910. }
  911. }
  912. }
  913. ASSERT(found_a_group);
  914. auto& bgd = group_descriptor(group_index);
  915. auto& cached_bitmap = get_bitmap_block(bgd.bg_block_bitmap);
  916. int blocks_in_group = min(blocks_per_group(), super_block().s_blocks_count);
  917. auto block_bitmap = Bitmap::wrap(cached_bitmap.buffer.data(), blocks_in_group);
  918. BlockIndex first_block_in_group = (group_index - 1) * blocks_per_group() + first_block_index();
  919. size_t free_region_size = 0;
  920. auto first_unset_bit_index = block_bitmap.find_longest_range_of_unset_bits(count - blocks.size(), free_region_size);
  921. ASSERT(first_unset_bit_index.has_value());
  922. #ifdef EXT2_DEBUG
  923. dbg() << "Ext2FS: allocating free region of size: " << free_region_size << "[" << group_index << "]";
  924. #endif
  925. for (size_t i = 0; i < free_region_size; ++i) {
  926. BlockIndex block_index = (first_unset_bit_index.value() + i) + first_block_in_group;
  927. set_block_allocation_state(block_index, true);
  928. blocks.unchecked_append(block_index);
  929. #ifdef EXT2_DEBUG
  930. dbg() << " allocated > " << block_index;
  931. #endif
  932. }
  933. }
  934. ASSERT(blocks.size() == count);
  935. return blocks;
  936. }
  937. unsigned Ext2FS::find_a_free_inode(GroupIndex preferred_group, off_t expected_size)
  938. {
  939. LOCKER(m_lock);
  940. #ifdef EXT2_DEBUG
  941. dbg() << "Ext2FS: find_a_free_inode(preferred_group: " << preferred_group << ", expected_size: " << String::format("%ld", expected_size) << ")";
  942. #endif
  943. unsigned needed_blocks = ceil_div(expected_size, block_size());
  944. #ifdef EXT2_DEBUG
  945. dbg() << "Ext2FS: minimum needed blocks: " << needed_blocks;
  946. #endif
  947. unsigned group_index = 0;
  948. // FIXME: We shouldn't refuse to allocate an inode if there is no group that can house the whole thing.
  949. // In those cases we should just spread it across multiple groups.
  950. auto is_suitable_group = [this, needed_blocks](GroupIndex group_index) {
  951. auto& bgd = group_descriptor(group_index);
  952. return bgd.bg_free_inodes_count && bgd.bg_free_blocks_count >= needed_blocks;
  953. };
  954. if (preferred_group && is_suitable_group(preferred_group)) {
  955. group_index = preferred_group;
  956. } else {
  957. for (unsigned i = 1; i <= m_block_group_count; ++i) {
  958. if (is_suitable_group(i))
  959. group_index = i;
  960. }
  961. }
  962. if (!group_index) {
  963. klog() << "Ext2FS: find_a_free_inode: no suitable group found for new inode with " << needed_blocks << " blocks needed :(";
  964. return 0;
  965. }
  966. #ifdef EXT2_DEBUG
  967. dbg() << "Ext2FS: find_a_free_inode: found suitable group [" << group_index << "] for new inode with " << needed_blocks << " blocks needed :^)";
  968. #endif
  969. auto& bgd = group_descriptor(group_index);
  970. unsigned inodes_in_group = min(inodes_per_group(), super_block().s_inodes_count);
  971. unsigned first_free_inode_in_group = 0;
  972. unsigned first_inode_in_group = (group_index - 1) * inodes_per_group() + 1;
  973. auto& cached_bitmap = get_bitmap_block(bgd.bg_inode_bitmap);
  974. auto inode_bitmap = Bitmap::wrap(cached_bitmap.buffer.data(), inodes_in_group);
  975. for (size_t i = 0; i < inode_bitmap.size(); ++i) {
  976. if (inode_bitmap.get(i))
  977. continue;
  978. first_free_inode_in_group = first_inode_in_group + i;
  979. break;
  980. }
  981. if (!first_free_inode_in_group) {
  982. klog() << "Ext2FS: first_free_inode_in_group returned no inode, despite bgd claiming there are inodes :(";
  983. return 0;
  984. }
  985. unsigned inode = first_free_inode_in_group;
  986. #ifdef EXT2_DEBUG
  987. dbg() << "Ext2FS: found suitable inode " << inode;
  988. #endif
  989. ASSERT(get_inode_allocation_state(inode) == false);
  990. return inode;
  991. }
  992. Ext2FS::GroupIndex Ext2FS::group_index_from_block_index(BlockIndex block_index) const
  993. {
  994. if (!block_index)
  995. return 0;
  996. return (block_index - 1) / blocks_per_group() + 1;
  997. }
  998. unsigned Ext2FS::group_index_from_inode(unsigned inode) const
  999. {
  1000. if (!inode)
  1001. return 0;
  1002. return (inode - 1) / inodes_per_group() + 1;
  1003. }
  1004. bool Ext2FS::get_inode_allocation_state(InodeIndex index) const
  1005. {
  1006. LOCKER(m_lock);
  1007. if (index == 0)
  1008. return true;
  1009. unsigned group_index = group_index_from_inode(index);
  1010. auto& bgd = group_descriptor(group_index);
  1011. unsigned index_in_group = index - ((group_index - 1) * inodes_per_group());
  1012. unsigned bit_index = (index_in_group - 1) % inodes_per_group();
  1013. auto& cached_bitmap = const_cast<Ext2FS&>(*this).get_bitmap_block(bgd.bg_inode_bitmap);
  1014. return cached_bitmap.bitmap(inodes_per_group()).get(bit_index);
  1015. }
  1016. bool Ext2FS::set_inode_allocation_state(InodeIndex inode_index, bool new_state)
  1017. {
  1018. LOCKER(m_lock);
  1019. unsigned group_index = group_index_from_inode(inode_index);
  1020. auto& bgd = group_descriptor(group_index);
  1021. unsigned index_in_group = inode_index - ((group_index - 1) * inodes_per_group());
  1022. unsigned bit_index = (index_in_group - 1) % inodes_per_group();
  1023. auto& cached_bitmap = get_bitmap_block(bgd.bg_inode_bitmap);
  1024. bool current_state = cached_bitmap.bitmap(inodes_per_group()).get(bit_index);
  1025. #ifdef EXT2_DEBUG
  1026. dbg() << "Ext2FS: set_inode_allocation_state(" << inode_index << ") " << String::format("%u", current_state) << " -> " << String::format("%u", new_state);
  1027. #endif
  1028. if (current_state == new_state) {
  1029. ASSERT_NOT_REACHED();
  1030. return true;
  1031. }
  1032. cached_bitmap.bitmap(inodes_per_group()).set(bit_index, new_state);
  1033. cached_bitmap.dirty = true;
  1034. // Update superblock
  1035. #ifdef EXT2_DEBUG
  1036. dbg() << "Ext2FS: superblock free inode count " << m_super_block.s_free_inodes_count << " -> " << (m_super_block.s_free_inodes_count - 1);
  1037. #endif
  1038. if (new_state)
  1039. --m_super_block.s_free_inodes_count;
  1040. else
  1041. ++m_super_block.s_free_inodes_count;
  1042. m_super_block_dirty = true;
  1043. // Update BGD
  1044. auto& mutable_bgd = const_cast<ext2_group_desc&>(bgd);
  1045. if (new_state)
  1046. --mutable_bgd.bg_free_inodes_count;
  1047. else
  1048. ++mutable_bgd.bg_free_inodes_count;
  1049. #ifdef EXT2_DEBUG
  1050. dbg() << "Ext2FS: group free inode count " << bgd.bg_free_inodes_count << " -> " << (bgd.bg_free_inodes_count - 1);
  1051. #endif
  1052. m_block_group_descriptors_dirty = true;
  1053. return true;
  1054. }
  1055. Ext2FS::BlockIndex Ext2FS::first_block_index() const
  1056. {
  1057. return block_size() == 1024 ? 1 : 0;
  1058. }
  1059. Ext2FS::CachedBitmap& Ext2FS::get_bitmap_block(BlockIndex bitmap_block_index)
  1060. {
  1061. for (auto& cached_bitmap : m_cached_bitmaps) {
  1062. if (cached_bitmap->bitmap_block_index == bitmap_block_index)
  1063. return *cached_bitmap;
  1064. }
  1065. auto block = KBuffer::create_with_size(block_size(), Region::Access::Read | Region::Access::Write, "Ext2FS: Cached bitmap block");
  1066. bool success = read_block(bitmap_block_index, block.data());
  1067. ASSERT(success);
  1068. m_cached_bitmaps.append(make<CachedBitmap>(bitmap_block_index, move(block)));
  1069. return *m_cached_bitmaps.last();
  1070. }
  1071. bool Ext2FS::set_block_allocation_state(BlockIndex block_index, bool new_state)
  1072. {
  1073. ASSERT(block_index != 0);
  1074. LOCKER(m_lock);
  1075. #ifdef EXT2_DEBUG
  1076. dbg() << "Ext2FS: set_block_allocation_state(block=" << block_index << ", state=" << String::format("%u", new_state) << ")";
  1077. #endif
  1078. GroupIndex group_index = group_index_from_block_index(block_index);
  1079. auto& bgd = group_descriptor(group_index);
  1080. BlockIndex index_in_group = (block_index - first_block_index()) - ((group_index - 1) * blocks_per_group());
  1081. unsigned bit_index = index_in_group % blocks_per_group();
  1082. auto& cached_bitmap = get_bitmap_block(bgd.bg_block_bitmap);
  1083. bool current_state = cached_bitmap.bitmap(blocks_per_group()).get(bit_index);
  1084. #ifdef EXT2_DEBUG
  1085. dbg() << "Ext2FS: block " << block_index << " state: " << String::format("%u", current_state) << " -> " << String::format("%u", new_state) << " (in bitmap block " << bgd.bg_block_bitmap << ")";
  1086. #endif
  1087. if (current_state == new_state) {
  1088. ASSERT_NOT_REACHED();
  1089. return true;
  1090. }
  1091. cached_bitmap.bitmap(blocks_per_group()).set(bit_index, new_state);
  1092. cached_bitmap.dirty = true;
  1093. // Update superblock
  1094. #ifdef EXT2_DEBUG
  1095. dbg() << "Ext2FS: superblock free block count " << m_super_block.s_free_blocks_count << " -> " << (m_super_block.s_free_blocks_count - 1);
  1096. #endif
  1097. if (new_state)
  1098. --m_super_block.s_free_blocks_count;
  1099. else
  1100. ++m_super_block.s_free_blocks_count;
  1101. m_super_block_dirty = true;
  1102. // Update BGD
  1103. auto& mutable_bgd = const_cast<ext2_group_desc&>(bgd);
  1104. if (new_state)
  1105. --mutable_bgd.bg_free_blocks_count;
  1106. else
  1107. ++mutable_bgd.bg_free_blocks_count;
  1108. #ifdef EXT2_DEBUG
  1109. dbg() << "Ext2FS: group " << group_index << " free block count " << bgd.bg_free_blocks_count << " -> " << (bgd.bg_free_blocks_count - 1);
  1110. #endif
  1111. m_block_group_descriptors_dirty = true;
  1112. return true;
  1113. }
  1114. KResult Ext2FS::create_directory(InodeIdentifier parent_id, const String& name, mode_t mode, uid_t uid, gid_t gid)
  1115. {
  1116. LOCKER(m_lock);
  1117. ASSERT(parent_id.fsid() == fsid());
  1118. // Fix up the mode to definitely be a directory.
  1119. // FIXME: This is a bit on the hackish side.
  1120. mode &= ~0170000;
  1121. mode |= 0040000;
  1122. // NOTE: When creating a new directory, make the size 1 block.
  1123. // There's probably a better strategy here, but this works for now.
  1124. auto inode_or_error = create_inode(parent_id, name, mode, block_size(), 0, uid, gid);
  1125. if (inode_or_error.is_error())
  1126. return inode_or_error.error();
  1127. auto& inode = inode_or_error.value();
  1128. #ifdef EXT2_DEBUG
  1129. dbg() << "Ext2FS: create_directory: created new directory named '" << name << "' with inode " << inode->identifier();
  1130. #endif
  1131. Vector<DirectoryEntry> entries;
  1132. entries.empend(".", inode->identifier(), EXT2_FT_DIR);
  1133. entries.empend("..", parent_id, EXT2_FT_DIR);
  1134. bool success = static_cast<Ext2FSInode&>(*inode).write_directory(entries);
  1135. ASSERT(success);
  1136. auto parent_inode = get_inode(parent_id);
  1137. auto result = parent_inode->increment_link_count();
  1138. if (result.is_error())
  1139. return result;
  1140. auto& bgd = const_cast<ext2_group_desc&>(group_descriptor(group_index_from_inode(inode->identifier().index())));
  1141. ++bgd.bg_used_dirs_count;
  1142. #ifdef EXT2_DEBUG
  1143. dbg() << "Ext2FS: incremented bg_used_dirs_count " << bgd.bg_used_dirs_count - 1 << " -> " << bgd.bg_used_dirs_count;
  1144. #endif
  1145. m_block_group_descriptors_dirty = true;
  1146. return KSuccess;
  1147. }
  1148. KResultOr<NonnullRefPtr<Inode>> Ext2FS::create_inode(InodeIdentifier parent_id, const String& name, mode_t mode, off_t size, dev_t dev, uid_t uid, gid_t gid)
  1149. {
  1150. LOCKER(m_lock);
  1151. ASSERT(parent_id.fsid() == fsid());
  1152. auto parent_inode = get_inode(parent_id);
  1153. ASSERT(parent_inode);
  1154. if (static_cast<const Ext2FSInode&>(*parent_inode).m_raw_inode.i_links_count == 0)
  1155. return KResult(-ENOENT);
  1156. #ifdef EXT2_DEBUG
  1157. dbg() << "Ext2FS: Adding inode '" << name << "' (mode " << String::format("%o", mode) << ") to parent directory " << parent_inode->identifier();
  1158. #endif
  1159. size_t needed_blocks = ceil_div(size, block_size());
  1160. if ((size_t)needed_blocks > super_block().s_free_blocks_count) {
  1161. dbg() << "Ext2FS: create_inode: not enough free blocks";
  1162. return KResult(-ENOSPC);
  1163. }
  1164. // NOTE: This doesn't commit the inode allocation just yet!
  1165. auto inode_id = find_a_free_inode(0, size);
  1166. if (!inode_id) {
  1167. klog() << "Ext2FS: create_inode: allocate_inode failed";
  1168. return KResult(-ENOSPC);
  1169. }
  1170. // Try adding it to the directory first, in case the name is already in use.
  1171. auto result = parent_inode->add_child({ fsid(), inode_id }, name, mode);
  1172. if (result.is_error())
  1173. return result;
  1174. auto blocks = allocate_blocks(group_index_from_inode(inode_id), needed_blocks);
  1175. ASSERT(blocks.size() == needed_blocks);
  1176. // Looks like we're good, time to update the inode bitmap and group+global inode counters.
  1177. bool success = set_inode_allocation_state(inode_id, true);
  1178. ASSERT(success);
  1179. unsigned initial_links_count;
  1180. if (is_directory(mode))
  1181. initial_links_count = 2; // (parent directory + "." entry in self)
  1182. else
  1183. initial_links_count = 1;
  1184. struct timeval now;
  1185. kgettimeofday(now);
  1186. ext2_inode e2inode;
  1187. memset(&e2inode, 0, sizeof(ext2_inode));
  1188. e2inode.i_mode = mode;
  1189. e2inode.i_uid = uid;
  1190. e2inode.i_gid = gid;
  1191. e2inode.i_size = size;
  1192. e2inode.i_atime = now.tv_sec;
  1193. e2inode.i_ctime = now.tv_sec;
  1194. e2inode.i_mtime = now.tv_sec;
  1195. e2inode.i_dtime = 0;
  1196. e2inode.i_links_count = initial_links_count;
  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. return inode.release_nonnull();
  1215. }
  1216. void Ext2FSInode::populate_lookup_cache() const
  1217. {
  1218. LOCKER(m_lock);
  1219. if (!m_lookup_cache.is_empty())
  1220. return;
  1221. HashMap<String, unsigned> children;
  1222. traverse_as_directory([&children](auto& entry) {
  1223. children.set(String(entry.name, entry.name_length), entry.inode.index());
  1224. return true;
  1225. });
  1226. if (!m_lookup_cache.is_empty())
  1227. return;
  1228. m_lookup_cache = move(children);
  1229. }
  1230. RefPtr<Inode> Ext2FSInode::lookup(StringView name)
  1231. {
  1232. ASSERT(is_directory());
  1233. populate_lookup_cache();
  1234. LOCKER(m_lock);
  1235. auto it = m_lookup_cache.find(name.hash(), [&](auto& entry) { return entry.key == name; });
  1236. if (it != m_lookup_cache.end())
  1237. return fs().get_inode({ fsid(), (*it).value });
  1238. return {};
  1239. }
  1240. void Ext2FSInode::one_ref_left()
  1241. {
  1242. // FIXME: I would like to not live forever, but uncached Ext2FS is fucking painful right now.
  1243. }
  1244. int Ext2FSInode::set_atime(time_t t)
  1245. {
  1246. LOCKER(m_lock);
  1247. if (fs().is_readonly())
  1248. return -EROFS;
  1249. m_raw_inode.i_atime = t;
  1250. set_metadata_dirty(true);
  1251. return 0;
  1252. }
  1253. int Ext2FSInode::set_ctime(time_t t)
  1254. {
  1255. LOCKER(m_lock);
  1256. if (fs().is_readonly())
  1257. return -EROFS;
  1258. m_raw_inode.i_ctime = t;
  1259. set_metadata_dirty(true);
  1260. return 0;
  1261. }
  1262. int Ext2FSInode::set_mtime(time_t t)
  1263. {
  1264. LOCKER(m_lock);
  1265. if (fs().is_readonly())
  1266. return -EROFS;
  1267. m_raw_inode.i_mtime = t;
  1268. set_metadata_dirty(true);
  1269. return 0;
  1270. }
  1271. KResult Ext2FSInode::increment_link_count()
  1272. {
  1273. LOCKER(m_lock);
  1274. if (fs().is_readonly())
  1275. return KResult(-EROFS);
  1276. if (m_raw_inode.i_links_count == max_link_count)
  1277. return KResult(-EMLINK);
  1278. ++m_raw_inode.i_links_count;
  1279. set_metadata_dirty(true);
  1280. return KSuccess;
  1281. }
  1282. KResult Ext2FSInode::decrement_link_count()
  1283. {
  1284. LOCKER(m_lock);
  1285. if (fs().is_readonly())
  1286. return KResult(-EROFS);
  1287. ASSERT(m_raw_inode.i_links_count);
  1288. --m_raw_inode.i_links_count;
  1289. if (ref_count() == 1 && m_raw_inode.i_links_count == 0)
  1290. fs().uncache_inode(index());
  1291. set_metadata_dirty(true);
  1292. return KSuccess;
  1293. }
  1294. void Ext2FS::uncache_inode(InodeIndex index)
  1295. {
  1296. LOCKER(m_lock);
  1297. m_inode_cache.remove(index);
  1298. }
  1299. size_t Ext2FSInode::directory_entry_count() const
  1300. {
  1301. ASSERT(is_directory());
  1302. LOCKER(m_lock);
  1303. populate_lookup_cache();
  1304. return m_lookup_cache.size();
  1305. }
  1306. KResult Ext2FSInode::chmod(mode_t mode)
  1307. {
  1308. LOCKER(m_lock);
  1309. if (m_raw_inode.i_mode == mode)
  1310. return KSuccess;
  1311. m_raw_inode.i_mode = mode;
  1312. set_metadata_dirty(true);
  1313. return KSuccess;
  1314. }
  1315. KResult Ext2FSInode::chown(uid_t uid, gid_t gid)
  1316. {
  1317. LOCKER(m_lock);
  1318. if (m_raw_inode.i_uid == uid && m_raw_inode.i_gid == gid)
  1319. return KSuccess;
  1320. m_raw_inode.i_uid = uid;
  1321. m_raw_inode.i_gid = gid;
  1322. set_metadata_dirty(true);
  1323. return KSuccess;
  1324. }
  1325. KResult Ext2FSInode::truncate(u64 size)
  1326. {
  1327. LOCKER(m_lock);
  1328. if (static_cast<u64>(m_raw_inode.i_size) == size)
  1329. return KSuccess;
  1330. auto result = resize(size);
  1331. if (result.is_error())
  1332. return result;
  1333. set_metadata_dirty(true);
  1334. return KSuccess;
  1335. }
  1336. unsigned Ext2FS::total_block_count() const
  1337. {
  1338. LOCKER(m_lock);
  1339. return super_block().s_blocks_count;
  1340. }
  1341. unsigned Ext2FS::free_block_count() const
  1342. {
  1343. LOCKER(m_lock);
  1344. return super_block().s_free_blocks_count;
  1345. }
  1346. unsigned Ext2FS::total_inode_count() const
  1347. {
  1348. LOCKER(m_lock);
  1349. return super_block().s_inodes_count;
  1350. }
  1351. unsigned Ext2FS::free_inode_count() const
  1352. {
  1353. LOCKER(m_lock);
  1354. return super_block().s_free_inodes_count;
  1355. }
  1356. KResult Ext2FS::prepare_to_unmount() const
  1357. {
  1358. LOCKER(m_lock);
  1359. for (auto& it : m_inode_cache) {
  1360. if (it.value->ref_count() > 1)
  1361. return KResult(-EBUSY);
  1362. }
  1363. m_inode_cache.clear();
  1364. return KSuccess;
  1365. }
  1366. }