Filesystems and storage configuration
Single-page view · as markdown
A block layer cache (bcache)
Peios Kernel / Administration / System administration / Filesystems and storage configuration
Say you've got a big slow raid 6, and an ssd or three. Wouldn't it be nice if you could use them as cache... Hence bcache.
-
The bcache wiki can be found at:
-
This is the git repository of bcache-tools:
https://git.kernel.org/pub/scm/linux/kernel/git/colyli/bcache-tools.git/
-
The latest bcache kernel code can be found from mainline Linux kernel:
https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/
It's designed around the performance characteristics of SSDs - it only allocates in erase block sized buckets, and it uses a hybrid btree/log to track cached extents (which can be anywhere from a single sector to the bucket size). It's designed to avoid random writes at all costs.
Both writethrough and writeback caching are supported. Writeback defaults to off, but can be switched on and off arbitrarily at runtime. Bcache goes to great lengths to protect your data - it reliably handles unclean shutdown. (It doesn't even have a notion of a clean shutdown; bcache simply doesn't return writes as completed until they're on stable storage).
Writeback caching can use most of the cache for buffering writes - writing dirty data to the backing device is always done sequentially, scanning from the start to the end of the index.
Since random IO is what SSDs excel at, there generally won't be much benefit to caching large sequential IO. Bcache detects sequential IO and skips it; it also keeps a rolling average of the IO sizes per task, and as long as the average is above the cutoff it will skip all IO from that task - instead of caching the first 512k after every seek. Backups and large file copies should thus entirely bypass the cache.
In the event of a data IO error on the flash it will try to recover by reading from disk or invalidating cache entries. For unrecoverable errors (meta data or dirty data), caching is automatically disabled; if dirty data was present in the cache it first disables writeback caching and waits for all dirty data to be flushed.
Getting started: You'll need bcache util from the bcache-tools repository. Both the cache device and backing device must be formatted before use:
bcache make -B /dev/sdb
bcache make -C /dev/sdc
bcache make has the ability to format multiple devices at the same time - if you format your backing devices and cache device at the same time, you won't have to manually attach:
bcache make -B /dev/sda /dev/sdb -C /dev/sdc
If your bcache-tools is not updated to latest version and does not have the unified bcache utility, you may use the legacy make-bcache utility to format bcache device with same -B and -C parameters.
bcache-tools now ships udev rules, and bcache devices are known to the kernel immediately. Without udev, you can manually register devices like this:
echo /dev/sdb > /sys/fs/bcache/register
echo /dev/sdc > /sys/fs/bcache/register
Registering the backing device makes the bcache device show up in /dev; you can now format it and use it as normal. But the first time using a new bcache device, it'll be running in passthrough mode until you attach it to a cache. If you are thinking about using bcache later, it is recommended to setup all your slow devices as bcache backing devices without a cache, and you can choose to add a caching device later. See 'ATTACHING' section below.
The devices show up as:
/dev/bcache<N>
As well as (with udev):
/dev/bcache/by-uuid/<uuid>
/dev/bcache/by-label/<label>
To get started:
mkfs.ext4 /dev/bcache0
mount /dev/bcache0 /mnt
You can control bcache devices through sysfs at /sys/block/bcache<N>/bcache . You can also control them through /sys/fs//bcache/<cset-uuid>/ .
Cache devices are managed as sets; multiple caches per set isn't supported yet but will allow for mirroring of metadata and dirty data in the future. Your new cache set shows up as /sys/fs/bcache/<UUID>
Attaching #
After your cache device and backing device are registered, the backing device must be attached to your cache set to enable caching. Attaching a backing device to a cache set is done thusly, with the UUID of the cache set in /sys/fs/bcache:
echo <CSET-UUID> > /sys/block/bcache0/bcache/attach
This only has to be done once. The next time you reboot, just reregister all your bcache devices. If a backing device has data in a cache somewhere, the /dev/bcache<N> device won't be created until the cache shows up - particularly important if you have writeback caching turned on.
If you're booting up and your cache device is gone and never coming back, you can force run the backing device:
echo 1 > /sys/block/sdb/bcache/running
(You need to use /sys/block/sdb (or whatever your backing device is called), not /sys/block/bcache0, because bcache0 doesn't exist yet. If you're using a partition, the bcache directory would be at /sys/block/sdb/sdb2/bcache)
The backing device will still use that cache set if it shows up in the future, but all the cached data will be invalidated. If there was dirty data in the cache, don't expect the filesystem to be recoverable - you will have massive filesystem corruption, though ext4's fsck does work miracles.
Error Handling #
Bcache tries to transparently handle IO errors to/from the cache device without affecting normal operation; if it sees too many errors (the threshold is configurable, and defaults to 0) it shuts down the cache device and switches all the backing devices to passthrough mode.
For reads from the cache, if they error we just retry the read from the backing device.
For writethrough writes, if the write to the cache errors we just switch to invalidating the data at that lba in the cache (i.e. the same thing we do for a write that bypasses the cache)
For writeback writes, we currently pass that error back up to the filesystem/userspace. This could be improved - we could retry it as a write that skips the cache so we don't have to error the write.
When we detach, we first try to flush any dirty data (if we were running in writeback mode). It currently doesn't do anything intelligent if it fails to read some of the dirty data, though.
Howto/cookbook #
- A) Starting a bcache with a missing caching device
If registering the backing device doesn't help, it's already there, you just need to force it to run without the cache:
host:~# echo /dev/sdb1 > /sys/fs/bcache/register
[ 119.844831] bcache: register_bcache() error opening /dev/sdb1: device already registered
Next, you try to register your caching device if it's present. However if it's absent, or registration fails for some reason, you can still start your bcache without its cache, like so:
host:/sys/block/sdb/sdb1/bcache# echo 1 > running
Note that this may cause data loss if you were running in writeback mode.
-
B) Bcache does not find its cache:
host:/sys/block/md5/bcache# echo 0226553a-37cf-41d5-b3ce-8b1e944543a8 > attach [ 1933.455082] bcache: bch_cached_dev_attach() Couldn't find uuid for md5 in set [ 1933.478179] bcache: __cached_dev_store() Can't attach 0226553a-37cf-41d5-b3ce-8b1e944543a8 [ 1933.478179] : cache set not found
In this case, the caching device was simply not registered at boot or disappeared and came back, and needs to be (re-)registered:
host:/sys/block/md5/bcache# echo /dev/sdh2 > /sys/fs/bcache/register
- C) Corrupt bcache crashes the kernel at device registration time:
This should never happen. If it does happen, then you have found a bug! Please report it to the bcache development list: linux-bcache@vger.kernel.org
Be sure to provide as much information that you can including kernel dmesg output if available so that we may assist.
- D) Recovering data without bcache:
If bcache is not available in the kernel, a filesystem on the backing device is still available at an 8KiB offset. So either via a loopdev of the backing device created with --offset 8K, or any value defined by --data-offset when you originally formatted bcache with bcache make.
For example:
losetup -o 8192 /dev/loop0 /dev/your_bcache_backing_dev
This should present your unmodified backing device data in /dev/loop0
If your cache is in writethrough mode, then you can safely discard the cache device without losing data.
- E) Wiping a cache device
host:~# wipefs -a /dev/sdh2
16 bytes were erased at offset 0x1018 (bcache)
they were: c6 85 73 f6 4e 1a 45 ca 82 65 f5 7f 48 ba 6d 81
After you boot back with bcache enabled, you recreate the cache and attach it:
host:~# bcache make -C /dev/sdh2
UUID: 7be7e175-8f4c-4f99-94b2-9c904d227045
Set UUID: 5bc072a8-ab17-446d-9744-e247949913c1
version: 0
nbuckets: 106874
block_size: 1
bucket_size: 1024
nr_in_set: 1
nr_this_dev: 0
first_bucket: 1
[ 650.511912] bcache: run_cache_set() invalidating existing data
[ 650.549228] bcache: register_cache() registered cache device sdh2
start backing device with missing cache:
host:/sys/block/md5/bcache# echo 1 > running
attach new cache:
host:/sys/block/md5/bcache# echo 5bc072a8-ab17-446d-9744-e247949913c1 > attach
[ 865.276616] bcache: bch_cached_dev_attach() Caching md5 as bcache0 on set 5bc072a8-ab17-446d-9744-e247949913c1
-
F) Remove or replace a caching device:
host:/sys/block/sda/sda7/bcache# echo 1 > detach [ 695.872542] bcache: cached_dev_detach_finish() Caching disabled for sda7 host:~# wipefs -a /dev/nvme0n1p4 wipefs: error: /dev/nvme0n1p4: probing initialization failed: Device or resource busy Ooops, it's disabled, but not unregistered, so it's still protected
We need to go and unregister it:
host:/sys/fs/bcache/b7ba27a1-2398-4649-8ae3-0959f57ba128# ls -l cache0
lrwxrwxrwx 1 root root 0 Feb 25 18:33 cache0 -> ../../../devices/pci0000:00/0000:00:1d.0/0000:70:00.0/nvme/nvme0/nvme0n1/nvme0n1p4/bcache/
host:/sys/fs/bcache/b7ba27a1-2398-4649-8ae3-0959f57ba128# echo 1 > stop
kernel: [ 917.041908] bcache: cache_set_free() Cache set b7ba27a1-2398-4649-8ae3-0959f57ba128 unregistered
Now we can wipe it:
host:~# wipefs -a /dev/nvme0n1p4
/dev/nvme0n1p4: 16 bytes were erased at offset 0x00001018 (bcache): c6 85 73 f6 4e 1a 45 ca 82 65 f5 7f 48 ba 6d 81
- G) dm-crypt and bcache
First setup bcache unencrypted and then install dmcrypt on top of /dev/bcache<N> This will work faster than if you dmcrypt both the backing and caching devices and then install bcache on top. [benchmarks?]
- H) Stop/free a registered bcache to wipe and/or recreate it
Suppose that you need to free up all bcache references so that you can fdisk run and re-register a changed partition table, which won't work if there are any active backing or caching devices left on it:
-
Is it present in /dev/bcache* ? (there are times where it won't be)
If so, it's easy:
host:/sys/block/bcache0/bcache# echo 1 > stop -
But if your backing device is gone, this won't work:
host:/sys/block/bcache0# cd bcache bash: cd: bcache: No such file or directoryIn this case, you may have to unregister the dmcrypt block device that references this bcache to free it up:
host:~# dmsetup remove oldds1 bcache: bcache_device_free() bcache0 stopped bcache: cache_set_free() Cache set 5bc072a8-ab17-446d-9744-e247949913c1 unregisteredThis causes the backing bcache to be removed from /sys/fs/bcache and then it can be reused. This would be true of any block device stacking where bcache is a lower device.
-
In other cases, you can also look in /sys/fs/bcache/:
host:/sys/fs/bcache# ls -l */{cache?,bdev?} lrwxrwxrwx 1 root root 0 Mar 5 09:39 0226553a-37cf-41d5-b3ce-8b1e944543a8/bdev1 -> ../../../devices/virtual/block/dm-1/bcache/ lrwxrwxrwx 1 root root 0 Mar 5 09:39 0226553a-37cf-41d5-b3ce-8b1e944543a8/cache0 -> ../../../devices/virtual/block/dm-4/bcache/ lrwxrwxrwx 1 root root 0 Mar 5 09:39 5bc072a8-ab17-446d-9744-e247949913c1/cache0 -> ../../../devices/pci0000:00/0000:00:01.0/0000:01:00.0/ata10/host9/target9:0:0/9:0:0:0/block/sdl/sdl2/bcache/The device names will show which UUID is relevant, cd in that directory and stop the cache:
host:/sys/fs/bcache/5bc072a8-ab17-446d-9744-e247949913c1# echo 1 > stopThis will free up bcache references and let you reuse the partition for other purposes.
Troubleshooting performance #
Bcache has a bunch of config options and tunables. The defaults are intended to be reasonable for typical desktop and server workloads, but they're not what you want for getting the best possible numbers when benchmarking.
Backing device alignment
The default metadata size in bcache is 8k. If your backing device is RAID based, then be sure to align this by a multiple of your stride width using
bcache make --data-offset. If you intend to expand your disk array in the future, then multiply a series of primes by your raid stripe size to get the disk multiples that you would like.For example: If you have a 64k stripe size, then the following offset would provide alignment for many common RAID5 data spindle counts:
64k * 2*2*2*3*3*5*7 bytes = 161280kThat space is wasted, but for only 157.5MB you can grow your RAID 5 volume to the following data-spindle counts without re-aligning:
3,4,5,6,7,8,9,10,12,14,15,18,20,21 ...Bad write performance
If write performance is not what you expected, you probably wanted to be running in writeback mode, which isn't the default (not due to a lack of maturity, but simply because in writeback mode you'll lose data if something happens to your SSD):
# echo writeback > /sys/block/bcache0/bcache/cache_modeBad performance, or traffic not going to the SSD that you'd expect
By default, bcache doesn't cache everything. It tries to skip sequential IO - because you really want to be caching the random IO, and if you copy a 10 gigabyte file you probably don't want that pushing 10 gigabytes of randomly accessed data out of your cache.
But if you want to benchmark reads from cache, and you start out with fio writing an 8 gigabyte test file - so you want to disable that:
# echo 0 > /sys/block/bcache0/bcache/sequential_cutoffTo set it back to the default (4 mb), do:
# echo 4M > /sys/block/bcache0/bcache/sequential_cutoffTraffic's still going to the spindle/still getting cache misses
In the real world, SSDs don't always keep up with disks - particularly with slower SSDs, many disks being cached by one SSD, or mostly sequential IO. So you want to avoid being bottlenecked by the SSD and having it slow everything down.
To avoid that bcache tracks latency to the cache device, and gradually throttles traffic if the latency exceeds a threshold (it does this by cranking down the sequential bypass).
You can disable this if you need to by setting the thresholds to 0:
# echo 0 > /sys/fs/bcache/<cache set>/congested_read_threshold_us # echo 0 > /sys/fs/bcache/<cache set>/congested_write_threshold_usThe default is 2000 us (2 milliseconds) for reads, and 20000 for writes.
Still getting cache misses, of the same data
One last issue that sometimes trips people up is actually an old bug, due to the way cache coherency is handled for cache misses. If a btree node is full, a cache miss won't be able to insert a key for the new data and the data won't be written to the cache.
In practice this isn't an issue because as soon as a write comes along it'll cause the btree node to be split, and you need almost no write traffic for this to not show up enough to be noticeable (especially since bcache's btree nodes are huge and index large regions of the device). But when you're benchmarking, if you're trying to warm the cache by reading a bunch of data and there's no other traffic - that can be a problem.
Solution: warm the cache by doing writes, or use the testing branch (there's a fix for the issue there).
Sysfs - backing device #
Available at /sys/block/<bdev>/bcache, /sys/block/bcache*/bcache and (if attached) /sys/fs/bcache/<cset-uuid>/bdev*
-
attach
Echo the UUID of a cache set to this file to enable caching.
-
cache_mode
Can be one of either writethrough, writeback, writearound or none.
-
clear_stats
Writing to this file resets the running total stats (not the day/hour/5 minute decaying versions).
-
detach
Write to this file to detach from a cache set. If there is dirty data in the cache, it will be flushed first.
-
dirty_data
Amount of dirty data for this backing device in the cache. Continuously updated unlike the cache set's version, but may be slightly off.
-
label
Name of underlying device.
-
readahead
Size of readahead that should be performed. Defaults to 0. If set to e.g. 1M, it will round cache miss reads up to that size, but without overlapping existing cache entries.
-
running
1 if bcache is running (i.e. whether the /dev/bcache device exists, whether it's in passthrough mode or caching).
-
sequential_cutoff
A sequential IO will bypass the cache once it passes this threshold; the most recent 128 IOs are tracked so sequential IO can be detected even when it isn't all done at once.
-
sequential_merge
If non zero, bcache keeps a list of the last 128 requests submitted to compare against all new requests to determine which new requests are sequential continuations of previous requests for the purpose of determining sequential cutoff. This is necessary if the sequential cutoff value is greater than the maximum acceptable sequential size for any single request.
-
state
The backing device can be in one of four different states:
no cache: Has never been attached to a cache set.
clean: Part of a cache set, and there is no cached dirty data.
dirty: Part of a cache set, and there is cached dirty data.
inconsistent: The backing device was forcibly run by the user when there was dirty data cached but the cache set was unavailable; whatever data was on the backing device has likely been corrupted.
-
stop
Write to this file to shut down the bcache device and close the backing device.
-
writeback_delay
When dirty data is written to the cache and it previously did not contain any, waits some number of seconds before initiating writeback. Defaults to 30.
-
writeback_percent
If nonzero, bcache tries to keep around this percentage of the cache dirty by throttling background writeback and using a PD controller to smoothly adjust the rate.
-
writeback_rate
Rate in sectors per second - if writeback_percent is nonzero, background writeback is throttled to this rate. Continuously adjusted by bcache but may also be set by the user.
-
writeback_running
If off, writeback of dirty data will not take place at all. Dirty data will still be added to the cache until it is mostly full; only meant for benchmarking. Defaults to on.
Sysfs - backing device stats #
There are directories with these numbers for a running total, as well as versions that decay over the past day, hour and 5 minutes; they're also aggregated in the cache set directory as well.
-
bypassed
Amount of IO (both reads and writes) that has bypassed the cache
-
cache_hits, cache_misses, cache_hit_ratio
Hits and misses are counted per individual IO as bcache sees them; a partial hit is counted as a miss.
-
cache_bypass_hits, cache_bypass_misses
Hits and misses for IO that is intended to skip the cache are still counted, but broken out here.
-
cache_miss_collisions
Counts instances where data was going to be inserted into the cache from a cache miss, but raced with a write and data was already present (usually 0 since the synchronization for cache misses was rewritten)
Sysfs - cache set #
Available at /sys/fs/bcache/<cset-uuid>
-
average_key_size
Average data per key in the btree.
-
bdev<0..n>
Symlink to each of the attached backing devices.
-
block_size
Block size of the cache devices.
-
btree_cache_size
Amount of memory currently used by the btree cache
-
bucket_size
Size of buckets
-
cache<0..n>
Symlink to each of the cache devices comprising this cache set.
-
cache_available_percent
Percentage of cache device which doesn't contain dirty data, and could potentially be used for writeback. This doesn't mean this space isn't used for clean cached data; the unused statistic (in priority_stats) is typically much lower.
-
clear_stats
Clears the statistics associated with this cache
-
dirty_data
Amount of dirty data is in the cache (updated when garbage collection runs).
-
flash_vol_create
Echoing a size to this file (in human readable units, k/M/G) creates a thinly provisioned volume backed by the cache set.
-
io_error_halflife, io_error_limit
These determines how many errors we accept before disabling the cache. Each error is decayed by the half life (in # ios). If the decaying count reaches io_error_limit dirty data is written out and the cache is disabled.
-
journal_delay_ms
Journal writes will delay for up to this many milliseconds, unless a cache flush happens sooner. Defaults to 100.
-
root_usage_percent
Percentage of the root btree node in use. If this gets too high the node will split, increasing the tree depth.
-
stop
Write to this file to shut down the cache set - waits until all attached backing devices have been shut down.
-
tree_depth
Depth of the btree (A single node btree has depth 0).
-
unregister
Detaches all backing devices and closes the cache devices; if dirty data is present it will disable writeback caching and wait for it to be flushed.
Sysfs - cache set internal #
This directory also exposes timings for a number of internal operations, with separate files for average duration, average frequency, last occurrence and max duration: garbage collection, btree read, btree node sorts and btree splits.
-
active_journal_entries
Number of journal entries that are newer than the index.
-
btree_nodes
Total nodes in the btree.
-
btree_used_percent
Average fraction of btree in use.
-
bset_tree_stats
Statistics about the auxiliary search trees
-
btree_cache_max_chain
Longest chain in the btree node cache's hash table
-
cache_read_races
Counts instances where while data was being read from the cache, the bucket was reused and invalidated - i.e. where the pointer was stale after the read completed. When this occurs the data is reread from the backing device.
-
trigger_gc
Writing to this file forces garbage collection to run.
Sysfs - Cache device #
Available at /sys/block/<cdev>/bcache
-
block_size
Minimum granularity of writes - should match hardware sector size.
-
btree_written
Sum of all btree writes, in (kilo/mega/giga) bytes
-
bucket_size
Size of buckets
-
cache_replacement_policy
One of either lru, fifo or random.
-
freelist_percent
Size of the freelist as a percentage of nbuckets. Can be written to to increase the number of buckets kept on the freelist, which lets you artificially reduce the size of the cache at runtime. Mostly for testing purposes (i.e. testing how different size caches affect your hit rate).
-
io_errors
Number of errors that have occurred, decayed by io_error_halflife.
-
metadata_written
Sum of all non data writes (btree writes and all other metadata).
-
nbuckets
Total buckets in this cache
-
priority_stats
Statistics about how recently data in the cache has been accessed. This can reveal your working set size. Unused is the percentage of the cache that doesn't contain any data. Metadata is bcache's metadata overhead. Average is the average priority of cache buckets. Next is a list of quantiles with the priority threshold of each.
-
written
Sum of all data that has been written to the cache; comparison with btree_written gives the amount of write inflation in bcache.
The Android binderfs Filesystem
Peios Kernel / Administration / System administration / Filesystems and storage configuration
Peios: User namespaces and Unix ID mappings do not create native privileges or determine KACS descriptor identity. Mount authorization uses the native privilege/descriptor rules; the descriptor-only new-filesystem allowlist is
tmpfs,procandstratafs. See Peios kernel behaviour.
Android binderfs is a filesystem for the Android binder IPC mechanism. It allows to dynamically add and remove binder devices at runtime. Binder devices located in a new binderfs instance are independent of binder devices located in other binderfs instances. Mounting a new binderfs instance makes it possible to get a set of private binder devices.
Mounting binderfs #
Android binderfs can be mounted with:
mkdir /dev/binderfs
mount -t binder binder /dev/binderfs
at which point a new instance of binderfs will show up at /dev/binderfs. In a fresh instance of binderfs no binder devices will be present. There will only be a binder-control device which serves as the request handler for binderfs. Mounting another binderfs instance at a different location will create a new and separate instance from all other binderfs mounts. This is identical to the behavior of e.g. devpts and tmpfs. The Android binderfs filesystem can be mounted in user namespaces.
Options #
-
max
binderfs instances can be mounted with a limit on the number of binder devices that can be allocated. The
max=<count>mount option serves as a per-instance limit. Ifmax=<count>is set then only<count>number of binder devices can be allocated in this binderfs instance. -
stats
Using
stats=globalenables global binder statistics.stats=globalis only available for a binderfs instance mounted in the initial user namespace. An attempt to use the option to mount a binderfs instance in another user namespace will return a permission error.
Allocating binder Devices #
To allocate a new binder device in a binderfs instance a request needs to be sent through the binder-control device node. A request is sent in the form of an ioctl().
What a program needs to do is to open the binder-control device node and send a BINDER_CTL_ADD request to the kernel. Users of binderfs need to tell the kernel which name the new binder device should get. By default a name can only contain up to BINDERFS_MAX_NAME chars including the terminating zero byte.
Once the request is made via an ioctl() passing a struct binder_device with the name to the kernel it will allocate a new binder device and return the major and minor number of the new device in the struct (This is necessary because binderfs allocates a major device number dynamically.). After the ioctl() returns there will be a new binder device located under /dev/binderfs with the chosen name.
Deleting binder Devices #
Binderfs binder devices can be deleted via unlink(). This means that the rm() tool can be used to delete them. Note that the binder-control device cannot be deleted since this would make the binderfs instance unusable. The binder-control device will be deleted when the binderfs instance is unmounted and all references to it have been dropped.
Binder features #
Assuming an instance of binderfs has been mounted at /dev/binderfs, the features supported by the binder driver can be located under /dev/binderfs/features/. The presence of individual files can be tested to determine whether a particular feature is supported by the driver.
Example:
cat /dev/binderfs/features/oneway_spam_detection
1
ext4 General Information
Peios Kernel / Administration / System administration / Filesystems and storage configuration
Ext4 is an advanced level of the ext3 filesystem which incorporates scalability and reliability enhancements for supporting large filesystems (64 bit) in keeping with increasing disk capacities and state-of-the-art feature requirements.
Mailing list: linux-ext4@vger.kernel.org Web site: http://ext4.wiki.kernel.org
Quick usage instructions #
Note: More extensive information for getting started with ext4 can be found at the ext4 wiki site at the URL: http://ext4.wiki.kernel.org/index.php/Ext4_Howto
The latest version of e2fsprogs can be found at:
https://www.kernel.org/pub/linux/kernel/people/tytso/e2fsprogs/
or
http://sourceforge.net/project/showfiles.php?group_id=2406
or grab the latest git repository from:
Create a new filesystem using the ext4 filesystem type:
# mke2fs -t ext4 /dev/hda1
Or to configure an existing ext3 filesystem to support extents:
# tune2fs -O extents /dev/hda1
If the filesystem was created with 128 byte inodes, it can be converted to use 256 byte for greater efficiency via:
# tune2fs -I 256 /dev/hda1
Mounting:
# mount -t ext4 /dev/hda1 /wherever
When comparing performance with other filesystems, it's always important to try multiple workloads; very often a subtle change in a workload parameter can completely change the ranking of which filesystems do well compared to others. When comparing versus ext3, note that ext4 enables write barriers by default, while ext3 does not enable write barriers by default. So it is useful to use explicitly specify whether barriers are enabled or not when via the '-o barriers=[0|1]' mount option for both ext3 and ext4 filesystems for a fair comparison. When tuning ext3 for best benchmark numbers, it is often worthwhile to try changing the data journaling mode; '-o data=writeback' can be faster for some workloads. (Note however that running mounted with data=writeback can potentially leave stale data exposed in recently written files in case of an unclean shutdown, which could be a security exposure in some situations.) Configuring the filesystem with a large journal can also be helpful for metadata-intensive workloads.
Features #
Currently Available #
-
ability to use filesystems > 16TB (e2fsprogs support not available yet)
-
extent format reduces metadata overhead (RAM, IO for access, transactions)
-
extent format more robust in face of on-disk corruption due to magics,
-
internal redundancy in tree
-
improved file allocation (multi-block alloc)
-
lift 32000 subdirectory limit imposed by i_links_count[1]
-
nsec timestamps for mtime, atime, ctime, create time
-
inode version field on disk (NFSv4, Lustre)
-
reduced e2fsck time via uninit_bg feature
-
journal checksumming for robustness, performance
-
persistent file preallocation (e.g for streaming media, databases)
-
ability to pack bitmaps and inode tables into larger virtual groups via the flex_bg feature
-
large file support
-
inode allocation using large virtual block groups via flex_bg
-
delayed allocation
-
large block (up to pagesize) support
-
efficient new ordered mode in JBD2 and ext4 (avoid using buffer head to force the ordering)
-
Case-insensitive file name lookups
-
file-based encryption support (fscrypt)
-
file-based verity support (fsverity)
[1] Filesystems with a block size of 1k may see a limit imposed by the directory hash tree having a maximum depth of two.
case-insensitive file name lookups #
The case-insensitive file name lookup feature is supported on a per-directory basis, allowing the user to mix case-insensitive and case-sensitive directories in the same filesystem. It is enabled by flipping the +F inode attribute of an empty directory. The case-insensitive string match operation is only defined when we know how text in encoded in a byte sequence. For that reason, in order to enable case-insensitive directories, the filesystem must have the casefold feature, which stores the filesystem-wide encoding model used. By default, the charset adopted is the latest version of Unicode (12.1.0, by the time of this writing), encoded in the UTF-8 form. The comparison algorithm is implemented by normalizing the strings to the Canonical decomposition form, as defined by Unicode, followed by a byte per byte comparison.
The case-awareness is name-preserving on the disk, meaning that the file name provided by userspace is a byte-per-byte match to what is actually written in the disk. The Unicode normalization format used by the kernel is thus an internal representation, and not exposed to the userspace nor to the disk, with the important exception of disk hashes, used on large case-insensitive directories with DX feature. On DX directories, the hash must be calculated using the casefolded version of the filename, meaning that the normalization format used actually has an impact on where the directory entry is stored.
When we change from viewing filenames as opaque byte sequences to seeing them as encoded strings we need to address what happens when a program tries to create a file with an invalid name. The Unicode subsystem within the kernel leaves the decision of what to do in this case to the filesystem, which select its preferred behavior by enabling/disabling the strict mode. When Ext4 encounters one of those strings and the filesystem did not require strict mode, it falls back to considering the entire string as an opaque byte sequence, which still allows the user to operate on that file, but the case-insensitive lookups won't work.
Options #
When mounting an ext4 filesystem, the following option are accepted: (*) == default
ro
Mount filesystem read only. Note that ext4 will replay the journal (and thus write to the partition) even when mounted "read only". The mount options "ro,noload" can be used to prevent writes to the filesystem.
journal_checksum
Enable checksumming of the journal transactions. This will allow the recovery code in e2fsck and the kernel to detect corruption in the kernel. It is a compatible change and will be ignored by older kernels.
journal_async_commit
Commit block can be written to disk without waiting for descriptor blocks. If enabled older kernels cannot mount the device. This will enable 'journal_checksum' internally.
journal_path=path, journal_dev=devnum
When the external journal device's major/minor numbers have changed, these options allow the user to specify the new journal location. The journal device is identified through either its new major/minor numbers encoded in devnum, or via a path to the device.
norecovery, noload
Don't load the journal on mounting. Note that if the filesystem was not unmounted cleanly, skipping the journal replay will lead to the filesystem containing inconsistencies that can lead to any number of problems.
data=journal
All data are committed into the journal prior to being written into the main file system. Enabling this mode will disable delayed allocation and O_DIRECT support.
data=ordered (*)
All data are forced directly out to the main file system prior to its metadata being committed to the journal.
data=writeback
Data ordering is not preserved, data may be written into the main file system after its metadata has been committed to the journal.
commit=nrsec (*)
This setting limits the maximum age of the running transaction to 'nrsec' seconds. The default value is 5 seconds. This means that if you lose your power, you will lose as much as the latest 5 seconds of metadata changes (your filesystem will not be damaged though, thanks to the journaling). This default value (or any low value) will hurt performance, but it's good for data-safety. Setting it to 0 will have the same effect as leaving it at the default (5 seconds). Setting it to very large values will improve performance. Note that due to delayed allocation even older data can be lost on power failure since writeback of those data begins only after time set in /proc/sys/vm/dirty_expire_centisecs.
barrier=<0|1(*)>, barrier(*), nobarrier
This enables/disables the use of write barriers in the jbd code. barrier=0 disables, barrier=1 enables. This also requires an IO stack which can support barriers, and if jbd gets an error on a barrier write, it will disable again with a warning. Write barriers enforce proper on-disk ordering of journal commits, making volatile disk write caches safe to use, at some performance penalty. If your disks are battery-backed in one way or another, disabling barriers may safely improve performance. The mount options "barrier" and "nobarrier" can also be used to enable or disable barriers, for consistency with other ext4 mount options.
inode_readahead_blks=n
This tuning parameter controls the maximum number of inode table blocks that ext4's inode table readahead algorithm will pre-read into the buffer cache. The default value is 32 blocks.
bsddf (*)
Make 'df' act like BSD.
minixdf
Make 'df' act like Minix.
debug
Extra debugging information is sent to syslog.
abort
Simulate the effects of calling ext4_abort() for debugging purposes. This is normally used while remounting a filesystem which is already mounted.
errors=remount-ro
Remount the filesystem read-only on an error.
errors=continue
Keep going on a filesystem error.
errors=panic
Panic and halt the machine if an error occurs. (These mount options override the errors behavior specified in the superblock, which can be configured using tune2fs)
data_err=ignore(*)
Just print an error message if an error occurs in a file data buffer.
data_err=abort
Abort the journal if an error occurs in a file data buffer.
grpid | bsdgroups
New objects have the group ID of their parent.
nogrpid (*) | sysvgroups
New objects have the group ID of their creator.
resgid=n
The group ID which may use the reserved blocks.
resuid=n
The user ID which may use the reserved blocks.
sb=
Use alternate superblock at this location.
quota, noquota, grpquota, usrquota
These options are ignored by the filesystem. They are used only by quota tools to recognize volumes where quota should be turned on. See documentation in the quota-tools package for more details (http://sourceforge.net/projects/linuxquota).
jqfmt=<quota type>, usrjquota=<file>, grpjquota=<file>
These options tell filesystem details about quota so that quota information can be properly updated during journal replay. They replace the above quota options. See documentation in the quota-tools package for more details (http://sourceforge.net/projects/linuxquota).
stripe=n
Number of filesystem blocks that mballoc will try to use for allocation size and alignment. For RAID5/6 systems this should be the number of data disks * RAID chunk size in file system blocks.
delalloc (*)
Defer block allocation until just before ext4 writes out the block(s) in question. This allows ext4 to better allocation decisions more efficiently.
nodelalloc
Disable delayed allocation. Blocks are allocated when the data is copied from userspace to the page cache, either via the write(2) system call or when an mmap'ed page which was previously unallocated is written for the first time.
max_batch_time=usec
Maximum amount of time ext4 should wait for additional filesystem operations to be batch together with a synchronous write operation. Since a synchronous write operation is going to force a commit and then a wait for the I/O complete, it doesn't cost much, and can be a huge throughput win, we wait for a small amount of time to see if any other transactions can piggyback on the synchronous write. The algorithm used is designed to automatically tune for the speed of the disk, by measuring the amount of time (on average) that it takes to finish committing a transaction. Call this time the "commit time". If the time that the transaction has been running is less than the commit time, ext4 will try sleeping for the commit time to see if other operations will join the transaction. The commit time is capped by the max_batch_time, which defaults to 15000us (15ms). This optimization can be turned off entirely by setting max_batch_time to 0.
min_batch_time=usec
This parameter sets the commit time (as described above) to be at least min_batch_time. It defaults to zero microseconds. Increasing this parameter may improve the throughput of multi-threaded, synchronous workloads on very fast disks, at the cost of increasing latency.
journal_ioprio=prio
The I/O priority (from 0 to 7, where 0 is the highest priority) which should be used for I/O operations submitted by kjournald2 during a commit operation. This defaults to 3, which is a slightly higher priority than the default I/O priority.
auto_da_alloc(*), noauto_da_alloc
Many broken applications don't use fsync() when replacing existing files via patterns such as fd = open("foo.new")/write(fd,..)/close(fd)/ rename("foo.new", "foo"), or worse yet, fd = open("foo", O_TRUNC)/write(fd,..)/close(fd). If auto_da_alloc is enabled, ext4 will detect the replace-via-rename and replace-via-truncate patterns and force that any delayed allocation blocks are allocated such that at the next journal commit, in the default data=ordered mode, the data blocks of the new file are forced to disk before the rename() operation is committed. This provides roughly the same level of guarantees as ext3, and avoids the "zero-length" problem that can happen when a system crashes before the delayed allocation blocks are forced to disk.
noinit_itable
Do not initialize any uninitialized inode table blocks in the background. This feature may be used by installation CD's so that the install process can complete as quickly as possible; the inode table initialization process would then be deferred until the next time the file system is unmounted.
init_itable=n
The lazy itable init code will wait n times the number of milliseconds it took to zero out the previous block group's inode table. This minimizes the impact on the system performance while file system's inode table is being initialized.
discard, nodiscard(*)
Controls whether ext4 should issue discard/TRIM commands to the underlying block device when blocks are freed. This is useful for SSD devices and sparse/thinly-provisioned LUNs, but it is off by default until sufficient testing has been done.
nouid32
Disables 32-bit UIDs and GIDs. This is for interoperability with older kernels which only store and expect 16-bit values.
block_validity(*), noblock_validity
These options enable or disable the in-kernel facility for tracking filesystem metadata blocks within internal data structures. This allows multi- block allocator and other routines to notice bugs or corrupted allocation bitmaps which cause blocks to be allocated which overlap with filesystem metadata blocks.
dioread_lock, dioread_nolock
Controls whether or not ext4 should use the DIO read locking. If the dioread_nolock option is specified ext4 will allocate uninitialized extent before buffer write and convert the extent to initialized after IO completes. This approach allows ext4 code to avoid using inode mutex, which improves scalability on high speed storages. However this does not work with data journaling and dioread_nolock option will be ignored with kernel warning. Note that dioread_nolock code path is only used for extent-based files. Because of the restrictions this options comprises it is off by default (e.g. dioread_lock).
max_dir_size_kb=n
This limits the size of directories so that any attempt to expand them beyond the specified limit in kilobytes will cause an ENOSPC error. This is useful in memory constrained environments, where a very large directory can cause severe performance problems or even provoke the Out Of Memory killer. (For example, if there is only 512mb memory available, a 176mb directory may seriously cramp the system's style.)
i_version
Enable 64-bit inode version support. This option is off by default.
dax
Use direct access (no page cache). See Documentation/filesystems/dax.rst. Note that this option is incompatible with data=journal.
inlinecrypt
When possible, encrypt/decrypt the contents of encrypted files using the blk-crypto framework rather than filesystem-layer encryption. This allows the use of inline encryption hardware. The on-disk format is unaffected. For more details, see Documentation/block/inline-encryption.rst.
Data Mode #
There are 3 different data modes:
-
writeback mode
In data=writeback mode, ext4 does not journal data at all. This mode provides a similar level of journaling as that of XFS and JFS in its default mode - metadata journaling. A crash+recovery can cause incorrect data to appear in files which were written shortly before the crash. This mode will typically provide the best ext4 performance.
-
ordered mode
In data=ordered mode, ext4 only officially journals metadata, but it logically groups metadata information related to data changes with the data blocks into a single unit called a transaction. When it's time to write the new metadata out to disk, the associated data blocks are written first. In general, this mode performs slightly slower than writeback but significantly faster than journal mode.
-
journal mode
data=journal mode provides full data and metadata journaling. All new data is written to the journal first, and then to its final location. In the event of a crash, the journal can be replayed, bringing both data and metadata into a consistent state. This mode is the slowest except when data needs to be read from and written to disk at the same time where it outperforms all others modes. Enabling this mode will disable delayed allocation and O_DIRECT support.
/proc entries #
Information about mounted ext4 file systems can be found in /proc/fs/ext4. Each mounted filesystem will have a directory in /proc/fs/ext4 based on its device name (i.e., /proc/fs/ext4/hdc or /proc/fs/ext4/dm-0). The files in each per-device directory are shown in table below.
Files in /proc/fs/ext4/<devname>
mb_groups
details of multiblock allocator buddy cache of free blocks
/sys entries #
Information about mounted ext4 file systems can be found in /sys/fs/ext4. Each mounted filesystem will have a directory in /sys/fs/ext4 based on its device name (i.e., /sys/fs/ext4/hdc or /sys/fs/ext4/dm-0). The files in each per-device directory are shown in table below.
Files in /sys/fs/ext4/<devname>:
(see also Documentation/ABI/testing/sysfs-fs-ext4)
delayed_allocation_blocks
This file is read-only and shows the number of blocks that are dirty in the page cache, but which do not have their location in the filesystem allocated yet.
inode_goal
Tuning parameter which (if non-zero) controls the goal inode used by the inode allocator in preference to all other allocation heuristics. This is intended for debugging use only, and should be 0 on production systems.
inode_readahead_blks
Tuning parameter which controls the maximum number of inode table blocks that ext4's inode table readahead algorithm will pre-read into the buffer cache.
lifetime_write_kbytes
This file is read-only and shows the number of kilobytes of data that have been written to this filesystem since it was created.
max_writeback_mb_bump
The maximum number of megabytes the writeback code will try to write out before move on to another inode.
mb_group_prealloc
The multiblock allocator will round up allocation requests to a multiple of this tuning parameter if the stripe size is not set in the ext4 superblock
mb_max_to_scan
The maximum number of extents the multiblock allocator will search to find the best extent.
mb_min_to_scan
The minimum number of extents the multiblock allocator will search to find the best extent.
mb_order2_req
Tuning parameter which controls the minimum size for requests (as a power of 2) where the buddy cache is used.
mb_stats
Controls whether the multiblock allocator should collect statistics, which are shown during the unmount. 1 means to collect statistics, 0 means not to collect statistics.
mb_stream_req
Files which have fewer blocks than this tunable parameter will have their blocks allocated out of a block group specific preallocation pool, so that small files are packed closely together. Each large file will have its blocks allocated out of its own unique preallocation pool.
session_write_kbytes
This file is read-only and shows the number of kilobytes of data that have been written to this filesystem since it was mounted.
reserved_clusters
This is RW file and contains number of reserved clusters in the file system which will be used in the specific situations to avoid costly zeroout, unexpected ENOSPC, or possible data loss. The default is 2% or 4096 clusters, whichever is smaller and this can be changed however it can never exceed number of clusters in the file system. If there is not enough space for the reserved space when mounting the file mount will _not_ fail.
Ioctls #
Ext4 implements various ioctls which can be used by applications to access ext4-specific functionality. An incomplete list of these ioctls is shown in the table below. This list includes truly ext4-specific ioctls (EXT4_IOC_*) as well as ioctls that may have been ext4-specific originally but are now supported by some other filesystem(s) too (FS_IOC_*).
Table of Ext4 ioctls
FS_IOC_GETFLAGS
Get additional attributes associated with inode. The ioctl argument is an integer bitfield, with bit values described in ext4.h.
FS_IOC_SETFLAGS
Set additional attributes associated with inode. The ioctl argument is an integer bitfield, with bit values described in ext4.h.
EXT4_IOC_GETVERSION, EXT4_IOC_GETVERSION_OLD
Get the inode i_generation number stored for each inode. The i_generation number is normally changed only when new inode is created and it is particularly useful for network filesystems. The '_OLD' version of this ioctl is an alias for FS_IOC_GETVERSION.
EXT4_IOC_SETVERSION, EXT4_IOC_SETVERSION_OLD
Set the inode i_generation number stored for each inode. The '_OLD' version of this ioctl is an alias for FS_IOC_SETVERSION.
EXT4_IOC_GROUP_EXTEND
This ioctl has the same purpose as the resize mount option. It allows to resize filesystem to the end of the last existing block group, further resize has to be done with resize2fs, either online, or offline. The argument points to the unsigned logn number representing the filesystem new block count.
EXT4_IOC_MOVE_EXT
Move the block extents from orig_fd (the one this ioctl is pointing to) to the donor_fd (the one specified in move_extent structure passed as an argument to this ioctl). Then, exchange inode metadata between orig_fd and donor_fd. This is especially useful for online defragmentation, because the allocator has the opportunity to allocate moved blocks better, ideally into one contiguous extent.
EXT4_IOC_GROUP_ADD
Add a new group descriptor to an existing or new group descriptor block. The new group descriptor is described by ext4_new_group_input structure, which is passed as an argument to this ioctl. This is especially useful in conjunction with EXT4_IOC_GROUP_EXTEND, which allows online resize of the filesystem to the end of the last existing block group. Those two ioctls combined is used in userspace online resize tool (e.g. resize2fs).
EXT4_IOC_MIGRATE
This ioctl operates on the filesystem itself. It converts (migrates) ext3 indirect block mapped inode to ext4 extent mapped inode by walking through indirect block mapping of the original inode and converting contiguous block ranges into ext4 extents of the temporary inode. Then, inodes are swapped. This ioctl might help, when migrating from ext3 to ext4 filesystem, however suggestion is to create fresh ext4 filesystem and copy data from the backup. Note, that filesystem has to support extents for this ioctl to work.
EXT4_IOC_ALLOC_DA_BLKS
Force all of the delay allocated blocks to be allocated to preserve application-expected ext3 behaviour. Note that this will also start triggering a write of the data blocks, but this behaviour may change in the future as it is not necessary and has been done this way only for sake of simplicity.
EXT4_IOC_RESIZE_FS
Resize the filesystem to a new size. The number of blocks of resized filesystem is passed in via 64 bit integer argument. The kernel allocates bitmaps and inode table, the userspace tool thus just passes the new number of blocks.
EXT4_IOC_SWAP_BOOT
Swap i_blocks and associated attributes (like i_blocks, i_size, i_flags, ...) from the specified inode with inode EXT4_BOOT_LOADER_INO (#5). This is typically used to store a boot loader in a secure part of the filesystem, where it can't be changed by a normal user by accident. The data blocks of the previous boot loader will be associated with the given inode.
References #
-
kernel source: <file:fs/ext4/>
programs: http://e2fsprogs.sourceforge.net/
File system Monitoring with fanotify
Peios Kernel / Administration / System administration / Filesystems and storage configuration
File system Error Reporting #
Fanotify supports the FAN_FS_ERROR event type for file system-wide error reporting. It is meant to be used by file system health monitoring daemons, which listen for these events and take actions (notify sysadmin, start recovery) when a file system problem is detected.
By design, a FAN_FS_ERROR notification exposes sufficient information for a monitoring tool to know a problem in the file system has happened. It doesn't necessarily provide a user space application with semantics to verify an IO operation was successfully executed. That is out of scope for this feature. Instead, it is only meant as a framework for early file system problem detection and reporting recovery tools.
When a file system operation fails, it is common for dozens of kernel errors to cascade after the initial failure, hiding the original failure log, which is usually the most useful debug data to troubleshoot the problem. For this reason, FAN_FS_ERROR tries to report only the first error that occurred for a file system since the last notification, and it simply counts additional errors. This ensures that the most important pieces of information are never lost.
FAN_FS_ERROR requires the fanotify group to be setup with the FAN_REPORT_FID flag.
At the time of this writing, the only file system that emits FAN_FS_ERROR notifications is Ext4.
A FAN_FS_ERROR Notification has the following format:
::
[ Notification Metadata (Mandatory) ]
[ Generic Error Record (Mandatory) ]
[ FID record (Mandatory) ]
The order of records is not guaranteed, and new records might be added in the future. Therefore, applications must not rely on the order and must be prepared to skip over unknown records. Please refer to samples/fanotify/fs-monitor.c for an example parser.
Generic error record #
The generic error record provides enough information for a file system agnostic tool to learn about a problem in the file system, without providing any additional details about the problem. This record is identified by struct fanotify_event_info_header.info_type being set to FAN_EVENT_INFO_TYPE_ERROR.
struct fanotify_event_info_error { struct fanotify_event_info_header hdr; __s32 error; __u32 error_count; };
The error field identifies the type of error using errno values. error_count tracks the number of errors that occurred and were suppressed to preserve the original error information, since the last notification.
FID record #
The FID record can be used to uniquely identify the inode that triggered the error through the combination of fsid and file handle. A file system specific application can use that information to attempt a recovery procedure. Errors that are not related to an inode are reported with an empty file handle of type FILEID_INVALID.
IBM's Journaled File System (JFS) for Linux
Peios Kernel / Administration / System administration / Filesystems and storage configuration
JFS Homepage: http://jfs.sourceforge.net/
The following mount options are supported:
(*) == default
-
iocharset=name
Character set to use for converting from Unicode to ASCII. The default is to do no conversion. Use iocharset=utf8 for UTF-8 translations. This requires CONFIG_NLS_UTF8 to be set in the kernel .config file. iocharset=none specifies the default behavior explicitly.
-
resize=value
Resize the volume to <value> blocks. JFS only supports growing a volume, not shrinking it. This option is only valid during a remount, when the volume is mounted read-write. The resize keyword with no value will grow the volume to the full size of the partition.
-
nointegrity
Do not write to the journal. The primary use of this option is to allow for higher performance when restoring a volume from backup media. The integrity of the volume is not guaranteed if the system abnormally abends.
-
integrity(*)
Commit metadata changes to the journal. Use this option to remount a volume where the nointegrity option was previously specified in order to restore normal behavior.
-
errors=continue
Keep going on a filesystem error.
-
errors=remount-ro(*)
Remount the filesystem read-only on an error.
-
errors=panic
Panic and halt the machine if an error occurs.
-
uid=value
Override on-disk uid with specified value
-
gid=value
Override on-disk gid with specified value
-
umask=value
Override on-disk umask with specified octal value. For directories, the execute bit will be set if the corresponding read bit is set.
-
discard=minlen, discard/nodiscard(*)
This enables/disables the use of discard/TRIM commands. The discard/TRIM commands are sent to the underlying block device when blocks are freed. This is useful for SSD devices and sparse/thinly-provisioned LUNs. The FITRIM ioctl command is also available together with the nodiscard option. The value of minlen specifies the minimum blockcount, when a TRIM command to the block device is considered useful. When no value is given to the discard option, it defaults to 64 blocks, which means 256KiB in JFS. The minlen value of discard overrides the minlen value given on an FITRIM ioctl().
The JFS mailing list can be subscribed to by using the link labeled "Mail list Subscribe" at our web page http://jfs.sourceforge.net/
LDM - Logical Disk Manager (Dynamic Disks)
Peios Kernel / Administration / System administration / Filesystems and storage configuration
Author: Originally Written by FlatCap - Richard Russon <ldm@flatcap.org>.
Last Updated: Anton Altaparmakov on 30 March 2007 for Windows Vista.
Overview #
Windows 2000, XP, and Vista use a new partitioning scheme. It is a complete replacement for the MSDOS style partitions. It stores its information in a 1MiB journalled database at the end of the physical disk. The size of partitions is limited only by disk space. The maximum number of partitions is nearly 2000.
Any partitions created under the LDM are called "Dynamic Disks". There are no longer any primary or extended partitions. Normal MSDOS style partitions are now known as Basic Disks.
If you wish to use Spanned, Striped, Mirrored or RAID 5 Volumes, you must use Dynamic Disks. The journalling allows Windows to make changes to these partitions and filesystems without the need to reboot.
Once the LDM driver has divided up the disk, you can use the MD driver to assemble any multi-partition volumes, e.g. Stripes, RAID5.
To prevent legacy applications from repartitioning the disk, the LDM creates a dummy MSDOS partition containing one disk-sized partition. This is what is supported with the Linux LDM driver.
A newer approach that has been implemented with Vista is to put LDM on top of a GPT label disk. This is not supported by the Linux LDM driver yet.
Example #
Below we have a 50MiB disk, divided into seven partitions.
|
Device |
Offset Bytes |
Sectors |
MiB |
Size Bytes |
Sectors |
MiB |
||
|---|---|---|---|---|---|---|---|---|
|
hda |
0 |
0 |
0 |
52428800 |
102400 |
50 |
||
|
hda1 |
51380224 |
100352 |
49 |
1048576 |
2048 |
1 |
||
|
hda2 |
16384 |
32 |
0 |
6979584 |
13632 |
6 |
||
|
hda3 |
6995968 |
13664 |
6 |
10485760 |
20480 |
10 |
||
|
hda4 |
17481728 |
34144 |
16 |
4194304 |
8192 |
4 |
||
|
hda5 |
21676032 |
42336 |
20 |
5242880 |
10240 |
5 |
||
|
hda6 |
26918912 |
52576 |
25 |
10485760 |
20480 |
10 |
||
|
hda7 |
37404672 |
73056 |
35 |
13959168 |
27264 |
13 |
The LDM Database may not store the partitions in the order that they appear on disk, but the driver will sort them.
When Linux boots, you will see something like:
hda: 102400 sectors w/32KiB Cache, CHS=50/64/32
hda: [LDM] hda1 hda2 hda3 hda4 hda5 hda6 hda7
Compiling LDM Support #
To enable LDM, choose the following two options:
"Advanced partition selection" CONFIG_PARTITION_ADVANCED
"Windows Logical Disk Manager (Dynamic Disk) support" CONFIG_LDM_PARTITION
If you believe the driver isn't working as it should, you can enable the extra debugging code. This will produce a LOT of output. The option is:
- "Windows LDM extra logging" CONFIG_LDM_DEBUG
N.B. The partition code cannot be compiled as a module.
As with all the partition code, if the driver doesn't see signs of its type of partition, it will pass control to another driver, so there is no harm in enabling it.
If you have Dynamic Disks but don't enable the driver, then all you will see is a dummy MSDOS partition filling the whole disk. You won't be able to mount any of the volumes on the disk.
Booting #
If you enable LDM support, then lilo is capable of booting from any of the discovered partitions. However, grub does not understand the LDM partitioning and cannot boot from a Dynamic Disk.
More Documentation #
There is an Overview of the LDM together with complete Technical Documentation. It is available for download.
If you have any LDM questions that aren't answered in the documentation, email me.
-
Cheers,
FlatCap - Richard Russon ldm@flatcap.org
RAID arrays
Peios Kernel / Administration / System administration / Filesystems and storage configuration
Boot time assembly of RAID arrays #
-
Tools that manage md devices can be found at
You can boot with your md device with the following kernel command lines:
for old raid arrays without persistent superblocks:
md=<md device no.>,<raid level>,<chunk size factor>,<fault level>,dev0,dev1,...,devn
for raid arrays with persistent superblocks:
md=<md device no.>,dev0,dev1,...,devn
or, to assemble a partitionable array:
md=d<md device no.>,dev0,dev1,...,devn
md device no. #
The number of the md device
|
|
device |
|---|---|
|
0 |
md0 |
|
1 |
md1 |
|
2 |
md2 |
|
3 |
md3 |
|
4 |
md4 |
raid level #
level of the RAID array
|
|
level |
|---|---|
|
-1 |
linear mode |
|
0 |
striped mode |
other modes are only supported with persistent super blocks
chunk size factor #
(raid-0 and raid-1 only)
Set the chunk size as 4k << n.
fault level #
Totally ignored
dev0 to devn #
e.g. /dev/hda1, /dev/hdc1, /dev/sda1, /dev/sdb1
A possible loadlin line (Harald Hoyer <HarryH@Royal.Net>) looks like this:
e:\loadlin\loadlin e:\zimage root=/dev/md0 md=0,0,4,0,/dev/hdb2,/dev/hdc3 ro
Boot time autodetection of RAID arrays #
When md is compiled into the kernel (not as module), partitions of type 0xfd are scanned and automatically assembled into RAID arrays. This autodetection may be suppressed with the kernel parameter raid=noautodetect. As of kernel 2.6.9, only drives with a type 0 superblock can be autodetected and run at boot time.
The kernel parameter raid=partitionable (or raid=part) means that all auto-detected arrays are assembled as partitionable.
Boot time assembly of degraded/dirty arrays #
If a raid5 or raid6 array is both dirty and degraded, it could have undetectable data corruption. This is because the fact that it is dirty means that the parity cannot be trusted, and the fact that it is degraded means that some datablocks are missing and cannot reliably be reconstructed (due to no parity).
For this reason, md will normally refuse to start such an array. This requires the sysadmin to take action to explicitly start the array despite possible corruption. This is normally done with:
mdadm --assemble --force ....
This option is not really available if the array has the root filesystem on it. In order to support this booting from such an array, md supports a module parameter start_dirty_degraded which, when set to 1, bypassed the checks and will allows dirty degraded arrays to be started.
So, to boot with a root filesystem of a dirty degraded raid 5 or 6, use:
md-mod.start_dirty_degraded=1
Superblock formats #
The md driver can support a variety of different superblock formats. Currently, it supports superblock formats 0.90.0 and the md-1 format introduced in the 2.5 development series.
The kernel will autodetect which format superblock is being used.
Superblock format 0 is treated differently to others for legacy reasons - it is the original superblock format.
General Rules - apply for all superblock formats #
An array is created by writing appropriate superblocks to all devices.
It is assembled by associating each of these devices with an particular md virtual device. Once it is completely assembled, it can be accessed.
An array should be created by a user-space tool. This will write superblocks to all devices. It will usually mark the array as unclean, or with some devices missing so that the kernel md driver can create appropriate redundancy (copying in raid 1, parity calculation in raid 4/5).
When an array is assembled, it is first initialized with the SET_ARRAY_INFO ioctl. This contains, in particular, a major and minor version number. The major version number selects which superblock format is to be used. The minor number might be used to tune handling of the format, such as suggesting where on each device to look for the superblock.
Then each device is added using the ADD_NEW_DISK ioctl. This provides, in particular, a major and minor number identifying the device to add.
The array is started with the RUN_ARRAY ioctl.
Once started, new devices can be added. They should have an appropriate superblock written to them, and then be passed in with ADD_NEW_DISK.
Devices that have failed or are not yet active can be detached from an array using HOT_REMOVE_DISK.
Specific Rules that apply to format-0 super block arrays, and arrays with no superblock (non-persistent) #
An array can be created by describing the array (level, chunksize etc) in a SET_ARRAY_INFO ioctl. This must have major_version==0 and raid_disks != 0.
Then uninitialized devices can be added with ADD_NEW_DISK. The structure passed to ADD_NEW_DISK must specify the state of the device and its role in the array.
Once started with RUN_ARRAY, uninitialized spares can be added with HOT_ADD_DISK.
MD devices in sysfs #
md devices appear in sysfs (/sys) as regular block devices, e.g.:
/sys/block/md0
Each md device will contain a subdirectory called md which contains further md-specific information about the device.
All md devices contain:
level
a text file indicating the
raid level. e.g. raid0, raid1, raid5, linear, multipath, faulty. If no raid level has been set yet (array is still being assembled), the value will reflect whatever has been written to it, which may be a name like the above, or may be a number such as0,5, etc.raid_disks
a text file with a simple number indicating the number of devices in a fully functional array. If this is not yet known, the file will be empty. If an array is being resized this will contain the new number of devices. Some raid levels allow this value to be set while the array is active. This will reconfigure the array. Otherwise it can only be set while assembling an array. A change to this attribute will not be permitted if it would reduce the size of the array. To reduce the number of drives in an e.g. raid5, the array size must first be reduced by setting the
array_sizeattribute.chunk_size
This is the size in bytes for
chunksand is only relevant to raid levels that involve striping (0,4,5,6,10). The address space of the array is conceptually divided into chunks and consecutive chunks are striped onto neighbouring devices. The size should be at least PAGE_SIZE (4k) and should be a power of 2. This can only be set while assembling an arraylayout
The
layoutfor the array for the particular level. This is simply a number that is interpreted differently by different levels. It can be written while assembling an array.array_size
This can be used to artificially constrain the available space in the array to be less than is actually available on the combined devices. Writing a number (in Kilobytes) which is less than the available size will set the size. Any reconfiguration of the array (e.g. adding devices) will not cause the size to change. Writing the word
defaultwill cause the effective size of the array to be whatever size is actually available based onlevel,chunk_sizeandcomponent_size.This can be used to reduce the size of the array before reducing the number of devices in a raid4/5/6, or to support external metadata formats which mandate such clipping.
logical_block_size
Configure the array's logical block size in bytes. This attribute is only supported for 1.x meta. Write the value before starting array. The final array LBS uses the maximum between this configuration and LBS of all combined devices. Note that LBS cannot exceed PAGE_SIZE before RAID supports folio. WARNING: Arrays created on new kernel cannot be assembled at old kernel due to padding check, Set module parameter 'check_new_feature' to false to bypass, but data loss may occur.
reshape_position
This is either
noneor a sector number within the devices of the array wherereshapeis up to. If this is set, the three attributes mentioned above (raid_disks, chunk_size, layout) can potentially have 2 values, an old and a new value. If these values differ, reading the attribute returns:new (old)and writing will effect the
newvalue, leaving theoldunchanged.component_size
For arrays with data redundancy (i.e. not raid0, linear, faulty, multipath), all components must be the same size - or at least there must a size that they all provide space for. This is a key part or the geometry of the array. It is measured in sectors and can be read from here. Writing to this value may resize the array if the personality supports it (raid1, raid5, raid6), and if the component drives are large enough.
metadata_version
This indicates the format that is being used to record metadata about the array. It can be 0.90 (traditional format), 1.0, 1.1, 1.2 (newer format in varying locations) or
noneindicating that the kernel isn't managing metadata at all. Alternately it can beexternal:followed by a string which is set by user-space. This indicates that metadata is managed by a user-space program. Any device failure or other event that requires a metadata update will cause array activity to be suspended until the event is acknowledged.resync_start
The point at which resync should start. If no resync is needed, this will be a very large number (or
nonesince 2.6.30-rc1). At array creation it will default to 0, though starting the array ascleanwill set it much larger.new_dev
This file can be written but not read. The value written should be a block device number as major:minor. e.g. 8:0 This will cause that device to be attached to the array, if it is available. It will then appear at md/dev-XXX (depending on the name of the device) and further configuration is then possible.
safe_mode_delay
When an md array has seen no write requests for a certain period of time, it will be marked as
clean. When another write request arrives, the array is marked asdirtybefore the write commences. This is known assafe_mode. Thecertain periodis controlled by this file which stores the period as a number of seconds. The default is 200msec (0.200). Writing a value of 0 disables safemode.array_state
This file contains a single word which describes the current state of the array. In many cases, the state can be set by writing the word for the desired state, however some states cannot be explicitly set, and some transitions are not allowed.
Select/poll works on this file. All changes except between Active_idle and active (which can be frequent and are not very interesting) are notified. active->active_idle is reported if the metadata is externally managed.
clear
No devices, no size, no level
Writing is equivalent to STOP_ARRAY ioctl
inactive
May have some settings, but array is not active all IO results in error
When written, doesn't tear down array, but just stops it
suspended (not supported yet)
All IO requests will block. The array can be reconfigured.
Writing this, if accepted, will block until array is quiescent
readonly
no resync can happen. no superblocks get written.
Write requests fail
read-auto
like readonly, but behaves like
cleanon a write request.clean
no pending writes, but otherwise active.
When written to inactive array, starts without resync
If a write request arrives then if metadata is known, mark
dirtyand switch toactive. if not known, block and switch to write-pendingIf written to an active array that has pending writes, then fails.
active
fully active: IO and resync can be happening. When written to inactive array, starts with resync
write-pending
clean, but writes are blocked waiting for
activeto be written.active-idle
like active, but no writes have been seen for a while (safe_mode_delay).
consistency_policy
This indicates how the array maintains consistency in case of unexpected shutdown. It can be:
none
Array has no redundancy information, e.g. raid0, linear.
resync
Full resync is performed and all redundancy is regenerated when the array is started after unclean shutdown.
bitmap
Resync assisted by a write-intent bitmap.
journal
For raid4/5/6, journal device is used to log transactions and replay after unclean shutdown.
ppl
For raid5 only, Partial Parity Log is used to close the write hole and eliminate resync.
The accepted values when writing to this file are
pplandresync, used to enable and disable PPL.uuid
This indicates the UUID of the array in the following format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
bitmap_type
[RW] When read, this file will display the current and available bitmap for this array. The currently active bitmap will be enclosed in [] brackets. Writing an bitmap name or ID to this file will switch control of this array to that new bitmap. Note that writing a new bitmap for created array is forbidden.
none
No bitmap
bitmap
The default internal bitmap
llbitmap
The lockless internal bitmap
If bitmap_type is not none, then additional bitmap attributes bitmap/xxx or llbitmap/xxx will be created after md device KOBJ_CHANGE event.
If bitmap_type is bitmap, then the md device will also contain:
bitmap/location
This indicates where the write-intent bitmap for the array is stored.
It can be one of
none,fileor[+-]N.filemay later be extended tofile:/file/name[+-]Nmeans that many sectors from the start of the metadata.This is replicated on all devices. For arrays with externally managed metadata, the offset is from the beginning of the device.
bitmap/chunksize
The size, in bytes, of the chunk which will be represented by a single bit. For RAID456, it is a portion of an individual device. For RAID10, it is a portion of the array. For RAID1, it is both (they come to the same thing).
bitmap/time_base
The time, in seconds, between looking for bits in the bitmap to be cleared. In the current implementation, a bit will be cleared between 2 and 3 times
time_baseafter all the covered blocks are known to be in-sync.bitmap/backlog
When write-mostly devices are active in a RAID1, write requests to those devices proceed in the background - the filesystem (or other user of the device) does not have to wait for them.
backlogsets a limit on the number of concurrent background writes. If there are more than this, new writes will by synchronous.bitmap/metadata
This can be either
internalorexternal.
internalis the default and means the metadata for the bitmap is stored in the first 256 bytes of the allocated space and is managed by the md module.
externalmeans that bitmap metadata is managed externally to the kernel (i.e. by some userspace program)
bitmap/can_clear
This is either
trueorfalse. Iftrue, then bits in the bitmap will be cleared when the corresponding blocks are thought to be in-sync. Iffalse, bits will never be cleared. This is automatically set tofalseif a write happens on a degraded array, or if the array becomes degraded during a write. When metadata is managed externally, it should be set to true once the array becomes non-degraded, and this fact has been recorded in the metadata.
If bitmap_type is llbitmap, then the md device will also contain:
llbitmap/bits
This is read-only, show status of bitmap bits, the number of each value.
llbitmap/metadata
This is read-only, show bitmap metadata, include chunksize, chunkshift, chunks, offset and daemon_sleep.
llbitmap/daemon_sleep
This is read-write, time in seconds that daemon function will be triggered to clear dirty bits.
llbitmap/barrier_idle
This is read-write, time in seconds that page barrier will be idled, means dirty bits in the page will be cleared.
As component devices are added to an md array, they appear in the md directory as new directories named:
dev-XXX
where XXX is a name that the kernel knows for the device, e.g. hdb1. Each directory contains:
block
a symlink to the block device in /sys/block, e.g.:
/sys/block/md0/md/dev-hdb1/block -> ../../../../block/hdb/hdb1super
A file containing an image of the superblock read from, or written to, that device.
state
A file recording the current state of the device in the array which can be a comma separated list of:
faulty
device has been kicked from active use due to a detected fault, or it has unacknowledged bad blocks
in_sync
device is a fully in-sync member of the array
writemostly
device will only be subject to read requests if there are no other options.
This applies only to raid1 arrays.
blocked
device has failed, and the failure hasn't been acknowledged yet by the metadata handler.
Writes that would write to this device if it were not faulty are blocked.
spare
device is working, but not a full member.
This includes spares that are in the process of being recovered to
write_error
device has ever seen a write error.
want_replacement
device is (mostly) working but probably should be replaced, either due to errors or due to user request.
replacement
device is a replacement for another active device with same raid_disk.
This list may grow in future.
This can be written to.
Writing
faultysimulates a failure on the device.Writing
removeremoves the device from the array.Writing
writemostlysets the writemostly flag.Writing
-writemostlyclears the writemostly flag.Writing
blockedsets theblockedflag.Writing
-blockedclears theblockedflags and allows writes to complete and possibly simulates an error.Writing
in_syncsets the in_sync flag.Writing
write_errorsets writeerrorseen flag.Writing
-write_errorclears writeerrorseen flag.Writing
want_replacementis allowed at any time except to a replacement device or a spare. It sets the flag.Writing
-want_replacementis allowed at any time. It clears the flag.Writing
replacementor-replacementis only allowed before starting the array. It sets or clears the flag.This file responds to select/poll. Any change to
faultyorblockedcauses an event.errors
An approximate count of read errors that have been detected on this device but have not caused the device to be evicted from the array (either because they were corrected or because they happened while the array was read-only). When using version-1 metadata, this value persists across restarts of the array.
This value can be written while assembling an array thus providing an ongoing count for arrays with metadata managed by userspace.
slot
This gives the role that the device has in the array. It will either be
noneif the device is not active in the array (i.e. is a spare or has failed) or an integer less than theraid_disksnumber for the array indicating which position it currently fills. This can only be set while assembling an array. A device for which this is set is assumed to be working.offset
This gives the location in the device (in sectors from the start) where data from the array will be stored. Any part of the device before this offset is not touched, unless it is used for storing metadata (Formats 1.1 and 1.2).
size
The amount of the device, after the offset, that can be used for storage of data. This will normally be the same as the component_size. This can be written while assembling an array. If a value less than the current component_size is written, it will be rejected.
recovery_start
When the device is not
in_sync, this records the number of sectors from the start of the device which are known to be correct. This is normally zero, but during a recovery operation it will steadily increase, and if the recovery is interrupted, restoring this value can cause recovery to avoid repeating the earlier blocks. With v1.x metadata, this value is saved and restored automatically.This can be set whenever the device is not an active member of the array, either before the array is activated, or before the
slotis set.Setting this to
noneis equivalent to settingin_sync. Setting to any other value also clears thein_syncflag.bad_blocks
This gives the list of all known bad blocks in the form of start address and length (in sectors respectively). If output is too big to fit in a page, it will be truncated. Writing
sector lengthto this file adds new acknowledged (i.e. recorded to disk safely) bad blocks.unacknowledged_bad_blocks
This gives the list of known-but-not-yet-saved-to-disk bad blocks in the same form of
bad_blocks. If output is too big to fit in a page, it will be truncated. Writing to this file adds bad blocks without acknowledging them. This is largely for testing.ppl_sector, ppl_size
Location and size (in sectors) of the space used for Partial Parity Log on this device.
An active md device will also contain an entry for each active device in the array. These are named:
rdNN
where NN is the position in the array, starting from 0. So for a 3 drive array there will be rd0, rd1, rd2. These are symbolic links to the appropriate dev-XXX entry. Thus, for example:
cat /sys/block/md*/md/rd*/state
will show in_sync on every line.
Active md devices for levels that support data redundancy (1,4,5,6,10) also have
sync_action
a text file that can be used to monitor and control the rebuild process. It contains one word which can be one of:
resync
redundancy is being recalculated after unclean shutdown or creation
recover
a hot spare is being built to replace a failed/missing device
idle
nothing is happening
check
A full check of redundancy was requested and is happening. This reads all blocks and checks them. A repair may also happen for some raid levels.
repair
A full check and repair is happening. This is similar to
resync, but was requested by the user, and the write-intent bitmap is NOT used to optimise the process.This file is writable, and each of the strings that could be read are meaningful for writing.
idlewill stop an active resync/recovery etc. There is no guarantee that another resync/recovery may not be automatically started again, though some event will be needed to trigger this.
resyncorrecoverycan be used to restart the corresponding operation if it was stopped withidle.
checkandrepairwill start the appropriate process providing the current state isidle.This file responds to select/poll. Any important change in the value triggers a poll event. Sometimes the value will briefly be
recoverif a recovery seems to be needed, but cannot be achieved. In that case, the transition torecoverisn't notified, but the transition away is.degraded
This contains a count of the number of devices by which the arrays is degraded. So an optimal array will show
0. A single failed/missing drive will show1, etc.This file responds to select/poll, any increase or decrease in the count of missing devices will trigger an event.
mismatch_count
When performing
checkandrepair, and possibly when performingresync, md will count the number of errors that are found. The count inmismatch_cntis the number of sectors that were re-written, or (forcheck) would have been re-written. As most raid levels work in units of pages rather than sectors, this may be larger than the number of actual errors by a factor of the number of sectors in a page.bitmap_set_bits
If the array has a write-intent bitmap, then writing to this attribute can set bits in the bitmap, indicating that a resync would need to check the corresponding blocks. Either individual numbers or start-end pairs can be written. Multiple numbers can be separated by a space.
Note that the numbers are
bitnumbers, notblocknumbers. They should be scaled by the bitmap_chunksize.sync_speed_min, sync_speed_max
This are similar to
/proc/sys/dev/raid/speed_limit_{min,max}however they only apply to the particular array.If no value has been written to these, or if the word
systemis written, then the system-wide value is used. If a value, in kibibytes-per-second is written, then it is used.When the files are read, they show the currently active value followed by
(local)or(system)depending on whether it is a locally set or system-wide value.sync_completed
This shows the number of sectors that have been completed of whatever the current sync_action is, followed by the number of sectors in total that could need to be processed. The two numbers are separated by a
/thus effectively showing one value, a fraction of the process that is complete.A
selecton this attribute will return when resync completes, when it reaches the current sync_max (below) and possibly at other times.sync_speed
This shows the current actual speed, in K/sec, of the current sync_action. It is averaged over the last 30 seconds.
suspend_lo, suspend_hi
The two values, given as numbers of sectors, indicate a range within the array where IO will be blocked. This is currently only supported for raid4/5/6.
sync_min, sync_max
The two values, given as numbers of sectors, indicate a range within the array where
check/repairwill operate. Must be a multiple of chunk_size. When it reachessync_maxit will pause, rather than complete. You can useselectorpollonsync_completedto wait for that number to reach sync_max. Then you can either increasesync_max, or can writeidletosync_action.The value of
maxforsync_maxeffectively disables the limit. When a resync is active, the value can only ever be increased, never decreased. The value of0is the minimum forsync_min.
Each active md device may also have attributes specific to the personality module that manages it. These are specific to the implementation of the module and could change substantially if the implementation changes.
These currently include:
stripe_cache_size (currently raid5 only)
number of entries in the stripe cache. This is writable, but there are upper and lower limits (32768, 17). Default is 256.
strip_cache_active (currently raid5 only)
number of active entries in the stripe cache
preread_bypass_threshold (currently raid5 only)
number of times a stripe requiring preread will be bypassed by a stripe that does not require preread. For fairness defaults to 1. Setting this to 0 disables bypass accounting and requires preread stripes to wait until all full-width stripe- writes are complete. Valid values are 0 to stripe_cache_size.
journal_mode (currently raid5 only)
The cache mode for raid5. raid5 could include an extra disk for caching. The mode can be "write-through" or "write-back". The default is "write-through".
ppl_write_hint
NVMe stream ID to be set for each PPL write request.
Linux NVMe multipath
Peios Kernel / Administration / System administration / Filesystems and storage configuration
This document describes NVMe multipath and its path selection policies supported by the Linux NVMe host driver.
Introduction #
The NVMe multipath feature in Linux integrates namespaces with the same identifier into a single block device. Using multipath enhances the reliability and stability of I/O access while improving bandwidth performance. When a user sends I/O to this merged block device, the multipath mechanism selects one of the underlying block devices (paths) according to the configured policy. Different policies result in different path selections.
Policies #
All policies follow the ANA (Asymmetric Namespace Access) mechanism, meaning that when an optimized path is available, it will be chosen over a non-optimized one. Current the NVMe multipath policies include numa(default), round-robin and queue-depth.
-
To set the desired policy (e.g., round-robin), use one of the following methods:
-
echo -n "round-robin" > /sys/module/nvme_core/parameters/iopolicy
-
or add the "nvme_core.iopolicy=round-robin" to cmdline.
-
NUMA #
The NUMA policy selects the path closest to the NUMA node of the current CPU for I/O distribution. This policy maintains the nearest paths to each NUMA node based on network interface connections.
-
When to use the NUMA policy:
-
Multi-core Systems: Optimizes memory access in multi-core and multi-processor systems, especially under NUMA architecture.
-
High Affinity Workloads: Binds I/O processing to the CPU to reduce communication and data transfer delays across nodes.
-
Round-Robin #
The round-robin policy distributes I/O requests evenly across all paths to enhance throughput and resource utilization. Each I/O operation is sent to the next path in sequence.
-
When to use the round-robin policy:
-
Balanced Workloads: Effective for balanced and predictable workloads with similar I/O size and type.
-
Homogeneous Path Performance: Utilizes all paths efficiently when performance characteristics (e.g., latency, bandwidth) are similar.
-
Queue-Depth #
The queue-depth policy manages I/O requests based on the current queue depth of each path, selecting the path with the least number of in-flight I/Os.
-
When to use the queue-depth policy:
- High load with small I/Os: Effectively balances load across paths when the load is high, and I/O operations consist of small, relatively fixed-sized requests.
Using UFS
Peios Kernel / Administration / System administration / Filesystems and storage configuration
mount -t ufs -o ufstype=type_of_ufs device dir
UFS Options #
-
ufstype=type_of_ufs
UFS is a file system widely used in different operating systems. The problem are differences among implementations. Features of some implementations are undocumented, so its hard to recognize type of ufs automatically. That's why user must specify type of ufs manually by mount option ufstype. Possible values are:
-
old
old format of ufs default value, supported as read-only
-
44bsd
used in FreeBSD, NetBSD, OpenBSD supported as read-write
-
ufs2
used in FreeBSD 5.x supported as read-write
-
5xbsd
synonym for ufs2
-
sun
used in SunOS (Solaris) supported as read-write
-
sunx86
used in SunOS for Intel (Solarisx86) supported as read-write
-
hp
used in HP-UX supported as read-only
-
nextstep
used in NextStep supported as read-only
-
nextstep-cd
used for NextStep CDROMs (block_size == 2048) supported as read-only
-
openstep
used in OpenStep supported as read-only
-
Possible Problems #
See next section, if you have any.
Bug Reports #
Any ufs bug report you can send to daniel.pirkl@email.cz or to dushistov@mail.ru (do not send partition tables bug reports).
The SGI XFS Filesystem
Peios Kernel / Administration / System administration / Filesystems and storage configuration
Peios: Linux capability names in this interface retain their API meaning, but KACS evaluates them through native token privileges or compatibility rules. UID 0,
setcapand Unix mode bits do not independently grant native authority. Object access and PIP checks remain additional constraints where applicable. See Peios kernel behaviour for the mapping and exceptions.
XFS is a high performance journaling filesystem which originated on the SGI IRIX platform. It is completely multi-threaded, can support large files and large filesystems, extended attributes, variable block sizes, is extent based, and makes extensive use of Btrees (directories, extents, free space) to aid both performance and scalability.
Refer to the documentation at https://xfs.wiki.kernel.org/ for further details. This implementation is on-disk compatible with the IRIX version of XFS.
Mount Options #
When mounting an XFS filesystem, the following options are accepted.
allocsize=size
Sets the buffered I/O end-of-file preallocation size when doing delayed allocation writeout (default size is 64KiB). Valid values for this option are page size (typically 4KiB) through to 1GiB, inclusive, in power-of-2 increments.
The default behaviour is for dynamic end-of-file preallocation size, which uses a set of heuristics to optimise the preallocation size based on the current allocation patterns within the file and the access patterns to the file. Specifying a fixed
allocsizevalue turns off the dynamic behaviour.discard or nodiscard (default)
Enable/disable the issuing of commands to let the block device reclaim space freed by the filesystem. This is useful for SSD devices, thinly provisioned LUNs and virtual machine images, but may have a performance impact.
Note: It is currently recommended that you use the
fstrimapplication todiscardunused blocks rather than thediscardmount option because the performance impact of this option is quite severe.grpid/bsdgroups or nogrpid/sysvgroups (default)
These options define what group ID a newly created file gets. When
grpidis set, it takes the group ID of the directory in which it is created; otherwise it takes thefsgidof the current process, unless the directory has thesetgidbit set, in which case it takes thegidfrom the parent directory, and also gets thesetgidbit set if it is a directory itself.filestreams
Make the data allocator use the filestreams allocation mode across the entire filesystem rather than just on directories configured to use it.
inode32 or inode64 (default)
When
inode32is specified, it indicates that XFS limits inode creation to locations which will not result in inode numbers with more than 32 bits of significance.When
inode64is specified, it indicates that XFS is allowed to create inodes at any location in the filesystem, including those which will result in inode numbers occupying more than 32 bits of significance.
inode32is provided for backwards compatibility with older systems and applications, since 64 bits inode numbers might cause problems for some applications that cannot handle large inode numbers. If applications are in use which do not handle inode numbers bigger than 32 bits, theinode32option should be specified.largeio or nolargeio (default)
If
nolargeiois specified, the optimal I/O reported inst_blksizeby stat(2) will be as small as possible to allow user applications to avoid inefficient read/modify/write I/O. This is typically the page size of the machine, as this is the granularity of the page cache.If
largeiois specified, a filesystem that was created with aswidthspecified will return theswidthvalue (in bytes) inst_blksize. If the filesystem does not have aswidthspecified but does specify anallocsizethenallocsize(in bytes) will be returned instead. Otherwise the behaviour is the same as ifnolargeiowas specified.logbufs=value
Set the number of in-memory log buffers. Valid numbers range from 2-8 inclusive.
The default value is 8 buffers.
If the memory cost of 8 log buffers is too high on small systems, then it may be reduced at some cost to performance on metadata intensive workloads. The
logbsizeoption below controls the size of each buffer and so is also relevant to this case.lifetime (default) or nolifetime
Enable data placement based on write life time hints provided by the user. This turns on co-allocation of data of similar life times when statistically favorable to reduce garbage collection cost.
These options are only available for zoned rt file systems.
logbsize=value
Set the size of each in-memory log buffer. The size may be specified in bytes, or in kilobytes with a "k" suffix. Valid sizes for version 1 and version 2 logs are 16384 (16k) and 32768 (32k). Valid sizes for version 2 logs also include 65536 (64k), 131072 (128k) and 262144 (256k). The logbsize must be an integer multiple of the log stripe unit configured at mkfs(8) time.
The default value for version 1 logs is 32768, while the default value for version 2 logs is MAX(32768, log_sunit).
logdev=device and rtdev=device
Use an external log (metadata journal) and/or real-time device. An XFS filesystem has up to three parts: a data section, a log section, and a real-time section. The real-time section is optional, and the log section can be separate from the data section or contained within it.
max_atomic_write=value
Set the maximum size of an atomic write. The size may be specified in bytes, in kilobytes with a "k" suffix, in megabytes with a "m" suffix, or in gigabytes with a "g" suffix. The size cannot be larger than the maximum write size, larger than the size of any allocation group, or larger than the size of a remapping operation that the log can complete atomically.
The default value is to set the maximum I/O completion size to allow each CPU to handle one at a time.
max_open_zones=value
Specify the max number of zones to keep open for writing on a zoned rt device. Many open zones aids file data separation but may impact performance on HDDs.
If
max_open_zonesis not specified, the value is determined by the capabilities and the size of the zoned rt device.noalign
Data allocations will not be aligned at stripe unit boundaries. This is only relevant to filesystems created with non-zero data alignment parameters (
sunit,swidth) by mkfs(8).norecovery
The filesystem will be mounted without running log recovery. If the filesystem was not cleanly unmounted, it is likely to be inconsistent when mounted in
norecoverymode. Some files or directories may not be accessible because of this. Filesystems mountednorecoverymust be mounted read-only or the mount will fail.nouuid
Don't check for double mounted file systems using the file system
uuid. This is useful to mount LVM snapshot volumes, and often used in combination withnorecoveryfor mounting read-only snapshots.noquota
Forcibly turns off all quota accounting and enforcement within the filesystem.
uquota/usrquota/uqnoenforce/quota
User disk quota accounting enabled, and limits (optionally) enforced. Refer to xfs_quota(8) for further details.
gquota/grpquota/gqnoenforce
Group disk quota accounting enabled and limits (optionally) enforced. Refer to xfs_quota(8) for further details.
pquota/prjquota/pqnoenforce
Project disk quota accounting enabled and limits (optionally) enforced. Refer to xfs_quota(8) for further details.
sunit=value and swidth=value
Used to specify the stripe unit and width for a RAID device or a stripe volume. "value" must be specified in 512-byte block units. These options are only relevant to filesystems that were created with non-zero data alignment parameters.
The
sunitandswidthparameters specified must be compatible with the existing filesystem alignment characteristics. In general, that means the only valid changes tosunitare increasing it by a power-of-2 multiple. Validswidthvalues are any integer multiple of a validsunitvalue.Typically the only time these mount options are necessary if after an underlying RAID device has had its geometry modified, such as adding a new disk to a RAID5 lun and reshaping it.
swalloc
Data allocations will be rounded up to stripe width boundaries when the current end of file is being extended and the file size is larger than the stripe width size.
wsync
When specified, all filesystem namespace operations are executed synchronously. This ensures that when the namespace operation (create, unlink, etc) completes, the change to the namespace is on stable storage. This is useful in HA setups where failover must not result in clients seeing inconsistent namespace presentation during or after a failover event.
errortag=tagname
When specified, enables the error inject tag named "tagname" with the default frequency. Can be specified multiple times to enable multiple errortags. Specifying this option on remount will reset the error tag to the default value if it was set to any other value before. This option is only supported when CONFIG_XFS_DEBUG is enabled, and will not be reflected in /proc/self/mounts.
Deprecation of V4 Format #
The V4 filesystem format lacks certain features that are supported by the V5 format, such as metadata checksumming, strengthened metadata verification, and the ability to store timestamps past the year 2038. Because of this, the V4 format is deprecated. All users should upgrade by backing up their files, reformatting, and restoring from the backup.
Administrators and users can detect a V4 filesystem by running xfs_info against a filesystem mountpoint and checking for a string containing "crc=". If no such string is found, please upgrade xfsprogs to the latest version and try again.
The deprecation will take place in two parts. Support for mounting V4 filesystems can now be disabled at kernel build time via Kconfig option. These options were changed to default to no in September 2025. In September 2030, support will be removed from the codebase entirely.
Note: Distributors may choose to withdraw V4 format support earlier than the dates listed above.
Deprecated Mount Options #
|
Name |
Removal Schedule |
|---|---|
|
Mounting with V4 filesystem |
September 2030 |
|
Mounting ascii-ci filesystem |
September 2030 |
Removed Mount Options #
|
Name |
Removed |
|---|---|
|
delaylog/nodelaylog |
v4.0 |
|
ihashsize |
v4.0 |
|
irixsgid |
v4.0 |
|
osyncisdsync/osyncisosync |
v4.0 |
|
barrier |
v4.19 |
|
nobarrier |
v4.19 |
|
ikeep/noikeep |
v6.18 |
|
attr2/noattr2 |
v6.18 |
sysctls #
The following sysctls are available for the XFS filesystem:
fs.xfs.stats_clear (Min: 0 Default: 0 Max: 1)
Setting this to "1" clears accumulated XFS statistics in /proc/fs/xfs/stat. It then immediately resets to "0".
fs.xfs.xfssyncd_centisecs (Min: 100 Default: 3000 Max: 720000)
The interval at which the filesystem flushes metadata out to disk and runs internal cache cleanup routines.
fs.xfs.filestream_centisecs (Min: 1 Default: 3000 Max: 360000)
The interval at which the filesystem ages filestreams cache references and returns timed-out AGs back to the free stream pool.
fs.xfs.speculative_prealloc_lifetime
(Units: seconds Min: 1 Default: 300 Max: 86400) The interval at which the background scanning for inodes with unused speculative preallocation runs. The scan removes unused preallocation from clean inodes and releases the unused space back to the free pool.
fs.xfs.error_level (Min: 0 Default: 3 Max: 11)
A volume knob for error reporting when internal errors occur. This will generate detailed messages & backtraces for filesystem shutdowns, for example. Current threshold values are:
XFS_ERRLEVEL_OFF: 0 XFS_ERRLEVEL_LOW: 1 XFS_ERRLEVEL_HIGH: 5
fs.xfs.panic_mask (Min: 0 Default: 0 Max: 511)
Causes certain error conditions to call BUG(). Value is a bitmask; OR together the tags which represent errors which should cause panics:
XFS_NO_PTAG 0 XFS_PTAG_IFLUSH 0x00000001 XFS_PTAG_LOGRES 0x00000002 XFS_PTAG_AILDELETE 0x00000004 XFS_PTAG_ERROR_REPORT 0x00000008 XFS_PTAG_SHUTDOWN_CORRUPT 0x00000010 XFS_PTAG_SHUTDOWN_IOERROR 0x00000020 XFS_PTAG_SHUTDOWN_LOGERROR 0x00000040 XFS_PTAG_FSBLOCK_ZERO 0x00000080 XFS_PTAG_VERIFIER_ERROR 0x00000100
This option is intended for debugging only.
fs.xfs.inherit_sync (Min: 0 Default: 1 Max: 1)
Setting this to "1" will cause the "sync" flag set by the xfs_io(8) chattr command on a directory to be inherited by files in that directory.
fs.xfs.inherit_nodump (Min: 0 Default: 1 Max: 1)
Setting this to "1" will cause the "nodump" flag set by the xfs_io(8) chattr command on a directory to be inherited by files in that directory.
fs.xfs.inherit_noatime (Min: 0 Default: 1 Max: 1)
Setting this to "1" will cause the "noatime" flag set by the xfs_io(8) chattr command on a directory to be inherited by files in that directory.
fs.xfs.inherit_nosymlinks (Min: 0 Default: 1 Max: 1)
Setting this to "1" will cause the "nosymlinks" flag set by the xfs_io(8) chattr command on a directory to be inherited by files in that directory.
fs.xfs.inherit_nodefrag (Min: 0 Default: 1 Max: 1)
Setting this to "1" will cause the "nodefrag" flag set by the xfs_io(8) chattr command on a directory to be inherited by files in that directory.
fs.xfs.rotorstep (Min: 1 Default: 1 Max: 256)
In "inode32" allocation mode, this option determines how many files the allocator attempts to allocate in the same allocation group before moving to the next allocation group. The intent is to control the rate at which the allocator moves between allocation groups when allocating extents for new files.
Deprecated Sysctls #
None currently.
Removed Sysctls #
|
Name |
Removed |
|---|---|
|
fs.xfs.xfsbufd_centisec |
v4.0 |
|
fs.xfs.age_buffer_centisecs |
v4.0 |
|
fs.xfs.irix_symlink_mode |
v6.18 |
|
fs.xfs.irix_sgid_inherit |
v6.18 |
|
fs.xfs.speculative_cow_prealloc_lifetime |
v6.18 |
Error handling #
XFS can act differently according to the type of error found during its operation. The implementation introduces the following concepts to the error handler:
-failure speed:
Defines how fast XFS should propagate an error upwards when a specific error is found during the filesystem operation. It can propagate immediately, after a defined number of retries, after a set time period, or simply retry forever.
-error classes:
Specifies the subsystem the error configuration will apply to, such as metadata IO or memory allocation. Different subsystems will have different error handlers for which behaviour can be configured.
-error handlers:
Defines the behavior for a specific error.
The filesystem behavior during an error can be set via sysfs files. Each error handler works independently - the first condition met by an error handler for a specific class will cause the error to be propagated rather than reset and retried.
The action taken by the filesystem when the error is propagated is context dependent - it may cause a shut down in the case of an unrecoverable error, it may be reported back to userspace, or it may even be ignored because there's nothing useful we can with the error or anyone we can report it to (e.g. during unmount).
The configuration files are organized into the following hierarchy for each mounted filesystem:
/sys/fs/xfs/<dev>/error/<class>/<error>/
-
Where:
-
<dev>
The short device name of the mounted filesystem. This is the same device name that shows up in XFS kernel error messages as "XFS(<dev>): ..."
-
<class>
The subsystem the error configuration belongs to. As of 4.9, the defined classes are:
- "metadata": applies metadata buffer write IO
-
<error>
The individual error handler configurations.
-
Each filesystem has "global" error configuration options defined in their top level directory:
/sys/fs/xfs/<dev>/error/
fail_at_unmount (Min: 0 Default: 1 Max: 1)
Defines the filesystem error behavior at unmount time.
If set to a value of 1, XFS will override all other error configurations during unmount and replace them with "immediate fail" characteristics. i.e. no retries, no retry timeout. This will always allow unmount to succeed when there are persistent errors present.
If set to 0, the configured retry behaviour will continue until all retries and/or timeouts have been exhausted. This will delay unmount completion when there are persistent errors, and it may prevent the filesystem from ever unmounting fully in the case of "retry forever" handler configurations.
Note: there is no guarantee that fail_at_unmount can be set while an unmount is in progress. It is possible that the
sysfsentries are removed by the unmounting filesystem before a "retry forever" error handler configuration causes unmount to hang, and hence the filesystem must be configured appropriately before unmount begins to prevent unmount hangs.
Each filesystem has specific error class handlers that define the error propagation behaviour for specific errors. There is also a "default" error handler defined, which defines the behaviour for all errors that don't have specific handlers defined. Where multiple retry constraints are configured for a single error, the first retry configuration that expires will cause the error to be propagated. The handler configurations are found in the directory:
/sys/fs/xfs/<dev>/error/<class>/<error>/
max_retries (Min: -1 Default: Varies Max: INTMAX)
Defines the allowed number of retries of a specific error before the filesystem will propagate the error. The retry count for a given error context (e.g. a specific metadata buffer) is reset every time there is a successful completion of the operation.
Setting the value to "-1" will cause XFS to retry forever for this specific error.
Setting the value to "0" will cause XFS to fail immediately when the specific error is reported.
Setting the value to "N" (where 0 < N < Max) will make XFS retry the operation "N" times before propagating the error.
retry_timeout_seconds (Min: -1 Default: Varies Max: 1 day)
Define the amount of time (in seconds) that the filesystem is allowed to retry its operations when the specific error is found.
Setting the value to "-1" will allow XFS to retry forever for this specific error.
Setting the value to "0" will cause XFS to fail immediately when the specific error is reported.
Setting the value to "N" (where 0 < N < Max) will allow XFS to retry the operation for up to "N" seconds before propagating the error.
Note: The default behaviour for a specific error handler is dependent on both the class and error context. For example, the default values for "metadata/ENODEV" are "0" rather than "-1" so that this error handler defaults to "fail immediately" behaviour. This is done because ENODEV is a fatal, unrecoverable error no matter how many times the metadata IO is retried.
Workqueue Concurrency #
XFS uses kernel workqueues to parallelize metadata update processes. This enables it to take advantage of storage hardware that can service many IO operations simultaneously. This interface exposes internal implementation details of XFS, and as such is explicitly not part of any userspace API/ABI guarantee the kernel may give userspace. These are undocumented features of the generic workqueue implementation XFS uses for concurrency, and they are provided here purely for diagnostic and tuning purposes and may change at any time in the future.
The control knobs for a filesystem's workqueues are organized by task at hand and the short name of the data device. They all can be found in:
/sys/bus/workqueue/devices/${task}!${device}
|
Task |
Description |
|---|---|
|
xfs_iwalk-$pid |
Inode scans of the entire filesystem. Currently limited to mount time quotacheck. |
|
xfs-gc |
Background garbage collection of disk space that have been speculatively allocated beyond EOF or for staging copy on write operations. |
For example, the knobs for the quotacheck workqueue for /dev/nvme0n1 would be found in /sys/bus/workqueue/devices/xfs_iwalk-1111!nvme0n1/.
The interesting knobs for XFS workqueues are as follows:
|
Knob |
Description |
|---|---|
|
max_active |
Maximum number of background threads that can be started to run the work. |
|
cpumask |
CPUs upon which the threads are allowed to run. |
|
nice |
Relative priority of scheduling the threads. These are the same nice levels that can be applied to userspace processes. |
Zoned Filesystems #
For zoned file systems, the following attributes are exposed in:
/sys/fs/xfs/<dev>/zoned/
max_open_zones (Min: 1 Default: Varies Max: UINTMAX)
This read-only attribute exposes the maximum number of open zones available for data placement. The value is determined at mount time and is limited by the capabilities of the backing zoned device, file system size and the max_open_zones mount option.
zonegc_low_space (Min: 0 Default: 0 Max: 100)
Define a percentage for how much of the unused space that GC should keep available for writing. A high value will reclaim more of the space occupied by unused blocks, creating a larger buffer against write bursts at the cost of increased write amplification. Regardless of this value, garbage collection will always aim to free a minimum amount of blocks to keep max_open_zones open for data placement purposes.