METADATA_CSUM: block group descriptor checksum added.
[lwext4.git] / lwext4 / ext4_fs.c
1 /*
2  * Copyright (c) 2013 Grzegorz Kostka (kostka.grzegorz@gmail.com)
3  *
4  *
5  * HelenOS:
6  * Copyright (c) 2012 Martin Sucha
7  * Copyright (c) 2012 Frantisek Princ
8  * All rights reserved.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  *
14  * - Redistributions of source code must retain the above copyright
15  *   notice, this list of conditions and the following disclaimer.
16  * - Redistributions in binary form must reproduce the above copyright
17  *   notice, this list of conditions and the following disclaimer in the
18  *   documentation and/or other materials provided with the distribution.
19  * - The name of the author may not be used to endorse or promote products
20  *   derived from this software without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
23  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
24  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
25  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
26  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
27  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
31  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32  */
33 /** @addtogroup lwext4
34  * @{
35  */
36 /**
37  * @file  ext4_fs.c
38  * @brief More complex filesystem functions.
39  */
40
41 #include "ext4_config.h"
42 #include "ext4_types.h"
43 #include "ext4_fs.h"
44 #include "ext4_errno.h"
45 #include "ext4_blockdev.h"
46 #include "ext4_super.h"
47 #include "ext4_crc32c.h"
48 #include "ext4_debug.h"
49 #include "ext4_block_group.h"
50 #include "ext4_balloc.h"
51 #include "ext4_bitmap.h"
52 #include "ext4_inode.h"
53 #include "ext4_ialloc.h"
54 #include "ext4_extent.h"
55
56 #include <string.h>
57
58 int ext4_fs_init(struct ext4_fs *fs, struct ext4_blockdev *bdev)
59 {
60         int r, i;
61         uint16_t tmp;
62         uint32_t bsize;
63         bool read_only = false;
64
65         ext4_assert(fs && bdev);
66
67         fs->bdev = bdev;
68
69         r = ext4_sb_read(fs->bdev, &fs->sb);
70         if (r != EOK)
71                 return r;
72
73         if (!ext4_sb_check(&fs->sb))
74                 return ENOTSUP;
75
76         bsize = ext4_sb_get_block_size(&fs->sb);
77         if (bsize > EXT4_MAX_BLOCK_SIZE)
78                 return ENXIO;
79
80         r = ext4_fs_check_features(fs, &read_only);
81         if (r != EOK)
82                 return r;
83
84         if (read_only)
85                 return ENOTSUP;
86
87         /* Compute limits for indirect block levels */
88         uint32_t blocks_id = bsize / sizeof(uint32_t);
89
90         fs->inode_block_limits[0] = EXT4_INODE_DIRECT_BLOCK_COUNT;
91         fs->inode_blocks_per_level[0] = 1;
92
93         for (i = 1; i < 4; i++) {
94                 fs->inode_blocks_per_level[i] =
95                     fs->inode_blocks_per_level[i - 1] * blocks_id;
96                 fs->inode_block_limits[i] = fs->inode_block_limits[i - 1] +
97                                             fs->inode_blocks_per_level[i];
98         }
99
100         /*Validate FS*/
101         tmp = ext4_get16(&fs->sb, state);
102         if (tmp & EXT4_SUPERBLOCK_STATE_ERROR_FS)
103                 ext4_dbg(DEBUG_FS, DBG_WARN
104                                 "last umount error: superblock fs_error flag\n");
105
106
107         /* Mark system as mounted */
108         ext4_set16(&fs->sb, state, EXT4_SUPERBLOCK_STATE_ERROR_FS);
109         r = ext4_sb_write(fs->bdev, &fs->sb);
110         if (r != EOK)
111                 return r;
112
113         /*Update mount count*/
114         ext4_set16(&fs->sb, mount_count, ext4_get16(&fs->sb, mount_count) + 1);
115
116         return r;
117 }
118
119 int ext4_fs_fini(struct ext4_fs *fs)
120 {
121         ext4_assert(fs);
122
123         /*Set superblock state*/
124         ext4_set16(&fs->sb, state, EXT4_SUPERBLOCK_STATE_VALID_FS);
125
126         return ext4_sb_write(fs->bdev, &fs->sb);
127 }
128
129 static void ext4_fs_debug_features_inc(uint32_t features_incompatible)
130 {
131         if (features_incompatible & EXT4_FEATURE_INCOMPAT_COMPRESSION)
132                 ext4_dbg(DEBUG_FS, DBG_NONE "compression\n");
133         if (features_incompatible & EXT4_FEATURE_INCOMPAT_FILETYPE)
134                 ext4_dbg(DEBUG_FS, DBG_NONE "filetype\n");
135         if (features_incompatible & EXT4_FEATURE_INCOMPAT_RECOVER)
136                 ext4_dbg(DEBUG_FS, DBG_NONE "recover\n");
137         if (features_incompatible & EXT4_FEATURE_INCOMPAT_JOURNAL_DEV)
138                 ext4_dbg(DEBUG_FS, DBG_NONE "journal_dev\n");
139         if (features_incompatible & EXT4_FEATURE_INCOMPAT_META_BG)
140                 ext4_dbg(DEBUG_FS, DBG_NONE "meta_bg\n");
141         if (features_incompatible & EXT4_FEATURE_INCOMPAT_EXTENTS)
142                 ext4_dbg(DEBUG_FS, DBG_NONE "extents\n");
143         if (features_incompatible & EXT4_FEATURE_INCOMPAT_64BIT)
144                 ext4_dbg(DEBUG_FS, DBG_NONE "64bit\n");
145         if (features_incompatible & EXT4_FEATURE_INCOMPAT_MMP)
146                 ext4_dbg(DEBUG_FS, DBG_NONE "mnp\n");
147         if (features_incompatible & EXT4_FEATURE_INCOMPAT_FLEX_BG)
148                 ext4_dbg(DEBUG_FS, DBG_NONE "flex_bg\n");
149         if (features_incompatible & EXT4_FEATURE_INCOMPAT_EA_INODE)
150                 ext4_dbg(DEBUG_FS, DBG_NONE "ea_inode\n");
151         if (features_incompatible & EXT4_FEATURE_INCOMPAT_DIRDATA)
152                 ext4_dbg(DEBUG_FS, DBG_NONE "dirdata\n");
153         if (features_incompatible & EXT4_FEATURE_INCOMPAT_BG_USE_META_CSUM)
154                 ext4_dbg(DEBUG_FS, DBG_NONE "meta_csum\n");
155         if (features_incompatible & EXT4_FEATURE_INCOMPAT_LARGEDIR)
156                 ext4_dbg(DEBUG_FS, DBG_NONE "largedir\n");
157         if (features_incompatible & EXT4_FEATURE_INCOMPAT_INLINE_DATA)
158                 ext4_dbg(DEBUG_FS, DBG_NONE "inline_data\n");
159 }
160 static void ext4_fs_debug_features_comp(uint32_t features_compatible)
161 {
162         if (features_compatible & EXT4_FEATURE_COMPAT_DIR_PREALLOC)
163                 ext4_dbg(DEBUG_FS, DBG_NONE "dir_prealloc\n");
164         if (features_compatible & EXT4_FEATURE_COMPAT_IMAGIC_INODES)
165                 ext4_dbg(DEBUG_FS, DBG_NONE "imagic_inodes\n");
166         if (features_compatible & EXT4_FEATURE_COMPAT_HAS_JOURNAL)
167                 ext4_dbg(DEBUG_FS, DBG_NONE "has_journal\n");
168         if (features_compatible & EXT4_FEATURE_COMPAT_EXT_ATTR)
169                 ext4_dbg(DEBUG_FS, DBG_NONE "ext_attr\n");
170         if (features_compatible & EXT4_FEATURE_COMPAT_RESIZE_INODE)
171                 ext4_dbg(DEBUG_FS, DBG_NONE "resize_inode\n");
172         if (features_compatible & EXT4_FEATURE_COMPAT_DIR_INDEX)
173                 ext4_dbg(DEBUG_FS, DBG_NONE "dir_index\n");
174 }
175
176 static void ext4_fs_debug_features_ro(uint32_t features_ro)
177 {
178         if (features_ro & EXT4_FEATURE_RO_COMPAT_SPARSE_SUPER)
179                 ext4_dbg(DEBUG_FS, DBG_NONE "sparse_super\n");
180         if (features_ro & EXT4_FEATURE_RO_COMPAT_LARGE_FILE)
181                 ext4_dbg(DEBUG_FS, DBG_NONE "large_file\n");
182         if (features_ro & EXT4_FEATURE_RO_COMPAT_BTREE_DIR)
183                 ext4_dbg(DEBUG_FS, DBG_NONE "btree_dir\n");
184         if (features_ro & EXT4_FEATURE_RO_COMPAT_HUGE_FILE)
185                 ext4_dbg(DEBUG_FS, DBG_NONE "huge_file\n");
186         if (features_ro & EXT4_FEATURE_RO_COMPAT_GDT_CSUM)
187                 ext4_dbg(DEBUG_FS, DBG_NONE "gtd_csum\n");
188         if (features_ro & EXT4_FEATURE_RO_COMPAT_DIR_NLINK)
189                 ext4_dbg(DEBUG_FS, DBG_NONE "dir_nlink\n");
190         if (features_ro & EXT4_FEATURE_RO_COMPAT_EXTRA_ISIZE)
191                 ext4_dbg(DEBUG_FS, DBG_NONE "extra_isize\n");
192         if (features_ro & EXT4_FEATURE_RO_COMPAT_QUOTA)
193                 ext4_dbg(DEBUG_FS, DBG_NONE "quota\n");
194         if (features_ro & EXT4_FEATURE_RO_COMPAT_BIGALLOC)
195                 ext4_dbg(DEBUG_FS, DBG_NONE "bigalloc\n");
196         if (features_ro & EXT4_FEATURE_RO_COMPAT_METADATA_CSUM)
197                 ext4_dbg(DEBUG_FS, DBG_NONE "metadata_csum\n");
198 }
199
200 int ext4_fs_check_features(struct ext4_fs *fs, bool *read_only)
201 {
202         ext4_assert(fs && read_only);
203         uint32_t v;
204         if (ext4_get32(&fs->sb, rev_level) == 0) {
205                 *read_only = false;
206                 return EOK;
207         }
208
209         ext4_dbg(DEBUG_FS, DBG_INFO "sblock features_incompatible:\n");
210         ext4_fs_debug_features_inc(ext4_get32(&fs->sb, features_incompatible));
211
212         ext4_dbg(DEBUG_FS, DBG_INFO "sblock features_compatible:\n");
213         ext4_fs_debug_features_comp(ext4_get32(&fs->sb, features_compatible));
214
215         ext4_dbg(DEBUG_FS, DBG_INFO "sblock features_read_only:\n");
216         ext4_fs_debug_features_ro(ext4_get32(&fs->sb, features_read_only));
217
218         /*Check features_incompatible*/
219         v = (ext4_get32(&fs->sb, features_incompatible) &
220              (~CONFIG_FEATURE_INCOMPAT_SUPP));
221         if (v) {
222                 ext4_dbg(DEBUG_FS, DBG_ERROR
223                                 "sblock has unsupported features incompatible:\n");
224                 ext4_fs_debug_features_inc(v);
225                 return ENOTSUP;
226         }
227
228         /*Check features_read_only*/
229         v = (ext4_get32(&fs->sb, features_read_only) &
230              (~CONFIG_FEATURE_RO_COMPAT_SUPP));
231         if (v) {
232                 ext4_dbg(DEBUG_FS, DBG_WARN
233                                 "sblock has unsupported features read only:\n");
234                 ext4_fs_debug_features_ro(v);
235                 *read_only = true;
236                 return EOK;
237         }
238         *read_only = false;
239
240         return EOK;
241 }
242
243 /**@brief Determine whether the block is inside the group.
244  * @param baddr   block address
245  * @param bgid    block group id
246  * @return Error code
247  */
248 static int ext4_block_in_group(struct ext4_sblock *s,
249                                ext4_fsblk_t baddr,
250                                uint32_t bgid)
251 {
252         uint32_t actual_bgid;
253         actual_bgid = ext4_balloc_get_bgid_of_block(s, baddr);
254         if (actual_bgid == bgid)
255                 return 1;
256         return 0;
257 }
258
259 /**@brief   To avoid calling the atomic setbit hundreds or thousands of times, we only
260  *          need to use it within a single byte (to ensure we get endianness right).
261  *          We can use memset for the rest of the bitmap as there are no other users.
262  */
263 static void ext4_fs_mark_bitmap_end(int start_bit, int end_bit, void *bitmap)
264 {
265         int i;
266
267         if (start_bit >= end_bit)
268                 return;
269
270         for (i = start_bit; (unsigned)i < ((start_bit + 7) & ~7UL); i++)
271                 ext4_bmap_bit_set(bitmap, i);
272
273         if (i < end_bit)
274                 memset((char *)bitmap + (i >> 3), 0xff, (end_bit - i) >> 3);
275 }
276
277 /**@brief Initialize block bitmap in block group.
278  * @param bg_ref Reference to block group
279  * @return Error code
280  */
281 static int ext4_fs_init_block_bitmap(struct ext4_block_group_ref *bg_ref)
282 {
283         uint32_t i, bit, bit_max;
284         uint32_t group_blocks;
285         uint16_t inode_size = ext4_get16(&bg_ref->fs->sb, inode_size);
286         uint32_t block_size = ext4_sb_get_block_size(&bg_ref->fs->sb);
287         uint32_t inodes_per_group = ext4_get32(&bg_ref->fs->sb, inodes_per_group);
288         ext4_fsblk_t bitmap_block_addr =
289             ext4_bg_get_block_bitmap(bg_ref->block_group, &bg_ref->fs->sb);
290         ext4_fsblk_t bitmap_inode_addr =
291             ext4_bg_get_inode_bitmap(bg_ref->block_group, &bg_ref->fs->sb);
292         ext4_fsblk_t inode_table_addr =
293             ext4_bg_get_inode_table_first_block(bg_ref->block_group,
294                                                 &bg_ref->fs->sb);
295         ext4_fsblk_t first_group_addr =
296             ext4_balloc_get_block_of_bgid(&bg_ref->fs->sb, bg_ref->index);
297
298         uint32_t dsc_per_block =
299             ext4_sb_get_block_size(&bg_ref->fs->sb) /
300             ext4_sb_get_desc_size(&bg_ref->fs->sb);
301
302         bool flex_bg =
303                 ext4_sb_has_feature_incompatible(&bg_ref->fs->sb,
304                                                  EXT4_FEATURE_INCOMPAT_FLEX_BG);
305
306         uint32_t inode_table_bcnt = inodes_per_group * inode_size / block_size;
307
308         struct ext4_block block_bitmap;
309         int rc =
310             ext4_block_get(bg_ref->fs->bdev, &block_bitmap, bitmap_block_addr);
311         if (rc != EOK)
312                 return rc;
313
314         memset(block_bitmap.data, 0, block_size);
315
316         bit_max = ext4_sb_is_super_in_bg(&bg_ref->fs->sb, bg_ref->index);
317         if (!ext4_sb_has_feature_incompatible(&bg_ref->fs->sb,
318                                               EXT4_FEATURE_INCOMPAT_META_BG) ||
319                         bg_ref->index < ext4_sb_first_meta_bg(&bg_ref->fs->sb) *
320                         dsc_per_block) {
321                 if (bit_max) {
322                         bit_max += ext4_bg_num_gdb(&bg_ref->fs->sb,
323                                                    bg_ref->index);
324                         bit_max +=
325                                 ext4_get16(&bg_ref->fs->sb,
326                                            s_reserved_gdt_blocks);
327                 }
328         } else { /* For META_BG_BLOCK_GROUPS */
329                 bit_max += ext4_bg_num_gdb(&bg_ref->fs->sb,
330                                            bg_ref->index);
331         }
332         for (bit = 0; bit < bit_max; bit++)
333                 ext4_bmap_bit_set(block_bitmap.data, bit);
334
335         if (bg_ref->index == ext4_block_group_cnt(&bg_ref->fs->sb) - 1) {
336                 /*
337                  * Even though mke2fs always initialize first and last group
338                  * if some other tool enabled the EXT4_BG_BLOCK_UNINIT we need
339                  * to make sure we calculate the right free blocks
340                  */
341                 group_blocks = (ext4_sb_get_blocks_cnt(&bg_ref->fs->sb) -
342                                 ext4_get32(&bg_ref->fs->sb, first_data_block) -
343                                 (ext4_get32(&bg_ref->fs->sb, blocks_per_group) *
344                                  (ext4_block_group_cnt(&bg_ref->fs->sb) - 1)));
345         } else {
346                 group_blocks = ext4_get32(&bg_ref->fs->sb, blocks_per_group);
347         }
348         if (!flex_bg ||
349             ext4_block_in_group(&bg_ref->fs->sb,
350                                 bitmap_block_addr, bg_ref->index))
351                 ext4_bmap_bit_set(block_bitmap.data,
352                                   bitmap_block_addr - first_group_addr);
353
354         if (!flex_bg ||
355             ext4_block_in_group(&bg_ref->fs->sb,
356                                 bitmap_inode_addr, bg_ref->index))
357                 ext4_bmap_bit_set(block_bitmap.data,
358                                   bitmap_inode_addr - first_group_addr);
359
360         for (i = inode_table_addr;
361                 i < inode_table_addr + inode_table_bcnt; i++) {
362                 if (!flex_bg ||
363                     ext4_block_in_group(&bg_ref->fs->sb,
364                                         i,
365                                         bg_ref->index))
366                         ext4_bmap_bit_set(block_bitmap.data,
367                                         i - first_group_addr);
368         }
369         /*
370          * Also if the number of blocks within the group is
371          * less than the blocksize * 8 ( which is the size
372          * of bitmap ), set rest of the block bitmap to 1
373          */
374         ext4_fs_mark_bitmap_end(group_blocks, block_size * 8, block_bitmap.data);
375         block_bitmap.dirty = true;
376
377         /* Save bitmap */
378         return ext4_block_set(bg_ref->fs->bdev, &block_bitmap);
379 }
380
381 /**@brief Initialize i-node bitmap in block group.
382  * @param bg_ref Reference to block group
383  * @return Error code
384  */
385 static int ext4_fs_init_inode_bitmap(struct ext4_block_group_ref *bg_ref)
386 {
387         /* Load bitmap */
388         ext4_fsblk_t bitmap_block_addr =
389             ext4_bg_get_inode_bitmap(bg_ref->block_group, &bg_ref->fs->sb);
390
391         struct ext4_block block_bitmap;
392         int rc =
393             ext4_block_get(bg_ref->fs->bdev, &block_bitmap, bitmap_block_addr);
394         if (rc != EOK)
395                 return rc;
396
397         /* Initialize all bitmap bits to zero */
398         uint32_t block_size = ext4_sb_get_block_size(&bg_ref->fs->sb);
399         uint32_t inodes_per_group =
400             ext4_get32(&bg_ref->fs->sb, inodes_per_group);
401
402         memset(block_bitmap.data, 0, (inodes_per_group + 7) / 8);
403
404         uint32_t start_bit = inodes_per_group;
405         uint32_t end_bit = block_size * 8;
406
407         uint32_t i;
408         for (i = start_bit; i < ((start_bit + 7) & ~7UL); i++)
409                 ext4_bmap_bit_set(block_bitmap.data, i);
410
411         if (i < end_bit)
412                 memset(block_bitmap.data + (i >> 3), 0xff, (end_bit - i) >> 3);
413
414         block_bitmap.dirty = true;
415
416         /* Save bitmap */
417         return ext4_block_set(bg_ref->fs->bdev, &block_bitmap);
418 }
419
420 /**@brief Initialize i-node table in block group.
421  * @param bg_ref Reference to block group
422  * @return Error code
423  */
424 static int ext4_fs_init_inode_table(struct ext4_block_group_ref *bg_ref)
425 {
426         struct ext4_sblock *sb = &bg_ref->fs->sb;
427
428         uint32_t inode_size = ext4_get32(sb, inode_size);
429         uint32_t block_size = ext4_sb_get_block_size(sb);
430         uint32_t inodes_per_block = block_size / inode_size;
431         uint32_t inodes_in_group = ext4_inodes_in_group_cnt(sb, bg_ref->index);
432         uint32_t table_blocks = inodes_in_group / inodes_per_block;
433         ext4_fsblk_t fblock;
434
435         if (inodes_in_group % inodes_per_block)
436                 table_blocks++;
437
438         /* Compute initialization bounds */
439         ext4_fsblk_t first_block =
440             ext4_bg_get_inode_table_first_block(bg_ref->block_group, sb);
441
442         ext4_fsblk_t last_block = first_block + table_blocks - 1;
443
444         /* Initialization of all itable blocks */
445         for (fblock = first_block; fblock <= last_block; ++fblock) {
446
447                 struct ext4_block block;
448                 int rc = ext4_block_get(bg_ref->fs->bdev, &block, fblock);
449                 if (rc != EOK)
450                         return rc;
451
452                 memset(block.data, 0, block_size);
453                 block.dirty = true;
454
455                 ext4_block_set(bg_ref->fs->bdev, &block);
456                 if (rc != EOK)
457                         return rc;
458         }
459
460         return EOK;
461 }
462
463 static ext4_fsblk_t ext4_fs_get_descriptor_block(struct ext4_sblock *s,
464                                              uint32_t bgid,
465                                              uint32_t dsc_per_block)
466 {
467         uint32_t first_meta_bg, dsc_id;
468
469         int has_super = 0;
470
471         dsc_id = bgid / dsc_per_block;
472         first_meta_bg = ext4_sb_first_meta_bg(s);
473
474         if (!ext4_sb_has_feature_incompatible(s,
475                                               EXT4_FEATURE_INCOMPAT_META_BG) ||
476             dsc_id < first_meta_bg)
477                 return ext4_get32(s, first_data_block) + dsc_id + 1;
478
479         if (ext4_sb_is_super_in_bg(s, bgid))
480                 has_super = 1;
481
482         return (has_super + ext4_fs_first_bg_block_no(s, bgid));
483 }
484
485 int ext4_fs_get_block_group_ref(struct ext4_fs *fs, uint32_t bgid,
486                                 struct ext4_block_group_ref *ref)
487 {
488         /* Compute number of descriptors, that fits in one data block */
489         uint32_t dsc_per_block =
490             ext4_sb_get_block_size(&fs->sb) / ext4_sb_get_desc_size(&fs->sb);
491
492         /* Block group descriptor table starts at the next block after
493          * superblock */
494         uint64_t block_id =
495             ext4_fs_get_descriptor_block(&fs->sb, bgid, dsc_per_block);
496
497         uint32_t offset =
498             (bgid % dsc_per_block) * ext4_sb_get_desc_size(&fs->sb);
499
500         int rc = ext4_block_get(fs->bdev, &ref->block, block_id);
501         if (rc != EOK)
502                 return rc;
503
504         ref->block_group = (void *)(ref->block.data + offset);
505         ref->fs = fs;
506         ref->index = bgid;
507         ref->dirty = false;
508
509         if (ext4_bg_has_flag(ref->block_group, EXT4_BLOCK_GROUP_BLOCK_UNINIT)) {
510                 rc = ext4_fs_init_block_bitmap(ref);
511                 if (rc != EOK) {
512                         ext4_block_set(fs->bdev, &ref->block);
513                         return rc;
514                 }
515                 ext4_bg_clear_flag(ref->block_group,
516                                    EXT4_BLOCK_GROUP_BLOCK_UNINIT);
517
518                 ref->dirty = true;
519         }
520
521         if (ext4_bg_has_flag(ref->block_group, EXT4_BLOCK_GROUP_INODE_UNINIT)) {
522                 rc = ext4_fs_init_inode_bitmap(ref);
523                 if (rc != EOK) {
524                         ext4_block_set(ref->fs->bdev, &ref->block);
525                         return rc;
526                 }
527
528                 ext4_bg_clear_flag(ref->block_group,
529                                    EXT4_BLOCK_GROUP_INODE_UNINIT);
530
531                 if (!ext4_bg_has_flag(ref->block_group,
532                                       EXT4_BLOCK_GROUP_ITABLE_ZEROED)) {
533                         rc = ext4_fs_init_inode_table(ref);
534                         if (rc != EOK) {
535                                 ext4_block_set(fs->bdev, &ref->block);
536                                 return rc;
537                         }
538
539                         ext4_bg_set_flag(ref->block_group,
540                                          EXT4_BLOCK_GROUP_ITABLE_ZEROED);
541                 }
542
543                 ref->dirty = true;
544         }
545
546         return EOK;
547 }
548
549 /**@brief  Compute checksum of block group descriptor.
550  * @param sb   Superblock
551  * @param bgid Index of block group in the filesystem
552  * @param bg   Block group to compute checksum for
553  * @return Checksum value
554  */
555 static uint16_t ext4_fs_bg_checksum(struct ext4_sblock *sb, uint32_t bgid,
556                                     struct ext4_bgroup *bg)
557 {
558         /* If checksum not supported, 0 will be returned */
559         uint16_t crc = 0;
560
561         /* Compute the checksum only if the filesystem supports it */
562         if (ext4_sb_has_feature_read_only(sb,
563                                 EXT4_FEATURE_RO_COMPAT_METADATA_CSUM)) {
564                 /* Use metadata_csum algorithm instead */
565                 uint32_t le32_bgid = to_le32(bgid);
566                 uint32_t orig_checksum, checksum;
567
568                 /* Preparation: temporarily set bg checksum to 0 */
569                 orig_checksum = bg->checksum;
570                 bg->checksum = 0;
571
572                 /* First calculate crc32 checksum against fs uuid */
573                 checksum = ext4_crc32c(~0, sb->uuid, sizeof(sb->uuid));
574                 /* Then calculate crc32 checksum against bgid */
575                 checksum = ext4_crc32c(checksum, (uint8_t *)&le32_bgid,
576                                      sizeof(bgid));
577                 /* Finally calculate crc32 checksum against block_group_desc */
578                 checksum = ext4_crc32c(checksum, (uint8_t *)bg,
579                                      ext4_sb_get_desc_size(sb));
580                 bg->checksum = orig_checksum;
581
582                 crc = checksum & 0xFFFF;
583         } else if (ext4_sb_has_feature_read_only(sb,
584                                         EXT4_FEATURE_RO_COMPAT_GDT_CSUM)) {
585                 uint8_t *base = (uint8_t *)bg;
586                 uint8_t *checksum = (uint8_t *)&bg->checksum;
587
588                 uint32_t offset = (uint32_t)(checksum - base);
589
590                 /* Convert block group index to little endian */
591                 uint32_t le_group = to_le32(bgid);
592
593                 /* Initialization */
594                 crc = ext4_bg_crc16(~0, sb->uuid, sizeof(sb->uuid));
595
596                 /* Include index of block group */
597                 crc =
598                     ext4_bg_crc16(crc, (uint8_t *)&le_group, sizeof(le_group));
599
600                 /* Compute crc from the first part (stop before checksum field)
601                  */
602                 crc = ext4_bg_crc16(crc, (uint8_t *)bg, offset);
603
604                 /* Skip checksum */
605                 offset += sizeof(bg->checksum);
606
607                 /* Checksum of the rest of block group descriptor */
608                 if ((ext4_sb_has_feature_incompatible(
609                         sb, EXT4_FEATURE_INCOMPAT_64BIT)) &&
610                     (offset < ext4_sb_get_desc_size(sb)))
611
612                         crc = ext4_bg_crc16(crc, ((uint8_t *)bg) + offset,
613                                             ext4_sb_get_desc_size(sb) - offset);
614         }
615         return crc;
616 }
617
618 int ext4_fs_put_block_group_ref(struct ext4_block_group_ref *ref)
619 {
620         /* Check if reference modified */
621         if (ref->dirty) {
622                 /* Compute new checksum of block group */
623                 uint16_t checksum = ext4_fs_bg_checksum(
624                     &ref->fs->sb, ref->index, ref->block_group);
625
626                 ref->block_group->checksum = to_le16(checksum);
627
628                 /* Mark block dirty for writing changes to physical device */
629                 ref->block.dirty = true;
630         }
631
632         /* Put back block, that contains block group descriptor */
633         return ext4_block_set(ref->fs->bdev, &ref->block);
634 }
635
636 /*
637  * BIG FAT NOTES:
638  *       Currently we do not verify the checksum of block_group_desc.
639  */
640 int ext4_fs_get_inode_ref(struct ext4_fs *fs, uint32_t index,
641                           struct ext4_inode_ref *ref)
642 {
643         /* Compute number of i-nodes, that fits in one data block */
644         uint32_t inodes_per_group = ext4_get32(&fs->sb, inodes_per_group);
645
646         /*
647          * Inode numbers are 1-based, but it is simpler to work with 0-based
648          * when computing indices
649          */
650         index -= 1;
651         uint32_t block_group = index / inodes_per_group;
652         uint32_t offset_in_group = index % inodes_per_group;
653
654         /* Load block group, where i-node is located */
655         struct ext4_block_group_ref bg_ref;
656
657         int rc = ext4_fs_get_block_group_ref(fs, block_group, &bg_ref);
658         if (rc != EOK) {
659                 return rc;
660         }
661
662         /* Load block address, where i-node table is located */
663         uint32_t inode_table_start =
664             ext4_bg_get_inode_table_first_block(bg_ref.block_group, &fs->sb);
665
666         /* Put back block group reference (not needed more) */
667         rc = ext4_fs_put_block_group_ref(&bg_ref);
668         if (rc != EOK) {
669                 return rc;
670         }
671
672         /* Compute position of i-node in the block group */
673         uint16_t inode_size = ext4_get16(&fs->sb, inode_size);
674         uint32_t block_size = ext4_sb_get_block_size(&fs->sb);
675         uint32_t byte_offset_in_group = offset_in_group * inode_size;
676
677         /* Compute block address */
678         ext4_fsblk_t block_id =
679             inode_table_start + (byte_offset_in_group / block_size);
680
681         rc = ext4_block_get(fs->bdev, &ref->block, block_id);
682         if (rc != EOK) {
683                 return rc;
684         }
685
686         /* Compute position of i-node in the data block */
687         uint32_t offset_in_block = byte_offset_in_group % block_size;
688         ref->inode = (struct ext4_inode *)(ref->block.data + offset_in_block);
689
690         /* We need to store the original value of index in the reference */
691         ref->index = index + 1;
692         ref->fs = fs;
693         ref->dirty = false;
694
695         return EOK;
696 }
697
698 int ext4_fs_put_inode_ref(struct ext4_inode_ref *ref)
699 {
700         /* Check if reference modified */
701         if (ref->dirty) {
702                 /* Mark block dirty for writing changes to physical device */
703                 ref->block.dirty = true;
704         }
705
706         /* Put back block, that contains i-node */
707         return ext4_block_set(ref->fs->bdev, &ref->block);
708 }
709
710 void ext4_fs_inode_blocks_init(struct ext4_fs *fs, struct ext4_inode_ref *inode_ref)
711 {
712         int i;
713         struct ext4_inode *inode = inode_ref->inode;
714
715         for (i = 0; i < EXT4_INODE_BLOCKS; i++)
716                 inode->blocks[i] = 0;
717
718         (void)fs;
719 #if CONFIG_EXTENT_ENABLE
720         /* Initialize extents if needed */
721         if (ext4_sb_has_feature_incompatible(&fs->sb,
722                                 EXT4_FEATURE_INCOMPAT_EXTENTS)) {
723                 ext4_inode_set_flag(inode, EXT4_INODE_FLAG_EXTENTS);
724
725                 /* Initialize extent root header */
726                 ext4_extent_tree_init(inode_ref);
727         }
728 #endif
729 }
730
731 static uint32_t ext4_fs_correspond_inode_mode(int filetype)
732 {
733         switch (filetype) {
734         case EXT4_DIRENTRY_DIR:
735                 return EXT4_INODE_MODE_DIRECTORY;
736         case EXT4_DIRENTRY_REG_FILE:
737                 return EXT4_INODE_MODE_FILE;
738         case EXT4_DIRENTRY_SYMLINK:
739                 return EXT4_INODE_MODE_SOFTLINK;
740         default:
741                 /* FIXME: right now we only support 3 file type. */
742                 ext4_assert(0);
743         }
744         return 0;
745 }
746
747 int ext4_fs_alloc_inode(struct ext4_fs *fs, struct ext4_inode_ref *inode_ref,
748                         int filetype)
749 {
750         /* Check if newly allocated i-node will be a directory */
751         bool is_dir;
752
753         is_dir = (filetype == EXT4_DIRENTRY_DIR);
754
755         /* Allocate inode by allocation algorithm */
756         uint32_t index;
757         int rc = ext4_ialloc_alloc_inode(fs, &index, is_dir);
758         if (rc != EOK)
759                 return rc;
760
761         /* Load i-node from on-disk i-node table */
762         rc = ext4_fs_get_inode_ref(fs, index, inode_ref);
763         if (rc != EOK) {
764                 ext4_ialloc_free_inode(fs, index, is_dir);
765                 return rc;
766         }
767
768         /* Initialize i-node */
769         struct ext4_inode *inode = inode_ref->inode;
770
771         uint32_t mode;
772         if (is_dir) {
773                 /*
774                  * Default directory permissions to be compatible with other
775                  * systems
776                  * 0777 (octal) == rwxrwxrwx
777                  */
778
779                 mode = 0777;
780                 mode |= EXT4_INODE_MODE_DIRECTORY;
781         } else {
782                 /*
783                  * Default file permissions to be compatible with other systems
784                  * 0666 (octal) == rw-rw-rw-
785                  */
786
787                 mode = 0666;
788                 mode |= ext4_fs_correspond_inode_mode(filetype);
789         }
790         ext4_inode_set_mode(&fs->sb, inode, mode);
791
792         ext4_inode_set_links_count(inode, 0);
793         ext4_inode_set_uid(inode, 0);
794         ext4_inode_set_gid(inode, 0);
795         ext4_inode_set_size(inode, 0);
796         ext4_inode_set_access_time(inode, 0);
797         ext4_inode_set_change_inode_time(inode, 0);
798         ext4_inode_set_modification_time(inode, 0);
799         ext4_inode_set_deletion_time(inode, 0);
800         ext4_inode_set_blocks_count(&fs->sb, inode, 0);
801         ext4_inode_set_flags(inode, 0);
802         ext4_inode_set_generation(inode, 0);
803
804         /* Reset blocks array. For symbolic link inode, just
805          * fill in blocks with 0 */
806         if (ext4_inode_is_type(&fs->sb, inode, EXT4_INODE_MODE_SOFTLINK)) {
807                 for (int i = 0; i < EXT4_INODE_BLOCKS; i++)
808                         inode->blocks[i] = 0;
809
810         } else
811                 ext4_fs_inode_blocks_init(fs, inode_ref);
812
813         inode_ref->dirty = true;
814
815         return EOK;
816 }
817
818 int ext4_fs_free_inode(struct ext4_inode_ref *inode_ref)
819 {
820         struct ext4_fs *fs = inode_ref->fs;
821         uint32_t offset;
822         uint32_t suboff;
823         int rc;
824 #if CONFIG_EXTENT_ENABLE
825         /* For extents must be data block destroyed by other way */
826         if ((ext4_sb_has_feature_incompatible(&fs->sb,
827                                               EXT4_FEATURE_INCOMPAT_EXTENTS)) &&
828             (ext4_inode_has_flag(inode_ref->inode, EXT4_INODE_FLAG_EXTENTS))) {
829                 /* Data structures are released during truncate operation... */
830                 goto finish;
831         }
832 #endif
833         /* Release all indirect (no data) blocks */
834
835         /* 1) Single indirect */
836         ext4_fsblk_t fblock = ext4_inode_get_indirect_block(inode_ref->inode, 0);
837         if (fblock != 0) {
838                 int rc = ext4_balloc_free_block(inode_ref, fblock);
839                 if (rc != EOK)
840                         return rc;
841
842                 ext4_inode_set_indirect_block(inode_ref->inode, 0, 0);
843         }
844
845         uint32_t block_size = ext4_sb_get_block_size(&fs->sb);
846         uint32_t count = block_size / sizeof(uint32_t);
847
848         struct ext4_block block;
849
850         /* 2) Double indirect */
851         fblock = ext4_inode_get_indirect_block(inode_ref->inode, 1);
852         if (fblock != 0) {
853                 int rc = ext4_block_get(fs->bdev, &block, fblock);
854                 if (rc != EOK)
855                         return rc;
856
857                 ext4_fsblk_t ind_block;
858                 for (offset = 0; offset < count; ++offset) {
859                         ind_block = to_le32(((uint32_t *)block.data)[offset]);
860
861                         if (ind_block == 0)
862                                 continue;
863                         rc = ext4_balloc_free_block(inode_ref, ind_block);
864                         if (rc != EOK) {
865                                 ext4_block_set(fs->bdev, &block);
866                                 return rc;
867                         }
868
869                 }
870
871                 ext4_block_set(fs->bdev, &block);
872                 rc = ext4_balloc_free_block(inode_ref, fblock);
873                 if (rc != EOK)
874                         return rc;
875
876                 ext4_inode_set_indirect_block(inode_ref->inode, 1, 0);
877         }
878
879         /* 3) Tripple indirect */
880         struct ext4_block subblock;
881         fblock = ext4_inode_get_indirect_block(inode_ref->inode, 2);
882         if (fblock == 0)
883                 goto finish;
884         rc = ext4_block_get(fs->bdev, &block, fblock);
885         if (rc != EOK)
886                 return rc;
887
888         ext4_fsblk_t ind_block;
889         for (offset = 0; offset < count; ++offset) {
890                 ind_block = to_le32(((uint32_t *)block.data)[offset]);
891
892                 if (ind_block == 0)
893                         continue;
894                 rc = ext4_block_get(fs->bdev, &subblock,
895                                 ind_block);
896                 if (rc != EOK) {
897                         ext4_block_set(fs->bdev, &block);
898                         return rc;
899                 }
900
901                 ext4_fsblk_t ind_subblk;
902                 for (suboff = 0; suboff < count; ++suboff) {
903                         ind_subblk = to_le32(((uint32_t *)subblock.data)[suboff]);
904
905                         if (ind_subblk == 0)
906                                 continue;
907                         rc = ext4_balloc_free_block(inode_ref, ind_subblk);
908                         if (rc != EOK) {
909                                 ext4_block_set(fs->bdev, &subblock);
910                                 ext4_block_set(fs->bdev, &block);
911                                 return rc;
912                         }
913
914                 }
915
916                 ext4_block_set(fs->bdev, &subblock);
917
918                 rc = ext4_balloc_free_block(inode_ref,
919                                 ind_block);
920                 if (rc != EOK) {
921                         ext4_block_set(fs->bdev, &block);
922                         return rc;
923                 }
924
925         }
926
927         ext4_block_set(fs->bdev, &block);
928         rc = ext4_balloc_free_block(inode_ref, fblock);
929         if (rc != EOK)
930                 return rc;
931
932         ext4_inode_set_indirect_block(inode_ref->inode, 2, 0);
933 finish:
934         /* Mark inode dirty for writing to the physical device */
935         inode_ref->dirty = true;
936
937         /* Free block with extended attributes if present */
938         ext4_fsblk_t xattr_block =
939             ext4_inode_get_file_acl(inode_ref->inode, &fs->sb);
940         if (xattr_block) {
941                 int rc = ext4_balloc_free_block(inode_ref, xattr_block);
942                 if (rc != EOK)
943                         return rc;
944
945                 ext4_inode_set_file_acl(inode_ref->inode, &fs->sb, 0);
946         }
947
948         /* Free inode by allocator */
949         if (ext4_inode_is_type(&fs->sb, inode_ref->inode,
950                                EXT4_INODE_MODE_DIRECTORY))
951                 rc = ext4_ialloc_free_inode(fs, inode_ref->index, true);
952         else
953                 rc = ext4_ialloc_free_inode(fs, inode_ref->index, false);
954
955         return rc;
956 }
957
958
959 /**@brief Release data block from i-node
960  * @param inode_ref I-node to release block from
961  * @param iblock    Logical block to be released
962  * @return Error code
963  */
964 static int ext4_fs_release_inode_block(struct ext4_inode_ref *inode_ref,
965                                 uint32_t iblock)
966 {
967         ext4_fsblk_t fblock;
968
969         struct ext4_fs *fs = inode_ref->fs;
970
971         /* Extents are handled otherwise = there is not support in this function
972          */
973         ext4_assert(!(
974             ext4_sb_has_feature_incompatible(&fs->sb,
975                                              EXT4_FEATURE_INCOMPAT_EXTENTS) &&
976             (ext4_inode_has_flag(inode_ref->inode, EXT4_INODE_FLAG_EXTENTS))));
977
978         struct ext4_inode *inode = inode_ref->inode;
979
980         /* Handle simple case when we are dealing with direct reference */
981         if (iblock < EXT4_INODE_DIRECT_BLOCK_COUNT) {
982                 fblock = ext4_inode_get_direct_block(inode, iblock);
983
984                 /* Sparse file */
985                 if (fblock == 0)
986                         return EOK;
987
988                 ext4_inode_set_direct_block(inode, iblock, 0);
989                 return ext4_balloc_free_block(inode_ref, fblock);
990         }
991
992         /* Determine the indirection level needed to get the desired block */
993         unsigned int level = 0;
994         unsigned int i;
995         for (i = 1; i < 4; i++) {
996                 if (iblock < fs->inode_block_limits[i]) {
997                         level = i;
998                         break;
999                 }
1000         }
1001
1002         if (level == 0)
1003                 return EIO;
1004
1005         /* Compute offsets for the topmost level */
1006         uint64_t block_offset_in_level =
1007             iblock - fs->inode_block_limits[level - 1];
1008         ext4_fsblk_t current_block =
1009             ext4_inode_get_indirect_block(inode, level - 1);
1010         uint32_t offset_in_block =
1011             block_offset_in_level / fs->inode_blocks_per_level[level - 1];
1012
1013         /*
1014          * Navigate through other levels, until we find the block number
1015          * or find null reference meaning we are dealing with sparse file
1016          */
1017         struct ext4_block block;
1018
1019         while (level > 0) {
1020
1021                 /* Sparse check */
1022                 if (current_block == 0)
1023                         return EOK;
1024
1025                 int rc = ext4_block_get(fs->bdev, &block, current_block);
1026                 if (rc != EOK)
1027                         return rc;
1028
1029                 current_block =
1030                     to_le32(((uint32_t *)block.data)[offset_in_block]);
1031
1032                 /* Set zero if physical data block address found */
1033                 if (level == 1) {
1034                         ((uint32_t *)block.data)[offset_in_block] = to_le32(0);
1035                         block.dirty = true;
1036                 }
1037
1038                 rc = ext4_block_set(fs->bdev, &block);
1039                 if (rc != EOK)
1040                         return rc;
1041
1042                 level--;
1043
1044                 /*
1045                  * If we are on the last level, break here as
1046                  * there is no next level to visit
1047                  */
1048                 if (level == 0)
1049                         break;
1050
1051                 /* Visit the next level */
1052                 block_offset_in_level %= fs->inode_blocks_per_level[level];
1053                 offset_in_block = block_offset_in_level /
1054                                   fs->inode_blocks_per_level[level - 1];
1055         }
1056
1057         fblock = current_block;
1058         if (fblock == 0)
1059                 return EOK;
1060
1061         /* Physical block is not referenced, it can be released */
1062         return ext4_balloc_free_block(inode_ref, fblock);
1063 }
1064
1065 int ext4_fs_truncate_inode(struct ext4_inode_ref *inode_ref, uint64_t new_size)
1066 {
1067         struct ext4_sblock *sb = &inode_ref->fs->sb;
1068         uint32_t i;
1069
1070         /* Check flags, if i-node can be truncated */
1071         if (!ext4_inode_can_truncate(sb, inode_ref->inode))
1072                 return EINVAL;
1073
1074         /* If sizes are equal, nothing has to be done. */
1075         uint64_t old_size = ext4_inode_get_size(sb, inode_ref->inode);
1076         if (old_size == new_size)
1077                 return EOK;
1078
1079         /* It's not supported to make the larger file by truncate operation */
1080         if (old_size < new_size)
1081                 return EINVAL;
1082
1083         if (ext4_inode_is_type(sb, inode_ref->inode, EXT4_INODE_MODE_SOFTLINK)
1084                         && old_size < sizeof(inode_ref->inode->blocks)
1085                         && !ext4_inode_get_blocks_count(sb, inode_ref->inode)) {
1086                 char *content = (char *)inode_ref->inode->blocks;
1087                 memset(content + new_size, 0,
1088                         sizeof(inode_ref->inode->blocks) - new_size);
1089                 ext4_inode_set_size(inode_ref->inode, new_size);
1090                 inode_ref->dirty = true;
1091
1092                 return EOK;
1093         }
1094
1095         /* Compute how many blocks will be released */
1096         uint32_t block_size = ext4_sb_get_block_size(sb);
1097         uint32_t new_blocks_count = (new_size + block_size - 1) /
1098                                     block_size;
1099         uint32_t old_blocks_count = (old_size + block_size - 1) /
1100                                     block_size;
1101         uint32_t diff_blocks_count = old_blocks_count - new_blocks_count;
1102 #if CONFIG_EXTENT_ENABLE
1103         if ((ext4_sb_has_feature_incompatible(sb,
1104                                               EXT4_FEATURE_INCOMPAT_EXTENTS)) &&
1105             (ext4_inode_has_flag(inode_ref->inode, EXT4_INODE_FLAG_EXTENTS))) {
1106
1107                 /* Extents require special operation */
1108                 if (diff_blocks_count) {
1109                         int rc = ext4_extent_remove_space(inode_ref,
1110                                         new_blocks_count, EXT_MAX_BLOCKS);
1111                         if (rc != EOK)
1112                                 return rc;
1113
1114                 }
1115         } else
1116 #endif
1117         {
1118                 /* Release data blocks from the end of file */
1119
1120                 /* Starting from 1 because of logical blocks are numbered from 0
1121                  */
1122                 for (i = 0; i < diff_blocks_count; ++i) {
1123                         int rc = ext4_fs_release_inode_block(
1124                             inode_ref, new_blocks_count + i);
1125                         if (rc != EOK)
1126                                 return rc;
1127                 }
1128         }
1129
1130         /* Update i-node */
1131         ext4_inode_set_size(inode_ref->inode, new_size);
1132         inode_ref->dirty = true;
1133
1134         return EOK;
1135 }
1136
1137 /**@brief Compute 'goal' for inode index
1138  * @param inode_ref Reference to inode, to allocate block for
1139  * @return goal
1140  */
1141 ext4_fsblk_t ext4_fs_inode_to_goal_block(struct ext4_inode_ref *inode_ref)
1142 {
1143         uint32_t group_inodes =
1144                 ext4_get32(&inode_ref->fs->sb, inodes_per_group);
1145         return (inode_ref->index - 1) / group_inodes;
1146 }
1147
1148 /**@brief Compute 'goal' for allocation algorithm (For blockmap).
1149  * @param inode_ref Reference to inode, to allocate block for
1150  * @param goal
1151  * @return error code
1152  */
1153 int ext4_fs_indirect_find_goal(struct ext4_inode_ref *inode_ref,
1154                                 ext4_fsblk_t *goal)
1155 {
1156         struct ext4_sblock *sb = &inode_ref->fs->sb;
1157         *goal = 0;
1158
1159         uint64_t inode_size = ext4_inode_get_size(sb, inode_ref->inode);
1160         uint32_t block_size = ext4_sb_get_block_size(sb);
1161         uint32_t inode_block_count = inode_size / block_size;
1162
1163         if (inode_size % block_size != 0)
1164                 inode_block_count++;
1165
1166         /* If inode has some blocks, get last block address + 1 */
1167         if (inode_block_count > 0) {
1168                 int rc = ext4_fs_get_inode_data_block_index(
1169                     inode_ref, inode_block_count - 1, goal, false);
1170                 if (rc != EOK)
1171                         return rc;
1172
1173                 if (*goal != 0) {
1174                         (*goal)++;
1175                         return rc;
1176                 }
1177
1178                 /* If goal == 0, sparse file -> continue */
1179         }
1180
1181         /* Identify block group of inode */
1182
1183         uint32_t inodes_per_group = ext4_get32(sb, inodes_per_group);
1184         uint32_t block_group = (inode_ref->index - 1) / inodes_per_group;
1185         block_size = ext4_sb_get_block_size(sb);
1186
1187         /* Load block group reference */
1188         struct ext4_block_group_ref bg_ref;
1189         int rc =
1190             ext4_fs_get_block_group_ref(inode_ref->fs, block_group, &bg_ref);
1191         if (rc != EOK)
1192                 return rc;
1193
1194         /* Compute indexes */
1195         uint32_t block_group_count = ext4_block_group_cnt(sb);
1196         ext4_fsblk_t inode_table_first_block =
1197             ext4_bg_get_inode_table_first_block(bg_ref.block_group, sb);
1198         uint16_t inode_table_item_size = ext4_get16(sb, inode_size);
1199         uint32_t inode_table_bytes;
1200
1201         /* Check for last block group */
1202         if (block_group < block_group_count - 1) {
1203                 inode_table_bytes = inodes_per_group * inode_table_item_size;
1204         } else {
1205                 /* Last block group could be smaller */
1206                 uint32_t inodes_count_total = ext4_get32(sb, inodes_count);
1207
1208                 inode_table_bytes =
1209                     (inodes_count_total -
1210                      ((block_group_count - 1) * inodes_per_group)) *
1211                     inode_table_item_size;
1212         }
1213
1214         ext4_fsblk_t inode_table_blocks = inode_table_bytes / block_size;
1215
1216         if (inode_table_bytes % block_size)
1217                 inode_table_blocks++;
1218
1219         *goal = inode_table_first_block + inode_table_blocks;
1220
1221         return ext4_fs_put_block_group_ref(&bg_ref);
1222 }
1223
1224 static int ext4_fs_get_inode_data_block_idx(struct ext4_inode_ref *inode_ref,
1225                                        uint64_t iblock, ext4_fsblk_t *fblock,
1226                                        bool extent_create,
1227                                        bool support_unwritten)
1228 {
1229         struct ext4_fs *fs = inode_ref->fs;
1230
1231         /* For empty file is situation simple */
1232         if (ext4_inode_get_size(&fs->sb, inode_ref->inode) == 0) {
1233                 *fblock = 0;
1234                 return EOK;
1235         }
1236
1237         ext4_fsblk_t current_block;
1238
1239         (void)extent_create;
1240 #if CONFIG_EXTENT_ENABLE
1241         /* Handle i-node using extents */
1242         if ((ext4_sb_has_feature_incompatible(&fs->sb,
1243                                               EXT4_FEATURE_INCOMPAT_EXTENTS)) &&
1244             (ext4_inode_has_flag(inode_ref->inode, EXT4_INODE_FLAG_EXTENTS))) {
1245
1246                 ext4_fsblk_t current_fsblk;
1247                 int rc = ext4_extent_get_blocks(inode_ref, iblock, 1,
1248                                 &current_fsblk, extent_create, NULL);
1249                 if (rc != EOK)
1250                         return rc;
1251
1252                 current_block = current_fsblk;
1253                 *fblock = current_block;
1254
1255                 ext4_assert(*fblock || support_unwritten);
1256                 return EOK;
1257         }
1258 #endif
1259
1260         struct ext4_inode *inode = inode_ref->inode;
1261
1262         /* Direct block are read directly from array in i-node structure */
1263         if (iblock < EXT4_INODE_DIRECT_BLOCK_COUNT) {
1264                 current_block =
1265                     ext4_inode_get_direct_block(inode, (uint32_t)iblock);
1266                 *fblock = current_block;
1267                 return EOK;
1268         }
1269
1270         /* Determine indirection level of the target block */
1271         unsigned int level = 0;
1272         unsigned int i;
1273         for (i = 1; i < 4; i++) {
1274                 if (iblock < fs->inode_block_limits[i]) {
1275                         level = i;
1276                         break;
1277                 }
1278         }
1279
1280         if (level == 0)
1281                 return EIO;
1282
1283         /* Compute offsets for the topmost level */
1284         uint64_t block_offset_in_level =
1285             iblock - fs->inode_block_limits[level - 1];
1286         current_block = ext4_inode_get_indirect_block(inode, level - 1);
1287         uint32_t offset_in_block =
1288             block_offset_in_level / fs->inode_blocks_per_level[level - 1];
1289
1290         /* Sparse file */
1291         if (current_block == 0) {
1292                 *fblock = 0;
1293                 return EOK;
1294         }
1295
1296         struct ext4_block block;
1297
1298         /*
1299          * Navigate through other levels, until we find the block number
1300          * or find null reference meaning we are dealing with sparse file
1301          */
1302         while (level > 0) {
1303                 /* Load indirect block */
1304                 int rc = ext4_block_get(fs->bdev, &block, current_block);
1305                 if (rc != EOK)
1306                         return rc;
1307
1308                 /* Read block address from indirect block */
1309                 current_block =
1310                     to_le32(((uint32_t *)block.data)[offset_in_block]);
1311
1312                 /* Put back indirect block untouched */
1313                 rc = ext4_block_set(fs->bdev, &block);
1314                 if (rc != EOK)
1315                         return rc;
1316
1317                 /* Check for sparse file */
1318                 if (current_block == 0) {
1319                         *fblock = 0;
1320                         return EOK;
1321                 }
1322
1323                 /* Jump to the next level */
1324                 level--;
1325
1326                 /* Termination condition - we have address of data block loaded
1327                  */
1328                 if (level == 0)
1329                         break;
1330
1331                 /* Visit the next level */
1332                 block_offset_in_level %= fs->inode_blocks_per_level[level];
1333                 offset_in_block = block_offset_in_level /
1334                                   fs->inode_blocks_per_level[level - 1];
1335         }
1336
1337         *fblock = current_block;
1338
1339         return EOK;
1340 }
1341
1342
1343 int ext4_fs_get_inode_data_block_index(struct ext4_inode_ref *inode_ref,
1344                                        uint64_t iblock, ext4_fsblk_t *fblock,
1345                                        bool support_unwritten)
1346 {
1347         return ext4_fs_get_inode_data_block_idx(inode_ref, iblock, fblock,
1348                         false, support_unwritten);
1349 }
1350
1351 int ext4_fs_init_inode_data_block_index(struct ext4_inode_ref *inode_ref,
1352                                        uint64_t iblock, ext4_fsblk_t *fblock)
1353 {
1354         return ext4_fs_get_inode_data_block_idx(inode_ref, iblock, fblock,
1355                         true, true);
1356 }
1357
1358 static int ext4_fs_set_inode_data_block_index(struct ext4_inode_ref *inode_ref,
1359                                        uint64_t iblock, ext4_fsblk_t fblock)
1360 {
1361         struct ext4_fs *fs = inode_ref->fs;
1362
1363 #if CONFIG_EXTENT_ENABLE
1364         /* Handle inode using extents */
1365         if ((ext4_sb_has_feature_incompatible(&fs->sb,
1366                                               EXT4_FEATURE_INCOMPAT_EXTENTS)) &&
1367             (ext4_inode_has_flag(inode_ref->inode, EXT4_INODE_FLAG_EXTENTS))) {
1368                 /* Not reachable */
1369                 return ENOTSUP;
1370         }
1371 #endif
1372
1373         /* Handle simple case when we are dealing with direct reference */
1374         if (iblock < EXT4_INODE_DIRECT_BLOCK_COUNT) {
1375                 ext4_inode_set_direct_block(inode_ref->inode, (uint32_t)iblock,
1376                                             (uint32_t)fblock);
1377                 inode_ref->dirty = true;
1378
1379                 return EOK;
1380         }
1381
1382         /* Determine the indirection level needed to get the desired block */
1383         unsigned int level = 0;
1384         unsigned int i;
1385         for (i = 1; i < 4; i++) {
1386                 if (iblock < fs->inode_block_limits[i]) {
1387                         level = i;
1388                         break;
1389                 }
1390         }
1391
1392         if (level == 0)
1393                 return EIO;
1394
1395         uint32_t block_size = ext4_sb_get_block_size(&fs->sb);
1396
1397         /* Compute offsets for the topmost level */
1398         uint64_t block_offset_in_level =
1399             iblock - fs->inode_block_limits[level - 1];
1400         ext4_fsblk_t current_block =
1401             ext4_inode_get_indirect_block(inode_ref->inode, level - 1);
1402         uint32_t offset_in_block =
1403             block_offset_in_level / fs->inode_blocks_per_level[level - 1];
1404
1405         ext4_fsblk_t new_block_addr;
1406
1407         struct ext4_block block;
1408         struct ext4_block new_block;
1409
1410         /* Is needed to allocate indirect block on the i-node level */
1411         if (current_block == 0) {
1412                 /* Allocate new indirect block */
1413                 ext4_fsblk_t goal;
1414                 int rc = ext4_fs_indirect_find_goal(inode_ref, &goal);
1415                 if (rc != EOK)
1416                         return rc;
1417
1418                 rc = ext4_balloc_alloc_block(inode_ref,
1419                                              goal,
1420                                              &new_block_addr);
1421                 if (rc != EOK)
1422                         return rc;
1423
1424                 /* Update i-node */
1425                 ext4_inode_set_indirect_block(inode_ref->inode, level - 1,
1426                                               (uint32_t)new_block_addr);
1427                 inode_ref->dirty = true;
1428
1429                 /* Load newly allocated block */
1430                 rc = ext4_block_get(fs->bdev, &new_block, new_block_addr);
1431                 if (rc != EOK) {
1432                         ext4_balloc_free_block(inode_ref, new_block_addr);
1433                         return rc;
1434                 }
1435
1436                 /* Initialize new block */
1437                 memset(new_block.data, 0, block_size);
1438                 new_block.dirty = true;
1439
1440                 /* Put back the allocated block */
1441                 rc = ext4_block_set(fs->bdev, &new_block);
1442                 if (rc != EOK)
1443                         return rc;
1444
1445                 current_block = new_block_addr;
1446         }
1447
1448         /*
1449          * Navigate through other levels, until we find the block number
1450          * or find null reference meaning we are dealing with sparse file
1451          */
1452         while (level > 0) {
1453                 int rc = ext4_block_get(fs->bdev, &block, current_block);
1454                 if (rc != EOK)
1455                         return rc;
1456
1457                 current_block =
1458                     to_le32(((uint32_t *)block.data)[offset_in_block]);
1459
1460                 if ((level > 1) && (current_block == 0)) {
1461                         ext4_fsblk_t goal;
1462                         rc = ext4_fs_indirect_find_goal(inode_ref, &goal);
1463                         if (rc != EOK) {
1464                                 ext4_block_set(fs->bdev, &block);
1465                                 return rc;
1466                         }
1467
1468                         /* Allocate new block */
1469                         rc =
1470                             ext4_balloc_alloc_block(inode_ref, goal, &new_block_addr);
1471                         if (rc != EOK) {
1472                                 ext4_block_set(fs->bdev, &block);
1473                                 return rc;
1474                         }
1475
1476                         /* Load newly allocated block */
1477                         rc = ext4_block_get(fs->bdev, &new_block,
1478                                             new_block_addr);
1479
1480                         if (rc != EOK) {
1481                                 ext4_block_set(fs->bdev, &block);
1482                                 return rc;
1483                         }
1484
1485                         /* Initialize allocated block */
1486                         memset(new_block.data, 0, block_size);
1487                         new_block.dirty = true;
1488
1489                         rc = ext4_block_set(fs->bdev, &new_block);
1490                         if (rc != EOK) {
1491                                 ext4_block_set(fs->bdev, &block);
1492                                 return rc;
1493                         }
1494
1495                         /* Write block address to the parent */
1496                         ((uint32_t *)block.data)[offset_in_block] =
1497                             to_le32((uint32_t)new_block_addr);
1498                         block.dirty = true;
1499                         current_block = new_block_addr;
1500                 }
1501
1502                 /* Will be finished, write the fblock address */
1503                 if (level == 1) {
1504                         ((uint32_t *)block.data)[offset_in_block] =
1505                             to_le32((uint32_t)fblock);
1506                         block.dirty = true;
1507                 }
1508
1509                 rc = ext4_block_set(fs->bdev, &block);
1510                 if (rc != EOK)
1511                         return rc;
1512
1513                 level--;
1514
1515                 /*
1516                  * If we are on the last level, break here as
1517                  * there is no next level to visit
1518                  */
1519                 if (level == 0)
1520                         break;
1521
1522                 /* Visit the next level */
1523                 block_offset_in_level %= fs->inode_blocks_per_level[level];
1524                 offset_in_block = block_offset_in_level /
1525                                   fs->inode_blocks_per_level[level - 1];
1526         }
1527
1528         return EOK;
1529 }
1530
1531
1532 int ext4_fs_append_inode_block(struct ext4_inode_ref *inode_ref,
1533                                ext4_fsblk_t *fblock, uint32_t *iblock)
1534 {
1535 #if CONFIG_EXTENT_ENABLE
1536         /* Handle extents separately */
1537         if ((ext4_sb_has_feature_incompatible(&inode_ref->fs->sb,
1538                                               EXT4_FEATURE_INCOMPAT_EXTENTS)) &&
1539             (ext4_inode_has_flag(inode_ref->inode, EXT4_INODE_FLAG_EXTENTS))) {
1540                 int rc;
1541                 ext4_fsblk_t current_fsblk;
1542                 struct ext4_sblock *sb = &inode_ref->fs->sb;
1543                 uint64_t inode_size = ext4_inode_get_size(sb, inode_ref->inode);
1544                 uint32_t block_size = ext4_sb_get_block_size(sb);
1545                 *iblock = (inode_size + block_size - 1) /
1546                                     block_size;
1547
1548                 rc = ext4_extent_get_blocks(inode_ref, *iblock, 1,
1549                                 &current_fsblk, true, NULL);
1550
1551
1552                 *fblock = current_fsblk;
1553                 ext4_assert(*fblock);
1554
1555                 ext4_inode_set_size(inode_ref->inode,
1556                                     inode_size + block_size);
1557                 inode_ref->dirty = true;
1558
1559
1560                 return rc;
1561         }
1562 #endif
1563         struct ext4_sblock *sb = &inode_ref->fs->sb;
1564
1565         /* Compute next block index and allocate data block */
1566         uint64_t inode_size = ext4_inode_get_size(sb, inode_ref->inode);
1567         uint32_t block_size = ext4_sb_get_block_size(sb);
1568
1569         /* Align size i-node size */
1570         if ((inode_size % block_size) != 0)
1571                 inode_size += block_size - (inode_size % block_size);
1572
1573         /* Logical blocks are numbered from 0 */
1574         uint32_t new_block_idx = inode_size / block_size;
1575
1576         /* Allocate new physical block */
1577         ext4_fsblk_t goal, phys_block;
1578         int rc = ext4_fs_indirect_find_goal(inode_ref, &goal);
1579         if (rc != EOK)
1580                 return rc;
1581
1582         rc = ext4_balloc_alloc_block(inode_ref, goal, &phys_block);
1583         if (rc != EOK)
1584                 return rc;
1585
1586         /* Add physical block address to the i-node */
1587         rc = ext4_fs_set_inode_data_block_index(inode_ref, new_block_idx,
1588                                                 phys_block);
1589         if (rc != EOK) {
1590                 ext4_balloc_free_block(inode_ref, phys_block);
1591                 return rc;
1592         }
1593
1594         /* Update i-node */
1595         ext4_inode_set_size(inode_ref->inode, inode_size + block_size);
1596         inode_ref->dirty = true;
1597
1598         *fblock = phys_block;
1599         *iblock = new_block_idx;
1600
1601         return EOK;
1602 }
1603
1604 void ext4_fs_inode_links_count_inc(struct ext4_inode_ref *inode_ref)
1605 {
1606         uint16_t link;
1607
1608         link = ext4_inode_get_links_count(inode_ref->inode);
1609         link++;
1610         ext4_inode_set_links_count(inode_ref->inode, link);
1611
1612         bool is_dx =
1613             ext4_sb_has_feature_compatible(&inode_ref->fs->sb,
1614                                            EXT4_FEATURE_COMPAT_DIR_INDEX) &&
1615             ext4_inode_has_flag(inode_ref->inode, EXT4_INODE_FLAG_INDEX);
1616
1617         if (is_dx && link > 1) {
1618                 if (link >= EXT4_LINK_MAX || link == 2) {
1619                         ext4_inode_set_links_count(inode_ref->inode, 1);
1620
1621                         uint32_t v =
1622                             ext4_get32(&inode_ref->fs->sb, features_read_only);
1623                         v |= EXT4_FEATURE_RO_COMPAT_DIR_NLINK;
1624                         ext4_set32(&inode_ref->fs->sb, features_read_only, v);
1625                 }
1626         }
1627 }
1628
1629 void ext4_fs_inode_links_count_dec(struct ext4_inode_ref *inode_ref)
1630 {
1631         uint16_t links = ext4_inode_get_links_count(inode_ref->inode);
1632         if (!ext4_inode_is_type(&inode_ref->fs->sb, inode_ref->inode,
1633                                 EXT4_INODE_MODE_DIRECTORY)) {
1634                 if (links > 0)
1635                         ext4_inode_set_links_count(inode_ref->inode, links - 1);
1636                 return;
1637         }
1638
1639         if (links > 2)
1640                 ext4_inode_set_links_count(inode_ref->inode, links - 1);
1641 }
1642
1643 /**
1644  * @}
1645  */