2 * Squashfs - a compressed read only filesystem for Linux
4 * Copyright (c) 2016-present, Facebook, Inc.
7 * This program is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation; either version 2,
10 * or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
20 #include <linux/mutex.h>
21 #include <linux/buffer_head.h>
22 #include <linux/slab.h>
23 #include <linux/zstd.h>
24 #include <linux/vmalloc.h>
26 #include "squashfs_fs.h"
27 #include "squashfs_fs_sb.h"
29 #include "decompressor.h"
30 #include "page_actor.h"
38 static void *zstd_init(struct squashfs_sb_info
*msblk
, void *buff
)
40 struct workspace
*wksp
= kmalloc(sizeof(*wksp
), GFP_KERNEL
);
44 wksp
->window_size
= max_t(size_t,
45 msblk
->block_size
, SQUASHFS_METADATA_SIZE
);
46 wksp
->mem_size
= ZSTD_DStreamWorkspaceBound(wksp
->window_size
);
47 wksp
->mem
= vmalloc(wksp
->mem_size
);
48 if (wksp
->mem
== NULL
)
54 ERROR("Failed to allocate zstd workspace\n");
56 return ERR_PTR(-ENOMEM
);
60 static void zstd_free(void *strm
)
62 struct workspace
*wksp
= strm
;
70 static int zstd_uncompress(struct squashfs_sb_info
*msblk
, void *strm
,
71 struct buffer_head
**bh
, int b
, int offset
, int length
,
72 struct squashfs_page_actor
*output
)
74 struct workspace
*wksp
= strm
;
79 ZSTD_inBuffer in_buf
= { NULL
, 0, 0 };
80 ZSTD_outBuffer out_buf
= { NULL
, 0, 0 };
82 stream
= ZSTD_initDStream(wksp
->window_size
, wksp
->mem
, wksp
->mem_size
);
85 ERROR("Failed to initialize zstd decompressor\n");
89 out_buf
.size
= PAGE_SIZE
;
90 out_buf
.dst
= squashfs_first_page(output
);
93 if (in_buf
.pos
== in_buf
.size
&& k
< b
) {
94 int avail
= min(length
, msblk
->devblksize
- offset
);
97 in_buf
.src
= bh
[k
]->b_data
+ offset
;
103 if (out_buf
.pos
== out_buf
.size
) {
104 out_buf
.dst
= squashfs_next_page(output
);
105 if (out_buf
.dst
== NULL
) {
106 /* Shouldn't run out of pages
107 * before stream is done.
109 squashfs_finish_page(output
);
113 out_buf
.size
= PAGE_SIZE
;
116 total_out
-= out_buf
.pos
;
117 zstd_err
= ZSTD_decompressStream(stream
, &out_buf
, &in_buf
);
118 total_out
+= out_buf
.pos
; /* add the additional data produced */
120 if (in_buf
.pos
== in_buf
.size
&& k
< b
)
122 } while (zstd_err
!= 0 && !ZSTD_isError(zstd_err
));
124 squashfs_finish_page(output
);
126 if (ZSTD_isError(zstd_err
)) {
127 ERROR("zstd decompression error: %d\n",
128 (int)ZSTD_getErrorCode(zstd_err
));
135 return (int)total_out
;
144 const struct squashfs_decompressor squashfs_zstd_comp_ops
= {
147 .decompress
= zstd_uncompress
,
148 .id
= ZSTD_COMPRESSION
,