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