1.. SPDX-License-Identifier: GPL-2.0
2
3==========================================
4WHAT IS Flash-Friendly File System (F2FS)?
5==========================================
6
7NAND flash memory-based storage devices, such as SSD, eMMC, and SD cards, have
8been equipped on a variety systems ranging from mobile to server systems. Since
9they are known to have different characteristics from the conventional rotating
10disks, a file system, an upper layer to the storage device, should adapt to the
11changes from the sketch in the design level.
12
13F2FS is a file system exploiting NAND flash memory-based storage devices, which
14is based on Log-structured File System (LFS). The design has been focused on
15addressing the fundamental issues in LFS, which are snowball effect of wandering
16tree and high cleaning overhead.
17
18Since a NAND flash memory-based storage device shows different characteristic
19according to its internal geometry or flash memory management scheme, namely FTL,
20F2FS and its tools support various parameters not only for configuring on-disk
21layout, but also for selecting allocation and cleaning algorithms.
22
23The following git tree provides the file system formatting tool (mkfs.f2fs),
24a consistency checking tool (fsck.f2fs), and a debugging tool (dump.f2fs).
25
26- git://git.kernel.org/pub/scm/linux/kernel/git/jaegeuk/f2fs-tools.git
27
28For sending patches, please use the following mailing list:
29
30- linux-f2fs-devel@lists.sourceforge.net
31
32For reporting bugs, please use the following f2fs bug tracker link:
33
34- https://bugzilla.kernel.org/enter_bug.cgi?product=File%20System&component=f2fs
35
36Background and Design issues
37============================
38
39Log-structured File System (LFS)
40--------------------------------
41"A log-structured file system writes all modifications to disk sequentially in
42a log-like structure, thereby speeding up  both file writing and crash recovery.
43The log is the only structure on disk; it contains indexing information so that
44files can be read back from the log efficiently. In order to maintain large free
45areas on disk for fast writing, we divide  the log into segments and use a
46segment cleaner to compress the live information from heavily fragmented
47segments." from Rosenblum, M. and Ousterhout, J. K., 1992, "The design and
48implementation of a log-structured file system", ACM Trans. Computer Systems
4910, 1, 26–52.
50
51Wandering Tree Problem
52----------------------
53In LFS, when a file data is updated and written to the end of log, its direct
54pointer block is updated due to the changed location. Then the indirect pointer
55block is also updated due to the direct pointer block update. In this manner,
56the upper index structures such as inode, inode map, and checkpoint block are
57also updated recursively. This problem is called as wandering tree problem [1],
58and in order to enhance the performance, it should eliminate or relax the update
59propagation as much as possible.
60
61[1] Bityutskiy, A. 2005. JFFS3 design issues. http://www.linux-mtd.infradead.org/
62
63Cleaning Overhead
64-----------------
65Since LFS is based on out-of-place writes, it produces so many obsolete blocks
66scattered across the whole storage. In order to serve new empty log space, it
67needs to reclaim these obsolete blocks seamlessly to users. This job is called
68as a cleaning process.
69
70The process consists of three operations as follows.
71
721. A victim segment is selected through referencing segment usage table.
732. It loads parent index structures of all the data in the victim identified by
74   segment summary blocks.
753. It checks the cross-reference between the data and its parent index structure.
764. It moves valid data selectively.
77
78This cleaning job may cause unexpected long delays, so the most important goal
79is to hide the latencies to users. And also definitely, it should reduce the
80amount of valid data to be moved, and move them quickly as well.
81
82Key Features
83============
84
85Flash Awareness
86---------------
87- Enlarge the random write area for better performance, but provide the high
88  spatial locality
89- Align FS data structures to the operational units in FTL as best efforts
90
91Wandering Tree Problem
92----------------------
93- Use a term, “node”, that represents inodes as well as various pointer blocks
94- Introduce Node Address Table (NAT) containing the locations of all the “node”
95  blocks; this will cut off the update propagation.
96
97Cleaning Overhead
98-----------------
99- Support a background cleaning process
100- Support greedy and cost-benefit algorithms for victim selection policies
101- Support multi-head logs for static/dynamic hot and cold data separation
102- Introduce adaptive logging for efficient block allocation
103
104Mount Options
105=============
106
107
108======================== ============================================================
109background_gc=%s	 Turn on/off cleaning operations, namely garbage
110			 collection, triggered in background when I/O subsystem is
111			 idle. If background_gc=on, it will turn on the garbage
112			 collection and if background_gc=off, garbage collection
113			 will be turned off. If background_gc=sync, it will turn
114			 on synchronous garbage collection running in background.
115			 Default value for this option is on. So garbage
116			 collection is on by default.
117gc_merge		 When background_gc is on, this option can be enabled to
118			 let background GC thread to handle foreground GC requests,
119			 it can eliminate the sluggish issue caused by slow foreground
120			 GC operation when GC is triggered from a process with limited
121			 I/O and CPU resources.
122nogc_merge		 Disable GC merge feature.
123disable_roll_forward	 Disable the roll-forward recovery routine
124norecovery		 Disable the roll-forward recovery routine, mounted read-
125			 only (i.e., -o ro,disable_roll_forward)
126discard/nodiscard	 Enable/disable real-time discard in f2fs, if discard is
127			 enabled, f2fs will issue discard/TRIM commands when a
128			 segment is cleaned.
129no_heap			 Disable heap-style segment allocation which finds free
130			 segments for data from the beginning of main area, while
131			 for node from the end of main area.
132nouser_xattr		 Disable Extended User Attributes. Note: xattr is enabled
133			 by default if CONFIG_F2FS_FS_XATTR is selected.
134noacl			 Disable POSIX Access Control List. Note: acl is enabled
135			 by default if CONFIG_F2FS_FS_POSIX_ACL is selected.
136active_logs=%u		 Support configuring the number of active logs. In the
137			 current design, f2fs supports only 2, 4, and 6 logs.
138			 Default number is 6.
139disable_ext_identify	 Disable the extension list configured by mkfs, so f2fs
140			 is not aware of cold files such as media files.
141inline_xattr		 Enable the inline xattrs feature.
142noinline_xattr		 Disable the inline xattrs feature.
143inline_xattr_size=%u	 Support configuring inline xattr size, it depends on
144			 flexible inline xattr feature.
145inline_data		 Enable the inline data feature: Newly created small (<~3.4k)
146			 files can be written into inode block.
147inline_dentry		 Enable the inline dir feature: data in newly created
148			 directory entries can be written into inode block. The
149			 space of inode block which is used to store inline
150			 dentries is limited to ~3.4k.
151noinline_dentry		 Disable the inline dentry feature.
152flush_merge		 Merge concurrent cache_flush commands as much as possible
153			 to eliminate redundant command issues. If the underlying
154			 device handles the cache_flush command relatively slowly,
155			 recommend to enable this option.
156nobarrier		 This option can be used if underlying storage guarantees
157			 its cached data should be written to the novolatile area.
158			 If this option is set, no cache_flush commands are issued
159			 but f2fs still guarantees the write ordering of all the
160			 data writes.
161barrier			 If this option is set, cache_flush commands are allowed to be
162			 issued.
163fastboot		 This option is used when a system wants to reduce mount
164			 time as much as possible, even though normal performance
165			 can be sacrificed.
166extent_cache		 Enable an extent cache based on rb-tree, it can cache
167			 as many as extent which map between contiguous logical
168			 address and physical address per inode, resulting in
169			 increasing the cache hit ratio. Set by default.
170noextent_cache		 Disable an extent cache based on rb-tree explicitly, see
171			 the above extent_cache mount option.
172noinline_data		 Disable the inline data feature, inline data feature is
173			 enabled by default.
174data_flush		 Enable data flushing before checkpoint in order to
175			 persist data of regular and symlink.
176reserve_root=%d		 Support configuring reserved space which is used for
177			 allocation from a privileged user with specified uid or
178			 gid, unit: 4KB, the default limit is 0.2% of user blocks.
179resuid=%d		 The user ID which may use the reserved blocks.
180resgid=%d		 The group ID which may use the reserved blocks.
181fault_injection=%d	 Enable fault injection in all supported types with
182			 specified injection rate.
183fault_type=%d		 Support configuring fault injection type, should be
184			 enabled with fault_injection option, fault type value
185			 is shown below, it supports single or combined type.
186
187			 ===================	  ===========
188			 Type_Name		  Type_Value
189			 ===================	  ===========
190			 FAULT_KMALLOC		  0x000000001
191			 FAULT_KVMALLOC		  0x000000002
192			 FAULT_PAGE_ALLOC	  0x000000004
193			 FAULT_PAGE_GET		  0x000000008
194			 FAULT_ALLOC_BIO	  0x000000010 (obsolete)
195			 FAULT_ALLOC_NID	  0x000000020
196			 FAULT_ORPHAN		  0x000000040
197			 FAULT_BLOCK		  0x000000080
198			 FAULT_DIR_DEPTH	  0x000000100
199			 FAULT_EVICT_INODE	  0x000000200
200			 FAULT_TRUNCATE		  0x000000400
201			 FAULT_READ_IO		  0x000000800
202			 FAULT_CHECKPOINT	  0x000001000
203			 FAULT_DISCARD		  0x000002000
204			 FAULT_WRITE_IO		  0x000004000
205			 FAULT_SLAB_ALLOC	  0x000008000
206			 FAULT_DQUOT_INIT	  0x000010000
207			 FAULT_LOCK_OP		  0x000020000
208			 FAULT_BLKADDR		  0x000040000
209			 ===================	  ===========
210mode=%s			 Control block allocation mode which supports "adaptive"
211			 and "lfs". In "lfs" mode, there should be no random
212			 writes towards main area.
213			 "fragment:segment" and "fragment:block" are newly added here.
214			 These are developer options for experiments to simulate filesystem
215			 fragmentation/after-GC situation itself. The developers use these
216			 modes to understand filesystem fragmentation/after-GC condition well,
217			 and eventually get some insights to handle them better.
218			 In "fragment:segment", f2fs allocates a new segment in ramdom
219			 position. With this, we can simulate the after-GC condition.
220			 In "fragment:block", we can scatter block allocation with
221			 "max_fragment_chunk" and "max_fragment_hole" sysfs nodes.
222			 We added some randomness to both chunk and hole size to make
223			 it close to realistic IO pattern. So, in this mode, f2fs will allocate
224			 1..<max_fragment_chunk> blocks in a chunk and make a hole in the
225			 length of 1..<max_fragment_hole> by turns. With this, the newly
226			 allocated blocks will be scattered throughout the whole partition.
227			 Note that "fragment:block" implicitly enables "fragment:segment"
228			 option for more randomness.
229			 Please, use these options for your experiments and we strongly
230			 recommend to re-format the filesystem after using these options.
231io_bits=%u		 Set the bit size of write IO requests. It should be set
232			 with "mode=lfs".
233usrquota		 Enable plain user disk quota accounting.
234grpquota		 Enable plain group disk quota accounting.
235prjquota		 Enable plain project quota accounting.
236usrjquota=<file>	 Appoint specified file and type during mount, so that quota
237grpjquota=<file>	 information can be properly updated during recovery flow,
238prjjquota=<file>	 <quota file>: must be in root directory;
239jqfmt=<quota type>	 <quota type>: [vfsold,vfsv0,vfsv1].
240offusrjquota		 Turn off user journalled quota.
241offgrpjquota		 Turn off group journalled quota.
242offprjjquota		 Turn off project journalled quota.
243quota			 Enable plain user disk quota accounting.
244noquota			 Disable all plain disk quota option.
245alloc_mode=%s		 Adjust block allocation policy, which supports "reuse"
246			 and "default".
247fsync_mode=%s		 Control the policy of fsync. Currently supports "posix",
248			 "strict", and "nobarrier". In "posix" mode, which is
249			 default, fsync will follow POSIX semantics and does a
250			 light operation to improve the filesystem performance.
251			 In "strict" mode, fsync will be heavy and behaves in line
252			 with xfs, ext4 and btrfs, where xfstest generic/342 will
253			 pass, but the performance will regress. "nobarrier" is
254			 based on "posix", but doesn't issue flush command for
255			 non-atomic files likewise "nobarrier" mount option.
256test_dummy_encryption
257test_dummy_encryption=%s
258			 Enable dummy encryption, which provides a fake fscrypt
259			 context. The fake fscrypt context is used by xfstests.
260			 The argument may be either "v1" or "v2", in order to
261			 select the corresponding fscrypt policy version.
262checkpoint=%s[:%u[%]]	 Set to "disable" to turn off checkpointing. Set to "enable"
263			 to reenable checkpointing. Is enabled by default. While
264			 disabled, any unmounting or unexpected shutdowns will cause
265			 the filesystem contents to appear as they did when the
266			 filesystem was mounted with that option.
267			 While mounting with checkpoint=disable, the filesystem must
268			 run garbage collection to ensure that all available space can
269			 be used. If this takes too much time, the mount may return
270			 EAGAIN. You may optionally add a value to indicate how much
271			 of the disk you would be willing to temporarily give up to
272			 avoid additional garbage collection. This can be given as a
273			 number of blocks, or as a percent. For instance, mounting
274			 with checkpoint=disable:100% would always succeed, but it may
275			 hide up to all remaining free space. The actual space that
276			 would be unusable can be viewed at /sys/fs/f2fs/<disk>/unusable
277			 This space is reclaimed once checkpoint=enable.
278checkpoint_merge	 When checkpoint is enabled, this can be used to create a kernel
279			 daemon and make it to merge concurrent checkpoint requests as
280			 much as possible to eliminate redundant checkpoint issues. Plus,
281			 we can eliminate the sluggish issue caused by slow checkpoint
282			 operation when the checkpoint is done in a process context in
283			 a cgroup having low i/o budget and cpu shares. To make this
284			 do better, we set the default i/o priority of the kernel daemon
285			 to "3", to give one higher priority than other kernel threads.
286			 This is the same way to give a I/O priority to the jbd2
287			 journaling thread of ext4 filesystem.
288nocheckpoint_merge	 Disable checkpoint merge feature.
289compress_algorithm=%s	 Control compress algorithm, currently f2fs supports "lzo",
290			 "lz4", "zstd" and "lzo-rle" algorithm.
291compress_algorithm=%s:%d Control compress algorithm and its compress level, now, only
292			 "lz4" and "zstd" support compress level config.
293			 algorithm	level range
294			 lz4		3 - 16
295			 zstd		1 - 22
296compress_log_size=%u	 Support configuring compress cluster size. The size will
297			 be 4KB * (1 << %u). The default and minimum sizes are 16KB.
298compress_extension=%s	 Support adding specified extension, so that f2fs can enable
299			 compression on those corresponding files, e.g. if all files
300			 with '.ext' has high compression rate, we can set the '.ext'
301			 on compression extension list and enable compression on
302			 these file by default rather than to enable it via ioctl.
303			 For other files, we can still enable compression via ioctl.
304			 Note that, there is one reserved special extension '*', it
305			 can be set to enable compression for all files.
306nocompress_extension=%s	 Support adding specified extension, so that f2fs can disable
307			 compression on those corresponding files, just contrary to compression extension.
308			 If you know exactly which files cannot be compressed, you can use this.
309			 The same extension name can't appear in both compress and nocompress
310			 extension at the same time.
311			 If the compress extension specifies all files, the types specified by the
312			 nocompress extension will be treated as special cases and will not be compressed.
313			 Don't allow use '*' to specifie all file in nocompress extension.
314			 After add nocompress_extension, the priority should be:
315			 dir_flag < comp_extention,nocompress_extension < comp_file_flag,no_comp_file_flag.
316			 See more in compression sections.
317
318compress_chksum		 Support verifying chksum of raw data in compressed cluster.
319compress_mode=%s	 Control file compression mode. This supports "fs" and "user"
320			 modes. In "fs" mode (default), f2fs does automatic compression
321			 on the compression enabled files. In "user" mode, f2fs disables
322			 the automaic compression and gives the user discretion of
323			 choosing the target file and the timing. The user can do manual
324			 compression/decompression on the compression enabled files using
325			 ioctls.
326compress_cache		 Support to use address space of a filesystem managed inode to
327			 cache compressed block, in order to improve cache hit ratio of
328			 random read.
329inlinecrypt		 When possible, encrypt/decrypt the contents of encrypted
330			 files using the blk-crypto framework rather than
331			 filesystem-layer encryption. This allows the use of
332			 inline encryption hardware. The on-disk format is
333			 unaffected. For more details, see
334			 Documentation/block/inline-encryption.rst.
335atgc			 Enable age-threshold garbage collection, it provides high
336			 effectiveness and efficiency on background GC.
337discard_unit=%s		 Control discard unit, the argument can be "block", "segment"
338			 and "section", issued discard command's offset/size will be
339			 aligned to the unit, by default, "discard_unit=block" is set,
340			 so that small discard functionality is enabled.
341			 For blkzoned device, "discard_unit=section" will be set by
342			 default, it is helpful for large sized SMR or ZNS devices to
343			 reduce memory cost by getting rid of fs metadata supports small
344			 discard.
345memory=%s		 Control memory mode. This supports "normal" and "low" modes.
346			 "low" mode is introduced to support low memory devices.
347			 Because of the nature of low memory devices, in this mode, f2fs
348			 will try to save memory sometimes by sacrificing performance.
349			 "normal" mode is the default mode and same as before.
350age_extent_cache	 Enable an age extent cache based on rb-tree. It records
351			 data block update frequency of the extent per inode, in
352			 order to provide better temperature hints for data block
353			 allocation.
354======================== ============================================================
355
356Debugfs Entries
357===============
358
359/sys/kernel/debug/f2fs/ contains information about all the partitions mounted as
360f2fs. Each file shows the whole f2fs information.
361
362/sys/kernel/debug/f2fs/status includes:
363
364 - major file system information managed by f2fs currently
365 - average SIT information about whole segments
366 - current memory footprint consumed by f2fs.
367
368Sysfs Entries
369=============
370
371Information about mounted f2fs file systems can be found in
372/sys/fs/f2fs.  Each mounted filesystem will have a directory in
373/sys/fs/f2fs based on its device name (i.e., /sys/fs/f2fs/sda).
374The files in each per-device directory are shown in table below.
375
376Files in /sys/fs/f2fs/<devname>
377(see also Documentation/ABI/testing/sysfs-fs-f2fs)
378
379Usage
380=====
381
3821. Download userland tools and compile them.
383
3842. Skip, if f2fs was compiled statically inside kernel.
385   Otherwise, insert the f2fs.ko module::
386
387	# insmod f2fs.ko
388
3893. Create a directory to use when mounting::
390
391	# mkdir /mnt/f2fs
392
3934. Format the block device, and then mount as f2fs::
394
395	# mkfs.f2fs -l label /dev/block_device
396	# mount -t f2fs /dev/block_device /mnt/f2fs
397
398mkfs.f2fs
399---------
400The mkfs.f2fs is for the use of formatting a partition as the f2fs filesystem,
401which builds a basic on-disk layout.
402
403The quick options consist of:
404
405===============    ===========================================================
406``-l [label]``     Give a volume label, up to 512 unicode name.
407``-a [0 or 1]``    Split start location of each area for heap-based allocation.
408
409                   1 is set by default, which performs this.
410``-o [int]``       Set overprovision ratio in percent over volume size.
411
412                   5 is set by default.
413``-s [int]``       Set the number of segments per section.
414
415                   1 is set by default.
416``-z [int]``       Set the number of sections per zone.
417
418                   1 is set by default.
419``-e [str]``       Set basic extension list. e.g. "mp3,gif,mov"
420``-t [0 or 1]``    Disable discard command or not.
421
422                   1 is set by default, which conducts discard.
423===============    ===========================================================
424
425Note: please refer to the manpage of mkfs.f2fs(8) to get full option list.
426
427fsck.f2fs
428---------
429The fsck.f2fs is a tool to check the consistency of an f2fs-formatted
430partition, which examines whether the filesystem metadata and user-made data
431are cross-referenced correctly or not.
432Note that, initial version of the tool does not fix any inconsistency.
433
434The quick options consist of::
435
436  -d debug level [default:0]
437
438Note: please refer to the manpage of fsck.f2fs(8) to get full option list.
439
440dump.f2fs
441---------
442The dump.f2fs shows the information of specific inode and dumps SSA and SIT to
443file. Each file is dump_ssa and dump_sit.
444
445The dump.f2fs is used to debug on-disk data structures of the f2fs filesystem.
446It shows on-disk inode information recognized by a given inode number, and is
447able to dump all the SSA and SIT entries into predefined files, ./dump_ssa and
448./dump_sit respectively.
449
450The options consist of::
451
452  -d debug level [default:0]
453  -i inode no (hex)
454  -s [SIT dump segno from #1~#2 (decimal), for all 0~-1]
455  -a [SSA dump segno from #1~#2 (decimal), for all 0~-1]
456
457Examples::
458
459    # dump.f2fs -i [ino] /dev/sdx
460    # dump.f2fs -s 0~-1 /dev/sdx (SIT dump)
461    # dump.f2fs -a 0~-1 /dev/sdx (SSA dump)
462
463Note: please refer to the manpage of dump.f2fs(8) to get full option list.
464
465sload.f2fs
466----------
467The sload.f2fs gives a way to insert files and directories in the exisiting disk
468image. This tool is useful when building f2fs images given compiled files.
469
470Note: please refer to the manpage of sload.f2fs(8) to get full option list.
471
472resize.f2fs
473-----------
474The resize.f2fs lets a user resize the f2fs-formatted disk image, while preserving
475all the files and directories stored in the image.
476
477Note: please refer to the manpage of resize.f2fs(8) to get full option list.
478
479defrag.f2fs
480-----------
481The defrag.f2fs can be used to defragment scattered written data as well as
482filesystem metadata across the disk. This can improve the write speed by giving
483more free consecutive space.
484
485Note: please refer to the manpage of defrag.f2fs(8) to get full option list.
486
487f2fs_io
488-------
489The f2fs_io is a simple tool to issue various filesystem APIs as well as
490f2fs-specific ones, which is very useful for QA tests.
491
492Note: please refer to the manpage of f2fs_io(8) to get full option list.
493
494Design
495======
496
497On-disk Layout
498--------------
499
500F2FS divides the whole volume into a number of segments, each of which is fixed
501to 2MB in size. A section is composed of consecutive segments, and a zone
502consists of a set of sections. By default, section and zone sizes are set to one
503segment size identically, but users can easily modify the sizes by mkfs.
504
505F2FS splits the entire volume into six areas, and all the areas except superblock
506consist of multiple segments as described below::
507
508                                            align with the zone size <-|
509                 |-> align with the segment size
510     _________________________________________________________________________
511    |            |            |   Segment   |    Node     |   Segment  |      |
512    | Superblock | Checkpoint |    Info.    |   Address   |   Summary  | Main |
513    |    (SB)    |   (CP)     | Table (SIT) | Table (NAT) | Area (SSA) |      |
514    |____________|_____2______|______N______|______N______|______N_____|__N___|
515                                                                       .      .
516                                                             .                .
517                                                 .                            .
518                                    ._________________________________________.
519                                    |_Segment_|_..._|_Segment_|_..._|_Segment_|
520                                    .           .
521                                    ._________._________
522                                    |_section_|__...__|_
523                                    .            .
524		                    .________.
525	                            |__zone__|
526
527- Superblock (SB)
528   It is located at the beginning of the partition, and there exist two copies
529   to avoid file system crash. It contains basic partition information and some
530   default parameters of f2fs.
531
532- Checkpoint (CP)
533   It contains file system information, bitmaps for valid NAT/SIT sets, orphan
534   inode lists, and summary entries of current active segments.
535
536- Segment Information Table (SIT)
537   It contains segment information such as valid block count and bitmap for the
538   validity of all the blocks.
539
540- Node Address Table (NAT)
541   It is composed of a block address table for all the node blocks stored in
542   Main area.
543
544- Segment Summary Area (SSA)
545   It contains summary entries which contains the owner information of all the
546   data and node blocks stored in Main area.
547
548- Main Area
549   It contains file and directory data including their indices.
550
551In order to avoid misalignment between file system and flash-based storage, F2FS
552aligns the start block address of CP with the segment size. Also, it aligns the
553start block address of Main area with the zone size by reserving some segments
554in SSA area.
555
556Reference the following survey for additional technical details.
557https://wiki.linaro.org/WorkingGroups/Kernel/Projects/FlashCardSurvey
558
559File System Metadata Structure
560------------------------------
561
562F2FS adopts the checkpointing scheme to maintain file system consistency. At
563mount time, F2FS first tries to find the last valid checkpoint data by scanning
564CP area. In order to reduce the scanning time, F2FS uses only two copies of CP.
565One of them always indicates the last valid data, which is called as shadow copy
566mechanism. In addition to CP, NAT and SIT also adopt the shadow copy mechanism.
567
568For file system consistency, each CP points to which NAT and SIT copies are
569valid, as shown as below::
570
571  +--------+----------+---------+
572  |   CP   |    SIT   |   NAT   |
573  +--------+----------+---------+
574  .         .          .          .
575  .            .              .              .
576  .               .                 .                 .
577  +-------+-------+--------+--------+--------+--------+
578  | CP #0 | CP #1 | SIT #0 | SIT #1 | NAT #0 | NAT #1 |
579  +-------+-------+--------+--------+--------+--------+
580     |             ^                          ^
581     |             |                          |
582     `----------------------------------------'
583
584Index Structure
585---------------
586
587The key data structure to manage the data locations is a "node". Similar to
588traditional file structures, F2FS has three types of node: inode, direct node,
589indirect node. F2FS assigns 4KB to an inode block which contains 923 data block
590indices, two direct node pointers, two indirect node pointers, and one double
591indirect node pointer as described below. One direct node block contains 1018
592data blocks, and one indirect node block contains also 1018 node blocks. Thus,
593one inode block (i.e., a file) covers::
594
595  4KB * (923 + 2 * 1018 + 2 * 1018 * 1018 + 1018 * 1018 * 1018) := 3.94TB.
596
597   Inode block (4KB)
598     |- data (923)
599     |- direct node (2)
600     |          `- data (1018)
601     |- indirect node (2)
602     |            `- direct node (1018)
603     |                       `- data (1018)
604     `- double indirect node (1)
605                         `- indirect node (1018)
606			              `- direct node (1018)
607	                                         `- data (1018)
608
609Note that all the node blocks are mapped by NAT which means the location of
610each node is translated by the NAT table. In the consideration of the wandering
611tree problem, F2FS is able to cut off the propagation of node updates caused by
612leaf data writes.
613
614Directory Structure
615-------------------
616
617A directory entry occupies 11 bytes, which consists of the following attributes.
618
619- hash		hash value of the file name
620- ino		inode number
621- len		the length of file name
622- type		file type such as directory, symlink, etc
623
624A dentry block consists of 214 dentry slots and file names. Therein a bitmap is
625used to represent whether each dentry is valid or not. A dentry block occupies
6264KB with the following composition.
627
628::
629
630  Dentry Block(4 K) = bitmap (27 bytes) + reserved (3 bytes) +
631	              dentries(11 * 214 bytes) + file name (8 * 214 bytes)
632
633                         [Bucket]
634             +--------------------------------+
635             |dentry block 1 | dentry block 2 |
636             +--------------------------------+
637             .               .
638       .                             .
639  .       [Dentry Block Structure: 4KB]       .
640  +--------+----------+----------+------------+
641  | bitmap | reserved | dentries | file names |
642  +--------+----------+----------+------------+
643  [Dentry Block: 4KB] .   .
644		 .               .
645            .                          .
646            +------+------+-----+------+
647            | hash | ino  | len | type |
648            +------+------+-----+------+
649            [Dentry Structure: 11 bytes]
650
651F2FS implements multi-level hash tables for directory structure. Each level has
652a hash table with dedicated number of hash buckets as shown below. Note that
653"A(2B)" means a bucket includes 2 data blocks.
654
655::
656
657    ----------------------
658    A : bucket
659    B : block
660    N : MAX_DIR_HASH_DEPTH
661    ----------------------
662
663    level #0   | A(2B)
664	    |
665    level #1   | A(2B) - A(2B)
666	    |
667    level #2   | A(2B) - A(2B) - A(2B) - A(2B)
668	.     |   .       .       .       .
669    level #N/2 | A(2B) - A(2B) - A(2B) - A(2B) - A(2B) - ... - A(2B)
670	.     |   .       .       .       .
671    level #N   | A(4B) - A(4B) - A(4B) - A(4B) - A(4B) - ... - A(4B)
672
673The number of blocks and buckets are determined by::
674
675                            ,- 2, if n < MAX_DIR_HASH_DEPTH / 2,
676  # of blocks in level #n = |
677                            `- 4, Otherwise
678
679                             ,- 2^(n + dir_level),
680			     |        if n + dir_level < MAX_DIR_HASH_DEPTH / 2,
681  # of buckets in level #n = |
682                             `- 2^((MAX_DIR_HASH_DEPTH / 2) - 1),
683			              Otherwise
684
685When F2FS finds a file name in a directory, at first a hash value of the file
686name is calculated. Then, F2FS scans the hash table in level #0 to find the
687dentry consisting of the file name and its inode number. If not found, F2FS
688scans the next hash table in level #1. In this way, F2FS scans hash tables in
689each levels incrementally from 1 to N. In each level F2FS needs to scan only
690one bucket determined by the following equation, which shows O(log(# of files))
691complexity::
692
693  bucket number to scan in level #n = (hash value) % (# of buckets in level #n)
694
695In the case of file creation, F2FS finds empty consecutive slots that cover the
696file name. F2FS searches the empty slots in the hash tables of whole levels from
6971 to N in the same way as the lookup operation.
698
699The following figure shows an example of two cases holding children::
700
701       --------------> Dir <--------------
702       |                                 |
703    child                             child
704
705    child - child                     [hole] - child
706
707    child - child - child             [hole] - [hole] - child
708
709   Case 1:                           Case 2:
710   Number of children = 6,           Number of children = 3,
711   File size = 7                     File size = 7
712
713Default Block Allocation
714------------------------
715
716At runtime, F2FS manages six active logs inside "Main" area: Hot/Warm/Cold node
717and Hot/Warm/Cold data.
718
719- Hot node	contains direct node blocks of directories.
720- Warm node	contains direct node blocks except hot node blocks.
721- Cold node	contains indirect node blocks
722- Hot data	contains dentry blocks
723- Warm data	contains data blocks except hot and cold data blocks
724- Cold data	contains multimedia data or migrated data blocks
725
726LFS has two schemes for free space management: threaded log and copy-and-compac-
727tion. The copy-and-compaction scheme which is known as cleaning, is well-suited
728for devices showing very good sequential write performance, since free segments
729are served all the time for writing new data. However, it suffers from cleaning
730overhead under high utilization. Contrarily, the threaded log scheme suffers
731from random writes, but no cleaning process is needed. F2FS adopts a hybrid
732scheme where the copy-and-compaction scheme is adopted by default, but the
733policy is dynamically changed to the threaded log scheme according to the file
734system status.
735
736In order to align F2FS with underlying flash-based storage, F2FS allocates a
737segment in a unit of section. F2FS expects that the section size would be the
738same as the unit size of garbage collection in FTL. Furthermore, with respect
739to the mapping granularity in FTL, F2FS allocates each section of the active
740logs from different zones as much as possible, since FTL can write the data in
741the active logs into one allocation unit according to its mapping granularity.
742
743Cleaning process
744----------------
745
746F2FS does cleaning both on demand and in the background. On-demand cleaning is
747triggered when there are not enough free segments to serve VFS calls. Background
748cleaner is operated by a kernel thread, and triggers the cleaning job when the
749system is idle.
750
751F2FS supports two victim selection policies: greedy and cost-benefit algorithms.
752In the greedy algorithm, F2FS selects a victim segment having the smallest number
753of valid blocks. In the cost-benefit algorithm, F2FS selects a victim segment
754according to the segment age and the number of valid blocks in order to address
755log block thrashing problem in the greedy algorithm. F2FS adopts the greedy
756algorithm for on-demand cleaner, while background cleaner adopts cost-benefit
757algorithm.
758
759In order to identify whether the data in the victim segment are valid or not,
760F2FS manages a bitmap. Each bit represents the validity of a block, and the
761bitmap is composed of a bit stream covering whole blocks in main area.
762
763Fallocate(2) Policy
764-------------------
765
766The default policy follows the below POSIX rule.
767
768Allocating disk space
769    The default operation (i.e., mode is zero) of fallocate() allocates
770    the disk space within the range specified by offset and len.  The
771    file size (as reported by stat(2)) will be changed if offset+len is
772    greater than the file size.  Any subregion within the range specified
773    by offset and len that did not contain data before the call will be
774    initialized to zero.  This default behavior closely resembles the
775    behavior of the posix_fallocate(3) library function, and is intended
776    as a method of optimally implementing that function.
777
778However, once F2FS receives ioctl(fd, F2FS_IOC_SET_PIN_FILE) in prior to
779fallocate(fd, DEFAULT_MODE), it allocates on-disk block addressess having
780zero or random data, which is useful to the below scenario where:
781
782 1. create(fd)
783 2. ioctl(fd, F2FS_IOC_SET_PIN_FILE)
784 3. fallocate(fd, 0, 0, size)
785 4. address = fibmap(fd, offset)
786 5. open(blkdev)
787 6. write(blkdev, address)
788
789Compression implementation
790--------------------------
791
792- New term named cluster is defined as basic unit of compression, file can
793  be divided into multiple clusters logically. One cluster includes 4 << n
794  (n >= 0) logical pages, compression size is also cluster size, each of
795  cluster can be compressed or not.
796
797- In cluster metadata layout, one special block address is used to indicate
798  a cluster is a compressed one or normal one; for compressed cluster, following
799  metadata maps cluster to [1, 4 << n - 1] physical blocks, in where f2fs
800  stores data including compress header and compressed data.
801
802- In order to eliminate write amplification during overwrite, F2FS only
803  support compression on write-once file, data can be compressed only when
804  all logical blocks in cluster contain valid data and compress ratio of
805  cluster data is lower than specified threshold.
806
807- To enable compression on regular inode, there are four ways:
808
809  * chattr +c file
810  * chattr +c dir; touch dir/file
811  * mount w/ -o compress_extension=ext; touch file.ext
812  * mount w/ -o compress_extension=*; touch any_file
813
814- To disable compression on regular inode, there are two ways:
815
816  * chattr -c file
817  * mount w/ -o nocompress_extension=ext; touch file.ext
818
819- Priority in between FS_COMPR_FL, FS_NOCOMP_FS, extensions:
820
821  * compress_extension=so; nocompress_extension=zip; chattr +c dir; touch
822    dir/foo.so; touch dir/bar.zip; touch dir/baz.txt; then foo.so and baz.txt
823    should be compresse, bar.zip should be non-compressed. chattr +c dir/bar.zip
824    can enable compress on bar.zip.
825  * compress_extension=so; nocompress_extension=zip; chattr -c dir; touch
826    dir/foo.so; touch dir/bar.zip; touch dir/baz.txt; then foo.so should be
827    compresse, bar.zip and baz.txt should be non-compressed.
828    chattr+c dir/bar.zip; chattr+c dir/baz.txt; can enable compress on bar.zip
829    and baz.txt.
830
831- At this point, compression feature doesn't expose compressed space to user
832  directly in order to guarantee potential data updates later to the space.
833  Instead, the main goal is to reduce data writes to flash disk as much as
834  possible, resulting in extending disk life time as well as relaxing IO
835  congestion. Alternatively, we've added ioctl(F2FS_IOC_RELEASE_COMPRESS_BLOCKS)
836  interface to reclaim compressed space and show it to user after setting a
837  special flag to the inode. Once the compressed space is released, the flag
838  will block writing data to the file until either the compressed space is
839  reserved via ioctl(F2FS_IOC_RESERVE_COMPRESS_BLOCKS) or the file size is
840  truncated to zero.
841
842Compress metadata layout::
843
844				[Dnode Structure]
845		+-----------------------------------------------+
846		| cluster 1 | cluster 2 | ......... | cluster N |
847		+-----------------------------------------------+
848		.           .                       .           .
849	  .                      .                .                      .
850    .         Compressed Cluster       .        .        Normal Cluster            .
851    +----------+---------+---------+---------+  +---------+---------+---------+---------+
852    |compr flag| block 1 | block 2 | block 3 |  | block 1 | block 2 | block 3 | block 4 |
853    +----------+---------+---------+---------+  +---------+---------+---------+---------+
854	       .                             .
855	    .                                           .
856	.                                                           .
857	+-------------+-------------+----------+----------------------------+
858	| data length | data chksum | reserved |      compressed data       |
859	+-------------+-------------+----------+----------------------------+
860
861Compression mode
862--------------------------
863
864f2fs supports "fs" and "user" compression modes with "compression_mode" mount option.
865With this option, f2fs provides a choice to select the way how to compress the
866compression enabled files (refer to "Compression implementation" section for how to
867enable compression on a regular inode).
868
8691) compress_mode=fs
870This is the default option. f2fs does automatic compression in the writeback of the
871compression enabled files.
872
8732) compress_mode=user
874This disables the automatic compression and gives the user discretion of choosing the
875target file and the timing. The user can do manual compression/decompression on the
876compression enabled files using F2FS_IOC_DECOMPRESS_FILE and F2FS_IOC_COMPRESS_FILE
877ioctls like the below.
878
879To decompress a file,
880
881fd = open(filename, O_WRONLY, 0);
882ret = ioctl(fd, F2FS_IOC_DECOMPRESS_FILE);
883
884To compress a file,
885
886fd = open(filename, O_WRONLY, 0);
887ret = ioctl(fd, F2FS_IOC_COMPRESS_FILE);
888
889NVMe Zoned Namespace devices
890----------------------------
891
892- ZNS defines a per-zone capacity which can be equal or less than the
893  zone-size. Zone-capacity is the number of usable blocks in the zone.
894  F2FS checks if zone-capacity is less than zone-size, if it is, then any
895  segment which starts after the zone-capacity is marked as not-free in
896  the free segment bitmap at initial mount time. These segments are marked
897  as permanently used so they are not allocated for writes and
898  consequently are not needed to be garbage collected. In case the
899  zone-capacity is not aligned to default segment size(2MB), then a segment
900  can start before the zone-capacity and span across zone-capacity boundary.
901  Such spanning segments are also considered as usable segments. All blocks
902  past the zone-capacity are considered unusable in these segments.
903