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