요약·해설과 원문, 전문 번역을 서로 분리했습니다. API 이름, symbol, source path는 원문 표기를 사용합니다.
1. 요약·해설
원문의 핵심 논리와 kernel programming 관점의 보충 설명입니다. 아래의 전문 번역과는 별도로 작성했습니다.
2. 영어 원문 전체
번역 기준이 된 Linux v6.18.37 원문입니다. 줄 번호는 이 버전의 파일 좌표입니다.
원문 전체 펼치기
===========================================================
LZO stream format as understood by Linux's LZO decompressor
===========================================================
Introduction
============
This is not a specification. No specification seems to be publicly available
for the LZO stream format. This document describes what input format the LZO
decompressor as implemented in the Linux kernel understands. The file subject
of this analysis is lib/lzo/lzo1x_decompress_safe.c. No analysis was made on
the compressor nor on any other implementations though it seems likely that
the format matches the standard one. The purpose of this document is to
better understand what the code does in order to propose more efficient fixes
for future bug reports.
Description
===========
The stream is composed of a series of instructions, operands, and data. The
instructions consist in a few bits representing an opcode, and bits forming
the operands for the instruction, whose size and position depend on the
opcode and on the number of literals copied by previous instruction. The
operands are used to indicate:
- a distance when copying data from the dictionary (past output buffer)
- a length (number of bytes to copy from dictionary)
- the number of literals to copy, which is retained in variable "state"
as a piece of information for next instructions.
Optionally depending on the opcode and operands, extra data may follow. These
extra data can be a complement for the operand (eg: a length or a distance
encoded on larger values), or a literal to be copied to the output buffer.
The first byte of the block follows a different encoding from other bytes, it
seems to be optimized for literal use only, since there is no dictionary yet
prior to that byte.
Lengths are always encoded on a variable size starting with a small number
of bits in the operand. If the number of bits isn't enough to represent the
length, up to 255 may be added in increments by consuming more bytes with a
rate of at most 255 per extra byte (thus the compression ratio cannot exceed
around 255:1). The variable length encoding using #bits is always the same::
length = byte & ((1 << #bits) - 1)
if (!length) {
length = ((1 << #bits) - 1)
length += 255*(number of zero bytes)
length += first-non-zero-byte
}
length += constant (generally 2 or 3)
For references to the dictionary, distances are relative to the output
pointer. Distances are encoded using very few bits belonging to certain
ranges, resulting in multiple copy instructions using different encodings.
Certain encodings involve one extra byte, others involve two extra bytes
forming a little-endian 16-bit quantity (marked LE16 below).
After any instruction except the large literal copy, 0, 1, 2 or 3 literals
are copied before starting the next instruction. The number of literals that
were copied may change the meaning and behaviour of the next instruction. In
practice, only one instruction needs to know whether 0, less than 4, or more
literals were copied. This is the information stored in the <state> variable
in this implementation. This number of immediate literals to be copied is
generally encoded in the last two bits of the instruction but may also be
taken from the last two bits of an extra operand (eg: distance).
End of stream is declared when a block copy of distance 0 is seen. Only one
instruction may encode this distance (0001HLLL), it takes one LE16 operand
for the distance, thus requiring 3 bytes.
.. important::
In the code some length checks are missing because certain instructions
are called under the assumption that a certain number of bytes follow
because it has already been guaranteed before parsing the instructions.
They just have to "refill" this credit if they consume extra bytes. This
is an implementation design choice independent on the algorithm or
encoding.
Versions
0: Original version
1: LZO-RLE
Version 1 of LZO implements an extension to encode runs of zeros using run
length encoding. This improves speed for data with many zeros, which is a
common case for zram. This modifies the bitstream in a backwards compatible way
(v1 can correctly decompress v0 compressed data, but v0 cannot read v1 data).
For maximum compatibility, both versions are available under different names
(lzo and lzo-rle). Differences in the encoding are noted in this document with
e.g.: version 1 only.
Byte sequences
==============
First byte encoding::
0..16 : follow regular instruction encoding, see below. It is worth
noting that code 16 will represent a block copy from the
dictionary which is empty, and that it will always be
invalid at this place.
17 : bitstream version. If the first byte is 17, and compressed
stream length is at least 5 bytes (length of shortest possible
versioned bitstream), the next byte gives the bitstream version
(version 1 only).
Otherwise, the bitstream version is 0.
18..21 : copy 0..3 literals
state = (byte - 17) = 0..3 [ copy <state> literals ]
skip byte
22..255 : copy literal string
length = (byte - 17) = 4..238
state = 4 [ don't copy extra literals ]
skip byte
Instruction encoding::
0 0 0 0 X X X X (0..15)
Depends on the number of literals copied by the last instruction.
If last instruction did not copy any literal (state == 0), this
encoding will be a copy of 4 or more literal, and must be interpreted
like this :
0 0 0 0 L L L L (0..15) : copy long literal string
length = 3 + (L ?: 15 + (zero_bytes * 255) + non_zero_byte)
state = 4 (no extra literals are copied)
If last instruction used to copy between 1 to 3 literals (encoded in
the instruction's opcode or distance), the instruction is a copy of a
2-byte block from the dictionary within a 1kB distance. It is worth
noting that this instruction provides little savings since it uses 2
bytes to encode a copy of 2 other bytes but it encodes the number of
following literals for free. It must be interpreted like this :
0 0 0 0 D D S S (0..15) : copy 2 bytes from <= 1kB distance
length = 2
state = S (copy S literals after this block)
Always followed by exactly one byte : H H H H H H H H
distance = (H << 2) + D + 1
If last instruction used to copy 4 or more literals (as detected by
state == 4), the instruction becomes a copy of a 3-byte block from the
dictionary from a 2..3kB distance, and must be interpreted like this :
0 0 0 0 D D S S (0..15) : copy 3 bytes from 2..3 kB distance
length = 3
state = S (copy S literals after this block)
Always followed by exactly one byte : H H H H H H H H
distance = (H << 2) + D + 2049
0 0 0 1 H L L L (16..31)
Copy of a block within 16..48kB distance (preferably less than 10B)
length = 2 + (L ?: 7 + (zero_bytes * 255) + non_zero_byte)
Always followed by exactly one LE16 : D D D D D D D D : D D D D D D S S
distance = 16384 + (H << 14) + D
state = S (copy S literals after this block)
End of stream is reached if distance == 16384
In version 1 only, to prevent ambiguity with the RLE case when
((distance & 0x803f) == 0x803f) && (261 <= length <= 264), the
compressor must not emit block copies where distance and length
meet these conditions.
In version 1 only, this instruction is also used to encode a run of
zeros if distance = 0xbfff, i.e. H = 1 and the D bits are all 1.
In this case, it is followed by a fourth byte, X.
run length = ((X << 3) | (0 0 0 0 0 L L L)) + 4
0 0 1 L L L L L (32..63)
Copy of small block within 16kB distance (preferably less than 34B)
length = 2 + (L ?: 31 + (zero_bytes * 255) + non_zero_byte)
Always followed by exactly one LE16 : D D D D D D D D : D D D D D D S S
distance = D + 1
state = S (copy S literals after this block)
0 1 L D D D S S (64..127)
Copy 3-4 bytes from block within 2kB distance
state = S (copy S literals after this block)
length = 3 + L
Always followed by exactly one byte : H H H H H H H H
distance = (H << 3) + D + 1
1 L L D D D S S (128..255)
Copy 5-8 bytes from block within 2kB distance
state = S (copy S literals after this block)
length = 5 + L
Always followed by exactly one byte : H H H H H H H H
distance = (H << 3) + D + 1
Authors
=======
This document was written by Willy Tarreau <[email protected]> on 2014/07/19 during an
analysis of the decompression code available in Linux 3.16-rc5, and updated
by Dave Rodgman <[email protected]> on 2018/10/30 to introduce run-length
encoding. The code is tricky, it is possible that this document contains
mistakes or that a few corner cases were overlooked. In any case, please
report any doubt, fix, or proposed updates to the author(s) so that the
document can be updated.
3. 한국어 전문 번역
영어 원문의 문단 순서와 의미를 유지한 전체 번역입니다. 코드, 함수명, symbol과 URL은 원문 표기를 유지합니다.
문서의 범위
1-16이 문서는 specification이 아니다. LZO stream format의 공개 specification은 없는 것으로 보인다. 여기서는 Linux kernel의 LZO decompressor가 이해하는 input format을 설명한다.
분석 대상은 `lib/lzo/lzo1x_decompress_safe.c`다. Compressor나 다른 구현은 분석하지 않았지만 형식은 표준과 일치할 가능성이 높다. 목적은 code 동작을 더 잘 이해해 향후 bug report에 더 효율적인 fix를 제안하는 것이다.
문서가 다루는 구현과 제외 범위다.
===========================================================
LZO stream format as understood by Linux's LZO decompressor
===========================================================
Introduction
============
This is not a specification. No specification seems to be publicly available
for the LZO stream format. This document describes what input format the LZO
decompressor as implemented in the Linux kernel understands. The file subject
of this analysis is lib/lzo/lzo1x_decompress_safe.c. No analysis was made on
the compressor nor on any other implementations though it seems likely that
the format matches the standard one. The purpose of this document is to
better understand what the code does in order to propose more efficient fixes
for future bug reports.
Instruction·operand·state와 길이 encoding
17-80Stream은 instruction, operand, data의 연속이다. Instruction에는 opcode를 나타내는 몇 bit와 operand를 이루는 bit가 들어간다. Operand의 크기와 위치는 opcode 및 이전 instruction이 복사한 literal 수에 따라 달라진다.
Operand는 과거 output buffer인 dictionary에서 data를 복사할 distance, dictionary에서 복사할 byte 수인 length, 다음 instruction을 위한 정보로 `state` variable에 유지할 literal 수를 지정한다. Opcode와 operand에 따라 operand를 확장하는 추가 data 또는 output buffer에 복사할 literal이 뒤따를 수 있다.
Block의 첫 byte는 다른 byte와 encoding이 다르다. 그 앞에는 dictionary가 없으므로 literal 전용으로 최적화된 것으로 보인다.
Length는 operand의 소수 bit에서 시작하는 variable-size 값이다. Bit가 부족하면 추가 byte를 소비해 byte당 최대 255씩 더한다. 따라서 compression ratio는 약 255:1을 넘을 수 없다. `#bits`를 쓰는 공통식은 먼저 `byte & ((1 << #bits) - 1)`을 취하고 0이면 기본 max 값, zero byte 수마다 255, 첫 non-zero byte를 더한 뒤 보통 2나 3인 constant를 더한다.
Dictionary reference의 distance는 output pointer에 상대적이다. 특정 range별 소수 bit로 encode되어 서로 다른 copy instruction이 존재한다. Encoding에 따라 extra byte 하나 또는 little-endian 16-bit 값 `LE16` 두 byte가 붙는다.
Large literal copy를 제외한 instruction 뒤에는 다음 instruction 전에 literal 0~3개가 복사된다. 이 수가 다음 instruction의 의미와 동작을 바꿀 수 있다. 실제로는 0개, 4개 미만, 4개 이상인지 알아야 하는 instruction 하나가 있고 이 정보가 `state`에 저장된다. Immediate literal 수는 보통 instruction 마지막 두 bit지만 distance 같은 extra operand 마지막 두 bit에서 얻기도 한다.
Distance 0인 block copy가 나타나면 stream 종료다. 이 distance는 `0001HLLL` instruction 하나만 encode할 수 있고 distance용 `LE16` operand 하나가 필요해 총 3 byte를 쓴다.
Code의 일부 length check는 의도적으로 생략되어 있다. Instruction parsing 전에 일정 수의 후속 byte가 있음을 이미 보장받았다는 전제로 호출되며 extra byte를 소비하면 그 credit만 다시 채운다. 이는 algorithm이나 encoding과 독립적인 구현 설계 선택이다.
Opcode와 이전 literal state가 operand 해석을 결정한다.
Operand bit가 0일 때 extension byte로 length를 늘린다.
Description
===========
The stream is composed of a series of instructions, operands, and data. The
instructions consist in a few bits representing an opcode, and bits forming
the operands for the instruction, whose size and position depend on the
opcode and on the number of literals copied by previous instruction. The
operands are used to indicate:
- a distance when copying data from the dictionary (past output buffer)
- a length (number of bytes to copy from dictionary)
- the number of literals to copy, which is retained in variable "state"
as a piece of information for next instructions.
Optionally depending on the opcode and operands, extra data may follow. These
extra data can be a complement for the operand (eg: a length or a distance
encoded on larger values), or a literal to be copied to the output buffer.
The first byte of the block follows a different encoding from other bytes, it
seems to be optimized for literal use only, since there is no dictionary yet
prior to that byte.
Lengths are always encoded on a variable size starting with a small number
of bits in the operand. If the number of bits isn't enough to represent the
length, up to 255 may be added in increments by consuming more bytes with a
rate of at most 255 per extra byte (thus the compression ratio cannot exceed
around 255:1). The variable length encoding using #bits is always the same::
length = byte & ((1 << #bits) - 1)
if (!length) {
length = ((1 << #bits) - 1)
length += 255*(number of zero bytes)
length += first-non-zero-byte
}
length += constant (generally 2 or 3)
For references to the dictionary, distances are relative to the output
pointer. Distances are encoded using very few bits belonging to certain
ranges, resulting in multiple copy instructions using different encodings.
Certain encodings involve one extra byte, others involve two extra bytes
forming a little-endian 16-bit quantity (marked LE16 below).
After any instruction except the large literal copy, 0, 1, 2 or 3 literals
are copied before starting the next instruction. The number of literals that
were copied may change the meaning and behaviour of the next instruction. In
practice, only one instruction needs to know whether 0, less than 4, or more
literals were copied. This is the information stored in the <state> variable
in this implementation. This number of immediate literals to be copied is
generally encoded in the last two bits of the instruction but may also be
taken from the last two bits of an extra operand (eg: distance).
End of stream is declared when a block copy of distance 0 is seen. Only one
instruction may encode this distance (0001HLLL), it takes one LE16 operand
for the distance, thus requiring 3 bytes.
.. important::
In the code some length checks are missing because certain instructions
are called under the assumption that a certain number of bytes follow
because it has already been guaranteed before parsing the instructions.
They just have to "refill" this credit if they consume extra bytes. This
is an implementation design choice independent on the algorithm or
encoding.
Version 0과 LZO-RLE
81-94Version 0은 원래 형식이고 version 1은 `LZO-RLE`이다. Version 1은 run-length encoding으로 zero run을 encode해 zero가 많은 zram의 흔한 data에서 속도를 높인다.
Bitstream 변경은 backward compatible이다. Version 1 decompressor는 version 0 data를 올바르게 풀 수 있지만 version 0 decompressor는 version 1 data를 읽지 못한다. 최대 호환성을 위해 두 version은 `lzo`와 `lzo-rle`이라는 별도 이름으로 제공하며 문서의 차이는 `version 1 only`처럼 표시한다.
두 형식의 호환 관계다.
Versions
0: Original version
1: LZO-RLE
Version 1 of LZO implements an extension to encode runs of zeros using run
length encoding. This improves speed for data with many zeros, which is a
common case for zram. This modifies the bitstream in a backwards compatible way
(v1 can correctly decompress v0 compressed data, but v0 cannot read v1 data).
For maximum compatibility, both versions are available under different names
(lzo and lzo-rle). Differences in the encoding are noted in this document with
e.g.: version 1 only.
첫 byte encoding
95-119첫 byte가 0~16이면 일반 instruction encoding을 따른다. Code 16은 비어 있는 dictionary에서 block copy를 뜻하므로 이 위치에서는 항상 invalid다.
첫 byte가 17이고 compressed stream 길이가 versioned bitstream의 최소 길이인 5 byte 이상이면 다음 byte가 bitstream version을 제공한다. 이는 version 1에만 해당한다. 조건을 만족하지 않으면 bitstream version은 0이다.
첫 byte 18~21은 literal 0~3개를 복사한다. `state = byte - 17`로 설정해 그 수만큼 literal을 복사하고 byte를 건너뛴다. 22~255는 길이 4~238의 literal string을 복사하고 `state=4`로 설정해 extra literal을 복사하지 않은 뒤 byte를 건너뛴다.
Block 시작에서만 적용되는 별도 encoding이다.
Byte sequences
==============
First byte encoding::
0..16 : follow regular instruction encoding, see below. It is worth
noting that code 16 will represent a block copy from the
dictionary which is empty, and that it will always be
invalid at this place.
17 : bitstream version. If the first byte is 17, and compressed
stream length is at least 5 bytes (length of shortest possible
versioned bitstream), the next byte gives the bitstream version
(version 1 only).
Otherwise, the bitstream version is 0.
18..21 : copy 0..3 literals
state = (byte - 17) = 0..3 [ copy <state> literals ]
skip byte
22..255 : copy literal string
length = (byte - 17) = 4..238
state = 4 [ don't copy extra literals ]
skip byte
Opcode 0..31과 RLE 확장
120-171`0000XXXX`(0..15)의 의미는 이전 instruction이 복사한 literal 수에 달려 있다. `state==0`이면 길이 4 이상의 긴 literal string을 복사한다. Pattern은 `0000LLLL`, 길이는 `3 + (L ?: 15 + zero_bytes*255 + non_zero_byte)`, state는 4다.
이전 instruction이 literal 1~3개를 복사했다면 같은 `0000DDSS`는 1 kB 이내 dictionary에서 2 byte를 복사한다. Length는 2, state는 S이고 extra byte `HHHHHHHH`가 반드시 이어진다. Distance는 `(H << 2) + D + 1`이다. 두 byte로 두 byte copy를 encode해 절약은 작지만 뒤따르는 literal 수를 공짜로 encode한다.
이전 instruction이 literal 4개 이상을 복사해 `state==4`라면 `0000DDSS`는 2~3 kB distance의 dictionary에서 3 byte를 복사한다. Length는 3, state는 S, extra byte가 하나 뒤따르며 distance는 `(H << 2) + D + 2049`다.
`0001HLLL`(16..31)은 16~48 kB distance의 block을 복사하며 10 byte 미만에 적합하다. Length는 `2 + (L ?: 7 + zero_bytes*255 + non_zero_byte)`다. Extra `LE16`의 상위 14 bit와 H로 distance `16384 + (H << 14) + D`를 만들고 마지막 SS가 state다. Distance가 16384이면 end of stream이다.
Version 1에서는 RLE와 모호해지는 조건 `((distance & 0x803f) == 0x803f) && (261 <= length <= 264)`을 만족하는 block copy를 compressor가 내보내면 안 된다. 또한 distance가 `0xbfff`, 즉 H=1이고 D bit가 모두 1이면 zero run을 encode한다. 이때 네 번째 byte X가 뒤따르고 run length는 `((X << 3) | 00000LLL) + 4`다.
이전 literal state에 따라 같은 bit pattern의 의미가 달라진다.
Instruction encoding::
0 0 0 0 X X X X (0..15)
Depends on the number of literals copied by the last instruction.
If last instruction did not copy any literal (state == 0), this
encoding will be a copy of 4 or more literal, and must be interpreted
like this :
0 0 0 0 L L L L (0..15) : copy long literal string
length = 3 + (L ?: 15 + (zero_bytes * 255) + non_zero_byte)
state = 4 (no extra literals are copied)
If last instruction used to copy between 1 to 3 literals (encoded in
the instruction's opcode or distance), the instruction is a copy of a
2-byte block from the dictionary within a 1kB distance. It is worth
noting that this instruction provides little savings since it uses 2
bytes to encode a copy of 2 other bytes but it encodes the number of
following literals for free. It must be interpreted like this :
0 0 0 0 D D S S (0..15) : copy 2 bytes from <= 1kB distance
length = 2
state = S (copy S literals after this block)
Always followed by exactly one byte : H H H H H H H H
distance = (H << 2) + D + 1
If last instruction used to copy 4 or more literals (as detected by
state == 4), the instruction becomes a copy of a 3-byte block from the
dictionary from a 2..3kB distance, and must be interpreted like this :
0 0 0 0 D D S S (0..15) : copy 3 bytes from 2..3 kB distance
length = 3
state = S (copy S literals after this block)
Always followed by exactly one byte : H H H H H H H H
distance = (H << 2) + D + 2049
0 0 0 1 H L L L (16..31)
Copy of a block within 16..48kB distance (preferably less than 10B)
length = 2 + (L ?: 7 + (zero_bytes * 255) + non_zero_byte)
Always followed by exactly one LE16 : D D D D D D D D : D D D D D D S S
distance = 16384 + (H << 14) + D
state = S (copy S literals after this block)
End of stream is reached if distance == 16384
In version 1 only, to prevent ambiguity with the RLE case when
((distance & 0x803f) == 0x803f) && (261 <= length <= 264), the
compressor must not emit block copies where distance and length
meet these conditions.
In version 1 only, this instruction is also used to encode a run of
zeros if distance = 0xbfff, i.e. H = 1 and the D bits are all 1.
In this case, it is followed by a fourth byte, X.
run length = ((X << 3) | (0 0 0 0 0 L L L)) + 4
Opcode 32..255
172-192`001LLLLL`(32..63)은 16 kB 이내의 작은 block을 복사하며 34 byte 미만에 적합하다. Length는 `2 + (L ?: 31 + zero_bytes*255 + non_zero_byte)`다. Extra `LE16` 하나가 항상 이어지고 distance는 `D+1`, state는 마지막 S bit다.
`01LDDDSS`(64..127)은 2 kB 이내 block에서 3~4 byte를 복사한다. Length는 `3+L`, state는 S이며 extra byte H가 하나 이어져 distance `(H << 3) + D + 1`을 만든다.
`1LLDDDSS`(128..255)은 2 kB 이내 block에서 5~8 byte를 복사한다. Length는 `5+L`, state는 S이고 extra H byte 뒤 distance 식은 `(H << 3) + D + 1`로 같다.
32 이상 opcode의 length와 distance 범위다.
0 0 1 L L L L L (32..63)
Copy of small block within 16kB distance (preferably less than 34B)
length = 2 + (L ?: 31 + (zero_bytes * 255) + non_zero_byte)
Always followed by exactly one LE16 : D D D D D D D D : D D D D D D S S
distance = D + 1
state = S (copy S literals after this block)
0 1 L D D D S S (64..127)
Copy 3-4 bytes from block within 2kB distance
state = S (copy S literals after this block)
length = 3 + L
Always followed by exactly one byte : H H H H H H H H
distance = (H << 3) + D + 1
1 L L D D D S S (128..255)
Copy 5-8 bytes from block within 2kB distance
state = S (copy S literals after this block)
length = 5 + L
Always followed by exactly one byte : H H H H H H H H
distance = (H << 3) + D + 1
저자와 주의사항
193-202Willy Tarreau가 Linux 3.16-rc5 decompression code를 분석하며 2014년 7월 19일 이 문서를 작성했고, Dave Rodgman이 run-length encoding을 도입하도록 2018년 10월 30일 갱신했다.
Code가 까다로워 문서에 오류가 있거나 corner case가 빠졌을 수 있다. 의문, fix, update 제안은 문서를 갱신할 수 있도록 저자에게 보고해야 한다. 연락처는 원문에 보존되어 있다.
구현 분석에서 발견한 차이를 저자에게 되돌리는 흐름이다.
Authors
=======
This document was written by Willy Tarreau <[email protected]> on 2014/07/19 during an
analysis of the decompression code available in Linux 3.16-rc5, and updated
by Dave Rodgman <[email protected]> on 2018/10/30 to introduce run-length
encoding. The code is tricky, it is possible that this document contains
mistakes or that a few corner cases were overlooked. In any case, please
report any doubt, fix, or proposed updates to the author(s) so that the
document can be updated.
요약·해설
lzo.rst:1-202Linux LZO decompressor가 해석하는 first byte, variable length, state 의존 opcode, LZO-RLE zero run과 stream 종료 encoding을 설명합니다.