Ext2FileSystem.cpp 56 KB

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