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