blob: 208334aa6c6ee9911f5ae0d0f87e0c993454db15 [file] [log] [blame]
Chris Masonc8b97812008-10-29 14:49:59 -04001/*
2 * Copyright (C) 2008 Oracle. All rights reserved.
3 *
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public
6 * License v2 as published by the Free Software Foundation.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public
14 * License along with this program; if not, write to the
15 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
16 * Boston, MA 021110-1307, USA.
17 */
18
19#include <linux/kernel.h>
20#include <linux/bio.h>
21#include <linux/buffer_head.h>
22#include <linux/file.h>
23#include <linux/fs.h>
24#include <linux/pagemap.h>
25#include <linux/highmem.h>
26#include <linux/time.h>
27#include <linux/init.h>
28#include <linux/string.h>
Chris Masonc8b97812008-10-29 14:49:59 -040029#include <linux/backing-dev.h>
30#include <linux/mpage.h>
31#include <linux/swap.h>
32#include <linux/writeback.h>
33#include <linux/bit_spinlock.h>
Tejun Heo5a0e3ad2010-03-24 17:04:11 +090034#include <linux/slab.h>
David Sterbafe308532017-05-31 17:14:56 +020035#include <linux/sched/mm.h>
Timofey Titovets19562432017-10-08 16:11:59 +030036#include <linux/log2.h>
Chris Masonc8b97812008-10-29 14:49:59 -040037#include "ctree.h"
38#include "disk-io.h"
39#include "transaction.h"
40#include "btrfs_inode.h"
41#include "volumes.h"
42#include "ordered-data.h"
Chris Masonc8b97812008-10-29 14:49:59 -040043#include "compression.h"
44#include "extent_io.h"
45#include "extent_map.h"
46
David Sterbae128f9c2017-10-31 17:24:26 +010047static const char* const btrfs_compress_types[] = { "", "zlib", "lzo", "zstd" };
48
49const char* btrfs_compress_type2str(enum btrfs_compression_type type)
50{
51 switch (type) {
52 case BTRFS_COMPRESS_ZLIB:
53 case BTRFS_COMPRESS_LZO:
54 case BTRFS_COMPRESS_ZSTD:
55 case BTRFS_COMPRESS_NONE:
56 return btrfs_compress_types[type];
57 }
58
59 return NULL;
60}
61
Anand Jain8140dc32017-05-26 15:44:58 +080062static int btrfs_decompress_bio(struct compressed_bio *cb);
Eric Sandeen48a3b632013-04-25 20:41:01 +000063
Jeff Mahoney2ff7e612016-06-22 18:54:24 -040064static inline int compressed_bio_size(struct btrfs_fs_info *fs_info,
Chris Masond20f7042008-12-08 16:58:54 -050065 unsigned long disk_size)
66{
Jeff Mahoney0b246af2016-06-22 18:54:23 -040067 u16 csum_size = btrfs_super_csum_size(fs_info->super_copy);
David Sterba6c417612011-04-13 15:41:04 +020068
Chris Masond20f7042008-12-08 16:58:54 -050069 return sizeof(struct compressed_bio) +
Jeff Mahoney0b246af2016-06-22 18:54:23 -040070 (DIV_ROUND_UP(disk_size, fs_info->sectorsize)) * csum_size;
Chris Masond20f7042008-12-08 16:58:54 -050071}
72
Nikolay Borisovf898ac62017-02-20 13:50:54 +020073static int check_compressed_csum(struct btrfs_inode *inode,
Chris Masond20f7042008-12-08 16:58:54 -050074 struct compressed_bio *cb,
75 u64 disk_start)
76{
77 int ret;
Chris Masond20f7042008-12-08 16:58:54 -050078 struct page *page;
79 unsigned long i;
80 char *kaddr;
81 u32 csum;
82 u32 *cb_sum = &cb->sums;
83
Nikolay Borisovf898ac62017-02-20 13:50:54 +020084 if (inode->flags & BTRFS_INODE_NODATASUM)
Chris Masond20f7042008-12-08 16:58:54 -050085 return 0;
86
87 for (i = 0; i < cb->nr_pages; i++) {
88 page = cb->compressed_pages[i];
89 csum = ~(u32)0;
90
Cong Wang7ac687d2011-11-25 23:14:28 +080091 kaddr = kmap_atomic(page);
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +030092 csum = btrfs_csum_data(kaddr, csum, PAGE_SIZE);
Domagoj Tršan0b5e3da2016-10-27 08:52:33 +010093 btrfs_csum_final(csum, (u8 *)&csum);
Cong Wang7ac687d2011-11-25 23:14:28 +080094 kunmap_atomic(kaddr);
Chris Masond20f7042008-12-08 16:58:54 -050095
96 if (csum != *cb_sum) {
Nikolay Borisovf898ac62017-02-20 13:50:54 +020097 btrfs_print_data_csum_error(inode, disk_start, csum,
Nikolay Borisov0970a222017-02-20 13:50:53 +020098 *cb_sum, cb->mirror_num);
Chris Masond20f7042008-12-08 16:58:54 -050099 ret = -EIO;
100 goto fail;
101 }
102 cb_sum++;
103
104 }
105 ret = 0;
106fail:
107 return ret;
108}
109
Chris Masonc8b97812008-10-29 14:49:59 -0400110/* when we finish reading compressed pages from the disk, we
111 * decompress them and then run the bio end_io routines on the
112 * decompressed pages (in the inode address space).
113 *
114 * This allows the checksumming and other IO error handling routines
115 * to work normally
116 *
117 * The compressed pages are freed here, and it must be run
118 * in process context
119 */
Christoph Hellwig4246a0b2015-07-20 15:29:37 +0200120static void end_compressed_bio_read(struct bio *bio)
Chris Masonc8b97812008-10-29 14:49:59 -0400121{
Chris Masonc8b97812008-10-29 14:49:59 -0400122 struct compressed_bio *cb = bio->bi_private;
123 struct inode *inode;
124 struct page *page;
125 unsigned long index;
Liu Bocf1167d2017-09-20 17:50:18 -0600126 unsigned int mirror = btrfs_io_bio(bio)->mirror_num;
Liu Boe6311f22017-09-20 17:50:19 -0600127 int ret = 0;
Chris Masonc8b97812008-10-29 14:49:59 -0400128
Christoph Hellwig4e4cbee2017-06-03 09:38:06 +0200129 if (bio->bi_status)
Chris Masonc8b97812008-10-29 14:49:59 -0400130 cb->errors = 1;
131
132 /* if there are more bios still pending for this compressed
133 * extent, just exit
134 */
Elena Reshetovaa50299a2017-03-03 10:55:20 +0200135 if (!refcount_dec_and_test(&cb->pending_bios))
Chris Masonc8b97812008-10-29 14:49:59 -0400136 goto out;
137
Liu Bocf1167d2017-09-20 17:50:18 -0600138 /*
139 * Record the correct mirror_num in cb->orig_bio so that
140 * read-repair can work properly.
141 */
142 ASSERT(btrfs_io_bio(cb->orig_bio));
143 btrfs_io_bio(cb->orig_bio)->mirror_num = mirror;
144 cb->mirror_num = mirror;
145
Liu Boe6311f22017-09-20 17:50:19 -0600146 /*
147 * Some IO in this cb have failed, just skip checksum as there
148 * is no way it could be correct.
149 */
150 if (cb->errors == 1)
151 goto csum_failed;
152
Chris Masond20f7042008-12-08 16:58:54 -0500153 inode = cb->inode;
Nikolay Borisovf898ac62017-02-20 13:50:54 +0200154 ret = check_compressed_csum(BTRFS_I(inode), cb,
Kent Overstreet4f024f32013-10-11 15:44:27 -0700155 (u64)bio->bi_iter.bi_sector << 9);
Chris Masond20f7042008-12-08 16:58:54 -0500156 if (ret)
157 goto csum_failed;
158
Chris Masonc8b97812008-10-29 14:49:59 -0400159 /* ok, we're the last bio for this extent, lets start
160 * the decompression.
161 */
Anand Jain8140dc32017-05-26 15:44:58 +0800162 ret = btrfs_decompress_bio(cb);
163
Chris Masond20f7042008-12-08 16:58:54 -0500164csum_failed:
Chris Masonc8b97812008-10-29 14:49:59 -0400165 if (ret)
166 cb->errors = 1;
167
168 /* release the compressed pages */
169 index = 0;
170 for (index = 0; index < cb->nr_pages; index++) {
171 page = cb->compressed_pages[index];
172 page->mapping = NULL;
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300173 put_page(page);
Chris Masonc8b97812008-10-29 14:49:59 -0400174 }
175
176 /* do io completion on the original bio */
Chris Mason771ed682008-11-06 22:02:51 -0500177 if (cb->errors) {
Chris Masonc8b97812008-10-29 14:49:59 -0400178 bio_io_error(cb->orig_bio);
Chris Masond20f7042008-12-08 16:58:54 -0500179 } else {
Kent Overstreet2c30c712013-11-07 12:20:26 -0800180 int i;
181 struct bio_vec *bvec;
Chris Masond20f7042008-12-08 16:58:54 -0500182
183 /*
184 * we have verified the checksum already, set page
185 * checked so the end_io handlers know about it
186 */
David Sterbac09abff2017-07-13 18:10:07 +0200187 ASSERT(!bio_flagged(bio, BIO_CLONED));
Kent Overstreet2c30c712013-11-07 12:20:26 -0800188 bio_for_each_segment_all(bvec, cb->orig_bio, i)
Chris Masond20f7042008-12-08 16:58:54 -0500189 SetPageChecked(bvec->bv_page);
Kent Overstreet2c30c712013-11-07 12:20:26 -0800190
Christoph Hellwig4246a0b2015-07-20 15:29:37 +0200191 bio_endio(cb->orig_bio);
Chris Masond20f7042008-12-08 16:58:54 -0500192 }
Chris Masonc8b97812008-10-29 14:49:59 -0400193
194 /* finally free the cb struct */
195 kfree(cb->compressed_pages);
196 kfree(cb);
197out:
198 bio_put(bio);
199}
200
201/*
202 * Clear the writeback bits on all of the file
203 * pages for a compressed write
204 */
Filipe Manana7bdcefc2014-10-07 01:48:26 +0100205static noinline void end_compressed_writeback(struct inode *inode,
206 const struct compressed_bio *cb)
Chris Masonc8b97812008-10-29 14:49:59 -0400207{
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300208 unsigned long index = cb->start >> PAGE_SHIFT;
209 unsigned long end_index = (cb->start + cb->len - 1) >> PAGE_SHIFT;
Chris Masonc8b97812008-10-29 14:49:59 -0400210 struct page *pages[16];
211 unsigned long nr_pages = end_index - index + 1;
212 int i;
213 int ret;
214
Filipe Manana7bdcefc2014-10-07 01:48:26 +0100215 if (cb->errors)
216 mapping_set_error(inode->i_mapping, -EIO);
217
Chris Masond3977122009-01-05 21:25:51 -0500218 while (nr_pages > 0) {
Chris Masonc8b97812008-10-29 14:49:59 -0400219 ret = find_get_pages_contig(inode->i_mapping, index,
Chris Mason5b050f02008-11-11 09:34:41 -0500220 min_t(unsigned long,
221 nr_pages, ARRAY_SIZE(pages)), pages);
Chris Masonc8b97812008-10-29 14:49:59 -0400222 if (ret == 0) {
223 nr_pages -= 1;
224 index += 1;
225 continue;
226 }
227 for (i = 0; i < ret; i++) {
Filipe Manana7bdcefc2014-10-07 01:48:26 +0100228 if (cb->errors)
229 SetPageError(pages[i]);
Chris Masonc8b97812008-10-29 14:49:59 -0400230 end_page_writeback(pages[i]);
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300231 put_page(pages[i]);
Chris Masonc8b97812008-10-29 14:49:59 -0400232 }
233 nr_pages -= ret;
234 index += ret;
235 }
236 /* the inode may be gone now */
Chris Masonc8b97812008-10-29 14:49:59 -0400237}
238
239/*
240 * do the cleanup once all the compressed pages hit the disk.
241 * This will clear writeback on the file pages and free the compressed
242 * pages.
243 *
244 * This also calls the writeback end hooks for the file pages so that
245 * metadata and checksums can be updated in the file.
246 */
Christoph Hellwig4246a0b2015-07-20 15:29:37 +0200247static void end_compressed_bio_write(struct bio *bio)
Chris Masonc8b97812008-10-29 14:49:59 -0400248{
249 struct extent_io_tree *tree;
250 struct compressed_bio *cb = bio->bi_private;
251 struct inode *inode;
252 struct page *page;
253 unsigned long index;
254
Christoph Hellwig4e4cbee2017-06-03 09:38:06 +0200255 if (bio->bi_status)
Chris Masonc8b97812008-10-29 14:49:59 -0400256 cb->errors = 1;
257
258 /* if there are more bios still pending for this compressed
259 * extent, just exit
260 */
Elena Reshetovaa50299a2017-03-03 10:55:20 +0200261 if (!refcount_dec_and_test(&cb->pending_bios))
Chris Masonc8b97812008-10-29 14:49:59 -0400262 goto out;
263
264 /* ok, we're the last bio for this extent, step one is to
265 * call back into the FS and do all the end_io operations
266 */
267 inode = cb->inode;
268 tree = &BTRFS_I(inode)->io_tree;
Chris Mason70b99e62008-10-31 12:46:39 -0400269 cb->compressed_pages[0]->mapping = cb->inode->i_mapping;
Chris Masonc8b97812008-10-29 14:49:59 -0400270 tree->ops->writepage_end_io_hook(cb->compressed_pages[0],
271 cb->start,
272 cb->start + cb->len - 1,
Filipe Manana7bdcefc2014-10-07 01:48:26 +0100273 NULL,
Anand Jain2dbe0c72017-10-14 08:35:56 +0800274 bio->bi_status ?
275 BLK_STS_OK : BLK_STS_NOTSUPP);
Chris Mason70b99e62008-10-31 12:46:39 -0400276 cb->compressed_pages[0]->mapping = NULL;
Chris Masonc8b97812008-10-29 14:49:59 -0400277
Filipe Manana7bdcefc2014-10-07 01:48:26 +0100278 end_compressed_writeback(inode, cb);
Chris Masonc8b97812008-10-29 14:49:59 -0400279 /* note, our inode could be gone now */
280
281 /*
282 * release the compressed pages, these came from alloc_page and
283 * are not attached to the inode at all
284 */
285 index = 0;
286 for (index = 0; index < cb->nr_pages; index++) {
287 page = cb->compressed_pages[index];
288 page->mapping = NULL;
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300289 put_page(page);
Chris Masonc8b97812008-10-29 14:49:59 -0400290 }
291
292 /* finally free the cb struct */
293 kfree(cb->compressed_pages);
294 kfree(cb);
295out:
296 bio_put(bio);
297}
298
299/*
300 * worker function to build and submit bios for previously compressed pages.
301 * The corresponding pages in the inode should be marked for writeback
302 * and the compressed pages should have a reference on them for dropping
303 * when the IO is complete.
304 *
305 * This also checksums the file bytes and gets things ready for
306 * the end io hooks.
307 */
Christoph Hellwig4e4cbee2017-06-03 09:38:06 +0200308blk_status_t btrfs_submit_compressed_write(struct inode *inode, u64 start,
Chris Masonc8b97812008-10-29 14:49:59 -0400309 unsigned long len, u64 disk_start,
310 unsigned long compressed_len,
311 struct page **compressed_pages,
Liu Bof82b7352017-10-23 23:18:16 -0600312 unsigned long nr_pages,
313 unsigned int write_flags)
Chris Masonc8b97812008-10-29 14:49:59 -0400314{
Jeff Mahoney0b246af2016-06-22 18:54:23 -0400315 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
Chris Masonc8b97812008-10-29 14:49:59 -0400316 struct bio *bio = NULL;
Chris Masonc8b97812008-10-29 14:49:59 -0400317 struct compressed_bio *cb;
318 unsigned long bytes_left;
319 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
David Sterba306e16c2011-04-19 14:29:38 +0200320 int pg_index = 0;
Chris Masonc8b97812008-10-29 14:49:59 -0400321 struct page *page;
322 u64 first_byte = disk_start;
323 struct block_device *bdev;
Christoph Hellwig4e4cbee2017-06-03 09:38:06 +0200324 blk_status_t ret;
Li Zefane55179b2011-07-14 03:16:47 +0000325 int skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
Chris Masonc8b97812008-10-29 14:49:59 -0400326
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300327 WARN_ON(start & ((u64)PAGE_SIZE - 1));
Jeff Mahoney2ff7e612016-06-22 18:54:24 -0400328 cb = kmalloc(compressed_bio_size(fs_info, compressed_len), GFP_NOFS);
Yoshinori Sanodac97e52011-02-15 12:01:42 +0000329 if (!cb)
Christoph Hellwig4e4cbee2017-06-03 09:38:06 +0200330 return BLK_STS_RESOURCE;
Elena Reshetovaa50299a2017-03-03 10:55:20 +0200331 refcount_set(&cb->pending_bios, 0);
Chris Masonc8b97812008-10-29 14:49:59 -0400332 cb->errors = 0;
333 cb->inode = inode;
334 cb->start = start;
335 cb->len = len;
Chris Masond20f7042008-12-08 16:58:54 -0500336 cb->mirror_num = 0;
Chris Masonc8b97812008-10-29 14:49:59 -0400337 cb->compressed_pages = compressed_pages;
338 cb->compressed_len = compressed_len;
339 cb->orig_bio = NULL;
340 cb->nr_pages = nr_pages;
341
Jeff Mahoney0b246af2016-06-22 18:54:23 -0400342 bdev = fs_info->fs_devices->latest_bdev;
Chris Masonc8b97812008-10-29 14:49:59 -0400343
David Sterbac821e7f32017-06-02 18:35:36 +0200344 bio = btrfs_bio_alloc(bdev, first_byte);
Liu Bof82b7352017-10-23 23:18:16 -0600345 bio->bi_opf = REQ_OP_WRITE | write_flags;
Chris Masonc8b97812008-10-29 14:49:59 -0400346 bio->bi_private = cb;
347 bio->bi_end_io = end_compressed_bio_write;
Elena Reshetovaa50299a2017-03-03 10:55:20 +0200348 refcount_set(&cb->pending_bios, 1);
Chris Masonc8b97812008-10-29 14:49:59 -0400349
350 /* create and submit bios for the compressed pages */
351 bytes_left = compressed_len;
David Sterba306e16c2011-04-19 14:29:38 +0200352 for (pg_index = 0; pg_index < cb->nr_pages; pg_index++) {
Christoph Hellwig4e4cbee2017-06-03 09:38:06 +0200353 int submit = 0;
354
David Sterba306e16c2011-04-19 14:29:38 +0200355 page = compressed_pages[pg_index];
Chris Masonc8b97812008-10-29 14:49:59 -0400356 page->mapping = inode->i_mapping;
Kent Overstreet4f024f32013-10-11 15:44:27 -0700357 if (bio->bi_iter.bi_size)
Christoph Hellwig4e4cbee2017-06-03 09:38:06 +0200358 submit = io_tree->ops->merge_bio_hook(page, 0,
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300359 PAGE_SIZE,
Chris Masonc8b97812008-10-29 14:49:59 -0400360 bio, 0);
Chris Masonc8b97812008-10-29 14:49:59 -0400361
Chris Mason70b99e62008-10-31 12:46:39 -0400362 page->mapping = NULL;
Christoph Hellwig4e4cbee2017-06-03 09:38:06 +0200363 if (submit || bio_add_page(bio, page, PAGE_SIZE, 0) <
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300364 PAGE_SIZE) {
Chris Masonc8b97812008-10-29 14:49:59 -0400365 bio_get(bio);
366
Chris Masonaf09abf2008-11-07 12:35:44 -0500367 /*
368 * inc the count before we submit the bio so
369 * we know the end IO handler won't happen before
370 * we inc the count. Otherwise, the cb might get
371 * freed before we're done setting it up
372 */
Elena Reshetovaa50299a2017-03-03 10:55:20 +0200373 refcount_inc(&cb->pending_bios);
Jeff Mahoney0b246af2016-06-22 18:54:23 -0400374 ret = btrfs_bio_wq_end_io(fs_info, bio,
375 BTRFS_WQ_ENDIO_DATA);
Jeff Mahoney79787ea2012-03-12 16:03:00 +0100376 BUG_ON(ret); /* -ENOMEM */
Chris Masonc8b97812008-10-29 14:49:59 -0400377
Li Zefane55179b2011-07-14 03:16:47 +0000378 if (!skip_sum) {
Jeff Mahoney2ff7e612016-06-22 18:54:24 -0400379 ret = btrfs_csum_one_bio(inode, bio, start, 1);
Jeff Mahoney79787ea2012-03-12 16:03:00 +0100380 BUG_ON(ret); /* -ENOMEM */
Li Zefane55179b2011-07-14 03:16:47 +0000381 }
Chris Masond20f7042008-12-08 16:58:54 -0500382
Jeff Mahoney2ff7e612016-06-22 18:54:24 -0400383 ret = btrfs_map_bio(fs_info, bio, 0, 1);
Liu Bof5daf2c2016-06-22 18:32:06 -0700384 if (ret) {
Christoph Hellwig4e4cbee2017-06-03 09:38:06 +0200385 bio->bi_status = ret;
Liu Bof5daf2c2016-06-22 18:32:06 -0700386 bio_endio(bio);
387 }
Chris Masonc8b97812008-10-29 14:49:59 -0400388
389 bio_put(bio);
390
David Sterbac821e7f32017-06-02 18:35:36 +0200391 bio = btrfs_bio_alloc(bdev, first_byte);
Liu Bof82b7352017-10-23 23:18:16 -0600392 bio->bi_opf = REQ_OP_WRITE | write_flags;
Chris Masonc8b97812008-10-29 14:49:59 -0400393 bio->bi_private = cb;
394 bio->bi_end_io = end_compressed_bio_write;
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300395 bio_add_page(bio, page, PAGE_SIZE, 0);
Chris Masonc8b97812008-10-29 14:49:59 -0400396 }
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300397 if (bytes_left < PAGE_SIZE) {
Jeff Mahoney0b246af2016-06-22 18:54:23 -0400398 btrfs_info(fs_info,
Frank Holtonefe120a2013-12-20 11:37:06 -0500399 "bytes left %lu compress len %lu nr %lu",
Chris Masoncfbc2462008-10-30 13:22:14 -0400400 bytes_left, cb->compressed_len, cb->nr_pages);
401 }
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300402 bytes_left -= PAGE_SIZE;
403 first_byte += PAGE_SIZE;
Chris Mason771ed682008-11-06 22:02:51 -0500404 cond_resched();
Chris Masonc8b97812008-10-29 14:49:59 -0400405 }
406 bio_get(bio);
407
Jeff Mahoney0b246af2016-06-22 18:54:23 -0400408 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DATA);
Jeff Mahoney79787ea2012-03-12 16:03:00 +0100409 BUG_ON(ret); /* -ENOMEM */
Chris Masonc8b97812008-10-29 14:49:59 -0400410
Li Zefane55179b2011-07-14 03:16:47 +0000411 if (!skip_sum) {
Jeff Mahoney2ff7e612016-06-22 18:54:24 -0400412 ret = btrfs_csum_one_bio(inode, bio, start, 1);
Jeff Mahoney79787ea2012-03-12 16:03:00 +0100413 BUG_ON(ret); /* -ENOMEM */
Li Zefane55179b2011-07-14 03:16:47 +0000414 }
Chris Masond20f7042008-12-08 16:58:54 -0500415
Jeff Mahoney2ff7e612016-06-22 18:54:24 -0400416 ret = btrfs_map_bio(fs_info, bio, 0, 1);
Liu Bof5daf2c2016-06-22 18:32:06 -0700417 if (ret) {
Christoph Hellwig4e4cbee2017-06-03 09:38:06 +0200418 bio->bi_status = ret;
Liu Bof5daf2c2016-06-22 18:32:06 -0700419 bio_endio(bio);
420 }
Chris Masonc8b97812008-10-29 14:49:59 -0400421
422 bio_put(bio);
423 return 0;
424}
425
Christoph Hellwig2a4d0c92016-11-25 09:07:51 +0100426static u64 bio_end_offset(struct bio *bio)
427{
428 struct bio_vec *last = &bio->bi_io_vec[bio->bi_vcnt - 1];
429
430 return page_offset(last->bv_page) + last->bv_len + last->bv_offset;
431}
432
Chris Mason771ed682008-11-06 22:02:51 -0500433static noinline int add_ra_bio_pages(struct inode *inode,
434 u64 compressed_end,
435 struct compressed_bio *cb)
436{
437 unsigned long end_index;
David Sterba306e16c2011-04-19 14:29:38 +0200438 unsigned long pg_index;
Chris Mason771ed682008-11-06 22:02:51 -0500439 u64 last_offset;
440 u64 isize = i_size_read(inode);
441 int ret;
442 struct page *page;
443 unsigned long nr_pages = 0;
444 struct extent_map *em;
445 struct address_space *mapping = inode->i_mapping;
Chris Mason771ed682008-11-06 22:02:51 -0500446 struct extent_map_tree *em_tree;
447 struct extent_io_tree *tree;
448 u64 end;
449 int misses = 0;
450
Christoph Hellwig2a4d0c92016-11-25 09:07:51 +0100451 last_offset = bio_end_offset(cb->orig_bio);
Chris Mason771ed682008-11-06 22:02:51 -0500452 em_tree = &BTRFS_I(inode)->extent_tree;
453 tree = &BTRFS_I(inode)->io_tree;
454
455 if (isize == 0)
456 return 0;
457
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300458 end_index = (i_size_read(inode) - 1) >> PAGE_SHIFT;
Chris Mason771ed682008-11-06 22:02:51 -0500459
Chris Masond3977122009-01-05 21:25:51 -0500460 while (last_offset < compressed_end) {
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300461 pg_index = last_offset >> PAGE_SHIFT;
Chris Mason771ed682008-11-06 22:02:51 -0500462
David Sterba306e16c2011-04-19 14:29:38 +0200463 if (pg_index > end_index)
Chris Mason771ed682008-11-06 22:02:51 -0500464 break;
465
466 rcu_read_lock();
David Sterba306e16c2011-04-19 14:29:38 +0200467 page = radix_tree_lookup(&mapping->page_tree, pg_index);
Chris Mason771ed682008-11-06 22:02:51 -0500468 rcu_read_unlock();
Johannes Weiner0cd61442014-04-03 14:47:46 -0700469 if (page && !radix_tree_exceptional_entry(page)) {
Chris Mason771ed682008-11-06 22:02:51 -0500470 misses++;
471 if (misses > 4)
472 break;
473 goto next;
474 }
475
Michal Hockoc62d2552015-11-06 16:28:49 -0800476 page = __page_cache_alloc(mapping_gfp_constraint(mapping,
477 ~__GFP_FS));
Chris Mason771ed682008-11-06 22:02:51 -0500478 if (!page)
479 break;
480
Michal Hockoc62d2552015-11-06 16:28:49 -0800481 if (add_to_page_cache_lru(page, mapping, pg_index, GFP_NOFS)) {
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300482 put_page(page);
Chris Mason771ed682008-11-06 22:02:51 -0500483 goto next;
484 }
485
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300486 end = last_offset + PAGE_SIZE - 1;
Chris Mason771ed682008-11-06 22:02:51 -0500487 /*
488 * at this point, we have a locked page in the page cache
489 * for these bytes in the file. But, we have to make
490 * sure they map to this compressed extent on disk.
491 */
492 set_page_extent_mapped(page);
Jeff Mahoneyd0082372012-03-01 14:57:19 +0100493 lock_extent(tree, last_offset, end);
Chris Mason890871b2009-09-02 16:24:52 -0400494 read_lock(&em_tree->lock);
Chris Mason771ed682008-11-06 22:02:51 -0500495 em = lookup_extent_mapping(em_tree, last_offset,
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300496 PAGE_SIZE);
Chris Mason890871b2009-09-02 16:24:52 -0400497 read_unlock(&em_tree->lock);
Chris Mason771ed682008-11-06 22:02:51 -0500498
499 if (!em || last_offset < em->start ||
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300500 (last_offset + PAGE_SIZE > extent_map_end(em)) ||
Kent Overstreet4f024f32013-10-11 15:44:27 -0700501 (em->block_start >> 9) != cb->orig_bio->bi_iter.bi_sector) {
Chris Mason771ed682008-11-06 22:02:51 -0500502 free_extent_map(em);
Jeff Mahoneyd0082372012-03-01 14:57:19 +0100503 unlock_extent(tree, last_offset, end);
Chris Mason771ed682008-11-06 22:02:51 -0500504 unlock_page(page);
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300505 put_page(page);
Chris Mason771ed682008-11-06 22:02:51 -0500506 break;
507 }
508 free_extent_map(em);
509
510 if (page->index == end_index) {
511 char *userpage;
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300512 size_t zero_offset = isize & (PAGE_SIZE - 1);
Chris Mason771ed682008-11-06 22:02:51 -0500513
514 if (zero_offset) {
515 int zeros;
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300516 zeros = PAGE_SIZE - zero_offset;
Cong Wang7ac687d2011-11-25 23:14:28 +0800517 userpage = kmap_atomic(page);
Chris Mason771ed682008-11-06 22:02:51 -0500518 memset(userpage + zero_offset, 0, zeros);
519 flush_dcache_page(page);
Cong Wang7ac687d2011-11-25 23:14:28 +0800520 kunmap_atomic(userpage);
Chris Mason771ed682008-11-06 22:02:51 -0500521 }
522 }
523
524 ret = bio_add_page(cb->orig_bio, page,
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300525 PAGE_SIZE, 0);
Chris Mason771ed682008-11-06 22:02:51 -0500526
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300527 if (ret == PAGE_SIZE) {
Chris Mason771ed682008-11-06 22:02:51 -0500528 nr_pages++;
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300529 put_page(page);
Chris Mason771ed682008-11-06 22:02:51 -0500530 } else {
Jeff Mahoneyd0082372012-03-01 14:57:19 +0100531 unlock_extent(tree, last_offset, end);
Chris Mason771ed682008-11-06 22:02:51 -0500532 unlock_page(page);
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300533 put_page(page);
Chris Mason771ed682008-11-06 22:02:51 -0500534 break;
535 }
536next:
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300537 last_offset += PAGE_SIZE;
Chris Mason771ed682008-11-06 22:02:51 -0500538 }
Chris Mason771ed682008-11-06 22:02:51 -0500539 return 0;
540}
541
Chris Masonc8b97812008-10-29 14:49:59 -0400542/*
543 * for a compressed read, the bio we get passed has all the inode pages
544 * in it. We don't actually do IO on those pages but allocate new ones
545 * to hold the compressed pages on disk.
546 *
Kent Overstreet4f024f32013-10-11 15:44:27 -0700547 * bio->bi_iter.bi_sector points to the compressed extent on disk
Chris Masonc8b97812008-10-29 14:49:59 -0400548 * bio->bi_io_vec points to all of the inode pages
Chris Masonc8b97812008-10-29 14:49:59 -0400549 *
550 * After the compressed pages are read, we copy the bytes into the
551 * bio we were passed and then call the bio end_io calls
552 */
Christoph Hellwig4e4cbee2017-06-03 09:38:06 +0200553blk_status_t btrfs_submit_compressed_read(struct inode *inode, struct bio *bio,
Chris Masonc8b97812008-10-29 14:49:59 -0400554 int mirror_num, unsigned long bio_flags)
555{
Jeff Mahoney0b246af2016-06-22 18:54:23 -0400556 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
Chris Masonc8b97812008-10-29 14:49:59 -0400557 struct extent_io_tree *tree;
558 struct extent_map_tree *em_tree;
559 struct compressed_bio *cb;
Chris Masonc8b97812008-10-29 14:49:59 -0400560 unsigned long compressed_len;
561 unsigned long nr_pages;
David Sterba306e16c2011-04-19 14:29:38 +0200562 unsigned long pg_index;
Chris Masonc8b97812008-10-29 14:49:59 -0400563 struct page *page;
564 struct block_device *bdev;
565 struct bio *comp_bio;
Kent Overstreet4f024f32013-10-11 15:44:27 -0700566 u64 cur_disk_byte = (u64)bio->bi_iter.bi_sector << 9;
Chris Masone04ca622008-11-10 11:44:58 -0500567 u64 em_len;
568 u64 em_start;
Chris Masonc8b97812008-10-29 14:49:59 -0400569 struct extent_map *em;
Christoph Hellwig4e4cbee2017-06-03 09:38:06 +0200570 blk_status_t ret = BLK_STS_RESOURCE;
Josef Bacik15e3004a2012-10-05 13:39:50 -0400571 int faili = 0;
Chris Masond20f7042008-12-08 16:58:54 -0500572 u32 *sums;
Chris Masonc8b97812008-10-29 14:49:59 -0400573
574 tree = &BTRFS_I(inode)->io_tree;
575 em_tree = &BTRFS_I(inode)->extent_tree;
576
577 /* we need the actual starting offset of this extent in the file */
Chris Mason890871b2009-09-02 16:24:52 -0400578 read_lock(&em_tree->lock);
Chris Masonc8b97812008-10-29 14:49:59 -0400579 em = lookup_extent_mapping(em_tree,
580 page_offset(bio->bi_io_vec->bv_page),
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300581 PAGE_SIZE);
Chris Mason890871b2009-09-02 16:24:52 -0400582 read_unlock(&em_tree->lock);
Tsutomu Itoh285190d2012-02-16 16:23:58 +0900583 if (!em)
Christoph Hellwig4e4cbee2017-06-03 09:38:06 +0200584 return BLK_STS_IOERR;
Chris Masonc8b97812008-10-29 14:49:59 -0400585
Chris Masond20f7042008-12-08 16:58:54 -0500586 compressed_len = em->block_len;
Jeff Mahoney2ff7e612016-06-22 18:54:24 -0400587 cb = kmalloc(compressed_bio_size(fs_info, compressed_len), GFP_NOFS);
liubo6b82ce82011-01-26 06:21:39 +0000588 if (!cb)
589 goto out;
590
Elena Reshetovaa50299a2017-03-03 10:55:20 +0200591 refcount_set(&cb->pending_bios, 0);
Chris Masonc8b97812008-10-29 14:49:59 -0400592 cb->errors = 0;
593 cb->inode = inode;
Chris Masond20f7042008-12-08 16:58:54 -0500594 cb->mirror_num = mirror_num;
595 sums = &cb->sums;
Chris Masonc8b97812008-10-29 14:49:59 -0400596
Yan Zhengff5b7ee2008-11-10 07:34:43 -0500597 cb->start = em->orig_start;
Chris Masone04ca622008-11-10 11:44:58 -0500598 em_len = em->len;
599 em_start = em->start;
Chris Masond20f7042008-12-08 16:58:54 -0500600
Chris Masonc8b97812008-10-29 14:49:59 -0400601 free_extent_map(em);
Chris Masone04ca622008-11-10 11:44:58 -0500602 em = NULL;
Chris Masonc8b97812008-10-29 14:49:59 -0400603
Christoph Hellwig81381052016-11-25 09:07:50 +0100604 cb->len = bio->bi_iter.bi_size;
Chris Masonc8b97812008-10-29 14:49:59 -0400605 cb->compressed_len = compressed_len;
Li Zefan261507a02010-12-17 14:21:50 +0800606 cb->compress_type = extent_compress_type(bio_flags);
Chris Masonc8b97812008-10-29 14:49:59 -0400607 cb->orig_bio = bio;
608
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300609 nr_pages = DIV_ROUND_UP(compressed_len, PAGE_SIZE);
David Sterba31e818f2015-02-20 18:00:26 +0100610 cb->compressed_pages = kcalloc(nr_pages, sizeof(struct page *),
Chris Masonc8b97812008-10-29 14:49:59 -0400611 GFP_NOFS);
liubo6b82ce82011-01-26 06:21:39 +0000612 if (!cb->compressed_pages)
613 goto fail1;
614
Jeff Mahoney0b246af2016-06-22 18:54:23 -0400615 bdev = fs_info->fs_devices->latest_bdev;
Chris Masonc8b97812008-10-29 14:49:59 -0400616
David Sterba306e16c2011-04-19 14:29:38 +0200617 for (pg_index = 0; pg_index < nr_pages; pg_index++) {
618 cb->compressed_pages[pg_index] = alloc_page(GFP_NOFS |
Chris Masonc8b97812008-10-29 14:49:59 -0400619 __GFP_HIGHMEM);
Josef Bacik15e3004a2012-10-05 13:39:50 -0400620 if (!cb->compressed_pages[pg_index]) {
621 faili = pg_index - 1;
Dan Carpenter0e9350d2017-06-19 13:55:37 +0300622 ret = BLK_STS_RESOURCE;
liubo6b82ce82011-01-26 06:21:39 +0000623 goto fail2;
Josef Bacik15e3004a2012-10-05 13:39:50 -0400624 }
Chris Masonc8b97812008-10-29 14:49:59 -0400625 }
Josef Bacik15e3004a2012-10-05 13:39:50 -0400626 faili = nr_pages - 1;
Chris Masonc8b97812008-10-29 14:49:59 -0400627 cb->nr_pages = nr_pages;
628
Filipe Manana7f042a82016-01-27 19:17:20 +0000629 add_ra_bio_pages(inode, em_start + em_len, cb);
Chris Mason771ed682008-11-06 22:02:51 -0500630
Chris Mason771ed682008-11-06 22:02:51 -0500631 /* include any pages we added in add_ra-bio_pages */
Christoph Hellwig81381052016-11-25 09:07:50 +0100632 cb->len = bio->bi_iter.bi_size;
Chris Mason771ed682008-11-06 22:02:51 -0500633
David Sterbac821e7f32017-06-02 18:35:36 +0200634 comp_bio = btrfs_bio_alloc(bdev, cur_disk_byte);
Mike Christie37226b22016-06-05 14:31:52 -0500635 bio_set_op_attrs (comp_bio, REQ_OP_READ, 0);
Chris Masonc8b97812008-10-29 14:49:59 -0400636 comp_bio->bi_private = cb;
637 comp_bio->bi_end_io = end_compressed_bio_read;
Elena Reshetovaa50299a2017-03-03 10:55:20 +0200638 refcount_set(&cb->pending_bios, 1);
Chris Masonc8b97812008-10-29 14:49:59 -0400639
David Sterba306e16c2011-04-19 14:29:38 +0200640 for (pg_index = 0; pg_index < nr_pages; pg_index++) {
Christoph Hellwig4e4cbee2017-06-03 09:38:06 +0200641 int submit = 0;
642
David Sterba306e16c2011-04-19 14:29:38 +0200643 page = cb->compressed_pages[pg_index];
Chris Masonc8b97812008-10-29 14:49:59 -0400644 page->mapping = inode->i_mapping;
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300645 page->index = em_start >> PAGE_SHIFT;
Chris Masond20f7042008-12-08 16:58:54 -0500646
Kent Overstreet4f024f32013-10-11 15:44:27 -0700647 if (comp_bio->bi_iter.bi_size)
Christoph Hellwig4e4cbee2017-06-03 09:38:06 +0200648 submit = tree->ops->merge_bio_hook(page, 0,
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300649 PAGE_SIZE,
Chris Masonc8b97812008-10-29 14:49:59 -0400650 comp_bio, 0);
Chris Masonc8b97812008-10-29 14:49:59 -0400651
Chris Mason70b99e62008-10-31 12:46:39 -0400652 page->mapping = NULL;
Christoph Hellwig4e4cbee2017-06-03 09:38:06 +0200653 if (submit || bio_add_page(comp_bio, page, PAGE_SIZE, 0) <
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300654 PAGE_SIZE) {
Chris Masonc8b97812008-10-29 14:49:59 -0400655 bio_get(comp_bio);
656
Jeff Mahoney0b246af2016-06-22 18:54:23 -0400657 ret = btrfs_bio_wq_end_io(fs_info, comp_bio,
658 BTRFS_WQ_ENDIO_DATA);
Jeff Mahoney79787ea2012-03-12 16:03:00 +0100659 BUG_ON(ret); /* -ENOMEM */
Chris Masonc8b97812008-10-29 14:49:59 -0400660
Chris Masonaf09abf2008-11-07 12:35:44 -0500661 /*
662 * inc the count before we submit the bio so
663 * we know the end IO handler won't happen before
664 * we inc the count. Otherwise, the cb might get
665 * freed before we're done setting it up
666 */
Elena Reshetovaa50299a2017-03-03 10:55:20 +0200667 refcount_inc(&cb->pending_bios);
Chris Masonaf09abf2008-11-07 12:35:44 -0500668
Christoph Hellwig6cbff002009-04-17 10:37:41 +0200669 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
Jeff Mahoney2ff7e612016-06-22 18:54:24 -0400670 ret = btrfs_lookup_bio_sums(inode, comp_bio,
671 sums);
Jeff Mahoney79787ea2012-03-12 16:03:00 +0100672 BUG_ON(ret); /* -ENOMEM */
Chris Masond20f7042008-12-08 16:58:54 -0500673 }
David Sterbaed6078f2014-06-05 01:59:57 +0200674 sums += DIV_ROUND_UP(comp_bio->bi_iter.bi_size,
Jeff Mahoney0b246af2016-06-22 18:54:23 -0400675 fs_info->sectorsize);
Chris Masond20f7042008-12-08 16:58:54 -0500676
Jeff Mahoney2ff7e612016-06-22 18:54:24 -0400677 ret = btrfs_map_bio(fs_info, comp_bio, mirror_num, 0);
Christoph Hellwig4246a0b2015-07-20 15:29:37 +0200678 if (ret) {
Christoph Hellwig4e4cbee2017-06-03 09:38:06 +0200679 comp_bio->bi_status = ret;
Christoph Hellwig4246a0b2015-07-20 15:29:37 +0200680 bio_endio(comp_bio);
681 }
Chris Masonc8b97812008-10-29 14:49:59 -0400682
683 bio_put(comp_bio);
684
David Sterbac821e7f32017-06-02 18:35:36 +0200685 comp_bio = btrfs_bio_alloc(bdev, cur_disk_byte);
Mike Christie37226b22016-06-05 14:31:52 -0500686 bio_set_op_attrs(comp_bio, REQ_OP_READ, 0);
Chris Mason771ed682008-11-06 22:02:51 -0500687 comp_bio->bi_private = cb;
688 comp_bio->bi_end_io = end_compressed_bio_read;
689
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300690 bio_add_page(comp_bio, page, PAGE_SIZE, 0);
Chris Masonc8b97812008-10-29 14:49:59 -0400691 }
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300692 cur_disk_byte += PAGE_SIZE;
Chris Masonc8b97812008-10-29 14:49:59 -0400693 }
694 bio_get(comp_bio);
695
Jeff Mahoney0b246af2016-06-22 18:54:23 -0400696 ret = btrfs_bio_wq_end_io(fs_info, comp_bio, BTRFS_WQ_ENDIO_DATA);
Jeff Mahoney79787ea2012-03-12 16:03:00 +0100697 BUG_ON(ret); /* -ENOMEM */
Chris Masonc8b97812008-10-29 14:49:59 -0400698
Tsutomu Itohc2db1072011-03-01 06:48:31 +0000699 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
Jeff Mahoney2ff7e612016-06-22 18:54:24 -0400700 ret = btrfs_lookup_bio_sums(inode, comp_bio, sums);
Jeff Mahoney79787ea2012-03-12 16:03:00 +0100701 BUG_ON(ret); /* -ENOMEM */
Tsutomu Itohc2db1072011-03-01 06:48:31 +0000702 }
Chris Masond20f7042008-12-08 16:58:54 -0500703
Jeff Mahoney2ff7e612016-06-22 18:54:24 -0400704 ret = btrfs_map_bio(fs_info, comp_bio, mirror_num, 0);
Christoph Hellwig4246a0b2015-07-20 15:29:37 +0200705 if (ret) {
Christoph Hellwig4e4cbee2017-06-03 09:38:06 +0200706 comp_bio->bi_status = ret;
Christoph Hellwig4246a0b2015-07-20 15:29:37 +0200707 bio_endio(comp_bio);
708 }
Chris Masonc8b97812008-10-29 14:49:59 -0400709
710 bio_put(comp_bio);
711 return 0;
liubo6b82ce82011-01-26 06:21:39 +0000712
713fail2:
Josef Bacik15e3004a2012-10-05 13:39:50 -0400714 while (faili >= 0) {
715 __free_page(cb->compressed_pages[faili]);
716 faili--;
717 }
liubo6b82ce82011-01-26 06:21:39 +0000718
719 kfree(cb->compressed_pages);
720fail1:
721 kfree(cb);
722out:
723 free_extent_map(em);
724 return ret;
Chris Masonc8b97812008-10-29 14:49:59 -0400725}
Li Zefan261507a02010-12-17 14:21:50 +0800726
Timofey Titovets17b5a6c2017-09-28 17:33:37 +0300727/*
728 * Heuristic uses systematic sampling to collect data from the input data
729 * range, the logic can be tuned by the following constants:
730 *
731 * @SAMPLING_READ_SIZE - how many bytes will be copied from for each sample
732 * @SAMPLING_INTERVAL - range from which the sampled data can be collected
733 */
734#define SAMPLING_READ_SIZE (16)
735#define SAMPLING_INTERVAL (256)
736
737/*
738 * For statistical analysis of the input data we consider bytes that form a
739 * Galois Field of 256 objects. Each object has an attribute count, ie. how
740 * many times the object appeared in the sample.
741 */
742#define BUCKET_SIZE (256)
743
744/*
745 * The size of the sample is based on a statistical sampling rule of thumb.
746 * The common way is to perform sampling tests as long as the number of
747 * elements in each cell is at least 5.
748 *
749 * Instead of 5, we choose 32 to obtain more accurate results.
750 * If the data contain the maximum number of symbols, which is 256, we obtain a
751 * sample size bound by 8192.
752 *
753 * For a sample of at most 8KB of data per data range: 16 consecutive bytes
754 * from up to 512 locations.
755 */
756#define MAX_SAMPLE_SIZE (BTRFS_MAX_UNCOMPRESSED * \
757 SAMPLING_READ_SIZE / SAMPLING_INTERVAL)
758
759struct bucket_item {
760 u32 count;
761};
Timofey Titovets4e439a02017-09-28 17:33:36 +0300762
763struct heuristic_ws {
Timofey Titovets17b5a6c2017-09-28 17:33:37 +0300764 /* Partial copy of input data */
765 u8 *sample;
Timofey Titovetsa440d482017-09-28 17:33:38 +0300766 u32 sample_size;
Timofey Titovets17b5a6c2017-09-28 17:33:37 +0300767 /* Buckets store counters for each byte value */
768 struct bucket_item *bucket;
Timofey Titovets440c8402017-12-04 00:30:33 +0300769 /* Sorting buffer */
770 struct bucket_item *bucket_b;
Timofey Titovets4e439a02017-09-28 17:33:36 +0300771 struct list_head list;
772};
773
774static void free_heuristic_ws(struct list_head *ws)
775{
776 struct heuristic_ws *workspace;
777
778 workspace = list_entry(ws, struct heuristic_ws, list);
779
Timofey Titovets17b5a6c2017-09-28 17:33:37 +0300780 kvfree(workspace->sample);
781 kfree(workspace->bucket);
Timofey Titovets440c8402017-12-04 00:30:33 +0300782 kfree(workspace->bucket_b);
Timofey Titovets4e439a02017-09-28 17:33:36 +0300783 kfree(workspace);
784}
785
786static struct list_head *alloc_heuristic_ws(void)
787{
788 struct heuristic_ws *ws;
789
790 ws = kzalloc(sizeof(*ws), GFP_KERNEL);
791 if (!ws)
792 return ERR_PTR(-ENOMEM);
793
Timofey Titovets17b5a6c2017-09-28 17:33:37 +0300794 ws->sample = kvmalloc(MAX_SAMPLE_SIZE, GFP_KERNEL);
795 if (!ws->sample)
796 goto fail;
Timofey Titovets4e439a02017-09-28 17:33:36 +0300797
Timofey Titovets17b5a6c2017-09-28 17:33:37 +0300798 ws->bucket = kcalloc(BUCKET_SIZE, sizeof(*ws->bucket), GFP_KERNEL);
799 if (!ws->bucket)
800 goto fail;
801
Timofey Titovets440c8402017-12-04 00:30:33 +0300802 ws->bucket_b = kcalloc(BUCKET_SIZE, sizeof(*ws->bucket_b), GFP_KERNEL);
803 if (!ws->bucket_b)
804 goto fail;
805
Timofey Titovets17b5a6c2017-09-28 17:33:37 +0300806 INIT_LIST_HEAD(&ws->list);
Timofey Titovets4e439a02017-09-28 17:33:36 +0300807 return &ws->list;
Timofey Titovets17b5a6c2017-09-28 17:33:37 +0300808fail:
809 free_heuristic_ws(&ws->list);
810 return ERR_PTR(-ENOMEM);
Timofey Titovets4e439a02017-09-28 17:33:36 +0300811}
812
813struct workspaces_list {
Byongho Leed9187642015-10-14 14:05:24 +0900814 struct list_head idle_ws;
815 spinlock_t ws_lock;
David Sterba6ac10a62016-04-27 02:15:15 +0200816 /* Number of free workspaces */
817 int free_ws;
818 /* Total number of allocated workspaces */
819 atomic_t total_ws;
820 /* Waiters for a free workspace */
Byongho Leed9187642015-10-14 14:05:24 +0900821 wait_queue_head_t ws_wait;
Timofey Titovets4e439a02017-09-28 17:33:36 +0300822};
823
824static struct workspaces_list btrfs_comp_ws[BTRFS_COMPRESS_TYPES];
825
826static struct workspaces_list btrfs_heuristic_ws;
Li Zefan261507a02010-12-17 14:21:50 +0800827
David Sterbae8c9f182015-01-02 18:23:10 +0100828static const struct btrfs_compress_op * const btrfs_compress_op[] = {
Li Zefan261507a02010-12-17 14:21:50 +0800829 &btrfs_zlib_compress,
Li Zefana6fa6fa2010-10-25 15:12:26 +0800830 &btrfs_lzo_compress,
Nick Terrell5c1aab12017-08-09 19:39:02 -0700831 &btrfs_zstd_compress,
Li Zefan261507a02010-12-17 14:21:50 +0800832};
833
Jeff Mahoney143bede2012-03-01 14:56:26 +0100834void __init btrfs_init_compress(void)
Li Zefan261507a02010-12-17 14:21:50 +0800835{
Timofey Titovets4e439a02017-09-28 17:33:36 +0300836 struct list_head *workspace;
Li Zefan261507a02010-12-17 14:21:50 +0800837 int i;
838
Timofey Titovets4e439a02017-09-28 17:33:36 +0300839 INIT_LIST_HEAD(&btrfs_heuristic_ws.idle_ws);
840 spin_lock_init(&btrfs_heuristic_ws.ws_lock);
841 atomic_set(&btrfs_heuristic_ws.total_ws, 0);
842 init_waitqueue_head(&btrfs_heuristic_ws.ws_wait);
David Sterbaf77dd0d2016-04-27 02:55:15 +0200843
Timofey Titovets4e439a02017-09-28 17:33:36 +0300844 workspace = alloc_heuristic_ws();
845 if (IS_ERR(workspace)) {
846 pr_warn(
847 "BTRFS: cannot preallocate heuristic workspace, will try later\n");
848 } else {
849 atomic_set(&btrfs_heuristic_ws.total_ws, 1);
850 btrfs_heuristic_ws.free_ws = 1;
851 list_add(workspace, &btrfs_heuristic_ws.idle_ws);
852 }
853
854 for (i = 0; i < BTRFS_COMPRESS_TYPES; i++) {
Byongho Leed9187642015-10-14 14:05:24 +0900855 INIT_LIST_HEAD(&btrfs_comp_ws[i].idle_ws);
856 spin_lock_init(&btrfs_comp_ws[i].ws_lock);
David Sterba6ac10a62016-04-27 02:15:15 +0200857 atomic_set(&btrfs_comp_ws[i].total_ws, 0);
Byongho Leed9187642015-10-14 14:05:24 +0900858 init_waitqueue_head(&btrfs_comp_ws[i].ws_wait);
David Sterbaf77dd0d2016-04-27 02:55:15 +0200859
860 /*
861 * Preallocate one workspace for each compression type so
862 * we can guarantee forward progress in the worst case
863 */
864 workspace = btrfs_compress_op[i]->alloc_workspace();
865 if (IS_ERR(workspace)) {
Jeff Mahoney62e85572016-09-20 10:05:01 -0400866 pr_warn("BTRFS: cannot preallocate compression workspace, will try later\n");
David Sterbaf77dd0d2016-04-27 02:55:15 +0200867 } else {
868 atomic_set(&btrfs_comp_ws[i].total_ws, 1);
869 btrfs_comp_ws[i].free_ws = 1;
870 list_add(workspace, &btrfs_comp_ws[i].idle_ws);
871 }
Li Zefan261507a02010-12-17 14:21:50 +0800872 }
Li Zefan261507a02010-12-17 14:21:50 +0800873}
874
875/*
David Sterbae721e492016-04-27 02:41:17 +0200876 * This finds an available workspace or allocates a new one.
877 * If it's not possible to allocate a new one, waits until there's one.
878 * Preallocation makes a forward progress guarantees and we do not return
879 * errors.
Li Zefan261507a02010-12-17 14:21:50 +0800880 */
Timofey Titovets4e439a02017-09-28 17:33:36 +0300881static struct list_head *__find_workspace(int type, bool heuristic)
Li Zefan261507a02010-12-17 14:21:50 +0800882{
883 struct list_head *workspace;
884 int cpus = num_online_cpus();
885 int idx = type - 1;
David Sterbafe308532017-05-31 17:14:56 +0200886 unsigned nofs_flag;
Timofey Titovets4e439a02017-09-28 17:33:36 +0300887 struct list_head *idle_ws;
888 spinlock_t *ws_lock;
889 atomic_t *total_ws;
890 wait_queue_head_t *ws_wait;
891 int *free_ws;
Li Zefan261507a02010-12-17 14:21:50 +0800892
Timofey Titovets4e439a02017-09-28 17:33:36 +0300893 if (heuristic) {
894 idle_ws = &btrfs_heuristic_ws.idle_ws;
895 ws_lock = &btrfs_heuristic_ws.ws_lock;
896 total_ws = &btrfs_heuristic_ws.total_ws;
897 ws_wait = &btrfs_heuristic_ws.ws_wait;
898 free_ws = &btrfs_heuristic_ws.free_ws;
899 } else {
900 idle_ws = &btrfs_comp_ws[idx].idle_ws;
901 ws_lock = &btrfs_comp_ws[idx].ws_lock;
902 total_ws = &btrfs_comp_ws[idx].total_ws;
903 ws_wait = &btrfs_comp_ws[idx].ws_wait;
904 free_ws = &btrfs_comp_ws[idx].free_ws;
905 }
906
Li Zefan261507a02010-12-17 14:21:50 +0800907again:
Byongho Leed9187642015-10-14 14:05:24 +0900908 spin_lock(ws_lock);
909 if (!list_empty(idle_ws)) {
910 workspace = idle_ws->next;
Li Zefan261507a02010-12-17 14:21:50 +0800911 list_del(workspace);
David Sterba6ac10a62016-04-27 02:15:15 +0200912 (*free_ws)--;
Byongho Leed9187642015-10-14 14:05:24 +0900913 spin_unlock(ws_lock);
Li Zefan261507a02010-12-17 14:21:50 +0800914 return workspace;
915
916 }
David Sterba6ac10a62016-04-27 02:15:15 +0200917 if (atomic_read(total_ws) > cpus) {
Li Zefan261507a02010-12-17 14:21:50 +0800918 DEFINE_WAIT(wait);
919
Byongho Leed9187642015-10-14 14:05:24 +0900920 spin_unlock(ws_lock);
921 prepare_to_wait(ws_wait, &wait, TASK_UNINTERRUPTIBLE);
David Sterba6ac10a62016-04-27 02:15:15 +0200922 if (atomic_read(total_ws) > cpus && !*free_ws)
Li Zefan261507a02010-12-17 14:21:50 +0800923 schedule();
Byongho Leed9187642015-10-14 14:05:24 +0900924 finish_wait(ws_wait, &wait);
Li Zefan261507a02010-12-17 14:21:50 +0800925 goto again;
926 }
David Sterba6ac10a62016-04-27 02:15:15 +0200927 atomic_inc(total_ws);
Byongho Leed9187642015-10-14 14:05:24 +0900928 spin_unlock(ws_lock);
Li Zefan261507a02010-12-17 14:21:50 +0800929
David Sterbafe308532017-05-31 17:14:56 +0200930 /*
931 * Allocation helpers call vmalloc that can't use GFP_NOFS, so we have
932 * to turn it off here because we might get called from the restricted
933 * context of btrfs_compress_bio/btrfs_compress_pages
934 */
935 nofs_flag = memalloc_nofs_save();
Timofey Titovets4e439a02017-09-28 17:33:36 +0300936 if (heuristic)
937 workspace = alloc_heuristic_ws();
938 else
939 workspace = btrfs_compress_op[idx]->alloc_workspace();
David Sterbafe308532017-05-31 17:14:56 +0200940 memalloc_nofs_restore(nofs_flag);
941
Li Zefan261507a02010-12-17 14:21:50 +0800942 if (IS_ERR(workspace)) {
David Sterba6ac10a62016-04-27 02:15:15 +0200943 atomic_dec(total_ws);
Byongho Leed9187642015-10-14 14:05:24 +0900944 wake_up(ws_wait);
David Sterbae721e492016-04-27 02:41:17 +0200945
946 /*
947 * Do not return the error but go back to waiting. There's a
948 * workspace preallocated for each type and the compression
949 * time is bounded so we get to a workspace eventually. This
950 * makes our caller's life easier.
David Sterba523567162016-04-27 03:07:39 +0200951 *
952 * To prevent silent and low-probability deadlocks (when the
953 * initial preallocation fails), check if there are any
954 * workspaces at all.
David Sterbae721e492016-04-27 02:41:17 +0200955 */
David Sterba523567162016-04-27 03:07:39 +0200956 if (atomic_read(total_ws) == 0) {
957 static DEFINE_RATELIMIT_STATE(_rs,
958 /* once per minute */ 60 * HZ,
959 /* no burst */ 1);
960
961 if (__ratelimit(&_rs)) {
Jeff Mahoneyab8d0fc2016-09-20 10:05:02 -0400962 pr_warn("BTRFS: no compression workspaces, low memory, retrying\n");
David Sterba523567162016-04-27 03:07:39 +0200963 }
964 }
David Sterbae721e492016-04-27 02:41:17 +0200965 goto again;
Li Zefan261507a02010-12-17 14:21:50 +0800966 }
967 return workspace;
968}
969
Timofey Titovets4e439a02017-09-28 17:33:36 +0300970static struct list_head *find_workspace(int type)
971{
972 return __find_workspace(type, false);
973}
974
Li Zefan261507a02010-12-17 14:21:50 +0800975/*
976 * put a workspace struct back on the list or free it if we have enough
977 * idle ones sitting around
978 */
Timofey Titovets4e439a02017-09-28 17:33:36 +0300979static void __free_workspace(int type, struct list_head *workspace,
980 bool heuristic)
Li Zefan261507a02010-12-17 14:21:50 +0800981{
982 int idx = type - 1;
Timofey Titovets4e439a02017-09-28 17:33:36 +0300983 struct list_head *idle_ws;
984 spinlock_t *ws_lock;
985 atomic_t *total_ws;
986 wait_queue_head_t *ws_wait;
987 int *free_ws;
988
989 if (heuristic) {
990 idle_ws = &btrfs_heuristic_ws.idle_ws;
991 ws_lock = &btrfs_heuristic_ws.ws_lock;
992 total_ws = &btrfs_heuristic_ws.total_ws;
993 ws_wait = &btrfs_heuristic_ws.ws_wait;
994 free_ws = &btrfs_heuristic_ws.free_ws;
995 } else {
996 idle_ws = &btrfs_comp_ws[idx].idle_ws;
997 ws_lock = &btrfs_comp_ws[idx].ws_lock;
998 total_ws = &btrfs_comp_ws[idx].total_ws;
999 ws_wait = &btrfs_comp_ws[idx].ws_wait;
1000 free_ws = &btrfs_comp_ws[idx].free_ws;
1001 }
Li Zefan261507a02010-12-17 14:21:50 +08001002
Byongho Leed9187642015-10-14 14:05:24 +09001003 spin_lock(ws_lock);
Nick Terrell26b28dc2017-06-29 10:57:26 -07001004 if (*free_ws <= num_online_cpus()) {
Byongho Leed9187642015-10-14 14:05:24 +09001005 list_add(workspace, idle_ws);
David Sterba6ac10a62016-04-27 02:15:15 +02001006 (*free_ws)++;
Byongho Leed9187642015-10-14 14:05:24 +09001007 spin_unlock(ws_lock);
Li Zefan261507a02010-12-17 14:21:50 +08001008 goto wake;
1009 }
Byongho Leed9187642015-10-14 14:05:24 +09001010 spin_unlock(ws_lock);
Li Zefan261507a02010-12-17 14:21:50 +08001011
Timofey Titovets4e439a02017-09-28 17:33:36 +03001012 if (heuristic)
1013 free_heuristic_ws(workspace);
1014 else
1015 btrfs_compress_op[idx]->free_workspace(workspace);
David Sterba6ac10a62016-04-27 02:15:15 +02001016 atomic_dec(total_ws);
Li Zefan261507a02010-12-17 14:21:50 +08001017wake:
David Sterbaa83342a2015-02-16 19:36:47 +01001018 /*
1019 * Make sure counter is updated before we wake up waiters.
1020 */
Josef Bacik66657b32012-08-01 15:36:24 -04001021 smp_mb();
Byongho Leed9187642015-10-14 14:05:24 +09001022 if (waitqueue_active(ws_wait))
1023 wake_up(ws_wait);
Li Zefan261507a02010-12-17 14:21:50 +08001024}
1025
Timofey Titovets4e439a02017-09-28 17:33:36 +03001026static void free_workspace(int type, struct list_head *ws)
1027{
1028 return __free_workspace(type, ws, false);
1029}
1030
Li Zefan261507a02010-12-17 14:21:50 +08001031/*
1032 * cleanup function for module exit
1033 */
1034static void free_workspaces(void)
1035{
1036 struct list_head *workspace;
1037 int i;
1038
Timofey Titovets4e439a02017-09-28 17:33:36 +03001039 while (!list_empty(&btrfs_heuristic_ws.idle_ws)) {
1040 workspace = btrfs_heuristic_ws.idle_ws.next;
1041 list_del(workspace);
1042 free_heuristic_ws(workspace);
1043 atomic_dec(&btrfs_heuristic_ws.total_ws);
1044 }
1045
Li Zefan261507a02010-12-17 14:21:50 +08001046 for (i = 0; i < BTRFS_COMPRESS_TYPES; i++) {
Byongho Leed9187642015-10-14 14:05:24 +09001047 while (!list_empty(&btrfs_comp_ws[i].idle_ws)) {
1048 workspace = btrfs_comp_ws[i].idle_ws.next;
Li Zefan261507a02010-12-17 14:21:50 +08001049 list_del(workspace);
1050 btrfs_compress_op[i]->free_workspace(workspace);
David Sterba6ac10a62016-04-27 02:15:15 +02001051 atomic_dec(&btrfs_comp_ws[i].total_ws);
Li Zefan261507a02010-12-17 14:21:50 +08001052 }
1053 }
1054}
1055
1056/*
David Sterba38c31462017-02-14 19:04:07 +01001057 * Given an address space and start and length, compress the bytes into @pages
1058 * that are allocated on demand.
Li Zefan261507a02010-12-17 14:21:50 +08001059 *
David Sterbaf51d2b52017-09-15 17:36:57 +02001060 * @type_level is encoded algorithm and level, where level 0 means whatever
1061 * default the algorithm chooses and is opaque here;
1062 * - compression algo are 0-3
1063 * - the level are bits 4-7
1064 *
David Sterba4d3a8002017-02-14 19:04:07 +01001065 * @out_pages is an in/out parameter, holds maximum number of pages to allocate
1066 * and returns number of actually allocated pages
Li Zefan261507a02010-12-17 14:21:50 +08001067 *
David Sterba38c31462017-02-14 19:04:07 +01001068 * @total_in is used to return the number of bytes actually read. It
1069 * may be smaller than the input length if we had to exit early because we
Li Zefan261507a02010-12-17 14:21:50 +08001070 * ran out of room in the pages array or because we cross the
1071 * max_out threshold.
1072 *
David Sterba38c31462017-02-14 19:04:07 +01001073 * @total_out is an in/out parameter, must be set to the input length and will
1074 * be also used to return the total number of compressed bytes
Li Zefan261507a02010-12-17 14:21:50 +08001075 *
David Sterba38c31462017-02-14 19:04:07 +01001076 * @max_out tells us the max number of bytes that we're allowed to
Li Zefan261507a02010-12-17 14:21:50 +08001077 * stuff into pages
1078 */
David Sterbaf51d2b52017-09-15 17:36:57 +02001079int btrfs_compress_pages(unsigned int type_level, struct address_space *mapping,
David Sterba38c31462017-02-14 19:04:07 +01001080 u64 start, struct page **pages,
Li Zefan261507a02010-12-17 14:21:50 +08001081 unsigned long *out_pages,
1082 unsigned long *total_in,
David Sterbae5d74902017-02-14 19:45:05 +01001083 unsigned long *total_out)
Li Zefan261507a02010-12-17 14:21:50 +08001084{
1085 struct list_head *workspace;
1086 int ret;
David Sterbaf51d2b52017-09-15 17:36:57 +02001087 int type = type_level & 0xF;
Li Zefan261507a02010-12-17 14:21:50 +08001088
1089 workspace = find_workspace(type);
Li Zefan261507a02010-12-17 14:21:50 +08001090
David Sterbaf51d2b52017-09-15 17:36:57 +02001091 btrfs_compress_op[type - 1]->set_level(workspace, type_level);
Li Zefan261507a02010-12-17 14:21:50 +08001092 ret = btrfs_compress_op[type-1]->compress_pages(workspace, mapping,
David Sterba38c31462017-02-14 19:04:07 +01001093 start, pages,
David Sterba4d3a8002017-02-14 19:04:07 +01001094 out_pages,
David Sterbae5d74902017-02-14 19:45:05 +01001095 total_in, total_out);
Li Zefan261507a02010-12-17 14:21:50 +08001096 free_workspace(type, workspace);
1097 return ret;
1098}
1099
1100/*
1101 * pages_in is an array of pages with compressed data.
1102 *
1103 * disk_start is the starting logical offset of this array in the file
1104 *
Christoph Hellwig974b1ad2016-11-25 09:07:46 +01001105 * orig_bio contains the pages from the file that we want to decompress into
Li Zefan261507a02010-12-17 14:21:50 +08001106 *
1107 * srclen is the number of bytes in pages_in
1108 *
1109 * The basic idea is that we have a bio that was created by readpages.
1110 * The pages in the bio are for the uncompressed data, and they may not
1111 * be contiguous. They all correspond to the range of bytes covered by
1112 * the compressed extent.
1113 */
Anand Jain8140dc32017-05-26 15:44:58 +08001114static int btrfs_decompress_bio(struct compressed_bio *cb)
Li Zefan261507a02010-12-17 14:21:50 +08001115{
1116 struct list_head *workspace;
1117 int ret;
Anand Jain8140dc32017-05-26 15:44:58 +08001118 int type = cb->compress_type;
Li Zefan261507a02010-12-17 14:21:50 +08001119
1120 workspace = find_workspace(type);
Anand Jaine1ddce72017-05-26 15:44:59 +08001121 ret = btrfs_compress_op[type - 1]->decompress_bio(workspace, cb);
Li Zefan261507a02010-12-17 14:21:50 +08001122 free_workspace(type, workspace);
Anand Jaine1ddce72017-05-26 15:44:59 +08001123
Li Zefan261507a02010-12-17 14:21:50 +08001124 return ret;
1125}
1126
1127/*
1128 * a less complex decompression routine. Our compressed data fits in a
1129 * single page, and we want to read a single page out of it.
1130 * start_byte tells us the offset into the compressed data we're interested in
1131 */
1132int btrfs_decompress(int type, unsigned char *data_in, struct page *dest_page,
1133 unsigned long start_byte, size_t srclen, size_t destlen)
1134{
1135 struct list_head *workspace;
1136 int ret;
1137
1138 workspace = find_workspace(type);
Li Zefan261507a02010-12-17 14:21:50 +08001139
1140 ret = btrfs_compress_op[type-1]->decompress(workspace, data_in,
1141 dest_page, start_byte,
1142 srclen, destlen);
1143
1144 free_workspace(type, workspace);
1145 return ret;
1146}
1147
Alexey Charkov8e4eef72011-02-02 21:15:35 +00001148void btrfs_exit_compress(void)
Li Zefan261507a02010-12-17 14:21:50 +08001149{
1150 free_workspaces();
1151}
Li Zefan3a39c182010-11-08 15:22:19 +08001152
1153/*
1154 * Copy uncompressed data from working buffer to pages.
1155 *
1156 * buf_start is the byte offset we're of the start of our workspace buffer.
1157 *
1158 * total_out is the last byte of the buffer
1159 */
David Sterba14a33572017-02-14 17:58:04 +01001160int btrfs_decompress_buf2page(const char *buf, unsigned long buf_start,
Li Zefan3a39c182010-11-08 15:22:19 +08001161 unsigned long total_out, u64 disk_start,
Christoph Hellwig974b1ad2016-11-25 09:07:46 +01001162 struct bio *bio)
Li Zefan3a39c182010-11-08 15:22:19 +08001163{
1164 unsigned long buf_offset;
1165 unsigned long current_buf_start;
1166 unsigned long start_byte;
Omar Sandoval6e78b3f2017-02-10 15:03:35 -08001167 unsigned long prev_start_byte;
Li Zefan3a39c182010-11-08 15:22:19 +08001168 unsigned long working_bytes = total_out - buf_start;
1169 unsigned long bytes;
1170 char *kaddr;
Christoph Hellwig974b1ad2016-11-25 09:07:46 +01001171 struct bio_vec bvec = bio_iter_iovec(bio, bio->bi_iter);
Li Zefan3a39c182010-11-08 15:22:19 +08001172
1173 /*
1174 * start byte is the first byte of the page we're currently
1175 * copying into relative to the start of the compressed data.
1176 */
Christoph Hellwig974b1ad2016-11-25 09:07:46 +01001177 start_byte = page_offset(bvec.bv_page) - disk_start;
Li Zefan3a39c182010-11-08 15:22:19 +08001178
1179 /* we haven't yet hit data corresponding to this page */
1180 if (total_out <= start_byte)
1181 return 1;
1182
1183 /*
1184 * the start of the data we care about is offset into
1185 * the middle of our working buffer
1186 */
1187 if (total_out > start_byte && buf_start < start_byte) {
1188 buf_offset = start_byte - buf_start;
1189 working_bytes -= buf_offset;
1190 } else {
1191 buf_offset = 0;
1192 }
1193 current_buf_start = buf_start;
1194
1195 /* copy bytes from the working buffer into the pages */
1196 while (working_bytes > 0) {
Christoph Hellwig974b1ad2016-11-25 09:07:46 +01001197 bytes = min_t(unsigned long, bvec.bv_len,
1198 PAGE_SIZE - buf_offset);
Li Zefan3a39c182010-11-08 15:22:19 +08001199 bytes = min(bytes, working_bytes);
Li Zefan3a39c182010-11-08 15:22:19 +08001200
Christoph Hellwig974b1ad2016-11-25 09:07:46 +01001201 kaddr = kmap_atomic(bvec.bv_page);
1202 memcpy(kaddr + bvec.bv_offset, buf + buf_offset, bytes);
1203 kunmap_atomic(kaddr);
1204 flush_dcache_page(bvec.bv_page);
1205
Li Zefan3a39c182010-11-08 15:22:19 +08001206 buf_offset += bytes;
1207 working_bytes -= bytes;
1208 current_buf_start += bytes;
1209
1210 /* check if we need to pick another page */
Christoph Hellwig974b1ad2016-11-25 09:07:46 +01001211 bio_advance(bio, bytes);
1212 if (!bio->bi_iter.bi_size)
1213 return 0;
1214 bvec = bio_iter_iovec(bio, bio->bi_iter);
Omar Sandoval6e78b3f2017-02-10 15:03:35 -08001215 prev_start_byte = start_byte;
Christoph Hellwig974b1ad2016-11-25 09:07:46 +01001216 start_byte = page_offset(bvec.bv_page) - disk_start;
Li Zefan3a39c182010-11-08 15:22:19 +08001217
Christoph Hellwig974b1ad2016-11-25 09:07:46 +01001218 /*
Omar Sandoval6e78b3f2017-02-10 15:03:35 -08001219 * We need to make sure we're only adjusting
1220 * our offset into compression working buffer when
1221 * we're switching pages. Otherwise we can incorrectly
1222 * keep copying when we were actually done.
Christoph Hellwig974b1ad2016-11-25 09:07:46 +01001223 */
Omar Sandoval6e78b3f2017-02-10 15:03:35 -08001224 if (start_byte != prev_start_byte) {
1225 /*
1226 * make sure our new page is covered by this
1227 * working buffer
1228 */
1229 if (total_out <= start_byte)
1230 return 1;
Li Zefan3a39c182010-11-08 15:22:19 +08001231
Omar Sandoval6e78b3f2017-02-10 15:03:35 -08001232 /*
1233 * the next page in the biovec might not be adjacent
1234 * to the last page, but it might still be found
1235 * inside this working buffer. bump our offset pointer
1236 */
1237 if (total_out > start_byte &&
1238 current_buf_start < start_byte) {
1239 buf_offset = start_byte - buf_start;
1240 working_bytes = total_out - start_byte;
1241 current_buf_start = buf_start + buf_offset;
1242 }
Li Zefan3a39c182010-11-08 15:22:19 +08001243 }
1244 }
1245
1246 return 1;
1247}
Timofey Titovetsc2fcdcd2017-07-17 16:52:58 +03001248
Timofey Titovets19562432017-10-08 16:11:59 +03001249/*
1250 * Shannon Entropy calculation
1251 *
1252 * Pure byte distribution analysis fails to determine compressiability of data.
1253 * Try calculating entropy to estimate the average minimum number of bits
1254 * needed to encode the sampled data.
1255 *
1256 * For convenience, return the percentage of needed bits, instead of amount of
1257 * bits directly.
1258 *
1259 * @ENTROPY_LVL_ACEPTABLE - below that threshold, sample has low byte entropy
1260 * and can be compressible with high probability
1261 *
1262 * @ENTROPY_LVL_HIGH - data are not compressible with high probability
1263 *
1264 * Use of ilog2() decreases precision, we lower the LVL to 5 to compensate.
1265 */
1266#define ENTROPY_LVL_ACEPTABLE (65)
1267#define ENTROPY_LVL_HIGH (80)
1268
1269/*
1270 * For increasead precision in shannon_entropy calculation,
1271 * let's do pow(n, M) to save more digits after comma:
1272 *
1273 * - maximum int bit length is 64
1274 * - ilog2(MAX_SAMPLE_SIZE) -> 13
1275 * - 13 * 4 = 52 < 64 -> M = 4
1276 *
1277 * So use pow(n, 4).
1278 */
1279static inline u32 ilog2_w(u64 n)
1280{
1281 return ilog2(n * n * n * n);
1282}
1283
1284static u32 shannon_entropy(struct heuristic_ws *ws)
1285{
1286 const u32 entropy_max = 8 * ilog2_w(2);
1287 u32 entropy_sum = 0;
1288 u32 p, p_base, sz_base;
1289 u32 i;
1290
1291 sz_base = ilog2_w(ws->sample_size);
1292 for (i = 0; i < BUCKET_SIZE && ws->bucket[i].count > 0; i++) {
1293 p = ws->bucket[i].count;
1294 p_base = ilog2_w(p);
1295 entropy_sum += p * (sz_base - p_base);
1296 }
1297
1298 entropy_sum /= ws->sample_size;
1299 return entropy_sum * 100 / entropy_max;
1300}
1301
Timofey Titovets440c8402017-12-04 00:30:33 +03001302#define RADIX_BASE 4U
1303#define COUNTERS_SIZE (1U << RADIX_BASE)
Timofey Titovets858177d2017-09-28 17:33:41 +03001304
Timofey Titovets440c8402017-12-04 00:30:33 +03001305static u8 get4bits(u64 num, int shift) {
1306 u8 low4bits;
1307
1308 num >>= shift;
1309 /* Reverse order */
1310 low4bits = (COUNTERS_SIZE - 1) - (num % COUNTERS_SIZE);
1311 return low4bits;
1312}
1313
Timofey Titovets440c8402017-12-04 00:30:33 +03001314/*
1315 * Use 4 bits as radix base
1316 * Use 16 u32 counters for calculating new possition in buf array
1317 *
1318 * @array - array that will be sorted
1319 * @array_buf - buffer array to store sorting results
1320 * must be equal in size to @array
1321 * @num - array size
Timofey Titovets440c8402017-12-04 00:30:33 +03001322 */
David Sterba23ae8c62017-12-12 20:35:02 +01001323static void radix_sort(struct bucket_item *array, struct bucket_item *array_buf,
David Sterba36243c92017-12-12 20:35:02 +01001324 int num)
Timofey Titovets440c8402017-12-04 00:30:33 +03001325{
1326 u64 max_num;
1327 u64 buf_num;
1328 u32 counters[COUNTERS_SIZE];
1329 u32 new_addr;
1330 u32 addr;
1331 int bitlen;
1332 int shift;
1333 int i;
1334
1335 /*
1336 * Try avoid useless loop iterations for small numbers stored in big
1337 * counters. Example: 48 33 4 ... in 64bit array
1338 */
David Sterba23ae8c62017-12-12 20:35:02 +01001339 max_num = array[0].count;
Timofey Titovets440c8402017-12-04 00:30:33 +03001340 for (i = 1; i < num; i++) {
David Sterba23ae8c62017-12-12 20:35:02 +01001341 buf_num = array[i].count;
Timofey Titovets440c8402017-12-04 00:30:33 +03001342 if (buf_num > max_num)
1343 max_num = buf_num;
1344 }
1345
1346 buf_num = ilog2(max_num);
1347 bitlen = ALIGN(buf_num, RADIX_BASE * 2);
1348
1349 shift = 0;
1350 while (shift < bitlen) {
1351 memset(counters, 0, sizeof(counters));
1352
1353 for (i = 0; i < num; i++) {
David Sterba23ae8c62017-12-12 20:35:02 +01001354 buf_num = array[i].count;
Timofey Titovets440c8402017-12-04 00:30:33 +03001355 addr = get4bits(buf_num, shift);
1356 counters[addr]++;
1357 }
1358
1359 for (i = 1; i < COUNTERS_SIZE; i++)
1360 counters[i] += counters[i - 1];
1361
1362 for (i = num - 1; i >= 0; i--) {
David Sterba23ae8c62017-12-12 20:35:02 +01001363 buf_num = array[i].count;
Timofey Titovets440c8402017-12-04 00:30:33 +03001364 addr = get4bits(buf_num, shift);
1365 counters[addr]--;
1366 new_addr = counters[addr];
David Sterba7add17b2017-12-12 20:35:02 +01001367 array_buf[new_addr] = array[i];
Timofey Titovets440c8402017-12-04 00:30:33 +03001368 }
1369
1370 shift += RADIX_BASE;
1371
1372 /*
1373 * Normal radix expects to move data from a temporary array, to
1374 * the main one. But that requires some CPU time. Avoid that
1375 * by doing another sort iteration to original array instead of
1376 * memcpy()
1377 */
1378 memset(counters, 0, sizeof(counters));
1379
1380 for (i = 0; i < num; i ++) {
David Sterba23ae8c62017-12-12 20:35:02 +01001381 buf_num = array_buf[i].count;
Timofey Titovets440c8402017-12-04 00:30:33 +03001382 addr = get4bits(buf_num, shift);
1383 counters[addr]++;
1384 }
1385
1386 for (i = 1; i < COUNTERS_SIZE; i++)
1387 counters[i] += counters[i - 1];
1388
1389 for (i = num - 1; i >= 0; i--) {
David Sterba23ae8c62017-12-12 20:35:02 +01001390 buf_num = array_buf[i].count;
Timofey Titovets440c8402017-12-04 00:30:33 +03001391 addr = get4bits(buf_num, shift);
1392 counters[addr]--;
1393 new_addr = counters[addr];
David Sterba7add17b2017-12-12 20:35:02 +01001394 array[new_addr] = array_buf[i];
Timofey Titovets440c8402017-12-04 00:30:33 +03001395 }
1396
1397 shift += RADIX_BASE;
1398 }
Timofey Titovets858177d2017-09-28 17:33:41 +03001399}
1400
1401/*
1402 * Size of the core byte set - how many bytes cover 90% of the sample
1403 *
1404 * There are several types of structured binary data that use nearly all byte
1405 * values. The distribution can be uniform and counts in all buckets will be
1406 * nearly the same (eg. encrypted data). Unlikely to be compressible.
1407 *
1408 * Other possibility is normal (Gaussian) distribution, where the data could
1409 * be potentially compressible, but we have to take a few more steps to decide
1410 * how much.
1411 *
1412 * @BYTE_CORE_SET_LOW - main part of byte values repeated frequently,
1413 * compression algo can easy fix that
1414 * @BYTE_CORE_SET_HIGH - data have uniform distribution and with high
1415 * probability is not compressible
1416 */
1417#define BYTE_CORE_SET_LOW (64)
1418#define BYTE_CORE_SET_HIGH (200)
1419
1420static int byte_core_set_size(struct heuristic_ws *ws)
1421{
1422 u32 i;
1423 u32 coreset_sum = 0;
1424 const u32 core_set_threshold = ws->sample_size * 90 / 100;
1425 struct bucket_item *bucket = ws->bucket;
1426
1427 /* Sort in reverse order */
David Sterba36243c92017-12-12 20:35:02 +01001428 radix_sort(ws->bucket, ws->bucket_b, BUCKET_SIZE);
Timofey Titovets858177d2017-09-28 17:33:41 +03001429
1430 for (i = 0; i < BYTE_CORE_SET_LOW; i++)
1431 coreset_sum += bucket[i].count;
1432
1433 if (coreset_sum > core_set_threshold)
1434 return i;
1435
1436 for (; i < BYTE_CORE_SET_HIGH && bucket[i].count > 0; i++) {
1437 coreset_sum += bucket[i].count;
1438 if (coreset_sum > core_set_threshold)
1439 break;
1440 }
1441
1442 return i;
1443}
1444
Timofey Titovetsa288e922017-09-28 17:33:40 +03001445/*
1446 * Count byte values in buckets.
1447 * This heuristic can detect textual data (configs, xml, json, html, etc).
1448 * Because in most text-like data byte set is restricted to limited number of
1449 * possible characters, and that restriction in most cases makes data easy to
1450 * compress.
1451 *
1452 * @BYTE_SET_THRESHOLD - consider all data within this byte set size:
1453 * less - compressible
1454 * more - need additional analysis
1455 */
1456#define BYTE_SET_THRESHOLD (64)
1457
1458static u32 byte_set_size(const struct heuristic_ws *ws)
1459{
1460 u32 i;
1461 u32 byte_set_size = 0;
1462
1463 for (i = 0; i < BYTE_SET_THRESHOLD; i++) {
1464 if (ws->bucket[i].count > 0)
1465 byte_set_size++;
1466 }
1467
1468 /*
1469 * Continue collecting count of byte values in buckets. If the byte
1470 * set size is bigger then the threshold, it's pointless to continue,
1471 * the detection technique would fail for this type of data.
1472 */
1473 for (; i < BUCKET_SIZE; i++) {
1474 if (ws->bucket[i].count > 0) {
1475 byte_set_size++;
1476 if (byte_set_size > BYTE_SET_THRESHOLD)
1477 return byte_set_size;
1478 }
1479 }
1480
1481 return byte_set_size;
1482}
1483
Timofey Titovets1fe4f6f2017-09-28 17:33:39 +03001484static bool sample_repeated_patterns(struct heuristic_ws *ws)
1485{
1486 const u32 half_of_sample = ws->sample_size / 2;
1487 const u8 *data = ws->sample;
1488
1489 return memcmp(&data[0], &data[half_of_sample], half_of_sample) == 0;
1490}
1491
Timofey Titovetsa440d482017-09-28 17:33:38 +03001492static void heuristic_collect_sample(struct inode *inode, u64 start, u64 end,
1493 struct heuristic_ws *ws)
1494{
1495 struct page *page;
1496 u64 index, index_end;
1497 u32 i, curr_sample_pos;
1498 u8 *in_data;
1499
1500 /*
1501 * Compression handles the input data by chunks of 128KiB
1502 * (defined by BTRFS_MAX_UNCOMPRESSED)
1503 *
1504 * We do the same for the heuristic and loop over the whole range.
1505 *
1506 * MAX_SAMPLE_SIZE - calculated under assumption that heuristic will
1507 * process no more than BTRFS_MAX_UNCOMPRESSED at a time.
1508 */
1509 if (end - start > BTRFS_MAX_UNCOMPRESSED)
1510 end = start + BTRFS_MAX_UNCOMPRESSED;
1511
1512 index = start >> PAGE_SHIFT;
1513 index_end = end >> PAGE_SHIFT;
1514
1515 /* Don't miss unaligned end */
1516 if (!IS_ALIGNED(end, PAGE_SIZE))
1517 index_end++;
1518
1519 curr_sample_pos = 0;
1520 while (index < index_end) {
1521 page = find_get_page(inode->i_mapping, index);
1522 in_data = kmap(page);
1523 /* Handle case where the start is not aligned to PAGE_SIZE */
1524 i = start % PAGE_SIZE;
1525 while (i < PAGE_SIZE - SAMPLING_READ_SIZE) {
1526 /* Don't sample any garbage from the last page */
1527 if (start > end - SAMPLING_READ_SIZE)
1528 break;
1529 memcpy(&ws->sample[curr_sample_pos], &in_data[i],
1530 SAMPLING_READ_SIZE);
1531 i += SAMPLING_INTERVAL;
1532 start += SAMPLING_INTERVAL;
1533 curr_sample_pos += SAMPLING_READ_SIZE;
1534 }
1535 kunmap(page);
1536 put_page(page);
1537
1538 index++;
1539 }
1540
1541 ws->sample_size = curr_sample_pos;
1542}
1543
Timofey Titovetsc2fcdcd2017-07-17 16:52:58 +03001544/*
1545 * Compression heuristic.
1546 *
1547 * For now is's a naive and optimistic 'return true', we'll extend the logic to
1548 * quickly (compared to direct compression) detect data characteristics
1549 * (compressible/uncompressible) to avoid wasting CPU time on uncompressible
1550 * data.
1551 *
1552 * The following types of analysis can be performed:
1553 * - detect mostly zero data
1554 * - detect data with low "byte set" size (text, etc)
1555 * - detect data with low/high "core byte" set
1556 *
1557 * Return non-zero if the compression should be done, 0 otherwise.
1558 */
1559int btrfs_compress_heuristic(struct inode *inode, u64 start, u64 end)
1560{
Timofey Titovets4e439a02017-09-28 17:33:36 +03001561 struct list_head *ws_list = __find_workspace(0, true);
1562 struct heuristic_ws *ws;
Timofey Titovetsa440d482017-09-28 17:33:38 +03001563 u32 i;
1564 u8 byte;
Timofey Titovets19562432017-10-08 16:11:59 +03001565 int ret = 0;
Timofey Titovetsc2fcdcd2017-07-17 16:52:58 +03001566
Timofey Titovets4e439a02017-09-28 17:33:36 +03001567 ws = list_entry(ws_list, struct heuristic_ws, list);
1568
Timofey Titovetsa440d482017-09-28 17:33:38 +03001569 heuristic_collect_sample(inode, start, end, ws);
1570
Timofey Titovets1fe4f6f2017-09-28 17:33:39 +03001571 if (sample_repeated_patterns(ws)) {
1572 ret = 1;
1573 goto out;
1574 }
1575
Timofey Titovetsa440d482017-09-28 17:33:38 +03001576 memset(ws->bucket, 0, sizeof(*ws->bucket)*BUCKET_SIZE);
1577
1578 for (i = 0; i < ws->sample_size; i++) {
1579 byte = ws->sample[i];
1580 ws->bucket[byte].count++;
Timofey Titovetsc2fcdcd2017-07-17 16:52:58 +03001581 }
1582
Timofey Titovetsa288e922017-09-28 17:33:40 +03001583 i = byte_set_size(ws);
1584 if (i < BYTE_SET_THRESHOLD) {
1585 ret = 2;
1586 goto out;
1587 }
1588
Timofey Titovets858177d2017-09-28 17:33:41 +03001589 i = byte_core_set_size(ws);
1590 if (i <= BYTE_CORE_SET_LOW) {
1591 ret = 3;
1592 goto out;
1593 }
1594
1595 if (i >= BYTE_CORE_SET_HIGH) {
1596 ret = 0;
1597 goto out;
1598 }
1599
Timofey Titovets19562432017-10-08 16:11:59 +03001600 i = shannon_entropy(ws);
1601 if (i <= ENTROPY_LVL_ACEPTABLE) {
1602 ret = 4;
1603 goto out;
1604 }
1605
1606 /*
1607 * For the levels below ENTROPY_LVL_HIGH, additional analysis would be
1608 * needed to give green light to compression.
1609 *
1610 * For now just assume that compression at that level is not worth the
1611 * resources because:
1612 *
1613 * 1. it is possible to defrag the data later
1614 *
1615 * 2. the data would turn out to be hardly compressible, eg. 150 byte
1616 * values, every bucket has counter at level ~54. The heuristic would
1617 * be confused. This can happen when data have some internal repeated
1618 * patterns like "abbacbbc...". This can be detected by analyzing
1619 * pairs of bytes, which is too costly.
1620 */
1621 if (i < ENTROPY_LVL_HIGH) {
1622 ret = 5;
1623 goto out;
1624 } else {
1625 ret = 0;
1626 goto out;
1627 }
1628
Timofey Titovets1fe4f6f2017-09-28 17:33:39 +03001629out:
Timofey Titovets4e439a02017-09-28 17:33:36 +03001630 __free_workspace(0, ws_list, true);
Timofey Titovetsc2fcdcd2017-07-17 16:52:58 +03001631 return ret;
1632}
David Sterbaf51d2b52017-09-15 17:36:57 +02001633
1634unsigned int btrfs_compress_str2level(const char *str)
1635{
1636 if (strncmp(str, "zlib", 4) != 0)
1637 return 0;
1638
Adam Borowskifa4d8852017-09-15 17:36:58 +02001639 /* Accepted form: zlib:1 up to zlib:9 and nothing left after the number */
1640 if (str[4] == ':' && '1' <= str[5] && str[5] <= '9' && str[6] == 0)
1641 return str[5] - '0';
David Sterbaf51d2b52017-09-15 17:36:57 +02001642
Qu Wenruoeae8d822017-11-06 10:43:18 +08001643 return BTRFS_ZLIB_DEFAULT_LEVEL;
David Sterbaf51d2b52017-09-15 17:36:57 +02001644}