smb: common: compress: add memory access helpers to compress.h
Subsystems (2)
PATCH v2 1/14 smb: common: compress: add memory access helpers to compress.h
Add memory access helpers + some other common definitions to be used by SMB2 compression (both server and client, and all algorithms).
Changes:
- update affected call paths in lz77.c and compress.c
- update server/compress.* and client/compress.* to include compress.h only
--- fs/smb/client/compress.c | 3 +- fs/smb/client/compress.h | 11 --- fs/smb/common/compress/compress.c | 9 +- fs/smb/common/compress/compress.h | 126 ++++++++++++++++++++++++++++ fs/smb/common/compress/lz77.c | 134 +++++++----------------------- fs/smb/server/compress.c | 3 - 6 files changed, 156 insertions(+), 130 deletions(-)
fs/smb/client/compress.c +1 -2
@@ -18,11 +18,10 @@#include <linux/sort.h> #include "cifsglob.h" -#include "../common/smb2pdu.h" #include "cifsproto.h" #include "smb2proto.h" -#include "../common/compress/lz77.h" +#include "../common/compress/compress.h" #include "compress.h" /*
fs/smb/client/compress.h +0 -11
@@ -17,24 +17,14 @@#include <linux/uio.h> #include <linux/kernel.h> -#include "../common/smb2pdu.h" -#include "../common/compress/compress.h" #include "cifsglob.h" -/* sizeof(smb2_compression_hdr) - sizeof(OriginalPayloadSize) */ -#define SMB_COMPRESS_HDR_LEN 16 -/* sizeof(smb2_compression_payload_hdr) - sizeof(OriginalPayloadSize) */ -#define SMB_COMPRESS_PAYLOAD_HDR_LEN 8 -#define SMB_COMPRESS_MIN_LEN PAGE_SIZE -#ifdef CONFIG_CIFS_COMPRESSION typedef int (*compress_send_fn )(struct TCP_Server_Info *,int ,struct smb_rqst *); -int smb_compress (struct TCP_Server_Info *server,struct smb_rqst *rq,compress_send_fn send_fn);bool should_compress (const struct cifs_tcon *tcon,const struct smb_rqst *rq); -#else /* !CONFIG_CIFS_COMPRESSION */ static inline int smb_compress (void *unused1,void *unused2,void *unused3) {
@@ -45,6 +35,5 @@ static inline bool should_compress(void *unused1, void *unused2) {return false; } -#endif /* !CONFIG_CIFS_COMPRESSION */ #endif /* _SMB_COMPRESS_H */
fs/smb/common/compress/compress.c +1 -8
@@ -7,15 +7,8 @@#include <linux/module.h> #include <linux/overflow.h> #include <linux/string.h> -#include <linux/unaligned.h> #include "compress.h" -#include "lz77.h" - -#define SMB2_COMPRESSION_CHAINED_HDR_LEN \ - offsetof(struct smb2_compression_hdr, CompressionAlgorithm) -#define SMB2_COMPRESSION_PAYLOAD_BASE_LEN \ - (sizeof(struct smb2_compression_payload_hdr) - sizeof(__le32))/* * A NONE payload carries bytes verbatim. Keep both cursors and remaining
@@ -75,7 +68,7 @@ static int smb_decompress_lz77_payload(const u8 **src, u32 *slen, u8 **dst,if (len <sizeof (__le32) || len > *slen)return -EINVAL ; - orig_size =get_unaligned_le32 (*src); + orig_size =mem_read32 (*src);if (orig_size > *dlen)return -EINVAL ;
fs/smb/common/compress/compress.h +126 -0
137 lines not on this page · raw message
fs/smb/common/compress/lz77.c +28 -106
284 lines not on this page · raw message
fs/smb/server/compress.c +0 -3
@@ -10,9 +10,6 @@#include "compress.h" #include "smb_common.h" -#include "../common/compress/lz77.h" - -#define SMB_COMPRESS_MIN_LEN PAGE_SIZE/** * ksmbd_decompress_request() - replace a compressed request with its SMB2 PDU
Signature · 1 line
2.54.0
PATCH v2 2/14 smb: client: compress: rework compression heuristics
- add enum with *COMPRESSIBLE values
- is_compressible() is now check_compressible(), and is called from smb_compress() instead of should_compress(); the latter only does the basic checks (write >= 4K)
- compressibility check now also may return 'MAYBE_COMPRESSIBLE', for cases when even with deeper analysis, it can't return a decisive result
- rewrite Shannon entropy computation (original code was copied over from btrfs, so it carelessly used their parameters)
- divide heuristics checks in stages:
1. check if buffer is filled with same byte (RLE)
2. check if partial RLE (first ~1% of buffer repeats same byte)
3. check whole buffer entropy
4. split buffer in 64k chunks and check entropy and byte distribution (based on hardcoded thresholds)
- remove collect_sample() and collect_step() helpers, heuristics checks are run on the entire buffer now
- remove calc_byte_distribution(), as it's a redundant entropy check
--- fs/smb/client/compress.c | 456 ++++++++++++++++++++++----------------- 1 file changed, 259 insertions(+), 197 deletions(-)
fs/smb/client/compress.c +259 -197
@@ -1,6 +1,6 @@// SPDX-License-Identifier: GPL-2.0-only /* -* Copyright (C) 2024, SUSE LLC +* Copyright (C) 2024-2026, SUSE LLC * * Authors: Enzo Matsumiya <[email protected]> *
@@ -24,242 +24,291 @@#include "../common/compress/compress.h" #include "compress.h" -/* -* The heuristic_*() functions below try to determine data compressibility. +/** +* freq_count() - Count symbols (bytes) frequencies in a buffer. +* @buf: uncompressed buffer +* @len: size of @buf +* @mem: (caller-allocated) auxiliary memory for parallel accumulators +* @count: on exit, set to unique byte count (alphabet size) in @buf * -* Derived from fs/btrfs/compression.c, changing coding style, some parameters, and removing -* unused parts. +* This function counts all bytes' unique count and frequencies. +* Expect @mem to be 1024 * sizeof(u32) long and zeroed. +* Final frequencies will be stored on first 256 elements of @mem. * -* Read that file for better and more detailed explanation of the calculations. +* Function is optimized for OoO CPUs (straightforward iterative count is about 2-3x slower). * -* The algorithms are ran in a collected sample of the input (uncompressed) data. -* The sample is formed of 2K reads in PAGE_SIZE intervals, with a maximum size of 4M. +* Return: max frequency found in @buf. * -* Parsing the sample goes from "low-hanging fruits" (fastest algorithms, likely compressible) -* to "need more analysis" (likely uncompressible). +* (*) This is an adapted version of FSE's https://github.com/Cyan4973/FiniteStateEntropy */ +static noinline u32 freq_count(const u8 *buf, const u32 len, u32 *mem, u32 *count) +{ +const u8 *p = buf, *end = p + len; +u32 c =0 , max_freq =0 ; +u32 v =mem_read32 (p); +u32 *acc1 = mem; +u32 *acc2 = acc1 +256 ; +u32 *acc3 = acc2 +256 ; +u32 *acc4 = acc3 +256 ; + + p +=sizeof (u32); + +/* Count by stripes of 16 bytes. */ +while (p < end -15 ) { +u32 cached = v; + + v =mem_read32 (p); + p +=4 ; + acc1[(u8 )cached]++; + acc2[(u8)(cached>>8 )]++; + acc3[(u8)(cached>>16 )]++; + acc4[(u8)(cached>>24 )]++; + + cached = v; + v =mem_read32 (p); + p +=4 ; + acc1[(u8 )cached]++; + acc2[(u8)(cached>>8 )]++; + acc3[(u8)(cached>>16 )]++; + acc4[(u8)(cached>>24 )]++; + + cached = v; + v =mem_read32 (p); + p +=4 ; + acc1[(u8 )cached]++; + acc2[(u8)(cached>>8 )]++; + acc3[(u8)(cached>>16 )]++; + acc4[(u8)(cached>>24 )]++; + + cached = v; + v =mem_read32 (p); + p +=4 ; + acc1[(u8 )cached]++; + acc2[(u8)(cached>>8 )]++; + acc3[(u8)(cached>>16 )]++; + acc4[(u8)(cached>>24 )]++; + } -struct bucket { -unsigned int count; -}; + p -=4 ; + +/* Count lefotver symbols. */ +while (p < end) + acc1[*p++]++; + +/* +* Combine accumulators + store. +* +* Avoid dereferencing @count here because performance. +*/ +for (v =0 ; v <256 ; v++) { + acc1[v] += acc2[v] + acc3[v] + acc4[v]; + +if (acc1[v]) { + c++; +if (acc1[v] > max_freq) + max_freq = acc1[v]; + } + } -static inline size_t pow4 (size_t n) -{ -return n * n * n * n; +if (count) + *count = c; + +return max_freq; } -/* -* has_low_entropy() - Compute Shannon entropy of the sampled data. -* @bkt: Bytes counts of the sample. -* @slen: Size of the sample. +/** +* calc_entropy() - Compute Shannon entropy of a sample symbols' frequencies. +* @freqs: frequency counts of the sample +* @len: size of the sample +* @scale: scale for final result * -* Return: true if the level (percentage of number of bits that would be required to -* compress the data) is below the minimum threshold. +* @freqs may include zero freq symbols. +* The final sum is multiplied by @factor to fit callers' precision requirements. * -* Note: -* There _is_ an entropy level here that's > 65 (minimum threshold) that would indicate a -* possibility of compression, but compressing, or even further analysing, it would waste so much -* resources that it's simply not worth it. +* Valid results interpretation for @factor == 1: +* < 6: definitely compressible +* 6 - 7: probably compressible, but needs other parameters/heuristics for decisive result +* > 7: probably uncompressible -- other parameters/heuristics _might_ evaluate to "somewhat +* compressible", but usually not much * -* Also Shannon entropy is the last computed heuristic; if we got this far and ended up -* with uncertainty, just stay on the safe side and call it uncompressible. +* Return: approximate number of bits (scaled to @scale) per byte that would be required to +* compress the data. */ -static bool has_low_entropy (struct bucket *bkt,size_t slen) +static __always_inline u32 calc_entropy(const u32 *freqs, const u32 len, const u32 scale) { -const size_t threshold =65 , max_entropy =8 *ilog2 (16 ); -size_t i, p, p2, len, sum =0 ; +const u32 len2 =ilog2 (len); +size_t i, p, sum =0 ; - len =ilog2 (pow4 (slen)); - -for (i =0 ; i <256 && bkt[i].count >0 ; i++) { - p = bkt[i].count; - p2 =ilog2 (pow4 (p)); - sum += p * (len - p2); +for (i =0 ; i <256 ; i++) { +/* 0 freq won't skew the results (ilog2(n) also returns 0 if n < 2) */ + p = freqs[i]; + sum += p * (len2 -ilog2 (p)); } - sum /= slen; - -return ((sum *100 / max_entropy) <= threshold); +return (sum * scale / len); } -#define BYTE_DIST_BAD 0 -#define BYTE_DIST_GOOD 1 -#define BYTE_DIST_MAYBE 2/* -* calc_byte_distribution() - Compute byte distribution on the sampled data. -* @bkt: Byte counts of the sample. -* @slen: Size of the sample. -* -* Return: -* BYTE_DIST_BAD: A "hard no" for compression -- a computed uniform distribution of -* the bytes (e.g. random or encrypted data). -* BYTE_DIST_GOOD: High probability (normal (Gaussian) distribution) of the data being -* compressible. -* BYTE_DIST_MAYBE: When computed byte distribution resulted in "low > n < high" -* grounds. has_low_entropy() should be used for a final decision. +* Heuristic limits based on 64k blocks. */ -static int calc_byte_distribution (struct bucket *bkt,size_t slen) -{ -const size_t low =64 , high =200 , threshold = slen *90 /100 ; -size_t sum =0 ; -int i; - -for (i =0 ; i < low; i++) - sum += bkt[i].count; - -if (sum > threshold) -return BYTE_DIST_BAD ; - -for (; i < high && bkt[i].count >0 ; i++) { - sum += bkt[i].count; -if (sum > threshold) -break ; - } - -if (i <= low) -return BYTE_DIST_GOOD ; - -if (i >= high) -return BYTE_DIST_BAD ; - -return BYTE_DIST_MAYBE ; -} - -static bool is_mostly_ascii (const struct bucket *bkt) -{ -size_t count =0 ; -int i; - -for (i =0 ; i <256 ; i++) -if (bkt[i].count >0 ) -/* Too many non-ASCII (0-63) bytes. */ -if (++count >64 ) -return false; - -return true; -} - -static bool has_repeated_data (const u8 *sample,size_t len) -{ -size_t s = len /2 ; - -return (!memcmp (&sample[0 ], &sample[s], s)); -} - -static int cmp_bkt (const void *_a,const void *_b) -{ -const struct bucket *a = _a, *b = _b; - -/* Reverse sort. */ -if (a->count > b->count) -return -1 ; - -return 1 ; -} +#define HEURISTIC_CHUNK_SIZE SZ_64K +static const u32 heuristic_freq_hi =8000 ; +static const u32 heuristic_freq_lo =5000 ; +static const u32 heuristic_entropy_hi =800 ; +static const u32 heuristic_entropy_mid =700 ; +static const u32 heuristic_entropy_lo =600 ; +static const u32 heuristic_alphabet_hi =256 ; +static const u32 heuristic_alphabet_lo =128 ; + +enum { +UNCOMPRESSIBLE =0 , +COMPRESSIBLE , +MAYBE_COMPRESSIBLE , +};/* -* Collect some 2K samples with 2K gaps between. +* Computes entropy and byte dominance of @buf, on a 64k block basis. +* +* Return: one of the *COMPRESSIBLE values */ -static int collect_sample (const struct iov_iter *source,ssize_t max,u8 *sample) +static int check_compressible_chunks (const u8 *buf,const u32 len,u32 *freqs) { -struct iov_iter iter = *source; -size_t s =0 ; - -while (iov_iter_count (&iter) >=SZ_2K ) { -size_t part =umin (umin (iov_iter_count (&iter),SZ_2K ), max); -size_t n; - - n =copy_from_iter (sample + s, part, &iter); -if (n != part) -return -EFAULT ; +int score =0 , boost =0 , n =0 ; +const u32 nsamples = (len /HEURISTIC_CHUNK_SIZE ); +const s32 half_samples = nsamples /2 ; +const u8 *end = buf + len; + +while (buf < end) { +u32 alphabet =0 ; +const u32 max_freq =freq_count (buf,HEURISTIC_CHUNK_SIZE , freqs, &alphabet); +const u32 entropy =calc_entropy (freqs,HEURISTIC_CHUNK_SIZE ,100 ); + +if (entropy < heuristic_entropy_mid && max_freq > heuristic_freq_hi) + score++; +else if (entropy >= heuristic_entropy_mid && max_freq < heuristic_freq_lo) + score--; + +if (alphabet < heuristic_alphabet_hi) { + boost++; +if (alphabet < heuristic_alphabet_lo) + boost++; + } + +/* Reward/penalty for really good/bad entropy. */ +if (entropy > heuristic_entropy_hi) + boost -=2 ; +else if (entropy < heuristic_entropy_lo) + boost +=2 ; + +memset (freqs,0 ,sizeof (u32) *1024 ); + buf +=HEURISTIC_CHUNK_SIZE ; + n++; + +if (end - buf <HEURISTIC_CHUNK_SIZE ) +break ; + } - s += n; - max -= n; +/* Check how much the heuristics above impacted (at least) half of @buf. */ +if (score + boost >0 && score + boost < half_samples) +return MAYBE_COMPRESSIBLE ; -if (iov_iter_count (&iter) <PAGE_SIZE -SZ_2K ) -break ; +if (score + boost > -half_samples) { +if (score > half_samples || score + boost > half_samples) +return COMPRESSIBLE ; -iov_iter_advance (&iter,SZ_2K ); +return MAYBE_COMPRESSIBLE ; } -return s; +return UNCOMPRESSIBLE ; }/* -* is_compressible() - Determines if a chunk of data is compressible. -* @data: Iterator containing uncompressed data. +* Check @buf heuristics (entropy/distribution) to determine its compressibility level. +* +* Tests shows that this function is quite reliable in predicting data compressibility, matching +* very close with the behaviour of LZ77 compression success and failures. * -* Return: true if @data is compressible, false otherwise. +* This function allocates memory, callers must check for -ENOMEM. * -* Tests shows that this function is quite reliable in predicting data compressibility, -* matching close to 1:1 with the behaviour of LZ77 compression success and failures. +* Return: one of the *COMPRESSIBLE values on success, -errno otherwise. */ -static bool is_compressible (const struct iov_iter *data) +static __must_check int check_compressible (const u8 *buf,u32 len) { -const size_t read_size =SZ_2K , bkt_size =256 , max =SZ_4M ; -struct bucket *bkt =NULL ; -size_t len; -u8 *sample; -bool ret = false; -int i; - -/* Preventive double check -- already checked in should_compress(). */ - len =iov_iter_count (data); -if (unlikely (len < read_size)) -return ret; - -if (len - read_size > max) - len = max; - - sample =kvzalloc (len,GFP_KERNEL ); -if (!sample) { -WARN_ON_ONCE (1 ); - -return ret; - } - -/* Sample 2K bytes per page of the uncompressed data. */ - i =collect_sample (data, len, sample); -if (i <=0 ) { -WARN_ON_ONCE (1 ); - - goto out; - } +u32 entropy, *freqs, rle =0 , rle_boost =0 ; +const u32 min_reps = (len /100 );/* ~1% of @len */ +const u8 *p; +int ret; - len = i; - ret = true; +if (unlikely (!buf || !len)) +return -EINVAL ; -if (has_repeated_data (sample, len)) - goto out; +/* Stage 1: RLE (@buf is filled with same byte, a.k.a Run-Length Encoding). */ + p =memchr_inv (buf, *buf, len); +if (!p) +/* Full RLE */ +return COMPRESSIBLE ; - bkt =kzalloc_objs (*bkt, bkt_size); -if (!bkt) { -WARN_ON_ONCE (1 ); - ret = false; +/* Stage 2: partial/starting RLE (repeating bytes cover are at least @min_reps long). */ +if (p - buf >= min_reps) { + rle = (p - buf); - goto out; + buf += rle; + len -= rle; } -for (i =0 ; i < len; i++) - bkt[sample[i]].count++; - -if (is_mostly_ascii (bkt)) - goto out; - -/* Sort in descending order */ -sort (bkt, bkt_size,sizeof (*bkt), cmp_bkt,NULL ); - - i =calc_byte_distribution (bkt, len); -if (i !=BYTE_DIST_MAYBE ) { - ret = !!i; - - goto out; +/* +* This might happen if: +* 1. original @len was <= chunk size +* 2. remaining @len after a long partial RLE +* +* In either case, we call it compressible (for (1), it's just faster to let compressor +* handle it). +*/ +if (len <=HEURISTIC_CHUNK_SIZE ) +return COMPRESSIBLE ; + + freqs =kzalloc_objs (*freqs,1024 ); +if (!freqs) +return -ENOMEM ; + +/* +* Stage 3: whole buffer entropy check (decisive results if too high or too low). +* +* Don't care about max freq or alphabet size here. +*/ + (void )freq_count (buf, len, freqs,NULL ); + entropy =calc_entropy (freqs, len,1 ); +/* +* Reduce entropy based on @rle coverage. +* Its usage is similar to decrementing @entropy for every 1/4 of @buf covered by +* repeating bytes. +* Apply boost only if @entropy < 8 and @rle_boost > 0. +*/ + rle_boost =umin (rle >> (ilog2 (len) -1 ), entropy); + ret =MAYBE_COMPRESSIBLE ; + +if (entropy >=8 ) + ret =UNCOMPRESSIBLE ; +else if (entropy <6 || (rle_boost && entropy - rle_boost <=6 )) + ret =COMPRESSIBLE ; + +/* +* Stage 4: if no decisive result yet, break down buffer into 64k chunks for more detailed +* analysis (requires >= 2 chunks). +* +* Note that it's quite common to go from MAYBE_COMPRESSIBLE -> COMPRESSIBLE after +* per-chunk analysis. +* +* OTOH, getting MAYBE_COMPRESSIBLE again here really means 'uncompressible' for +* compressors that focus on speed (e.g. LZ77). +* Compressors focused on compression ratio might still get good compression though. +*/ +if (ret ==MAYBE_COMPRESSIBLE && len >=2 *HEURISTIC_CHUNK_SIZE ) { +memset (freqs,0 ,sizeof (u32) *1024 ); + ret =check_compressible_chunks (buf, len, freqs); } - ret =has_low_entropy (bkt, len); -out: -kvfree (sample); -kfree (bkt); +kfree (freqs);return ret; }
@@ -275,7 +324,6 @@ static bool is_compressible(const struct iov_iter *data)* - server has enabled compression for the share * - it's a read or write request * - (write only) request length is >= SMB_COMPRESS_MIN_LEN -* - (write only) is_compressible() returns 1 * * Return false otherwise. */
@@ -295,10 +343,7 @@ bool should_compress(const struct cifs_tcon *tcon, const struct smb_rqst *rq)if (shdr->Command ==SMB2_WRITE ) {const struct smb2_write_req *wreq = rq->rq_iov->iov_base; -if (le32_to_cpu (wreq->Length) <SMB_COMPRESS_MIN_LEN ) -return false; - -return is_compressible (&rq->rq_iter); +return (le32_to_cpu (wreq->Length) >=SMB_COMPRESS_MIN_LEN ); }return (shdr->Command ==SMB2_READ );
@@ -332,6 +377,23 @@ int smb_compress(struct TCP_Server_Info *server, struct smb_rqst *rq, compress_s goto err_free; } +/* +* Even though smb_lz77_compress() runs quite fast on uncompressible data (it ends up +* usually just parsing the input buffer), this is much faster. +* +* So to keep things balanced (compress performance vs prediction accuracy), let's drop the +* uncompressible low-hanging fruits here and let smb_lz77_compress() handle the +* exceptions/rare cases. +*/ + ret =check_compressible (src, slen); + +/* XXX: do something with MAYBE_COMPRESSIBLE */ +if (ret !=COMPRESSIBLE ) { +if (ret >=0 ) + ret =send_fn (server,1 , rq); + goto err_free; + } + dlen =smb_lz77_compressed_alloc_size (slen); dst =kvzalloc (dlen,GFP_KERNEL );if (!dst) {
Signature · 1 line
2.54.0
PATCH v2 3/14 smb: client: compress: disable compression on reconnects
In reply to Enzo MatsumiyaWindows Server resets the connection if it gets a compressed request that it couldn't decompress.
Some encoded payloads might decode differently on the server, or vice-versa, due to different implementation details (not really a bug), or an actual bug on either implementation.
To prevent an infinite retry on such failed sends, simply disable compression for that server when a reconnect is about to happen.
Other:
- add disable_compression() helper (cifsglob.h)
--- fs/smb/client/cifsglob.h | 20 ++++++++++++++++++++ fs/smb/client/connect.c | 11 +++++++++++ 2 files changed, 31 insertions(+)
fs/smb/client/cifsglob.h +20 -0
@@ -835,6 +835,26 @@ struct TCP_Server_Info {char dns_dom[CIFS_MAX_DOMAINNAME_LEN +1 ]; }; +static __always_inline void disable_compression(struct TCP_Server_Info *server) +{ +/* +* should_compress() checks the primary server compression state, so disable it only +* on primary server. +*/ +if (SERVER_IS_CHAN (server)) + server = server->primary_server; + +if (server->compression.enabled) { +pr_warn ("%s: disabling compression (failsafe)\n" , server->hostname); + +/* +* We must keep ->requested as true, in case new channels are added, so server +* capabilities are kept in sync (even though no further compression will be done). +*/ + server->compression.enabled = false; + } +} +static inline bool is_smb1 (const struct TCP_Server_Info *server) {return server->vals->protocol_id ==SMB10_PROT_ID ;
fs/smb/client/connect.c +11 -0
@@ -401,6 +401,17 @@ static int __cifs_reconnect(struct TCP_Server_Info *server,try_to_freeze ();cifs_server_lock (server); +/* +* Servers might disconnect us when they can't decompress a compressed request we +* sent. +* When this happens, as a failsafe measure, disable compression entirely to avoid +* an endless retry. +* +* TODO: implement a more flexible alternative, e.g. identify and retry sending +* the failed request uncompressed, without having to disable compression entirely. +*/ +disable_compression (server); +if (!cifs_swn_set_server_dstaddr (server) && !SERVER_IS_CHAN (server)) {/* resolve the hostname again to make sure that IP address is up-to-date */
Signature · 1 line
2.54.0
PATCH v2 4/14 smb: client: sync compression settings between channels
In reply to Enzo MatsumiyaIf there are any errors or inconsistencies on negotiated compression settings for a channel, disable compression globally (primary server).
--- fs/smb/client/smb2pdu.c | 95 ++++++++++++++++++++++++++++++----------- 1 file changed, 71 insertions(+), 24 deletions(-)
fs/smb/client/smb2pdu.c +71 -24
@@ -832,56 +832,103 @@ static void decode_preauth_context(struct smb2_preauth_neg_context *ctxt)static void decode_compress_ctx (struct TCP_Server_Info *server,struct smb2_compression_capabilities_context *ctxt) { +struct TCP_Server_Info *pserver;unsigned int len =le16_to_cpu (ctxt->DataLength);unsigned int count, i; +bool pattern, chained; +__le16 alg; - server->compression.enabled = false; - server->compression.chained = false; - server->compression.pattern = false; - server->compression.alg =SMB3_COMPRESS_NONE ; +/* +* This is a bug and should never happen -- we're either on first Negotiate (mount) or +* reconnecting (disable_compression() was called), where ->enabled is false in both cases. +*/ +if (WARN_ON_ONCE (server->compression.enabled)) { +cifs_dbg (VFS ,"compression enabled unexpectedly\n" ); + goto out; + }/* +* Do not overwrite any settings until we've fully validated them. +* * Caller checked that DataLength remains within SMB boundary. We still * need to confirm that one CompressionAlgorithms member is accounted * for. */ -if (len <10 ) { -pr_warn_once ("server sent bad compression cntxt\n" ); -return ; +if (unlikely (len <10 )) { +cifs_dbg (VFS ,"server sent bad compression context (len %u)\n" , len); + goto out; } count =le16_to_cpu (ctxt->CompressionAlgorithmCount); -if (!count || count >ARRAY_SIZE (ctxt->CompressionAlgorithms) || - len <8 + count *sizeof (__le16)) { -pr_warn_once ("invalid SMB3 compress algorithm count\n" ); -return ; +if (unlikely (!count || count >ARRAY_SIZE (ctxt->CompressionAlgorithms) || + len <8 + count *sizeof (__le16))) { +cifs_dbg (VFS ,"invalid SMB3 compress algorithm count (%u)\n" , count); + goto out; } -if (ctxt->Flags !=SMB2_COMPRESSION_CAPABILITIES_FLAG_NONE && - ctxt->Flags !=SMB2_COMPRESSION_CAPABILITIES_FLAG_CHAINED ) { -pr_warn_once ("invalid SMB3 compression flags\n" ); -return ; +if (unlikely (ctxt->Flags !=SMB2_COMPRESSION_CAPABILITIES_FLAG_NONE && + ctxt->Flags !=SMB2_COMPRESSION_CAPABILITIES_FLAG_CHAINED )) { +cifs_dbg (VFS ,"invalid SMB3 compression flags 0x%x\n" , ctxt->Flags); + goto out; } + alg =SMB3_COMPRESS_NONE ; + chained = false; + pattern = false; +for (i =0 ; i < count; i++) {/* Record the intersection supported by the shared SMB codec. */ if (ctxt->CompressionAlgorithms[i] ==SMB3_COMPRESS_LZ77 ) - server->compression.alg =SMB3_COMPRESS_LZ77 ; + alg =SMB3_COMPRESS_LZ77 ;else if (ctxt->CompressionAlgorithms[i] ==SMB3_COMPRESS_PATTERN ) - server->compression.pattern = true; + pattern = true; + } + +if (unlikely (alg !=SMB3_COMPRESS_LZ77 )) { +cifs_dbg (VFS ,"invalid LZ algorithm negotiated 0x%x\n" , alg); + goto out; } -if (server->compression.alg !=SMB3_COMPRESS_LZ77 ) -return ;/* * Pattern_V1 cannot appear in an unchained transform even if a broken * peer lists it in the algorithm array. */ - server->compression.chained = - ctxt->Flags ==SMB2_COMPRESSION_CAPABILITIES_FLAG_CHAINED ; -if (!server->compression.chained) - server->compression.pattern = false; - server->compression.enabled = true; + chained = (ctxt->Flags ==SMB2_COMPRESSION_CAPABILITIES_FLAG_CHAINED ); +if (!chained) + pattern = false; + +/* +* Regardless of that, if @server is a channel, we must check if the negotiated parameters +* match the primary server ones. If there's a mismatch and compression is enabled in +* primary server, disable it (to avoid operations with mixed settings). +*/ + pserver = server; +if (SERVER_IS_CHAN (server)) { + pserver = server->primary_server; +if (unlikely (chained != pserver->compression.chained || + pattern != pserver->compression.pattern || + alg != pserver->compression.alg)) { +cifs_dbg (VFS ,"channel compression settings mismatch\n" ); + goto out; + } + } + +/* +* We may only enable compression for @server if we entered this function with @pserver +* ->alg == NONE and ->enabled == false, otherwise it means disable_compression() was +* called. +*/ +if (!pserver->compression.enabled && pserver->compression.alg ==SMB3_COMPRESS_NONE ) + server->compression.enabled = true; + + server->compression.chained = chained; + server->compression.pattern = pattern; + server->compression.alg = alg; + +/* Compression was just enabled, or previously disabled on primary server, just leave */ +return ; +out: +disable_compression (server); } static int decode_encrypt_ctx(struct TCP_Server_Info *server,
Signature · 1 line
2.54.0
PATCH v2 5/14 smb: common: compress: use a single function for chained and unchained compression
In reply to Enzo MatsumiyaRename smb_compression_compress_chained() to smb_compression_compress(), and handle both unchained and chained compressions there, similar to smb_compression_decompress().
Changes:
- add @chained arg to smb_compression_compress(), so it's possible to handle (chained && !allow_pattern) cases
- drop smb_compression_builder::first field -- add all payload headers with Flags = "NONE", set flag "CHAINED" at the end on the starting header
- drop @orig_size from smb_compression_add_payload(), compute it directly on smb_compression_add_lz77() instead
- adjust smb_compression_compress() call in server/compress.c
- TODO: rework the code around to fully use the single function
--- fs/smb/common/compress/compress.c | 119 +++++++++++++++++++----------- fs/smb/common/compress/compress.h | 6 +- fs/smb/server/compress.c | 11 +-- 3 files changed, 83 insertions(+), 53 deletions(-)
fs/smb/common/compress/compress.c +74 -45
@@ -213,7 +213,6 @@ EXPORT_SYMBOL_GPL(smb_compression_decompress);struct smb_compression_builder {u8 *pos;u32 remaining; -bool first; };/*
@@ -222,28 +221,22 @@ struct smb_compression_builder {*/ static struct smb2_compression_payload_hdr *smb_compression_add_payload (struct smb_compression_builder *builder, -__le16 alg,u32 payload_len,bool orig_size) +__le16 alg,u32 payload_len) {struct smb2_compression_payload_hdr *payload; -u32 hdr_len =SMB2_COMPRESSION_PAYLOAD_BASE_LEN ;u32 total_len; -if (orig_size) - hdr_len +=sizeof (payload->OriginalPayloadSize); -if (check_add_overflow (hdr_len, payload_len, &total_len) || +if (check_add_overflow (payload_len,SMB2_COMPRESSION_PAYLOAD_BASE_LEN , &total_len) || total_len > builder->remaining)return NULL ; payload = (struct smb2_compression_payload_hdr *)builder->pos; payload->CompressionAlgorithm = alg; - payload->Flags =cpu_to_le16 (builder->first ? -SMB2_COMPRESSION_FLAG_CHAINED :SMB2_COMPRESSION_FLAG_NONE ); - payload->Length =cpu_to_le32 (payload_len + - (orig_size ?sizeof (payload->OriginalPayloadSize) :0 )); - - builder->pos += hdr_len; - builder->remaining -= hdr_len; - builder->first = false; + payload->Flags =cpu_to_le16 (SMB2_COMPRESSION_FLAG_NONE ); + payload->Length =cpu_to_le32 (payload_len); + + builder->pos +=SMB2_COMPRESSION_PAYLOAD_BASE_LEN ; + builder->remaining -=SMB2_COMPRESSION_PAYLOAD_BASE_LEN ;return payload; }
@@ -252,8 +245,7 @@ static int smb_compression_add_pattern(struct smb_compression_builder *builder, {struct smb2_compression_pattern_v1 *payload; -if (!smb_compression_add_payload (builder,SMB3_COMPRESS_PATTERN , -sizeof (*payload), false)) +if (!smb_compression_add_payload (builder,SMB3_COMPRESS_PATTERN ,sizeof (*payload)))return -ENOSPC ; payload = (struct smb2_compression_pattern_v1 *)builder->pos;
@@ -269,7 +261,7 @@ static int smb_compression_add_pattern(struct smb_compression_builder *builder,static int smb_compression_add_none (struct smb_compression_builder *builder,const u8 *src,u32 len) { -if (!smb_compression_add_payload (builder,SMB3_COMPRESS_NONE , len, false)) +if (!smb_compression_add_payload (builder,SMB3_COMPRESS_NONE , len))return -ENOSPC ;memcpy (builder->pos, src, len);
@@ -279,36 +271,47 @@ static int smb_compression_add_none(struct smb_compression_builder *builder, }static int smb_compression_add_lz77 (struct smb_compression_builder *builder, -const u8 *src,u32 len) +const u8 *src,u32 len,bool chained) {struct smb2_compression_payload_hdr *payload; -u32 comp_len; +u32 comp_len, offset = chained ?sizeof (payload->OriginalPayloadSize) :0 ;int rc;if (builder->remaining <=sizeof (*payload))return -ENOSPC ; - comp_len = builder->remaining -sizeof (*payload); - payload =smb_compression_add_payload (builder,SMB3_COMPRESS_LZ77 , - comp_len, true); +/* +* Always add LZ data as a payload, regardless of @chained. +* The only difference is whether offset (sizeof(payload->OriginalPayloadSize)) is +* accounted for. +* Also, use @payload_len == 0 as we don't know compressed size yet. +*/ + payload =smb_compression_add_payload (builder,SMB3_COMPRESS_LZ77 ,0 );if (!payload)return -ENOSPC ; + builder->pos += offset; + builder->remaining -= offset; + comp_len = builder->remaining; rc =smb_lz77_compress (src, len, builder->pos, &comp_len);if (rc)return rc; - payload->Length =cpu_to_le32 (comp_len + -sizeof (payload->OriginalPayloadSize)); - payload->OriginalPayloadSize =cpu_to_le32 (len); +/* These are only set when @chained. */ +if (chained) { + payload->Length =cpu_to_le32 (comp_len + offset); + payload->OriginalPayloadSize =cpu_to_le32 (len); + } + builder->pos += comp_len; builder->remaining -= comp_len;return 0 ; }/** -* smb_compression_compress_chained() - build a chained SMB2 transform +* smb_compression_compress() - build a SMB2 compression transform (chained optional) * @alg: negotiated general-purpose compression algorithm +* @chained: is chained compression was negotiated * @allow_pattern: whether Pattern_V1 was negotiated * @src: complete uncompressed SMB2 message * @slen: size of @src
@@ -325,12 +328,12 @@ static int smb_compression_add_lz77(struct smb_compression_builder *builder,* * Return: 0 on success, otherwise a negative errno. */ -int smb_compression_compress_chained (__le16 alg,bool allow_pattern, -const void *src,u32 slen, -void *dst,u32 *dlen) +int smb_compression_compress (__le16 alg,bool chained,bool allow_pattern, +const void *src,u32 slen, +void *dst,u32 *dlen) { -struct smb2_compression_hdr *hdr = dst;struct smb_compression_builder builder; +struct smb2_compression_hdr *hdr;const u8 *input = src;u32 forward =0 , backward =0 , middle_len;int rc;
@@ -339,13 +342,21 @@ int smb_compression_compress_chained(__le16 alg, bool allow_pattern, *dlen <= SMB2_COMPRESSION_CHAINED_HDR_LEN || !slen)return -EINVAL ; - hdr->ProtocolId =SMB2_COMPRESSION_TRANSFORM_ID ; - hdr->OriginalCompressedSegmentSize =cpu_to_le32 (slen); +/* Note that the below is a bug, but (chained && !allow_pattern) is a valid combination */ +if (WARN_ON_ONCE (!chained && allow_pattern)) +return -EINVAL ; + +/* +* Offset @dst for both unchained and chained cases, header is setup at the end. +* If unchained, we must align @dst to the end of compression header. +*/ builder.pos = (u8 *)dst +SMB2_COMPRESSION_CHAINED_HDR_LEN ; builder.remaining = *dlen -SMB2_COMPRESSION_CHAINED_HDR_LEN ; - builder.first = true; -if (allow_pattern && slen >32 ) { +if (!chained || !allow_pattern) + goto do_lz; + +if (slen >32 ) {for (forward =1 ; forward < slen; forward++) {if (input[forward] != input[0 ])break ;
@@ -366,18 +377,22 @@ int smb_compression_compress_chained(__le16 alg, bool allow_pattern,if (rc)return rc; } - +do_lz: + rc = -ENODATA ; middle_len = slen - forward - backward; -if (middle_len >1024 ) - rc =smb_compression_add_lz77 (&builder, input + forward, - middle_len); -else if (middle_len) - rc =smb_compression_add_none (&builder, - input + forward, middle_len); -else - rc =0 ; -if (rc) +if (middle_len >1024 || !chained) + rc =smb_compression_add_lz77 (&builder, input + forward, middle_len, chained); +else if (middle_len && allow_pattern) + rc =smb_compression_add_none (&builder, input + forward, middle_len); + +if (rc) { +/* These will allow callers to send uncompressed request in case of small input */ +if (rc == -ENODATA ) { + *dlen = slen; + rc =0 ; + }return rc; + }if (backward) { rc = smb_compression_add_pattern(&builder, input[slen - 1],
@@ -387,6 +402,20 @@ int smb_compression_compress_chained(__le16 alg, bool allow_pattern, } *dlen = builder.pos - (u8 *)dst; + + hdr = dst; + hdr->ProtocolId =SMB2_COMPRESSION_TRANSFORM_ID ; + hdr->OriginalCompressedSegmentSize =cpu_to_le32 (slen); + +if (chained) { +/* Overwrite the first payload->Flags, the other fields must stay as is. */ + hdr->Flags =cpu_to_le16 (SMB2_COMPRESSION_FLAG_CHAINED ); + }else { + hdr->CompressionAlgorithm = alg; + hdr->Flags =cpu_to_le16 (SMB2_COMPRESSION_FLAG_NONE ); + hdr->Offset =cpu_to_le32 (0 ); + } +return 0 ; } -EXPORT_SYMBOL_GPL (smb_compression_compress_chained); +EXPORT_SYMBOL_GPL (smb_compression_compress);
fs/smb/common/compress/compress.h +3 -3
@@ -147,8 +147,8 @@ static __always_inline bool smb_compress_alg_valid(__le16 alg, bool valid_none)int smb_compression_decompress (__le16 alg,bool allow_chained,const void *src,u32 slen,void *dst,u32 dlen); -int smb_compression_compress_chained (__le16 alg,bool allow_pattern, -const void *src,u32 slen, -void *dst,u32 *dlen); +int smb_compression_compress (__le16 alg,bool chained,bool allow_pattern, +const void *src,u32 slen, +void *dst,u32 *dlen);#endif /* _COMMON_SMB_COMPRESS_H */
fs/smb/server/compress.c +6 -5
@@ -145,11 +145,12 @@ int ksmbd_compress_response(struct ksmbd_work *work)if (work->conn->compress_chained) { dst_len = max_dst_len; - rc =smb_compression_compress_chained (SMB3_COMPRESS_LZ77 , - work->conn->compress_pattern, - src, src_len, - out +sizeof (__be32), - &dst_len); + rc =smb_compression_compress (SMB3_COMPRESS_LZ77 , + work->conn->compress_chained, + work->conn->compress_pattern, + src, src_len, + out +sizeof (__be32), + &dst_len);if (rc == -EMSGSIZE || dst_len >= src_len) { rc =0 ; goto out;
Signature · 1 line
2.54.0
PATCH v2 6/14 smb: common: compress: drop 'allow_chained' arg from smb_decompress_chained()
In reply to Enzo MatsumiyaThat arg is redundant as the function is already only called when chaining was detected on header.
Also 'NONE' payloads are allowed as the first payload when chained, so check for it only if not chained.
Other changes:
- remove 'first' variable, check only the first payload->Flags == CHAINED, then == NONE in the loop
- code style changes
--- fs/smb/common/compress/compress.c | 72 ++++++++++++++++++------------- 1 file changed, 41 insertions(+), 31 deletions(-)
fs/smb/common/compress/compress.c +41 -31
@@ -87,8 +87,7 @@ static int smb_decompress_lz77_payload(const u8 **src, u32 *slen, u8 **dst,return 0 ; } -static int smb_decompress_chained (__le16 alg,bool allow_chained, -const struct smb2_compression_hdr *hdr, +static int smb_decompress_chained (__le16 alg,const struct smb2_compression_hdr *hdr,u32 slen,void *dst,u32 dlen) {const struct smb2_compression_payload_hdr *payload;
@@ -97,10 +96,17 @@ static int smb_decompress_chained(__le16 alg, bool allow_chained,u32 remaining = slen -SMB2_COMPRESSION_CHAINED_HDR_LEN ;u8 *out = dst;u32 out_remaining = dlen; -bool first = true;int rc; -if (!allow_chained || orig_size != dlen) +if (orig_size != dlen) +return -EINVAL ; + + payload = (const struct smb2_compression_payload_hdr *)src; +/* +* CHAINED marks only the first payload. Requiring NONE on every +* later payload rejects ambiguous or independently chained data. +*/ +if (unlikely (payload->Flags !=cpu_to_le16 (SMB2_COMPRESSION_FLAG_CHAINED )))return -EINVAL ;/*
@@ -110,43 +116,40 @@ static int smb_decompress_chained(__le16 alg, bool allow_chained,*/ while (remaining) {__le16 payload_alg; -__le16 flags;u32 len;if (remaining <SMB2_COMPRESSION_PAYLOAD_BASE_LEN )return -EINVAL ; - payload = (const struct smb2_compression_payload_hdr *)src; payload_alg = payload->CompressionAlgorithm; - flags = payload->Flags; - len =le32_to_cpu (payload->Length); - -/* -* CHAINED marks only the first payload. Requiring NONE on every -* later payload rejects ambiguous or independently chained data. -*/ -if ((first && flags !=cpu_to_le16 (SMB2_COMPRESSION_FLAG_CHAINED )) || - (!first && flags !=cpu_to_le16 (SMB2_COMPRESSION_FLAG_NONE ))) +if (unlikely (!smb_compress_alg_valid (payload_alg, true)))return -EINVAL ; + len =le32_to_cpu (payload->Length); src +=SMB2_COMPRESSION_PAYLOAD_BASE_LEN ; remaining -=SMB2_COMPRESSION_PAYLOAD_BASE_LEN ; -if (payload_alg ==SMB3_COMPRESS_NONE ) { - rc =smb_decompress_none (&src, &remaining, &out, - &out_remaining, len); - }else if (payload_alg ==SMB3_COMPRESS_PATTERN ) { - rc =smb_decompress_pattern (&src, &remaining, &out, - &out_remaining, len); - }else if (payload_alg == alg && alg ==SMB3_COMPRESS_LZ77 ) { + rc = -EINVAL ; +switch (payload_alg) { +case SMB3_COMPRESS_NONE : + rc =smb_decompress_none (&src, &remaining, &out, &out_remaining, len); +break ; +case SMB3_COMPRESS_LZ77 : rc =smb_decompress_lz77_payload (&src, &remaining, &out, &out_remaining, len); - }else { -return -EINVAL ; +break ; +case SMB3_COMPRESS_PATTERN : + rc =smb_decompress_pattern (&src, &remaining, &out, &out_remaining, len); +break ; } +if (rc)return rc; - first = false; + + payload = (const struct smb2_compression_payload_hdr *)src; +if (remaining >=SMB2_COMPRESSION_PAYLOAD_BASE_LEN && +unlikely (payload->Flags !=cpu_to_le16 (SMB2_COMPRESSION_FLAG_NONE ))) +return -EINVAL ; }return out_remaining ? -EINVAL :0 ;
@@ -195,15 +198,22 @@ int smb_compression_decompress(__le16 alg, bool allow_chained,const struct smb2_compression_hdr *hdr = src;if (!src || !dst || slen <sizeof (*hdr) || - hdr->ProtocolId !=SMB2_COMPRESSION_TRANSFORM_ID || - alg ==SMB3_COMPRESS_NONE ) + hdr->ProtocolId !=SMB2_COMPRESSION_TRANSFORM_ID )return -EINVAL ; -if (hdr->Flags ==cpu_to_le16 (SMB2_COMPRESSION_FLAG_CHAINED )) -return smb_decompress_chained (alg, allow_chained, hdr, slen, - dst, dlen); +/* If @allow_chained == true, the first payload hdr may have "NONE" algorithm */ +if (unlikely (!allow_chained && (hdr->CompressionAlgorithm ==SMB3_COMPRESS_NONE || + hdr->CompressionAlgorithm ==SMB3_COMPRESS_PATTERN ))) +return -EINVAL ; + +if (hdr->Flags ==cpu_to_le16 (SMB2_COMPRESSION_FLAG_CHAINED )) { +if (likely (allow_chained)) +return smb_decompress_chained (alg, hdr, slen, dst, dlen); + +return -EINVAL ; + } -if (hdr->Flags !=cpu_to_le16 (SMB2_COMPRESSION_FLAG_NONE )) +if (unlikely (hdr->Flags !=cpu_to_le16 (SMB2_COMPRESSION_FLAG_NONE ) || allow_chained))return -EINVAL ;return smb_decompress_unchained (alg, hdr, slen, dst, dlen);
Signature · 1 line
2.54.0
PATCH v2 7/14 smb: client: compress: enable Pattern_V1 + chained compression
In reply to Enzo MatsumiyaNegotiate Pattern_V1 and LZ77 compression algorithms by default (if 'compress' mount option is set).
Changes:
- add smb_compress_alloc_size() helper to compute compressed buffer size, to account for Pattern_V1 payloads as well
- adjust server/compress.c to use smb_compress_alloc_size()
- adjust client/compress.c to use smb_compression_compress(), and fixup the compression header (as client sends the SMB2 header uncompressed)
--- fs/smb/client/cifs_debug.c | 18 ++++++--- fs/smb/client/compress.c | 61 +++++++++++++++++++++++-------- fs/smb/client/smb2pdu.c | 17 +++++++++ fs/smb/common/compress/compress.h | 38 +++++++++++++++++++ fs/smb/server/compress.c | 19 ++++++---- 5 files changed, 124 insertions(+), 29 deletions(-)
fs/smb/client/cifs_debug.c +12 -6
@@ -552,14 +552,20 @@ static int cifs_debug_data_proc_show(struct seq_file *m, void *v) }seq_puts (m,"\nCompression: " ); -if (!IS_ENABLED (CONFIG_CIFS_COMPRESSION )) +if (!IS_ENABLED (CONFIG_CIFS_COMPRESSION )) {seq_puts (m,"no built-in support" ); -else if (!server->compression.requested) + }else if (!server->compression.requested) {seq_puts (m,"disabled on mount" ); -else if (server->compression.enabled) -seq_printf (m,"enabled (%s)" ,compression_alg_str (server->compression.alg)); -else -seq_puts (m,"disabled (not supported by this server)" ); + }else if (!server->compression.enabled) { +seq_puts (m,"disabled" );/* XXX: reason? */ + }else { +seq_printf (m,"enabled, chained: %s, algs: " , +str_yes_no (server->compression.chained)); + +seq_printf (m,"%s " ,compression_alg_str (server->compression.alg)); +if (server->compression.pattern) +seq_printf (m,"%s " ,compression_alg_str (SMB3_COMPRESS_PATTERN )); + }/* Show negotiated encryption cipher, even if not required */ seq_puts (m,"\nEncryption: " );
fs/smb/client/compress.c +46 -15
84 lines not on this page · raw message
fs/smb/client/smb2pdu.c +17 -0
@@ -892,6 +892,12 @@ static void decode_compress_ctx(struct TCP_Server_Info *server,/* * Pattern_V1 cannot appear in an unchained transform even if a broken * peer lists it in the algorithm array. +* +* OTOH, the chained flag might have been negotiated without either/both peers having not +* advertised Pattern_V1 algorithm support. +* +* (which doesn't make much sense, but we'll still have to send compressed payloads with +* the chained flag set in "chained && !pattern_v1" cases) */ chained = (ctxt->Flags ==SMB2_COMPRESSION_CAPABILITIES_FLAG_CHAINED );if (!chained)
@@ -1382,6 +1388,12 @@ SMB2_negotiate(const unsigned int xid, rc =smb_EIO1 (smb_eio_trace_neg_decode_token, rc); } +/* +* Disable compression until we decode negcontext -- keep other settings as they are, in +* case there are channels doing compression concurrently. +*/ + server->compression.enabled = false; +if (server->dialect ==SMB311_PROT_ID ) {if (rsp->NegotiateContextCount) rc = smb311_decode_neg_context(rsp, server,
@@ -1390,6 +1402,11 @@ SMB2_negotiate(const unsigned int xid,cifs_server_dbg (VFS ,"Missing expected negotiate contexts\n" ); } +if (server->compression.requested && !server->compression.enabled) { +cifs_server_dbg (VFS ,"Server doesn't support SMB2 compression\n" ); +disable_compression (server); + } +if (server->cipher_type && !rc) rc =smb3_crypto_aead_allocate (server); neg_exit:
fs/smb/common/compress/compress.h +38 -0
@@ -145,6 +145,44 @@ static __always_inline bool smb_compress_alg_valid(__le16 alg, bool valid_none)return alg ==SMB3_COMPRESS_LZ77 || alg ==SMB3_COMPRESS_PATTERN ; } +/** +* smb_compress_alloc_size() - Compute total allocation size required for compressed (dst) buffer. +* @size: uncompressed size +* @chained: if chained compression is enabled +* @use_pattern: if Pattern_V1 is enabled +* +* For any case: +* - SMB2 compression hdr +* - LZ* payload +* +* If @chained, account for: +* - 1x payload hdr +* +* If @use_pattern, also account for: +* - 2x payload hdr for Pattern_V1 +* - 2x Pattern_V1 payloads +* +* (possible uncompressed leftovers are included in LZ alloc size) +* +* This helper assumes that the invalid combination (!@chained && @use_pattern) was previously +* checked by the caller. +*/ +static __always_inline u32 smb_compress_alloc_size(const u32 size, const bool chained, +const bool use_pattern) +{ +u32 alloc_size; + + alloc_size =sizeof (struct smb2_compression_hdr ) +smb_lz77_compressed_alloc_size (size); +if (chained) { + alloc_size +=SMB2_COMPRESSION_PAYLOAD_BASE_LEN ; +if (use_pattern) + alloc_size += (SMB2_COMPRESSION_PAYLOAD_BASE_LEN *2 ) + + (sizeof (struct smb2_compression_pattern_v1 ) *2 ); + } + +return alloc_size; +} +int smb_compression_decompress (__le16 alg,bool allow_chained,const void *src,u32 slen,void *dst,u32 dlen); int smb_compression_compress(__le16 alg, bool chained, bool allow_pattern,
fs/smb/server/compress.c +11 -8
@@ -98,6 +98,7 @@ int ksmbd_compress_response(struct ksmbd_work *work)struct smb2_hdr *req_hdr;u32 src_len, dst_len, compressed_pdu_len, max_dst_len;u8 *src =NULL , *out =NULL , *p; +bool chained, pattern;int i, rc; if (!work->compress_response || work->encrypted ||
@@ -132,10 +133,14 @@ int ksmbd_compress_response(struct ksmbd_work *work) goto out; } - max_dst_len =smb_lz77_compressed_alloc_size (src_len) + -sizeof (struct smb2_compression_hdr ) + -3 *sizeof (struct smb2_compression_payload_hdr ) + -2 *sizeof (struct smb2_compression_pattern_v1 ); + chained = work->conn->compress_chained; + pattern = work->conn->compress_pattern; +if (unlikely (!chained && pattern)) { + rc = -EINVAL ; + goto out; + } + + max_dst_len =smb_compress_alloc_size (src_len, chained, pattern); out =kvzalloc (sizeof (__be32) + max_dst_len,KSMBD_DEFAULT_GFP );if (!out) {
@@ -143,11 +148,9 @@ int ksmbd_compress_response(struct ksmbd_work *work) goto out; } -if (work->conn->compress_chained) { +if (chained) { dst_len = max_dst_len; - rc =smb_compression_compress (SMB3_COMPRESS_LZ77 , - work->conn->compress_chained, - work->conn->compress_pattern, + rc =smb_compression_compress (SMB3_COMPRESS_LZ77 , chained, pattern, src, src_len, out +sizeof (__be32), &dst_len);
Signature · 1 line
2.54.0
PATCH v2 8/14 smb: server: compress: use generic smb_compression_compress()
In reply to Enzo MatsumiyaRework ksmbd_compress_response() to use smb_compression_compress() that's suitable for both chained and unchained cases now.
Changes:
- remove no longer used local variables
--- fs/smb/server/compress.c | 55 +++++++++------------------------------- 1 file changed, 12 insertions(+), 43 deletions(-)
fs/smb/server/compress.c +12 -43
@@ -94,11 +94,10 @@ int ksmbd_decompress_request(struct ksmbd_conn *conn)*/ int ksmbd_compress_response (struct ksmbd_work *work) { -struct smb2_compression_hdr *chdr;struct smb2_hdr *req_hdr; -u32 src_len, dst_len, compressed_pdu_len, max_dst_len;u8 *src =NULL , *out =NULL , *p;bool chained, pattern; +u32 src_len, dst_len;int i, rc; if (!work->compress_response || work->encrypted ||
@@ -140,54 +139,24 @@ int ksmbd_compress_response(struct ksmbd_work *work) goto out; } - max_dst_len =smb_compress_alloc_size (src_len, chained, pattern); - out =kvzalloc (sizeof (__be32) + max_dst_len, + dst_len =smb_compress_alloc_size (src_len, chained, pattern); + out =kvzalloc (sizeof (__be32) + dst_len,KSMBD_DEFAULT_GFP );if (!out) { rc = -ENOMEM ; goto out; } -if (chained) { - dst_len = max_dst_len; - rc =smb_compression_compress (SMB3_COMPRESS_LZ77 , chained, pattern, - src, src_len, - out +sizeof (__be32), - &dst_len); -if (rc == -EMSGSIZE || dst_len >= src_len) { - rc =0 ; - goto out; - } -if (rc) - goto out; - compressed_pdu_len = dst_len; - }else { -/* -* Peers which did not negotiate chained compression still use -* the original 16-byte unchained transform format. -*/ - dst_len =smb_lz77_compressed_alloc_size (src_len); - rc =smb_lz77_compress (src, src_len, - out +sizeof (__be32) +sizeof (*chdr), - &dst_len); -if (rc == -EMSGSIZE || - dst_len +sizeof (*chdr) >= src_len) { - rc =0 ; - goto out; - } -if (rc) - goto out; - - compressed_pdu_len =sizeof (*chdr) + dst_len; - chdr = (struct smb2_compression_hdr *)(out +sizeof (__be32)); - chdr->ProtocolId =SMB2_COMPRESSION_TRANSFORM_ID ; - chdr->OriginalCompressedSegmentSize =cpu_to_le32 (src_len); - chdr->CompressionAlgorithm =SMB3_COMPRESS_LZ77 ; - chdr->Flags =cpu_to_le16 (SMB2_COMPRESSION_FLAG_NONE ); - chdr->Offset =0 ; + rc =smb_compression_compress (SMB3_COMPRESS_LZ77 , chained, pattern, + src, src_len, + out +sizeof (__be32), + &dst_len); +if (rc == -EMSGSIZE || dst_len >= src_len) { + rc =0 ; + goto out; } - *(__be32 *)out =cpu_to_be32 (compressed_pdu_len); + *(__be32 *)out =cpu_to_be32 (dst_len);/* * Keep the transform in work->compress_buf until send completion.
@@ -198,7 +167,7 @@ int ksmbd_compress_response(struct ksmbd_work *work) work->iov[0 ].iov_base = out; work->iov[0 ].iov_len =sizeof (__be32); work->iov[1 ].iov_base = out +sizeof (__be32); - work->iov[1 ].iov_len = compressed_pdu_len; + work->iov[1 ].iov_len = dst_len; work->iov_cnt =2 ; work->iov_idx =1 ; out =NULL ;
Signature · 1 line
2.54.0
PATCH v2 9/14 smb: common: compress: allow smb_lz77_compress() to overcompress
In reply to Enzo MatsumiyaChange smb_lz77_compress() to return 0 on successful compression, leaving it up to callers to decide if @dlen >= @slen is an error (currently returns -EMSGSIZE on such cases).
This allows better compression in certain cases where Pattern_V1 got a good compression already, but LZ77 chunk was overcompressed (which usually yields good compressed data as a whole)
Other changes:
- adjust client and server callers to correctly interpret the new return value
--- fs/smb/client/compress.c | 4 ++-- fs/smb/common/compress/lz77.c | 7 ++----- fs/smb/server/compress.c | 5 ++--- 3 files changed, 6 insertions(+), 10 deletions(-)
fs/smb/client/compress.c +2 -2
@@ -406,7 +406,7 @@ int smb_compress(struct TCP_Server_Info *server, struct smb_rqst *rq, compress_s ret =smb_compression_compress (SMB3_COMPRESS_LZ77 , chained, use_pattern, src, slen, dst, &dlen); -if (!ret) { +if (!ret && dlen < slen) {struct smb2_compression_hdr *hdrp = dst, hdr = {};struct smb_rqst comp_rq = { .rq_nvec =3 , };struct kvec iov[3 ];
@@ -453,7 +453,7 @@ int smb_compress(struct TCP_Server_Info *server, struct smb_rqst *rq, compress_s comp_rq.rq_iov = iov; ret =send_fn (server,1 , &comp_rq); - }else if (ret == -EMSGSIZE || dlen >= slen) { + }else if (!ret) { ret =send_fn (server,1 , rq); } err_free:
fs/smb/common/compress/lz77.c +2 -5
@@ -248,19 +248,16 @@ noinline int smb_lz77_compress(const void *src, const u32 slen, void *dst, u32 * }while (srcp < end); out: dstp =lz77_encode_literals (anchor, end, dstp, &flag, &flag_count, &flag_pos); - flag_count =LZ77_FLAG_MAX - flag_count; flag <<= flag_count; flag |= (1UL << flag_count) -1 ;mem_write32 (flag_pos, flag); +/* Compression is successful from our POV -- let caller decide if @dlen suits them. */ *dlen = dstp - dst;kvfree (htable); -if (*dlen < slen) -return 0 ; - -return -EMSGSIZE ; +return 0 ; }EXPORT_SYMBOL_GPL (smb_lz77_compress);
fs/smb/server/compress.c +2 -3
@@ -151,10 +151,9 @@ int ksmbd_compress_response(struct ksmbd_work *work) src, src_len, out +sizeof (__be32), &dst_len); -if (rc == -EMSGSIZE || dst_len >= src_len) { - rc =0 ; +/* if dst_len >= src_len, rc is 0 */ +if (rc || dst_len >= src_len) goto out; - } *(__be32 *)out =cpu_to_be32 (dst_len);
Signature · 1 line
2.54.0
PATCH v2 10/14 smb: common: compress: smb_lz77_decompress() improvements
In reply to Enzo MatsumiyaLZ77 decompression performance improvements:
- make use of mem_read*() helpers for faster unaligned reads in x86
- change lz77_decode_match_len() to return a pointer as it advances (instead of dereferencing @src every time to update it, which is costlier)
- also use a pointer for nib position instead of 2 separate args (@nibble and @have_nibble)
- decode flags in batches instead of one by one, e.g. a 00001111 flag is read only once now, with decoding operations in sequence (saves a few operations on back-and-forth reading/parsing)
- use memcpy() when copying non-overlapping memory (faster and a much more common case)
Other:
- warn and return -EIO if decompressed buffer length != @dlen (a bug)
--- fs/smb/common/compress/lz77.c | 284 +++++++++++++++++++++++----------- 1 file changed, 192 insertions(+), 92 deletions(-)
fs/smb/common/compress/lz77.c +192 -92
@@ -261,117 +261,217 @@ noinline int smb_lz77_compress(const void *src, const u32 slen, void *dst, u32 * }EXPORT_SYMBOL_GPL (smb_lz77_compress); -static int lz77_decode_match_len (const u8 **src,const u8 *end,u16 token, -u8 *nibble,bool *have_nibble,u32 *len) +static __always_inline const void *lz77_decode_match_len(const void *src, const void *end, +const void **nib,u32 *len) { -u8 extra; - - *len = (token &0x7 ) +3 ; -if ((token &0x7 ) !=0x7 ) -return 0 ; - -if (!*have_nibble) { -if (*src >= end) -return -EINVAL ; - *nibble = *(*src)++; - extra = *nibble &0xf ; - *have_nibble = true; - }else { - extra = *nibble >>4 ; - *have_nibble = false; - } - - *len += extra; -if (extra ==0xf ) { -u8 b; +u32 mlen = *len &7 ; -if (*src >= end) -return -EINVAL ; - b = *(*src)++; -if (b !=0xff ) { - *len += b; +/* +* *@len points to the initial match length decoded. +* We'll keep checking + decoding further if extra bits/bytes were used to encode larger +* lengths. +* +* Since we're reading from @src itself, this means any OOB read is an error +* (bug, malformed payload, etc). +*/ +if (mlen ==7 ) { +if (!*nib) { + *nib = src; +if (unlikely (src >= end)) +return NULL ; + + mlen =mem_read8 (src) &15 ; + src++; }else { -u16 w; - -if (end - *src <2 ) -return -EINVAL ; - w =mem_read16 (*src); - *src +=2 ; -if (w) { - *len = w +3 ; - }else { -u32 long_len; - -if (end - *src <4 ) -return -EINVAL ; - long_len =mem_read32 (*src); - *src +=4 ; -if (check_add_overflow (long_len,3 , len)) -return -EINVAL ; + mlen =mem_read8 (*nib) >>4 ; + *nib =NULL ; + } + +if (mlen ==15 ) { +if (unlikely (src >= end)) +return NULL ; + + mlen =mem_read8 (src); + src++; + +if (mlen ==255 ) { +if (unlikely (src +sizeof (u16) > end)) +return NULL ; + + mlen =mem_read16 (src); + src +=sizeof (u16); + +if (mlen ==0 ) { +if (unlikely (src +sizeof (u32) > end)) +return NULL ; + + mlen =mem_read32 (src); + src +=sizeof (u32); + } + +/* Unexpected match len < 15 + 7 (decoding bug) */ +if (unlikely (mlen <23 )) +return NULL ; + + mlen -= (15 +7 ); } + mlen +=15 ; } + mlen +=7 ; } + mlen +=3 ; + *len = mlen; -return 0 ; +return src; } -int smb_lz77_decompress (const void *src,const u32 slen,void *dst, -const u32 dlen) +/* @dlen is expected to be the _exact_ decompressed size of this payload, regardless of chaining */ +noinline int smb_lz77_decompress(const void *src, const u32 slen, void *dst, const u32 dlen) { -const u8 *sp = src, *send = sp + slen; -u8 *dp = dst, *dend = dp + dlen; -u32 flags =0 ; -int flag_count =0 ; -u8 nibble =0 ; -bool have_nibble = false; - -while (dp < dend) { -u32 len, dist; -u16 token; - -if (!flag_count) { -if (send - sp <4 ) -return -EINVAL ; - flags =mem_read32 (sp); - sp +=4 ; - flag_count =32 ; - } +const void *srcp = src, *end = src + slen, *nib =NULL ; +void *dstp = dst, *dst_end = dst + dlen; -if (!(flags &0x80000000 )) { -if (sp >= send) -return -EINVAL ; - *dp++ = *sp++; - flags <<=1 ; - flag_count--; -continue ; - } +while (srcp +SMB_COMPRESS_RSTEP_SIZE <= end) { +u32 flag, flag_count =LZ77_FLAG_MAX ; - flags <<=1 ; - flag_count--; - -if (send - sp <2 ) -return -EINVAL ; +/* +* Read flag. +* +* LZ77 flags are 32-bit bitmaps where 0s indicates a literal in the stream +* (straight copied from @srcp to @dstp) and 1s indicates a match (decoded from +* @srcp). +* +* Compressed payloads always starts with a flag. +*/ + flag =mem_read32 (srcp); + srcp +=SMB_COMPRESS_RSTEP_SIZE ; - token =mem_read16 (sp); - sp +=2 ; +do { +u32 m =0 , l; - dist = (token >>3 ) +1 ; -if (dist > dp - (u8 *)dst) -return -EINVAL ; +/* +* Decode flag. +* +* Each bit in @flag represents a literal (0) or a match (1). +* Instead of processing them as individual bits, do it in batches: +* (@m matches, @l literals) +* +* Count leading zeroes for that (flip @flag bits to compute matches). +* +* Notes: +* - @flag == 0 means we're are bound by @flag_count literals +* - __builtin_clz() yields UB if arg is 0 +* - we can't rely on bit counting alone as bound-checking because the +* final flag in compressed payload might contain lots of 1s +* (((1 << (32 - @flag_count)) - 1), cf. smb_lz77_compress()). +* +* Also, matches can be encoded from 2 up to 10 bytes each, and since we +* don't know the size of each match beforehand, we can't determine a +* fixed limit, so we have to check @srcp limits before each match read. +*/ +if (flag) { + m = flag <0xFFFFFFFF ?__builtin_clz (~flag) :LZ77_FLAG_MAX ; + flag_count -= m; +if (m <32 ) + flag <<= m; +else + flag =0 ; + } -if (lz77_decode_match_len (&sp, send, token, &nibble, - &have_nibble, &len)) -return -EINVAL ; + l = flag ?umin (__builtin_clz (flag), flag_count) : flag_count; + flag_count -= l; +if (l <32 ) + flag <<= l; +else + flag =0 ; + +/* Decoding bug (or, unlikely, __builtin_clz() bug) */ +if (WARN_ON_ONCE (l + m >LZ77_FLAG_MAX )) +return -EIO ; + +while (m--) { +const void *match; +u32 dist, len; + +/* +* Final flag done (not a bug). +* +* Note that even if we reached here (@m wasn't 0), we can't rely +* on that value alone as a "true match flag counter" because of +* how the last flag is encoded (cf. smb_lz77_compress()). +*/ +if (unlikely (srcp +sizeof (u16) > end)) { +/* unexpected truncated input */ +if (unlikely (srcp < end)) +return -EFAULT ; + goto out; + } + +/* Store match symbol in @len */ + len =mem_read16 (srcp); + srcp +=sizeof (u16); + dist = (len >>3 ) +1 ; + srcp =lz77_decode_match_len (srcp, end, &nib, &len); +if (unlikely (!srcp)) +return -EFAULT ; + +/* +* Check bogus match values. +* +* We don't know what compression parameters (e.g. match max dist, +* min len) the server is using, so check against limits allowed +* by spec. +* +* Also check if within @dst boundaries so we can do a straight +* copy. +*/ +if (unlikely (!dist || dist >SZ_8K || dstp - dst < dist)) +return -EFAULT ; + +if (unlikely (len <3 || len ==U32_MAX || dst_end - dstp < len)) +return -EFAULT ; + +/* +* If non-overlapping memory, we can use memcpy() (common case). +* Otherwise, we have to do it byte by byte. +* +* Note @match is always behind @dstp (@dist is at least 1). +*/ + match = dstp - dist; +if (likely (len < dist)) { +memcpy (dstp, match, len); + dstp += len; + }else { +while (len--) +mem_write8 (dstp++,mem_read8 (match++)); + } + } -if (len > dend - dp) -return -EINVAL ; +if (l) { +if (unlikely (end - srcp < l || dst_end - dstp < l)) +return -EFAULT ; -while (len--) { - *dp = *(dp - dist); - dp++; - } +memcpy (dstp, srcp, l); + srcp += l; + dstp += l; + } + }while (flag_count); } +out: +/* +* @dstp > @dst_end is an OOB write (and should've been caught in the loop above). +* @dstp < @dst_end, without any other decoding errors, might be: +* - caller bug (wrong input arguments, e.g. wrong @src or @dlen) +* - decoding bug (compressed buffer decodes fine (passes all checks), but parsed a bogus +* length value) +*/ +if (WARN_ON_ONCE (dstp != dst_end)) +return -EIO ; +/* +* We've now fully parsed the compressed buffer without any processing errors. +* However, it's up to callers to determine the validity of @dst. +*/ return 0 ; }EXPORT_SYMBOL_GPL (smb_lz77_decompress);
Signature · 1 line
2.54.0
PATCH v2 11/14 smb: common: compress: implement LZ77-Huffman
In reply to Enzo MatsumiyaImplement LZ77-Huffman compression algorithm as per MS-XCA.
Huffman encoding adds a few extra passes on top of LZ77-style encoding in order to provide better compression ratio (at bit level rather than byte level).
Refer to MS-XCA spec or code/comments in huffman.* for details.
Changes:
- add huffman.{h,c} with implementation
- adjust server/ and client/ code to support new alg
- rename smb_compression_add_lz77() to smb_compression_add_lz() and smb_decompress_lz77_payload() to smb_decompress_lz_payload(), and add an @alg arg to both, so they handle LZ77 and LZ77-Huffman (which are handled the same way in that regard)
- add @lzalg arg to smb_compress_alloc_size() to account for LZ77-Huffman allocation requirements
- add LZ77-Huffman to smb_compress_alg_valid()
--- fs/smb/client/compress.c | 21 +- fs/smb/client/smb2pdu.c | 20 +- fs/smb/common/Makefile | 2 +- fs/smb/common/compress/compress.c | 46 +- fs/smb/common/compress/compress.h | 22 +- fs/smb/common/compress/huffman.c | 983 ++++++++++++++++++++++++++++++ fs/smb/common/compress/huffman.h | 31 + fs/smb/server/compress.c | 9 +- fs/smb/server/smb2pdu.c | 27 +- 9 files changed, 1117 insertions(+), 44 deletions(-) create mode 100644 fs/smb/common/compress/huffman.c create mode 100644 fs/smb/common/compress/huffman.h
fs/smb/client/compress.c +15 -6
@@ -225,14 +225,16 @@ static int check_compressible_chunks(const u8 *buf, const u32 len, u32 *freqs)/* * Check @buf heuristics (entropy/distribution) to determine its compressibility level. * +* If @maybe_ok is false, alias MAYBE_COMPRESSIBLE to UNCOMPRESSIBLE. +* * Tests shows that this function is quite reliable in predicting data compressibility, matching -* very close with the behaviour of LZ77 compression success and failures. +* very close with the behaviour of LZ* compression success and failures. * * This function allocates memory, callers must check for -ENOMEM. * * Return: one of the *COMPRESSIBLE values on success, -errno otherwise. */ -static __must_check int check_compressible (const u8 *buf,u32 len) +static __must_check int check_compressible (const u8 *buf,u32 len,bool maybe_ok) {u32 entropy, *freqs, rle =0 , rle_boost =0 ;const u32 min_reps = (len /100 );/* ~1% of @len */
@@ -310,6 +312,9 @@ static __must_check int check_compressible(const u8 *buf, u32 len)kfree (freqs); +if (!maybe_ok && ret ==MAYBE_COMPRESSIBLE ) + ret =UNCOMPRESSIBLE ; +return ret; }
@@ -355,6 +360,7 @@ int smb_compress(struct TCP_Server_Info *server, struct smb_rqst *rq, compress_sbool chained, use_pattern;void *src, *dst =NULL ;u32 slen, dlen; +__le16 lzalg;int ret;if (!server || !rq || !rq->rq_iov || !rq->rq_iov->iov_base)
@@ -363,6 +369,10 @@ int smb_compress(struct TCP_Server_Info *server, struct smb_rqst *rq, compress_sif (rq->rq_iov->iov_len !=sizeof (struct smb2_write_req ))return -EINVAL ; + lzalg = server->compression.alg; +if (unlikely (!smb_compress_alg_valid (lzalg, false))) +return -EINVAL ; + slen =iov_iter_count (&rq->rq_iter); src =kvzalloc (slen,GFP_KERNEL );if (!src) {
@@ -386,7 +396,7 @@ int smb_compress(struct TCP_Server_Info *server, struct smb_rqst *rq, compress_s* uncompressible low-hanging fruits here and let smb_lz77_compress() handle the * exceptions/rare cases. */ - ret =check_compressible (src, slen); + ret =check_compressible (src, slen, lzalg ==SMB3_COMPRESS_LZ77_HUFF );/* XXX: do something with MAYBE_COMPRESSIBLE */ if (ret !=COMPRESSIBLE ) {
@@ -397,15 +407,14 @@ int smb_compress(struct TCP_Server_Info *server, struct smb_rqst *rq, compress_s chained = server->compression.chained; use_pattern = server->compression.pattern; - dlen =smb_compress_alloc_size (slen, chained, use_pattern); + dlen =smb_compress_alloc_size (slen, chained, use_pattern, lzalg); dst =kvzalloc (dlen,GFP_KERNEL );if (!dst) { ret = -ENOMEM ; goto err_free; } - ret =smb_compression_compress (SMB3_COMPRESS_LZ77 , chained, use_pattern, - src, slen, dst, &dlen); + ret =smb_compression_compress (lzalg, chained, use_pattern, src, slen, dst, &dlen);if (!ret && dlen < slen) {struct smb2_compression_hdr *hdrp = dst, hdr = {};struct smb_rqst comp_rq = { .rq_nvec =3 , };
fs/smb/client/smb2pdu.c +15 -5
@@ -44,6 +44,7 @@#include "cached_dir.h" #include "compress.h" #include "fs_context.h" +#include "../common/compress/compress.h" /* * The following table defines the expected "StructureSize" of SMB2 requests
@@ -877,14 +878,23 @@ static void decode_compress_ctx(struct TCP_Server_Info *server, pattern = false;for (i =0 ; i < count; i++) { -/* Record the intersection supported by the shared SMB codec. */ -if (ctxt->CompressionAlgorithms[i] ==SMB3_COMPRESS_LZ77 ) - alg =SMB3_COMPRESS_LZ77 ; -else if (ctxt->CompressionAlgorithms[i] ==SMB3_COMPRESS_PATTERN ) +__le16 rsp_alg = ctxt->CompressionAlgorithms[i]; + +/* +* Servers only return 1 LZ* algorithm, or + Pattern_V1 if chained. +* server->compression.alg only tracks LZ* algs. +*/ +if (rsp_alg ==SMB3_COMPRESS_PATTERN ) pattern = true; +else if (smb_compress_alg_valid (rsp_alg, false)) + alg = rsp_alg; +else +pr_warn_once ("invalid compression algorithm '0x%04x'\n" , +le16_to_cpu (rsp_alg)); } -if (unlikely (alg !=SMB3_COMPRESS_LZ77 )) { +/* We explicitly checked for SMB3_COMPRESS_PATTERN above, so this works fine */ +if (unlikely (!smb_compress_alg_valid (alg, false))) {cifs_dbg (VFS ,"invalid LZ algorithm negotiated 0x%x\n" , alg); goto out; }
fs/smb/common/Makefile +1 -1
@@ -6,4 +6,4 @@ obj-$(CONFIG_SMBFS) += cifs_md4.o obj-$(CONFIG_SMBFS) += smb_compress.o -smb_compress-y := compress/compress.o compress/lz77.o +smb_compress-y := compress/compress.o compress/lz77.o compress/huffman.o
fs/smb/common/compress/compress.c +32 -14
102 lines not on this page · raw message
fs/smb/common/compress/compress.h +17 -5
@@ -15,6 +15,7 @@#include <linux/slab.h> #include "../smb2pdu.h" +#include "huffman.h" #include "lz77.h" #define SMB2_COMPRESSION_CHAINED_HDR_LEN \
@@ -139,10 +140,16 @@ static __always_inline u32 smb_compress_hash_ptr(const void *ptr)*/ static __always_inline bool smb_compress_alg_valid(__le16 alg, bool valid_none) { -if (alg ==SMB3_COMPRESS_NONE ) +switch (alg) { +case SMB3_COMPRESS_NONE :return valid_none; +case SMB3_COMPRESS_LZ77 : +case SMB3_COMPRESS_LZ77_HUFF : +case SMB3_COMPRESS_PATTERN : +return true; + } -return alg ==SMB3_COMPRESS_LZ77 || alg ==SMB3_COMPRESS_PATTERN ; +return false; }/**
@@ -150,6 +157,7 @@ static __always_inline bool smb_compress_alg_valid(__le16 alg, bool valid_none)* @size: uncompressed size * @chained: if chained compression is enabled * @use_pattern: if Pattern_V1 is enabled +* @lzalg: LZ* algorithm that will be used * * For any case: * - SMB2 compression hdr
@@ -168,11 +176,15 @@ static __always_inline bool smb_compress_alg_valid(__le16 alg, bool valid_none)* checked by the caller. */ static __always_inline u32 smb_compress_alloc_size(const u32 size, const bool chained, -const bool use_pattern) +const bool use_pattern,const __le16 lzalg) { -u32 alloc_size; +u32 alloc_size =sizeof (struct smb2_compression_hdr ); + +if (lzalg ==SMB3_COMPRESS_LZ77 ) + alloc_size +=smb_lz77_compressed_alloc_size (size); +else if (lzalg ==SMB3_COMPRESS_LZ77_HUFF ) + alloc_size +=smb_huff_compressed_alloc_size (size); - alloc_size =sizeof (struct smb2_compression_hdr ) +smb_lz77_compressed_alloc_size (size);if (chained) { alloc_size +=SMB2_COMPRESSION_PAYLOAD_BASE_LEN ;if (use_pattern)
fs/smb/common/compress/huffman.c new file +983 -0
983 lines not on this page · raw message
fs/smb/common/compress/huffman.h new file +31 -0
@@ -0,0 +1,31 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +/* +* Copyright (C) 2026, SUSE LLC +* +* Authors: Enzo Matsumiya <[email protected]> +* +* Implementation of the LZ77+Huffman compression algorithm, as per MS-XCA spec. +*/ +#ifndef _SMB_COMPRESS_LZ77_HUFF_H +#define _SMB_COMPRESS_LZ77_HUFF_H + +#include <linux/kernel.h> +#include <linux/sizes.h> + +#define HUFF_TABLE_SIZE 256 +#define HUFF_BLOCK_SIZE SZ_64K + +/* +* LZ77-Huffman metadata is Huffman table (256 bytes) at the beginning of every 64k block, so +* compute allocation size considering the worst-case scenarios (fully uncompressible blocks). +*/ +static __always_inline u32 smb_huff_compressed_alloc_size(const u32 size) +{ +const u32 nblocks =DIV_ROUND_UP (size,HUFF_BLOCK_SIZE ); + +return nblocks * (HUFF_TABLE_SIZE +HUFF_BLOCK_SIZE ); +} + +int smb_huff_compress (const void *src,const u32 slen,void *dst,u32 *dlen); +int smb_huff_decompress (const void *src,const u32 slen,void *dst,const u32 dlen); +#endif /* _SMB_COMPRESS_LZ77_HUFF_H */
fs/smb/server/compress.c +5 -4
@@ -35,7 +35,7 @@ int ksmbd_decompress_request(struct ksmbd_conn *conn)return -EINVAL ;if (conn->dialect !=SMB311_PROT_ID || - conn->compress_algorithm ==SMB3_COMPRESS_NONE ) + !smb_compress_alg_valid (conn->compress_algorithm, false))return -EINVAL ; hdr =smb_get_msg (conn->request_buf);
@@ -98,10 +98,11 @@ int ksmbd_compress_response(struct ksmbd_work *work)u8 *src =NULL , *out =NULL , *p;bool chained, pattern;u32 src_len, dst_len; +__le16 alg = work->conn->compress_algorithm;int i, rc;if (!work->compress_response || work->encrypted || - work->conn->compress_algorithm !=SMB3_COMPRESS_LZ77 ) + !smb_compress_alg_valid (alg, false))return 0 ; req_hdr =smb_get_msg (work->request_buf);
@@ -139,7 +140,7 @@ int ksmbd_compress_response(struct ksmbd_work *work) goto out; } - dst_len =smb_compress_alloc_size (src_len, chained, pattern); + dst_len =smb_compress_alloc_size (src_len, chained, pattern, alg); out =kvzalloc (sizeof (__be32) + dst_len,KSMBD_DEFAULT_GFP );if (!out) {
@@ -147,7 +148,7 @@ int ksmbd_compress_response(struct ksmbd_work *work) goto out; } - rc =smb_compression_compress (SMB3_COMPRESS_LZ77 , chained, pattern, + rc =smb_compression_compress (alg, chained, pattern, src, src_len, out +sizeof (__be32), &dst_len);
fs/smb/server/smb2pdu.c +18 -9
@@ -1130,18 +1130,27 @@ static __le32 decode_compress_ctxt(struct ksmbd_conn *conn,__le16 alg = algs[i];/* -* LZ77 is the required general-purpose codec. Pattern_V1 is an +* LZ* are the required general-purpose codecs. Pattern_V1 is an * optional chained payload type and cannot stand alone. +* +* Use the first LZ algorithm found in the request array. It's sorted by +* client-preferred order, so don't overwrite it if already set. */ -if (alg ==SMB3_COMPRESS_LZ77 ) { - conn->compress_algorithm = alg; - conn->compress_chained = - pneg_ctxt->Flags == -SMB2_COMPRESSION_CAPABILITIES_FLAG_CHAINED ; -ksmbd_debug (SMB ,"Compression Algorithm ID = 0x%x\n" , -le16_to_cpu (alg)); - }else if (alg ==SMB3_COMPRESS_PATTERN ) { +switch (alg) { +case SMB3_COMPRESS_LZ77 : +case SMB3_COMPRESS_LZ77_HUFF : +if (conn->compress_algorithm ==SMB3_COMPRESS_NONE ) { + conn->compress_algorithm = alg; + conn->compress_chained = + pneg_ctxt->Flags == +SMB2_COMPRESSION_CAPABILITIES_FLAG_CHAINED ; +ksmbd_debug (SMB ,"Compression Algorithm ID = 0x%x\n" , +le16_to_cpu (alg)); + } +break ; +case SMB3_COMPRESS_PATTERN : conn->compress_pattern = true; +break ; } }
Signature · 1 line
2.54.0
PATCH v2 12/14 smb: client: add support for decompressing READs
In reply to Enzo MatsumiyaImplement decompression support for SMB2 READ messages.
Changes:
- smb2ops.c: add receive_compressed() and check_decompressed_smb2()
- check for compress header in smb3_is_transform_hdr() as well so we fall into the same path handling offloaded READ decryption
- common/compress/compress.h: add is_compress_hdr() and smb_decompress_alloc_size() helpers
--- fs/smb/client/smb2ops.c | 160 +++++++++++++++++++++++++++++- fs/smb/client/smb2pdu.c | 6 ++ fs/smb/common/compress/compress.h | 86 ++++++++++++++++ 3 files changed, 251 insertions(+), 1 deletion(-)
fs/smb/client/smb2ops.c +159 -1
@@ -30,6 +30,8 @@#include "fs_context.h" #include "cached_dir.h" #include "reparse.h" +#include "../common/compress/compress.h" +#include "compress.h" /* Change credits for different ops and return the total number of credits */ static int
@@ -4714,7 +4716,7 @@ smb3_is_transform_hdr(void *buf) {struct smb2_transform_hdr *trhdr = buf; -return trhdr->ProtocolId ==SMB2_TRANSFORM_PROTO_NUM ; +return (trhdr->ProtocolId ==SMB2_TRANSFORM_PROTO_NUM ) ||is_compress_hdr (buf); } static int
@@ -5246,6 +5248,153 @@ receive_encrypted_standard(struct TCP_Server_Info *server,return ret; } +static __always_inline bool check_decompressed_smb2(const void *buf, const u32 len) +{ +const struct smb2_read_rsp *rsp = buf; + +if (unlikely (rsp->hdr.ProtocolId !=SMB2_PROTO_NUMBER )) { +cifs_dbg (VFS ,"decompressed message is not an SMB2 message (got ProtocolId 0x%x)\n" , + rsp->hdr.ProtocolId); +return false; + } + +if (unlikely (rsp->hdr.Command !=SMB2_READ )) { +cifs_dbg (VFS ,"decompressed message is not an SMB2 READ (got %u)\n" , +le16_to_cpu (rsp->hdr.Command)); +return false; + } + +if (unlikely (le32_to_cpu (rsp->DataLength) != len)) { +cifs_dbg (VFS ,"invalid decompressed length for SMB2 READ (got %u, expected %u)\n" , +le32_to_cpu (rsp->DataLength), len); +return false; + } + +return true; +} + +static int receive_compressed (struct TCP_Server_Info *server) +{ +struct mid_q_entry *mid; +void *src =NULL , *dst =NULL ; +u32 slen, dlen; +int read, ret; + +/* smb2_compression_pattern_v1 is the smallest compressed data we can have. */ + slen = server->pdu_size; +if (unlikely (slen <sizeof (struct smb2_compression_hdr ) + +sizeof (struct smb2_compression_pattern_v1 ))) { + ret = -EINVAL ; + goto err_free; + } + + src =kvzalloc (slen,GFP_KERNEL ); +if (unlikely (!src)) { + ret = -ENOMEM ; + goto err_free; + } + + read = server->total_read; +if (unlikely (read > slen)) { + ret = -EINVAL ; + goto err_free; + } + +memcpy (src, server->smallbuf, read); + ret =cifs_read_from_socket (server, src + read, slen - read); +if (ret <0 ) + goto err_free; + + server->total_read += ret; +if (unlikely (slen - ret != read)) { + ret = -EINVAL ; + goto err_free; + } + + ret = -EINVAL ; + read = server->vals->read_rsp_size; + dlen =smb_decompress_alloc_size (src, slen, read, read +256 + +SMB2_COMPRESSION_PAYLOAD_BASE_LEN + server->max_read, + server->compression.chained); +if (unlikely (dlen ==0 )) + goto err_free; + + dst =kvzalloc (dlen,GFP_KERNEL ); +if (unlikely (!dst)) { + ret = -ENOMEM ; + goto err_free; + } + + ret =smb_compression_decompress (server->compression.alg, server->compression.chained, + src, slen, dst, dlen); +if (unlikely (ret)) + goto err_free; + +if (unlikely (!check_decompressed_smb2 (dst, dlen - server->vals->read_rsp_size))) { + ret = -EINVAL ; + goto err_free; + } + + mid =smb2_find_dequeue_mid (server, dst); +if (!mid) { + ret = -EIO ; + goto err_free; + } + + ret =handle_read_data (server, mid, dst, dlen,NULL ,0 , true); +if (!ret) { +struct cifs_io_subrequest *rdata = mid->callback_data; +#ifdef CONFIG_CIFS_STATS2 + mid->when_received = jiffies; +#endif +if (server->ops->is_network_name_deleted) + server->ops->is_network_name_deleted (dst, server); + + rdata->iov[0 ].iov_base = dst; + rdata->iov[0 ].iov_len = server->vals->read_rsp_size; +mid_execute_callback (server, mid); + }else { +spin_lock (&server->srv_lock); +if (server->tcpStatus == CifsNeedReconnect) { +spin_lock (&server->mid_queue_lock); + mid->mid_state =MID_RETRY_NEEDED ; +spin_unlock (&server->mid_queue_lock); +spin_unlock (&server->srv_lock); + +mid_execute_callback (server, mid); + }else { +spin_lock (&server->mid_queue_lock); + mid->mid_state =MID_REQUEST_SUBMITTED ; + mid->deleted_from_q = false; +list_add_tail (&mid->qhead, &server->pending_mid_q); +spin_unlock (&server->mid_queue_lock); +spin_unlock (&server->srv_lock); + } + } + +release_mid (server, mid); +err_free: +kvfree (src); +kvfree (dst); + +/* +* We _must_ disconnect on any failed decompression. +* Actually, there's not much we can do to handle different decompression errors here, so +* forcing a reconnect (which will disable compression) is our best option as the request +* should be retried. +*/ +if (unlikely (ret)) { +/* Alias only if not -ENOMEM */ +if (ret != -ENOMEM ) + ret = -ECONNRESET ; +spin_lock (&server->srv_lock); + server->tcpStatus = CifsNeedReconnect; +spin_unlock (&server->srv_lock); + } + +return ret; +} +static int smb3_receive_transform (struct TCP_Server_Info *server,struct mid_q_entry **mids,char **bufs,int *num_mids)
@@ -5255,6 +5404,13 @@ smb3_receive_transform(struct TCP_Server_Info *server,struct smb2_transform_hdr *tr_hdr = (struct smb2_transform_hdr *)buf;unsigned int orig_len =le32_to_cpu (tr_hdr->OriginalMessageSize); +if (is_compress_hdr (buf)) +return receive_compressed (server); + +/* +* @buf is either a compress or transform (encrypt) header, previously checked by cifsd +* (or we wouldn't reach here), so no need to check again. +*/ if (pdu_length <sizeof (struct smb2_transform_hdr ) +sizeof (struct smb2_hdr )) { cifs_server_dbg(VFS, "Transform message is too small (%u)\n",
@@ -5296,6 +5452,8 @@ static int smb2_next_header(struct TCP_Server_Info *server, char *buf, *noff =le32_to_cpu (t_hdr->OriginalMessageSize);if (unlikely (check_add_overflow (*noff,sizeof (*t_hdr), noff)))return -EINVAL ; + }else if (hdr->ProtocolId ==SMB2_COMPRESSION_TRANSFORM_ID ) { + *noff =0 ; }else { *noff =le32_to_cpu (hdr->NextCommand); }
fs/smb/client/smb2pdu.c +6 -0
@@ -4933,6 +4933,12 @@ smb2_async_readv(struct cifs_io_subrequest *rdata) flags |=CIFS_HAS_CREDITS ; } +if (should_compress (io_parms.tcon, &rqst)) { +struct smb2_read_req *req = (struct smb2_read_req *)buf; + + req->Flags |=SMB2_READFLAG_REQUEST_COMPRESSED ; + } + rc = cifs_call_async(server, &rqst, cifs_readv_receive, smb2_readv_callback, smb3_handle_read_data, rdata, flags,
fs/smb/common/compress/compress.h +86 -0
92 lines not on this page · raw message
Signature · 1 line
2.54.0
PATCH v2 13/14 smb: server: use smb_decompress_alloc_size() in ksmbd_decompress_request()
In reply to Enzo MatsumiyaUse common helper to validate compress header and get decompressed size.
--- fs/smb/server/compress.c | 27 ++++++--------------------- 1 file changed, 6 insertions(+), 21 deletions(-)
fs/smb/server/compress.c +6 -21
@@ -24,11 +24,9 @@*/ int ksmbd_decompress_request (struct ksmbd_conn *conn) { -struct smb2_compression_hdr *hdr;unsigned int pdu_size =get_rfc1002_len (conn->request_buf); -u32 orig_size, offset, out_size; -u32 max_allowed_pdu_size;char *buf, *out; +u32 out_size;int rc;if (pdu_size <sizeof (struct smb2_compression_hdr ))
@@ -38,30 +36,17 @@ int ksmbd_decompress_request(struct ksmbd_conn *conn) !smb_compress_alg_valid(conn->compress_algorithm, false))return -EINVAL ; - hdr =smb_get_msg (conn->request_buf); -if (hdr->ProtocolId !=SMB2_COMPRESSION_TRANSFORM_ID ) -return -EINVAL ; - - orig_size =le32_to_cpu (hdr->OriginalCompressedSegmentSize); -if (hdr->Flags ==cpu_to_le16 (SMB2_COMPRESSION_FLAG_CHAINED )) { - out_size = orig_size; - }else { - offset =le32_to_cpu (hdr->Offset); -if (offset > pdu_size -sizeof (*hdr) || -check_add_overflow (orig_size, offset, &out_size)) -return -EINVAL ; - } - - max_allowed_pdu_size =SMB3_MAX_MSGSIZE + conn->vals->max_write_size; -if (out_size > max_allowed_pdu_size || - out_size >MAX_STREAM_PROT_LEN ) + buf =smb_get_msg (conn->request_buf); + out_size =smb_decompress_alloc_size (buf, pdu_size,0 , +SMB3_MAX_MSGSIZE + conn->vals->max_write_size, + conn->compress_chained); +if (out_size ==0 || out_size >MAX_STREAM_PROT_LEN )return -EINVAL ; out =kvmalloc (out_size +4 +1 ,KSMBD_DEFAULT_GFP );if (!out)return -ENOMEM ; - buf = (char *)hdr; *(__be32 *)out =cpu_to_be32 (out_size); rc = smb_compression_decompress(conn->compress_algorithm, conn->compress_chained,
Signature · 1 line
2.54.0
Namjae Jeon
maintainerRe: [PATCH v2 13/14] smb: server: use smb_decompress_alloc_size() in ksmbd_decompress_request()
Quoted 4 lines · Enzo Matsumiya
Use common helper to validate compress header and get decompressed size.
Signed-off-by Enzo Matsumiya <[email protected]>
I can not apply this patch to #ksmbd-for-next-next. Can you create this patch based on #ksmbd-for-next-next ?
fs/smb/server/compress.c int ksmbd_decompress_request(struct ksmbd_conn *conn) · line 42
Quoted 7 lines
fs/smb/server/compress.c +4
-3- max_allowed_pdu_size =SMB3_MAX_MSGSIZE + conn->vals->max_write_size; -if (out_size > max_allowed_pdu_size || - out_size >MAX_STREAM_PROT_LEN ) + buf =smb_get_msg (conn->request_buf); + out_size =smb_decompress_alloc_size (buf, pdu_size,0 , +SMB3_MAX_MSGSIZE + conn->vals->max_write_size, + conn->compress_chained);
In ksmbd_decompress_request(), the old code rejected decompressed messages smaller than sizeof(struct smb2_pdu). The new helper call passes 0 as dmin.
So you need to pass sizeof(struct smb2_pdu) as dmin :out_size = smb_decompress_alloc_size(buf, pdu_size,
sizeof(struct smb2_pdu),
SMB3_MAX_MSGSIZE +
conn->vals->max_write_size,
conn->compress_chained);Except this, The other server and common patches look good to me. I'll leave the client patches to the cifs.ko developers.
Thanks.
Namjae Jeon
maintainerRe: [PATCH v2 13/14] smb: server: use smb_decompress_alloc_size() in ksmbd_decompress_request()
Quoted 21 lines · Namjae Jeon
Quoted 4 lines · Enzo Matsumiya
Use common helper to validate compress header and get decompressed size.
Signed-off-by Enzo Matsumiya <[email protected]>I can not apply this patch to #ksmbd-for-next-next. Can you create this patch based on #ksmbd-for-next-next ?
fs/smb/server/compress.c int ksmbd_decompress_request(struct ksmbd_conn *conn) · line 42
Quoted 7 lines
fs/smb/server/compress.c +4
-3- max_allowed_pdu_size =SMB3_MAX_MSGSIZE + conn->vals->max_write_size; -if (out_size > max_allowed_pdu_size || - out_size >MAX_STREAM_PROT_LEN ) + buf =smb_get_msg (conn->request_buf); + out_size =smb_decompress_alloc_size (buf, pdu_size,0 , +SMB3_MAX_MSGSIZE + conn->vals->max_write_size, + conn->compress_chained);In
ksmbd_decompress_request(), the old code rejected decompressed messages smaller thansizeof(struct smb2_pdu). The new helper call passes 0 as dmin.
So you need to passsizeof(struct smb2_pdu)as dmin :out_size= smb_decompress_alloc_size(buf,pdu_size,
Quoted 7 lines
sizeof(struct smb2_pdu), SMB3_MAX_MSGSIZE + conn->vals->max_write_size, conn->compress_chained);Except this, The other server and common patches look good to me. I'll leave the client patches to the cifs.ko developers.
If you do not send the v3 patchset by next week, It will be difficult to merge into the 7.3 kernel.
PATCH v2 14/14 smb: client: mark compression as supported on 64-bit LE only
In reply to Enzo MatsumiyaOther architectures require more tuning + tests, even more so to maintain the same performance.
So for now, mark SMB2 compression as supported only on 64-bit little endian architectures.
--- fs/smb/client/fs_context.c | 25 +++++++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-)
fs/smb/client/fs_context.c +23 -2
@@ -1248,6 +1248,22 @@ static int smb3_reconfigure(struct fs_context *fc)return rc; } +/* +* Current SMB2 compression code works best, or at all, only in 64-bit little endian architectures. +* +* (this is more of a "TODO" than a final statement for other archs) +*/ +static inline bool smb_compress_arch_supported (void ) +{ +#if BITS_PER_LONG ==64 && (defined(__LITTLE_ENDIAN) || \ + (defined(__BYTE_ORDER__) && defined(__ORDER_LITTLE_ENDIAN__) && \ + __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__)) +return true; +#else +return false; +#endif +} +static int smb3_fs_context_parse_param (struct fs_context *fc,struct fs_parameter *param) {
@@ -1289,8 +1305,13 @@ static int smb3_fs_context_parse_param(struct fs_context *fc,cifs_errorf (fc,"CONFIG_CIFS_COMPRESSION kernel config option is unset\n" ); goto cifs_parse_mount_err; } - ctx->compress = true; -cifs_dbg (VFS ,"SMB3 compression support is experimental\n" ); + +if (smb_compress_arch_supported ()) { + ctx->compress = true; +cifs_dbg (VFS ,"SMB3 compression support is experimental\n" ); + }else { +cifs_dbg (VFS ,"SMB3 compression is currently only supported on 64-bit little endian architectures, not enabling\n" ); + }break ;case Opt_nodfs: ctx->nodfs =1 ;
Signature · 1 line
2.54.0