Ext2FileSystem.cpp 43 KB

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