FIX: simple extent implementation overwriting the inode block.
[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_FINCOM_COMPRESSION)
132                 ext4_dbg(DEBUG_FS, DBG_NONE "compression\n");
133         if (features_incompatible & EXT4_FINCOM_FILETYPE)
134                 ext4_dbg(DEBUG_FS, DBG_NONE "filetype\n");
135         if (features_incompatible & EXT4_FINCOM_RECOVER)
136                 ext4_dbg(DEBUG_FS, DBG_NONE "recover\n");
137         if (features_incompatible & EXT4_FINCOM_JOURNAL_DEV)
138                 ext4_dbg(DEBUG_FS, DBG_NONE "journal_dev\n");
139         if (features_incompatible & EXT4_FINCOM_META_BG)
140                 ext4_dbg(DEBUG_FS, DBG_NONE "meta_bg\n");
141         if (features_incompatible & EXT4_FINCOM_EXTENTS)
142                 ext4_dbg(DEBUG_FS, DBG_NONE "extents\n");
143         if (features_incompatible & EXT4_FINCOM_64BIT)
144                 ext4_dbg(DEBUG_FS, DBG_NONE "64bit\n");
145         if (features_incompatible & EXT4_FINCOM_MMP)
146                 ext4_dbg(DEBUG_FS, DBG_NONE "mnp\n");
147         if (features_incompatible & EXT4_FINCOM_FLEX_BG)
148                 ext4_dbg(DEBUG_FS, DBG_NONE "flex_bg\n");
149         if (features_incompatible & EXT4_FINCOM_EA_INODE)
150                 ext4_dbg(DEBUG_FS, DBG_NONE "ea_inode\n");
151         if (features_incompatible & EXT4_FINCOM_DIRDATA)
152                 ext4_dbg(DEBUG_FS, DBG_NONE "dirdata\n");
153         if (features_incompatible & EXT4_FINCOM_BG_USE_META_CSUM)
154                 ext4_dbg(DEBUG_FS, DBG_NONE "meta_csum\n");
155         if (features_incompatible & EXT4_FINCOM_LARGEDIR)
156                 ext4_dbg(DEBUG_FS, DBG_NONE "largedir\n");
157         if (features_incompatible & EXT4_FINCOM_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_FCOM_DIR_PREALLOC)
163                 ext4_dbg(DEBUG_FS, DBG_NONE "dir_prealloc\n");
164         if (features_compatible & EXT4_FCOM_IMAGIC_INODES)
165                 ext4_dbg(DEBUG_FS, DBG_NONE "imagic_inodes\n");
166         if (features_compatible & EXT4_FCOM_HAS_JOURNAL)
167                 ext4_dbg(DEBUG_FS, DBG_NONE "has_journal\n");
168         if (features_compatible & EXT4_FCOM_EXT_ATTR)
169                 ext4_dbg(DEBUG_FS, DBG_NONE "ext_attr\n");
170         if (features_compatible & EXT4_FCOM_RESIZE_INODE)
171                 ext4_dbg(DEBUG_FS, DBG_NONE "resize_inode\n");
172         if (features_compatible & EXT4_FCOM_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_FRO_COM_SPARSE_SUPER)
179                 ext4_dbg(DEBUG_FS, DBG_NONE "sparse_super\n");
180         if (features_ro & EXT4_FRO_COM_LARGE_FILE)
181                 ext4_dbg(DEBUG_FS, DBG_NONE "large_file\n");
182         if (features_ro & EXT4_FRO_COM_BTREE_DIR)
183                 ext4_dbg(DEBUG_FS, DBG_NONE "btree_dir\n");
184         if (features_ro & EXT4_FRO_COM_HUGE_FILE)
185                 ext4_dbg(DEBUG_FS, DBG_NONE "huge_file\n");
186         if (features_ro & EXT4_FRO_COM_GDT_CSUM)
187                 ext4_dbg(DEBUG_FS, DBG_NONE "gtd_csum\n");
188         if (features_ro & EXT4_FRO_COM_DIR_NLINK)
189                 ext4_dbg(DEBUG_FS, DBG_NONE "dir_nlink\n");
190         if (features_ro & EXT4_FRO_COM_EXTRA_ISIZE)
191                 ext4_dbg(DEBUG_FS, DBG_NONE "extra_isize\n");
192         if (features_ro & EXT4_FRO_COM_QUOTA)
193                 ext4_dbg(DEBUG_FS, DBG_NONE "quota\n");
194         if (features_ro & EXT4_FRO_COM_BIGALLOC)
195                 ext4_dbg(DEBUG_FS, DBG_NONE "bigalloc\n");
196         if (features_ro & EXT4_FRO_COM_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_SUPPORTED_FINCOM));
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_SUPPORTED_FRO_COM));
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_feature_incom(&bg_ref->fs->sb, EXT4_FINCOM_FLEX_BG);
304
305         uint32_t inode_table_bcnt = inodes_per_group * inode_size / block_size;
306
307         struct ext4_block block_bitmap;
308         int rc =
309             ext4_block_get(bg_ref->fs->bdev, &block_bitmap, bitmap_block_addr);
310         if (rc != EOK)
311                 return rc;
312
313         memset(block_bitmap.data, 0, block_size);
314
315         bit_max = ext4_sb_is_super_in_bg(&bg_ref->fs->sb, bg_ref->index);
316         if (!ext4_sb_feature_incom(&bg_ref->fs->sb, EXT4_FINCOM_META_BG) ||
317                         bg_ref->index < ext4_sb_first_meta_bg(&bg_ref->fs->sb) *
318                         dsc_per_block) {
319                 if (bit_max) {
320                         bit_max += ext4_bg_num_gdb(&bg_ref->fs->sb,
321                                                    bg_ref->index);
322                         bit_max +=
323                                 ext4_get16(&bg_ref->fs->sb,
324                                            s_reserved_gdt_blocks);
325                 }
326         } else { /* For META_BG_BLOCK_GROUPS */
327                 bit_max += ext4_bg_num_gdb(&bg_ref->fs->sb,
328                                            bg_ref->index);
329         }
330         for (bit = 0; bit < bit_max; bit++)
331                 ext4_bmap_bit_set(block_bitmap.data, bit);
332
333         if (bg_ref->index == ext4_block_group_cnt(&bg_ref->fs->sb) - 1) {
334                 /*
335                  * Even though mke2fs always initialize first and last group
336                  * if some other tool enabled the EXT4_BG_BLOCK_UNINIT we need
337                  * to make sure we calculate the right free blocks
338                  */
339                 group_blocks = (ext4_sb_get_blocks_cnt(&bg_ref->fs->sb) -
340                                 ext4_get32(&bg_ref->fs->sb, first_data_block) -
341                                 (ext4_get32(&bg_ref->fs->sb, blocks_per_group) *
342                                  (ext4_block_group_cnt(&bg_ref->fs->sb) - 1)));
343         } else {
344                 group_blocks = ext4_get32(&bg_ref->fs->sb, blocks_per_group);
345         }
346         if (!flex_bg ||
347             ext4_block_in_group(&bg_ref->fs->sb,
348                                 bitmap_block_addr, bg_ref->index))
349                 ext4_bmap_bit_set(block_bitmap.data,
350                                   bitmap_block_addr - first_group_addr);
351
352         if (!flex_bg ||
353             ext4_block_in_group(&bg_ref->fs->sb,
354                                 bitmap_inode_addr, bg_ref->index))
355                 ext4_bmap_bit_set(block_bitmap.data,
356                                   bitmap_inode_addr - first_group_addr);
357
358         for (i = inode_table_addr;
359                 i < inode_table_addr + inode_table_bcnt; i++) {
360                 if (!flex_bg ||
361                     ext4_block_in_group(&bg_ref->fs->sb,
362                                         i,
363                                         bg_ref->index))
364                         ext4_bmap_bit_set(block_bitmap.data,
365                                         i - first_group_addr);
366         }
367         /*
368          * Also if the number of blocks within the group is
369          * less than the blocksize * 8 ( which is the size
370          * of bitmap ), set rest of the block bitmap to 1
371          */
372         ext4_fs_mark_bitmap_end(group_blocks, block_size * 8, block_bitmap.data);
373         block_bitmap.dirty = true;
374
375         ext4_balloc_set_bitmap_csum(&bg_ref->fs->sb,
376                                     bg_ref->block_group,
377                                     block_bitmap.data);
378         bg_ref->dirty = true;
379
380         /* Save bitmap */
381         return ext4_block_set(bg_ref->fs->bdev, &block_bitmap);
382 }
383
384 /**@brief Initialize i-node bitmap in block group.
385  * @param bg_ref Reference to block group
386  * @return Error code
387  */
388 static int ext4_fs_init_inode_bitmap(struct ext4_block_group_ref *bg_ref)
389 {
390         /* Load bitmap */
391         ext4_fsblk_t bitmap_block_addr =
392             ext4_bg_get_inode_bitmap(bg_ref->block_group, &bg_ref->fs->sb);
393
394         struct ext4_block block_bitmap;
395         int rc =
396             ext4_block_get(bg_ref->fs->bdev, &block_bitmap, bitmap_block_addr);
397         if (rc != EOK)
398                 return rc;
399
400         /* Initialize all bitmap bits to zero */
401         uint32_t block_size = ext4_sb_get_block_size(&bg_ref->fs->sb);
402         uint32_t inodes_per_group =
403             ext4_get32(&bg_ref->fs->sb, inodes_per_group);
404
405         memset(block_bitmap.data, 0, (inodes_per_group + 7) / 8);
406
407         uint32_t start_bit = inodes_per_group;
408         uint32_t end_bit = block_size * 8;
409
410         uint32_t i;
411         for (i = start_bit; i < ((start_bit + 7) & ~7UL); i++)
412                 ext4_bmap_bit_set(block_bitmap.data, i);
413
414         if (i < end_bit)
415                 memset(block_bitmap.data + (i >> 3), 0xff, (end_bit - i) >> 3);
416
417         block_bitmap.dirty = true;
418
419         ext4_ialloc_set_bitmap_csum(&bg_ref->fs->sb,
420                                     bg_ref->block_group,
421                                     block_bitmap.data);
422         bg_ref->dirty = true;
423
424         /* Save bitmap */
425         return ext4_block_set(bg_ref->fs->bdev, &block_bitmap);
426 }
427
428 /**@brief Initialize i-node table in block group.
429  * @param bg_ref Reference to block group
430  * @return Error code
431  */
432 static int ext4_fs_init_inode_table(struct ext4_block_group_ref *bg_ref)
433 {
434         struct ext4_sblock *sb = &bg_ref->fs->sb;
435
436         uint32_t inode_size = ext4_get32(sb, inode_size);
437         uint32_t block_size = ext4_sb_get_block_size(sb);
438         uint32_t inodes_per_block = block_size / inode_size;
439         uint32_t inodes_in_group = ext4_inodes_in_group_cnt(sb, bg_ref->index);
440         uint32_t table_blocks = inodes_in_group / inodes_per_block;
441         ext4_fsblk_t fblock;
442
443         if (inodes_in_group % inodes_per_block)
444                 table_blocks++;
445
446         /* Compute initialization bounds */
447         ext4_fsblk_t first_block =
448             ext4_bg_get_inode_table_first_block(bg_ref->block_group, sb);
449
450         ext4_fsblk_t last_block = first_block + table_blocks - 1;
451
452         /* Initialization of all itable blocks */
453         for (fblock = first_block; fblock <= last_block; ++fblock) {
454
455                 struct ext4_block block;
456                 int rc = ext4_block_get(bg_ref->fs->bdev, &block, fblock);
457                 if (rc != EOK)
458                         return rc;
459
460                 memset(block.data, 0, block_size);
461                 block.dirty = true;
462
463                 ext4_block_set(bg_ref->fs->bdev, &block);
464                 if (rc != EOK)
465                         return rc;
466         }
467
468         return EOK;
469 }
470
471 static ext4_fsblk_t ext4_fs_get_descriptor_block(struct ext4_sblock *s,
472                                              uint32_t bgid,
473                                              uint32_t dsc_per_block)
474 {
475         uint32_t first_meta_bg, dsc_id;
476
477         int has_super = 0;
478
479         dsc_id = bgid / dsc_per_block;
480         first_meta_bg = ext4_sb_first_meta_bg(s);
481
482         if (!ext4_sb_feature_incom(s, EXT4_FINCOM_META_BG) ||
483             dsc_id < first_meta_bg)
484                 return ext4_get32(s, first_data_block) + dsc_id + 1;
485
486         if (ext4_sb_is_super_in_bg(s, bgid))
487                 has_super = 1;
488
489         return (has_super + ext4_fs_first_bg_block_no(s, bgid));
490 }
491
492 int ext4_fs_get_block_group_ref(struct ext4_fs *fs, uint32_t bgid,
493                                 struct ext4_block_group_ref *ref)
494 {
495         /* Compute number of descriptors, that fits in one data block */
496         uint32_t dsc_per_block =
497             ext4_sb_get_block_size(&fs->sb) / ext4_sb_get_desc_size(&fs->sb);
498
499         /* Block group descriptor table starts at the next block after
500          * superblock */
501         uint64_t block_id =
502             ext4_fs_get_descriptor_block(&fs->sb, bgid, dsc_per_block);
503
504         uint32_t offset =
505             (bgid % dsc_per_block) * ext4_sb_get_desc_size(&fs->sb);
506
507         int rc = ext4_block_get(fs->bdev, &ref->block, block_id);
508         if (rc != EOK)
509                 return rc;
510
511         ref->block_group = (void *)(ref->block.data + offset);
512         ref->fs = fs;
513         ref->index = bgid;
514         ref->dirty = false;
515
516         if (ext4_bg_has_flag(ref->block_group, EXT4_BLOCK_GROUP_BLOCK_UNINIT)) {
517                 rc = ext4_fs_init_block_bitmap(ref);
518                 if (rc != EOK) {
519                         ext4_block_set(fs->bdev, &ref->block);
520                         return rc;
521                 }
522                 ext4_bg_clear_flag(ref->block_group,
523                                    EXT4_BLOCK_GROUP_BLOCK_UNINIT);
524
525                 ref->dirty = true;
526         }
527
528         if (ext4_bg_has_flag(ref->block_group, EXT4_BLOCK_GROUP_INODE_UNINIT)) {
529                 rc = ext4_fs_init_inode_bitmap(ref);
530                 if (rc != EOK) {
531                         ext4_block_set(ref->fs->bdev, &ref->block);
532                         return rc;
533                 }
534
535                 ext4_bg_clear_flag(ref->block_group,
536                                    EXT4_BLOCK_GROUP_INODE_UNINIT);
537
538                 if (!ext4_bg_has_flag(ref->block_group,
539                                       EXT4_BLOCK_GROUP_ITABLE_ZEROED)) {
540                         rc = ext4_fs_init_inode_table(ref);
541                         if (rc != EOK) {
542                                 ext4_block_set(fs->bdev, &ref->block);
543                                 return rc;
544                         }
545
546                         ext4_bg_set_flag(ref->block_group,
547                                          EXT4_BLOCK_GROUP_ITABLE_ZEROED);
548                 }
549
550                 ref->dirty = true;
551         }
552
553         return EOK;
554 }
555
556 /*
557  * BIG FAT NOTES:
558  *       Currently we do not verify the checksum of block_group_desc
559  *       and inode.
560  */
561
562 /**@brief  Compute checksum of block group descriptor.
563  * @param sb   Superblock
564  * @param bgid Index of block group in the filesystem
565  * @param bg   Block group to compute checksum for
566  * @return Checksum value
567  */
568 static uint16_t ext4_fs_bg_checksum(struct ext4_sblock *sb, uint32_t bgid,
569                                     struct ext4_bgroup *bg)
570 {
571         /* If checksum not supported, 0 will be returned */
572         uint16_t crc = 0;
573 #if CONFIG_META_CSUM_ENABLE
574         /* Compute the checksum only if the filesystem supports it */
575         if (ext4_sb_feature_ro_com(sb, EXT4_FRO_COM_METADATA_CSUM)) {
576                 /* Use metadata_csum algorithm instead */
577                 uint32_t le32_bgid = to_le32(bgid);
578                 uint32_t orig_checksum, checksum;
579
580                 /* Preparation: temporarily set bg checksum to 0 */
581                 orig_checksum = bg->checksum;
582                 bg->checksum = 0;
583
584                 /* First calculate crc32 checksum against fs uuid */
585                 checksum = ext4_crc32c(EXT4_CRC32_INIT, sb->uuid,
586                                 sizeof(sb->uuid));
587                 /* Then calculate crc32 checksum against bgid */
588                 checksum = ext4_crc32c(checksum, &le32_bgid,
589                                      sizeof(bgid));
590                 /* Finally calculate crc32 checksum against block_group_desc */
591                 checksum = ext4_crc32c(checksum, bg,
592                                      ext4_sb_get_desc_size(sb));
593                 bg->checksum = orig_checksum;
594
595                 crc = checksum & 0xFFFF;
596                 return crc;
597         }
598 #endif
599         if (ext4_sb_feature_ro_com(sb, EXT4_FRO_COM_GDT_CSUM)) {
600                 uint8_t *base = (uint8_t *)bg;
601                 uint8_t *checksum = (uint8_t *)&bg->checksum;
602
603                 uint32_t offset = (uint32_t)(checksum - base);
604
605                 /* Convert block group index to little endian */
606                 uint32_t le_group = to_le32(bgid);
607
608                 /* Initialization */
609                 crc = ext4_bg_crc16(~0, sb->uuid, sizeof(sb->uuid));
610
611                 /* Include index of block group */
612                 crc =
613                     ext4_bg_crc16(crc, (uint8_t *)&le_group, sizeof(le_group));
614
615                 /* Compute crc from the first part (stop before checksum field)
616                  */
617                 crc = ext4_bg_crc16(crc, (uint8_t *)bg, offset);
618
619                 /* Skip checksum */
620                 offset += sizeof(bg->checksum);
621
622                 /* Checksum of the rest of block group descriptor */
623                 if ((ext4_sb_feature_incom(sb, EXT4_FINCOM_64BIT)) &&
624                     (offset < ext4_sb_get_desc_size(sb)))
625
626                         crc = ext4_bg_crc16(crc, ((uint8_t *)bg) + offset,
627                                             ext4_sb_get_desc_size(sb) - offset);
628         }
629         return crc;
630 }
631
632 int ext4_fs_put_block_group_ref(struct ext4_block_group_ref *ref)
633 {
634         /* Check if reference modified */
635         if (ref->dirty) {
636                 /* Compute new checksum of block group */
637                 uint16_t checksum = ext4_fs_bg_checksum(
638                     &ref->fs->sb, ref->index, ref->block_group);
639
640                 ref->block_group->checksum = to_le16(checksum);
641
642                 /* Mark block dirty for writing changes to physical device */
643                 ref->block.dirty = true;
644         }
645
646         /* Put back block, that contains block group descriptor */
647         return ext4_block_set(ref->fs->bdev, &ref->block);
648 }
649
650 #if CONFIG_META_CSUM_ENABLE
651 static uint32_t ext4_fs_inode_checksum(struct ext4_inode_ref *inode_ref)
652 {
653         uint32_t checksum = 0;
654         struct ext4_sblock *sb = &inode_ref->fs->sb;
655         uint16_t inode_size = ext4_get16(sb, inode_size);
656
657         if (ext4_sb_feature_ro_com(sb, EXT4_FRO_COM_METADATA_CSUM)) {
658                 uint32_t orig_checksum;
659
660                 uint32_t ino_index = to_le32(inode_ref->index);
661                 uint32_t ino_gen =
662                         to_le32(ext4_inode_get_generation(inode_ref->inode));
663
664                 /* Preparation: temporarily set bg checksum to 0 */
665                 orig_checksum = ext4_inode_get_checksum(sb, inode_ref->inode);
666                 ext4_inode_set_checksum(sb, inode_ref->inode, 0);
667
668                 /* First calculate crc32 checksum against fs uuid */
669                 checksum = ext4_crc32c(EXT4_CRC32_INIT, sb->uuid,
670                                 sizeof(sb->uuid));
671                 /* Then calculate crc32 checksum against inode number
672                  * and inode generation */
673                 checksum = ext4_crc32c(checksum, &ino_index,
674                                      sizeof(ino_index));
675                 checksum = ext4_crc32c(checksum, &ino_gen,
676                                      sizeof(ino_gen));
677                 /* Finally calculate crc32 checksum against 
678                  * the entire inode */
679                 checksum = ext4_crc32c(checksum, inode_ref->inode,
680                                 inode_size);
681                 ext4_inode_set_checksum(sb, inode_ref->inode,
682                                 orig_checksum);
683         }
684         return checksum;
685 }
686 #else
687 #define ext4_fs_inode_checksum(...) 0
688 #endif
689
690 static void ext4_fs_set_inode_checksum(struct ext4_inode_ref *inode_ref)
691 {
692         struct ext4_sblock *sb = &inode_ref->fs->sb;
693         if (!ext4_sb_feature_ro_com(sb, EXT4_FRO_COM_METADATA_CSUM))
694                 return;
695
696         ext4_inode_set_checksum(sb, inode_ref->inode,
697                                 ext4_fs_inode_checksum(inode_ref));
698 }
699
700 int ext4_fs_get_inode_ref(struct ext4_fs *fs, uint32_t index,
701                           struct ext4_inode_ref *ref)
702 {
703         /* Compute number of i-nodes, that fits in one data block */
704         uint32_t inodes_per_group = ext4_get32(&fs->sb, inodes_per_group);
705
706         /*
707          * Inode numbers are 1-based, but it is simpler to work with 0-based
708          * when computing indices
709          */
710         index -= 1;
711         uint32_t block_group = index / inodes_per_group;
712         uint32_t offset_in_group = index % inodes_per_group;
713
714         /* Load block group, where i-node is located */
715         struct ext4_block_group_ref bg_ref;
716
717         int rc = ext4_fs_get_block_group_ref(fs, block_group, &bg_ref);
718         if (rc != EOK) {
719                 return rc;
720         }
721
722         /* Load block address, where i-node table is located */
723         uint32_t inode_table_start =
724             ext4_bg_get_inode_table_first_block(bg_ref.block_group, &fs->sb);
725
726         /* Put back block group reference (not needed more) */
727         rc = ext4_fs_put_block_group_ref(&bg_ref);
728         if (rc != EOK) {
729                 return rc;
730         }
731
732         /* Compute position of i-node in the block group */
733         uint16_t inode_size = ext4_get16(&fs->sb, inode_size);
734         uint32_t block_size = ext4_sb_get_block_size(&fs->sb);
735         uint32_t byte_offset_in_group = offset_in_group * inode_size;
736
737         /* Compute block address */
738         ext4_fsblk_t block_id =
739             inode_table_start + (byte_offset_in_group / block_size);
740
741         rc = ext4_block_get(fs->bdev, &ref->block, block_id);
742         if (rc != EOK) {
743                 return rc;
744         }
745
746         /* Compute position of i-node in the data block */
747         uint32_t offset_in_block = byte_offset_in_group % block_size;
748         ref->inode = (struct ext4_inode *)(ref->block.data + offset_in_block);
749
750         /* We need to store the original value of index in the reference */
751         ref->index = index + 1;
752         ref->fs = fs;
753         ref->dirty = false;
754
755         return EOK;
756 }
757
758 int ext4_fs_put_inode_ref(struct ext4_inode_ref *ref)
759 {
760         /* Check if reference modified */
761         if (ref->dirty) {
762                 /* Mark block dirty for writing changes to physical device */
763                 ext4_fs_set_inode_checksum(ref);
764                 ref->block.dirty = true;
765         }
766
767         /* Put back block, that contains i-node */
768         return ext4_block_set(ref->fs->bdev, &ref->block);
769 }
770
771 void ext4_fs_inode_blocks_init(struct ext4_fs *fs, struct ext4_inode_ref *inode_ref)
772 {
773         int i;
774         struct ext4_inode *inode = inode_ref->inode;
775
776         for (i = 0; i < EXT4_INODE_BLOCKS; i++)
777                 inode->blocks[i] = 0;
778
779         (void)fs;
780 #if CONFIG_EXTENT_ENABLE
781         /* Initialize extents if needed */
782         if (ext4_sb_feature_incom(&fs->sb, EXT4_FINCOM_EXTENTS)) {
783                 ext4_inode_set_flag(inode, EXT4_INODE_FLAG_EXTENTS);
784
785                 /* Initialize extent root header */
786                 ext4_extent_tree_init(inode_ref);
787         }
788 #endif
789 }
790
791 static uint32_t ext4_fs_correspond_inode_mode(int filetype)
792 {
793         switch (filetype) {
794         case EXT4_DIRENTRY_DIR:
795                 return EXT4_INODE_MODE_DIRECTORY;
796         case EXT4_DIRENTRY_REG_FILE:
797                 return EXT4_INODE_MODE_FILE;
798         case EXT4_DIRENTRY_SYMLINK:
799                 return EXT4_INODE_MODE_SOFTLINK;
800         default:
801                 /* FIXME: right now we only support 3 file type. */
802                 ext4_assert(0);
803         }
804         return 0;
805 }
806
807 int ext4_fs_alloc_inode(struct ext4_fs *fs, struct ext4_inode_ref *inode_ref,
808                         int filetype)
809 {
810         /* Check if newly allocated i-node will be a directory */
811         bool is_dir;
812         uint16_t inode_size = ext4_get16(&fs->sb, inode_size);
813
814         is_dir = (filetype == EXT4_DIRENTRY_DIR);
815
816         /* Allocate inode by allocation algorithm */
817         uint32_t index;
818         int rc = ext4_ialloc_alloc_inode(fs, &index, is_dir);
819         if (rc != EOK)
820                 return rc;
821
822         /* Load i-node from on-disk i-node table */
823         rc = ext4_fs_get_inode_ref(fs, index, inode_ref);
824         if (rc != EOK) {
825                 ext4_ialloc_free_inode(fs, index, is_dir);
826                 return rc;
827         }
828
829         /* Initialize i-node */
830         struct ext4_inode *inode = inode_ref->inode;
831
832         uint32_t mode;
833         if (is_dir) {
834                 /*
835                  * Default directory permissions to be compatible with other
836                  * systems
837                  * 0777 (octal) == rwxrwxrwx
838                  */
839
840                 mode = 0777;
841                 mode |= EXT4_INODE_MODE_DIRECTORY;
842         } else {
843                 /*
844                  * Default file permissions to be compatible with other systems
845                  * 0666 (octal) == rw-rw-rw-
846                  */
847
848                 mode = 0666;
849                 mode |= ext4_fs_correspond_inode_mode(filetype);
850         }
851         ext4_inode_set_mode(&fs->sb, inode, mode);
852
853         ext4_inode_set_links_count(inode, 0);
854         ext4_inode_set_uid(inode, 0);
855         ext4_inode_set_gid(inode, 0);
856         ext4_inode_set_size(inode, 0);
857         ext4_inode_set_access_time(inode, 0);
858         ext4_inode_set_change_inode_time(inode, 0);
859         ext4_inode_set_modification_time(inode, 0);
860         ext4_inode_set_deletion_time(inode, 0);
861         ext4_inode_set_blocks_count(&fs->sb, inode, 0);
862         ext4_inode_set_flags(inode, 0);
863         ext4_inode_set_generation(inode, 0);
864         if (inode_size > EXT4_GOOD_OLD_INODE_SIZE)
865                 ext4_inode_set_extra_isize(inode,
866                                 sizeof(struct ext4_inode) -
867                                 offsetof(struct ext4_inode,
868                                         extra_isize));
869
870         /* Reset blocks array. For symbolic link inode, just
871          * fill in blocks with 0 */
872         if (ext4_inode_is_type(&fs->sb, inode, EXT4_INODE_MODE_SOFTLINK)) {
873                 for (int i = 0; i < EXT4_INODE_BLOCKS; i++)
874                         inode->blocks[i] = 0;
875
876         } else
877                 ext4_fs_inode_blocks_init(fs, inode_ref);
878
879         inode_ref->dirty = true;
880
881         return EOK;
882 }
883
884 int ext4_fs_free_inode(struct ext4_inode_ref *inode_ref)
885 {
886         struct ext4_fs *fs = inode_ref->fs;
887         uint32_t offset;
888         uint32_t suboff;
889         int rc;
890 #if CONFIG_EXTENT_ENABLE
891         /* For extents must be data block destroyed by other way */
892         if ((ext4_sb_feature_incom(&fs->sb, EXT4_FINCOM_EXTENTS)) &&
893             (ext4_inode_has_flag(inode_ref->inode, EXT4_INODE_FLAG_EXTENTS))) {
894                 /* Data structures are released during truncate operation... */
895                 goto finish;
896         }
897 #endif
898         /* Release all indirect (no data) blocks */
899
900         /* 1) Single indirect */
901         ext4_fsblk_t fblock = ext4_inode_get_indirect_block(inode_ref->inode, 0);
902         if (fblock != 0) {
903                 int rc = ext4_balloc_free_block(inode_ref, fblock);
904                 if (rc != EOK)
905                         return rc;
906
907                 ext4_inode_set_indirect_block(inode_ref->inode, 0, 0);
908         }
909
910         uint32_t block_size = ext4_sb_get_block_size(&fs->sb);
911         uint32_t count = block_size / sizeof(uint32_t);
912
913         struct ext4_block block;
914
915         /* 2) Double indirect */
916         fblock = ext4_inode_get_indirect_block(inode_ref->inode, 1);
917         if (fblock != 0) {
918                 int rc = ext4_block_get(fs->bdev, &block, fblock);
919                 if (rc != EOK)
920                         return rc;
921
922                 ext4_fsblk_t ind_block;
923                 for (offset = 0; offset < count; ++offset) {
924                         ind_block = to_le32(((uint32_t *)block.data)[offset]);
925
926                         if (ind_block == 0)
927                                 continue;
928                         rc = ext4_balloc_free_block(inode_ref, ind_block);
929                         if (rc != EOK) {
930                                 ext4_block_set(fs->bdev, &block);
931                                 return rc;
932                         }
933
934                 }
935
936                 ext4_block_set(fs->bdev, &block);
937                 rc = ext4_balloc_free_block(inode_ref, fblock);
938                 if (rc != EOK)
939                         return rc;
940
941                 ext4_inode_set_indirect_block(inode_ref->inode, 1, 0);
942         }
943
944         /* 3) Tripple indirect */
945         struct ext4_block subblock;
946         fblock = ext4_inode_get_indirect_block(inode_ref->inode, 2);
947         if (fblock == 0)
948                 goto finish;
949         rc = ext4_block_get(fs->bdev, &block, fblock);
950         if (rc != EOK)
951                 return rc;
952
953         ext4_fsblk_t ind_block;
954         for (offset = 0; offset < count; ++offset) {
955                 ind_block = to_le32(((uint32_t *)block.data)[offset]);
956
957                 if (ind_block == 0)
958                         continue;
959                 rc = ext4_block_get(fs->bdev, &subblock,
960                                 ind_block);
961                 if (rc != EOK) {
962                         ext4_block_set(fs->bdev, &block);
963                         return rc;
964                 }
965
966                 ext4_fsblk_t ind_subblk;
967                 for (suboff = 0; suboff < count; ++suboff) {
968                         ind_subblk = to_le32(((uint32_t *)subblock.data)[suboff]);
969
970                         if (ind_subblk == 0)
971                                 continue;
972                         rc = ext4_balloc_free_block(inode_ref, ind_subblk);
973                         if (rc != EOK) {
974                                 ext4_block_set(fs->bdev, &subblock);
975                                 ext4_block_set(fs->bdev, &block);
976                                 return rc;
977                         }
978
979                 }
980
981                 ext4_block_set(fs->bdev, &subblock);
982
983                 rc = ext4_balloc_free_block(inode_ref,
984                                 ind_block);
985                 if (rc != EOK) {
986                         ext4_block_set(fs->bdev, &block);
987                         return rc;
988                 }
989
990         }
991
992         ext4_block_set(fs->bdev, &block);
993         rc = ext4_balloc_free_block(inode_ref, fblock);
994         if (rc != EOK)
995                 return rc;
996
997         ext4_inode_set_indirect_block(inode_ref->inode, 2, 0);
998 finish:
999         /* Mark inode dirty for writing to the physical device */
1000         inode_ref->dirty = true;
1001
1002         /* Free block with extended attributes if present */
1003         ext4_fsblk_t xattr_block =
1004             ext4_inode_get_file_acl(inode_ref->inode, &fs->sb);
1005         if (xattr_block) {
1006                 int rc = ext4_balloc_free_block(inode_ref, xattr_block);
1007                 if (rc != EOK)
1008                         return rc;
1009
1010                 ext4_inode_set_file_acl(inode_ref->inode, &fs->sb, 0);
1011         }
1012
1013         /* Free inode by allocator */
1014         if (ext4_inode_is_type(&fs->sb, inode_ref->inode,
1015                                EXT4_INODE_MODE_DIRECTORY))
1016                 rc = ext4_ialloc_free_inode(fs, inode_ref->index, true);
1017         else
1018                 rc = ext4_ialloc_free_inode(fs, inode_ref->index, false);
1019
1020         return rc;
1021 }
1022
1023
1024 /**@brief Release data block from i-node
1025  * @param inode_ref I-node to release block from
1026  * @param iblock    Logical block to be released
1027  * @return Error code
1028  */
1029 static int ext4_fs_release_inode_block(struct ext4_inode_ref *inode_ref,
1030                                 uint32_t iblock)
1031 {
1032         ext4_fsblk_t fblock;
1033
1034         struct ext4_fs *fs = inode_ref->fs;
1035
1036         /* Extents are handled otherwise = there is not support in this function
1037          */
1038         ext4_assert(!(
1039             ext4_sb_feature_incom(&fs->sb, EXT4_FINCOM_EXTENTS) &&
1040             (ext4_inode_has_flag(inode_ref->inode, EXT4_INODE_FLAG_EXTENTS))));
1041
1042         struct ext4_inode *inode = inode_ref->inode;
1043
1044         /* Handle simple case when we are dealing with direct reference */
1045         if (iblock < EXT4_INODE_DIRECT_BLOCK_COUNT) {
1046                 fblock = ext4_inode_get_direct_block(inode, iblock);
1047
1048                 /* Sparse file */
1049                 if (fblock == 0)
1050                         return EOK;
1051
1052                 ext4_inode_set_direct_block(inode, iblock, 0);
1053                 return ext4_balloc_free_block(inode_ref, fblock);
1054         }
1055
1056         /* Determine the indirection level needed to get the desired block */
1057         unsigned int level = 0;
1058         unsigned int i;
1059         for (i = 1; i < 4; i++) {
1060                 if (iblock < fs->inode_block_limits[i]) {
1061                         level = i;
1062                         break;
1063                 }
1064         }
1065
1066         if (level == 0)
1067                 return EIO;
1068
1069         /* Compute offsets for the topmost level */
1070         uint64_t block_offset_in_level =
1071             iblock - fs->inode_block_limits[level - 1];
1072         ext4_fsblk_t current_block =
1073             ext4_inode_get_indirect_block(inode, level - 1);
1074         uint32_t offset_in_block =
1075             block_offset_in_level / fs->inode_blocks_per_level[level - 1];
1076
1077         /*
1078          * Navigate through other levels, until we find the block number
1079          * or find null reference meaning we are dealing with sparse file
1080          */
1081         struct ext4_block block;
1082
1083         while (level > 0) {
1084
1085                 /* Sparse check */
1086                 if (current_block == 0)
1087                         return EOK;
1088
1089                 int rc = ext4_block_get(fs->bdev, &block, current_block);
1090                 if (rc != EOK)
1091                         return rc;
1092
1093                 current_block =
1094                     to_le32(((uint32_t *)block.data)[offset_in_block]);
1095
1096                 /* Set zero if physical data block address found */
1097                 if (level == 1) {
1098                         ((uint32_t *)block.data)[offset_in_block] = to_le32(0);
1099                         block.dirty = true;
1100                 }
1101
1102                 rc = ext4_block_set(fs->bdev, &block);
1103                 if (rc != EOK)
1104                         return rc;
1105
1106                 level--;
1107
1108                 /*
1109                  * If we are on the last level, break here as
1110                  * there is no next level to visit
1111                  */
1112                 if (level == 0)
1113                         break;
1114
1115                 /* Visit the next level */
1116                 block_offset_in_level %= fs->inode_blocks_per_level[level];
1117                 offset_in_block = block_offset_in_level /
1118                                   fs->inode_blocks_per_level[level - 1];
1119         }
1120
1121         fblock = current_block;
1122         if (fblock == 0)
1123                 return EOK;
1124
1125         /* Physical block is not referenced, it can be released */
1126         return ext4_balloc_free_block(inode_ref, fblock);
1127 }
1128
1129 int ext4_fs_truncate_inode(struct ext4_inode_ref *inode_ref, uint64_t new_size)
1130 {
1131         struct ext4_sblock *sb = &inode_ref->fs->sb;
1132         uint32_t i;
1133
1134         /* Check flags, if i-node can be truncated */
1135         if (!ext4_inode_can_truncate(sb, inode_ref->inode))
1136                 return EINVAL;
1137
1138         /* If sizes are equal, nothing has to be done. */
1139         uint64_t old_size = ext4_inode_get_size(sb, inode_ref->inode);
1140         if (old_size == new_size)
1141                 return EOK;
1142
1143         /* It's not supported to make the larger file by truncate operation */
1144         if (old_size < new_size)
1145                 return EINVAL;
1146
1147         if (ext4_inode_is_type(sb, inode_ref->inode, EXT4_INODE_MODE_SOFTLINK)
1148                         && old_size < sizeof(inode_ref->inode->blocks)
1149                         && !ext4_inode_get_blocks_count(sb, inode_ref->inode)) {
1150                 char *content = (char *)inode_ref->inode->blocks;
1151                 memset(content + new_size, 0,
1152                         sizeof(inode_ref->inode->blocks) - new_size);
1153                 ext4_inode_set_size(inode_ref->inode, new_size);
1154                 inode_ref->dirty = true;
1155
1156                 return EOK;
1157         }
1158
1159         /* Compute how many blocks will be released */
1160         uint32_t block_size = ext4_sb_get_block_size(sb);
1161         uint32_t new_blocks_count = (new_size + block_size - 1) /
1162                                     block_size;
1163         uint32_t old_blocks_count = (old_size + block_size - 1) /
1164                                     block_size;
1165         uint32_t diff_blocks_count = old_blocks_count - new_blocks_count;
1166 #if CONFIG_EXTENT_ENABLE
1167         if ((ext4_sb_feature_incom(sb, EXT4_FINCOM_EXTENTS)) &&
1168             (ext4_inode_has_flag(inode_ref->inode, EXT4_INODE_FLAG_EXTENTS))) {
1169
1170                 /* Extents require special operation */
1171                 if (diff_blocks_count) {
1172                         int rc = ext4_extent_remove_space(inode_ref,
1173                                         new_blocks_count, EXT_MAX_BLOCKS);
1174                         if (rc != EOK)
1175                                 return rc;
1176
1177                 }
1178         } else
1179 #endif
1180         {
1181                 /* Release data blocks from the end of file */
1182
1183                 /* Starting from 1 because of logical blocks are numbered from 0
1184                  */
1185                 for (i = 0; i < diff_blocks_count; ++i) {
1186                         int rc = ext4_fs_release_inode_block(
1187                             inode_ref, new_blocks_count + i);
1188                         if (rc != EOK)
1189                                 return rc;
1190                 }
1191         }
1192
1193         /* Update i-node */
1194         ext4_inode_set_size(inode_ref->inode, new_size);
1195         inode_ref->dirty = true;
1196
1197         return EOK;
1198 }
1199
1200 /**@brief Compute 'goal' for inode index
1201  * @param inode_ref Reference to inode, to allocate block for
1202  * @return goal
1203  */
1204 ext4_fsblk_t ext4_fs_inode_to_goal_block(struct ext4_inode_ref *inode_ref)
1205 {
1206         uint32_t group_inodes =
1207                 ext4_get32(&inode_ref->fs->sb, inodes_per_group);
1208         return (inode_ref->index - 1) / group_inodes;
1209 }
1210
1211 /**@brief Compute 'goal' for allocation algorithm (For blockmap).
1212  * @param inode_ref Reference to inode, to allocate block for
1213  * @param goal
1214  * @return error code
1215  */
1216 int ext4_fs_indirect_find_goal(struct ext4_inode_ref *inode_ref,
1217                                 ext4_fsblk_t *goal)
1218 {
1219         struct ext4_sblock *sb = &inode_ref->fs->sb;
1220         *goal = 0;
1221
1222         uint64_t inode_size = ext4_inode_get_size(sb, inode_ref->inode);
1223         uint32_t block_size = ext4_sb_get_block_size(sb);
1224         uint32_t inode_block_count = inode_size / block_size;
1225
1226         if (inode_size % block_size != 0)
1227                 inode_block_count++;
1228
1229         /* If inode has some blocks, get last block address + 1 */
1230         if (inode_block_count > 0) {
1231                 int rc = ext4_fs_get_inode_data_block_index(
1232                     inode_ref, inode_block_count - 1, goal, false);
1233                 if (rc != EOK)
1234                         return rc;
1235
1236                 if (*goal != 0) {
1237                         (*goal)++;
1238                         return rc;
1239                 }
1240
1241                 /* If goal == 0, sparse file -> continue */
1242         }
1243
1244         /* Identify block group of inode */
1245
1246         uint32_t inodes_per_group = ext4_get32(sb, inodes_per_group);
1247         uint32_t block_group = (inode_ref->index - 1) / inodes_per_group;
1248         block_size = ext4_sb_get_block_size(sb);
1249
1250         /* Load block group reference */
1251         struct ext4_block_group_ref bg_ref;
1252         int rc =
1253             ext4_fs_get_block_group_ref(inode_ref->fs, block_group, &bg_ref);
1254         if (rc != EOK)
1255                 return rc;
1256
1257         /* Compute indexes */
1258         uint32_t block_group_count = ext4_block_group_cnt(sb);
1259         ext4_fsblk_t inode_table_first_block =
1260             ext4_bg_get_inode_table_first_block(bg_ref.block_group, sb);
1261         uint16_t inode_table_item_size = ext4_get16(sb, inode_size);
1262         uint32_t inode_table_bytes;
1263
1264         /* Check for last block group */
1265         if (block_group < block_group_count - 1) {
1266                 inode_table_bytes = inodes_per_group * inode_table_item_size;
1267         } else {
1268                 /* Last block group could be smaller */
1269                 uint32_t inodes_count_total = ext4_get32(sb, inodes_count);
1270
1271                 inode_table_bytes =
1272                     (inodes_count_total -
1273                      ((block_group_count - 1) * inodes_per_group)) *
1274                     inode_table_item_size;
1275         }
1276
1277         ext4_fsblk_t inode_table_blocks = inode_table_bytes / block_size;
1278
1279         if (inode_table_bytes % block_size)
1280                 inode_table_blocks++;
1281
1282         *goal = inode_table_first_block + inode_table_blocks;
1283
1284         return ext4_fs_put_block_group_ref(&bg_ref);
1285 }
1286
1287 static int ext4_fs_get_inode_data_block_idx(struct ext4_inode_ref *inode_ref,
1288                                        uint64_t iblock, ext4_fsblk_t *fblock,
1289                                        bool extent_create,
1290                                        bool support_unwritten __unused)
1291 {
1292         struct ext4_fs *fs = inode_ref->fs;
1293
1294         /* For empty file is situation simple */
1295         if (ext4_inode_get_size(&fs->sb, inode_ref->inode) == 0) {
1296                 *fblock = 0;
1297                 return EOK;
1298         }
1299
1300         ext4_fsblk_t current_block;
1301
1302         (void)extent_create;
1303 #if CONFIG_EXTENT_ENABLE
1304         /* Handle i-node using extents */
1305         if ((ext4_sb_feature_incom(&fs->sb, EXT4_FINCOM_EXTENTS)) &&
1306             (ext4_inode_has_flag(inode_ref->inode, EXT4_INODE_FLAG_EXTENTS))) {
1307
1308                 ext4_fsblk_t current_fsblk;
1309                 int rc = ext4_extent_get_blocks(inode_ref, iblock, 1,
1310                                 &current_fsblk, extent_create, NULL);
1311                 if (rc != EOK)
1312                         return rc;
1313
1314                 current_block = current_fsblk;
1315                 *fblock = current_block;
1316
1317                 ext4_assert(*fblock || support_unwritten);
1318                 return EOK;
1319         }
1320 #endif
1321
1322         struct ext4_inode *inode = inode_ref->inode;
1323
1324         /* Direct block are read directly from array in i-node structure */
1325         if (iblock < EXT4_INODE_DIRECT_BLOCK_COUNT) {
1326                 current_block =
1327                     ext4_inode_get_direct_block(inode, (uint32_t)iblock);
1328                 *fblock = current_block;
1329                 return EOK;
1330         }
1331
1332         /* Determine indirection level of the target block */
1333         unsigned int level = 0;
1334         unsigned int i;
1335         for (i = 1; i < 4; i++) {
1336                 if (iblock < fs->inode_block_limits[i]) {
1337                         level = i;
1338                         break;
1339                 }
1340         }
1341
1342         if (level == 0)
1343                 return EIO;
1344
1345         /* Compute offsets for the topmost level */
1346         uint64_t block_offset_in_level =
1347             iblock - fs->inode_block_limits[level - 1];
1348         current_block = ext4_inode_get_indirect_block(inode, level - 1);
1349         uint32_t offset_in_block =
1350             block_offset_in_level / fs->inode_blocks_per_level[level - 1];
1351
1352         /* Sparse file */
1353         if (current_block == 0) {
1354                 *fblock = 0;
1355                 return EOK;
1356         }
1357
1358         struct ext4_block block;
1359
1360         /*
1361          * Navigate through other levels, until we find the block number
1362          * or find null reference meaning we are dealing with sparse file
1363          */
1364         while (level > 0) {
1365                 /* Load indirect block */
1366                 int rc = ext4_block_get(fs->bdev, &block, current_block);
1367                 if (rc != EOK)
1368                         return rc;
1369
1370                 /* Read block address from indirect block */
1371                 current_block =
1372                     to_le32(((uint32_t *)block.data)[offset_in_block]);
1373
1374                 /* Put back indirect block untouched */
1375                 rc = ext4_block_set(fs->bdev, &block);
1376                 if (rc != EOK)
1377                         return rc;
1378
1379                 /* Check for sparse file */
1380                 if (current_block == 0) {
1381                         *fblock = 0;
1382                         return EOK;
1383                 }
1384
1385                 /* Jump to the next level */
1386                 level--;
1387
1388                 /* Termination condition - we have address of data block loaded
1389                  */
1390                 if (level == 0)
1391                         break;
1392
1393                 /* Visit the next level */
1394                 block_offset_in_level %= fs->inode_blocks_per_level[level];
1395                 offset_in_block = block_offset_in_level /
1396                                   fs->inode_blocks_per_level[level - 1];
1397         }
1398
1399         *fblock = current_block;
1400
1401         return EOK;
1402 }
1403
1404
1405 int ext4_fs_get_inode_data_block_index(struct ext4_inode_ref *inode_ref,
1406                                        uint64_t iblock, ext4_fsblk_t *fblock,
1407                                        bool support_unwritten)
1408 {
1409         return ext4_fs_get_inode_data_block_idx(inode_ref, iblock, fblock,
1410                         false, support_unwritten);
1411 }
1412
1413 int ext4_fs_init_inode_data_block_index(struct ext4_inode_ref *inode_ref,
1414                                        uint64_t iblock, ext4_fsblk_t *fblock)
1415 {
1416         return ext4_fs_get_inode_data_block_idx(inode_ref, iblock, fblock,
1417                         true, true);
1418 }
1419
1420 static int ext4_fs_set_inode_data_block_index(struct ext4_inode_ref *inode_ref,
1421                                        uint64_t iblock, ext4_fsblk_t fblock)
1422 {
1423         struct ext4_fs *fs = inode_ref->fs;
1424
1425 #if CONFIG_EXTENT_ENABLE
1426         /* Handle inode using extents */
1427         if ((ext4_sb_feature_incom(&fs->sb, EXT4_FINCOM_EXTENTS)) &&
1428             (ext4_inode_has_flag(inode_ref->inode, EXT4_INODE_FLAG_EXTENTS))) {
1429                 /* Not reachable */
1430                 return ENOTSUP;
1431         }
1432 #endif
1433
1434         /* Handle simple case when we are dealing with direct reference */
1435         if (iblock < EXT4_INODE_DIRECT_BLOCK_COUNT) {
1436                 ext4_inode_set_direct_block(inode_ref->inode, (uint32_t)iblock,
1437                                             (uint32_t)fblock);
1438                 inode_ref->dirty = true;
1439
1440                 return EOK;
1441         }
1442
1443         /* Determine the indirection level needed to get the desired block */
1444         unsigned int level = 0;
1445         unsigned int i;
1446         for (i = 1; i < 4; i++) {
1447                 if (iblock < fs->inode_block_limits[i]) {
1448                         level = i;
1449                         break;
1450                 }
1451         }
1452
1453         if (level == 0)
1454                 return EIO;
1455
1456         uint32_t block_size = ext4_sb_get_block_size(&fs->sb);
1457
1458         /* Compute offsets for the topmost level */
1459         uint64_t block_offset_in_level =
1460             iblock - fs->inode_block_limits[level - 1];
1461         ext4_fsblk_t current_block =
1462             ext4_inode_get_indirect_block(inode_ref->inode, level - 1);
1463         uint32_t offset_in_block =
1464             block_offset_in_level / fs->inode_blocks_per_level[level - 1];
1465
1466         ext4_fsblk_t new_block_addr;
1467
1468         struct ext4_block block;
1469         struct ext4_block new_block;
1470
1471         /* Is needed to allocate indirect block on the i-node level */
1472         if (current_block == 0) {
1473                 /* Allocate new indirect block */
1474                 ext4_fsblk_t goal;
1475                 int rc = ext4_fs_indirect_find_goal(inode_ref, &goal);
1476                 if (rc != EOK)
1477                         return rc;
1478
1479                 rc = ext4_balloc_alloc_block(inode_ref,
1480                                              goal,
1481                                              &new_block_addr);
1482                 if (rc != EOK)
1483                         return rc;
1484
1485                 /* Update i-node */
1486                 ext4_inode_set_indirect_block(inode_ref->inode, level - 1,
1487                                               (uint32_t)new_block_addr);
1488                 inode_ref->dirty = true;
1489
1490                 /* Load newly allocated block */
1491                 rc = ext4_block_get(fs->bdev, &new_block, new_block_addr);
1492                 if (rc != EOK) {
1493                         ext4_balloc_free_block(inode_ref, new_block_addr);
1494                         return rc;
1495                 }
1496
1497                 /* Initialize new block */
1498                 memset(new_block.data, 0, block_size);
1499                 new_block.dirty = true;
1500
1501                 /* Put back the allocated block */
1502                 rc = ext4_block_set(fs->bdev, &new_block);
1503                 if (rc != EOK)
1504                         return rc;
1505
1506                 current_block = new_block_addr;
1507         }
1508
1509         /*
1510          * Navigate through other levels, until we find the block number
1511          * or find null reference meaning we are dealing with sparse file
1512          */
1513         while (level > 0) {
1514                 int rc = ext4_block_get(fs->bdev, &block, current_block);
1515                 if (rc != EOK)
1516                         return rc;
1517
1518                 current_block =
1519                     to_le32(((uint32_t *)block.data)[offset_in_block]);
1520
1521                 if ((level > 1) && (current_block == 0)) {
1522                         ext4_fsblk_t goal;
1523                         rc = ext4_fs_indirect_find_goal(inode_ref, &goal);
1524                         if (rc != EOK) {
1525                                 ext4_block_set(fs->bdev, &block);
1526                                 return rc;
1527                         }
1528
1529                         /* Allocate new block */
1530                         rc =
1531                             ext4_balloc_alloc_block(inode_ref, goal, &new_block_addr);
1532                         if (rc != EOK) {
1533                                 ext4_block_set(fs->bdev, &block);
1534                                 return rc;
1535                         }
1536
1537                         /* Load newly allocated block */
1538                         rc = ext4_block_get(fs->bdev, &new_block,
1539                                             new_block_addr);
1540
1541                         if (rc != EOK) {
1542                                 ext4_block_set(fs->bdev, &block);
1543                                 return rc;
1544                         }
1545
1546                         /* Initialize allocated block */
1547                         memset(new_block.data, 0, block_size);
1548                         new_block.dirty = true;
1549
1550                         rc = ext4_block_set(fs->bdev, &new_block);
1551                         if (rc != EOK) {
1552                                 ext4_block_set(fs->bdev, &block);
1553                                 return rc;
1554                         }
1555
1556                         /* Write block address to the parent */
1557                         ((uint32_t *)block.data)[offset_in_block] =
1558                             to_le32((uint32_t)new_block_addr);
1559                         block.dirty = true;
1560                         current_block = new_block_addr;
1561                 }
1562
1563                 /* Will be finished, write the fblock address */
1564                 if (level == 1) {
1565                         ((uint32_t *)block.data)[offset_in_block] =
1566                             to_le32((uint32_t)fblock);
1567                         block.dirty = true;
1568                 }
1569
1570                 rc = ext4_block_set(fs->bdev, &block);
1571                 if (rc != EOK)
1572                         return rc;
1573
1574                 level--;
1575
1576                 /*
1577                  * If we are on the last level, break here as
1578                  * there is no next level to visit
1579                  */
1580                 if (level == 0)
1581                         break;
1582
1583                 /* Visit the next level */
1584                 block_offset_in_level %= fs->inode_blocks_per_level[level];
1585                 offset_in_block = block_offset_in_level /
1586                                   fs->inode_blocks_per_level[level - 1];
1587         }
1588
1589         return EOK;
1590 }
1591
1592
1593 int ext4_fs_append_inode_block(struct ext4_inode_ref *inode_ref,
1594                                ext4_fsblk_t *fblock, uint32_t *iblock)
1595 {
1596 #if CONFIG_EXTENT_ENABLE
1597         /* Handle extents separately */
1598         if ((ext4_sb_feature_incom(&inode_ref->fs->sb, EXT4_FINCOM_EXTENTS)) &&
1599             (ext4_inode_has_flag(inode_ref->inode, EXT4_INODE_FLAG_EXTENTS))) {
1600                 int rc;
1601                 ext4_fsblk_t current_fsblk;
1602                 struct ext4_sblock *sb = &inode_ref->fs->sb;
1603                 uint64_t inode_size = ext4_inode_get_size(sb, inode_ref->inode);
1604                 uint32_t block_size = ext4_sb_get_block_size(sb);
1605                 *iblock = (inode_size + block_size - 1) /
1606                                     block_size;
1607
1608                 rc = ext4_extent_get_blocks(inode_ref, *iblock, 1,
1609                                 &current_fsblk, true, NULL);
1610
1611
1612                 *fblock = current_fsblk;
1613                 ext4_assert(*fblock);
1614
1615                 ext4_inode_set_size(inode_ref->inode,
1616                                     inode_size + block_size);
1617                 inode_ref->dirty = true;
1618
1619
1620                 return rc;
1621         }
1622 #endif
1623         struct ext4_sblock *sb = &inode_ref->fs->sb;
1624
1625         /* Compute next block index and allocate data block */
1626         uint64_t inode_size = ext4_inode_get_size(sb, inode_ref->inode);
1627         uint32_t block_size = ext4_sb_get_block_size(sb);
1628
1629         /* Align size i-node size */
1630         if ((inode_size % block_size) != 0)
1631                 inode_size += block_size - (inode_size % block_size);
1632
1633         /* Logical blocks are numbered from 0 */
1634         uint32_t new_block_idx = inode_size / block_size;
1635
1636         /* Allocate new physical block */
1637         ext4_fsblk_t goal, phys_block;
1638         int rc = ext4_fs_indirect_find_goal(inode_ref, &goal);
1639         if (rc != EOK)
1640                 return rc;
1641
1642         rc = ext4_balloc_alloc_block(inode_ref, goal, &phys_block);
1643         if (rc != EOK)
1644                 return rc;
1645
1646         /* Add physical block address to the i-node */
1647         rc = ext4_fs_set_inode_data_block_index(inode_ref, new_block_idx,
1648                                                 phys_block);
1649         if (rc != EOK) {
1650                 ext4_balloc_free_block(inode_ref, phys_block);
1651                 return rc;
1652         }
1653
1654         /* Update i-node */
1655         ext4_inode_set_size(inode_ref->inode, inode_size + block_size);
1656         inode_ref->dirty = true;
1657
1658         *fblock = phys_block;
1659         *iblock = new_block_idx;
1660
1661         return EOK;
1662 }
1663
1664 void ext4_fs_inode_links_count_inc(struct ext4_inode_ref *inode_ref)
1665 {
1666         uint16_t link;
1667
1668         link = ext4_inode_get_links_count(inode_ref->inode);
1669         link++;
1670         ext4_inode_set_links_count(inode_ref->inode, link);
1671
1672         bool is_dx =
1673             ext4_sb_feature_com(&inode_ref->fs->sb, EXT4_FCOM_DIR_INDEX) &&
1674             ext4_inode_has_flag(inode_ref->inode, EXT4_INODE_FLAG_INDEX);
1675
1676         if (is_dx && link > 1) {
1677                 if (link >= EXT4_LINK_MAX || link == 2) {
1678                         ext4_inode_set_links_count(inode_ref->inode, 1);
1679
1680                         uint32_t v =
1681                             ext4_get32(&inode_ref->fs->sb, features_read_only);
1682                         v |= EXT4_FRO_COM_DIR_NLINK;
1683                         ext4_set32(&inode_ref->fs->sb, features_read_only, v);
1684                 }
1685         }
1686 }
1687
1688 void ext4_fs_inode_links_count_dec(struct ext4_inode_ref *inode_ref)
1689 {
1690         uint16_t links = ext4_inode_get_links_count(inode_ref->inode);
1691         if (!ext4_inode_is_type(&inode_ref->fs->sb, inode_ref->inode,
1692                                 EXT4_INODE_MODE_DIRECTORY)) {
1693                 if (links > 0)
1694                         ext4_inode_set_links_count(inode_ref->inode, links - 1);
1695                 return;
1696         }
1697
1698         if (links > 2)
1699                 ext4_inode_set_links_count(inode_ref->inode, links - 1);
1700 }
1701
1702 /**
1703  * @}
1704  */