Ext2FileSystem.cpp 46 KB

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