Room 12 · Compression, dedup, encryption
What do compression, dedup and encryption do to a block?
ZFS writes files in blocks, 128 KiB by default, and a disk stores them in whole sectors of 512 bytes or 4 KiB. Before a block is written, three optional features act on it, in this order: compression, encryption, then deduplication. ZFS keeps a block compressed only if that saves at least an eighth of it, counted in whole sectors; otherwise it stores the block as it is.
Deduplication avoids writing a block that is already on disk. ZFS looks the checksum of every block up in a table, the dedup table. On a match, the new block pointer (the record a parent block keeps of each child’s address and checksum) takes the address of the copy on disk, and a reference count goes up. Otherwise the block is written and gets an entry. The price is a lookup on every write and a table that grows with the data.
To encrypt a block, ZFS uses a salt and an initialization vector (IV), two values that make each block’s encryption different, and computes a message authentication code (MAC), which proves that the block was not altered. All three go in the block pointer, in the place of the third copy’s address, half of the checksum and a few spare bits. The other half is a checksum of the encrypted bytes, so a scrub can check every block without the key.
1 Compress a block
The figure follows one block through the tests the write path makes. Choose the data, the block size, the sector size and the compression. The line under the controls says what happened, and what the choice changed is outlined.
With compressible data, the output stays under the limit, the solid line at seven eighths of the block rounded down to a sector, and the block takes fewer sectors on disk. Already compressed data goes over the limit and is stored as it is. With compression on, a block of zeros is not written at all: All zeros makes a hole. A block that compresses to 112 bytes or less goes inside its block pointer instead of on disk: try Almost empty.
Then choose a 4 KiB block on 4 KiB sectors. Seven eighths of one sector rounds down to nothing, so the block stays compressed only if it shrinks to 112 bytes or less, and then it goes into its block pointer. The table under the figure shows the same data at the three sector sizes.
- Compression is LZ4: the block goes through the branches below.
- The block is not all zeros.
- The output (49,807 bytes) fits under the limit (112 KiB).
- More than 112 bytes: it cannot go into the block pointer.
- Rounded up to the sector: 52 KiB, less than 128 KiB. Stored compressed, the tail zeroed. (this branch decided)
Stored compressed. 49,807 bytes compressed with LZ4, rounded up to the sector: PSIZE 52 KiB, 13 sectors at ashift 12.
Block pointer: PSIZE 52 KiB, LSIZE 128 KiB, compression LZ4; ASIZE 52 KiB.
| Word | Holds |
|---|---|
| 0 | DVA 1: vdev, ASIZE |
| 1 | DVA 1: G, offset |
| 2 | DVA 2: vdev, ASIZE |
| 3 | DVA 2: G, offset |
| 4 | DVA 3: vdev, ASIZE |
| 5 | DVA 3: G, offset |
| 6 | B D X, level, type, checksum, E, compression, PSIZE, LSIZE |
| 7 | R, padding |
| 8 | padding |
| 9 | physical birth txg |
| a | logical birth txg |
| b | fill count |
| c | checksum[0] |
| d | checksum[1] |
| e | checksum[2] |
| f | checksum[3] |
| ashift | Limit | Outcome | PSIZE | Allocated |
|---|---|---|---|---|
| 9 (512 bytes) | 114,688 | Stored compressed. | 50,176 | 50,176 |
| 12 (4 KiB) | 114,688 | Stored compressed. | 53,248 | 53,248 |
| 13 (8 KiB) | 114,688 | Stored compressed. | 57,344 | 57,344 |
Text version of this figure
49,807 bytes compressed with LZ4, rounded up to the sector: PSIZE 52 KiB, 13 sectors at ashift 12.
2 Write the same block twice
Each Write button writes a block with that content, in a new transaction group (the batch of changes ZFS commits every few seconds). The figure opens after three writes: A, B, then A again, which was found in the table: a hit.
Write C: C is not in the table, a miss, so the block is written and the table gets an entry for its checksum. Write C again: it is a hit, the entry’s count goes to 2 and no block is written. The lookup counter goes up with every write.
Start again, write A, then press Dedup table over its quota and write B. B gets no entry and is written like any block. Write A: it is still found in the table and still deduplicated.
3 writes3 DDT lookups2 data blocks written2 entries
The last write
- Block A, txg 102: checksum
5cf94b00…, looked up in the DDT. - In the table: its entry already holds the address of a copy on disk.
- Hit: the new block pointer gets
0:400000from the entry, born in txg 102 with physical birth 100; refcount 2. Nothing is written.
Dedup table (DDT)
| Key | Data | Refcount | DVA | Physical birth |
|---|---|---|---|---|
5cf94b00… | A | 2 | 0:400000 | 100 |
fa9a4a00… | B | 1 | 0:420000 | 101 |
Block pointers written
- bp0AD=1
0:400000born 100, physical 100 - bp1BD=1
0:420000born 101, physical 101 - bp2AD=1
0:400000born 102, physical 100
Data blocks on disk
0:400000Areferenced by bp0, bp20:420000Breferenced by bp1
Text version of this figure
- Miss: A is written at
0:400000; the entry gets the DVA and refcount 1. - Miss: B is written at
0:420000; the entry gets the DVA and refcount 1. - Hit: the new block pointer gets
0:400000from the entry, born in txg 102 with physical birth 100; refcount 2. Nothing is written.
3 writes, 3 DDT lookups, 2 data blocks written, 2 entries.
3 Unload the key, then scrub
On the left are the 16 words of a block pointer. For an encrypted data block, the highlighted words are the ones that differ from an ordinary block: the third address, the upper half of the fill count and the second half of the checksum.
On the right is a small encrypted file: its dnode block, which describes the file, an indirect block that points to the data, and three data blocks. Press Unload the key: the data shows as ciphertext. Scrub: every block still passes. Read the file: the read fails at the first data block, which cannot be decrypted. Flip a bit, then scrub again: the damaged block is caught, with or without the key.
A level-0 block of an encrypted type: the third DVA holds the salt and the start of the IV, the top of the fill count the rest of the IV, half of the checksum the MAC. At most 2 copies.
| Word | Holds |
|---|---|
| 0 | DVA 1: vdev, ASIZE |
| 1 | DVA 1: G, offset |
| 2 | DVA 2: vdev, ASIZE |
| 3 | DVA 2: G, offset |
| 4 | salt (changed) |
| 5 | IV1: first 64 bits of the IV (changed) |
| 6 | B D X, level, type, checksum, E, compression, PSIZE, LSIZE |
| 7 | R, padding |
| 8 | padding |
| 9 | physical birth txg |
| a | logical birth txg |
| b | IV2: last 32 bits of the IV | fill count, 32 bits (changed) |
| c | checksum[0] |
| d | checksum[1] |
| e | MAC[0] (changed) |
| f | MAC[1] (changed) |
An encrypted file
Key loaded: the encrypted blocks are decrypted on read.
- dnode blockencrypted type, core in cleardnode core, in clear: type, levels, block pointerbonus buffer: “file attributes”
- indirect block (L1)indirect, checksum of the MACsthree block pointers, in clear: DVAs, births, checksums, salts, IVs, MACs
- data block 0encrypted“This text”
- data block 1encrypted“stays readable”
- data block 2encrypted“with the key.”
Text version of this figure
An ordinary block pointer: three DVAs, a 256-bit checksum. At most 3 copies.
A level-0 block of an encrypted type: the third DVA holds the salt and the start of the IV, the top of the fill count the rest of the IV, half of the checksum the MAC. At most 2 copies.
A level-0 block of a type that must stay readable: its data is in clear, protected by a MAC in half of the checksum. At most 3 copies.
An indirect block of an encrypted dataset: in clear, its MAC words hold a checksum of the MACs of the level below. At most 3 copies.
Key unloaded: the data blocks and the bonus buffer read as ciphertext; the dnode core and the indirect block are in clear on disk.
In the code
The figures follow ten places in the OpenZFS source. Open a Source note to see the lines, taken from release zfs-2.4.4.
The order of the stages
Each stage of a write is one bit, and a write runs its stages from the lowest bit up. Compression comes before encryption, and the checksum is computed on the bytes that will be written. The dedup lookup comes after, so it uses the checksum of the compressed and encrypted block.
Source
enum zio_stage, zio_impl.h
enum zio_stage
Excerpt of include/sys/zio_impl.h, lines
135–144, OpenZFS zfs-2.4.4.
View on GitHub
ZIO_STAGE_WRITE_COMPRESS = 1 << 5, /* -W---- */
ZIO_STAGE_ENCRYPT = 1 << 6, /* -W---- */
ZIO_STAGE_CHECKSUM_GENERATE = 1 << 7, /* -W---- */
ZIO_STAGE_NOP_WRITE = 1 << 8, /* -W---- */
ZIO_STAGE_DDT_READ_START = 1 << 9, /* R----- */
ZIO_STAGE_DDT_READ_DONE = 1 << 10, /* R----- */
ZIO_STAGE_DDT_WRITE = 1 << 11, /* -W---- */- L135–L138 Compression, then encryption, then the checksum of what will be written.
- L140 Nop-write, which skips a write whose new checksum equals the old one. The figures leave it out.
- L142–L144 The dedup stages. A write moves to the next bit set in its pipeline, so they come last.
The limit
Before compressing, zio_get_compression_max_size works out how big the output may be: seven
eighths of the block, rounded down to a whole number of sectors. A saving smaller than a sector saves nothing,
because a block takes whole sectors on disk.
Source
zio_get_compression_max_size, zio.c
zio_get_compression_max_size
Excerpt of module/zfs/zio.c, lines
1797–1807, OpenZFS zfs-2.4.4.
View on GitHub
/* minimum 12.5% must be saved (legacy value, may be changed later) */
d_len = s_len - (s_len >> 3);
/* ZLE can't use exactly d_len bytes, it needs more, so ignore it */
if (compress == ZIO_COMPRESS_ZLE)
return (d_len);
d_len = d_len - d_len % gcd_alloc;
if (d_len < min_alloc)
return (BPE_PAYLOAD_SIZE);- L1797–L1798 Seven eighths of the source: at least 12.5% must be saved, a “legacy value”, says the comment.
- L1800–L1802 For ZLE, which only compresses runs of zeros, the limit is not rounded.
-
L1804
Rounded down to a multiple of
spa_gcd_alloc, which on a pool of plain disks of one ashift is the sector (the greatest common divisor of the vdevs’ allocation sizes). -
L1806–L1807
If that leaves less than one sector, only an output that fits in a block pointer is worth keeping:
BPE_PAYLOAD_SIZE, 14 words of 8 bytes, 112 bytes.
Zeros, too big, or small enough to embed
zio_write_compress first checks for a block of zeros, then runs the compressor with the limit as
its output size. The outcome is decided by the size it gets back.
Source
zio_write_compress, zio.c
zio_write_compress
Excerpt of module/zfs/zio.c, lines
1986–2004, OpenZFS zfs-2.4.4.
View on GitHub
if (abd_cmp_zero(zio->io_abd, lsize) == 0)
psize = 0;
else if (compress == ZIO_COMPRESS_EMPTY)
psize = lsize;
else
psize = zio_compress_data(compress, zio->io_abd, &cabd,
lsize,
zio_get_compression_max_size(compress,
spa->spa_gcd_alloc, spa->spa_min_alloc, lsize),
zp->zp_complevel);
if (psize == 0) {
compress = ZIO_COMPRESS_OFF;
} else if (psize >= lsize) {
compress = ZIO_COMPRESS_OFF;
if (cabd != NULL)
abd_free(cabd);
} else if (psize <= BPE_PAYLOAD_SIZE && !zp->zp_encrypt &&
zp->zp_level == 0 && !DMU_OT_HAS_FILL(zp->zp_type) &&
spa_feature_is_enabled(spa, SPA_FEATURE_EMBEDDED_DATA)) {- L1986–L1987 All zeros: PSIZE 0. This test runs only with compression on. With compression off and dedup on, ZFS turns on a mode that only detects zeros, because “storing many references to an all zeros block in the dedup table would be expensive”.
- L1991–L1995 The compressor gets the limit as its output size; it returns the source size when the output does not fit.
- L1996–L1997 PSIZE 0 makes a hole: nothing is allocated. If the block existed before, the hole keeps its size and is born in this txg, so an incremental send sees it.
- L1998–L2001 Nothing saved: compression is off for this block, which is stored at its full size.
-
L2002–L2004
At most 112 bytes, not encrypted, at level 0, with
embedded_dataenabled: the data is encoded into the block pointer, whose words then hold the data, and the write stops there.
Rounding up to the sector
Any other output is rounded up to whole sectors. If the rounded size is not smaller than the block, the block is stored uncompressed after all.
Source
zio_write_compress, rounding, zio.c
zio_write_compress
Excerpt of module/zfs/zio.c, lines
2027–2035, OpenZFS zfs-2.4.4.
View on GitHub
size_t rounded = (size_t)zio_roundup_alloc_size(spa,
psize);
if (rounded >= lsize) {
compress = ZIO_COMPRESS_OFF;
abd_free(cabd);
psize = lsize;
} else {
abd_zero_off(cabd, psize, rounded - psize);
psize = rounded;-
L2027–L2028
zio_roundup_alloc_sizerounds up to the minimum allocation, or to a multiple of the sector above it. - L2029–L2032 Not smaller than the block: stored uncompressed. The rounded-down limit makes this rare; ZLE, whose limit is not rounded, can reach it, and so can a 112-byte output of an encrypted block, which cannot be embedded.
-
L2034–L2035
The tail of the last sector is zeroed and PSIZE is the rounded size, so the
compressratioproperty counts the padding. On a single disk the space allocated is PSIZE rounded up to the sector.
Looking the checksum up
A block of a dataset with dedup on goes through zio_ddt_write, which looks its checksum up in
the dedup table. Over its quota, the table refuses new entries, and a block it has never seen is written
normally.
Source
zio_ddt_write, the lookup, zio.c
zio_ddt_write
Excerpt of module/zfs/zio.c, lines
3823–3832, OpenZFS zfs-2.4.4.
View on GitHub
dde = ddt_lookup(ddt, bp, B_FALSE);
if (dde == NULL) {
/* DDT size is over its quota so no new entries */
ddt_exit(ddt);
zp->zp_dedup = B_FALSE;
BP_SET_DEDUP(bp, B_FALSE);
if (zio->io_bp_override == NULL)
zio->io_pipeline = ZIO_WRITE_PIPELINE;
return (zio);
}- L3823 Every dedup write looks its block pointer up, keyed by the checksum. An entry is a 40-byte key and a value of 256 bytes, or 72 in the newer flat format.
-
L3824–L3832
NULL comes from
ddt_lookupwhen the key is in no table and the table is over its quota. The D bit is cleared and the block takes the ordinary write path. A key that is found is still returned: only new entries are refused. The quota’s default,auto, sets no size and caps the table only on a pool with a dedup or special vdev; on a pool of plain disks, the table grows with the data.
A hit writes nothing
When the entry already holds an address, the new block pointer is filled from it and the reference count goes up. The new block pointer’s logical birth is the current transaction group and its physical birth is the one the data was written in, which is why the figure shows “born 102, physical 100”.
Source
zio_ddt_write, a hit, zio.c
zio_ddt_write
Excerpt of module/zfs/zio.c, lines
3983–3986, OpenZFS zfs-2.4.4.
View on GitHub
ddt_bp_fill(ddp, v, bp, txg);
ddt_phys_addref(ddp, v);
ddt_exit(ddt);
return (zio);-
L3983
ddt_bp_fillcopies the entry’s addresses into the new block pointer, with the current txg as logical birth and the entry’s as physical birth. A rewrite first fills the pointer with its original birth txg, and does nothing if that gives the same block pointer. -
L3984
ddt_phys_addrefadds a reference. - L3985–L3986 The function returns with no write I/O.
A miss writes the block and fills the entry
A new entry has no address yet. The block is written by a child I/O, and when that write has its address, the address is copied into the entry for the next hit.
Source
zio_ddt_write, a miss, zio.c
zio_ddt_write
Excerpt of module/zfs/zio.c, lines
4161–4165, OpenZFS zfs-2.4.4.
View on GitHub
ddt_phys_addref(ddp, v);
ddt_exit(ddt);
zio_nowait(cio);- L4161 The new entry’s count goes from 0 to 1 now, before the write completes; it is undone if the write fails.
-
L4165
The child write runs; when it has its address,
zio_ddt_child_write_readycopies it into the entry.
Keeping the table on disk
The entries changed in a transaction group must reach the table on disk, which is stored as ZAP objects. A
comment in ddt.c says why that used to be expensive. The fast_dedup feature adds a
log for this, and the dedup_table_quota property can cap the table’s size.
Source The dedup log, ddt.c
DDT: the dedup log
Excerpt of module/zfs/ddt.c, lines
138–142, OpenZFS zfs-2.4.4.
View on GitHub
* Historically, all entries modified on a txg were written back to dedup
* storage objects at the end of every txg. This could cause significant
* overheads, as each entry only takes up a tiny portion of a ZAP leaf node,
* and so required reading the whole node, updating the entry, and writing it
* back. On busy pools, this could add serious IO and memory overheads.-
L138–L142
Without the log, each changed entry was written back at the end of its txg: the whole ZAP leaf read, one entry updated, the leaf written back. With
fast_dedup, changed entries are appended to a log and flushed to the ZAP a little every txg; only tables created with the feature get the log.
Where the encryption values go
A comment in spa.h lays out the encrypted block pointer. The MAC takes half of the checksum,
the salt and the start of the IV take the third address, and the rest of the IV takes the upper half of the
fill count.
Source
blkptr_t, encrypted, spa.h
blkptr_t, encrypted
Excerpt of include/sys/spa.h, lines
250–257, OpenZFS zfs-2.4.4.
View on GitHub
* The MAC occupies half of the checksum space since it serves a very similar
* purpose: to prevent data corruption on disk. The only functional difference
* is that the checksum is used to detect on-disk corruption whether or not the
* encryption key is loaded and the MAC provides additional protection against
* malicious disk tampering. We use the 3rd DVA to store the salt and first
* 64 bits of the IV. As a result encrypted blocks can only have 2 copies
* maximum instead of the normal 3. The last 32 bits of the IV are stored in
* the upper bits of what is usually the fill count. Note that only blocks at-
L250–L254
The MAC takes the second half of the checksum (
zio_crypt_encode_mac_bp); the first half still detects damage, key or not. -
L254–L256
Salt and the first 64 bits of the IV in the third address (
zio_crypt_encode_params_bp), so an encrypted block keeps at most two copies. An embedded block pointer cannot be encrypted: it has no words left. - L256–L257 The last 32 bits of the IV in the upper half of the fill count. The same X bit marks three kinds of block: encrypted, only authenticated, or an indirect block holding a checksum of the MACs below. The cipher is AES-GCM or AES-CCM, with an 8-byte salt, a 12-byte IV and a 16-byte MAC.
Scrub without the key
When it checks a block that uses encryption, zio_checksum_error_impl compares only the first
half of the checksum. Scrub reads blocks without decrypting them, so this comparison is all it needs, and it
works with the key unloaded.
Source
zio_checksum_error_impl, zio_checksum.c
zio_checksum_error_impl
Excerpt of module/zfs/zio_checksum.c, lines
515–525, OpenZFS zfs-2.4.4.
View on GitHub
if (bp != NULL && BP_USES_CRYPT(bp) &&
BP_GET_TYPE(bp) != DMU_OT_OBJSET) {
if (!(ci->ci_flags & ZCHECKSUM_FLAG_DEDUP)) {
actual_cksum.zc_word[0] ^= actual_cksum.zc_word[2];
actual_cksum.zc_word[1] ^= actual_cksum.zc_word[3];
}
actual_cksum.zc_word[2] = 0;
actual_cksum.zc_word[3] = 0;
expected_cksum.zc_word[2] = 0;
expected_cksum.zc_word[3] = 0;- L515–L516 A block pointer that uses encryption, except an objset block, which carries its MACs inside itself.
- L517–L520 For a checksum not made for dedup (fletcher-4, for instance), words 2 and 3 are folded into 0 and 1, as the writer did.
-
L522–L525
The MAC words are ignored on both sides; decryption checks the MAC. Scrub reads raw, so it stops here; a read that must decrypt fails with
EACCESwhen the key is not loaded. The dnode core stays in clear for the same reason.
Source
What the figures leave out
The compressor’s output is an input of the figure, not computed by a real compressor, and the presets are examples. LZ4 stands for every compressor but ZLE, since they all follow the same limit. Compression levels are left out, and so is the rule that stops compressing rewrites from the eighth sync pass on. The pool is plain disks of one ashift, where the minimum allocation and the sector are the same; RAID-Z and mixed pools are not shown.
The dedup figure writes one block per transaction group with one copy, at made-up addresses. Dedup verify, checksum collisions, extra copies and pruning, which removes old entries never duplicated, are left out; the dedup log is only described, above, in “In the code”. Scrub walks the dedup table first, so a block referenced many times is checked once. The code gives no figure for the memory a table takes per terabyte or for a dedup ratio: both depend on the data.
The ciphertext, salt, IV and MAC in the encryption figure are stand-ins, not AES; the checksum is fletcher-4 of the figure’s bytes. The key that encrypts the data is a random master key, stored on disk encrypted by the user’s key, so changing a passphrase re-encrypts no data, and snapshots and clones share it. With dedup, the salt and IV come from the data instead of being random, so encrypted blocks are deduplicated only within one dataset and its clones. Key rotation, which takes a new salt after 400,000,000 blocks, and the encryption of the intent log are left out. Where a block goes next is in Metaslabs and space maps; an incremental send picks blocks by their logical birth, so a block deduplicated after a snapshot is still sent, as send / receive shows.