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