blob: 7869ad12bc6e198ea504e2e5058a498ed24380e6 [file] [log] [blame]
David Sterbac1d7c512018-04-03 19:23:33 +02001// SPDX-License-Identifier: GPL-2.0
Chris Masonc8b97812008-10-29 14:49:59 -04002/*
3 * Copyright (C) 2008 Oracle. All rights reserved.
Chris Masonc8b97812008-10-29 14:49:59 -04004 */
5
6#include <linux/kernel.h>
7#include <linux/bio.h>
Chris Masonc8b97812008-10-29 14:49:59 -04008#include <linux/file.h>
9#include <linux/fs.h>
10#include <linux/pagemap.h>
11#include <linux/highmem.h>
12#include <linux/time.h>
13#include <linux/init.h>
14#include <linux/string.h>
Chris Masonc8b97812008-10-29 14:49:59 -040015#include <linux/backing-dev.h>
Chris Masonc8b97812008-10-29 14:49:59 -040016#include <linux/writeback.h>
Tejun Heo5a0e3ad2010-03-24 17:04:11 +090017#include <linux/slab.h>
David Sterbafe308532017-05-31 17:14:56 +020018#include <linux/sched/mm.h>
Timofey Titovets19562432017-10-08 16:11:59 +030019#include <linux/log2.h>
Johannes Thumshirnd5178572019-06-03 16:58:57 +020020#include <crypto/hash.h>
David Sterba602cbe92019-08-21 18:48:25 +020021#include "misc.h"
Chris Masonc8b97812008-10-29 14:49:59 -040022#include "ctree.h"
23#include "disk-io.h"
24#include "transaction.h"
25#include "btrfs_inode.h"
26#include "volumes.h"
27#include "ordered-data.h"
Chris Masonc8b97812008-10-29 14:49:59 -040028#include "compression.h"
29#include "extent_io.h"
30#include "extent_map.h"
Johannes Thumshirn764c7c92021-05-19 00:40:28 +090031#include "zoned.h"
Chris Masonc8b97812008-10-29 14:49:59 -040032
David Sterbae128f9c2017-10-31 17:24:26 +010033static const char* const btrfs_compress_types[] = { "", "zlib", "lzo", "zstd" };
34
35const char* btrfs_compress_type2str(enum btrfs_compression_type type)
36{
37 switch (type) {
38 case BTRFS_COMPRESS_ZLIB:
39 case BTRFS_COMPRESS_LZO:
40 case BTRFS_COMPRESS_ZSTD:
41 case BTRFS_COMPRESS_NONE:
42 return btrfs_compress_types[type];
Chengguang Xuce96b7f2019-10-10 15:59:57 +080043 default:
44 break;
David Sterbae128f9c2017-10-31 17:24:26 +010045 }
46
47 return NULL;
48}
49
Johannes Thumshirnaa53e3b2019-06-06 12:07:15 +020050bool btrfs_compress_is_valid_type(const char *str, size_t len)
51{
52 int i;
53
54 for (i = 1; i < ARRAY_SIZE(btrfs_compress_types); i++) {
55 size_t comp_len = strlen(btrfs_compress_types[i]);
56
57 if (len < comp_len)
58 continue;
59
60 if (!strncmp(btrfs_compress_types[i], str, comp_len))
61 return true;
62 }
63 return false;
64}
65
David Sterba1e4eb742019-10-02 00:06:15 +020066static int compression_compress_pages(int type, struct list_head *ws,
67 struct address_space *mapping, u64 start, struct page **pages,
68 unsigned long *out_pages, unsigned long *total_in,
69 unsigned long *total_out)
70{
71 switch (type) {
72 case BTRFS_COMPRESS_ZLIB:
73 return zlib_compress_pages(ws, mapping, start, pages,
74 out_pages, total_in, total_out);
75 case BTRFS_COMPRESS_LZO:
76 return lzo_compress_pages(ws, mapping, start, pages,
77 out_pages, total_in, total_out);
78 case BTRFS_COMPRESS_ZSTD:
79 return zstd_compress_pages(ws, mapping, start, pages,
80 out_pages, total_in, total_out);
81 case BTRFS_COMPRESS_NONE:
82 default:
83 /*
Qu Wenruo1d8ba9e2020-08-04 15:25:47 +080084 * This can happen when compression races with remount setting
85 * it to 'no compress', while caller doesn't call
86 * inode_need_compress() to check if we really need to
87 * compress.
88 *
89 * Not a big deal, just need to inform caller that we
90 * haven't allocated any pages yet.
David Sterba1e4eb742019-10-02 00:06:15 +020091 */
Qu Wenruo1d8ba9e2020-08-04 15:25:47 +080092 *out_pages = 0;
David Sterba1e4eb742019-10-02 00:06:15 +020093 return -E2BIG;
94 }
95}
96
97static int compression_decompress_bio(int type, struct list_head *ws,
98 struct compressed_bio *cb)
99{
100 switch (type) {
101 case BTRFS_COMPRESS_ZLIB: return zlib_decompress_bio(ws, cb);
102 case BTRFS_COMPRESS_LZO: return lzo_decompress_bio(ws, cb);
103 case BTRFS_COMPRESS_ZSTD: return zstd_decompress_bio(ws, cb);
104 case BTRFS_COMPRESS_NONE:
105 default:
106 /*
107 * This can't happen, the type is validated several times
108 * before we get here.
109 */
110 BUG();
111 }
112}
113
114static int compression_decompress(int type, struct list_head *ws,
115 unsigned char *data_in, struct page *dest_page,
116 unsigned long start_byte, size_t srclen, size_t destlen)
117{
118 switch (type) {
119 case BTRFS_COMPRESS_ZLIB: return zlib_decompress(ws, data_in, dest_page,
120 start_byte, srclen, destlen);
121 case BTRFS_COMPRESS_LZO: return lzo_decompress(ws, data_in, dest_page,
122 start_byte, srclen, destlen);
123 case BTRFS_COMPRESS_ZSTD: return zstd_decompress(ws, data_in, dest_page,
124 start_byte, srclen, destlen);
125 case BTRFS_COMPRESS_NONE:
126 default:
127 /*
128 * This can't happen, the type is validated several times
129 * before we get here.
130 */
131 BUG();
132 }
133}
134
Anand Jain8140dc32017-05-26 15:44:58 +0800135static int btrfs_decompress_bio(struct compressed_bio *cb);
Eric Sandeen48a3b632013-04-25 20:41:01 +0000136
Jeff Mahoney2ff7e612016-06-22 18:54:24 -0400137static inline int compressed_bio_size(struct btrfs_fs_info *fs_info,
Chris Masond20f7042008-12-08 16:58:54 -0500138 unsigned long disk_size)
139{
Chris Masond20f7042008-12-08 16:58:54 -0500140 return sizeof(struct compressed_bio) +
David Sterba713cebf2020-06-30 18:04:02 +0200141 (DIV_ROUND_UP(disk_size, fs_info->sectorsize)) * fs_info->csum_size;
Chris Masond20f7042008-12-08 16:58:54 -0500142}
143
Nikolay Borisov5a9472f2020-07-02 15:23:34 +0300144static int check_compressed_csum(struct btrfs_inode *inode, struct bio *bio,
Chris Masond20f7042008-12-08 16:58:54 -0500145 u64 disk_start)
146{
Johannes Thumshirn10fe6ca2019-05-22 10:19:02 +0200147 struct btrfs_fs_info *fs_info = inode->root->fs_info;
Johannes Thumshirnd5178572019-06-03 16:58:57 +0200148 SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
David Sterba223486c2020-07-02 11:27:30 +0200149 const u32 csum_size = fs_info->csum_size;
Qu Wenruo04d4ba4c2021-02-04 15:03:24 +0800150 const u32 sectorsize = fs_info->sectorsize;
Chris Masond20f7042008-12-08 16:58:54 -0500151 struct page *page;
Anand Jain1d08ce582021-05-29 17:48:33 +0800152 unsigned int i;
Chris Masond20f7042008-12-08 16:58:54 -0500153 char *kaddr;
Johannes Thumshirnd5178572019-06-03 16:58:57 +0200154 u8 csum[BTRFS_CSUM_SIZE];
Nikolay Borisov5a9472f2020-07-02 15:23:34 +0300155 struct compressed_bio *cb = bio->bi_private;
Johannes Thumshirn10fe6ca2019-05-22 10:19:02 +0200156 u8 *cb_sum = cb->sums;
Chris Masond20f7042008-12-08 16:58:54 -0500157
Josef Bacik42437a62020-10-16 11:29:18 -0400158 if (!fs_info->csum_root || (inode->flags & BTRFS_INODE_NODATASUM))
Chris Masond20f7042008-12-08 16:58:54 -0500159 return 0;
160
Johannes Thumshirnd5178572019-06-03 16:58:57 +0200161 shash->tfm = fs_info->csum_shash;
162
Chris Masond20f7042008-12-08 16:58:54 -0500163 for (i = 0; i < cb->nr_pages; i++) {
Qu Wenruo04d4ba4c2021-02-04 15:03:24 +0800164 u32 pg_offset;
165 u32 bytes_left = PAGE_SIZE;
Chris Masond20f7042008-12-08 16:58:54 -0500166 page = cb->compressed_pages[i];
Chris Masond20f7042008-12-08 16:58:54 -0500167
Qu Wenruo04d4ba4c2021-02-04 15:03:24 +0800168 /* Determine the remaining bytes inside the page first */
169 if (i == cb->nr_pages - 1)
170 bytes_left = cb->compressed_len - i * PAGE_SIZE;
Chris Masond20f7042008-12-08 16:58:54 -0500171
Qu Wenruo04d4ba4c2021-02-04 15:03:24 +0800172 /* Hash through the page sector by sector */
173 for (pg_offset = 0; pg_offset < bytes_left;
174 pg_offset += sectorsize) {
David Sterba4c2bf272021-06-15 17:15:38 +0200175 kaddr = page_address(page);
Qu Wenruo04d4ba4c2021-02-04 15:03:24 +0800176 crypto_shash_digest(shash, kaddr + pg_offset,
177 sectorsize, csum);
Qu Wenruo04d4ba4c2021-02-04 15:03:24 +0800178
179 if (memcmp(&csum, cb_sum, csum_size) != 0) {
180 btrfs_print_data_csum_error(inode, disk_start,
181 csum, cb_sum, cb->mirror_num);
182 if (btrfs_io_bio(bio)->device)
183 btrfs_dev_stat_inc_and_print(
184 btrfs_io_bio(bio)->device,
185 BTRFS_DEV_STAT_CORRUPTION_ERRS);
186 return -EIO;
187 }
188 cb_sum += csum_size;
189 disk_start += sectorsize;
Chris Masond20f7042008-12-08 16:58:54 -0500190 }
Chris Masond20f7042008-12-08 16:58:54 -0500191 }
Nikolay Borisov93c4c032020-07-02 16:46:47 +0300192 return 0;
Chris Masond20f7042008-12-08 16:58:54 -0500193}
194
Chris Masonc8b97812008-10-29 14:49:59 -0400195/* when we finish reading compressed pages from the disk, we
196 * decompress them and then run the bio end_io routines on the
197 * decompressed pages (in the inode address space).
198 *
199 * This allows the checksumming and other IO error handling routines
200 * to work normally
201 *
202 * The compressed pages are freed here, and it must be run
203 * in process context
204 */
Christoph Hellwig4246a0b2015-07-20 15:29:37 +0200205static void end_compressed_bio_read(struct bio *bio)
Chris Masonc8b97812008-10-29 14:49:59 -0400206{
Chris Masonc8b97812008-10-29 14:49:59 -0400207 struct compressed_bio *cb = bio->bi_private;
208 struct inode *inode;
209 struct page *page;
Anand Jain1d08ce582021-05-29 17:48:33 +0800210 unsigned int index;
Liu Bocf1167d2017-09-20 17:50:18 -0600211 unsigned int mirror = btrfs_io_bio(bio)->mirror_num;
Liu Boe6311f22017-09-20 17:50:19 -0600212 int ret = 0;
Chris Masonc8b97812008-10-29 14:49:59 -0400213
Christoph Hellwig4e4cbee2017-06-03 09:38:06 +0200214 if (bio->bi_status)
Chris Masonc8b97812008-10-29 14:49:59 -0400215 cb->errors = 1;
216
217 /* if there are more bios still pending for this compressed
218 * extent, just exit
219 */
Elena Reshetovaa50299a2017-03-03 10:55:20 +0200220 if (!refcount_dec_and_test(&cb->pending_bios))
Chris Masonc8b97812008-10-29 14:49:59 -0400221 goto out;
222
Liu Bocf1167d2017-09-20 17:50:18 -0600223 /*
224 * Record the correct mirror_num in cb->orig_bio so that
225 * read-repair can work properly.
226 */
Liu Bocf1167d2017-09-20 17:50:18 -0600227 btrfs_io_bio(cb->orig_bio)->mirror_num = mirror;
228 cb->mirror_num = mirror;
229
Liu Boe6311f22017-09-20 17:50:19 -0600230 /*
231 * Some IO in this cb have failed, just skip checksum as there
232 * is no way it could be correct.
233 */
234 if (cb->errors == 1)
235 goto csum_failed;
236
Chris Masond20f7042008-12-08 16:58:54 -0500237 inode = cb->inode;
Nikolay Borisov5a9472f2020-07-02 15:23:34 +0300238 ret = check_compressed_csum(BTRFS_I(inode), bio,
David Sterba1201b582020-11-26 15:41:27 +0100239 bio->bi_iter.bi_sector << 9);
Chris Masond20f7042008-12-08 16:58:54 -0500240 if (ret)
241 goto csum_failed;
242
Chris Masonc8b97812008-10-29 14:49:59 -0400243 /* ok, we're the last bio for this extent, lets start
244 * the decompression.
245 */
Anand Jain8140dc32017-05-26 15:44:58 +0800246 ret = btrfs_decompress_bio(cb);
247
Chris Masond20f7042008-12-08 16:58:54 -0500248csum_failed:
Chris Masonc8b97812008-10-29 14:49:59 -0400249 if (ret)
250 cb->errors = 1;
251
252 /* release the compressed pages */
253 index = 0;
254 for (index = 0; index < cb->nr_pages; index++) {
255 page = cb->compressed_pages[index];
256 page->mapping = NULL;
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300257 put_page(page);
Chris Masonc8b97812008-10-29 14:49:59 -0400258 }
259
260 /* do io completion on the original bio */
Chris Mason771ed682008-11-06 22:02:51 -0500261 if (cb->errors) {
Chris Masonc8b97812008-10-29 14:49:59 -0400262 bio_io_error(cb->orig_bio);
Chris Masond20f7042008-12-08 16:58:54 -0500263 } else {
Kent Overstreet2c30c712013-11-07 12:20:26 -0800264 struct bio_vec *bvec;
Ming Lei6dc4f102019-02-15 19:13:19 +0800265 struct bvec_iter_all iter_all;
Chris Masond20f7042008-12-08 16:58:54 -0500266
267 /*
268 * we have verified the checksum already, set page
269 * checked so the end_io handlers know about it
270 */
David Sterbac09abff2017-07-13 18:10:07 +0200271 ASSERT(!bio_flagged(bio, BIO_CLONED));
Christoph Hellwig2b070cf2019-04-25 09:03:00 +0200272 bio_for_each_segment_all(bvec, cb->orig_bio, iter_all)
Chris Masond20f7042008-12-08 16:58:54 -0500273 SetPageChecked(bvec->bv_page);
Kent Overstreet2c30c712013-11-07 12:20:26 -0800274
Christoph Hellwig4246a0b2015-07-20 15:29:37 +0200275 bio_endio(cb->orig_bio);
Chris Masond20f7042008-12-08 16:58:54 -0500276 }
Chris Masonc8b97812008-10-29 14:49:59 -0400277
278 /* finally free the cb struct */
279 kfree(cb->compressed_pages);
280 kfree(cb);
281out:
282 bio_put(bio);
283}
284
285/*
286 * Clear the writeback bits on all of the file
287 * pages for a compressed write
288 */
Filipe Manana7bdcefc2014-10-07 01:48:26 +0100289static noinline void end_compressed_writeback(struct inode *inode,
290 const struct compressed_bio *cb)
Chris Masonc8b97812008-10-29 14:49:59 -0400291{
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300292 unsigned long index = cb->start >> PAGE_SHIFT;
293 unsigned long end_index = (cb->start + cb->len - 1) >> PAGE_SHIFT;
Chris Masonc8b97812008-10-29 14:49:59 -0400294 struct page *pages[16];
295 unsigned long nr_pages = end_index - index + 1;
296 int i;
297 int ret;
298
Filipe Manana7bdcefc2014-10-07 01:48:26 +0100299 if (cb->errors)
300 mapping_set_error(inode->i_mapping, -EIO);
301
Chris Masond3977122009-01-05 21:25:51 -0500302 while (nr_pages > 0) {
Chris Masonc8b97812008-10-29 14:49:59 -0400303 ret = find_get_pages_contig(inode->i_mapping, index,
Chris Mason5b050f02008-11-11 09:34:41 -0500304 min_t(unsigned long,
305 nr_pages, ARRAY_SIZE(pages)), pages);
Chris Masonc8b97812008-10-29 14:49:59 -0400306 if (ret == 0) {
307 nr_pages -= 1;
308 index += 1;
309 continue;
310 }
311 for (i = 0; i < ret; i++) {
Filipe Manana7bdcefc2014-10-07 01:48:26 +0100312 if (cb->errors)
313 SetPageError(pages[i]);
Chris Masonc8b97812008-10-29 14:49:59 -0400314 end_page_writeback(pages[i]);
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300315 put_page(pages[i]);
Chris Masonc8b97812008-10-29 14:49:59 -0400316 }
317 nr_pages -= ret;
318 index += ret;
319 }
320 /* the inode may be gone now */
Chris Masonc8b97812008-10-29 14:49:59 -0400321}
322
323/*
324 * do the cleanup once all the compressed pages hit the disk.
325 * This will clear writeback on the file pages and free the compressed
326 * pages.
327 *
328 * This also calls the writeback end hooks for the file pages so that
329 * metadata and checksums can be updated in the file.
330 */
Christoph Hellwig4246a0b2015-07-20 15:29:37 +0200331static void end_compressed_bio_write(struct bio *bio)
Chris Masonc8b97812008-10-29 14:49:59 -0400332{
Chris Masonc8b97812008-10-29 14:49:59 -0400333 struct compressed_bio *cb = bio->bi_private;
334 struct inode *inode;
335 struct page *page;
Anand Jain1d08ce582021-05-29 17:48:33 +0800336 unsigned int index;
Chris Masonc8b97812008-10-29 14:49:59 -0400337
Christoph Hellwig4e4cbee2017-06-03 09:38:06 +0200338 if (bio->bi_status)
Chris Masonc8b97812008-10-29 14:49:59 -0400339 cb->errors = 1;
340
341 /* if there are more bios still pending for this compressed
342 * extent, just exit
343 */
Elena Reshetovaa50299a2017-03-03 10:55:20 +0200344 if (!refcount_dec_and_test(&cb->pending_bios))
Chris Masonc8b97812008-10-29 14:49:59 -0400345 goto out;
346
347 /* ok, we're the last bio for this extent, step one is to
348 * call back into the FS and do all the end_io operations
349 */
350 inode = cb->inode;
Johannes Thumshirn764c7c92021-05-19 00:40:28 +0900351 btrfs_record_physical_zoned(inode, cb->start, bio);
Qu Wenruo38a39ac72021-04-08 20:32:27 +0800352 btrfs_writepage_endio_finish_ordered(BTRFS_I(inode), NULL,
Nikolay Borisovc6297322018-11-08 10:18:08 +0200353 cb->start, cb->start + cb->len - 1,
Goldwyn Rodrigues240246f2021-07-09 11:29:22 -0500354 !cb->errors);
Chris Masonc8b97812008-10-29 14:49:59 -0400355
Filipe Manana7bdcefc2014-10-07 01:48:26 +0100356 end_compressed_writeback(inode, cb);
Chris Masonc8b97812008-10-29 14:49:59 -0400357 /* note, our inode could be gone now */
358
359 /*
360 * release the compressed pages, these came from alloc_page and
361 * are not attached to the inode at all
362 */
363 index = 0;
364 for (index = 0; index < cb->nr_pages; index++) {
365 page = cb->compressed_pages[index];
366 page->mapping = NULL;
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300367 put_page(page);
Chris Masonc8b97812008-10-29 14:49:59 -0400368 }
369
370 /* finally free the cb struct */
371 kfree(cb->compressed_pages);
372 kfree(cb);
373out:
374 bio_put(bio);
375}
376
377/*
378 * worker function to build and submit bios for previously compressed pages.
379 * The corresponding pages in the inode should be marked for writeback
380 * and the compressed pages should have a reference on them for dropping
381 * when the IO is complete.
382 *
383 * This also checksums the file bytes and gets things ready for
384 * the end io hooks.
385 */
Nikolay Borisovc7ee1812020-06-03 08:55:16 +0300386blk_status_t btrfs_submit_compressed_write(struct btrfs_inode *inode, u64 start,
Anand Jain65b53552021-05-29 17:48:35 +0800387 unsigned int len, u64 disk_start,
388 unsigned int compressed_len,
Chris Masonc8b97812008-10-29 14:49:59 -0400389 struct page **compressed_pages,
Anand Jain65b53552021-05-29 17:48:35 +0800390 unsigned int nr_pages,
Chris Masonec39f762019-07-10 12:28:17 -0700391 unsigned int write_flags,
392 struct cgroup_subsys_state *blkcg_css)
Chris Masonc8b97812008-10-29 14:49:59 -0400393{
Nikolay Borisovc7ee1812020-06-03 08:55:16 +0300394 struct btrfs_fs_info *fs_info = inode->root->fs_info;
Chris Masonc8b97812008-10-29 14:49:59 -0400395 struct bio *bio = NULL;
Chris Masonc8b97812008-10-29 14:49:59 -0400396 struct compressed_bio *cb;
397 unsigned long bytes_left;
David Sterba306e16c2011-04-19 14:29:38 +0200398 int pg_index = 0;
Chris Masonc8b97812008-10-29 14:49:59 -0400399 struct page *page;
400 u64 first_byte = disk_start;
Christoph Hellwig4e4cbee2017-06-03 09:38:06 +0200401 blk_status_t ret;
Nikolay Borisovc7ee1812020-06-03 08:55:16 +0300402 int skip_sum = inode->flags & BTRFS_INODE_NODATASUM;
Johannes Thumshirn764c7c92021-05-19 00:40:28 +0900403 const bool use_append = btrfs_use_zone_append(inode, disk_start);
404 const unsigned int bio_op = use_append ? REQ_OP_ZONE_APPEND : REQ_OP_WRITE;
Chris Masonc8b97812008-10-29 14:49:59 -0400405
Johannes Thumshirnfdb1e122018-12-05 15:23:04 +0100406 WARN_ON(!PAGE_ALIGNED(start));
Jeff Mahoney2ff7e612016-06-22 18:54:24 -0400407 cb = kmalloc(compressed_bio_size(fs_info, compressed_len), GFP_NOFS);
Yoshinori Sanodac97e52011-02-15 12:01:42 +0000408 if (!cb)
Christoph Hellwig4e4cbee2017-06-03 09:38:06 +0200409 return BLK_STS_RESOURCE;
Elena Reshetovaa50299a2017-03-03 10:55:20 +0200410 refcount_set(&cb->pending_bios, 0);
Chris Masonc8b97812008-10-29 14:49:59 -0400411 cb->errors = 0;
Nikolay Borisovc7ee1812020-06-03 08:55:16 +0300412 cb->inode = &inode->vfs_inode;
Chris Masonc8b97812008-10-29 14:49:59 -0400413 cb->start = start;
414 cb->len = len;
Chris Masond20f7042008-12-08 16:58:54 -0500415 cb->mirror_num = 0;
Chris Masonc8b97812008-10-29 14:49:59 -0400416 cb->compressed_pages = compressed_pages;
417 cb->compressed_len = compressed_len;
418 cb->orig_bio = NULL;
419 cb->nr_pages = nr_pages;
420
David Sterbae749af442019-06-18 20:00:16 +0200421 bio = btrfs_bio_alloc(first_byte);
Johannes Thumshirn764c7c92021-05-19 00:40:28 +0900422 bio->bi_opf = bio_op | write_flags;
Chris Masonc8b97812008-10-29 14:49:59 -0400423 bio->bi_private = cb;
424 bio->bi_end_io = end_compressed_bio_write;
Chris Masonec39f762019-07-10 12:28:17 -0700425
Johannes Thumshirn764c7c92021-05-19 00:40:28 +0900426 if (use_append) {
Johannes Thumshirne7ff9e62021-05-19 00:40:29 +0900427 struct btrfs_device *device;
Johannes Thumshirn764c7c92021-05-19 00:40:28 +0900428
Johannes Thumshirne7ff9e62021-05-19 00:40:29 +0900429 device = btrfs_zoned_get_device(fs_info, disk_start, PAGE_SIZE);
430 if (IS_ERR(device)) {
Johannes Thumshirn764c7c92021-05-19 00:40:28 +0900431 kfree(cb);
432 bio_put(bio);
433 return BLK_STS_NOTSUPP;
434 }
435
Johannes Thumshirne7ff9e62021-05-19 00:40:29 +0900436 bio_set_dev(bio, device->bdev);
Johannes Thumshirn764c7c92021-05-19 00:40:28 +0900437 }
438
Chris Masonec39f762019-07-10 12:28:17 -0700439 if (blkcg_css) {
440 bio->bi_opf |= REQ_CGROUP_PUNT;
Dennis Zhou46bcff2b2019-12-11 15:20:15 -0800441 kthread_associate_blkcg(blkcg_css);
Chris Masonec39f762019-07-10 12:28:17 -0700442 }
Elena Reshetovaa50299a2017-03-03 10:55:20 +0200443 refcount_set(&cb->pending_bios, 1);
Chris Masonc8b97812008-10-29 14:49:59 -0400444
445 /* create and submit bios for the compressed pages */
446 bytes_left = compressed_len;
David Sterba306e16c2011-04-19 14:29:38 +0200447 for (pg_index = 0; pg_index < cb->nr_pages; pg_index++) {
Christoph Hellwig4e4cbee2017-06-03 09:38:06 +0200448 int submit = 0;
Qu Wenruo4c80a972021-05-25 13:52:43 +0800449 int len = 0;
Christoph Hellwig4e4cbee2017-06-03 09:38:06 +0200450
David Sterba306e16c2011-04-19 14:29:38 +0200451 page = compressed_pages[pg_index];
Nikolay Borisovc7ee1812020-06-03 08:55:16 +0300452 page->mapping = inode->vfs_inode.i_mapping;
Kent Overstreet4f024f32013-10-11 15:44:27 -0700453 if (bio->bi_iter.bi_size)
Nikolay Borisovda12fe52018-11-27 20:57:58 +0200454 submit = btrfs_bio_fits_in_stripe(page, PAGE_SIZE, bio,
455 0);
Chris Masonc8b97812008-10-29 14:49:59 -0400456
Qu Wenruo4c80a972021-05-25 13:52:43 +0800457 /*
458 * Page can only be added to bio if the current bio fits in
459 * stripe.
460 */
461 if (!submit) {
462 if (pg_index == 0 && use_append)
463 len = bio_add_zone_append_page(bio, page,
464 PAGE_SIZE, 0);
465 else
466 len = bio_add_page(bio, page, PAGE_SIZE, 0);
467 }
Johannes Thumshirn764c7c92021-05-19 00:40:28 +0900468
Chris Mason70b99e62008-10-31 12:46:39 -0400469 page->mapping = NULL;
Johannes Thumshirn764c7c92021-05-19 00:40:28 +0900470 if (submit || len < PAGE_SIZE) {
Chris Masonaf09abf2008-11-07 12:35:44 -0500471 /*
472 * inc the count before we submit the bio so
473 * we know the end IO handler won't happen before
474 * we inc the count. Otherwise, the cb might get
475 * freed before we're done setting it up
476 */
Elena Reshetovaa50299a2017-03-03 10:55:20 +0200477 refcount_inc(&cb->pending_bios);
Jeff Mahoney0b246af2016-06-22 18:54:23 -0400478 ret = btrfs_bio_wq_end_io(fs_info, bio,
479 BTRFS_WQ_ENDIO_DATA);
Jeff Mahoney79787ea2012-03-12 16:03:00 +0100480 BUG_ON(ret); /* -ENOMEM */
Chris Masonc8b97812008-10-29 14:49:59 -0400481
Li Zefane55179b2011-07-14 03:16:47 +0000482 if (!skip_sum) {
Nikolay Borisovc7ee1812020-06-03 08:55:16 +0300483 ret = btrfs_csum_one_bio(inode, bio, start, 1);
Jeff Mahoney79787ea2012-03-12 16:03:00 +0100484 BUG_ON(ret); /* -ENOMEM */
Li Zefane55179b2011-07-14 03:16:47 +0000485 }
Chris Masond20f7042008-12-08 16:58:54 -0500486
Chris Mason08635ba2019-07-10 12:28:14 -0700487 ret = btrfs_map_bio(fs_info, bio, 0);
Liu Bof5daf2c2016-06-22 18:32:06 -0700488 if (ret) {
Christoph Hellwig4e4cbee2017-06-03 09:38:06 +0200489 bio->bi_status = ret;
Liu Bof5daf2c2016-06-22 18:32:06 -0700490 bio_endio(bio);
491 }
Chris Masonc8b97812008-10-29 14:49:59 -0400492
David Sterbae749af442019-06-18 20:00:16 +0200493 bio = btrfs_bio_alloc(first_byte);
Johannes Thumshirn764c7c92021-05-19 00:40:28 +0900494 bio->bi_opf = bio_op | write_flags;
Chris Masonc8b97812008-10-29 14:49:59 -0400495 bio->bi_private = cb;
496 bio->bi_end_io = end_compressed_bio_write;
Dennis Zhou46bcff2b2019-12-11 15:20:15 -0800497 if (blkcg_css)
Dennis Zhou7b62e662019-12-11 16:07:06 -0800498 bio->bi_opf |= REQ_CGROUP_PUNT;
Johannes Thumshirn764c7c92021-05-19 00:40:28 +0900499 /*
500 * Use bio_add_page() to ensure the bio has at least one
501 * page.
502 */
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300503 bio_add_page(bio, page, PAGE_SIZE, 0);
Chris Masonc8b97812008-10-29 14:49:59 -0400504 }
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300505 if (bytes_left < PAGE_SIZE) {
Jeff Mahoney0b246af2016-06-22 18:54:23 -0400506 btrfs_info(fs_info,
David Sterba282ab3f2019-10-14 14:38:33 +0200507 "bytes left %lu compress len %u nr %u",
Chris Masoncfbc2462008-10-30 13:22:14 -0400508 bytes_left, cb->compressed_len, cb->nr_pages);
509 }
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300510 bytes_left -= PAGE_SIZE;
511 first_byte += PAGE_SIZE;
Chris Mason771ed682008-11-06 22:02:51 -0500512 cond_resched();
Chris Masonc8b97812008-10-29 14:49:59 -0400513 }
Chris Masonc8b97812008-10-29 14:49:59 -0400514
Jeff Mahoney0b246af2016-06-22 18:54:23 -0400515 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DATA);
Jeff Mahoney79787ea2012-03-12 16:03:00 +0100516 BUG_ON(ret); /* -ENOMEM */
Chris Masonc8b97812008-10-29 14:49:59 -0400517
Li Zefane55179b2011-07-14 03:16:47 +0000518 if (!skip_sum) {
Nikolay Borisovc7ee1812020-06-03 08:55:16 +0300519 ret = btrfs_csum_one_bio(inode, bio, start, 1);
Jeff Mahoney79787ea2012-03-12 16:03:00 +0100520 BUG_ON(ret); /* -ENOMEM */
Li Zefane55179b2011-07-14 03:16:47 +0000521 }
Chris Masond20f7042008-12-08 16:58:54 -0500522
Chris Mason08635ba2019-07-10 12:28:14 -0700523 ret = btrfs_map_bio(fs_info, bio, 0);
Liu Bof5daf2c2016-06-22 18:32:06 -0700524 if (ret) {
Christoph Hellwig4e4cbee2017-06-03 09:38:06 +0200525 bio->bi_status = ret;
Liu Bof5daf2c2016-06-22 18:32:06 -0700526 bio_endio(bio);
527 }
Chris Masonc8b97812008-10-29 14:49:59 -0400528
Dennis Zhou46bcff2b2019-12-11 15:20:15 -0800529 if (blkcg_css)
530 kthread_associate_blkcg(NULL);
531
Chris Masonc8b97812008-10-29 14:49:59 -0400532 return 0;
533}
534
Christoph Hellwig2a4d0c92016-11-25 09:07:51 +0100535static u64 bio_end_offset(struct bio *bio)
536{
Ming Leic45a8f22017-12-18 20:22:05 +0800537 struct bio_vec *last = bio_last_bvec_all(bio);
Christoph Hellwig2a4d0c92016-11-25 09:07:51 +0100538
539 return page_offset(last->bv_page) + last->bv_len + last->bv_offset;
540}
541
Chris Mason771ed682008-11-06 22:02:51 -0500542static noinline int add_ra_bio_pages(struct inode *inode,
543 u64 compressed_end,
544 struct compressed_bio *cb)
545{
546 unsigned long end_index;
David Sterba306e16c2011-04-19 14:29:38 +0200547 unsigned long pg_index;
Chris Mason771ed682008-11-06 22:02:51 -0500548 u64 last_offset;
549 u64 isize = i_size_read(inode);
550 int ret;
551 struct page *page;
552 unsigned long nr_pages = 0;
553 struct extent_map *em;
554 struct address_space *mapping = inode->i_mapping;
Chris Mason771ed682008-11-06 22:02:51 -0500555 struct extent_map_tree *em_tree;
556 struct extent_io_tree *tree;
557 u64 end;
558 int misses = 0;
559
Christoph Hellwig2a4d0c92016-11-25 09:07:51 +0100560 last_offset = bio_end_offset(cb->orig_bio);
Chris Mason771ed682008-11-06 22:02:51 -0500561 em_tree = &BTRFS_I(inode)->extent_tree;
562 tree = &BTRFS_I(inode)->io_tree;
563
564 if (isize == 0)
565 return 0;
566
Qu Wenruoca62e852021-07-26 14:34:52 +0800567 /*
568 * For current subpage support, we only support 64K page size,
569 * which means maximum compressed extent size (128K) is just 2x page
570 * size.
571 * This makes readahead less effective, so here disable readahead for
572 * subpage for now, until full compressed write is supported.
573 */
574 if (btrfs_sb(inode->i_sb)->sectorsize < PAGE_SIZE)
575 return 0;
576
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300577 end_index = (i_size_read(inode) - 1) >> PAGE_SHIFT;
Chris Mason771ed682008-11-06 22:02:51 -0500578
Chris Masond3977122009-01-05 21:25:51 -0500579 while (last_offset < compressed_end) {
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300580 pg_index = last_offset >> PAGE_SHIFT;
Chris Mason771ed682008-11-06 22:02:51 -0500581
David Sterba306e16c2011-04-19 14:29:38 +0200582 if (pg_index > end_index)
Chris Mason771ed682008-11-06 22:02:51 -0500583 break;
584
Matthew Wilcox0a943c62017-12-04 10:37:22 -0500585 page = xa_load(&mapping->i_pages, pg_index);
Matthew Wilcox3159f942017-11-03 13:30:42 -0400586 if (page && !xa_is_value(page)) {
Chris Mason771ed682008-11-06 22:02:51 -0500587 misses++;
588 if (misses > 4)
589 break;
590 goto next;
591 }
592
Michal Hockoc62d2552015-11-06 16:28:49 -0800593 page = __page_cache_alloc(mapping_gfp_constraint(mapping,
594 ~__GFP_FS));
Chris Mason771ed682008-11-06 22:02:51 -0500595 if (!page)
596 break;
597
Michal Hockoc62d2552015-11-06 16:28:49 -0800598 if (add_to_page_cache_lru(page, mapping, pg_index, GFP_NOFS)) {
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300599 put_page(page);
Chris Mason771ed682008-11-06 22:02:51 -0500600 goto next;
601 }
602
Chris Mason771ed682008-11-06 22:02:51 -0500603 /*
604 * at this point, we have a locked page in the page cache
605 * for these bytes in the file. But, we have to make
606 * sure they map to this compressed extent on disk.
607 */
Qu Wenruo32443de2021-01-26 16:34:00 +0800608 ret = set_page_extent_mapped(page);
609 if (ret < 0) {
610 unlock_page(page);
611 put_page(page);
612 break;
613 }
614
615 end = last_offset + PAGE_SIZE - 1;
Jeff Mahoneyd0082372012-03-01 14:57:19 +0100616 lock_extent(tree, last_offset, end);
Chris Mason890871b2009-09-02 16:24:52 -0400617 read_lock(&em_tree->lock);
Chris Mason771ed682008-11-06 22:02:51 -0500618 em = lookup_extent_mapping(em_tree, last_offset,
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300619 PAGE_SIZE);
Chris Mason890871b2009-09-02 16:24:52 -0400620 read_unlock(&em_tree->lock);
Chris Mason771ed682008-11-06 22:02:51 -0500621
622 if (!em || last_offset < em->start ||
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300623 (last_offset + PAGE_SIZE > extent_map_end(em)) ||
Kent Overstreet4f024f32013-10-11 15:44:27 -0700624 (em->block_start >> 9) != cb->orig_bio->bi_iter.bi_sector) {
Chris Mason771ed682008-11-06 22:02:51 -0500625 free_extent_map(em);
Jeff Mahoneyd0082372012-03-01 14:57:19 +0100626 unlock_extent(tree, last_offset, end);
Chris Mason771ed682008-11-06 22:02:51 -0500627 unlock_page(page);
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300628 put_page(page);
Chris Mason771ed682008-11-06 22:02:51 -0500629 break;
630 }
631 free_extent_map(em);
632
633 if (page->index == end_index) {
Johannes Thumshirn70730172018-12-05 15:23:03 +0100634 size_t zero_offset = offset_in_page(isize);
Chris Mason771ed682008-11-06 22:02:51 -0500635
636 if (zero_offset) {
637 int zeros;
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300638 zeros = PAGE_SIZE - zero_offset;
Ira Weinyd048b9c2021-05-04 18:40:07 -0700639 memzero_page(page, zero_offset, zeros);
Chris Mason771ed682008-11-06 22:02:51 -0500640 flush_dcache_page(page);
Chris Mason771ed682008-11-06 22:02:51 -0500641 }
642 }
643
644 ret = bio_add_page(cb->orig_bio, page,
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300645 PAGE_SIZE, 0);
Chris Mason771ed682008-11-06 22:02:51 -0500646
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300647 if (ret == PAGE_SIZE) {
Chris Mason771ed682008-11-06 22:02:51 -0500648 nr_pages++;
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300649 put_page(page);
Chris Mason771ed682008-11-06 22:02:51 -0500650 } else {
Jeff Mahoneyd0082372012-03-01 14:57:19 +0100651 unlock_extent(tree, last_offset, end);
Chris Mason771ed682008-11-06 22:02:51 -0500652 unlock_page(page);
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300653 put_page(page);
Chris Mason771ed682008-11-06 22:02:51 -0500654 break;
655 }
656next:
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300657 last_offset += PAGE_SIZE;
Chris Mason771ed682008-11-06 22:02:51 -0500658 }
Chris Mason771ed682008-11-06 22:02:51 -0500659 return 0;
660}
661
Chris Masonc8b97812008-10-29 14:49:59 -0400662/*
663 * for a compressed read, the bio we get passed has all the inode pages
664 * in it. We don't actually do IO on those pages but allocate new ones
665 * to hold the compressed pages on disk.
666 *
Kent Overstreet4f024f32013-10-11 15:44:27 -0700667 * bio->bi_iter.bi_sector points to the compressed extent on disk
Chris Masonc8b97812008-10-29 14:49:59 -0400668 * bio->bi_io_vec points to all of the inode pages
Chris Masonc8b97812008-10-29 14:49:59 -0400669 *
670 * After the compressed pages are read, we copy the bytes into the
671 * bio we were passed and then call the bio end_io calls
672 */
Christoph Hellwig4e4cbee2017-06-03 09:38:06 +0200673blk_status_t btrfs_submit_compressed_read(struct inode *inode, struct bio *bio,
Chris Masonc8b97812008-10-29 14:49:59 -0400674 int mirror_num, unsigned long bio_flags)
675{
Jeff Mahoney0b246af2016-06-22 18:54:23 -0400676 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
Chris Masonc8b97812008-10-29 14:49:59 -0400677 struct extent_map_tree *em_tree;
678 struct compressed_bio *cb;
Anand Jain356b4a22021-05-29 17:48:34 +0800679 unsigned int compressed_len;
680 unsigned int nr_pages;
681 unsigned int pg_index;
Chris Masonc8b97812008-10-29 14:49:59 -0400682 struct page *page;
Chris Masonc8b97812008-10-29 14:49:59 -0400683 struct bio *comp_bio;
David Sterba1201b582020-11-26 15:41:27 +0100684 u64 cur_disk_byte = bio->bi_iter.bi_sector << 9;
Qu Wenruo557023e2021-07-05 10:00:56 +0800685 u64 file_offset;
Chris Masone04ca622008-11-10 11:44:58 -0500686 u64 em_len;
687 u64 em_start;
Chris Masonc8b97812008-10-29 14:49:59 -0400688 struct extent_map *em;
Christoph Hellwig4e4cbee2017-06-03 09:38:06 +0200689 blk_status_t ret = BLK_STS_RESOURCE;
Josef Bacik15e3004a2012-10-05 13:39:50 -0400690 int faili = 0;
Johannes Thumshirn10fe6ca2019-05-22 10:19:02 +0200691 u8 *sums;
Chris Masonc8b97812008-10-29 14:49:59 -0400692
Chris Masonc8b97812008-10-29 14:49:59 -0400693 em_tree = &BTRFS_I(inode)->extent_tree;
694
Qu Wenruo557023e2021-07-05 10:00:56 +0800695 file_offset = bio_first_bvec_all(bio)->bv_offset +
696 page_offset(bio_first_page_all(bio));
697
Chris Masonc8b97812008-10-29 14:49:59 -0400698 /* we need the actual starting offset of this extent in the file */
Chris Mason890871b2009-09-02 16:24:52 -0400699 read_lock(&em_tree->lock);
Qu Wenruo557023e2021-07-05 10:00:56 +0800700 em = lookup_extent_mapping(em_tree, file_offset, fs_info->sectorsize);
Chris Mason890871b2009-09-02 16:24:52 -0400701 read_unlock(&em_tree->lock);
Tsutomu Itoh285190d2012-02-16 16:23:58 +0900702 if (!em)
Christoph Hellwig4e4cbee2017-06-03 09:38:06 +0200703 return BLK_STS_IOERR;
Chris Masonc8b97812008-10-29 14:49:59 -0400704
Qu Wenruo557023e2021-07-05 10:00:56 +0800705 ASSERT(em->compress_type != BTRFS_COMPRESS_NONE);
Chris Masond20f7042008-12-08 16:58:54 -0500706 compressed_len = em->block_len;
Jeff Mahoney2ff7e612016-06-22 18:54:24 -0400707 cb = kmalloc(compressed_bio_size(fs_info, compressed_len), GFP_NOFS);
liubo6b82ce82011-01-26 06:21:39 +0000708 if (!cb)
709 goto out;
710
Elena Reshetovaa50299a2017-03-03 10:55:20 +0200711 refcount_set(&cb->pending_bios, 0);
Chris Masonc8b97812008-10-29 14:49:59 -0400712 cb->errors = 0;
713 cb->inode = inode;
Chris Masond20f7042008-12-08 16:58:54 -0500714 cb->mirror_num = mirror_num;
Johannes Thumshirn10fe6ca2019-05-22 10:19:02 +0200715 sums = cb->sums;
Chris Masonc8b97812008-10-29 14:49:59 -0400716
Yan Zhengff5b7ee2008-11-10 07:34:43 -0500717 cb->start = em->orig_start;
Chris Masone04ca622008-11-10 11:44:58 -0500718 em_len = em->len;
719 em_start = em->start;
Chris Masond20f7042008-12-08 16:58:54 -0500720
Chris Masonc8b97812008-10-29 14:49:59 -0400721 free_extent_map(em);
Chris Masone04ca622008-11-10 11:44:58 -0500722 em = NULL;
Chris Masonc8b97812008-10-29 14:49:59 -0400723
Christoph Hellwig81381052016-11-25 09:07:50 +0100724 cb->len = bio->bi_iter.bi_size;
Chris Masonc8b97812008-10-29 14:49:59 -0400725 cb->compressed_len = compressed_len;
Li Zefan261507a02010-12-17 14:21:50 +0800726 cb->compress_type = extent_compress_type(bio_flags);
Chris Masonc8b97812008-10-29 14:49:59 -0400727 cb->orig_bio = bio;
728
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300729 nr_pages = DIV_ROUND_UP(compressed_len, PAGE_SIZE);
David Sterba31e818f2015-02-20 18:00:26 +0100730 cb->compressed_pages = kcalloc(nr_pages, sizeof(struct page *),
Chris Masonc8b97812008-10-29 14:49:59 -0400731 GFP_NOFS);
liubo6b82ce82011-01-26 06:21:39 +0000732 if (!cb->compressed_pages)
733 goto fail1;
734
David Sterba306e16c2011-04-19 14:29:38 +0200735 for (pg_index = 0; pg_index < nr_pages; pg_index++) {
David Sterbab0ee5e12021-06-14 22:22:22 +0200736 cb->compressed_pages[pg_index] = alloc_page(GFP_NOFS);
Josef Bacik15e3004a2012-10-05 13:39:50 -0400737 if (!cb->compressed_pages[pg_index]) {
738 faili = pg_index - 1;
Dan Carpenter0e9350d2017-06-19 13:55:37 +0300739 ret = BLK_STS_RESOURCE;
liubo6b82ce82011-01-26 06:21:39 +0000740 goto fail2;
Josef Bacik15e3004a2012-10-05 13:39:50 -0400741 }
Chris Masonc8b97812008-10-29 14:49:59 -0400742 }
Josef Bacik15e3004a2012-10-05 13:39:50 -0400743 faili = nr_pages - 1;
Chris Masonc8b97812008-10-29 14:49:59 -0400744 cb->nr_pages = nr_pages;
745
Filipe Manana7f042a82016-01-27 19:17:20 +0000746 add_ra_bio_pages(inode, em_start + em_len, cb);
Chris Mason771ed682008-11-06 22:02:51 -0500747
Chris Mason771ed682008-11-06 22:02:51 -0500748 /* include any pages we added in add_ra-bio_pages */
Christoph Hellwig81381052016-11-25 09:07:50 +0100749 cb->len = bio->bi_iter.bi_size;
Chris Mason771ed682008-11-06 22:02:51 -0500750
David Sterbae749af442019-06-18 20:00:16 +0200751 comp_bio = btrfs_bio_alloc(cur_disk_byte);
David Sterbaebcc3262018-06-29 10:56:53 +0200752 comp_bio->bi_opf = REQ_OP_READ;
Chris Masonc8b97812008-10-29 14:49:59 -0400753 comp_bio->bi_private = cb;
754 comp_bio->bi_end_io = end_compressed_bio_read;
Elena Reshetovaa50299a2017-03-03 10:55:20 +0200755 refcount_set(&cb->pending_bios, 1);
Chris Masonc8b97812008-10-29 14:49:59 -0400756
David Sterba306e16c2011-04-19 14:29:38 +0200757 for (pg_index = 0; pg_index < nr_pages; pg_index++) {
Qu Wenruobe6a1362021-02-04 15:03:23 +0800758 u32 pg_len = PAGE_SIZE;
Christoph Hellwig4e4cbee2017-06-03 09:38:06 +0200759 int submit = 0;
760
Qu Wenruobe6a1362021-02-04 15:03:23 +0800761 /*
762 * To handle subpage case, we need to make sure the bio only
763 * covers the range we need.
764 *
765 * If we're at the last page, truncate the length to only cover
766 * the remaining part.
767 */
768 if (pg_index == nr_pages - 1)
769 pg_len = min_t(u32, PAGE_SIZE,
770 compressed_len - pg_index * PAGE_SIZE);
771
David Sterba306e16c2011-04-19 14:29:38 +0200772 page = cb->compressed_pages[pg_index];
Chris Masonc8b97812008-10-29 14:49:59 -0400773 page->mapping = inode->i_mapping;
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300774 page->index = em_start >> PAGE_SHIFT;
Chris Masond20f7042008-12-08 16:58:54 -0500775
Kent Overstreet4f024f32013-10-11 15:44:27 -0700776 if (comp_bio->bi_iter.bi_size)
Qu Wenruobe6a1362021-02-04 15:03:23 +0800777 submit = btrfs_bio_fits_in_stripe(page, pg_len,
Nikolay Borisovda12fe52018-11-27 20:57:58 +0200778 comp_bio, 0);
Chris Masonc8b97812008-10-29 14:49:59 -0400779
Chris Mason70b99e62008-10-31 12:46:39 -0400780 page->mapping = NULL;
Qu Wenruobe6a1362021-02-04 15:03:23 +0800781 if (submit || bio_add_page(comp_bio, page, pg_len, 0) < pg_len) {
Johannes Thumshirn10fe6ca2019-05-22 10:19:02 +0200782 unsigned int nr_sectors;
783
Jeff Mahoney0b246af2016-06-22 18:54:23 -0400784 ret = btrfs_bio_wq_end_io(fs_info, comp_bio,
785 BTRFS_WQ_ENDIO_DATA);
Jeff Mahoney79787ea2012-03-12 16:03:00 +0100786 BUG_ON(ret); /* -ENOMEM */
Chris Masonc8b97812008-10-29 14:49:59 -0400787
Chris Masonaf09abf2008-11-07 12:35:44 -0500788 /*
789 * inc the count before we submit the bio so
790 * we know the end IO handler won't happen before
791 * we inc the count. Otherwise, the cb might get
792 * freed before we're done setting it up
793 */
Elena Reshetovaa50299a2017-03-03 10:55:20 +0200794 refcount_inc(&cb->pending_bios);
Chris Masonaf09abf2008-11-07 12:35:44 -0500795
Qu Wenruo62751932020-12-02 14:48:06 +0800796 ret = btrfs_lookup_bio_sums(inode, comp_bio, sums);
Josef Bacik334c16d2020-10-16 11:29:14 -0400797 BUG_ON(ret); /* -ENOMEM */
Johannes Thumshirn10fe6ca2019-05-22 10:19:02 +0200798
799 nr_sectors = DIV_ROUND_UP(comp_bio->bi_iter.bi_size,
800 fs_info->sectorsize);
David Sterba713cebf2020-06-30 18:04:02 +0200801 sums += fs_info->csum_size * nr_sectors;
Chris Masond20f7042008-12-08 16:58:54 -0500802
Chris Mason08635ba2019-07-10 12:28:14 -0700803 ret = btrfs_map_bio(fs_info, comp_bio, mirror_num);
Christoph Hellwig4246a0b2015-07-20 15:29:37 +0200804 if (ret) {
Christoph Hellwig4e4cbee2017-06-03 09:38:06 +0200805 comp_bio->bi_status = ret;
Christoph Hellwig4246a0b2015-07-20 15:29:37 +0200806 bio_endio(comp_bio);
807 }
Chris Masonc8b97812008-10-29 14:49:59 -0400808
David Sterbae749af442019-06-18 20:00:16 +0200809 comp_bio = btrfs_bio_alloc(cur_disk_byte);
David Sterbaebcc3262018-06-29 10:56:53 +0200810 comp_bio->bi_opf = REQ_OP_READ;
Chris Mason771ed682008-11-06 22:02:51 -0500811 comp_bio->bi_private = cb;
812 comp_bio->bi_end_io = end_compressed_bio_read;
813
Qu Wenruobe6a1362021-02-04 15:03:23 +0800814 bio_add_page(comp_bio, page, pg_len, 0);
Chris Masonc8b97812008-10-29 14:49:59 -0400815 }
Qu Wenruobe6a1362021-02-04 15:03:23 +0800816 cur_disk_byte += pg_len;
Chris Masonc8b97812008-10-29 14:49:59 -0400817 }
Chris Masonc8b97812008-10-29 14:49:59 -0400818
Jeff Mahoney0b246af2016-06-22 18:54:23 -0400819 ret = btrfs_bio_wq_end_io(fs_info, comp_bio, BTRFS_WQ_ENDIO_DATA);
Jeff Mahoney79787ea2012-03-12 16:03:00 +0100820 BUG_ON(ret); /* -ENOMEM */
Chris Masonc8b97812008-10-29 14:49:59 -0400821
Qu Wenruo62751932020-12-02 14:48:06 +0800822 ret = btrfs_lookup_bio_sums(inode, comp_bio, sums);
Josef Bacik334c16d2020-10-16 11:29:14 -0400823 BUG_ON(ret); /* -ENOMEM */
Chris Masond20f7042008-12-08 16:58:54 -0500824
Chris Mason08635ba2019-07-10 12:28:14 -0700825 ret = btrfs_map_bio(fs_info, comp_bio, mirror_num);
Christoph Hellwig4246a0b2015-07-20 15:29:37 +0200826 if (ret) {
Christoph Hellwig4e4cbee2017-06-03 09:38:06 +0200827 comp_bio->bi_status = ret;
Christoph Hellwig4246a0b2015-07-20 15:29:37 +0200828 bio_endio(comp_bio);
829 }
Chris Masonc8b97812008-10-29 14:49:59 -0400830
Chris Masonc8b97812008-10-29 14:49:59 -0400831 return 0;
liubo6b82ce82011-01-26 06:21:39 +0000832
833fail2:
Josef Bacik15e3004a2012-10-05 13:39:50 -0400834 while (faili >= 0) {
835 __free_page(cb->compressed_pages[faili]);
836 faili--;
837 }
liubo6b82ce82011-01-26 06:21:39 +0000838
839 kfree(cb->compressed_pages);
840fail1:
841 kfree(cb);
842out:
843 free_extent_map(em);
844 return ret;
Chris Masonc8b97812008-10-29 14:49:59 -0400845}
Li Zefan261507a02010-12-17 14:21:50 +0800846
Timofey Titovets17b5a6c2017-09-28 17:33:37 +0300847/*
848 * Heuristic uses systematic sampling to collect data from the input data
849 * range, the logic can be tuned by the following constants:
850 *
851 * @SAMPLING_READ_SIZE - how many bytes will be copied from for each sample
852 * @SAMPLING_INTERVAL - range from which the sampled data can be collected
853 */
854#define SAMPLING_READ_SIZE (16)
855#define SAMPLING_INTERVAL (256)
856
857/*
858 * For statistical analysis of the input data we consider bytes that form a
859 * Galois Field of 256 objects. Each object has an attribute count, ie. how
860 * many times the object appeared in the sample.
861 */
862#define BUCKET_SIZE (256)
863
864/*
865 * The size of the sample is based on a statistical sampling rule of thumb.
866 * The common way is to perform sampling tests as long as the number of
867 * elements in each cell is at least 5.
868 *
869 * Instead of 5, we choose 32 to obtain more accurate results.
870 * If the data contain the maximum number of symbols, which is 256, we obtain a
871 * sample size bound by 8192.
872 *
873 * For a sample of at most 8KB of data per data range: 16 consecutive bytes
874 * from up to 512 locations.
875 */
876#define MAX_SAMPLE_SIZE (BTRFS_MAX_UNCOMPRESSED * \
877 SAMPLING_READ_SIZE / SAMPLING_INTERVAL)
878
879struct bucket_item {
880 u32 count;
881};
Timofey Titovets4e439a02017-09-28 17:33:36 +0300882
883struct heuristic_ws {
Timofey Titovets17b5a6c2017-09-28 17:33:37 +0300884 /* Partial copy of input data */
885 u8 *sample;
Timofey Titovetsa440d482017-09-28 17:33:38 +0300886 u32 sample_size;
Timofey Titovets17b5a6c2017-09-28 17:33:37 +0300887 /* Buckets store counters for each byte value */
888 struct bucket_item *bucket;
Timofey Titovets440c8402017-12-04 00:30:33 +0300889 /* Sorting buffer */
890 struct bucket_item *bucket_b;
Timofey Titovets4e439a02017-09-28 17:33:36 +0300891 struct list_head list;
892};
893
Dennis Zhou92ee55302019-02-04 15:20:03 -0500894static struct workspace_manager heuristic_wsm;
895
Timofey Titovets4e439a02017-09-28 17:33:36 +0300896static void free_heuristic_ws(struct list_head *ws)
897{
898 struct heuristic_ws *workspace;
899
900 workspace = list_entry(ws, struct heuristic_ws, list);
901
Timofey Titovets17b5a6c2017-09-28 17:33:37 +0300902 kvfree(workspace->sample);
903 kfree(workspace->bucket);
Timofey Titovets440c8402017-12-04 00:30:33 +0300904 kfree(workspace->bucket_b);
Timofey Titovets4e439a02017-09-28 17:33:36 +0300905 kfree(workspace);
906}
907
Dennis Zhou7bf49942019-02-04 15:20:04 -0500908static struct list_head *alloc_heuristic_ws(unsigned int level)
Timofey Titovets4e439a02017-09-28 17:33:36 +0300909{
910 struct heuristic_ws *ws;
911
912 ws = kzalloc(sizeof(*ws), GFP_KERNEL);
913 if (!ws)
914 return ERR_PTR(-ENOMEM);
915
Timofey Titovets17b5a6c2017-09-28 17:33:37 +0300916 ws->sample = kvmalloc(MAX_SAMPLE_SIZE, GFP_KERNEL);
917 if (!ws->sample)
918 goto fail;
Timofey Titovets4e439a02017-09-28 17:33:36 +0300919
Timofey Titovets17b5a6c2017-09-28 17:33:37 +0300920 ws->bucket = kcalloc(BUCKET_SIZE, sizeof(*ws->bucket), GFP_KERNEL);
921 if (!ws->bucket)
922 goto fail;
923
Timofey Titovets440c8402017-12-04 00:30:33 +0300924 ws->bucket_b = kcalloc(BUCKET_SIZE, sizeof(*ws->bucket_b), GFP_KERNEL);
925 if (!ws->bucket_b)
926 goto fail;
927
Timofey Titovets17b5a6c2017-09-28 17:33:37 +0300928 INIT_LIST_HEAD(&ws->list);
Timofey Titovets4e439a02017-09-28 17:33:36 +0300929 return &ws->list;
Timofey Titovets17b5a6c2017-09-28 17:33:37 +0300930fail:
931 free_heuristic_ws(&ws->list);
932 return ERR_PTR(-ENOMEM);
Timofey Titovets4e439a02017-09-28 17:33:36 +0300933}
934
Dennis Zhouca4ac362019-02-04 15:19:59 -0500935const struct btrfs_compress_op btrfs_heuristic_compress = {
David Sterbabe9510452019-10-02 00:53:31 +0200936 .workspace_manager = &heuristic_wsm,
Dennis Zhouca4ac362019-02-04 15:19:59 -0500937};
938
David Sterbae8c9f182015-01-02 18:23:10 +0100939static const struct btrfs_compress_op * const btrfs_compress_op[] = {
Dennis Zhouca4ac362019-02-04 15:19:59 -0500940 /* The heuristic is represented as compression type 0 */
941 &btrfs_heuristic_compress,
Li Zefan261507a02010-12-17 14:21:50 +0800942 &btrfs_zlib_compress,
Li Zefana6fa6fa2010-10-25 15:12:26 +0800943 &btrfs_lzo_compress,
Nick Terrell5c1aab12017-08-09 19:39:02 -0700944 &btrfs_zstd_compress,
Li Zefan261507a02010-12-17 14:21:50 +0800945};
946
David Sterbac778df12019-10-04 02:47:39 +0200947static struct list_head *alloc_workspace(int type, unsigned int level)
948{
949 switch (type) {
950 case BTRFS_COMPRESS_NONE: return alloc_heuristic_ws(level);
951 case BTRFS_COMPRESS_ZLIB: return zlib_alloc_workspace(level);
952 case BTRFS_COMPRESS_LZO: return lzo_alloc_workspace(level);
953 case BTRFS_COMPRESS_ZSTD: return zstd_alloc_workspace(level);
954 default:
955 /*
956 * This can't happen, the type is validated several times
957 * before we get here.
958 */
959 BUG();
960 }
961}
962
David Sterba1e002352019-10-04 02:57:22 +0200963static void free_workspace(int type, struct list_head *ws)
964{
965 switch (type) {
966 case BTRFS_COMPRESS_NONE: return free_heuristic_ws(ws);
967 case BTRFS_COMPRESS_ZLIB: return zlib_free_workspace(ws);
968 case BTRFS_COMPRESS_LZO: return lzo_free_workspace(ws);
969 case BTRFS_COMPRESS_ZSTD: return zstd_free_workspace(ws);
970 default:
971 /*
972 * This can't happen, the type is validated several times
973 * before we get here.
974 */
975 BUG();
976 }
977}
978
David Sterbad5517032019-10-02 01:08:03 +0200979static void btrfs_init_workspace_manager(int type)
Li Zefan261507a02010-12-17 14:21:50 +0800980{
David Sterba0cf25212019-10-04 03:09:55 +0200981 struct workspace_manager *wsm;
Timofey Titovets4e439a02017-09-28 17:33:36 +0300982 struct list_head *workspace;
Li Zefan261507a02010-12-17 14:21:50 +0800983
David Sterba0cf25212019-10-04 03:09:55 +0200984 wsm = btrfs_compress_op[type]->workspace_manager;
Dennis Zhou92ee55302019-02-04 15:20:03 -0500985 INIT_LIST_HEAD(&wsm->idle_ws);
986 spin_lock_init(&wsm->ws_lock);
987 atomic_set(&wsm->total_ws, 0);
988 init_waitqueue_head(&wsm->ws_wait);
David Sterbaf77dd0d2016-04-27 02:55:15 +0200989
Dennis Zhou1666eda2019-02-04 15:20:01 -0500990 /*
991 * Preallocate one workspace for each compression type so we can
992 * guarantee forward progress in the worst case
993 */
David Sterbac778df12019-10-04 02:47:39 +0200994 workspace = alloc_workspace(type, 0);
Dennis Zhou1666eda2019-02-04 15:20:01 -0500995 if (IS_ERR(workspace)) {
996 pr_warn(
997 "BTRFS: cannot preallocate compression workspace, will try later\n");
998 } else {
Dennis Zhou92ee55302019-02-04 15:20:03 -0500999 atomic_set(&wsm->total_ws, 1);
1000 wsm->free_ws = 1;
1001 list_add(workspace, &wsm->idle_ws);
Dennis Zhou1666eda2019-02-04 15:20:01 -05001002 }
1003}
1004
David Sterba25103072019-10-02 01:08:03 +02001005static void btrfs_cleanup_workspace_manager(int type)
Dennis Zhou1666eda2019-02-04 15:20:01 -05001006{
David Sterba2dba7142019-10-04 01:40:58 +02001007 struct workspace_manager *wsman;
Dennis Zhou1666eda2019-02-04 15:20:01 -05001008 struct list_head *ws;
1009
David Sterba2dba7142019-10-04 01:40:58 +02001010 wsman = btrfs_compress_op[type]->workspace_manager;
Dennis Zhou1666eda2019-02-04 15:20:01 -05001011 while (!list_empty(&wsman->idle_ws)) {
1012 ws = wsman->idle_ws.next;
1013 list_del(ws);
David Sterba1e002352019-10-04 02:57:22 +02001014 free_workspace(type, ws);
Dennis Zhou1666eda2019-02-04 15:20:01 -05001015 atomic_dec(&wsman->total_ws);
Li Zefan261507a02010-12-17 14:21:50 +08001016 }
Li Zefan261507a02010-12-17 14:21:50 +08001017}
1018
1019/*
David Sterbae721e492016-04-27 02:41:17 +02001020 * This finds an available workspace or allocates a new one.
1021 * If it's not possible to allocate a new one, waits until there's one.
1022 * Preallocation makes a forward progress guarantees and we do not return
1023 * errors.
Li Zefan261507a02010-12-17 14:21:50 +08001024 */
David Sterba5907a9b2019-10-04 02:50:28 +02001025struct list_head *btrfs_get_workspace(int type, unsigned int level)
Li Zefan261507a02010-12-17 14:21:50 +08001026{
David Sterba5907a9b2019-10-04 02:50:28 +02001027 struct workspace_manager *wsm;
Li Zefan261507a02010-12-17 14:21:50 +08001028 struct list_head *workspace;
1029 int cpus = num_online_cpus();
David Sterbafe308532017-05-31 17:14:56 +02001030 unsigned nofs_flag;
Timofey Titovets4e439a02017-09-28 17:33:36 +03001031 struct list_head *idle_ws;
1032 spinlock_t *ws_lock;
1033 atomic_t *total_ws;
1034 wait_queue_head_t *ws_wait;
1035 int *free_ws;
Li Zefan261507a02010-12-17 14:21:50 +08001036
David Sterba5907a9b2019-10-04 02:50:28 +02001037 wsm = btrfs_compress_op[type]->workspace_manager;
Dennis Zhou92ee55302019-02-04 15:20:03 -05001038 idle_ws = &wsm->idle_ws;
1039 ws_lock = &wsm->ws_lock;
1040 total_ws = &wsm->total_ws;
1041 ws_wait = &wsm->ws_wait;
1042 free_ws = &wsm->free_ws;
Timofey Titovets4e439a02017-09-28 17:33:36 +03001043
Li Zefan261507a02010-12-17 14:21:50 +08001044again:
Byongho Leed9187642015-10-14 14:05:24 +09001045 spin_lock(ws_lock);
1046 if (!list_empty(idle_ws)) {
1047 workspace = idle_ws->next;
Li Zefan261507a02010-12-17 14:21:50 +08001048 list_del(workspace);
David Sterba6ac10a62016-04-27 02:15:15 +02001049 (*free_ws)--;
Byongho Leed9187642015-10-14 14:05:24 +09001050 spin_unlock(ws_lock);
Li Zefan261507a02010-12-17 14:21:50 +08001051 return workspace;
1052
1053 }
David Sterba6ac10a62016-04-27 02:15:15 +02001054 if (atomic_read(total_ws) > cpus) {
Li Zefan261507a02010-12-17 14:21:50 +08001055 DEFINE_WAIT(wait);
1056
Byongho Leed9187642015-10-14 14:05:24 +09001057 spin_unlock(ws_lock);
1058 prepare_to_wait(ws_wait, &wait, TASK_UNINTERRUPTIBLE);
David Sterba6ac10a62016-04-27 02:15:15 +02001059 if (atomic_read(total_ws) > cpus && !*free_ws)
Li Zefan261507a02010-12-17 14:21:50 +08001060 schedule();
Byongho Leed9187642015-10-14 14:05:24 +09001061 finish_wait(ws_wait, &wait);
Li Zefan261507a02010-12-17 14:21:50 +08001062 goto again;
1063 }
David Sterba6ac10a62016-04-27 02:15:15 +02001064 atomic_inc(total_ws);
Byongho Leed9187642015-10-14 14:05:24 +09001065 spin_unlock(ws_lock);
Li Zefan261507a02010-12-17 14:21:50 +08001066
David Sterbafe308532017-05-31 17:14:56 +02001067 /*
1068 * Allocation helpers call vmalloc that can't use GFP_NOFS, so we have
1069 * to turn it off here because we might get called from the restricted
1070 * context of btrfs_compress_bio/btrfs_compress_pages
1071 */
1072 nofs_flag = memalloc_nofs_save();
David Sterbac778df12019-10-04 02:47:39 +02001073 workspace = alloc_workspace(type, level);
David Sterbafe308532017-05-31 17:14:56 +02001074 memalloc_nofs_restore(nofs_flag);
1075
Li Zefan261507a02010-12-17 14:21:50 +08001076 if (IS_ERR(workspace)) {
David Sterba6ac10a62016-04-27 02:15:15 +02001077 atomic_dec(total_ws);
Byongho Leed9187642015-10-14 14:05:24 +09001078 wake_up(ws_wait);
David Sterbae721e492016-04-27 02:41:17 +02001079
1080 /*
1081 * Do not return the error but go back to waiting. There's a
1082 * workspace preallocated for each type and the compression
1083 * time is bounded so we get to a workspace eventually. This
1084 * makes our caller's life easier.
David Sterba523567162016-04-27 03:07:39 +02001085 *
1086 * To prevent silent and low-probability deadlocks (when the
1087 * initial preallocation fails), check if there are any
1088 * workspaces at all.
David Sterbae721e492016-04-27 02:41:17 +02001089 */
David Sterba523567162016-04-27 03:07:39 +02001090 if (atomic_read(total_ws) == 0) {
1091 static DEFINE_RATELIMIT_STATE(_rs,
1092 /* once per minute */ 60 * HZ,
1093 /* no burst */ 1);
1094
1095 if (__ratelimit(&_rs)) {
Jeff Mahoneyab8d0fc2016-09-20 10:05:02 -04001096 pr_warn("BTRFS: no compression workspaces, low memory, retrying\n");
David Sterba523567162016-04-27 03:07:39 +02001097 }
1098 }
David Sterbae721e492016-04-27 02:41:17 +02001099 goto again;
Li Zefan261507a02010-12-17 14:21:50 +08001100 }
1101 return workspace;
1102}
1103
Dennis Zhou7bf49942019-02-04 15:20:04 -05001104static struct list_head *get_workspace(int type, int level)
Dennis Zhou929f4ba2019-02-04 15:20:02 -05001105{
David Sterba6a0d1272019-10-04 02:36:16 +02001106 switch (type) {
David Sterba5907a9b2019-10-04 02:50:28 +02001107 case BTRFS_COMPRESS_NONE: return btrfs_get_workspace(type, level);
David Sterba6a0d1272019-10-04 02:36:16 +02001108 case BTRFS_COMPRESS_ZLIB: return zlib_get_workspace(level);
David Sterba5907a9b2019-10-04 02:50:28 +02001109 case BTRFS_COMPRESS_LZO: return btrfs_get_workspace(type, level);
David Sterba6a0d1272019-10-04 02:36:16 +02001110 case BTRFS_COMPRESS_ZSTD: return zstd_get_workspace(level);
1111 default:
1112 /*
1113 * This can't happen, the type is validated several times
1114 * before we get here.
1115 */
1116 BUG();
1117 }
Dennis Zhou929f4ba2019-02-04 15:20:02 -05001118}
1119
Li Zefan261507a02010-12-17 14:21:50 +08001120/*
1121 * put a workspace struct back on the list or free it if we have enough
1122 * idle ones sitting around
1123 */
David Sterbaa3bbd2a2019-10-04 02:50:28 +02001124void btrfs_put_workspace(int type, struct list_head *ws)
Li Zefan261507a02010-12-17 14:21:50 +08001125{
David Sterbaa3bbd2a2019-10-04 02:50:28 +02001126 struct workspace_manager *wsm;
Timofey Titovets4e439a02017-09-28 17:33:36 +03001127 struct list_head *idle_ws;
1128 spinlock_t *ws_lock;
1129 atomic_t *total_ws;
1130 wait_queue_head_t *ws_wait;
1131 int *free_ws;
1132
David Sterbaa3bbd2a2019-10-04 02:50:28 +02001133 wsm = btrfs_compress_op[type]->workspace_manager;
Dennis Zhou92ee55302019-02-04 15:20:03 -05001134 idle_ws = &wsm->idle_ws;
1135 ws_lock = &wsm->ws_lock;
1136 total_ws = &wsm->total_ws;
1137 ws_wait = &wsm->ws_wait;
1138 free_ws = &wsm->free_ws;
Li Zefan261507a02010-12-17 14:21:50 +08001139
Byongho Leed9187642015-10-14 14:05:24 +09001140 spin_lock(ws_lock);
Nick Terrell26b28dc2017-06-29 10:57:26 -07001141 if (*free_ws <= num_online_cpus()) {
Dennis Zhou929f4ba2019-02-04 15:20:02 -05001142 list_add(ws, idle_ws);
David Sterba6ac10a62016-04-27 02:15:15 +02001143 (*free_ws)++;
Byongho Leed9187642015-10-14 14:05:24 +09001144 spin_unlock(ws_lock);
Li Zefan261507a02010-12-17 14:21:50 +08001145 goto wake;
1146 }
Byongho Leed9187642015-10-14 14:05:24 +09001147 spin_unlock(ws_lock);
Li Zefan261507a02010-12-17 14:21:50 +08001148
David Sterba1e002352019-10-04 02:57:22 +02001149 free_workspace(type, ws);
David Sterba6ac10a62016-04-27 02:15:15 +02001150 atomic_dec(total_ws);
Li Zefan261507a02010-12-17 14:21:50 +08001151wake:
David Sterba093258e2018-02-26 16:15:17 +01001152 cond_wake_up(ws_wait);
Li Zefan261507a02010-12-17 14:21:50 +08001153}
1154
Dennis Zhou929f4ba2019-02-04 15:20:02 -05001155static void put_workspace(int type, struct list_head *ws)
1156{
David Sterbabd3a5282019-10-04 02:42:03 +02001157 switch (type) {
David Sterbaa3bbd2a2019-10-04 02:50:28 +02001158 case BTRFS_COMPRESS_NONE: return btrfs_put_workspace(type, ws);
1159 case BTRFS_COMPRESS_ZLIB: return btrfs_put_workspace(type, ws);
1160 case BTRFS_COMPRESS_LZO: return btrfs_put_workspace(type, ws);
David Sterbabd3a5282019-10-04 02:42:03 +02001161 case BTRFS_COMPRESS_ZSTD: return zstd_put_workspace(ws);
1162 default:
1163 /*
1164 * This can't happen, the type is validated several times
1165 * before we get here.
1166 */
1167 BUG();
1168 }
Dennis Zhou929f4ba2019-02-04 15:20:02 -05001169}
1170
Li Zefan261507a02010-12-17 14:21:50 +08001171/*
Anand Jainadbab642020-05-11 22:37:51 -07001172 * Adjust @level according to the limits of the compression algorithm or
1173 * fallback to default
1174 */
1175static unsigned int btrfs_compress_set_level(int type, unsigned level)
1176{
1177 const struct btrfs_compress_op *ops = btrfs_compress_op[type];
1178
1179 if (level == 0)
1180 level = ops->default_level;
1181 else
1182 level = min(level, ops->max_level);
1183
1184 return level;
1185}
1186
1187/*
David Sterba38c31462017-02-14 19:04:07 +01001188 * Given an address space and start and length, compress the bytes into @pages
1189 * that are allocated on demand.
Li Zefan261507a02010-12-17 14:21:50 +08001190 *
David Sterbaf51d2b52017-09-15 17:36:57 +02001191 * @type_level is encoded algorithm and level, where level 0 means whatever
1192 * default the algorithm chooses and is opaque here;
1193 * - compression algo are 0-3
1194 * - the level are bits 4-7
1195 *
David Sterba4d3a8002017-02-14 19:04:07 +01001196 * @out_pages is an in/out parameter, holds maximum number of pages to allocate
1197 * and returns number of actually allocated pages
Li Zefan261507a02010-12-17 14:21:50 +08001198 *
David Sterba38c31462017-02-14 19:04:07 +01001199 * @total_in is used to return the number of bytes actually read. It
1200 * may be smaller than the input length if we had to exit early because we
Li Zefan261507a02010-12-17 14:21:50 +08001201 * ran out of room in the pages array or because we cross the
1202 * max_out threshold.
1203 *
David Sterba38c31462017-02-14 19:04:07 +01001204 * @total_out is an in/out parameter, must be set to the input length and will
1205 * be also used to return the total number of compressed bytes
Li Zefan261507a02010-12-17 14:21:50 +08001206 */
David Sterbaf51d2b52017-09-15 17:36:57 +02001207int btrfs_compress_pages(unsigned int type_level, struct address_space *mapping,
David Sterba38c31462017-02-14 19:04:07 +01001208 u64 start, struct page **pages,
Li Zefan261507a02010-12-17 14:21:50 +08001209 unsigned long *out_pages,
1210 unsigned long *total_in,
David Sterbae5d74902017-02-14 19:45:05 +01001211 unsigned long *total_out)
Li Zefan261507a02010-12-17 14:21:50 +08001212{
Dennis Zhou19727082019-02-04 15:19:57 -05001213 int type = btrfs_compress_type(type_level);
Dennis Zhou7bf49942019-02-04 15:20:04 -05001214 int level = btrfs_compress_level(type_level);
Li Zefan261507a02010-12-17 14:21:50 +08001215 struct list_head *workspace;
1216 int ret;
1217
David Sterbab0c1fe12019-08-09 16:49:06 +02001218 level = btrfs_compress_set_level(type, level);
Dennis Zhou7bf49942019-02-04 15:20:04 -05001219 workspace = get_workspace(type, level);
David Sterba1e4eb742019-10-02 00:06:15 +02001220 ret = compression_compress_pages(type, workspace, mapping, start, pages,
1221 out_pages, total_in, total_out);
Dennis Zhou929f4ba2019-02-04 15:20:02 -05001222 put_workspace(type, workspace);
Li Zefan261507a02010-12-17 14:21:50 +08001223 return ret;
1224}
1225
Anand Jain8140dc32017-05-26 15:44:58 +08001226static int btrfs_decompress_bio(struct compressed_bio *cb)
Li Zefan261507a02010-12-17 14:21:50 +08001227{
1228 struct list_head *workspace;
1229 int ret;
Anand Jain8140dc32017-05-26 15:44:58 +08001230 int type = cb->compress_type;
Li Zefan261507a02010-12-17 14:21:50 +08001231
Dennis Zhou7bf49942019-02-04 15:20:04 -05001232 workspace = get_workspace(type, 0);
David Sterba1e4eb742019-10-02 00:06:15 +02001233 ret = compression_decompress_bio(type, workspace, cb);
Dennis Zhou929f4ba2019-02-04 15:20:02 -05001234 put_workspace(type, workspace);
Anand Jaine1ddce72017-05-26 15:44:59 +08001235
Li Zefan261507a02010-12-17 14:21:50 +08001236 return ret;
1237}
1238
1239/*
1240 * a less complex decompression routine. Our compressed data fits in a
1241 * single page, and we want to read a single page out of it.
1242 * start_byte tells us the offset into the compressed data we're interested in
1243 */
1244int btrfs_decompress(int type, unsigned char *data_in, struct page *dest_page,
1245 unsigned long start_byte, size_t srclen, size_t destlen)
1246{
1247 struct list_head *workspace;
1248 int ret;
1249
Dennis Zhou7bf49942019-02-04 15:20:04 -05001250 workspace = get_workspace(type, 0);
David Sterba1e4eb742019-10-02 00:06:15 +02001251 ret = compression_decompress(type, workspace, data_in, dest_page,
1252 start_byte, srclen, destlen);
Dennis Zhou929f4ba2019-02-04 15:20:02 -05001253 put_workspace(type, workspace);
Dennis Zhou7bf49942019-02-04 15:20:04 -05001254
Li Zefan261507a02010-12-17 14:21:50 +08001255 return ret;
1256}
1257
Dennis Zhou1666eda2019-02-04 15:20:01 -05001258void __init btrfs_init_compress(void)
1259{
David Sterbad5517032019-10-02 01:08:03 +02001260 btrfs_init_workspace_manager(BTRFS_COMPRESS_NONE);
1261 btrfs_init_workspace_manager(BTRFS_COMPRESS_ZLIB);
1262 btrfs_init_workspace_manager(BTRFS_COMPRESS_LZO);
1263 zstd_init_workspace_manager();
Dennis Zhou1666eda2019-02-04 15:20:01 -05001264}
1265
David Sterbae67c7182018-02-19 17:24:18 +01001266void __cold btrfs_exit_compress(void)
Li Zefan261507a02010-12-17 14:21:50 +08001267{
David Sterba25103072019-10-02 01:08:03 +02001268 btrfs_cleanup_workspace_manager(BTRFS_COMPRESS_NONE);
1269 btrfs_cleanup_workspace_manager(BTRFS_COMPRESS_ZLIB);
1270 btrfs_cleanup_workspace_manager(BTRFS_COMPRESS_LZO);
1271 zstd_cleanup_workspace_manager();
Li Zefan261507a02010-12-17 14:21:50 +08001272}
Li Zefan3a39c182010-11-08 15:22:19 +08001273
1274/*
Qu Wenruo1c3dc172021-07-05 10:00:58 +08001275 * Copy decompressed data from working buffer to pages.
Li Zefan3a39c182010-11-08 15:22:19 +08001276 *
Qu Wenruo1c3dc172021-07-05 10:00:58 +08001277 * @buf: The decompressed data buffer
1278 * @buf_len: The decompressed data length
1279 * @decompressed: Number of bytes that are already decompressed inside the
1280 * compressed extent
1281 * @cb: The compressed extent descriptor
1282 * @orig_bio: The original bio that the caller wants to read for
Li Zefan3a39c182010-11-08 15:22:19 +08001283 *
Qu Wenruo1c3dc172021-07-05 10:00:58 +08001284 * An easier to understand graph is like below:
1285 *
1286 * |<- orig_bio ->| |<- orig_bio->|
1287 * |<------- full decompressed extent ----->|
1288 * |<----------- @cb range ---->|
1289 * | |<-- @buf_len -->|
1290 * |<--- @decompressed --->|
1291 *
1292 * Note that, @cb can be a subpage of the full decompressed extent, but
1293 * @cb->start always has the same as the orig_file_offset value of the full
1294 * decompressed extent.
1295 *
1296 * When reading compressed extent, we have to read the full compressed extent,
1297 * while @orig_bio may only want part of the range.
1298 * Thus this function will ensure only data covered by @orig_bio will be copied
1299 * to.
1300 *
1301 * Return 0 if we have copied all needed contents for @orig_bio.
1302 * Return >0 if we need continue decompress.
Li Zefan3a39c182010-11-08 15:22:19 +08001303 */
Qu Wenruo1c3dc172021-07-05 10:00:58 +08001304int btrfs_decompress_buf2page(const char *buf, u32 buf_len,
1305 struct compressed_bio *cb, u32 decompressed)
Li Zefan3a39c182010-11-08 15:22:19 +08001306{
Qu Wenruo1c3dc172021-07-05 10:00:58 +08001307 struct bio *orig_bio = cb->orig_bio;
1308 /* Offset inside the full decompressed extent */
1309 u32 cur_offset;
Li Zefan3a39c182010-11-08 15:22:19 +08001310
Qu Wenruo1c3dc172021-07-05 10:00:58 +08001311 cur_offset = decompressed;
1312 /* The main loop to do the copy */
1313 while (cur_offset < decompressed + buf_len) {
1314 struct bio_vec bvec;
1315 size_t copy_len;
1316 u32 copy_start;
1317 /* Offset inside the full decompressed extent */
1318 u32 bvec_offset;
Li Zefan3a39c182010-11-08 15:22:19 +08001319
Qu Wenruo1c3dc172021-07-05 10:00:58 +08001320 bvec = bio_iter_iovec(orig_bio, orig_bio->bi_iter);
1321 /*
1322 * cb->start may underflow, but subtracting that value can still
1323 * give us correct offset inside the full decompressed extent.
1324 */
1325 bvec_offset = page_offset(bvec.bv_page) + bvec.bv_offset - cb->start;
Li Zefan3a39c182010-11-08 15:22:19 +08001326
Qu Wenruo1c3dc172021-07-05 10:00:58 +08001327 /* Haven't reached the bvec range, exit */
1328 if (decompressed + buf_len <= bvec_offset)
1329 return 1;
Li Zefan3a39c182010-11-08 15:22:19 +08001330
Qu Wenruo1c3dc172021-07-05 10:00:58 +08001331 copy_start = max(cur_offset, bvec_offset);
1332 copy_len = min(bvec_offset + bvec.bv_len,
1333 decompressed + buf_len) - copy_start;
1334 ASSERT(copy_len);
Li Zefan3a39c182010-11-08 15:22:19 +08001335
Christoph Hellwig974b1ad2016-11-25 09:07:46 +01001336 /*
Qu Wenruo1c3dc172021-07-05 10:00:58 +08001337 * Extra range check to ensure we didn't go beyond
1338 * @buf + @buf_len.
Christoph Hellwig974b1ad2016-11-25 09:07:46 +01001339 */
Qu Wenruo1c3dc172021-07-05 10:00:58 +08001340 ASSERT(copy_start - decompressed < buf_len);
1341 memcpy_to_page(bvec.bv_page, bvec.bv_offset,
1342 buf + copy_start - decompressed, copy_len);
1343 flush_dcache_page(bvec.bv_page);
1344 cur_offset += copy_len;
Li Zefan3a39c182010-11-08 15:22:19 +08001345
Qu Wenruo1c3dc172021-07-05 10:00:58 +08001346 bio_advance(orig_bio, copy_len);
1347 /* Finished the bio */
1348 if (!orig_bio->bi_iter.bi_size)
1349 return 0;
Li Zefan3a39c182010-11-08 15:22:19 +08001350 }
Li Zefan3a39c182010-11-08 15:22:19 +08001351 return 1;
1352}
Timofey Titovetsc2fcdcd2017-07-17 16:52:58 +03001353
Timofey Titovets19562432017-10-08 16:11:59 +03001354/*
1355 * Shannon Entropy calculation
1356 *
Andrea Gelmini52042d82018-11-28 12:05:13 +01001357 * Pure byte distribution analysis fails to determine compressibility of data.
Timofey Titovets19562432017-10-08 16:11:59 +03001358 * Try calculating entropy to estimate the average minimum number of bits
1359 * needed to encode the sampled data.
1360 *
1361 * For convenience, return the percentage of needed bits, instead of amount of
1362 * bits directly.
1363 *
1364 * @ENTROPY_LVL_ACEPTABLE - below that threshold, sample has low byte entropy
1365 * and can be compressible with high probability
1366 *
1367 * @ENTROPY_LVL_HIGH - data are not compressible with high probability
1368 *
1369 * Use of ilog2() decreases precision, we lower the LVL to 5 to compensate.
1370 */
1371#define ENTROPY_LVL_ACEPTABLE (65)
1372#define ENTROPY_LVL_HIGH (80)
1373
1374/*
1375 * For increasead precision in shannon_entropy calculation,
1376 * let's do pow(n, M) to save more digits after comma:
1377 *
1378 * - maximum int bit length is 64
1379 * - ilog2(MAX_SAMPLE_SIZE) -> 13
1380 * - 13 * 4 = 52 < 64 -> M = 4
1381 *
1382 * So use pow(n, 4).
1383 */
1384static inline u32 ilog2_w(u64 n)
1385{
1386 return ilog2(n * n * n * n);
1387}
1388
1389static u32 shannon_entropy(struct heuristic_ws *ws)
1390{
1391 const u32 entropy_max = 8 * ilog2_w(2);
1392 u32 entropy_sum = 0;
1393 u32 p, p_base, sz_base;
1394 u32 i;
1395
1396 sz_base = ilog2_w(ws->sample_size);
1397 for (i = 0; i < BUCKET_SIZE && ws->bucket[i].count > 0; i++) {
1398 p = ws->bucket[i].count;
1399 p_base = ilog2_w(p);
1400 entropy_sum += p * (sz_base - p_base);
1401 }
1402
1403 entropy_sum /= ws->sample_size;
1404 return entropy_sum * 100 / entropy_max;
1405}
1406
Timofey Titovets440c8402017-12-04 00:30:33 +03001407#define RADIX_BASE 4U
1408#define COUNTERS_SIZE (1U << RADIX_BASE)
Timofey Titovets858177d2017-09-28 17:33:41 +03001409
Timofey Titovets440c8402017-12-04 00:30:33 +03001410static u8 get4bits(u64 num, int shift) {
1411 u8 low4bits;
1412
1413 num >>= shift;
1414 /* Reverse order */
1415 low4bits = (COUNTERS_SIZE - 1) - (num % COUNTERS_SIZE);
1416 return low4bits;
1417}
1418
Timofey Titovets440c8402017-12-04 00:30:33 +03001419/*
1420 * Use 4 bits as radix base
Andrea Gelmini52042d82018-11-28 12:05:13 +01001421 * Use 16 u32 counters for calculating new position in buf array
Timofey Titovets440c8402017-12-04 00:30:33 +03001422 *
1423 * @array - array that will be sorted
1424 * @array_buf - buffer array to store sorting results
1425 * must be equal in size to @array
1426 * @num - array size
Timofey Titovets440c8402017-12-04 00:30:33 +03001427 */
David Sterba23ae8c62017-12-12 20:35:02 +01001428static void radix_sort(struct bucket_item *array, struct bucket_item *array_buf,
David Sterba36243c92017-12-12 20:35:02 +01001429 int num)
Timofey Titovets440c8402017-12-04 00:30:33 +03001430{
1431 u64 max_num;
1432 u64 buf_num;
1433 u32 counters[COUNTERS_SIZE];
1434 u32 new_addr;
1435 u32 addr;
1436 int bitlen;
1437 int shift;
1438 int i;
1439
1440 /*
1441 * Try avoid useless loop iterations for small numbers stored in big
1442 * counters. Example: 48 33 4 ... in 64bit array
1443 */
David Sterba23ae8c62017-12-12 20:35:02 +01001444 max_num = array[0].count;
Timofey Titovets440c8402017-12-04 00:30:33 +03001445 for (i = 1; i < num; i++) {
David Sterba23ae8c62017-12-12 20:35:02 +01001446 buf_num = array[i].count;
Timofey Titovets440c8402017-12-04 00:30:33 +03001447 if (buf_num > max_num)
1448 max_num = buf_num;
1449 }
1450
1451 buf_num = ilog2(max_num);
1452 bitlen = ALIGN(buf_num, RADIX_BASE * 2);
1453
1454 shift = 0;
1455 while (shift < bitlen) {
1456 memset(counters, 0, sizeof(counters));
1457
1458 for (i = 0; i < num; i++) {
David Sterba23ae8c62017-12-12 20:35:02 +01001459 buf_num = array[i].count;
Timofey Titovets440c8402017-12-04 00:30:33 +03001460 addr = get4bits(buf_num, shift);
1461 counters[addr]++;
1462 }
1463
1464 for (i = 1; i < COUNTERS_SIZE; i++)
1465 counters[i] += counters[i - 1];
1466
1467 for (i = num - 1; i >= 0; i--) {
David Sterba23ae8c62017-12-12 20:35:02 +01001468 buf_num = array[i].count;
Timofey Titovets440c8402017-12-04 00:30:33 +03001469 addr = get4bits(buf_num, shift);
1470 counters[addr]--;
1471 new_addr = counters[addr];
David Sterba7add17b2017-12-12 20:35:02 +01001472 array_buf[new_addr] = array[i];
Timofey Titovets440c8402017-12-04 00:30:33 +03001473 }
1474
1475 shift += RADIX_BASE;
1476
1477 /*
1478 * Normal radix expects to move data from a temporary array, to
1479 * the main one. But that requires some CPU time. Avoid that
1480 * by doing another sort iteration to original array instead of
1481 * memcpy()
1482 */
1483 memset(counters, 0, sizeof(counters));
1484
1485 for (i = 0; i < num; i ++) {
David Sterba23ae8c62017-12-12 20:35:02 +01001486 buf_num = array_buf[i].count;
Timofey Titovets440c8402017-12-04 00:30:33 +03001487 addr = get4bits(buf_num, shift);
1488 counters[addr]++;
1489 }
1490
1491 for (i = 1; i < COUNTERS_SIZE; i++)
1492 counters[i] += counters[i - 1];
1493
1494 for (i = num - 1; i >= 0; i--) {
David Sterba23ae8c62017-12-12 20:35:02 +01001495 buf_num = array_buf[i].count;
Timofey Titovets440c8402017-12-04 00:30:33 +03001496 addr = get4bits(buf_num, shift);
1497 counters[addr]--;
1498 new_addr = counters[addr];
David Sterba7add17b2017-12-12 20:35:02 +01001499 array[new_addr] = array_buf[i];
Timofey Titovets440c8402017-12-04 00:30:33 +03001500 }
1501
1502 shift += RADIX_BASE;
1503 }
Timofey Titovets858177d2017-09-28 17:33:41 +03001504}
1505
1506/*
1507 * Size of the core byte set - how many bytes cover 90% of the sample
1508 *
1509 * There are several types of structured binary data that use nearly all byte
1510 * values. The distribution can be uniform and counts in all buckets will be
1511 * nearly the same (eg. encrypted data). Unlikely to be compressible.
1512 *
1513 * Other possibility is normal (Gaussian) distribution, where the data could
1514 * be potentially compressible, but we have to take a few more steps to decide
1515 * how much.
1516 *
1517 * @BYTE_CORE_SET_LOW - main part of byte values repeated frequently,
1518 * compression algo can easy fix that
1519 * @BYTE_CORE_SET_HIGH - data have uniform distribution and with high
1520 * probability is not compressible
1521 */
1522#define BYTE_CORE_SET_LOW (64)
1523#define BYTE_CORE_SET_HIGH (200)
1524
1525static int byte_core_set_size(struct heuristic_ws *ws)
1526{
1527 u32 i;
1528 u32 coreset_sum = 0;
1529 const u32 core_set_threshold = ws->sample_size * 90 / 100;
1530 struct bucket_item *bucket = ws->bucket;
1531
1532 /* Sort in reverse order */
David Sterba36243c92017-12-12 20:35:02 +01001533 radix_sort(ws->bucket, ws->bucket_b, BUCKET_SIZE);
Timofey Titovets858177d2017-09-28 17:33:41 +03001534
1535 for (i = 0; i < BYTE_CORE_SET_LOW; i++)
1536 coreset_sum += bucket[i].count;
1537
1538 if (coreset_sum > core_set_threshold)
1539 return i;
1540
1541 for (; i < BYTE_CORE_SET_HIGH && bucket[i].count > 0; i++) {
1542 coreset_sum += bucket[i].count;
1543 if (coreset_sum > core_set_threshold)
1544 break;
1545 }
1546
1547 return i;
1548}
1549
Timofey Titovetsa288e922017-09-28 17:33:40 +03001550/*
1551 * Count byte values in buckets.
1552 * This heuristic can detect textual data (configs, xml, json, html, etc).
1553 * Because in most text-like data byte set is restricted to limited number of
1554 * possible characters, and that restriction in most cases makes data easy to
1555 * compress.
1556 *
1557 * @BYTE_SET_THRESHOLD - consider all data within this byte set size:
1558 * less - compressible
1559 * more - need additional analysis
1560 */
1561#define BYTE_SET_THRESHOLD (64)
1562
1563static u32 byte_set_size(const struct heuristic_ws *ws)
1564{
1565 u32 i;
1566 u32 byte_set_size = 0;
1567
1568 for (i = 0; i < BYTE_SET_THRESHOLD; i++) {
1569 if (ws->bucket[i].count > 0)
1570 byte_set_size++;
1571 }
1572
1573 /*
1574 * Continue collecting count of byte values in buckets. If the byte
1575 * set size is bigger then the threshold, it's pointless to continue,
1576 * the detection technique would fail for this type of data.
1577 */
1578 for (; i < BUCKET_SIZE; i++) {
1579 if (ws->bucket[i].count > 0) {
1580 byte_set_size++;
1581 if (byte_set_size > BYTE_SET_THRESHOLD)
1582 return byte_set_size;
1583 }
1584 }
1585
1586 return byte_set_size;
1587}
1588
Timofey Titovets1fe4f6f2017-09-28 17:33:39 +03001589static bool sample_repeated_patterns(struct heuristic_ws *ws)
1590{
1591 const u32 half_of_sample = ws->sample_size / 2;
1592 const u8 *data = ws->sample;
1593
1594 return memcmp(&data[0], &data[half_of_sample], half_of_sample) == 0;
1595}
1596
Timofey Titovetsa440d482017-09-28 17:33:38 +03001597static void heuristic_collect_sample(struct inode *inode, u64 start, u64 end,
1598 struct heuristic_ws *ws)
1599{
1600 struct page *page;
1601 u64 index, index_end;
1602 u32 i, curr_sample_pos;
1603 u8 *in_data;
1604
1605 /*
1606 * Compression handles the input data by chunks of 128KiB
1607 * (defined by BTRFS_MAX_UNCOMPRESSED)
1608 *
1609 * We do the same for the heuristic and loop over the whole range.
1610 *
1611 * MAX_SAMPLE_SIZE - calculated under assumption that heuristic will
1612 * process no more than BTRFS_MAX_UNCOMPRESSED at a time.
1613 */
1614 if (end - start > BTRFS_MAX_UNCOMPRESSED)
1615 end = start + BTRFS_MAX_UNCOMPRESSED;
1616
1617 index = start >> PAGE_SHIFT;
1618 index_end = end >> PAGE_SHIFT;
1619
1620 /* Don't miss unaligned end */
1621 if (!IS_ALIGNED(end, PAGE_SIZE))
1622 index_end++;
1623
1624 curr_sample_pos = 0;
1625 while (index < index_end) {
1626 page = find_get_page(inode->i_mapping, index);
Ira Weiny58c1a352021-02-16 18:48:23 -08001627 in_data = kmap_local_page(page);
Timofey Titovetsa440d482017-09-28 17:33:38 +03001628 /* Handle case where the start is not aligned to PAGE_SIZE */
1629 i = start % PAGE_SIZE;
1630 while (i < PAGE_SIZE - SAMPLING_READ_SIZE) {
1631 /* Don't sample any garbage from the last page */
1632 if (start > end - SAMPLING_READ_SIZE)
1633 break;
1634 memcpy(&ws->sample[curr_sample_pos], &in_data[i],
1635 SAMPLING_READ_SIZE);
1636 i += SAMPLING_INTERVAL;
1637 start += SAMPLING_INTERVAL;
1638 curr_sample_pos += SAMPLING_READ_SIZE;
1639 }
Ira Weiny58c1a352021-02-16 18:48:23 -08001640 kunmap_local(in_data);
Timofey Titovetsa440d482017-09-28 17:33:38 +03001641 put_page(page);
1642
1643 index++;
1644 }
1645
1646 ws->sample_size = curr_sample_pos;
1647}
1648
Timofey Titovetsc2fcdcd2017-07-17 16:52:58 +03001649/*
1650 * Compression heuristic.
1651 *
1652 * For now is's a naive and optimistic 'return true', we'll extend the logic to
1653 * quickly (compared to direct compression) detect data characteristics
1654 * (compressible/uncompressible) to avoid wasting CPU time on uncompressible
1655 * data.
1656 *
1657 * The following types of analysis can be performed:
1658 * - detect mostly zero data
1659 * - detect data with low "byte set" size (text, etc)
1660 * - detect data with low/high "core byte" set
1661 *
1662 * Return non-zero if the compression should be done, 0 otherwise.
1663 */
1664int btrfs_compress_heuristic(struct inode *inode, u64 start, u64 end)
1665{
Dennis Zhou7bf49942019-02-04 15:20:04 -05001666 struct list_head *ws_list = get_workspace(0, 0);
Timofey Titovets4e439a02017-09-28 17:33:36 +03001667 struct heuristic_ws *ws;
Timofey Titovetsa440d482017-09-28 17:33:38 +03001668 u32 i;
1669 u8 byte;
Timofey Titovets19562432017-10-08 16:11:59 +03001670 int ret = 0;
Timofey Titovetsc2fcdcd2017-07-17 16:52:58 +03001671
Timofey Titovets4e439a02017-09-28 17:33:36 +03001672 ws = list_entry(ws_list, struct heuristic_ws, list);
1673
Timofey Titovetsa440d482017-09-28 17:33:38 +03001674 heuristic_collect_sample(inode, start, end, ws);
1675
Timofey Titovets1fe4f6f2017-09-28 17:33:39 +03001676 if (sample_repeated_patterns(ws)) {
1677 ret = 1;
1678 goto out;
1679 }
1680
Timofey Titovetsa440d482017-09-28 17:33:38 +03001681 memset(ws->bucket, 0, sizeof(*ws->bucket)*BUCKET_SIZE);
1682
1683 for (i = 0; i < ws->sample_size; i++) {
1684 byte = ws->sample[i];
1685 ws->bucket[byte].count++;
Timofey Titovetsc2fcdcd2017-07-17 16:52:58 +03001686 }
1687
Timofey Titovetsa288e922017-09-28 17:33:40 +03001688 i = byte_set_size(ws);
1689 if (i < BYTE_SET_THRESHOLD) {
1690 ret = 2;
1691 goto out;
1692 }
1693
Timofey Titovets858177d2017-09-28 17:33:41 +03001694 i = byte_core_set_size(ws);
1695 if (i <= BYTE_CORE_SET_LOW) {
1696 ret = 3;
1697 goto out;
1698 }
1699
1700 if (i >= BYTE_CORE_SET_HIGH) {
1701 ret = 0;
1702 goto out;
1703 }
1704
Timofey Titovets19562432017-10-08 16:11:59 +03001705 i = shannon_entropy(ws);
1706 if (i <= ENTROPY_LVL_ACEPTABLE) {
1707 ret = 4;
1708 goto out;
1709 }
1710
1711 /*
1712 * For the levels below ENTROPY_LVL_HIGH, additional analysis would be
1713 * needed to give green light to compression.
1714 *
1715 * For now just assume that compression at that level is not worth the
1716 * resources because:
1717 *
1718 * 1. it is possible to defrag the data later
1719 *
1720 * 2. the data would turn out to be hardly compressible, eg. 150 byte
1721 * values, every bucket has counter at level ~54. The heuristic would
1722 * be confused. This can happen when data have some internal repeated
1723 * patterns like "abbacbbc...". This can be detected by analyzing
1724 * pairs of bytes, which is too costly.
1725 */
1726 if (i < ENTROPY_LVL_HIGH) {
1727 ret = 5;
1728 goto out;
1729 } else {
1730 ret = 0;
1731 goto out;
1732 }
1733
Timofey Titovets1fe4f6f2017-09-28 17:33:39 +03001734out:
Dennis Zhou929f4ba2019-02-04 15:20:02 -05001735 put_workspace(0, ws_list);
Timofey Titovetsc2fcdcd2017-07-17 16:52:58 +03001736 return ret;
1737}
David Sterbaf51d2b52017-09-15 17:36:57 +02001738
Dennis Zhoud0ab62c2019-02-04 15:20:05 -05001739/*
1740 * Convert the compression suffix (eg. after "zlib" starting with ":") to
1741 * level, unrecognized string will set the default level
1742 */
1743unsigned int btrfs_compress_str2level(unsigned int type, const char *str)
David Sterbaf51d2b52017-09-15 17:36:57 +02001744{
Dennis Zhoud0ab62c2019-02-04 15:20:05 -05001745 unsigned int level = 0;
1746 int ret;
1747
1748 if (!type)
David Sterbaf51d2b52017-09-15 17:36:57 +02001749 return 0;
1750
Dennis Zhoud0ab62c2019-02-04 15:20:05 -05001751 if (str[0] == ':') {
1752 ret = kstrtouint(str + 1, 10, &level);
1753 if (ret)
1754 level = 0;
1755 }
David Sterbaf51d2b52017-09-15 17:36:57 +02001756
David Sterbab0c1fe12019-08-09 16:49:06 +02001757 level = btrfs_compress_set_level(type, level);
1758
1759 return level;
1760}