1 // SPDX-License-Identifier: GPL-2.0-or-later
3 * Squashfs - a compressed read only filesystem for Linux
5 * Copyright (c) 2016-present, Facebook, Inc.
11 #include <linux/mutex.h>
12 #include <linux/buffer_head.h>
13 #include <linux/slab.h>
14 #include <linux/zstd.h>
15 #include <linux/vmalloc.h>
17 #include "squashfs_fs.h"
18 #include "squashfs_fs_sb.h"
20 #include "decompressor.h"
21 #include "page_actor.h"
29 static void *zstd_init(struct squashfs_sb_info
*msblk
, void *buff
)
31 struct workspace
*wksp
= kmalloc(sizeof(*wksp
), GFP_KERNEL
);
35 wksp
->window_size
= max_t(size_t,
36 msblk
->block_size
, SQUASHFS_METADATA_SIZE
);
37 wksp
->mem_size
= ZSTD_DStreamWorkspaceBound(wksp
->window_size
);
38 wksp
->mem
= vmalloc(wksp
->mem_size
);
39 if (wksp
->mem
== NULL
)
45 ERROR("Failed to allocate zstd workspace\n");
47 return ERR_PTR(-ENOMEM
);
51 static void zstd_free(void *strm
)
53 struct workspace
*wksp
= strm
;
61 static int zstd_uncompress(struct squashfs_sb_info
*msblk
, void *strm
,
62 struct buffer_head
**bh
, int b
, int offset
, int length
,
63 struct squashfs_page_actor
*output
)
65 struct workspace
*wksp
= strm
;
70 ZSTD_inBuffer in_buf
= { NULL
, 0, 0 };
71 ZSTD_outBuffer out_buf
= { NULL
, 0, 0 };
73 stream
= ZSTD_initDStream(wksp
->window_size
, wksp
->mem
, wksp
->mem_size
);
76 ERROR("Failed to initialize zstd decompressor\n");
80 out_buf
.size
= PAGE_SIZE
;
81 out_buf
.dst
= squashfs_first_page(output
);
84 if (in_buf
.pos
== in_buf
.size
&& k
< b
) {
85 int avail
= min(length
, msblk
->devblksize
- offset
);
88 in_buf
.src
= bh
[k
]->b_data
+ offset
;
94 if (out_buf
.pos
== out_buf
.size
) {
95 out_buf
.dst
= squashfs_next_page(output
);
96 if (out_buf
.dst
== NULL
) {
97 /* Shouldn't run out of pages
98 * before stream is done.
100 squashfs_finish_page(output
);
104 out_buf
.size
= PAGE_SIZE
;
107 total_out
-= out_buf
.pos
;
108 zstd_err
= ZSTD_decompressStream(stream
, &out_buf
, &in_buf
);
109 total_out
+= out_buf
.pos
; /* add the additional data produced */
111 if (in_buf
.pos
== in_buf
.size
&& k
< b
)
113 } while (zstd_err
!= 0 && !ZSTD_isError(zstd_err
));
115 squashfs_finish_page(output
);
117 if (ZSTD_isError(zstd_err
)) {
118 ERROR("zstd decompression error: %d\n",
119 (int)ZSTD_getErrorCode(zstd_err
));
126 return (int)total_out
;
135 const struct squashfs_decompressor squashfs_zstd_comp_ops
= {
138 .decompress
= zstd_uncompress
,
139 .id
= ZSTD_COMPRESSION
,