0f81a99e58a3abb9e1f2041a4846c5d4e383b0cb
[platform/upstream/f2fs-tools.git] / mkfs / f2fs_format.c
1 /**
2  * f2fs_format.c
3  *
4  * Copyright (c) 2012 Samsung Electronics Co., Ltd.
5  *             http://www.samsung.com/
6  *
7  * Dual licensed under the GPL or LGPL version 2 licenses.
8  */
9 #define _LARGEFILE64_SOURCE
10
11 #include <stdio.h>
12 #include <stdlib.h>
13 #include <fcntl.h>
14 #include <string.h>
15 #include <unistd.h>
16 #include <f2fs_fs.h>
17 #include <assert.h>
18
19 #ifdef HAVE_SYS_STAT_H
20 #include <sys/stat.h>
21 #endif
22 #ifdef HAVE_SYS_MOUNT_H
23 #include <sys/mount.h>
24 #endif
25 #include <time.h>
26
27 #ifdef HAVE_UUID_UUID_H
28 #include <uuid/uuid.h>
29 #endif
30 #ifndef HAVE_LIBUUID
31 #define uuid_parse(a, b) -1
32 #define uuid_generate(a)
33 #define uuid_unparse(a, b) -1
34 #endif
35
36 #include "quota.h"
37 #include "f2fs_format_utils.h"
38
39 extern struct f2fs_configuration c;
40 struct f2fs_super_block raw_sb;
41 struct f2fs_super_block *sb = &raw_sb;
42 struct f2fs_checkpoint *cp;
43
44 /* Return first segment number of each area */
45 #define prev_zone(cur)          (c.cur_seg[cur] - c.segs_per_zone)
46 #define next_zone(cur)          (c.cur_seg[cur] + c.segs_per_zone)
47 #define last_zone(cur)          ((cur - 1) * c.segs_per_zone)
48 #define last_section(cur)       (cur + (c.secs_per_zone - 1) * c.segs_per_sec)
49
50 /* Return time fixed by the user or current time by default */
51 #define mkfs_time ((c.fixed_time == -1) ? time(NULL) : c.fixed_time)
52
53 const char *media_ext_lists[] = {
54         /* common prefix */
55         "mp", // Covers mp3, mp4, mpeg, mpg
56         "wm", // Covers wma, wmb, wmv
57         "og", // Covers oga, ogg, ogm, ogv
58         "jp", // Covers jpg, jpeg, jp2
59
60         /* video */
61         "avi",
62         "m4v",
63         "m4p",
64         "mkv",
65         "mov",
66         "webm",
67
68         /* audio */
69         "wav",
70         "m4a",
71         "3gp",
72         "opus",
73         "flac",
74
75         /* image */
76         "gif",
77         "png",
78         "svg",
79         "webp",
80
81         /* archives */
82         "jar",
83         "deb",
84         "iso",
85         "gz",
86         "xz",
87         "zst",
88
89         /* others */
90         "pdf",
91         "pyc", // Python bytecode
92         "ttc",
93         "ttf",
94         "exe",
95
96         /* android */
97         "apk",
98         "cnt", // Image alias
99         "exo", // YouTube
100         "odex", // Android RunTime
101         "vdex", // Android RunTime
102         "so",
103
104         NULL
105 };
106
107 const char *hot_ext_lists[] = {
108         "db",
109
110 #ifndef WITH_ANDROID
111         /* Virtual machines */
112         "vmdk", // VMware or VirtualBox
113         "vdi", // VirtualBox
114         "qcow2", // QEMU
115 #endif
116         NULL
117 };
118
119 const char **default_ext_list[] = {
120         media_ext_lists,
121         hot_ext_lists
122 };
123
124 static bool is_extension_exist(const char *name)
125 {
126         int i;
127
128         for (i = 0; i < F2FS_MAX_EXTENSION; i++) {
129                 char *ext = (char *)sb->extension_list[i];
130                 if (!strcmp(ext, name))
131                         return 1;
132         }
133
134         return 0;
135 }
136
137 static void cure_extension_list(void)
138 {
139         const char **extlist;
140         char *ext_str;
141         char *ue;
142         int name_len;
143         int i, pos = 0;
144
145         set_sb(extension_count, 0);
146         memset(sb->extension_list, 0, sizeof(sb->extension_list));
147
148         for (i = 0; i < 2; i++) {
149                 ext_str = c.extension_list[i];
150                 extlist = default_ext_list[i];
151
152                 while (*extlist) {
153                         name_len = strlen(*extlist);
154                         memcpy(sb->extension_list[pos++], *extlist, name_len);
155                         extlist++;
156                 }
157                 if (i == 0)
158                         set_sb(extension_count, pos);
159                 else
160                         sb->hot_ext_count = pos - get_sb(extension_count);;
161
162                 if (!ext_str)
163                         continue;
164
165                 /* add user ext list */
166                 ue = strtok(ext_str, ", ");
167                 while (ue != NULL) {
168                         name_len = strlen(ue);
169                         if (name_len >= F2FS_EXTENSION_LEN) {
170                                 MSG(0, "\tWarn: Extension name (%s) is too long\n", ue);
171                                 goto next;
172                         }
173                         if (!is_extension_exist(ue))
174                                 memcpy(sb->extension_list[pos++], ue, name_len);
175 next:
176                         ue = strtok(NULL, ", ");
177                         if (pos >= F2FS_MAX_EXTENSION)
178                                 break;
179                 }
180
181                 if (i == 0)
182                         set_sb(extension_count, pos);
183                 else
184                         sb->hot_ext_count = pos - get_sb(extension_count);
185
186                 free(c.extension_list[i]);
187         }
188 }
189
190 static void verify_cur_segs(void)
191 {
192         int i, j;
193         int reorder = 0;
194
195         for (i = 0; i < NR_CURSEG_TYPE; i++) {
196                 for (j = i + 1; j < NR_CURSEG_TYPE; j++) {
197                         if (c.cur_seg[i] == c.cur_seg[j]) {
198                                 reorder = 1;
199                                 break;
200                         }
201                 }
202         }
203
204         if (!reorder)
205                 return;
206
207         c.cur_seg[0] = 0;
208         for (i = 1; i < NR_CURSEG_TYPE; i++)
209                 c.cur_seg[i] = next_zone(i - 1);
210 }
211
212 static int f2fs_prepare_super_block(void)
213 {
214         uint32_t blk_size_bytes;
215         uint32_t log_sectorsize, log_sectors_per_block;
216         uint32_t log_blocksize, log_blks_per_seg;
217         uint32_t segment_size_bytes, zone_size_bytes;
218         uint32_t sit_segments, nat_segments;
219         uint32_t blocks_for_sit, blocks_for_nat, blocks_for_ssa;
220         uint32_t total_valid_blks_available;
221         uint64_t zone_align_start_offset, diff;
222         uint64_t total_meta_zones, total_meta_segments;
223         uint32_t sit_bitmap_size, max_sit_bitmap_size;
224         uint32_t max_nat_bitmap_size, max_nat_segments;
225         uint32_t total_zones, avail_zones;
226         enum quota_type qtype;
227         int i;
228
229         set_sb(magic, F2FS_SUPER_MAGIC);
230         set_sb(major_ver, F2FS_MAJOR_VERSION);
231         set_sb(minor_ver, F2FS_MINOR_VERSION);
232
233         log_sectorsize = log_base_2(c.sector_size);
234         log_sectors_per_block = log_base_2(c.sectors_per_blk);
235         log_blocksize = log_sectorsize + log_sectors_per_block;
236         log_blks_per_seg = log_base_2(c.blks_per_seg);
237
238         set_sb(log_sectorsize, log_sectorsize);
239         set_sb(log_sectors_per_block, log_sectors_per_block);
240
241         set_sb(log_blocksize, log_blocksize);
242         set_sb(log_blocks_per_seg, log_blks_per_seg);
243
244         set_sb(segs_per_sec, c.segs_per_sec);
245         set_sb(secs_per_zone, c.secs_per_zone);
246
247         blk_size_bytes = 1 << log_blocksize;
248         segment_size_bytes = blk_size_bytes * c.blks_per_seg;
249         zone_size_bytes =
250                 blk_size_bytes * c.secs_per_zone *
251                 c.segs_per_sec * c.blks_per_seg;
252
253         set_sb(checksum_offset, 0);
254
255         set_sb(block_count, c.total_sectors >> log_sectors_per_block);
256
257         zone_align_start_offset =
258                 ((uint64_t) c.start_sector * DEFAULT_SECTOR_SIZE +
259                 2 * F2FS_BLKSIZE + zone_size_bytes - 1) /
260                 zone_size_bytes * zone_size_bytes -
261                 (uint64_t) c.start_sector * DEFAULT_SECTOR_SIZE;
262
263         if (c.feature & cpu_to_le32(F2FS_FEATURE_RO))
264                 zone_align_start_offset = 8192;
265
266         if (c.start_sector % DEFAULT_SECTORS_PER_BLOCK) {
267                 MSG(1, "\t%s: Align start sector number to the page unit\n",
268                                 c.zoned_mode ? "FAIL" : "WARN");
269                 MSG(1, "\ti.e., start sector: %d, ofs:%d (sects/page: %d)\n",
270                                 c.start_sector,
271                                 c.start_sector % DEFAULT_SECTORS_PER_BLOCK,
272                                 DEFAULT_SECTORS_PER_BLOCK);
273                 if (c.zoned_mode)
274                         return -1;
275         }
276
277         if (c.zoned_mode && c.ndevs > 1)
278                 zone_align_start_offset +=
279                         (c.devices[0].total_sectors * c.sector_size) % zone_size_bytes;
280
281         set_sb(segment0_blkaddr, zone_align_start_offset / blk_size_bytes);
282         sb->cp_blkaddr = sb->segment0_blkaddr;
283
284         MSG(0, "Info: zone aligned segment0 blkaddr: %u\n",
285                                         get_sb(segment0_blkaddr));
286
287         if (c.zoned_mode &&
288                 ((c.ndevs == 1 &&
289                         (get_sb(segment0_blkaddr) + c.start_sector /
290                         DEFAULT_SECTORS_PER_BLOCK) % c.zone_blocks) ||
291                 (c.ndevs > 1 &&
292                         c.devices[1].start_blkaddr % c.zone_blocks))) {
293                 MSG(1, "\tError: Unaligned segment0 block address %u\n",
294                                 get_sb(segment0_blkaddr));
295                 return -1;
296         }
297
298         for (i = 0; i < c.ndevs; i++) {
299                 if (i == 0) {
300                         c.devices[i].total_segments =
301                                 (c.devices[i].total_sectors *
302                                 c.sector_size - zone_align_start_offset) /
303                                 segment_size_bytes;
304                         c.devices[i].start_blkaddr = 0;
305                         c.devices[i].end_blkaddr = c.devices[i].total_segments *
306                                                 c.blks_per_seg - 1 +
307                                                 sb->segment0_blkaddr;
308                 } else {
309                         c.devices[i].total_segments =
310                                 c.devices[i].total_sectors /
311                                 (c.sectors_per_blk * c.blks_per_seg);
312                         c.devices[i].start_blkaddr =
313                                         c.devices[i - 1].end_blkaddr + 1;
314                         c.devices[i].end_blkaddr = c.devices[i].start_blkaddr +
315                                         c.devices[i].total_segments *
316                                         c.blks_per_seg - 1;
317                 }
318                 if (c.ndevs > 1) {
319                         memcpy(sb->devs[i].path, c.devices[i].path, MAX_PATH_LEN);
320                         sb->devs[i].total_segments =
321                                         cpu_to_le32(c.devices[i].total_segments);
322                 }
323
324                 c.total_segments += c.devices[i].total_segments;
325         }
326         set_sb(segment_count, (c.total_segments / c.segs_per_zone *
327                                                 c.segs_per_zone));
328         set_sb(segment_count_ckpt, F2FS_NUMBER_OF_CHECKPOINT_PACK);
329
330         set_sb(sit_blkaddr, get_sb(segment0_blkaddr) +
331                         get_sb(segment_count_ckpt) * c.blks_per_seg);
332
333         blocks_for_sit = SIZE_ALIGN(get_sb(segment_count), SIT_ENTRY_PER_BLOCK);
334
335         sit_segments = SEG_ALIGN(blocks_for_sit);
336
337         set_sb(segment_count_sit, sit_segments * 2);
338
339         set_sb(nat_blkaddr, get_sb(sit_blkaddr) + get_sb(segment_count_sit) *
340                         c.blks_per_seg);
341
342         total_valid_blks_available = (get_sb(segment_count) -
343                         (get_sb(segment_count_ckpt) +
344                         get_sb(segment_count_sit))) * c.blks_per_seg;
345
346         blocks_for_nat = SIZE_ALIGN(total_valid_blks_available,
347                         NAT_ENTRY_PER_BLOCK);
348
349         if (c.large_nat_bitmap) {
350                 nat_segments = SEG_ALIGN(blocks_for_nat) *
351                                                 DEFAULT_NAT_ENTRY_RATIO / 100;
352                 set_sb(segment_count_nat, nat_segments ? nat_segments : 1);
353                 max_nat_bitmap_size = (get_sb(segment_count_nat) <<
354                                                 log_blks_per_seg) / 8;
355                 set_sb(segment_count_nat, get_sb(segment_count_nat) * 2);
356         } else {
357                 set_sb(segment_count_nat, SEG_ALIGN(blocks_for_nat));
358                 max_nat_bitmap_size = 0;
359         }
360
361         /*
362          * The number of node segments should not be exceeded a "Threshold".
363          * This number resizes NAT bitmap area in a CP page.
364          * So the threshold is determined not to overflow one CP page
365          */
366         sit_bitmap_size = ((get_sb(segment_count_sit) / 2) <<
367                                 log_blks_per_seg) / 8;
368
369         if (sit_bitmap_size > MAX_SIT_BITMAP_SIZE)
370                 max_sit_bitmap_size = MAX_SIT_BITMAP_SIZE;
371         else
372                 max_sit_bitmap_size = sit_bitmap_size;
373
374         if (c.large_nat_bitmap) {
375                 /* use cp_payload if free space of f2fs_checkpoint is not enough */
376                 if (max_sit_bitmap_size + max_nat_bitmap_size >
377                                                 MAX_BITMAP_SIZE_IN_CKPT) {
378                         uint32_t diff =  max_sit_bitmap_size +
379                                                 max_nat_bitmap_size -
380                                                 MAX_BITMAP_SIZE_IN_CKPT;
381                         set_sb(cp_payload, F2FS_BLK_ALIGN(diff));
382                 } else {
383                         set_sb(cp_payload, 0);
384                 }
385         } else {
386                 /*
387                  * It should be reserved minimum 1 segment for nat.
388                  * When sit is too large, we should expand cp area.
389                  * It requires more pages for cp.
390                  */
391                 if (max_sit_bitmap_size > MAX_SIT_BITMAP_SIZE_IN_CKPT) {
392                         max_nat_bitmap_size = MAX_BITMAP_SIZE_IN_CKPT;
393                         set_sb(cp_payload, F2FS_BLK_ALIGN(max_sit_bitmap_size));
394                 } else {
395                         max_nat_bitmap_size = MAX_BITMAP_SIZE_IN_CKPT -
396                                                         max_sit_bitmap_size;
397                         set_sb(cp_payload, 0);
398                 }
399                 max_nat_segments = (max_nat_bitmap_size * 8) >> log_blks_per_seg;
400
401                 if (get_sb(segment_count_nat) > max_nat_segments)
402                         set_sb(segment_count_nat, max_nat_segments);
403
404                 set_sb(segment_count_nat, get_sb(segment_count_nat) * 2);
405         }
406
407         set_sb(ssa_blkaddr, get_sb(nat_blkaddr) + get_sb(segment_count_nat) *
408                         c.blks_per_seg);
409
410         total_valid_blks_available = (get_sb(segment_count) -
411                         (get_sb(segment_count_ckpt) +
412                         get_sb(segment_count_sit) +
413                         get_sb(segment_count_nat))) *
414                         c.blks_per_seg;
415
416         if (c.feature & cpu_to_le32(F2FS_FEATURE_RO))
417                 blocks_for_ssa = 0;
418         else
419                 blocks_for_ssa = total_valid_blks_available /
420                                 c.blks_per_seg + 1;
421
422         set_sb(segment_count_ssa, SEG_ALIGN(blocks_for_ssa));
423
424         total_meta_segments = get_sb(segment_count_ckpt) +
425                 get_sb(segment_count_sit) +
426                 get_sb(segment_count_nat) +
427                 get_sb(segment_count_ssa);
428         diff = total_meta_segments % (c.segs_per_zone);
429         if (diff)
430                 set_sb(segment_count_ssa, get_sb(segment_count_ssa) +
431                         (c.segs_per_zone - diff));
432
433         total_meta_zones = ZONE_ALIGN(total_meta_segments *
434                                                 c.blks_per_seg);
435
436         set_sb(main_blkaddr, get_sb(segment0_blkaddr) + total_meta_zones *
437                                 c.segs_per_zone * c.blks_per_seg);
438
439         if (c.zoned_mode) {
440                 /*
441                  * Make sure there is enough randomly writeable
442                  * space at the beginning of the disk.
443                  */
444                 unsigned long main_blkzone = get_sb(main_blkaddr) / c.zone_blocks;
445
446                 if (c.devices[0].zoned_model == F2FS_ZONED_HM &&
447                                 c.devices[0].nr_rnd_zones < main_blkzone) {
448                         MSG(0, "\tError: Device does not have enough random "
449                                         "write zones for F2FS volume (%lu needed)\n",
450                                         main_blkzone);
451                         return -1;
452                 }
453                 /*
454                  * Check if conventional device has enough space
455                  * to accommodate all metadata, zoned device should
456                  * not overlap to metadata area.
457                  */
458                 for (i = 1; i < c.ndevs; i++) {
459                         if (c.devices[i].zoned_model != F2FS_ZONED_NONE &&
460                                 c.devices[i].start_blkaddr < get_sb(main_blkaddr)) {
461                                 MSG(0, "\tError: Conventional device %s is too small,"
462                                         " (%"PRIu64" MiB needed).\n", c.devices[0].path,
463                                         (get_sb(main_blkaddr) -
464                                         c.devices[i].start_blkaddr) >> 8);
465                                 return -1;
466                         }
467                 }
468         }
469
470         total_zones = get_sb(segment_count) / (c.segs_per_zone) -
471                                                         total_meta_zones;
472         if (total_zones == 0)
473                 goto too_small;
474         set_sb(section_count, total_zones * c.secs_per_zone);
475
476         set_sb(segment_count_main, get_sb(section_count) * c.segs_per_sec);
477
478         /*
479          * Let's determine the best reserved and overprovisioned space.
480          * For Zoned device, if zone capacity less than zone size, the segments
481          * starting after the zone capacity are unusable in each zone. So get
482          * overprovision ratio and reserved seg count based on avg usable
483          * segs_per_sec.
484          */
485         if (c.overprovision == 0)
486                 c.overprovision = get_best_overprovision(sb);
487
488         c.reserved_segments = get_reserved(sb, c.overprovision);
489
490         if (c.feature & cpu_to_le32(F2FS_FEATURE_RO)) {
491                 c.overprovision = 0;
492                 c.reserved_segments = 0;
493         }
494         if ((!(c.feature & cpu_to_le32(F2FS_FEATURE_RO)) &&
495                 c.overprovision == 0) ||
496                 c.total_segments < F2FS_MIN_SEGMENTS ||
497                 (c.devices[0].total_sectors *
498                         c.sector_size < zone_align_start_offset) ||
499                 (get_sb(segment_count_main) - NR_CURSEG_TYPE) <
500                                                 c.reserved_segments) {
501                 goto too_small;
502         }
503
504         if (c.vol_uuid) {
505                 if (uuid_parse(c.vol_uuid, sb->uuid)) {
506                         MSG(0, "\tError: supplied string is not a valid UUID\n");
507                         return -1;
508                 }
509         } else {
510                 uuid_generate(sb->uuid);
511         }
512
513         /* precompute checksum seed for metadata */
514         if (c.feature & cpu_to_le32(F2FS_FEATURE_INODE_CHKSUM))
515                 c.chksum_seed = f2fs_cal_crc32(~0, sb->uuid, sizeof(sb->uuid));
516
517         utf8_to_utf16((char *)sb->volume_name, (const char *)c.vol_label,
518                                 MAX_VOLUME_NAME, strlen(c.vol_label));
519         set_sb(node_ino, 1);
520         set_sb(meta_ino, 2);
521         set_sb(root_ino, 3);
522         c.next_free_nid = 4;
523
524         for (qtype = 0; qtype < F2FS_MAX_QUOTAS; qtype++) {
525                 if (!((1 << qtype) & c.quota_bits))
526                         continue;
527                 sb->qf_ino[qtype] = cpu_to_le32(c.next_free_nid++);
528                 MSG(0, "Info: add quota type = %u => %u\n",
529                                         qtype, c.next_free_nid - 1);
530         }
531
532         if (c.feature & cpu_to_le32(F2FS_FEATURE_LOST_FOUND))
533                 c.lpf_ino = c.next_free_nid++;
534
535         if (c.feature & cpu_to_le32(F2FS_FEATURE_RO))
536                 avail_zones = 2;
537         else
538                 avail_zones = 6;
539
540         if (total_zones <= avail_zones) {
541                 MSG(1, "\tError: %d zones: Need more zones "
542                         "by shrinking zone size\n", total_zones);
543                 return -1;
544         }
545
546         if (c.feature & cpu_to_le32(F2FS_FEATURE_RO)) {
547                 c.cur_seg[CURSEG_HOT_NODE] = last_section(last_zone(total_zones));
548                 c.cur_seg[CURSEG_WARM_NODE] = 0;
549                 c.cur_seg[CURSEG_COLD_NODE] = 0;
550                 c.cur_seg[CURSEG_HOT_DATA] = 0;
551                 c.cur_seg[CURSEG_COLD_DATA] = 0;
552                 c.cur_seg[CURSEG_WARM_DATA] = 0;
553         } else if (c.heap) {
554                 c.cur_seg[CURSEG_HOT_NODE] =
555                                 last_section(last_zone(total_zones));
556                 c.cur_seg[CURSEG_WARM_NODE] = prev_zone(CURSEG_HOT_NODE);
557                 c.cur_seg[CURSEG_COLD_NODE] = prev_zone(CURSEG_WARM_NODE);
558                 c.cur_seg[CURSEG_HOT_DATA] = prev_zone(CURSEG_COLD_NODE);
559                 c.cur_seg[CURSEG_COLD_DATA] = 0;
560                 c.cur_seg[CURSEG_WARM_DATA] = next_zone(CURSEG_COLD_DATA);
561         } else if (c.zoned_mode) {
562                 c.cur_seg[CURSEG_HOT_NODE] = 0;
563                 c.cur_seg[CURSEG_WARM_NODE] = next_zone(CURSEG_HOT_NODE);
564                 c.cur_seg[CURSEG_COLD_NODE] = next_zone(CURSEG_WARM_NODE);
565                 c.cur_seg[CURSEG_HOT_DATA] = next_zone(CURSEG_COLD_NODE);
566                 c.cur_seg[CURSEG_WARM_DATA] = next_zone(CURSEG_HOT_DATA);
567                 c.cur_seg[CURSEG_COLD_DATA] = next_zone(CURSEG_WARM_DATA);
568         } else {
569                 c.cur_seg[CURSEG_HOT_NODE] = 0;
570                 c.cur_seg[CURSEG_WARM_NODE] = next_zone(CURSEG_HOT_NODE);
571                 c.cur_seg[CURSEG_COLD_NODE] = next_zone(CURSEG_WARM_NODE);
572                 c.cur_seg[CURSEG_HOT_DATA] = next_zone(CURSEG_COLD_NODE);
573                 c.cur_seg[CURSEG_COLD_DATA] =
574                                 max(last_zone((total_zones >> 2)),
575                                         next_zone(CURSEG_HOT_DATA));
576                 c.cur_seg[CURSEG_WARM_DATA] =
577                                 max(last_zone((total_zones >> 1)),
578                                         next_zone(CURSEG_COLD_DATA));
579         }
580
581         /* if there is redundancy, reassign it */
582         if (!(c.feature & cpu_to_le32(F2FS_FEATURE_RO)))
583                 verify_cur_segs();
584
585         cure_extension_list();
586
587         /* get kernel version */
588         if (c.kd >= 0) {
589                 dev_read_version(c.version, 0, VERSION_LEN);
590                 get_kernel_version(c.version);
591         } else {
592                 get_kernel_uname_version(c.version);
593         }
594         MSG(0, "Info: format version with\n  \"%s\"\n", c.version);
595
596         memcpy(sb->version, c.version, VERSION_LEN);
597         memcpy(sb->init_version, c.version, VERSION_LEN);
598
599         if (c.feature & cpu_to_le32(F2FS_FEATURE_CASEFOLD)) {
600                 set_sb(s_encoding, c.s_encoding);
601                 set_sb(s_encoding_flags, c.s_encoding_flags);
602         }
603
604         sb->feature = c.feature;
605
606         if (get_sb(feature) & F2FS_FEATURE_SB_CHKSUM) {
607                 set_sb(checksum_offset, SB_CHKSUM_OFFSET);
608                 set_sb(crc, f2fs_cal_crc32(F2FS_SUPER_MAGIC, sb,
609                                                 SB_CHKSUM_OFFSET));
610                 MSG(1, "Info: SB CRC is set: offset (%d), crc (0x%x)\n",
611                                         get_sb(checksum_offset), get_sb(crc));
612         }
613
614         return 0;
615
616 too_small:
617         MSG(0, "\tError: Device size is not sufficient for F2FS volume\n");
618         return -1;
619 }
620
621 static int f2fs_init_sit_area(void)
622 {
623         uint32_t blk_size, seg_size;
624         uint32_t index = 0;
625         uint64_t sit_seg_addr = 0;
626         uint8_t *zero_buf = NULL;
627
628         blk_size = 1 << get_sb(log_blocksize);
629         seg_size = (1 << get_sb(log_blocks_per_seg)) * blk_size;
630
631         zero_buf = calloc(sizeof(uint8_t), seg_size);
632         if(zero_buf == NULL) {
633                 MSG(1, "\tError: Calloc Failed for sit_zero_buf!!!\n");
634                 return -1;
635         }
636
637         sit_seg_addr = get_sb(sit_blkaddr);
638         sit_seg_addr *= blk_size;
639
640         DBG(1, "\tFilling sit area at offset 0x%08"PRIx64"\n", sit_seg_addr);
641         for (index = 0; index < (get_sb(segment_count_sit) / 2); index++) {
642                 if (dev_fill(zero_buf, sit_seg_addr, seg_size)) {
643                         MSG(1, "\tError: While zeroing out the sit area "
644                                         "on disk!!!\n");
645                         free(zero_buf);
646                         return -1;
647                 }
648                 sit_seg_addr += seg_size;
649         }
650
651         free(zero_buf);
652         return 0 ;
653 }
654
655 static int f2fs_init_nat_area(void)
656 {
657         uint32_t blk_size, seg_size;
658         uint32_t index = 0;
659         uint64_t nat_seg_addr = 0;
660         uint8_t *nat_buf = NULL;
661
662         blk_size = 1 << get_sb(log_blocksize);
663         seg_size = (1 << get_sb(log_blocks_per_seg)) * blk_size;
664
665         nat_buf = calloc(sizeof(uint8_t), seg_size);
666         if (nat_buf == NULL) {
667                 MSG(1, "\tError: Calloc Failed for nat_zero_blk!!!\n");
668                 return -1;
669         }
670
671         nat_seg_addr = get_sb(nat_blkaddr);
672         nat_seg_addr *= blk_size;
673
674         DBG(1, "\tFilling nat area at offset 0x%08"PRIx64"\n", nat_seg_addr);
675         for (index = 0; index < get_sb(segment_count_nat) / 2; index++) {
676                 if (dev_fill(nat_buf, nat_seg_addr, seg_size)) {
677                         MSG(1, "\tError: While zeroing out the nat area "
678                                         "on disk!!!\n");
679                         free(nat_buf);
680                         return -1;
681                 }
682                 nat_seg_addr = nat_seg_addr + (2 * seg_size);
683         }
684
685         free(nat_buf);
686         return 0 ;
687 }
688
689 static int f2fs_write_check_point_pack(void)
690 {
691         struct f2fs_summary_block *sum;
692         struct f2fs_journal *journal;
693         uint32_t blk_size_bytes;
694         uint32_t nat_bits_bytes, nat_bits_blocks;
695         unsigned char *nat_bits = NULL, *empty_nat_bits;
696         uint64_t cp_seg_blk = 0;
697         uint32_t crc = 0, flags;
698         unsigned int i;
699         char *cp_payload = NULL;
700         char *sum_compact, *sum_compact_p;
701         struct f2fs_summary *sum_entry;
702         unsigned short vblocks;
703         int ret = -1;
704
705         cp = calloc(F2FS_BLKSIZE, 1);
706         if (cp == NULL) {
707                 MSG(1, "\tError: Calloc failed for f2fs_checkpoint!!!\n");
708                 return ret;
709         }
710
711         sum = calloc(F2FS_BLKSIZE, 1);
712         if (sum == NULL) {
713                 MSG(1, "\tError: Calloc failed for summary_node!!!\n");
714                 goto free_cp;
715         }
716
717         sum_compact = calloc(F2FS_BLKSIZE, 1);
718         if (sum_compact == NULL) {
719                 MSG(1, "\tError: Calloc failed for summary buffer!!!\n");
720                 goto free_sum;
721         }
722         sum_compact_p = sum_compact;
723
724         nat_bits_bytes = get_sb(segment_count_nat) << 5;
725         nat_bits_blocks = F2FS_BYTES_TO_BLK((nat_bits_bytes << 1) + 8 +
726                                                 F2FS_BLKSIZE - 1);
727         nat_bits = calloc(F2FS_BLKSIZE, nat_bits_blocks);
728         if (nat_bits == NULL) {
729                 MSG(1, "\tError: Calloc failed for nat bits buffer!!!\n");
730                 goto free_sum_compact;
731         }
732
733         cp_payload = calloc(F2FS_BLKSIZE, 1);
734         if (cp_payload == NULL) {
735                 MSG(1, "\tError: Calloc failed for cp_payload!!!\n");
736                 goto free_nat_bits;
737         }
738
739         /* 1. cp page 1 of checkpoint pack 1 */
740         srand((c.fake_seed) ? 0 : time(NULL));
741         cp->checkpoint_ver = cpu_to_le64(rand() | 0x1);
742         set_cp(cur_node_segno[0], c.cur_seg[CURSEG_HOT_NODE]);
743         set_cp(cur_node_segno[1], c.cur_seg[CURSEG_WARM_NODE]);
744         set_cp(cur_node_segno[2], c.cur_seg[CURSEG_COLD_NODE]);
745         set_cp(cur_data_segno[0], c.cur_seg[CURSEG_HOT_DATA]);
746         set_cp(cur_data_segno[1], c.cur_seg[CURSEG_WARM_DATA]);
747         set_cp(cur_data_segno[2], c.cur_seg[CURSEG_COLD_DATA]);
748         for (i = 3; i < MAX_ACTIVE_NODE_LOGS; i++) {
749                 set_cp(cur_node_segno[i], 0xffffffff);
750                 set_cp(cur_data_segno[i], 0xffffffff);
751         }
752
753         set_cp(cur_node_blkoff[0], c.curseg_offset[CURSEG_HOT_NODE]);
754         set_cp(cur_data_blkoff[0], c.curseg_offset[CURSEG_HOT_DATA]);
755         set_cp(valid_block_count, c.curseg_offset[CURSEG_HOT_NODE] +
756                                         c.curseg_offset[CURSEG_HOT_DATA]);
757         set_cp(rsvd_segment_count, c.reserved_segments);
758
759         /*
760          * For zoned devices, if zone capacity less than zone size, get
761          * overprovision segment count based on usable segments in the device.
762          */
763         set_cp(overprov_segment_count, (f2fs_get_usable_segments(sb) -
764                         get_cp(rsvd_segment_count)) *
765                         c.overprovision / 100);
766
767         if (!(c.conf_reserved_sections) &&
768             get_cp(overprov_segment_count) < get_cp(rsvd_segment_count))
769                 set_cp(overprov_segment_count, get_cp(rsvd_segment_count));
770
771         /*
772          * If conf_reserved_sections has a non zero value, overprov_segment_count
773          * is set to overprov_segment_count + rsvd_segment_count.
774          */
775         if (c.conf_reserved_sections) {
776                 /*
777                  * Overprovision segments must be bigger than two sections.
778                  * In non configurable reserved section case, overprovision
779                  * segments are always bigger than two sections.
780                  */
781                 if (get_cp(overprov_segment_count) < 2 * get_sb(segs_per_sec)) {
782                         MSG(0, "\tError: Not enough overprovision segments (%u)\n",
783                             get_cp(overprov_segment_count));
784                         goto free_cp_payload;
785                 }
786                 set_cp(overprov_segment_count, get_cp(overprov_segment_count) +
787                                 get_cp(rsvd_segment_count));
788          } else {
789                 set_cp(overprov_segment_count, get_cp(overprov_segment_count) +
790                                 2 * get_sb(segs_per_sec));
791          }
792
793         if (f2fs_get_usable_segments(sb) <= get_cp(overprov_segment_count)) {
794                 MSG(0, "\tError: Not enough segments to create F2FS Volume\n");
795                 goto free_cp_payload;
796         }
797         MSG(0, "Info: Overprovision ratio = %.3lf%%\n", c.overprovision);
798         MSG(0, "Info: Overprovision segments = %u (GC reserved = %u)\n",
799                                         get_cp(overprov_segment_count),
800                                         c.reserved_segments);
801
802         /* main segments - reserved segments - (node + data segments) */
803         if (c.feature & cpu_to_le32(F2FS_FEATURE_RO)) {
804                 set_cp(free_segment_count, f2fs_get_usable_segments(sb) - 2);
805                 set_cp(user_block_count, ((get_cp(free_segment_count) + 2 -
806                         get_cp(overprov_segment_count)) * c.blks_per_seg));
807         } else {
808                 set_cp(free_segment_count, f2fs_get_usable_segments(sb) - 6);
809                 set_cp(user_block_count, ((get_cp(free_segment_count) + 6 -
810                         get_cp(overprov_segment_count)) * c.blks_per_seg));
811         }
812         /* cp page (2), data summaries (1), node summaries (3) */
813         set_cp(cp_pack_total_block_count, 6 + get_sb(cp_payload));
814         flags = CP_UMOUNT_FLAG | CP_COMPACT_SUM_FLAG;
815         if (get_cp(cp_pack_total_block_count) <=
816                         (1 << get_sb(log_blocks_per_seg)) - nat_bits_blocks)
817                 flags |= CP_NAT_BITS_FLAG;
818
819         if (c.trimmed)
820                 flags |= CP_TRIMMED_FLAG;
821
822         if (c.large_nat_bitmap)
823                 flags |= CP_LARGE_NAT_BITMAP_FLAG;
824
825         set_cp(ckpt_flags, flags);
826         set_cp(cp_pack_start_sum, 1 + get_sb(cp_payload));
827         set_cp(valid_node_count, c.curseg_offset[CURSEG_HOT_NODE]);
828         set_cp(valid_inode_count, c.curseg_offset[CURSEG_HOT_NODE]);
829         set_cp(next_free_nid, c.next_free_nid);
830         set_cp(sit_ver_bitmap_bytesize, ((get_sb(segment_count_sit) / 2) <<
831                         get_sb(log_blocks_per_seg)) / 8);
832
833         set_cp(nat_ver_bitmap_bytesize, ((get_sb(segment_count_nat) / 2) <<
834                          get_sb(log_blocks_per_seg)) / 8);
835
836         if (c.large_nat_bitmap)
837                 set_cp(checksum_offset, CP_MIN_CHKSUM_OFFSET);
838         else
839                 set_cp(checksum_offset, CP_CHKSUM_OFFSET);
840
841         crc = f2fs_checkpoint_chksum(cp);
842         *((__le32 *)((unsigned char *)cp + get_cp(checksum_offset))) =
843                                                         cpu_to_le32(crc);
844
845         blk_size_bytes = 1 << get_sb(log_blocksize);
846
847         if (blk_size_bytes != F2FS_BLKSIZE) {
848                 MSG(1, "\tError: Wrong block size %d / %d!!!\n",
849                                         blk_size_bytes, F2FS_BLKSIZE);
850                 goto free_cp_payload;
851         }
852
853         cp_seg_blk = get_sb(segment0_blkaddr);
854
855         DBG(1, "\tWriting main segments, cp at offset 0x%08"PRIx64"\n",
856                                                 cp_seg_blk);
857         if (dev_write_block(cp, cp_seg_blk)) {
858                 MSG(1, "\tError: While writing the cp to disk!!!\n");
859                 goto free_cp_payload;
860         }
861
862         for (i = 0; i < get_sb(cp_payload); i++) {
863                 cp_seg_blk++;
864                 if (dev_fill_block(cp_payload, cp_seg_blk)) {
865                         MSG(1, "\tError: While zeroing out the sit bitmap area "
866                                         "on disk!!!\n");
867                         goto free_cp_payload;
868                 }
869         }
870
871         /* Prepare and write Segment summary for HOT/WARM/COLD DATA
872          *
873          * The structure of compact summary
874          * +-------------------+
875          * | nat_journal       |
876          * +-------------------+
877          * | sit_journal       |
878          * +-------------------+
879          * | hot data summary  |
880          * +-------------------+
881          * | warm data summary |
882          * +-------------------+
883          * | cold data summary |
884          * +-------------------+
885         */
886
887         /* nat_sjournal */
888         journal = &c.nat_jnl;
889         memcpy(sum_compact_p, &journal->n_nats, SUM_JOURNAL_SIZE);
890         sum_compact_p += SUM_JOURNAL_SIZE;
891
892         /* sit_journal */
893         journal = &c.sit_jnl;
894
895         if (c.feature & cpu_to_le32(F2FS_FEATURE_RO)) {
896                 i = CURSEG_RO_HOT_DATA;
897                 vblocks = le16_to_cpu(journal->sit_j.entries[i].se.vblocks);
898                 journal->sit_j.entries[i].segno = cp->cur_data_segno[0];
899                 journal->sit_j.entries[i].se.vblocks =
900                                 cpu_to_le16(vblocks | (CURSEG_HOT_DATA << 10));
901
902                 i = CURSEG_RO_HOT_NODE;
903                 vblocks = le16_to_cpu(journal->sit_j.entries[i].se.vblocks);
904                 journal->sit_j.entries[i].segno = cp->cur_node_segno[0];
905                 journal->sit_j.entries[i].se.vblocks |=
906                                 cpu_to_le16(vblocks | (CURSEG_HOT_NODE << 10));
907
908                 journal->n_sits = cpu_to_le16(2);
909         } else {
910                 for (i = CURSEG_HOT_DATA; i < NR_CURSEG_TYPE; i++) {
911                         if (i < NR_CURSEG_DATA_TYPE)
912                                 journal->sit_j.entries[i].segno =
913                                         cp->cur_data_segno[i];
914
915                         else
916                                 journal->sit_j.entries[i].segno =
917                                         cp->cur_node_segno[i - NR_CURSEG_DATA_TYPE];
918
919                         vblocks =
920                                 le16_to_cpu(journal->sit_j.entries[i].se.vblocks);
921                         journal->sit_j.entries[i].se.vblocks =
922                                                 cpu_to_le16(vblocks | (i << 10));
923                 }
924
925                 journal->n_sits = cpu_to_le16(6);
926         }
927
928         memcpy(sum_compact_p, &journal->n_sits, SUM_JOURNAL_SIZE);
929         sum_compact_p += SUM_JOURNAL_SIZE;
930
931         /* hot data summary */
932         memset(sum, 0, sizeof(struct f2fs_summary_block));
933         SET_SUM_TYPE((&sum->footer), SUM_TYPE_DATA);
934
935         sum_entry = (struct f2fs_summary *)sum_compact_p;
936         memcpy(sum_entry, c.sum[CURSEG_HOT_DATA],
937                         sizeof(struct f2fs_summary) * MAX_CACHE_SUMS);
938
939         /* warm data summary, nothing to do */
940         /* cold data summary, nothing to do */
941
942         cp_seg_blk++;
943         DBG(1, "\tWriting Segment summary for HOT/WARM/COLD_DATA, at offset 0x%08"PRIx64"\n",
944                         cp_seg_blk);
945         if (dev_write_block(sum_compact, cp_seg_blk)) {
946                 MSG(1, "\tError: While writing the sum_blk to disk!!!\n");
947                 goto free_cp_payload;
948         }
949
950         /* Prepare and write Segment summary for HOT_NODE */
951         memset(sum, 0, sizeof(struct f2fs_summary_block));
952         SET_SUM_TYPE((&sum->footer), SUM_TYPE_NODE);
953         memcpy(sum->entries, c.sum[CURSEG_HOT_NODE],
954                         sizeof(struct f2fs_summary) * MAX_CACHE_SUMS);
955
956         cp_seg_blk++;
957         DBG(1, "\tWriting Segment summary for HOT_NODE, at offset 0x%08"PRIx64"\n",
958                         cp_seg_blk);
959         if (dev_write_block(sum, cp_seg_blk)) {
960                 MSG(1, "\tError: While writing the sum_blk to disk!!!\n");
961                 goto free_cp_payload;
962         }
963
964         /* Fill segment summary for WARM_NODE to zero. */
965         memset(sum, 0, sizeof(struct f2fs_summary_block));
966         SET_SUM_TYPE((&sum->footer), SUM_TYPE_NODE);
967
968         cp_seg_blk++;
969         DBG(1, "\tWriting Segment summary for WARM_NODE, at offset 0x%08"PRIx64"\n",
970                         cp_seg_blk);
971         if (dev_write_block(sum, cp_seg_blk)) {
972                 MSG(1, "\tError: While writing the sum_blk to disk!!!\n");
973                 goto free_cp_payload;
974         }
975
976         /* Fill segment summary for COLD_NODE to zero. */
977         memset(sum, 0, sizeof(struct f2fs_summary_block));
978         SET_SUM_TYPE((&sum->footer), SUM_TYPE_NODE);
979         cp_seg_blk++;
980         DBG(1, "\tWriting Segment summary for COLD_NODE, at offset 0x%08"PRIx64"\n",
981                         cp_seg_blk);
982         if (dev_write_block(sum, cp_seg_blk)) {
983                 MSG(1, "\tError: While writing the sum_blk to disk!!!\n");
984                 goto free_cp_payload;
985         }
986
987         /* cp page2 */
988         cp_seg_blk++;
989         DBG(1, "\tWriting cp page2, at offset 0x%08"PRIx64"\n", cp_seg_blk);
990         if (dev_write_block(cp, cp_seg_blk)) {
991                 MSG(1, "\tError: While writing the cp to disk!!!\n");
992                 goto free_cp_payload;
993         }
994
995         /* write NAT bits, if possible */
996         if (flags & CP_NAT_BITS_FLAG) {
997                 uint32_t i;
998
999                 *(__le64 *)nat_bits = get_cp_crc(cp);
1000                 empty_nat_bits = nat_bits + 8 + nat_bits_bytes;
1001                 memset(empty_nat_bits, 0xff, nat_bits_bytes);
1002                 test_and_clear_bit_le(0, empty_nat_bits);
1003
1004                 /* write the last blocks in cp pack */
1005                 cp_seg_blk = get_sb(segment0_blkaddr) + (1 <<
1006                                 get_sb(log_blocks_per_seg)) - nat_bits_blocks;
1007
1008                 DBG(1, "\tWriting NAT bits pages, at offset 0x%08"PRIx64"\n",
1009                                         cp_seg_blk);
1010
1011                 for (i = 0; i < nat_bits_blocks; i++) {
1012                         if (dev_write_block(nat_bits + i *
1013                                                 F2FS_BLKSIZE, cp_seg_blk + i)) {
1014                                 MSG(1, "\tError: write NAT bits to disk!!!\n");
1015                                 goto free_cp_payload;
1016                         }
1017                 }
1018         }
1019
1020         /* cp page 1 of check point pack 2
1021          * Initialize other checkpoint pack with version zero
1022          */
1023         cp->checkpoint_ver = 0;
1024
1025         crc = f2fs_checkpoint_chksum(cp);
1026         *((__le32 *)((unsigned char *)cp + get_cp(checksum_offset))) =
1027                                                         cpu_to_le32(crc);
1028         cp_seg_blk = get_sb(segment0_blkaddr) + c.blks_per_seg;
1029         DBG(1, "\tWriting cp page 1 of checkpoint pack 2, at offset 0x%08"PRIx64"\n",
1030                                 cp_seg_blk);
1031         if (dev_write_block(cp, cp_seg_blk)) {
1032                 MSG(1, "\tError: While writing the cp to disk!!!\n");
1033                 goto free_cp_payload;
1034         }
1035
1036         for (i = 0; i < get_sb(cp_payload); i++) {
1037                 cp_seg_blk++;
1038                 if (dev_fill_block(cp_payload, cp_seg_blk)) {
1039                         MSG(1, "\tError: While zeroing out the sit bitmap area "
1040                                         "on disk!!!\n");
1041                         goto free_cp_payload;
1042                 }
1043         }
1044
1045         /* cp page 2 of check point pack 2 */
1046         cp_seg_blk += (le32_to_cpu(cp->cp_pack_total_block_count) -
1047                                         get_sb(cp_payload) - 1);
1048         DBG(1, "\tWriting cp page 2 of checkpoint pack 2, at offset 0x%08"PRIx64"\n",
1049                                 cp_seg_blk);
1050         if (dev_write_block(cp, cp_seg_blk)) {
1051                 MSG(1, "\tError: While writing the cp to disk!!!\n");
1052                 goto free_cp_payload;
1053         }
1054
1055         ret = 0;
1056
1057 free_cp_payload:
1058         free(cp_payload);
1059 free_nat_bits:
1060         free(nat_bits);
1061 free_sum_compact:
1062         free(sum_compact);
1063 free_sum:
1064         free(sum);
1065 free_cp:
1066         free(cp);
1067         return ret;
1068 }
1069
1070 static int f2fs_write_super_block(void)
1071 {
1072         int index;
1073         uint8_t *zero_buff;
1074
1075         zero_buff = calloc(F2FS_BLKSIZE, 1);
1076         if (zero_buff == NULL) {
1077                 MSG(1, "\tError: Calloc Failed for super_blk_zero_buf!!!\n");
1078                 return -1;
1079         }
1080
1081         memcpy(zero_buff + F2FS_SUPER_OFFSET, sb, sizeof(*sb));
1082         DBG(1, "\tWriting super block, at offset 0x%08x\n", 0);
1083         for (index = 0; index < 2; index++) {
1084                 if (dev_write_block(zero_buff, index)) {
1085                         MSG(1, "\tError: While while writing super_blk "
1086                                         "on disk!!! index : %d\n", index);
1087                         free(zero_buff);
1088                         return -1;
1089                 }
1090         }
1091
1092         free(zero_buff);
1093         return 0;
1094 }
1095
1096 #ifndef WITH_ANDROID
1097 static int f2fs_discard_obsolete_dnode(void)
1098 {
1099         struct f2fs_node *raw_node;
1100         uint64_t next_blkaddr = 0, offset;
1101         u64 end_blkaddr = (get_sb(segment_count_main) <<
1102                         get_sb(log_blocks_per_seg)) + get_sb(main_blkaddr);
1103         uint64_t start_inode_pos = get_sb(main_blkaddr);
1104         uint64_t last_inode_pos;
1105
1106         if (c.zoned_mode || c.feature & cpu_to_le32(F2FS_FEATURE_RO))
1107                 return 0;
1108
1109         raw_node = calloc(sizeof(struct f2fs_node), 1);
1110         if (raw_node == NULL) {
1111                 MSG(1, "\tError: Calloc Failed for discard_raw_node!!!\n");
1112                 return -1;
1113         }
1114
1115         /* avoid power-off-recovery based on roll-forward policy */
1116         offset = get_sb(main_blkaddr);
1117         offset += c.cur_seg[CURSEG_WARM_NODE] * c.blks_per_seg;
1118
1119         last_inode_pos = start_inode_pos +
1120                 c.cur_seg[CURSEG_HOT_NODE] * c.blks_per_seg +
1121                 c.curseg_offset[CURSEG_COLD_NODE] - 1;
1122
1123         do {
1124                 if (offset < get_sb(main_blkaddr) || offset >= end_blkaddr)
1125                         break;
1126
1127                 if (dev_read_block(raw_node, offset)) {
1128                         MSG(1, "\tError: While traversing direct node!!!\n");
1129                         free(raw_node);
1130                         return -1;
1131                 }
1132
1133                 next_blkaddr = le32_to_cpu(raw_node->footer.next_blkaddr);
1134                 memset(raw_node, 0, F2FS_BLKSIZE);
1135
1136                 DBG(1, "\tDiscard dnode, at offset 0x%08"PRIx64"\n", offset);
1137                 if (dev_write_block(raw_node, offset)) {
1138                         MSG(1, "\tError: While discarding direct node!!!\n");
1139                         free(raw_node);
1140                         return -1;
1141                 }
1142                 offset = next_blkaddr;
1143                 /* should avoid recursive chain due to stale data */
1144                 if (offset >= start_inode_pos || offset <= last_inode_pos)
1145                         break;
1146         } while (1);
1147
1148         free(raw_node);
1149         return 0;
1150 }
1151 #endif
1152
1153 static block_t alloc_next_free_block(int curseg_type)
1154 {
1155         block_t blkaddr;
1156
1157         blkaddr = get_sb(main_blkaddr) +
1158                         c.cur_seg[curseg_type] * c.blks_per_seg +
1159                         c.curseg_offset[curseg_type];
1160
1161         c.curseg_offset[curseg_type]++;
1162
1163         return blkaddr;
1164 }
1165
1166 void update_sit_journal(int curseg_type)
1167 {
1168         struct f2fs_journal *sit_jnl = &c.sit_jnl;
1169         unsigned short vblocks;
1170         int idx = curseg_type;
1171
1172         if (c.feature & cpu_to_le32(F2FS_FEATURE_RO)) {
1173                 if (curseg_type < NR_CURSEG_DATA_TYPE)
1174                         idx = CURSEG_RO_HOT_DATA;
1175                 else
1176                         idx = CURSEG_RO_HOT_NODE;
1177         }
1178
1179         f2fs_set_bit(c.curseg_offset[curseg_type] - 1,
1180                 (char *)sit_jnl->sit_j.entries[idx].se.valid_map);
1181
1182         vblocks = le16_to_cpu(sit_jnl->sit_j.entries[idx].se.vblocks);
1183         sit_jnl->sit_j.entries[idx].se.vblocks = cpu_to_le16(vblocks + 1);
1184 }
1185
1186 void update_nat_journal(nid_t nid, block_t blkaddr)
1187 {
1188         struct f2fs_journal *nat_jnl = &c.nat_jnl;
1189         unsigned short n_nats = le16_to_cpu(nat_jnl->n_nats);
1190
1191         nat_jnl->nat_j.entries[n_nats].nid = cpu_to_le32(nid);
1192         nat_jnl->nat_j.entries[n_nats].ne.version = 0;
1193         nat_jnl->nat_j.entries[n_nats].ne.ino = cpu_to_le32(nid);
1194         nat_jnl->nat_j.entries[n_nats].ne.block_addr = cpu_to_le32(blkaddr);
1195         nat_jnl->n_nats = cpu_to_le16(n_nats + 1);
1196 }
1197
1198 void update_summary_entry(int curseg_type, nid_t nid,
1199                                         unsigned short ofs_in_node)
1200 {
1201         struct f2fs_summary *sum;
1202         unsigned int curofs = c.curseg_offset[curseg_type] - 1;
1203
1204         assert(curofs < MAX_CACHE_SUMS);
1205
1206         sum = c.sum[curseg_type] + curofs;
1207         sum->nid = cpu_to_le32(nid);
1208         sum->ofs_in_node = cpu_to_le16(ofs_in_node);
1209 }
1210
1211 static block_t f2fs_add_default_dentry_root(void)
1212 {
1213         struct f2fs_dentry_block *dent_blk = NULL;
1214         block_t data_blkaddr;
1215
1216         dent_blk = calloc(F2FS_BLKSIZE, 1);
1217         if(dent_blk == NULL) {
1218                 MSG(1, "\tError: Calloc Failed for dent_blk!!!\n");
1219                 return 0;
1220         }
1221
1222         dent_blk->dentry[0].hash_code = 0;
1223         dent_blk->dentry[0].ino = sb->root_ino;
1224         dent_blk->dentry[0].name_len = cpu_to_le16(1);
1225         dent_blk->dentry[0].file_type = F2FS_FT_DIR;
1226         memcpy(dent_blk->filename[0], ".", 1);
1227
1228         dent_blk->dentry[1].hash_code = 0;
1229         dent_blk->dentry[1].ino = sb->root_ino;
1230         dent_blk->dentry[1].name_len = cpu_to_le16(2);
1231         dent_blk->dentry[1].file_type = F2FS_FT_DIR;
1232         memcpy(dent_blk->filename[1], "..", 2);
1233
1234         /* bitmap for . and .. */
1235         test_and_set_bit_le(0, dent_blk->dentry_bitmap);
1236         test_and_set_bit_le(1, dent_blk->dentry_bitmap);
1237
1238         if (c.lpf_ino) {
1239                 int len = strlen(LPF);
1240                 f2fs_hash_t hash = f2fs_dentry_hash(0, 0, (unsigned char *)LPF, len);
1241
1242                 dent_blk->dentry[2].hash_code = cpu_to_le32(hash);
1243                 dent_blk->dentry[2].ino = cpu_to_le32(c.lpf_ino);
1244                 dent_blk->dentry[2].name_len = cpu_to_le16(len);
1245                 dent_blk->dentry[2].file_type = F2FS_FT_DIR;
1246                 memcpy(dent_blk->filename[2], LPF, F2FS_SLOT_LEN);
1247
1248                 memcpy(dent_blk->filename[3], &LPF[F2FS_SLOT_LEN],
1249                                 len - F2FS_SLOT_LEN);
1250
1251                 test_and_set_bit_le(2, dent_blk->dentry_bitmap);
1252                 test_and_set_bit_le(3, dent_blk->dentry_bitmap);
1253         }
1254
1255         data_blkaddr = alloc_next_free_block(CURSEG_HOT_DATA);
1256
1257         DBG(1, "\tWriting default dentry root, at offset 0x%x\n", data_blkaddr);
1258         if (dev_write_block(dent_blk, data_blkaddr)) {
1259                 MSG(1, "\tError: While writing the dentry_blk to disk!!!\n");
1260                 free(dent_blk);
1261                 return 0;
1262         }
1263
1264         update_sit_journal(CURSEG_HOT_DATA);
1265         update_summary_entry(CURSEG_HOT_DATA, le32_to_cpu(sb->root_ino), 0);
1266
1267         free(dent_blk);
1268         return data_blkaddr;
1269 }
1270
1271 static int f2fs_write_root_inode(void)
1272 {
1273         struct f2fs_node *raw_node = NULL;
1274         block_t data_blkaddr;
1275         block_t node_blkaddr;
1276
1277         raw_node = calloc(F2FS_BLKSIZE, 1);
1278         if (raw_node == NULL) {
1279                 MSG(1, "\tError: Calloc Failed for raw_node!!!\n");
1280                 return -1;
1281         }
1282
1283         f2fs_init_inode(sb, raw_node, le32_to_cpu(sb->root_ino),
1284                                                 mkfs_time, 0x41ed);
1285
1286         if (c.lpf_ino)
1287                 raw_node->i.i_links = cpu_to_le32(3);
1288
1289         data_blkaddr = f2fs_add_default_dentry_root();
1290         if (data_blkaddr == 0) {
1291                 MSG(1, "\tError: Failed to add default dentries for root!!!\n");
1292                 free(raw_node);
1293                 return -1;
1294         }
1295
1296         raw_node->i.i_addr[get_extra_isize(raw_node)] =
1297                                 cpu_to_le32(data_blkaddr);
1298
1299         node_blkaddr = alloc_next_free_block(CURSEG_HOT_NODE);
1300         raw_node->footer.next_blkaddr = cpu_to_le32(node_blkaddr + 1);
1301
1302         DBG(1, "\tWriting root inode (hot node), offset 0x%x\n", node_blkaddr);
1303         if (write_inode(raw_node, node_blkaddr) < 0) {
1304                 MSG(1, "\tError: While writing the raw_node to disk!!!\n");
1305                 free(raw_node);
1306                 return -1;
1307         }
1308
1309         update_nat_journal(le32_to_cpu(sb->root_ino), node_blkaddr);
1310         update_sit_journal(CURSEG_HOT_NODE);
1311         update_summary_entry(CURSEG_HOT_NODE, le32_to_cpu(sb->root_ino), 0);
1312
1313         free(raw_node);
1314         return 0;
1315 }
1316
1317 static int f2fs_write_default_quota(int qtype, __le32 raw_id)
1318 {
1319         char *filebuf = calloc(F2FS_BLKSIZE, 2);
1320         int file_magics[] = INITQMAGICS;
1321         struct v2_disk_dqheader ddqheader;
1322         struct v2_disk_dqinfo ddqinfo;
1323         struct v2r1_disk_dqblk dqblk;
1324         block_t blkaddr;
1325         int i;
1326
1327         if (filebuf == NULL) {
1328                 MSG(1, "\tError: Calloc Failed for filebuf!!!\n");
1329                 return 0;
1330         }
1331
1332         /* Write basic quota header */
1333         ddqheader.dqh_magic = cpu_to_le32(file_magics[qtype]);
1334         /* only support QF_VFSV1 */
1335         ddqheader.dqh_version = cpu_to_le32(1);
1336
1337         memcpy(filebuf, &ddqheader, sizeof(ddqheader));
1338
1339         /* Fill Initial quota file content */
1340         ddqinfo.dqi_bgrace = cpu_to_le32(MAX_DQ_TIME);
1341         ddqinfo.dqi_igrace = cpu_to_le32(MAX_IQ_TIME);
1342         ddqinfo.dqi_flags = cpu_to_le32(0);
1343         ddqinfo.dqi_blocks = cpu_to_le32(QT_TREEOFF + 5);
1344         ddqinfo.dqi_free_blk = cpu_to_le32(0);
1345         ddqinfo.dqi_free_entry = cpu_to_le32(5);
1346
1347         memcpy(filebuf + V2_DQINFOOFF, &ddqinfo, sizeof(ddqinfo));
1348
1349         filebuf[1024] = 2;
1350         filebuf[2048] = 3;
1351         filebuf[3072] = 4;
1352         filebuf[4096] = 5;
1353
1354         filebuf[5120 + 8] = 1;
1355
1356         dqblk.dqb_id = raw_id;
1357         dqblk.dqb_pad = cpu_to_le32(0);
1358         dqblk.dqb_ihardlimit = cpu_to_le64(0);
1359         dqblk.dqb_isoftlimit = cpu_to_le64(0);
1360         if (c.lpf_ino)
1361                 dqblk.dqb_curinodes = cpu_to_le64(2);
1362         else
1363                 dqblk.dqb_curinodes = cpu_to_le64(1);
1364         dqblk.dqb_bhardlimit = cpu_to_le64(0);
1365         dqblk.dqb_bsoftlimit = cpu_to_le64(0);
1366         if (c.lpf_ino)
1367                 dqblk.dqb_curspace = cpu_to_le64(8192);
1368         else
1369                 dqblk.dqb_curspace = cpu_to_le64(4096);
1370         dqblk.dqb_btime = cpu_to_le64(0);
1371         dqblk.dqb_itime = cpu_to_le64(0);
1372
1373         memcpy(filebuf + 5136, &dqblk, sizeof(struct v2r1_disk_dqblk));
1374
1375         /* Write two blocks */
1376         for (i = 0; i < QUOTA_DATA; i++) {
1377                 blkaddr = alloc_next_free_block(CURSEG_HOT_DATA);
1378
1379                 if (dev_write_block(filebuf + i * F2FS_BLKSIZE, blkaddr)) {
1380                         MSG(1, "\tError: While writing the quota_blk to disk!!!\n");
1381                         free(filebuf);
1382                         return 0;
1383                 }
1384
1385                 update_sit_journal(CURSEG_HOT_DATA);
1386                 update_summary_entry(CURSEG_HOT_DATA,
1387                                         le32_to_cpu(sb->qf_ino[qtype]), i);
1388         }
1389
1390         DBG(1, "\tWriting quota data, at offset %08x, %08x\n",
1391                                         blkaddr - 1, blkaddr);
1392
1393         free(filebuf);
1394         return blkaddr - 1;
1395 }
1396
1397 static int f2fs_write_qf_inode(int qtype)
1398 {
1399         struct f2fs_node *raw_node = NULL;
1400         block_t data_blkaddr;
1401         block_t node_blkaddr;
1402         __le32 raw_id;
1403         int i;
1404
1405         raw_node = calloc(F2FS_BLKSIZE, 1);
1406         if (raw_node == NULL) {
1407                 MSG(1, "\tError: Calloc Failed for raw_node!!!\n");
1408                 return -1;
1409         }
1410         f2fs_init_inode(sb, raw_node,
1411                         le32_to_cpu(sb->qf_ino[qtype]), mkfs_time, 0x8180);
1412
1413         raw_node->i.i_size = cpu_to_le64(1024 * 6);
1414         raw_node->i.i_blocks = cpu_to_le64(1 + QUOTA_DATA);
1415         raw_node->i.i_flags = F2FS_NOATIME_FL | F2FS_IMMUTABLE_FL;
1416
1417         node_blkaddr = alloc_next_free_block(CURSEG_HOT_NODE);
1418         raw_node->footer.next_blkaddr = cpu_to_le32(node_blkaddr + 1);
1419
1420         if (qtype == 0)
1421                 raw_id = raw_node->i.i_uid;
1422         else if (qtype == 1)
1423                 raw_id = raw_node->i.i_gid;
1424         else if (qtype == 2)
1425                 raw_id = raw_node->i.i_projid;
1426         else
1427                 ASSERT(0);
1428
1429         /* write two blocks */
1430         data_blkaddr = f2fs_write_default_quota(qtype, raw_id);
1431         if (data_blkaddr == 0) {
1432                 free(raw_node);
1433                 return -1;
1434         }
1435
1436         for (i = 0; i < QUOTA_DATA; i++)
1437                 raw_node->i.i_addr[get_extra_isize(raw_node) + i] =
1438                                         cpu_to_le32(data_blkaddr + i);
1439
1440         DBG(1, "\tWriting quota inode (hot node), offset 0x%x\n", node_blkaddr);
1441         if (write_inode(raw_node, node_blkaddr) < 0) {
1442                 MSG(1, "\tError: While writing the raw_node to disk!!!\n");
1443                 free(raw_node);
1444                 return -1;
1445         }
1446
1447         update_nat_journal(le32_to_cpu(sb->qf_ino[qtype]), node_blkaddr);
1448         update_sit_journal(CURSEG_HOT_NODE);
1449         update_summary_entry(CURSEG_HOT_NODE, le32_to_cpu(sb->qf_ino[qtype]), 0);
1450
1451         free(raw_node);
1452         return 0;
1453 }
1454
1455 static int f2fs_update_nat_default(void)
1456 {
1457         struct f2fs_nat_block *nat_blk = NULL;
1458         uint64_t nat_seg_blk_offset = 0;
1459
1460         nat_blk = calloc(F2FS_BLKSIZE, 1);
1461         if(nat_blk == NULL) {
1462                 MSG(1, "\tError: Calloc Failed for nat_blk!!!\n");
1463                 return -1;
1464         }
1465
1466         /* update node nat */
1467         nat_blk->entries[get_sb(node_ino)].block_addr = cpu_to_le32(1);
1468         nat_blk->entries[get_sb(node_ino)].ino = sb->node_ino;
1469
1470         /* update meta nat */
1471         nat_blk->entries[get_sb(meta_ino)].block_addr = cpu_to_le32(1);
1472         nat_blk->entries[get_sb(meta_ino)].ino = sb->meta_ino;
1473
1474         nat_seg_blk_offset = get_sb(nat_blkaddr);
1475
1476         DBG(1, "\tWriting nat root, at offset 0x%08"PRIx64"\n",
1477                                         nat_seg_blk_offset);
1478         if (dev_write_block(nat_blk, nat_seg_blk_offset)) {
1479                 MSG(1, "\tError: While writing the nat_blk set0 to disk!\n");
1480                 free(nat_blk);
1481                 return -1;
1482         }
1483
1484         free(nat_blk);
1485         return 0;
1486 }
1487
1488 static block_t f2fs_add_default_dentry_lpf(void)
1489 {
1490         struct f2fs_dentry_block *dent_blk;
1491         block_t data_blkaddr;
1492
1493         dent_blk = calloc(F2FS_BLKSIZE, 1);
1494         if (dent_blk == NULL) {
1495                 MSG(1, "\tError: Calloc Failed for dent_blk!!!\n");
1496                 return 0;
1497         }
1498
1499         dent_blk->dentry[0].hash_code = 0;
1500         dent_blk->dentry[0].ino = cpu_to_le32(c.lpf_ino);
1501         dent_blk->dentry[0].name_len = cpu_to_le16(1);
1502         dent_blk->dentry[0].file_type = F2FS_FT_DIR;
1503         memcpy(dent_blk->filename[0], ".", 1);
1504
1505         dent_blk->dentry[1].hash_code = 0;
1506         dent_blk->dentry[1].ino = sb->root_ino;
1507         dent_blk->dentry[1].name_len = cpu_to_le16(2);
1508         dent_blk->dentry[1].file_type = F2FS_FT_DIR;
1509         memcpy(dent_blk->filename[1], "..", 2);
1510
1511         test_and_set_bit_le(0, dent_blk->dentry_bitmap);
1512         test_and_set_bit_le(1, dent_blk->dentry_bitmap);
1513
1514         data_blkaddr = alloc_next_free_block(CURSEG_HOT_DATA);
1515
1516         DBG(1, "\tWriting default dentry lost+found, at offset 0x%x\n",
1517                                                         data_blkaddr);
1518         if (dev_write_block(dent_blk, data_blkaddr)) {
1519                 MSG(1, "\tError While writing the dentry_blk to disk!!!\n");
1520                 free(dent_blk);
1521                 return 0;
1522         }
1523
1524         update_sit_journal(CURSEG_HOT_DATA);
1525         update_summary_entry(CURSEG_HOT_DATA, c.lpf_ino, 0);
1526
1527         free(dent_blk);
1528         return data_blkaddr;
1529 }
1530
1531 static int f2fs_write_lpf_inode(void)
1532 {
1533         struct f2fs_node *raw_node;
1534         block_t data_blkaddr;
1535         block_t node_blkaddr;
1536         int err = 0;
1537
1538         ASSERT(c.lpf_ino);
1539
1540         raw_node = calloc(F2FS_BLKSIZE, 1);
1541         if (raw_node == NULL) {
1542                 MSG(1, "\tError: Calloc Failed for raw_node!!!\n");
1543                 return -1;
1544         }
1545
1546         f2fs_init_inode(sb, raw_node, c.lpf_ino, mkfs_time, 0x41c0);
1547
1548         raw_node->i.i_pino = le32_to_cpu(sb->root_ino);
1549         raw_node->i.i_namelen = le32_to_cpu(strlen(LPF));
1550         memcpy(raw_node->i.i_name, LPF, strlen(LPF));
1551
1552         node_blkaddr = alloc_next_free_block(CURSEG_HOT_NODE);
1553         raw_node->footer.next_blkaddr = cpu_to_le32(node_blkaddr + 1);
1554
1555         data_blkaddr = f2fs_add_default_dentry_lpf();
1556         if (data_blkaddr == 0) {
1557                 MSG(1, "\tError: Failed to add default dentries for lost+found!!!\n");
1558                 err = -1;
1559                 goto exit;
1560         }
1561         raw_node->i.i_addr[get_extra_isize(raw_node)] = cpu_to_le32(data_blkaddr);
1562
1563         DBG(1, "\tWriting lost+found inode (hot node), offset 0x%x\n",
1564                                                                 node_blkaddr);
1565         if (write_inode(raw_node, node_blkaddr) < 0) {
1566                 MSG(1, "\tError: While writing the raw_node to disk!!!\n");
1567                 err = -1;
1568                 goto exit;
1569         }
1570
1571         update_nat_journal(c.lpf_ino, node_blkaddr);
1572         update_sit_journal(CURSEG_HOT_NODE);
1573         update_summary_entry(CURSEG_HOT_NODE, c.lpf_ino, 0);
1574
1575 exit:
1576         free(raw_node);
1577         return err;
1578 }
1579
1580 static int f2fs_create_root_dir(void)
1581 {
1582         enum quota_type qtype;
1583         int err = 0;
1584
1585         err = f2fs_write_root_inode();
1586         if (err < 0) {
1587                 MSG(1, "\tError: Failed to write root inode!!!\n");
1588                 goto exit;
1589         }
1590
1591         for (qtype = 0; qtype < F2FS_MAX_QUOTAS; qtype++)  {
1592                 if (!((1 << qtype) & c.quota_bits))
1593                         continue;
1594                 err = f2fs_write_qf_inode(qtype);
1595                 if (err < 0) {
1596                         MSG(1, "\tError: Failed to write quota inode!!!\n");
1597                         goto exit;
1598                 }
1599         }
1600
1601         if (c.feature & cpu_to_le32(F2FS_FEATURE_LOST_FOUND)) {
1602                 err = f2fs_write_lpf_inode();
1603                 if (err < 0) {
1604                         MSG(1, "\tError: Failed to write lost+found inode!!!\n");
1605                         goto exit;
1606                 }
1607         }
1608
1609 #ifndef WITH_ANDROID
1610         err = f2fs_discard_obsolete_dnode();
1611         if (err < 0) {
1612                 MSG(1, "\tError: Failed to discard obsolete dnode!!!\n");
1613                 goto exit;
1614         }
1615 #endif
1616
1617         err = f2fs_update_nat_default();
1618         if (err < 0) {
1619                 MSG(1, "\tError: Failed to update NAT for root!!!\n");
1620                 goto exit;
1621         }
1622 exit:
1623         if (err)
1624                 MSG(1, "\tError: Could not create the root directory!!!\n");
1625
1626         return err;
1627 }
1628
1629 int f2fs_format_device(void)
1630 {
1631         int err = 0;
1632
1633         err= f2fs_prepare_super_block();
1634         if (err < 0) {
1635                 MSG(0, "\tError: Failed to prepare a super block!!!\n");
1636                 goto exit;
1637         }
1638
1639         if (c.trim) {
1640                 err = f2fs_trim_devices();
1641                 if (err < 0) {
1642                         MSG(0, "\tError: Failed to trim whole device!!!\n");
1643                         goto exit;
1644                 }
1645         }
1646
1647         err = f2fs_init_sit_area();
1648         if (err < 0) {
1649                 MSG(0, "\tError: Failed to initialise the SIT AREA!!!\n");
1650                 goto exit;
1651         }
1652
1653         err = f2fs_init_nat_area();
1654         if (err < 0) {
1655                 MSG(0, "\tError: Failed to initialise the NAT AREA!!!\n");
1656                 goto exit;
1657         }
1658
1659         err = f2fs_create_root_dir();
1660         if (err < 0) {
1661                 MSG(0, "\tError: Failed to create the root directory!!!\n");
1662                 goto exit;
1663         }
1664
1665         err = f2fs_write_check_point_pack();
1666         if (err < 0) {
1667                 MSG(0, "\tError: Failed to write the check point pack!!!\n");
1668                 goto exit;
1669         }
1670
1671         err = f2fs_write_super_block();
1672         if (err < 0) {
1673                 MSG(0, "\tError: Failed to write the super block!!!\n");
1674                 goto exit;
1675         }
1676 exit:
1677         if (err)
1678                 MSG(0, "\tError: Could not format the device!!!\n");
1679
1680         return err;
1681 }