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