Ext2FileSystem.cpp 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630
  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. Vector<Ext2FS::BlockIndex> Ext2FS::allocate_blocks(GroupIndex preferred_group_index, size_t count)
  879. {
  880. LOCKER(m_lock);
  881. #ifdef EXT2_DEBUG
  882. dbg() << "Ext2FS: allocate_blocks(preferred group: " << preferred_group_index << ", count: " << count << ")";
  883. #endif
  884. if (count == 0)
  885. return {};
  886. Vector<BlockIndex> blocks;
  887. #ifdef EXT2_DEBUG
  888. dbg() << "Ext2FS: allocate_blocks:";
  889. #endif
  890. blocks.ensure_capacity(count);
  891. bool found_a_group = false;
  892. GroupIndex group_index = preferred_group_index;
  893. if (!group_descriptor(preferred_group_index).bg_free_blocks_count) {
  894. group_index = 1;
  895. }
  896. while (blocks.size() < count) {
  897. if (group_descriptor(group_index).bg_free_blocks_count) {
  898. found_a_group = true;
  899. } else {
  900. if (group_index == preferred_group_index)
  901. group_index = 1;
  902. for (; group_index < m_block_group_count; ++group_index) {
  903. if (group_descriptor(group_index).bg_free_blocks_count) {
  904. found_a_group = true;
  905. break;
  906. }
  907. }
  908. }
  909. ASSERT(found_a_group);
  910. auto& bgd = group_descriptor(group_index);
  911. auto& cached_bitmap = get_bitmap_block(bgd.bg_block_bitmap);
  912. int blocks_in_group = min(blocks_per_group(), super_block().s_blocks_count);
  913. auto block_bitmap = Bitmap::wrap(cached_bitmap.buffer.data(), blocks_in_group);
  914. BlockIndex first_block_in_group = (group_index - 1) * blocks_per_group() + first_block_index();
  915. size_t free_region_size = 0;
  916. auto first_unset_bit_index = block_bitmap.find_longest_range_of_unset_bits(count - blocks.size(), free_region_size);
  917. ASSERT(first_unset_bit_index.has_value());
  918. #ifdef EXT2_DEBUG
  919. dbg() << "Ext2FS: allocating free region of size: " << free_region_size << "[" << group_index << "]";
  920. #endif
  921. for (size_t i = 0; i < free_region_size; ++i) {
  922. BlockIndex block_index = (first_unset_bit_index.value() + i) + first_block_in_group;
  923. set_block_allocation_state(block_index, true);
  924. blocks.unchecked_append(block_index);
  925. #ifdef EXT2_DEBUG
  926. dbg() << " allocated > " << block_index;
  927. #endif
  928. }
  929. }
  930. ASSERT(blocks.size() == count);
  931. return blocks;
  932. }
  933. unsigned Ext2FS::find_a_free_inode(GroupIndex preferred_group, off_t expected_size)
  934. {
  935. LOCKER(m_lock);
  936. #ifdef EXT2_DEBUG
  937. dbg() << "Ext2FS: find_a_free_inode(preferred_group: " << preferred_group << ", expected_size: " << String::format("%ld", expected_size) << ")";
  938. #endif
  939. unsigned needed_blocks = ceil_div(expected_size, block_size());
  940. #ifdef EXT2_DEBUG
  941. dbg() << "Ext2FS: minimum needed blocks: " << needed_blocks;
  942. #endif
  943. unsigned group_index = 0;
  944. // FIXME: We shouldn't refuse to allocate an inode if there is no group that can house the whole thing.
  945. // In those cases we should just spread it across multiple groups.
  946. auto is_suitable_group = [this, needed_blocks](GroupIndex group_index) {
  947. auto& bgd = group_descriptor(group_index);
  948. return bgd.bg_free_inodes_count && bgd.bg_free_blocks_count >= needed_blocks;
  949. };
  950. if (preferred_group && is_suitable_group(preferred_group)) {
  951. group_index = preferred_group;
  952. } else {
  953. for (unsigned i = 1; i <= m_block_group_count; ++i) {
  954. if (is_suitable_group(i))
  955. group_index = i;
  956. }
  957. }
  958. if (!group_index) {
  959. klog() << "Ext2FS: find_a_free_inode: no suitable group found for new inode with " << needed_blocks << " blocks needed :(";
  960. return 0;
  961. }
  962. #ifdef EXT2_DEBUG
  963. dbg() << "Ext2FS: find_a_free_inode: found suitable group [" << group_index << "] for new inode with " << needed_blocks << " blocks needed :^)";
  964. #endif
  965. auto& bgd = group_descriptor(group_index);
  966. unsigned inodes_in_group = min(inodes_per_group(), super_block().s_inodes_count);
  967. unsigned first_free_inode_in_group = 0;
  968. unsigned first_inode_in_group = (group_index - 1) * inodes_per_group() + 1;
  969. auto& cached_bitmap = get_bitmap_block(bgd.bg_inode_bitmap);
  970. auto inode_bitmap = Bitmap::wrap(cached_bitmap.buffer.data(), inodes_in_group);
  971. for (size_t i = 0; i < inode_bitmap.size(); ++i) {
  972. if (inode_bitmap.get(i))
  973. continue;
  974. first_free_inode_in_group = first_inode_in_group + i;
  975. break;
  976. }
  977. if (!first_free_inode_in_group) {
  978. klog() << "Ext2FS: first_free_inode_in_group returned no inode, despite bgd claiming there are inodes :(";
  979. return 0;
  980. }
  981. unsigned inode = first_free_inode_in_group;
  982. #ifdef EXT2_DEBUG
  983. dbg() << "Ext2FS: found suitable inode " << inode;
  984. #endif
  985. ASSERT(get_inode_allocation_state(inode) == false);
  986. return inode;
  987. }
  988. Ext2FS::GroupIndex Ext2FS::group_index_from_block_index(BlockIndex block_index) const
  989. {
  990. if (!block_index)
  991. return 0;
  992. return (block_index - 1) / blocks_per_group() + 1;
  993. }
  994. unsigned Ext2FS::group_index_from_inode(unsigned inode) const
  995. {
  996. if (!inode)
  997. return 0;
  998. return (inode - 1) / inodes_per_group() + 1;
  999. }
  1000. bool Ext2FS::get_inode_allocation_state(InodeIndex index) const
  1001. {
  1002. LOCKER(m_lock);
  1003. if (index == 0)
  1004. return true;
  1005. unsigned group_index = group_index_from_inode(index);
  1006. auto& bgd = group_descriptor(group_index);
  1007. unsigned index_in_group = index - ((group_index - 1) * inodes_per_group());
  1008. unsigned bit_index = (index_in_group - 1) % inodes_per_group();
  1009. auto& cached_bitmap = const_cast<Ext2FS&>(*this).get_bitmap_block(bgd.bg_inode_bitmap);
  1010. return cached_bitmap.bitmap(inodes_per_group()).get(bit_index);
  1011. }
  1012. bool Ext2FS::set_inode_allocation_state(InodeIndex inode_index, bool new_state)
  1013. {
  1014. LOCKER(m_lock);
  1015. unsigned group_index = group_index_from_inode(inode_index);
  1016. auto& bgd = group_descriptor(group_index);
  1017. unsigned index_in_group = inode_index - ((group_index - 1) * inodes_per_group());
  1018. unsigned bit_index = (index_in_group - 1) % inodes_per_group();
  1019. auto& cached_bitmap = get_bitmap_block(bgd.bg_inode_bitmap);
  1020. bool current_state = cached_bitmap.bitmap(inodes_per_group()).get(bit_index);
  1021. #ifdef EXT2_DEBUG
  1022. dbg() << "Ext2FS: set_inode_allocation_state(" << inode_index << ") " << String::format("%u", current_state) << " -> " << String::format("%u", new_state);
  1023. #endif
  1024. if (current_state == new_state) {
  1025. ASSERT_NOT_REACHED();
  1026. return true;
  1027. }
  1028. cached_bitmap.bitmap(inodes_per_group()).set(bit_index, new_state);
  1029. cached_bitmap.dirty = true;
  1030. // Update superblock
  1031. #ifdef EXT2_DEBUG
  1032. dbg() << "Ext2FS: superblock free inode count " << m_super_block.s_free_inodes_count << " -> " << (m_super_block.s_free_inodes_count - 1);
  1033. #endif
  1034. if (new_state)
  1035. --m_super_block.s_free_inodes_count;
  1036. else
  1037. ++m_super_block.s_free_inodes_count;
  1038. m_super_block_dirty = true;
  1039. // Update BGD
  1040. auto& mutable_bgd = const_cast<ext2_group_desc&>(bgd);
  1041. if (new_state)
  1042. --mutable_bgd.bg_free_inodes_count;
  1043. else
  1044. ++mutable_bgd.bg_free_inodes_count;
  1045. #ifdef EXT2_DEBUG
  1046. dbg() << "Ext2FS: group free inode count " << bgd.bg_free_inodes_count << " -> " << (bgd.bg_free_inodes_count - 1);
  1047. #endif
  1048. m_block_group_descriptors_dirty = true;
  1049. return true;
  1050. }
  1051. Ext2FS::BlockIndex Ext2FS::first_block_index() const
  1052. {
  1053. return block_size() == 1024 ? 1 : 0;
  1054. }
  1055. Ext2FS::CachedBitmap& Ext2FS::get_bitmap_block(BlockIndex bitmap_block_index)
  1056. {
  1057. for (auto& cached_bitmap : m_cached_bitmaps) {
  1058. if (cached_bitmap->bitmap_block_index == bitmap_block_index)
  1059. return *cached_bitmap;
  1060. }
  1061. auto block = KBuffer::create_with_size(block_size(), Region::Access::Read | Region::Access::Write, "Ext2FS: Cached bitmap block");
  1062. bool success = read_block(bitmap_block_index, block.data());
  1063. ASSERT(success);
  1064. m_cached_bitmaps.append(make<CachedBitmap>(bitmap_block_index, move(block)));
  1065. return *m_cached_bitmaps.last();
  1066. }
  1067. bool Ext2FS::set_block_allocation_state(BlockIndex block_index, bool new_state)
  1068. {
  1069. ASSERT(block_index != 0);
  1070. LOCKER(m_lock);
  1071. #ifdef EXT2_DEBUG
  1072. dbg() << "Ext2FS: set_block_allocation_state(block=" << block_index << ", state=" << String::format("%u", new_state) << ")";
  1073. #endif
  1074. GroupIndex group_index = group_index_from_block_index(block_index);
  1075. auto& bgd = group_descriptor(group_index);
  1076. BlockIndex index_in_group = (block_index - first_block_index()) - ((group_index - 1) * blocks_per_group());
  1077. unsigned bit_index = index_in_group % blocks_per_group();
  1078. auto& cached_bitmap = get_bitmap_block(bgd.bg_block_bitmap);
  1079. bool current_state = cached_bitmap.bitmap(blocks_per_group()).get(bit_index);
  1080. #ifdef EXT2_DEBUG
  1081. dbg() << "Ext2FS: block " << block_index << " state: " << String::format("%u", current_state) << " -> " << String::format("%u", new_state) << " (in bitmap block " << bgd.bg_block_bitmap << ")";
  1082. #endif
  1083. if (current_state == new_state) {
  1084. ASSERT_NOT_REACHED();
  1085. return true;
  1086. }
  1087. cached_bitmap.bitmap(blocks_per_group()).set(bit_index, new_state);
  1088. cached_bitmap.dirty = true;
  1089. // Update superblock
  1090. #ifdef EXT2_DEBUG
  1091. dbg() << "Ext2FS: superblock free block count " << m_super_block.s_free_blocks_count << " -> " << (m_super_block.s_free_blocks_count - 1);
  1092. #endif
  1093. if (new_state)
  1094. --m_super_block.s_free_blocks_count;
  1095. else
  1096. ++m_super_block.s_free_blocks_count;
  1097. m_super_block_dirty = true;
  1098. // Update BGD
  1099. auto& mutable_bgd = const_cast<ext2_group_desc&>(bgd);
  1100. if (new_state)
  1101. --mutable_bgd.bg_free_blocks_count;
  1102. else
  1103. ++mutable_bgd.bg_free_blocks_count;
  1104. #ifdef EXT2_DEBUG
  1105. dbg() << "Ext2FS: group " << group_index << " free block count " << bgd.bg_free_blocks_count << " -> " << (bgd.bg_free_blocks_count - 1);
  1106. #endif
  1107. m_block_group_descriptors_dirty = true;
  1108. return true;
  1109. }
  1110. KResult Ext2FS::create_directory(InodeIdentifier parent_id, const String& name, mode_t mode, uid_t uid, gid_t gid)
  1111. {
  1112. LOCKER(m_lock);
  1113. ASSERT(parent_id.fsid() == fsid());
  1114. // Fix up the mode to definitely be a directory.
  1115. // FIXME: This is a bit on the hackish side.
  1116. mode &= ~0170000;
  1117. mode |= 0040000;
  1118. // NOTE: When creating a new directory, make the size 1 block.
  1119. // There's probably a better strategy here, but this works for now.
  1120. auto inode_or_error = create_inode(parent_id, name, mode, block_size(), 0, uid, gid);
  1121. if (inode_or_error.is_error())
  1122. return inode_or_error.error();
  1123. auto& inode = inode_or_error.value();
  1124. #ifdef EXT2_DEBUG
  1125. dbg() << "Ext2FS: create_directory: created new directory named '" << name << "' with inode " << inode->identifier();
  1126. #endif
  1127. Vector<DirectoryEntry> entries;
  1128. entries.empend(".", inode->identifier(), EXT2_FT_DIR);
  1129. entries.empend("..", parent_id, EXT2_FT_DIR);
  1130. bool success = static_cast<Ext2FSInode&>(*inode).write_directory(entries);
  1131. ASSERT(success);
  1132. auto parent_inode = get_inode(parent_id);
  1133. auto result = parent_inode->increment_link_count();
  1134. if (result.is_error())
  1135. return result;
  1136. auto& bgd = const_cast<ext2_group_desc&>(group_descriptor(group_index_from_inode(inode->identifier().index())));
  1137. ++bgd.bg_used_dirs_count;
  1138. #ifdef EXT2_DEBUG
  1139. dbg() << "Ext2FS: incremented bg_used_dirs_count " << bgd.bg_used_dirs_count - 1 << " -> " << bgd.bg_used_dirs_count;
  1140. #endif
  1141. m_block_group_descriptors_dirty = true;
  1142. return KSuccess;
  1143. }
  1144. 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)
  1145. {
  1146. LOCKER(m_lock);
  1147. ASSERT(parent_id.fsid() == fsid());
  1148. auto parent_inode = get_inode(parent_id);
  1149. ASSERT(parent_inode);
  1150. if (static_cast<const Ext2FSInode&>(*parent_inode).m_raw_inode.i_links_count == 0)
  1151. return KResult(-ENOENT);
  1152. #ifdef EXT2_DEBUG
  1153. dbg() << "Ext2FS: Adding inode '" << name << "' (mode " << String::format("%o", mode) << ") to parent directory " << parent_inode->identifier();
  1154. #endif
  1155. size_t needed_blocks = ceil_div(size, block_size());
  1156. if ((size_t)needed_blocks > super_block().s_free_blocks_count) {
  1157. dbg() << "Ext2FS: create_inode: not enough free blocks";
  1158. return KResult(-ENOSPC);
  1159. }
  1160. // NOTE: This doesn't commit the inode allocation just yet!
  1161. auto inode_id = find_a_free_inode(0, size);
  1162. if (!inode_id) {
  1163. klog() << "Ext2FS: create_inode: allocate_inode failed";
  1164. return KResult(-ENOSPC);
  1165. }
  1166. // Try adding it to the directory first, in case the name is already in use.
  1167. auto result = parent_inode->add_child({ fsid(), inode_id }, name, mode);
  1168. if (result.is_error())
  1169. return result;
  1170. auto blocks = allocate_blocks(group_index_from_inode(inode_id), needed_blocks);
  1171. ASSERT(blocks.size() == needed_blocks);
  1172. // Looks like we're good, time to update the inode bitmap and group+global inode counters.
  1173. bool success = set_inode_allocation_state(inode_id, true);
  1174. ASSERT(success);
  1175. unsigned initial_links_count;
  1176. if (is_directory(mode))
  1177. initial_links_count = 2; // (parent directory + "." entry in self)
  1178. else
  1179. initial_links_count = 1;
  1180. struct timeval now;
  1181. kgettimeofday(now);
  1182. ext2_inode e2inode;
  1183. memset(&e2inode, 0, sizeof(ext2_inode));
  1184. e2inode.i_mode = mode;
  1185. e2inode.i_uid = uid;
  1186. e2inode.i_gid = gid;
  1187. e2inode.i_size = size;
  1188. e2inode.i_atime = now.tv_sec;
  1189. e2inode.i_ctime = now.tv_sec;
  1190. e2inode.i_mtime = now.tv_sec;
  1191. e2inode.i_dtime = 0;
  1192. e2inode.i_links_count = initial_links_count;
  1193. if (is_character_device(mode))
  1194. e2inode.i_block[0] = dev;
  1195. else if (is_block_device(mode))
  1196. e2inode.i_block[1] = dev;
  1197. success = write_block_list_for_inode(inode_id, e2inode, blocks);
  1198. ASSERT(success);
  1199. #ifdef EXT2_DEBUG
  1200. dbg() << "Ext2FS: writing initial metadata for inode " << inode_id;
  1201. #endif
  1202. e2inode.i_flags = 0;
  1203. success = write_ext2_inode(inode_id, e2inode);
  1204. ASSERT(success);
  1205. // We might have cached the fact that this inode didn't exist. Wipe the slate.
  1206. m_inode_cache.remove(inode_id);
  1207. auto inode = get_inode({ fsid(), inode_id });
  1208. // If we've already computed a block list, no sense in throwing it away.
  1209. static_cast<Ext2FSInode&>(*inode).m_block_list = move(blocks);
  1210. return inode.release_nonnull();
  1211. }
  1212. void Ext2FSInode::populate_lookup_cache() const
  1213. {
  1214. LOCKER(m_lock);
  1215. if (!m_lookup_cache.is_empty())
  1216. return;
  1217. HashMap<String, unsigned> children;
  1218. traverse_as_directory([&children](auto& entry) {
  1219. children.set(String(entry.name, entry.name_length), entry.inode.index());
  1220. return true;
  1221. });
  1222. if (!m_lookup_cache.is_empty())
  1223. return;
  1224. m_lookup_cache = move(children);
  1225. }
  1226. RefPtr<Inode> Ext2FSInode::lookup(StringView name)
  1227. {
  1228. ASSERT(is_directory());
  1229. populate_lookup_cache();
  1230. LOCKER(m_lock);
  1231. auto it = m_lookup_cache.find(name.hash(), [&](auto& entry) { return entry.key == name; });
  1232. if (it != m_lookup_cache.end())
  1233. return fs().get_inode({ fsid(), (*it).value });
  1234. return {};
  1235. }
  1236. void Ext2FSInode::one_ref_left()
  1237. {
  1238. // FIXME: I would like to not live forever, but uncached Ext2FS is fucking painful right now.
  1239. }
  1240. int Ext2FSInode::set_atime(time_t t)
  1241. {
  1242. LOCKER(m_lock);
  1243. if (fs().is_readonly())
  1244. return -EROFS;
  1245. m_raw_inode.i_atime = t;
  1246. set_metadata_dirty(true);
  1247. return 0;
  1248. }
  1249. int Ext2FSInode::set_ctime(time_t t)
  1250. {
  1251. LOCKER(m_lock);
  1252. if (fs().is_readonly())
  1253. return -EROFS;
  1254. m_raw_inode.i_ctime = t;
  1255. set_metadata_dirty(true);
  1256. return 0;
  1257. }
  1258. int Ext2FSInode::set_mtime(time_t t)
  1259. {
  1260. LOCKER(m_lock);
  1261. if (fs().is_readonly())
  1262. return -EROFS;
  1263. m_raw_inode.i_mtime = t;
  1264. set_metadata_dirty(true);
  1265. return 0;
  1266. }
  1267. KResult Ext2FSInode::increment_link_count()
  1268. {
  1269. LOCKER(m_lock);
  1270. if (fs().is_readonly())
  1271. return KResult(-EROFS);
  1272. if (m_raw_inode.i_links_count == max_link_count)
  1273. return KResult(-EMLINK);
  1274. ++m_raw_inode.i_links_count;
  1275. set_metadata_dirty(true);
  1276. return KSuccess;
  1277. }
  1278. KResult Ext2FSInode::decrement_link_count()
  1279. {
  1280. LOCKER(m_lock);
  1281. if (fs().is_readonly())
  1282. return KResult(-EROFS);
  1283. ASSERT(m_raw_inode.i_links_count);
  1284. --m_raw_inode.i_links_count;
  1285. if (ref_count() == 1 && m_raw_inode.i_links_count == 0)
  1286. fs().uncache_inode(index());
  1287. set_metadata_dirty(true);
  1288. return KSuccess;
  1289. }
  1290. void Ext2FS::uncache_inode(InodeIndex index)
  1291. {
  1292. LOCKER(m_lock);
  1293. m_inode_cache.remove(index);
  1294. }
  1295. size_t Ext2FSInode::directory_entry_count() const
  1296. {
  1297. ASSERT(is_directory());
  1298. LOCKER(m_lock);
  1299. populate_lookup_cache();
  1300. return m_lookup_cache.size();
  1301. }
  1302. KResult Ext2FSInode::chmod(mode_t mode)
  1303. {
  1304. LOCKER(m_lock);
  1305. if (m_raw_inode.i_mode == mode)
  1306. return KSuccess;
  1307. m_raw_inode.i_mode = mode;
  1308. set_metadata_dirty(true);
  1309. return KSuccess;
  1310. }
  1311. KResult Ext2FSInode::chown(uid_t uid, gid_t gid)
  1312. {
  1313. LOCKER(m_lock);
  1314. if (m_raw_inode.i_uid == uid && m_raw_inode.i_gid == gid)
  1315. return KSuccess;
  1316. m_raw_inode.i_uid = uid;
  1317. m_raw_inode.i_gid = gid;
  1318. set_metadata_dirty(true);
  1319. return KSuccess;
  1320. }
  1321. KResult Ext2FSInode::truncate(u64 size)
  1322. {
  1323. LOCKER(m_lock);
  1324. if (static_cast<u64>(m_raw_inode.i_size) == size)
  1325. return KSuccess;
  1326. auto result = resize(size);
  1327. if (result.is_error())
  1328. return result;
  1329. set_metadata_dirty(true);
  1330. return KSuccess;
  1331. }
  1332. unsigned Ext2FS::total_block_count() const
  1333. {
  1334. LOCKER(m_lock);
  1335. return super_block().s_blocks_count;
  1336. }
  1337. unsigned Ext2FS::free_block_count() const
  1338. {
  1339. LOCKER(m_lock);
  1340. return super_block().s_free_blocks_count;
  1341. }
  1342. unsigned Ext2FS::total_inode_count() const
  1343. {
  1344. LOCKER(m_lock);
  1345. return super_block().s_inodes_count;
  1346. }
  1347. unsigned Ext2FS::free_inode_count() const
  1348. {
  1349. LOCKER(m_lock);
  1350. return super_block().s_free_inodes_count;
  1351. }
  1352. KResult Ext2FS::prepare_to_unmount() const
  1353. {
  1354. LOCKER(m_lock);
  1355. for (auto& it : m_inode_cache) {
  1356. if (it.value->ref_count() > 1)
  1357. return KResult(-EBUSY);
  1358. }
  1359. m_inode_cache.clear();
  1360. return KSuccess;
  1361. }
  1362. }