Ext2FileSystem.cpp 45 KB

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