xref: /kernel/linux/linux-6.6/fs/erofs/decompressor.c (revision 62306a36)
1// SPDX-License-Identifier: GPL-2.0-only
2/*
3 * Copyright (C) 2019 HUAWEI, Inc.
4 *             https://www.huawei.com/
5 */
6#include "compress.h"
7#include <linux/module.h>
8#include <linux/lz4.h>
9
10#ifndef LZ4_DISTANCE_MAX	/* history window size */
11#define LZ4_DISTANCE_MAX 65535	/* set to maximum value by default */
12#endif
13
14#define LZ4_MAX_DISTANCE_PAGES	(DIV_ROUND_UP(LZ4_DISTANCE_MAX, PAGE_SIZE) + 1)
15#ifndef LZ4_DECOMPRESS_INPLACE_MARGIN
16#define LZ4_DECOMPRESS_INPLACE_MARGIN(srcsize)  (((srcsize) >> 8) + 32)
17#endif
18
19struct z_erofs_lz4_decompress_ctx {
20	struct z_erofs_decompress_req *rq;
21	/* # of encoded, decoded pages */
22	unsigned int inpages, outpages;
23	/* decoded block total length (used for in-place decompression) */
24	unsigned int oend;
25};
26
27static int z_erofs_load_lz4_config(struct super_block *sb,
28			    struct erofs_super_block *dsb, void *data, int size)
29{
30	struct erofs_sb_info *sbi = EROFS_SB(sb);
31	struct z_erofs_lz4_cfgs *lz4 = data;
32	u16 distance;
33
34	if (lz4) {
35		if (size < sizeof(struct z_erofs_lz4_cfgs)) {
36			erofs_err(sb, "invalid lz4 cfgs, size=%u", size);
37			return -EINVAL;
38		}
39		distance = le16_to_cpu(lz4->max_distance);
40
41		sbi->lz4.max_pclusterblks = le16_to_cpu(lz4->max_pclusterblks);
42		if (!sbi->lz4.max_pclusterblks) {
43			sbi->lz4.max_pclusterblks = 1;	/* reserved case */
44		} else if (sbi->lz4.max_pclusterblks >
45			   erofs_blknr(sb, Z_EROFS_PCLUSTER_MAX_SIZE)) {
46			erofs_err(sb, "too large lz4 pclusterblks %u",
47				  sbi->lz4.max_pclusterblks);
48			return -EINVAL;
49		}
50	} else {
51		distance = le16_to_cpu(dsb->u1.lz4_max_distance);
52		sbi->lz4.max_pclusterblks = 1;
53	}
54
55	sbi->lz4.max_distance_pages = distance ?
56					DIV_ROUND_UP(distance, PAGE_SIZE) + 1 :
57					LZ4_MAX_DISTANCE_PAGES;
58	return erofs_pcpubuf_growsize(sbi->lz4.max_pclusterblks);
59}
60
61/*
62 * Fill all gaps with bounce pages if it's a sparse page list. Also check if
63 * all physical pages are consecutive, which can be seen for moderate CR.
64 */
65static int z_erofs_lz4_prepare_dstpages(struct z_erofs_lz4_decompress_ctx *ctx,
66					struct page **pagepool)
67{
68	struct z_erofs_decompress_req *rq = ctx->rq;
69	struct page *availables[LZ4_MAX_DISTANCE_PAGES] = { NULL };
70	unsigned long bounced[DIV_ROUND_UP(LZ4_MAX_DISTANCE_PAGES,
71					   BITS_PER_LONG)] = { 0 };
72	unsigned int lz4_max_distance_pages =
73				EROFS_SB(rq->sb)->lz4.max_distance_pages;
74	void *kaddr = NULL;
75	unsigned int i, j, top;
76
77	top = 0;
78	for (i = j = 0; i < ctx->outpages; ++i, ++j) {
79		struct page *const page = rq->out[i];
80		struct page *victim;
81
82		if (j >= lz4_max_distance_pages)
83			j = 0;
84
85		/* 'valid' bounced can only be tested after a complete round */
86		if (!rq->fillgaps && test_bit(j, bounced)) {
87			DBG_BUGON(i < lz4_max_distance_pages);
88			DBG_BUGON(top >= lz4_max_distance_pages);
89			availables[top++] = rq->out[i - lz4_max_distance_pages];
90		}
91
92		if (page) {
93			__clear_bit(j, bounced);
94			if (!PageHighMem(page)) {
95				if (!i) {
96					kaddr = page_address(page);
97					continue;
98				}
99				if (kaddr &&
100				    kaddr + PAGE_SIZE == page_address(page)) {
101					kaddr += PAGE_SIZE;
102					continue;
103				}
104			}
105			kaddr = NULL;
106			continue;
107		}
108		kaddr = NULL;
109		__set_bit(j, bounced);
110
111		if (top) {
112			victim = availables[--top];
113			get_page(victim);
114		} else {
115			victim = erofs_allocpage(pagepool,
116						 GFP_KERNEL | __GFP_NOFAIL);
117			set_page_private(victim, Z_EROFS_SHORTLIVED_PAGE);
118		}
119		rq->out[i] = victim;
120	}
121	return kaddr ? 1 : 0;
122}
123
124static void *z_erofs_lz4_handle_overlap(struct z_erofs_lz4_decompress_ctx *ctx,
125			void *inpage, void *out, unsigned int *inputmargin,
126			int *maptype, bool may_inplace)
127{
128	struct z_erofs_decompress_req *rq = ctx->rq;
129	unsigned int omargin, total, i;
130	struct page **in;
131	void *src, *tmp;
132
133	if (rq->inplace_io) {
134		omargin = PAGE_ALIGN(ctx->oend) - ctx->oend;
135		if (rq->partial_decoding || !may_inplace ||
136		    omargin < LZ4_DECOMPRESS_INPLACE_MARGIN(rq->inputsize))
137			goto docopy;
138
139		for (i = 0; i < ctx->inpages; ++i)
140			if (rq->out[ctx->outpages - ctx->inpages + i] !=
141			    rq->in[i])
142				goto docopy;
143		kunmap_local(inpage);
144		*maptype = 3;
145		return out + ((ctx->outpages - ctx->inpages) << PAGE_SHIFT);
146	}
147
148	if (ctx->inpages <= 1) {
149		*maptype = 0;
150		return inpage;
151	}
152	kunmap_local(inpage);
153	src = erofs_vm_map_ram(rq->in, ctx->inpages);
154	if (!src)
155		return ERR_PTR(-ENOMEM);
156	*maptype = 1;
157	return src;
158
159docopy:
160	/* Or copy compressed data which can be overlapped to per-CPU buffer */
161	in = rq->in;
162	src = erofs_get_pcpubuf(ctx->inpages);
163	if (!src) {
164		DBG_BUGON(1);
165		kunmap_local(inpage);
166		return ERR_PTR(-EFAULT);
167	}
168
169	tmp = src;
170	total = rq->inputsize;
171	while (total) {
172		unsigned int page_copycnt =
173			min_t(unsigned int, total, PAGE_SIZE - *inputmargin);
174
175		if (!inpage)
176			inpage = kmap_local_page(*in);
177		memcpy(tmp, inpage + *inputmargin, page_copycnt);
178		kunmap_local(inpage);
179		inpage = NULL;
180		tmp += page_copycnt;
181		total -= page_copycnt;
182		++in;
183		*inputmargin = 0;
184	}
185	*maptype = 2;
186	return src;
187}
188
189/*
190 * Get the exact inputsize with zero_padding feature.
191 *  - For LZ4, it should work if zero_padding feature is on (5.3+);
192 *  - For MicroLZMA, it'd be enabled all the time.
193 */
194int z_erofs_fixup_insize(struct z_erofs_decompress_req *rq, const char *padbuf,
195			 unsigned int padbufsize)
196{
197	const char *padend;
198
199	padend = memchr_inv(padbuf, 0, padbufsize);
200	if (!padend)
201		return -EFSCORRUPTED;
202	rq->inputsize -= padend - padbuf;
203	rq->pageofs_in += padend - padbuf;
204	return 0;
205}
206
207static int z_erofs_lz4_decompress_mem(struct z_erofs_lz4_decompress_ctx *ctx,
208				      u8 *dst)
209{
210	struct z_erofs_decompress_req *rq = ctx->rq;
211	bool support_0padding = false, may_inplace = false;
212	unsigned int inputmargin;
213	u8 *out, *headpage, *src;
214	int ret, maptype;
215
216	DBG_BUGON(*rq->in == NULL);
217	headpage = kmap_local_page(*rq->in);
218
219	/* LZ4 decompression inplace is only safe if zero_padding is enabled */
220	if (erofs_sb_has_zero_padding(EROFS_SB(rq->sb))) {
221		support_0padding = true;
222		ret = z_erofs_fixup_insize(rq, headpage + rq->pageofs_in,
223				min_t(unsigned int, rq->inputsize,
224				      rq->sb->s_blocksize - rq->pageofs_in));
225		if (ret) {
226			kunmap_local(headpage);
227			return ret;
228		}
229		may_inplace = !((rq->pageofs_in + rq->inputsize) &
230				(rq->sb->s_blocksize - 1));
231	}
232
233	inputmargin = rq->pageofs_in;
234	src = z_erofs_lz4_handle_overlap(ctx, headpage, dst, &inputmargin,
235					 &maptype, may_inplace);
236	if (IS_ERR(src))
237		return PTR_ERR(src);
238
239	out = dst + rq->pageofs_out;
240	/* legacy format could compress extra data in a pcluster. */
241	if (rq->partial_decoding || !support_0padding)
242		ret = LZ4_decompress_safe_partial(src + inputmargin, out,
243				rq->inputsize, rq->outputsize, rq->outputsize);
244	else
245		ret = LZ4_decompress_safe(src + inputmargin, out,
246					  rq->inputsize, rq->outputsize);
247
248	if (ret != rq->outputsize) {
249		erofs_err(rq->sb, "failed to decompress %d in[%u, %u] out[%u]",
250			  ret, rq->inputsize, inputmargin, rq->outputsize);
251
252		print_hex_dump(KERN_DEBUG, "[ in]: ", DUMP_PREFIX_OFFSET,
253			       16, 1, src + inputmargin, rq->inputsize, true);
254		print_hex_dump(KERN_DEBUG, "[out]: ", DUMP_PREFIX_OFFSET,
255			       16, 1, out, rq->outputsize, true);
256
257		if (ret >= 0)
258			memset(out + ret, 0, rq->outputsize - ret);
259		ret = -EIO;
260	} else {
261		ret = 0;
262	}
263
264	if (maptype == 0) {
265		kunmap_local(headpage);
266	} else if (maptype == 1) {
267		vm_unmap_ram(src, ctx->inpages);
268	} else if (maptype == 2) {
269		erofs_put_pcpubuf(src);
270	} else if (maptype != 3) {
271		DBG_BUGON(1);
272		return -EFAULT;
273	}
274	return ret;
275}
276
277static int z_erofs_lz4_decompress(struct z_erofs_decompress_req *rq,
278				  struct page **pagepool)
279{
280	struct z_erofs_lz4_decompress_ctx ctx;
281	unsigned int dst_maptype;
282	void *dst;
283	int ret;
284
285	ctx.rq = rq;
286	ctx.oend = rq->pageofs_out + rq->outputsize;
287	ctx.outpages = PAGE_ALIGN(ctx.oend) >> PAGE_SHIFT;
288	ctx.inpages = PAGE_ALIGN(rq->inputsize) >> PAGE_SHIFT;
289
290	/* one optimized fast path only for non bigpcluster cases yet */
291	if (ctx.inpages == 1 && ctx.outpages == 1 && !rq->inplace_io) {
292		DBG_BUGON(!*rq->out);
293		dst = kmap_local_page(*rq->out);
294		dst_maptype = 0;
295		goto dstmap_out;
296	}
297
298	/* general decoding path which can be used for all cases */
299	ret = z_erofs_lz4_prepare_dstpages(&ctx, pagepool);
300	if (ret < 0) {
301		return ret;
302	} else if (ret > 0) {
303		dst = page_address(*rq->out);
304		dst_maptype = 1;
305	} else {
306		dst = erofs_vm_map_ram(rq->out, ctx.outpages);
307		if (!dst)
308			return -ENOMEM;
309		dst_maptype = 2;
310	}
311
312dstmap_out:
313	ret = z_erofs_lz4_decompress_mem(&ctx, dst);
314	if (!dst_maptype)
315		kunmap_local(dst);
316	else if (dst_maptype == 2)
317		vm_unmap_ram(dst, ctx.outpages);
318	return ret;
319}
320
321static int z_erofs_transform_plain(struct z_erofs_decompress_req *rq,
322				   struct page **pagepool)
323{
324	const unsigned int inpages = PAGE_ALIGN(rq->inputsize) >> PAGE_SHIFT;
325	const unsigned int outpages =
326		PAGE_ALIGN(rq->pageofs_out + rq->outputsize) >> PAGE_SHIFT;
327	const unsigned int righthalf = min_t(unsigned int, rq->outputsize,
328					     PAGE_SIZE - rq->pageofs_out);
329	const unsigned int lefthalf = rq->outputsize - righthalf;
330	const unsigned int interlaced_offset =
331		rq->alg == Z_EROFS_COMPRESSION_SHIFTED ? 0 : rq->pageofs_out;
332	u8 *src;
333
334	if (outpages > 2 && rq->alg == Z_EROFS_COMPRESSION_SHIFTED) {
335		DBG_BUGON(1);
336		return -EFSCORRUPTED;
337	}
338
339	if (rq->out[0] == *rq->in) {
340		DBG_BUGON(rq->pageofs_out);
341		return 0;
342	}
343
344	src = kmap_local_page(rq->in[inpages - 1]) + rq->pageofs_in;
345	if (rq->out[0])
346		memcpy_to_page(rq->out[0], rq->pageofs_out,
347			       src + interlaced_offset, righthalf);
348
349	if (outpages > inpages) {
350		DBG_BUGON(!rq->out[outpages - 1]);
351		if (rq->out[outpages - 1] != rq->in[inpages - 1]) {
352			memcpy_to_page(rq->out[outpages - 1], 0, src +
353					(interlaced_offset ? 0 : righthalf),
354				       lefthalf);
355		} else if (!interlaced_offset) {
356			memmove(src, src + righthalf, lefthalf);
357			flush_dcache_page(rq->in[inpages - 1]);
358		}
359	}
360	kunmap_local(src);
361	return 0;
362}
363
364const struct z_erofs_decompressor erofs_decompressors[] = {
365	[Z_EROFS_COMPRESSION_SHIFTED] = {
366		.decompress = z_erofs_transform_plain,
367		.name = "shifted"
368	},
369	[Z_EROFS_COMPRESSION_INTERLACED] = {
370		.decompress = z_erofs_transform_plain,
371		.name = "interlaced"
372	},
373	[Z_EROFS_COMPRESSION_LZ4] = {
374		.config = z_erofs_load_lz4_config,
375		.decompress = z_erofs_lz4_decompress,
376		.name = "lz4"
377	},
378#ifdef CONFIG_EROFS_FS_ZIP_LZMA
379	[Z_EROFS_COMPRESSION_LZMA] = {
380		.config = z_erofs_load_lzma_config,
381		.decompress = z_erofs_lzma_decompress,
382		.name = "lzma"
383	},
384#endif
385#ifdef CONFIG_EROFS_FS_ZIP_DEFLATE
386	[Z_EROFS_COMPRESSION_DEFLATE] = {
387		.config = z_erofs_load_deflate_config,
388		.decompress = z_erofs_deflate_decompress,
389		.name = "deflate"
390	},
391#endif
392};
393
394int z_erofs_parse_cfgs(struct super_block *sb, struct erofs_super_block *dsb)
395{
396	struct erofs_sb_info *sbi = EROFS_SB(sb);
397	struct erofs_buf buf = __EROFS_BUF_INITIALIZER;
398	unsigned int algs, alg;
399	erofs_off_t offset;
400	int size, ret = 0;
401
402	if (!erofs_sb_has_compr_cfgs(sbi)) {
403		sbi->available_compr_algs = 1 << Z_EROFS_COMPRESSION_LZ4;
404		return z_erofs_load_lz4_config(sb, dsb, NULL, 0);
405	}
406
407	sbi->available_compr_algs = le16_to_cpu(dsb->u1.available_compr_algs);
408	if (sbi->available_compr_algs & ~Z_EROFS_ALL_COMPR_ALGS) {
409		erofs_err(sb, "unidentified algorithms %x, please upgrade kernel",
410			  sbi->available_compr_algs & ~Z_EROFS_ALL_COMPR_ALGS);
411		return -EOPNOTSUPP;
412	}
413
414	erofs_init_metabuf(&buf, sb);
415	offset = EROFS_SUPER_OFFSET + sbi->sb_size;
416	alg = 0;
417	for (algs = sbi->available_compr_algs; algs; algs >>= 1, ++alg) {
418		void *data;
419
420		if (!(algs & 1))
421			continue;
422
423		data = erofs_read_metadata(sb, &buf, &offset, &size);
424		if (IS_ERR(data)) {
425			ret = PTR_ERR(data);
426			break;
427		}
428
429		if (alg >= ARRAY_SIZE(erofs_decompressors) ||
430		    !erofs_decompressors[alg].config) {
431			erofs_err(sb, "algorithm %d isn't enabled on this kernel",
432				  alg);
433			ret = -EOPNOTSUPP;
434		} else {
435			ret = erofs_decompressors[alg].config(sb,
436					dsb, data, size);
437		}
438
439		kfree(data);
440		if (ret)
441			break;
442	}
443	erofs_put_metabuf(&buf);
444	return ret;
445}
446