Ext2FileSystem.cpp 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294
  1. #include "Ext2FileSystem.h"
  2. #include "ext2_fs.h"
  3. #include "UnixTypes.h"
  4. #include "RTC.h"
  5. #include <AK/Bitmap.h>
  6. #include <AK/StdLibExtras.h>
  7. #include <AK/kmalloc.h>
  8. #include <AK/ktime.h>
  9. #include <AK/kstdio.h>
  10. #include <AK/BufferStream.h>
  11. #include <LibC/errno_numbers.h>
  12. //#define EXT2_DEBUG
  13. RetainPtr<Ext2FS> Ext2FS::create(RetainPtr<DiskDevice>&& device)
  14. {
  15. return adopt(*new Ext2FS(move(device)));
  16. }
  17. Ext2FS::Ext2FS(RetainPtr<DiskDevice>&& device)
  18. : DiskBackedFS(move(device))
  19. {
  20. }
  21. Ext2FS::~Ext2FS()
  22. {
  23. }
  24. ByteBuffer Ext2FS::read_super_block() const
  25. {
  26. auto buffer = ByteBuffer::create_uninitialized(1024);
  27. device().read_block(2, buffer.pointer());
  28. device().read_block(3, buffer.offset_pointer(512));
  29. return buffer;
  30. }
  31. bool Ext2FS::write_super_block(const ext2_super_block& sb)
  32. {
  33. const byte* raw = (const byte*)&sb;
  34. bool success;
  35. success = device().write_block(2, raw);
  36. ASSERT(success);
  37. success = device().write_block(3, raw + 512);
  38. ASSERT(success);
  39. // FIXME: This is an ugly way to refresh the superblock cache. :-|
  40. super_block();
  41. return true;
  42. }
  43. unsigned Ext2FS::first_block_of_group(unsigned groupIndex) const
  44. {
  45. return super_block().s_first_data_block + (groupIndex * super_block().s_blocks_per_group);
  46. }
  47. const ext2_super_block& Ext2FS::super_block() const
  48. {
  49. if (!m_cached_super_block)
  50. m_cached_super_block = read_super_block();
  51. return *reinterpret_cast<ext2_super_block*>(m_cached_super_block.pointer());
  52. }
  53. const ext2_group_desc& Ext2FS::group_descriptor(unsigned groupIndex) const
  54. {
  55. // FIXME: Should this fail gracefully somehow?
  56. ASSERT(groupIndex <= m_block_group_count);
  57. if (!m_cached_group_descriptor_table) {
  58. unsigned blocks_to_read = ceil_div(m_block_group_count * (unsigned)sizeof(ext2_group_desc), block_size());
  59. unsigned first_block_of_bgdt = block_size() == 1024 ? 2 : 1;
  60. #ifdef EXT2_DEBUG
  61. kprintf("ext2fs: block group count: %u, blocks-to-read: %u\n", m_block_group_count, blocks_to_read);
  62. kprintf("ext2fs: first block of BGDT: %u\n", first_block_of_bgdt);
  63. #endif
  64. m_cached_group_descriptor_table = read_blocks(first_block_of_bgdt, blocks_to_read);
  65. }
  66. return reinterpret_cast<ext2_group_desc*>(m_cached_group_descriptor_table.pointer())[groupIndex - 1];
  67. }
  68. bool Ext2FS::initialize()
  69. {
  70. auto& super_block = this->super_block();
  71. #ifdef EXT2_DEBUG
  72. kprintf("ext2fs: super block magic: %x (super block size: %u)\n", super_block.s_magic, sizeof(ext2_super_block));
  73. #endif
  74. if (super_block.s_magic != EXT2_SUPER_MAGIC)
  75. return false;
  76. #ifdef EXT2_DEBUG
  77. kprintf("ext2fs: %u inodes, %u blocks\n", super_block.s_inodes_count, super_block.s_blocks_count);
  78. kprintf("ext2fs: block size = %u\n", EXT2_BLOCK_SIZE(&super_block));
  79. kprintf("ext2fs: first data block = %u\n", super_block.s_first_data_block);
  80. kprintf("ext2fs: inodes per block = %u\n", inodes_per_block());
  81. kprintf("ext2fs: inodes per group = %u\n", inodes_per_group());
  82. kprintf("ext2fs: free inodes = %u\n", super_block.s_free_inodes_count);
  83. kprintf("ext2fs: desc per block = %u\n", EXT2_DESC_PER_BLOCK(&super_block));
  84. kprintf("ext2fs: desc size = %u\n", EXT2_DESC_SIZE(&super_block));
  85. #endif
  86. set_block_size(EXT2_BLOCK_SIZE(&super_block));
  87. m_block_group_count = ceil_div(super_block.s_blocks_count, super_block.s_blocks_per_group);
  88. if (m_block_group_count == 0) {
  89. kprintf("ext2fs: no block groups :(\n");
  90. return false;
  91. }
  92. // Preheat the BGD cache.
  93. group_descriptor(0);
  94. #ifdef EXT2_DEBUG
  95. for (unsigned i = 1; i <= m_block_group_count; ++i) {
  96. auto& group = group_descriptor(i);
  97. kprintf("ext2fs: group[%u] { block_bitmap: %u, inode_bitmap: %u, inode_table: %u }\n",
  98. i,
  99. group.bg_block_bitmap,
  100. group.bg_inode_bitmap,
  101. group.bg_inode_table);
  102. }
  103. #endif
  104. return true;
  105. }
  106. const char* Ext2FS::class_name() const
  107. {
  108. return "Ext2FS";
  109. }
  110. InodeIdentifier Ext2FS::root_inode() const
  111. {
  112. return { fsid(), EXT2_ROOT_INO };
  113. }
  114. ByteBuffer Ext2FS::read_block_containing_inode(unsigned inode, unsigned& block_index, unsigned& offset) const
  115. {
  116. auto& super_block = this->super_block();
  117. if (inode != EXT2_ROOT_INO && inode < EXT2_FIRST_INO(&super_block))
  118. return { };
  119. if (inode > super_block.s_inodes_count)
  120. return { };
  121. auto& bgd = group_descriptor(group_index_from_inode(inode));
  122. offset = ((inode - 1) % inodes_per_group()) * inode_size();
  123. block_index = bgd.bg_inode_table + (offset >> EXT2_BLOCK_SIZE_BITS(&super_block));
  124. offset &= block_size() - 1;
  125. return read_block(block_index);
  126. }
  127. Ext2FS::BlockListShape Ext2FS::compute_block_list_shape(unsigned blocks)
  128. {
  129. BlockListShape shape;
  130. const unsigned entries_per_block = EXT2_ADDR_PER_BLOCK(&super_block());
  131. unsigned blocks_remaining = blocks;
  132. shape.direct_blocks = min((unsigned)EXT2_NDIR_BLOCKS, blocks_remaining);
  133. blocks_remaining -= shape.direct_blocks;
  134. if (!blocks_remaining)
  135. return shape;
  136. shape.indirect_blocks = min(blocks_remaining, entries_per_block);
  137. blocks_remaining -= shape.indirect_blocks;
  138. shape.meta_blocks += 1;
  139. if (!blocks_remaining)
  140. return shape;
  141. ASSERT_NOT_REACHED();
  142. // FIXME: Support dind/tind blocks.
  143. shape.doubly_indirect_blocks = min(blocks_remaining, entries_per_block * entries_per_block);
  144. blocks_remaining -= shape.doubly_indirect_blocks;
  145. if (!blocks_remaining)
  146. return shape;
  147. shape.triply_indirect_blocks = min(blocks_remaining, entries_per_block * entries_per_block * entries_per_block);
  148. blocks_remaining -= shape.triply_indirect_blocks;
  149. // FIXME: What do we do for files >= 16GB?
  150. ASSERT(!blocks_remaining);
  151. return shape;
  152. }
  153. bool Ext2FS::write_block_list_for_inode(InodeIndex inode_index, ext2_inode& e2inode, const Vector<BlockIndex>& blocks)
  154. {
  155. dbgprintf("Ext2FS: writing %u block(s) to i_block array\n", min((size_t)EXT2_NDIR_BLOCKS, blocks.size()));
  156. auto old_shape = compute_block_list_shape(e2inode.i_blocks / (2 << super_block().s_log_block_size));
  157. auto new_shape = compute_block_list_shape(blocks.size());
  158. Vector<BlockIndex> new_meta_blocks;
  159. if (new_shape.meta_blocks > old_shape.meta_blocks) {
  160. new_meta_blocks = allocate_blocks(group_index_from_inode(inode_index), new_shape.meta_blocks - old_shape.meta_blocks);
  161. for (auto bi : new_meta_blocks)
  162. set_block_allocation_state(group_index_from_inode(inode_index), bi, true);
  163. }
  164. e2inode.i_blocks = (blocks.size() + new_shape.meta_blocks) * (block_size() / 512);
  165. unsigned output_block_index = 0;
  166. unsigned remaining_blocks = blocks.size();
  167. for (unsigned i = 0; i < new_shape.direct_blocks; ++i) {
  168. e2inode.i_block[i] = blocks[output_block_index++];
  169. --remaining_blocks;
  170. }
  171. write_ext2_inode(inode_index, e2inode);
  172. if (!remaining_blocks)
  173. return true;
  174. if (!e2inode.i_block[EXT2_IND_BLOCK]) {
  175. e2inode.i_block[EXT2_IND_BLOCK] = new_meta_blocks.take_last();
  176. write_ext2_inode(inode_index, e2inode);
  177. }
  178. {
  179. dbgprintf("Ext2FS: Writing out indirect blockptr block for inode %u\n", inode_index);
  180. auto block_contents = ByteBuffer::create_uninitialized(block_size());
  181. BufferStream stream(block_contents);
  182. ASSERT(new_shape.indirect_blocks <= EXT2_ADDR_PER_BLOCK(&super_block()));
  183. for (unsigned i = 0; i < new_shape.indirect_blocks; ++i) {
  184. stream << blocks[output_block_index++];
  185. --remaining_blocks;
  186. }
  187. stream.fill_to_end(0);
  188. write_block(e2inode.i_block[EXT2_IND_BLOCK], block_contents);
  189. }
  190. if (!remaining_blocks)
  191. return true;
  192. // FIXME: Implement!
  193. ASSERT_NOT_REACHED();
  194. }
  195. Vector<unsigned> Ext2FS::block_list_for_inode(const ext2_inode& e2inode, bool include_block_list_blocks) const
  196. {
  197. unsigned entries_per_block = EXT2_ADDR_PER_BLOCK(&super_block());
  198. // NOTE: i_blocks is number of 512-byte blocks, not number of fs-blocks.
  199. unsigned block_count = e2inode.i_blocks / (block_size() / 512);
  200. unsigned blocksRemaining = block_count;
  201. Vector<unsigned> list;
  202. if (include_block_list_blocks) {
  203. // This seems like an excessive over-estimate but w/e.
  204. list.ensure_capacity(blocksRemaining * 2);
  205. } else {
  206. list.ensure_capacity(blocksRemaining);
  207. }
  208. unsigned direct_count = min(block_count, (unsigned)EXT2_NDIR_BLOCKS);
  209. for (unsigned i = 0; i < direct_count; ++i) {
  210. list.unchecked_append(e2inode.i_block[i]);
  211. --blocksRemaining;
  212. }
  213. if (!blocksRemaining)
  214. return list;
  215. auto process_block_array = [&] (unsigned array_block_index, auto&& callback) {
  216. if (include_block_list_blocks)
  217. callback(array_block_index);
  218. auto array_block = read_block(array_block_index);
  219. ASSERT(array_block);
  220. auto* array = reinterpret_cast<const __u32*>(array_block.pointer());
  221. unsigned count = min(blocksRemaining, entries_per_block);
  222. for (unsigned i = 0; i < count; ++i) {
  223. if (!array[i]) {
  224. blocksRemaining = 0;
  225. return;
  226. }
  227. callback(array[i]);
  228. --blocksRemaining;
  229. }
  230. };
  231. process_block_array(e2inode.i_block[EXT2_IND_BLOCK], [&] (unsigned entry) {
  232. list.unchecked_append(entry);
  233. });
  234. if (!blocksRemaining)
  235. return list;
  236. process_block_array(e2inode.i_block[EXT2_DIND_BLOCK], [&] (unsigned entry) {
  237. process_block_array(entry, [&] (unsigned entry) {
  238. list.unchecked_append(entry);
  239. });
  240. });
  241. if (!blocksRemaining)
  242. return list;
  243. process_block_array(e2inode.i_block[EXT2_TIND_BLOCK], [&] (unsigned entry) {
  244. process_block_array(entry, [&] (unsigned entry) {
  245. process_block_array(entry, [&] (unsigned entry) {
  246. list.unchecked_append(entry);
  247. });
  248. });
  249. });
  250. return list;
  251. }
  252. void Ext2FS::free_inode(Ext2FSInode& inode)
  253. {
  254. ASSERT(inode.m_raw_inode.i_links_count == 0);
  255. dbgprintf("Ext2FS: inode %u has no more links, time to delete!\n", inode.index());
  256. inode.m_raw_inode.i_dtime = RTC::now();
  257. write_ext2_inode(inode.index(), inode.m_raw_inode);
  258. auto block_list = block_list_for_inode(inode.m_raw_inode, true);
  259. auto group_index = group_index_from_inode(inode.index());
  260. for (auto block_index : block_list)
  261. set_block_allocation_state(group_index, block_index, false);
  262. set_inode_allocation_state(inode.index(), false);
  263. if (inode.is_directory()) {
  264. auto& bgd = const_cast<ext2_group_desc&>(group_descriptor(group_index_from_inode(inode.index())));
  265. --bgd.bg_used_dirs_count;
  266. dbgprintf("Ext2FS: decremented bg_used_dirs_count %u -> %u\n", bgd.bg_used_dirs_count - 1, bgd.bg_used_dirs_count);
  267. flush_block_group_descriptor_table();
  268. }
  269. }
  270. void Ext2FS::flush_block_group_descriptor_table()
  271. {
  272. unsigned blocks_to_write = ceil_div(m_block_group_count * (unsigned)sizeof(ext2_group_desc), block_size());
  273. unsigned first_block_of_bgdt = block_size() == 1024 ? 2 : 1;
  274. write_blocks(first_block_of_bgdt, blocks_to_write, m_cached_group_descriptor_table);
  275. }
  276. Ext2FSInode::Ext2FSInode(Ext2FS& fs, unsigned index)
  277. : Inode(fs, index)
  278. {
  279. }
  280. Ext2FSInode::~Ext2FSInode()
  281. {
  282. if (m_raw_inode.i_links_count == 0)
  283. fs().free_inode(*this);
  284. }
  285. InodeMetadata Ext2FSInode::metadata() const
  286. {
  287. InodeMetadata metadata;
  288. metadata.inode = identifier();
  289. metadata.size = m_raw_inode.i_size;
  290. metadata.mode = m_raw_inode.i_mode;
  291. metadata.uid = m_raw_inode.i_uid;
  292. metadata.gid = m_raw_inode.i_gid;
  293. metadata.link_count = m_raw_inode.i_links_count;
  294. metadata.atime = m_raw_inode.i_atime;
  295. metadata.ctime = m_raw_inode.i_ctime;
  296. metadata.mtime = m_raw_inode.i_mtime;
  297. metadata.dtime = m_raw_inode.i_dtime;
  298. metadata.block_size = fs().block_size();
  299. metadata.block_count = m_raw_inode.i_blocks;
  300. if (::is_block_device(m_raw_inode.i_mode) || ::is_character_device(m_raw_inode.i_mode)) {
  301. unsigned dev = m_raw_inode.i_block[0];
  302. metadata.major_device = (dev & 0xfff00) >> 8;
  303. metadata.minor_device = (dev & 0xff) | ((dev >> 12) & 0xfff00);
  304. }
  305. return metadata;
  306. }
  307. void Ext2FSInode::flush_metadata()
  308. {
  309. dbgprintf("Ext2FSInode: flush_metadata for inode %u\n", index());
  310. fs().write_ext2_inode(index(), m_raw_inode);
  311. if (is_directory()) {
  312. // Unless we're about to go away permanently, invalidate the lookup cache.
  313. if (m_raw_inode.i_links_count != 0) {
  314. LOCKER(m_lock);
  315. // FIXME: This invalidation is way too hardcore. It's sad to throw away the whole cache.
  316. m_lookup_cache.clear();
  317. }
  318. }
  319. set_metadata_dirty(false);
  320. }
  321. RetainPtr<Inode> Ext2FS::get_inode(InodeIdentifier inode) const
  322. {
  323. ASSERT(inode.fsid() == fsid());
  324. {
  325. LOCKER(m_inode_cache_lock);
  326. auto it = m_inode_cache.find(inode.index());
  327. if (it != m_inode_cache.end())
  328. return (*it).value;
  329. }
  330. if (!get_inode_allocation_state(inode.index())) {
  331. LOCKER(m_inode_cache_lock);
  332. m_inode_cache.set(inode.index(), nullptr);
  333. return nullptr;
  334. }
  335. unsigned block_index;
  336. unsigned offset;
  337. auto block = read_block_containing_inode(inode.index(), block_index, offset);
  338. if (!block)
  339. return { };
  340. LOCKER(m_inode_cache_lock);
  341. auto it = m_inode_cache.find(inode.index());
  342. if (it != m_inode_cache.end())
  343. return (*it).value;
  344. auto new_inode = adopt(*new Ext2FSInode(const_cast<Ext2FS&>(*this), inode.index()));
  345. memcpy(&new_inode->m_raw_inode, reinterpret_cast<ext2_inode*>(block.offset_pointer(offset)), inode_size());
  346. m_inode_cache.set(inode.index(), new_inode.copy_ref());
  347. return new_inode;
  348. }
  349. ssize_t Ext2FSInode::read_bytes(off_t offset, size_t count, byte* buffer, FileDescriptor*) const
  350. {
  351. ASSERT(offset >= 0);
  352. if (m_raw_inode.i_size == 0)
  353. return 0;
  354. // Symbolic links shorter than 60 characters are store inline inside the i_block array.
  355. // This avoids wasting an entire block on short links. (Most links are short.)
  356. static const unsigned max_inline_symlink_length = 60;
  357. if (is_symlink() && size() < max_inline_symlink_length) {
  358. ssize_t nread = min((off_t)size() - offset, static_cast<off_t>(count));
  359. memcpy(buffer, m_raw_inode.i_block + offset, nread);
  360. return nread;
  361. }
  362. if (m_block_list.is_empty()) {
  363. auto block_list = fs().block_list_for_inode(m_raw_inode);
  364. LOCKER(m_lock);
  365. if (m_block_list.size() != block_list.size())
  366. m_block_list = move(block_list);
  367. }
  368. if (m_block_list.is_empty()) {
  369. kprintf("ext2fs: read_bytes: empty block list for inode %u\n", index());
  370. return -EIO;
  371. }
  372. const size_t block_size = fs().block_size();
  373. dword first_block_logical_index = offset / block_size;
  374. dword last_block_logical_index = (offset + count) / block_size;
  375. if (last_block_logical_index >= m_block_list.size())
  376. last_block_logical_index = m_block_list.size() - 1;
  377. dword offset_into_first_block = offset % block_size;
  378. ssize_t nread = 0;
  379. size_t remaining_count = min((off_t)count, (off_t)size() - offset);
  380. byte* out = buffer;
  381. #ifdef EXT2_DEBUG
  382. kprintf("Ext2FS: Reading up to %u bytes %d bytes into inode %u:%u to %p\n", count, offset, identifier().fsid(), identifier().index(), buffer);
  383. //kprintf("ok let's do it, read(%u, %u) -> blocks %u thru %u, oifb: %u\n", offset, count, first_block_logical_index, last_block_logical_index, offset_into_first_block);
  384. #endif
  385. for (dword bi = first_block_logical_index; remaining_count && bi <= last_block_logical_index; ++bi) {
  386. auto block = fs().read_block(m_block_list[bi]);
  387. if (!block) {
  388. kprintf("ext2fs: read_bytes: read_block(%u) failed (lbi: %u)\n", m_block_list[bi], bi);
  389. return -EIO;
  390. }
  391. dword offset_into_block = (bi == first_block_logical_index) ? offset_into_first_block : 0;
  392. dword num_bytes_to_copy = min(block_size - offset_into_block, remaining_count);
  393. memcpy(out, block.pointer() + offset_into_block, num_bytes_to_copy);
  394. remaining_count -= num_bytes_to_copy;
  395. nread += num_bytes_to_copy;
  396. out += num_bytes_to_copy;
  397. }
  398. return nread;
  399. }
  400. ssize_t Ext2FSInode::write_bytes(off_t offset, size_t count, const byte* data, FileDescriptor*)
  401. {
  402. LOCKER(m_lock);
  403. // FIXME: Support writing to symlink inodes.
  404. ASSERT(!is_symlink());
  405. ASSERT(offset >= 0);
  406. const size_t block_size = fs().block_size();
  407. size_t new_size = max(static_cast<size_t>(offset) + count, size());
  408. unsigned blocks_needed_before = ceil_div(size(), block_size);
  409. unsigned blocks_needed_after = ceil_div(new_size, block_size);
  410. auto block_list = fs().block_list_for_inode(m_raw_inode);
  411. if (blocks_needed_after > blocks_needed_before) {
  412. auto new_blocks = fs().allocate_blocks(fs().group_index_from_inode(index()), blocks_needed_after - blocks_needed_before);
  413. for (auto new_block_index : new_blocks)
  414. fs().set_block_allocation_state(fs().group_index_from_inode(index()), new_block_index, true);
  415. block_list.append(move(new_blocks));
  416. } else if (blocks_needed_after < blocks_needed_before) {
  417. // FIXME: Implement block list shrinking!
  418. ASSERT_NOT_REACHED();
  419. }
  420. dword first_block_logical_index = offset / block_size;
  421. dword last_block_logical_index = (offset + count) / block_size;
  422. if (last_block_logical_index >= block_list.size())
  423. last_block_logical_index = block_list.size() - 1;
  424. dword offset_into_first_block = offset % block_size;
  425. ssize_t nwritten = 0;
  426. size_t remaining_count = min((off_t)count, (off_t)new_size - offset);
  427. const byte* in = data;
  428. #ifdef EXT2_DEBUG
  429. dbgprintf("Ext2FSInode::write_bytes: Writing %u bytes %d bytes into inode %u:%u from %p\n", count, offset, fsid(), index(), data);
  430. #endif
  431. auto buffer_block = ByteBuffer::create_uninitialized(block_size);
  432. for (dword bi = first_block_logical_index; remaining_count && bi <= last_block_logical_index; ++bi) {
  433. dword offset_into_block = (bi == first_block_logical_index) ? offset_into_first_block : 0;
  434. dword num_bytes_to_copy = min(block_size - offset_into_block, remaining_count);
  435. ByteBuffer block;
  436. if (offset_into_block != 0) {
  437. block = fs().read_block(block_list[bi]);
  438. if (!block) {
  439. kprintf("Ext2FSInode::write_bytes: read_block(%u) failed (lbi: %u)\n", block_list[bi], bi);
  440. return -EIO;
  441. }
  442. } else
  443. block = buffer_block;
  444. memcpy(block.pointer() + offset_into_block, in, num_bytes_to_copy);
  445. if (offset_into_block == 0 && !num_bytes_to_copy)
  446. memset(block.pointer() + num_bytes_to_copy, 0, block_size - num_bytes_to_copy);
  447. #ifdef EXT2_DEBUG
  448. dbgprintf("Ext2FSInode::write_bytes: writing block %u (offset_into_block: %u)\n", block_list[bi], offset_into_block);
  449. #endif
  450. bool success = fs().write_block(block_list[bi], block);
  451. if (!success) {
  452. kprintf("Ext2FSInode::write_bytes: write_block(%u) failed (lbi: %u)\n", block_list[bi], bi);
  453. return -EIO;
  454. }
  455. remaining_count -= num_bytes_to_copy;
  456. nwritten += num_bytes_to_copy;
  457. in += num_bytes_to_copy;
  458. }
  459. bool success = fs().write_block_list_for_inode(index(), m_raw_inode, block_list);
  460. ASSERT(success);
  461. m_raw_inode.i_size = new_size;
  462. fs().write_ext2_inode(index(), m_raw_inode);
  463. #ifdef EXT2_DEBUG
  464. dbgprintf("Ext2FSInode::write_bytes: after write, i_size=%u, i_blocks=%u (%u blocks in list)\n", m_raw_inode.i_size, m_raw_inode.i_blocks, block_list.size());
  465. #endif
  466. // NOTE: Make sure the cached block list is up to date!
  467. m_block_list = move(block_list);
  468. return nwritten;
  469. }
  470. bool Ext2FSInode::traverse_as_directory(Function<bool(const FS::DirectoryEntry&)> callback) const
  471. {
  472. ASSERT(metadata().is_directory());
  473. #ifdef EXT2_DEBUG
  474. kprintf("Ext2Inode::traverse_as_directory: inode=%u:\n", index());
  475. #endif
  476. auto buffer = read_entire();
  477. ASSERT(buffer);
  478. auto* entry = reinterpret_cast<ext2_dir_entry_2*>(buffer.pointer());
  479. while (entry < buffer.end_pointer()) {
  480. if (entry->inode != 0) {
  481. #ifdef EXT2_DEBUG
  482. kprintf("Ext2Inode::traverse_as_directory: %u, name_len: %u, rec_len: %u, file_type: %u, name: %s\n", entry->inode, entry->name_len, entry->rec_len, entry->file_type, String(entry->name, entry->name_len).characters());
  483. #endif
  484. if (!callback({ entry->name, entry->name_len, { fsid(), entry->inode }, entry->file_type }))
  485. break;
  486. }
  487. entry = (ext2_dir_entry_2*)((char*)entry + entry->rec_len);
  488. }
  489. return true;
  490. }
  491. bool Ext2FSInode::add_child(InodeIdentifier child_id, const String& name, byte file_type, int& error)
  492. {
  493. ASSERT(is_directory());
  494. //#ifdef EXT2_DEBUG
  495. dbgprintf("Ext2FS: Adding inode %u with name '%s' to directory %u\n", child_id.index(), name.characters(), index());
  496. //#endif
  497. Vector<FS::DirectoryEntry> entries;
  498. bool name_already_exists = false;
  499. traverse_as_directory([&] (auto& entry) {
  500. if (!strcmp(entry.name, name.characters())) {
  501. name_already_exists = true;
  502. return false;
  503. }
  504. entries.append(entry);
  505. return true;
  506. });
  507. if (name_already_exists) {
  508. kprintf("Ext2FS: Name '%s' already exists in directory inode %u\n", name.characters(), index());
  509. error = -EEXIST;
  510. return false;
  511. }
  512. entries.append({ name.characters(), name.length(), child_id, file_type });
  513. bool success = fs().write_directory_inode(index(), move(entries));
  514. if (success) {
  515. LOCKER(m_lock);
  516. m_lookup_cache.set(name, child_id.index());
  517. }
  518. return success;
  519. }
  520. bool Ext2FSInode::remove_child(const String& name, int& error)
  521. {
  522. #ifdef EXT2_DEBUG
  523. dbgprintf("Ext2FSInode::remove_child(%s) in inode %u\n", name.characters(), index());
  524. #endif
  525. ASSERT(is_directory());
  526. unsigned child_inode_index;
  527. {
  528. LOCKER(m_lock);
  529. auto it = m_lookup_cache.find(name);
  530. if (it == m_lookup_cache.end()) {
  531. error = -ENOENT;
  532. return false;
  533. }
  534. child_inode_index = (*it).value;
  535. }
  536. InodeIdentifier child_id { fsid(), child_inode_index };
  537. //#ifdef EXT2_DEBUG
  538. dbgprintf("Ext2FS: Removing '%s' in directory %u\n", name.characters(), index());
  539. //#endif
  540. Vector<FS::DirectoryEntry> entries;
  541. traverse_as_directory([&] (auto& entry) {
  542. if (entry.inode != child_id)
  543. entries.append(entry);
  544. return true;
  545. });
  546. bool success = fs().write_directory_inode(index(), move(entries));
  547. if (!success) {
  548. // FIXME: Plumb error from write_directory_inode().
  549. error = -EIO;
  550. return false;
  551. }
  552. {
  553. LOCKER(m_lock);
  554. m_lookup_cache.remove(name);
  555. }
  556. auto child_inode = fs().get_inode(child_id);
  557. child_inode->decrement_link_count();
  558. return success;
  559. }
  560. bool Ext2FS::write_directory_inode(unsigned directoryInode, Vector<DirectoryEntry>&& entries)
  561. {
  562. dbgprintf("Ext2FS: New directory inode %u contents to write:\n", directoryInode);
  563. unsigned directory_size = 0;
  564. for (auto& entry : entries) {
  565. //kprintf(" - %08u %s\n", entry.inode.index(), entry.name);
  566. directory_size += EXT2_DIR_REC_LEN(entry.name_length);
  567. }
  568. unsigned blocks_needed = ceil_div(directory_size, block_size());
  569. unsigned occupied_size = blocks_needed * block_size();
  570. dbgprintf("Ext2FS: directory size: %u (occupied: %u)\n", directory_size, occupied_size);
  571. auto directory_data = ByteBuffer::create_uninitialized(occupied_size);
  572. BufferStream stream(directory_data);
  573. for (unsigned i = 0; i < entries.size(); ++i) {
  574. auto& entry = entries[i];
  575. unsigned record_length = EXT2_DIR_REC_LEN(entry.name_length);
  576. if (i == entries.size() - 1)
  577. record_length += occupied_size - directory_size;
  578. dbgprintf("* inode: %u", entry.inode.index());
  579. dbgprintf(", name_len: %u", word(entry.name_length));
  580. dbgprintf(", rec_len: %u", word(record_length));
  581. dbgprintf(", file_type: %u", byte(entry.file_type));
  582. dbgprintf(", name: %s\n", entry.name);
  583. stream << dword(entry.inode.index());
  584. stream << word(record_length);
  585. stream << byte(entry.name_length);
  586. stream << byte(entry.file_type);
  587. stream << entry.name;
  588. unsigned padding = record_length - entry.name_length - 8;
  589. //dbgprintf(" *** pad %u bytes\n", padding);
  590. for (unsigned j = 0; j < padding; ++j) {
  591. stream << byte(0);
  592. }
  593. }
  594. stream.fill_to_end(0);
  595. #if 0
  596. kprintf("data to write (%u):\n", directory_data.size());
  597. for (unsigned i = 0; i < directory_data.size(); ++i) {
  598. kprintf("%02x ", directory_data[i]);
  599. if ((i + 1) % 8 == 0)
  600. kprintf(" ");
  601. if ((i + 1) % 16 == 0)
  602. kprintf("\n");
  603. }
  604. kprintf("\n");
  605. #endif
  606. auto directory_inode = get_inode({ fsid(), directoryInode });
  607. ssize_t nwritten = directory_inode->write_bytes(0, directory_data.size(), directory_data.pointer(), nullptr);
  608. return nwritten == directory_data.size();
  609. }
  610. unsigned Ext2FS::inodes_per_block() const
  611. {
  612. return EXT2_INODES_PER_BLOCK(&super_block());
  613. }
  614. unsigned Ext2FS::inodes_per_group() const
  615. {
  616. return EXT2_INODES_PER_GROUP(&super_block());
  617. }
  618. unsigned Ext2FS::inode_size() const
  619. {
  620. return EXT2_INODE_SIZE(&super_block());
  621. }
  622. unsigned Ext2FS::blocks_per_group() const
  623. {
  624. return EXT2_BLOCKS_PER_GROUP(&super_block());
  625. }
  626. void Ext2FS::dump_block_bitmap(unsigned groupIndex) const
  627. {
  628. ASSERT(groupIndex <= m_block_group_count);
  629. auto& bgd = group_descriptor(groupIndex);
  630. unsigned blocks_in_group = min(blocks_per_group(), super_block().s_blocks_count);
  631. unsigned block_count = ceil_div(blocks_in_group, 8u);
  632. auto bitmap_blocks = read_blocks(bgd.bg_block_bitmap, block_count);
  633. ASSERT(bitmap_blocks);
  634. kprintf("ext2fs: group[%u] block bitmap (bitmap occupies %u blocks):\n", groupIndex, block_count);
  635. auto bitmap = Bitmap::wrap(bitmap_blocks.pointer(), blocks_in_group);
  636. for (unsigned i = 0; i < blocks_in_group; ++i) {
  637. kprintf("%c", bitmap.get(i) ? '1' : '0');
  638. }
  639. kprintf("\n");
  640. }
  641. void Ext2FS::dump_inode_bitmap(unsigned groupIndex) const
  642. {
  643. traverse_inode_bitmap(groupIndex, [] (unsigned, const Bitmap& bitmap) {
  644. for (unsigned i = 0; i < bitmap.size(); ++i)
  645. kprintf("%c", bitmap.get(i) ? '1' : '0');
  646. return true;
  647. });
  648. }
  649. template<typename F>
  650. void Ext2FS::traverse_inode_bitmap(unsigned groupIndex, F callback) const
  651. {
  652. ASSERT(groupIndex <= m_block_group_count);
  653. auto& bgd = group_descriptor(groupIndex);
  654. unsigned inodes_in_group = min(inodes_per_group(), super_block().s_inodes_count);
  655. unsigned block_count = ceil_div(inodes_in_group, 8u);
  656. for (unsigned i = 0; i < block_count; ++i) {
  657. auto block = read_block(bgd.bg_inode_bitmap + i);
  658. ASSERT(block);
  659. bool should_continue = callback(i * (block_size() / 8) + 1, Bitmap::wrap(block.pointer(), inodes_in_group));
  660. if (!should_continue)
  661. break;
  662. }
  663. }
  664. template<typename F>
  665. void Ext2FS::traverse_block_bitmap(unsigned groupIndex, F callback) const
  666. {
  667. ASSERT(groupIndex <= m_block_group_count);
  668. auto& bgd = group_descriptor(groupIndex);
  669. unsigned blocks_in_group = min(blocks_per_group(), super_block().s_blocks_count);
  670. unsigned block_count = ceil_div(blocks_in_group, 8u);
  671. for (unsigned i = 0; i < block_count; ++i) {
  672. auto block = read_block(bgd.bg_block_bitmap + i);
  673. ASSERT(block);
  674. bool should_continue = callback(i * (block_size() / 8) + 1, Bitmap::wrap(block.pointer(), blocks_in_group));
  675. if (!should_continue)
  676. break;
  677. }
  678. }
  679. bool Ext2FS::write_ext2_inode(unsigned inode, const ext2_inode& e2inode)
  680. {
  681. unsigned block_index;
  682. unsigned offset;
  683. auto block = read_block_containing_inode(inode, block_index, offset);
  684. if (!block)
  685. return false;
  686. memcpy(reinterpret_cast<ext2_inode*>(block.offset_pointer(offset)), &e2inode, inode_size());
  687. write_block(block_index, block);
  688. return true;
  689. }
  690. Vector<Ext2FS::BlockIndex> Ext2FS::allocate_blocks(unsigned group, unsigned count)
  691. {
  692. dbgprintf("Ext2FS: allocate_blocks(group: %u, count: %u)\n", group, count);
  693. if (count == 0)
  694. return { };
  695. auto& bgd = group_descriptor(group);
  696. if (bgd.bg_free_blocks_count < count) {
  697. kprintf("Ext2FS: allocate_blocks can't allocate out of group %u, wanted %u but only %u available\n", group, count, bgd.bg_free_blocks_count);
  698. return { };
  699. }
  700. // FIXME: Implement a scan that finds consecutive blocks if possible.
  701. Vector<BlockIndex> blocks;
  702. traverse_block_bitmap(group, [&blocks, count] (unsigned first_block_in_bitmap, const Bitmap& bitmap) {
  703. for (unsigned i = 0; i < bitmap.size(); ++i) {
  704. if (!bitmap.get(i)) {
  705. blocks.append(first_block_in_bitmap + i);
  706. if (blocks.size() == count)
  707. return false;
  708. }
  709. }
  710. return true;
  711. });
  712. dbgprintf("Ext2FS: allocate_block found these blocks:\n");
  713. for (auto& bi : blocks) {
  714. dbgprintf(" > %u\n", bi);
  715. }
  716. return blocks;
  717. }
  718. unsigned Ext2FS::allocate_inode(unsigned preferred_group, unsigned expected_size)
  719. {
  720. dbgprintf("Ext2FS: allocate_inode(preferredGroup: %u, expectedSize: %u)\n", preferred_group, expected_size);
  721. unsigned needed_blocks = ceil_div(expected_size, block_size());
  722. dbgprintf("Ext2FS: minimum needed blocks: %u\n", needed_blocks);
  723. unsigned groupIndex = 0;
  724. auto is_suitable_group = [this, needed_blocks] (unsigned groupIndex) {
  725. auto& bgd = group_descriptor(groupIndex);
  726. return bgd.bg_free_inodes_count && bgd.bg_free_blocks_count >= needed_blocks;
  727. };
  728. if (preferred_group && is_suitable_group(preferred_group)) {
  729. groupIndex = preferred_group;
  730. } else {
  731. for (unsigned i = 1; i <= m_block_group_count; ++i) {
  732. if (is_suitable_group(i))
  733. groupIndex = i;
  734. }
  735. }
  736. if (!groupIndex) {
  737. kprintf("Ext2FS: allocate_inode: no suitable group found for new inode with %u blocks needed :(\n", needed_blocks);
  738. return 0;
  739. }
  740. dbgprintf("Ext2FS: allocate_inode: found suitable group [%u] for new inode with %u blocks needed :^)\n", groupIndex, needed_blocks);
  741. unsigned firstFreeInodeInGroup = 0;
  742. traverse_inode_bitmap(groupIndex, [&firstFreeInodeInGroup] (unsigned firstInodeInBitmap, const Bitmap& bitmap) {
  743. for (unsigned i = 0; i < bitmap.size(); ++i) {
  744. if (!bitmap.get(i)) {
  745. firstFreeInodeInGroup = firstInodeInBitmap + i;
  746. return false;
  747. }
  748. }
  749. return true;
  750. });
  751. if (!firstFreeInodeInGroup) {
  752. kprintf("Ext2FS: first_free_inode_in_group returned no inode, despite bgd claiming there are inodes :(\n");
  753. return 0;
  754. }
  755. unsigned inode = firstFreeInodeInGroup;
  756. dbgprintf("Ext2FS: found suitable inode %u\n", inode);
  757. // FIXME: allocate blocks if needed!
  758. return inode;
  759. }
  760. unsigned Ext2FS::group_index_from_inode(unsigned inode) const
  761. {
  762. if (!inode)
  763. return 0;
  764. return (inode - 1) / inodes_per_group() + 1;
  765. }
  766. bool Ext2FS::get_inode_allocation_state(InodeIndex index) const
  767. {
  768. if (index == 0)
  769. return true;
  770. auto& bgd = group_descriptor(group_index_from_inode(index));
  771. unsigned inodes_per_bitmap_block = block_size() * 8;
  772. unsigned bitmap_block_index = (index - 1) / inodes_per_bitmap_block;
  773. unsigned bit_index = (index - 1) % inodes_per_bitmap_block;
  774. auto block = read_block(bgd.bg_inode_bitmap + bitmap_block_index);
  775. ASSERT(block);
  776. auto bitmap = Bitmap::wrap(block.pointer(), block.size());
  777. return bitmap.get(bit_index);
  778. }
  779. bool Ext2FS::set_inode_allocation_state(unsigned index, bool newState)
  780. {
  781. auto& bgd = group_descriptor(group_index_from_inode(index));
  782. // Update inode bitmap
  783. unsigned inodes_per_bitmap_block = block_size() * 8;
  784. unsigned bitmap_block_index = (index - 1) / inodes_per_bitmap_block;
  785. unsigned bit_index = (index - 1) % inodes_per_bitmap_block;
  786. auto block = read_block(bgd.bg_inode_bitmap + bitmap_block_index);
  787. ASSERT(block);
  788. auto bitmap = Bitmap::wrap(block.pointer(), block.size());
  789. bool current_state = bitmap.get(bit_index);
  790. dbgprintf("Ext2FS: set_inode_allocation_state(%u) %u -> %u\n", index, current_state, newState);
  791. if (current_state == newState)
  792. return true;
  793. bitmap.set(bit_index, newState);
  794. write_block(bgd.bg_inode_bitmap + bitmap_block_index, block);
  795. // Update superblock
  796. auto& sb = *reinterpret_cast<ext2_super_block*>(m_cached_super_block.pointer());
  797. dbgprintf("Ext2FS: superblock free inode count %u -> %u\n", sb.s_free_inodes_count, sb.s_free_inodes_count - 1);
  798. if (newState)
  799. --sb.s_free_inodes_count;
  800. else
  801. ++sb.s_free_inodes_count;
  802. write_super_block(sb);
  803. // Update BGD
  804. auto& mutable_bgd = const_cast<ext2_group_desc&>(bgd);
  805. if (newState)
  806. --mutable_bgd.bg_free_inodes_count;
  807. else
  808. ++mutable_bgd.bg_free_inodes_count;
  809. dbgprintf("Ext2FS: group free inode count %u -> %u\n", bgd.bg_free_inodes_count, bgd.bg_free_inodes_count - 1);
  810. flush_block_group_descriptor_table();
  811. return true;
  812. }
  813. bool Ext2FS::set_block_allocation_state(GroupIndex group, BlockIndex bi, bool new_state)
  814. {
  815. dbgprintf("Ext2FS: set_block_allocation_state(group=%u, block=%u, state=%u)\n", group, bi, new_state);
  816. auto& bgd = group_descriptor(group);
  817. // Update block bitmap
  818. unsigned blocks_per_bitmap_block = block_size() * 8;
  819. unsigned bitmap_block_index = (bi - 1) / blocks_per_bitmap_block;
  820. unsigned bit_index = (bi - 1) % blocks_per_bitmap_block;
  821. auto block = read_block(bgd.bg_block_bitmap + bitmap_block_index);
  822. ASSERT(block);
  823. auto bitmap = Bitmap::wrap(block.pointer(), blocks_per_bitmap_block);
  824. bool current_state = bitmap.get(bit_index);
  825. dbgprintf("Ext2FS: block %u state: %u -> %u\n", bi, current_state, new_state);
  826. if (current_state == new_state)
  827. return true;
  828. bitmap.set(bit_index, new_state);
  829. write_block(bgd.bg_block_bitmap + bitmap_block_index, block);
  830. // Update superblock
  831. auto& sb = *reinterpret_cast<ext2_super_block*>(m_cached_super_block.pointer());
  832. dbgprintf("Ext2FS: superblock free block count %u -> %u\n", sb.s_free_blocks_count, sb.s_free_blocks_count - 1);
  833. if (new_state)
  834. --sb.s_free_blocks_count;
  835. else
  836. ++sb.s_free_blocks_count;
  837. write_super_block(sb);
  838. // Update BGD
  839. auto& mutable_bgd = const_cast<ext2_group_desc&>(bgd);
  840. if (new_state)
  841. --mutable_bgd.bg_free_blocks_count;
  842. else
  843. ++mutable_bgd.bg_free_blocks_count;
  844. dbgprintf("Ext2FS: group free block count %u -> %u\n", bgd.bg_free_blocks_count, bgd.bg_free_blocks_count - 1);
  845. flush_block_group_descriptor_table();
  846. return true;
  847. }
  848. RetainPtr<Inode> Ext2FS::create_directory(InodeIdentifier parent_id, const String& name, mode_t mode, int& error)
  849. {
  850. ASSERT(parent_id.fsid() == fsid());
  851. // Fix up the mode to definitely be a directory.
  852. // FIXME: This is a bit on the hackish side.
  853. mode &= ~0170000;
  854. mode |= 0040000;
  855. // NOTE: When creating a new directory, make the size 1 block.
  856. // There's probably a better strategy here, but this works for now.
  857. auto inode = create_inode(parent_id, name, mode, block_size(), error);
  858. if (!inode)
  859. return nullptr;
  860. dbgprintf("Ext2FS: create_directory: created new directory named '%s' with inode %u\n", name.characters(), inode->identifier().index());
  861. Vector<DirectoryEntry> entries;
  862. entries.append({ ".", inode->identifier(), EXT2_FT_DIR });
  863. entries.append({ "..", parent_id, EXT2_FT_DIR });
  864. bool success = write_directory_inode(inode->identifier().index(), move(entries));
  865. ASSERT(success);
  866. auto parent_inode = get_inode(parent_id);
  867. error = parent_inode->increment_link_count();
  868. if (error < 0)
  869. return nullptr;
  870. auto& bgd = const_cast<ext2_group_desc&>(group_descriptor(group_index_from_inode(inode->identifier().index())));
  871. ++bgd.bg_used_dirs_count;
  872. dbgprintf("Ext2FS: incremented bg_used_dirs_count %u -> %u\n", bgd.bg_used_dirs_count - 1, bgd.bg_used_dirs_count);
  873. flush_block_group_descriptor_table();
  874. error = 0;
  875. return inode;
  876. }
  877. RetainPtr<Inode> Ext2FS::create_inode(InodeIdentifier parent_id, const String& name, mode_t mode, unsigned size, int& error)
  878. {
  879. ASSERT(parent_id.fsid() == fsid());
  880. auto parent_inode = get_inode(parent_id);
  881. dbgprintf("Ext2FS: Adding inode '%s' (mode %u) to parent directory %u:\n", name.characters(), mode, parent_inode->identifier().index());
  882. // NOTE: This doesn't commit the inode allocation just yet!
  883. auto inode_id = allocate_inode(0, size);
  884. if (!inode_id) {
  885. kprintf("Ext2FS: create_inode: allocate_inode failed\n");
  886. error = -ENOSPC;
  887. return { };
  888. }
  889. auto needed_blocks = ceil_div(size, block_size());
  890. auto blocks = allocate_blocks(group_index_from_inode(inode_id), needed_blocks);
  891. if (blocks.size() != needed_blocks) {
  892. kprintf("Ext2FS: create_inode: allocate_blocks failed\n");
  893. error = -ENOSPC;
  894. return { };
  895. }
  896. byte file_type = 0;
  897. if (is_regular_file(mode))
  898. file_type = EXT2_FT_REG_FILE;
  899. else if (is_directory(mode))
  900. file_type = EXT2_FT_DIR;
  901. else if (is_character_device(mode))
  902. file_type = EXT2_FT_CHRDEV;
  903. else if (is_block_device(mode))
  904. file_type = EXT2_FT_BLKDEV;
  905. else if (is_fifo(mode))
  906. file_type = EXT2_FT_FIFO;
  907. else if (is_socket(mode))
  908. file_type = EXT2_FT_SOCK;
  909. else if (is_symlink(mode))
  910. file_type = EXT2_FT_SYMLINK;
  911. // Try adding it to the directory first, in case the name is already in use.
  912. bool success = parent_inode->add_child({ fsid(), inode_id }, name, file_type, error);
  913. if (!success)
  914. return { };
  915. // Looks like we're good, time to update the inode bitmap and group+global inode counters.
  916. success = set_inode_allocation_state(inode_id, true);
  917. ASSERT(success);
  918. for (auto bi : blocks) {
  919. success = set_block_allocation_state(group_index_from_inode(inode_id), bi, true);
  920. ASSERT(success);
  921. }
  922. unsigned initial_links_count;
  923. if (is_directory(mode))
  924. initial_links_count = 2; // (parent directory + "." entry in self)
  925. else
  926. initial_links_count = 1;
  927. auto timestamp = RTC::now();
  928. ext2_inode e2inode;
  929. memset(&e2inode, 0, sizeof(ext2_inode));
  930. e2inode.i_mode = mode;
  931. e2inode.i_uid = 0;
  932. e2inode.i_size = size;
  933. e2inode.i_atime = timestamp;
  934. e2inode.i_ctime = timestamp;
  935. e2inode.i_mtime = timestamp;
  936. e2inode.i_dtime = 0;
  937. e2inode.i_gid = 0;
  938. e2inode.i_links_count = initial_links_count;
  939. success = write_block_list_for_inode(inode_id, e2inode, blocks);
  940. ASSERT(success);
  941. dbgprintf("Ext2FS: writing initial metadata for inode %u\n", inode_id);
  942. e2inode.i_flags = 0;
  943. success = write_ext2_inode(inode_id, e2inode);
  944. ASSERT(success);
  945. {
  946. // We might have cached the fact that this inode didn't exist. Wipe the slate.
  947. LOCKER(m_inode_cache_lock);
  948. m_inode_cache.remove(inode_id);
  949. }
  950. return get_inode({ fsid(), inode_id });
  951. }
  952. RetainPtr<Inode> Ext2FSInode::parent() const
  953. {
  954. if (m_parent_id.is_valid())
  955. return fs().get_inode(m_parent_id);
  956. unsigned group_index = fs().group_index_from_inode(index());
  957. unsigned first_inode_in_group = fs().inodes_per_group() * (group_index - 1);
  958. Vector<RetainPtr<Ext2FSInode>> directories_in_group;
  959. for (unsigned i = 0; i < fs().inodes_per_group(); ++i) {
  960. auto group_member = fs().get_inode({ fsid(), first_inode_in_group + i });
  961. if (!group_member)
  962. continue;
  963. if (group_member->is_directory())
  964. directories_in_group.append(move(group_member));
  965. }
  966. for (auto& directory : directories_in_group) {
  967. if (!directory->reverse_lookup(identifier()).is_null()) {
  968. m_parent_id = directory->identifier();
  969. break;
  970. }
  971. }
  972. ASSERT(m_parent_id.is_valid());
  973. return fs().get_inode(m_parent_id);
  974. }
  975. void Ext2FSInode::populate_lookup_cache() const
  976. {
  977. {
  978. LOCKER(m_lock);
  979. if (!m_lookup_cache.is_empty())
  980. return;
  981. }
  982. HashMap<String, unsigned> children;
  983. traverse_as_directory([&children] (auto& entry) {
  984. children.set(String(entry.name, entry.name_length), entry.inode.index());
  985. return true;
  986. });
  987. LOCKER(m_lock);
  988. if (!m_lookup_cache.is_empty())
  989. return;
  990. m_lookup_cache = move(children);
  991. }
  992. InodeIdentifier Ext2FSInode::lookup(const String& name)
  993. {
  994. ASSERT(is_directory());
  995. populate_lookup_cache();
  996. LOCKER(m_lock);
  997. auto it = m_lookup_cache.find(name);
  998. if (it != m_lookup_cache.end())
  999. return { fsid(), (*it).value };
  1000. return { };
  1001. }
  1002. String Ext2FSInode::reverse_lookup(InodeIdentifier child_id)
  1003. {
  1004. ASSERT(is_directory());
  1005. ASSERT(child_id.fsid() == fsid());
  1006. populate_lookup_cache();
  1007. LOCKER(m_lock);
  1008. for (auto it : m_lookup_cache) {
  1009. if (it.value == child_id.index())
  1010. return it.key;
  1011. }
  1012. return { };
  1013. }
  1014. void Ext2FSInode::one_retain_left()
  1015. {
  1016. // FIXME: I would like to not live forever, but uncached Ext2FS is fucking painful right now.
  1017. }
  1018. int Ext2FSInode::set_atime(time_t t)
  1019. {
  1020. if (fs().is_readonly())
  1021. return -EROFS;
  1022. m_raw_inode.i_atime = t;
  1023. set_metadata_dirty(true);
  1024. return 0;
  1025. }
  1026. int Ext2FSInode::set_ctime(time_t t)
  1027. {
  1028. if (fs().is_readonly())
  1029. return -EROFS;
  1030. m_raw_inode.i_ctime = t;
  1031. set_metadata_dirty(true);
  1032. return 0;
  1033. }
  1034. int Ext2FSInode::set_mtime(time_t t)
  1035. {
  1036. if (fs().is_readonly())
  1037. return -EROFS;
  1038. m_raw_inode.i_mtime = t;
  1039. set_metadata_dirty(true);
  1040. return 0;
  1041. }
  1042. int Ext2FSInode::increment_link_count()
  1043. {
  1044. if (fs().is_readonly())
  1045. return -EROFS;
  1046. ++m_raw_inode.i_links_count;
  1047. set_metadata_dirty(true);
  1048. return 0;
  1049. }
  1050. int Ext2FSInode::decrement_link_count()
  1051. {
  1052. if (fs().is_readonly())
  1053. return -EROFS;
  1054. ASSERT(m_raw_inode.i_links_count);
  1055. --m_raw_inode.i_links_count;
  1056. if (m_raw_inode.i_links_count == 0)
  1057. fs().uncache_inode(index());
  1058. set_metadata_dirty(true);
  1059. return 0;
  1060. }
  1061. void Ext2FS::uncache_inode(InodeIndex index)
  1062. {
  1063. LOCKER(m_inode_cache_lock);
  1064. m_inode_cache.remove(index);
  1065. }
  1066. size_t Ext2FSInode::directory_entry_count() const
  1067. {
  1068. ASSERT(is_directory());
  1069. populate_lookup_cache();
  1070. LOCKER(m_lock);
  1071. return m_lookup_cache.size();
  1072. }
  1073. bool Ext2FSInode::chmod(mode_t mode, int& error)
  1074. {
  1075. error = 0;
  1076. if (m_raw_inode.i_mode == mode)
  1077. return true;
  1078. m_raw_inode.i_mode = mode;
  1079. set_metadata_dirty(true);
  1080. return true;
  1081. }