blob: b35ce16b3df3c6550a69289077eb922bcd5d76cb [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 Titovets858177d2017-09-28 17:33:41 +030036#include <linux/sort.h>
Timofey Titovets19562432017-10-08 16:11:59 +030037#include <linux/log2.h>
Chris Masonc8b97812008-10-29 14:49:59 -040038#include "ctree.h"
39#include "disk-io.h"
40#include "transaction.h"
41#include "btrfs_inode.h"
42#include "volumes.h"
43#include "ordered-data.h"
Chris Masonc8b97812008-10-29 14:49:59 -040044#include "compression.h"
45#include "extent_io.h"
46#include "extent_map.h"
47
Anand Jain8140dc32017-05-26 15:44:58 +080048static int btrfs_decompress_bio(struct compressed_bio *cb);
Eric Sandeen48a3b632013-04-25 20:41:01 +000049
Jeff Mahoney2ff7e612016-06-22 18:54:24 -040050static inline int compressed_bio_size(struct btrfs_fs_info *fs_info,
Chris Masond20f7042008-12-08 16:58:54 -050051 unsigned long disk_size)
52{
Jeff Mahoney0b246af2016-06-22 18:54:23 -040053 u16 csum_size = btrfs_super_csum_size(fs_info->super_copy);
David Sterba6c417612011-04-13 15:41:04 +020054
Chris Masond20f7042008-12-08 16:58:54 -050055 return sizeof(struct compressed_bio) +
Jeff Mahoney0b246af2016-06-22 18:54:23 -040056 (DIV_ROUND_UP(disk_size, fs_info->sectorsize)) * csum_size;
Chris Masond20f7042008-12-08 16:58:54 -050057}
58
Nikolay Borisovf898ac62017-02-20 13:50:54 +020059static int check_compressed_csum(struct btrfs_inode *inode,
Chris Masond20f7042008-12-08 16:58:54 -050060 struct compressed_bio *cb,
61 u64 disk_start)
62{
63 int ret;
Chris Masond20f7042008-12-08 16:58:54 -050064 struct page *page;
65 unsigned long i;
66 char *kaddr;
67 u32 csum;
68 u32 *cb_sum = &cb->sums;
69
Nikolay Borisovf898ac62017-02-20 13:50:54 +020070 if (inode->flags & BTRFS_INODE_NODATASUM)
Chris Masond20f7042008-12-08 16:58:54 -050071 return 0;
72
73 for (i = 0; i < cb->nr_pages; i++) {
74 page = cb->compressed_pages[i];
75 csum = ~(u32)0;
76
Cong Wang7ac687d2011-11-25 23:14:28 +080077 kaddr = kmap_atomic(page);
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +030078 csum = btrfs_csum_data(kaddr, csum, PAGE_SIZE);
Domagoj Tršan0b5e3da2016-10-27 08:52:33 +010079 btrfs_csum_final(csum, (u8 *)&csum);
Cong Wang7ac687d2011-11-25 23:14:28 +080080 kunmap_atomic(kaddr);
Chris Masond20f7042008-12-08 16:58:54 -050081
82 if (csum != *cb_sum) {
Nikolay Borisovf898ac62017-02-20 13:50:54 +020083 btrfs_print_data_csum_error(inode, disk_start, csum,
Nikolay Borisov0970a222017-02-20 13:50:53 +020084 *cb_sum, cb->mirror_num);
Chris Masond20f7042008-12-08 16:58:54 -050085 ret = -EIO;
86 goto fail;
87 }
88 cb_sum++;
89
90 }
91 ret = 0;
92fail:
93 return ret;
94}
95
Chris Masonc8b97812008-10-29 14:49:59 -040096/* when we finish reading compressed pages from the disk, we
97 * decompress them and then run the bio end_io routines on the
98 * decompressed pages (in the inode address space).
99 *
100 * This allows the checksumming and other IO error handling routines
101 * to work normally
102 *
103 * The compressed pages are freed here, and it must be run
104 * in process context
105 */
Christoph Hellwig4246a0b2015-07-20 15:29:37 +0200106static void end_compressed_bio_read(struct bio *bio)
Chris Masonc8b97812008-10-29 14:49:59 -0400107{
Chris Masonc8b97812008-10-29 14:49:59 -0400108 struct compressed_bio *cb = bio->bi_private;
109 struct inode *inode;
110 struct page *page;
111 unsigned long index;
Liu Bocf1167d2017-09-20 17:50:18 -0600112 unsigned int mirror = btrfs_io_bio(bio)->mirror_num;
Liu Boe6311f22017-09-20 17:50:19 -0600113 int ret = 0;
Chris Masonc8b97812008-10-29 14:49:59 -0400114
Christoph Hellwig4e4cbee2017-06-03 09:38:06 +0200115 if (bio->bi_status)
Chris Masonc8b97812008-10-29 14:49:59 -0400116 cb->errors = 1;
117
118 /* if there are more bios still pending for this compressed
119 * extent, just exit
120 */
Elena Reshetovaa50299a2017-03-03 10:55:20 +0200121 if (!refcount_dec_and_test(&cb->pending_bios))
Chris Masonc8b97812008-10-29 14:49:59 -0400122 goto out;
123
Liu Bocf1167d2017-09-20 17:50:18 -0600124 /*
125 * Record the correct mirror_num in cb->orig_bio so that
126 * read-repair can work properly.
127 */
128 ASSERT(btrfs_io_bio(cb->orig_bio));
129 btrfs_io_bio(cb->orig_bio)->mirror_num = mirror;
130 cb->mirror_num = mirror;
131
Liu Boe6311f22017-09-20 17:50:19 -0600132 /*
133 * Some IO in this cb have failed, just skip checksum as there
134 * is no way it could be correct.
135 */
136 if (cb->errors == 1)
137 goto csum_failed;
138
Chris Masond20f7042008-12-08 16:58:54 -0500139 inode = cb->inode;
Nikolay Borisovf898ac62017-02-20 13:50:54 +0200140 ret = check_compressed_csum(BTRFS_I(inode), cb,
Kent Overstreet4f024f32013-10-11 15:44:27 -0700141 (u64)bio->bi_iter.bi_sector << 9);
Chris Masond20f7042008-12-08 16:58:54 -0500142 if (ret)
143 goto csum_failed;
144
Chris Masonc8b97812008-10-29 14:49:59 -0400145 /* ok, we're the last bio for this extent, lets start
146 * the decompression.
147 */
Anand Jain8140dc32017-05-26 15:44:58 +0800148 ret = btrfs_decompress_bio(cb);
149
Chris Masond20f7042008-12-08 16:58:54 -0500150csum_failed:
Chris Masonc8b97812008-10-29 14:49:59 -0400151 if (ret)
152 cb->errors = 1;
153
154 /* release the compressed pages */
155 index = 0;
156 for (index = 0; index < cb->nr_pages; index++) {
157 page = cb->compressed_pages[index];
158 page->mapping = NULL;
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300159 put_page(page);
Chris Masonc8b97812008-10-29 14:49:59 -0400160 }
161
162 /* do io completion on the original bio */
Chris Mason771ed682008-11-06 22:02:51 -0500163 if (cb->errors) {
Chris Masonc8b97812008-10-29 14:49:59 -0400164 bio_io_error(cb->orig_bio);
Chris Masond20f7042008-12-08 16:58:54 -0500165 } else {
Kent Overstreet2c30c712013-11-07 12:20:26 -0800166 int i;
167 struct bio_vec *bvec;
Chris Masond20f7042008-12-08 16:58:54 -0500168
169 /*
170 * we have verified the checksum already, set page
171 * checked so the end_io handlers know about it
172 */
David Sterbac09abff2017-07-13 18:10:07 +0200173 ASSERT(!bio_flagged(bio, BIO_CLONED));
Kent Overstreet2c30c712013-11-07 12:20:26 -0800174 bio_for_each_segment_all(bvec, cb->orig_bio, i)
Chris Masond20f7042008-12-08 16:58:54 -0500175 SetPageChecked(bvec->bv_page);
Kent Overstreet2c30c712013-11-07 12:20:26 -0800176
Christoph Hellwig4246a0b2015-07-20 15:29:37 +0200177 bio_endio(cb->orig_bio);
Chris Masond20f7042008-12-08 16:58:54 -0500178 }
Chris Masonc8b97812008-10-29 14:49:59 -0400179
180 /* finally free the cb struct */
181 kfree(cb->compressed_pages);
182 kfree(cb);
183out:
184 bio_put(bio);
185}
186
187/*
188 * Clear the writeback bits on all of the file
189 * pages for a compressed write
190 */
Filipe Manana7bdcefc2014-10-07 01:48:26 +0100191static noinline void end_compressed_writeback(struct inode *inode,
192 const struct compressed_bio *cb)
Chris Masonc8b97812008-10-29 14:49:59 -0400193{
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300194 unsigned long index = cb->start >> PAGE_SHIFT;
195 unsigned long end_index = (cb->start + cb->len - 1) >> PAGE_SHIFT;
Chris Masonc8b97812008-10-29 14:49:59 -0400196 struct page *pages[16];
197 unsigned long nr_pages = end_index - index + 1;
198 int i;
199 int ret;
200
Filipe Manana7bdcefc2014-10-07 01:48:26 +0100201 if (cb->errors)
202 mapping_set_error(inode->i_mapping, -EIO);
203
Chris Masond3977122009-01-05 21:25:51 -0500204 while (nr_pages > 0) {
Chris Masonc8b97812008-10-29 14:49:59 -0400205 ret = find_get_pages_contig(inode->i_mapping, index,
Chris Mason5b050f02008-11-11 09:34:41 -0500206 min_t(unsigned long,
207 nr_pages, ARRAY_SIZE(pages)), pages);
Chris Masonc8b97812008-10-29 14:49:59 -0400208 if (ret == 0) {
209 nr_pages -= 1;
210 index += 1;
211 continue;
212 }
213 for (i = 0; i < ret; i++) {
Filipe Manana7bdcefc2014-10-07 01:48:26 +0100214 if (cb->errors)
215 SetPageError(pages[i]);
Chris Masonc8b97812008-10-29 14:49:59 -0400216 end_page_writeback(pages[i]);
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300217 put_page(pages[i]);
Chris Masonc8b97812008-10-29 14:49:59 -0400218 }
219 nr_pages -= ret;
220 index += ret;
221 }
222 /* the inode may be gone now */
Chris Masonc8b97812008-10-29 14:49:59 -0400223}
224
225/*
226 * do the cleanup once all the compressed pages hit the disk.
227 * This will clear writeback on the file pages and free the compressed
228 * pages.
229 *
230 * This also calls the writeback end hooks for the file pages so that
231 * metadata and checksums can be updated in the file.
232 */
Christoph Hellwig4246a0b2015-07-20 15:29:37 +0200233static void end_compressed_bio_write(struct bio *bio)
Chris Masonc8b97812008-10-29 14:49:59 -0400234{
235 struct extent_io_tree *tree;
236 struct compressed_bio *cb = bio->bi_private;
237 struct inode *inode;
238 struct page *page;
239 unsigned long index;
240
Christoph Hellwig4e4cbee2017-06-03 09:38:06 +0200241 if (bio->bi_status)
Chris Masonc8b97812008-10-29 14:49:59 -0400242 cb->errors = 1;
243
244 /* if there are more bios still pending for this compressed
245 * extent, just exit
246 */
Elena Reshetovaa50299a2017-03-03 10:55:20 +0200247 if (!refcount_dec_and_test(&cb->pending_bios))
Chris Masonc8b97812008-10-29 14:49:59 -0400248 goto out;
249
250 /* ok, we're the last bio for this extent, step one is to
251 * call back into the FS and do all the end_io operations
252 */
253 inode = cb->inode;
254 tree = &BTRFS_I(inode)->io_tree;
Chris Mason70b99e62008-10-31 12:46:39 -0400255 cb->compressed_pages[0]->mapping = cb->inode->i_mapping;
Chris Masonc8b97812008-10-29 14:49:59 -0400256 tree->ops->writepage_end_io_hook(cb->compressed_pages[0],
257 cb->start,
258 cb->start + cb->len - 1,
Filipe Manana7bdcefc2014-10-07 01:48:26 +0100259 NULL,
Anand Jain2dbe0c72017-10-14 08:35:56 +0800260 bio->bi_status ?
261 BLK_STS_OK : BLK_STS_NOTSUPP);
Chris Mason70b99e62008-10-31 12:46:39 -0400262 cb->compressed_pages[0]->mapping = NULL;
Chris Masonc8b97812008-10-29 14:49:59 -0400263
Filipe Manana7bdcefc2014-10-07 01:48:26 +0100264 end_compressed_writeback(inode, cb);
Chris Masonc8b97812008-10-29 14:49:59 -0400265 /* note, our inode could be gone now */
266
267 /*
268 * release the compressed pages, these came from alloc_page and
269 * are not attached to the inode at all
270 */
271 index = 0;
272 for (index = 0; index < cb->nr_pages; index++) {
273 page = cb->compressed_pages[index];
274 page->mapping = NULL;
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300275 put_page(page);
Chris Masonc8b97812008-10-29 14:49:59 -0400276 }
277
278 /* finally free the cb struct */
279 kfree(cb->compressed_pages);
280 kfree(cb);
281out:
282 bio_put(bio);
283}
284
285/*
286 * worker function to build and submit bios for previously compressed pages.
287 * The corresponding pages in the inode should be marked for writeback
288 * and the compressed pages should have a reference on them for dropping
289 * when the IO is complete.
290 *
291 * This also checksums the file bytes and gets things ready for
292 * the end io hooks.
293 */
Christoph Hellwig4e4cbee2017-06-03 09:38:06 +0200294blk_status_t btrfs_submit_compressed_write(struct inode *inode, u64 start,
Chris Masonc8b97812008-10-29 14:49:59 -0400295 unsigned long len, u64 disk_start,
296 unsigned long compressed_len,
297 struct page **compressed_pages,
298 unsigned long nr_pages)
299{
Jeff Mahoney0b246af2016-06-22 18:54:23 -0400300 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
Chris Masonc8b97812008-10-29 14:49:59 -0400301 struct bio *bio = NULL;
Chris Masonc8b97812008-10-29 14:49:59 -0400302 struct compressed_bio *cb;
303 unsigned long bytes_left;
304 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
David Sterba306e16c2011-04-19 14:29:38 +0200305 int pg_index = 0;
Chris Masonc8b97812008-10-29 14:49:59 -0400306 struct page *page;
307 u64 first_byte = disk_start;
308 struct block_device *bdev;
Christoph Hellwig4e4cbee2017-06-03 09:38:06 +0200309 blk_status_t ret;
Li Zefane55179b2011-07-14 03:16:47 +0000310 int skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
Chris Masonc8b97812008-10-29 14:49:59 -0400311
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300312 WARN_ON(start & ((u64)PAGE_SIZE - 1));
Jeff Mahoney2ff7e612016-06-22 18:54:24 -0400313 cb = kmalloc(compressed_bio_size(fs_info, compressed_len), GFP_NOFS);
Yoshinori Sanodac97e52011-02-15 12:01:42 +0000314 if (!cb)
Christoph Hellwig4e4cbee2017-06-03 09:38:06 +0200315 return BLK_STS_RESOURCE;
Elena Reshetovaa50299a2017-03-03 10:55:20 +0200316 refcount_set(&cb->pending_bios, 0);
Chris Masonc8b97812008-10-29 14:49:59 -0400317 cb->errors = 0;
318 cb->inode = inode;
319 cb->start = start;
320 cb->len = len;
Chris Masond20f7042008-12-08 16:58:54 -0500321 cb->mirror_num = 0;
Chris Masonc8b97812008-10-29 14:49:59 -0400322 cb->compressed_pages = compressed_pages;
323 cb->compressed_len = compressed_len;
324 cb->orig_bio = NULL;
325 cb->nr_pages = nr_pages;
326
Jeff Mahoney0b246af2016-06-22 18:54:23 -0400327 bdev = fs_info->fs_devices->latest_bdev;
Chris Masonc8b97812008-10-29 14:49:59 -0400328
David Sterbac821e7f32017-06-02 18:35:36 +0200329 bio = btrfs_bio_alloc(bdev, first_byte);
Mike Christie37226b22016-06-05 14:31:52 -0500330 bio_set_op_attrs(bio, REQ_OP_WRITE, 0);
Chris Masonc8b97812008-10-29 14:49:59 -0400331 bio->bi_private = cb;
332 bio->bi_end_io = end_compressed_bio_write;
Elena Reshetovaa50299a2017-03-03 10:55:20 +0200333 refcount_set(&cb->pending_bios, 1);
Chris Masonc8b97812008-10-29 14:49:59 -0400334
335 /* create and submit bios for the compressed pages */
336 bytes_left = compressed_len;
David Sterba306e16c2011-04-19 14:29:38 +0200337 for (pg_index = 0; pg_index < cb->nr_pages; pg_index++) {
Christoph Hellwig4e4cbee2017-06-03 09:38:06 +0200338 int submit = 0;
339
David Sterba306e16c2011-04-19 14:29:38 +0200340 page = compressed_pages[pg_index];
Chris Masonc8b97812008-10-29 14:49:59 -0400341 page->mapping = inode->i_mapping;
Kent Overstreet4f024f32013-10-11 15:44:27 -0700342 if (bio->bi_iter.bi_size)
Christoph Hellwig4e4cbee2017-06-03 09:38:06 +0200343 submit = io_tree->ops->merge_bio_hook(page, 0,
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300344 PAGE_SIZE,
Chris Masonc8b97812008-10-29 14:49:59 -0400345 bio, 0);
Chris Masonc8b97812008-10-29 14:49:59 -0400346
Chris Mason70b99e62008-10-31 12:46:39 -0400347 page->mapping = NULL;
Christoph Hellwig4e4cbee2017-06-03 09:38:06 +0200348 if (submit || bio_add_page(bio, page, PAGE_SIZE, 0) <
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300349 PAGE_SIZE) {
Chris Masonc8b97812008-10-29 14:49:59 -0400350 bio_get(bio);
351
Chris Masonaf09abf2008-11-07 12:35:44 -0500352 /*
353 * inc the count before we submit the bio so
354 * we know the end IO handler won't happen before
355 * we inc the count. Otherwise, the cb might get
356 * freed before we're done setting it up
357 */
Elena Reshetovaa50299a2017-03-03 10:55:20 +0200358 refcount_inc(&cb->pending_bios);
Jeff Mahoney0b246af2016-06-22 18:54:23 -0400359 ret = btrfs_bio_wq_end_io(fs_info, bio,
360 BTRFS_WQ_ENDIO_DATA);
Jeff Mahoney79787ea2012-03-12 16:03:00 +0100361 BUG_ON(ret); /* -ENOMEM */
Chris Masonc8b97812008-10-29 14:49:59 -0400362
Li Zefane55179b2011-07-14 03:16:47 +0000363 if (!skip_sum) {
Jeff Mahoney2ff7e612016-06-22 18:54:24 -0400364 ret = btrfs_csum_one_bio(inode, bio, start, 1);
Jeff Mahoney79787ea2012-03-12 16:03:00 +0100365 BUG_ON(ret); /* -ENOMEM */
Li Zefane55179b2011-07-14 03:16:47 +0000366 }
Chris Masond20f7042008-12-08 16:58:54 -0500367
Jeff Mahoney2ff7e612016-06-22 18:54:24 -0400368 ret = btrfs_map_bio(fs_info, bio, 0, 1);
Liu Bof5daf2c2016-06-22 18:32:06 -0700369 if (ret) {
Christoph Hellwig4e4cbee2017-06-03 09:38:06 +0200370 bio->bi_status = ret;
Liu Bof5daf2c2016-06-22 18:32:06 -0700371 bio_endio(bio);
372 }
Chris Masonc8b97812008-10-29 14:49:59 -0400373
374 bio_put(bio);
375
David Sterbac821e7f32017-06-02 18:35:36 +0200376 bio = btrfs_bio_alloc(bdev, first_byte);
Mike Christie37226b22016-06-05 14:31:52 -0500377 bio_set_op_attrs(bio, REQ_OP_WRITE, 0);
Chris Masonc8b97812008-10-29 14:49:59 -0400378 bio->bi_private = cb;
379 bio->bi_end_io = end_compressed_bio_write;
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300380 bio_add_page(bio, page, PAGE_SIZE, 0);
Chris Masonc8b97812008-10-29 14:49:59 -0400381 }
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300382 if (bytes_left < PAGE_SIZE) {
Jeff Mahoney0b246af2016-06-22 18:54:23 -0400383 btrfs_info(fs_info,
Frank Holtonefe120a2013-12-20 11:37:06 -0500384 "bytes left %lu compress len %lu nr %lu",
Chris Masoncfbc2462008-10-30 13:22:14 -0400385 bytes_left, cb->compressed_len, cb->nr_pages);
386 }
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300387 bytes_left -= PAGE_SIZE;
388 first_byte += PAGE_SIZE;
Chris Mason771ed682008-11-06 22:02:51 -0500389 cond_resched();
Chris Masonc8b97812008-10-29 14:49:59 -0400390 }
391 bio_get(bio);
392
Jeff Mahoney0b246af2016-06-22 18:54:23 -0400393 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DATA);
Jeff Mahoney79787ea2012-03-12 16:03:00 +0100394 BUG_ON(ret); /* -ENOMEM */
Chris Masonc8b97812008-10-29 14:49:59 -0400395
Li Zefane55179b2011-07-14 03:16:47 +0000396 if (!skip_sum) {
Jeff Mahoney2ff7e612016-06-22 18:54:24 -0400397 ret = btrfs_csum_one_bio(inode, bio, start, 1);
Jeff Mahoney79787ea2012-03-12 16:03:00 +0100398 BUG_ON(ret); /* -ENOMEM */
Li Zefane55179b2011-07-14 03:16:47 +0000399 }
Chris Masond20f7042008-12-08 16:58:54 -0500400
Jeff Mahoney2ff7e612016-06-22 18:54:24 -0400401 ret = btrfs_map_bio(fs_info, bio, 0, 1);
Liu Bof5daf2c2016-06-22 18:32:06 -0700402 if (ret) {
Christoph Hellwig4e4cbee2017-06-03 09:38:06 +0200403 bio->bi_status = ret;
Liu Bof5daf2c2016-06-22 18:32:06 -0700404 bio_endio(bio);
405 }
Chris Masonc8b97812008-10-29 14:49:59 -0400406
407 bio_put(bio);
408 return 0;
409}
410
Christoph Hellwig2a4d0c92016-11-25 09:07:51 +0100411static u64 bio_end_offset(struct bio *bio)
412{
413 struct bio_vec *last = &bio->bi_io_vec[bio->bi_vcnt - 1];
414
415 return page_offset(last->bv_page) + last->bv_len + last->bv_offset;
416}
417
Chris Mason771ed682008-11-06 22:02:51 -0500418static noinline int add_ra_bio_pages(struct inode *inode,
419 u64 compressed_end,
420 struct compressed_bio *cb)
421{
422 unsigned long end_index;
David Sterba306e16c2011-04-19 14:29:38 +0200423 unsigned long pg_index;
Chris Mason771ed682008-11-06 22:02:51 -0500424 u64 last_offset;
425 u64 isize = i_size_read(inode);
426 int ret;
427 struct page *page;
428 unsigned long nr_pages = 0;
429 struct extent_map *em;
430 struct address_space *mapping = inode->i_mapping;
Chris Mason771ed682008-11-06 22:02:51 -0500431 struct extent_map_tree *em_tree;
432 struct extent_io_tree *tree;
433 u64 end;
434 int misses = 0;
435
Christoph Hellwig2a4d0c92016-11-25 09:07:51 +0100436 last_offset = bio_end_offset(cb->orig_bio);
Chris Mason771ed682008-11-06 22:02:51 -0500437 em_tree = &BTRFS_I(inode)->extent_tree;
438 tree = &BTRFS_I(inode)->io_tree;
439
440 if (isize == 0)
441 return 0;
442
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300443 end_index = (i_size_read(inode) - 1) >> PAGE_SHIFT;
Chris Mason771ed682008-11-06 22:02:51 -0500444
Chris Masond3977122009-01-05 21:25:51 -0500445 while (last_offset < compressed_end) {
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300446 pg_index = last_offset >> PAGE_SHIFT;
Chris Mason771ed682008-11-06 22:02:51 -0500447
David Sterba306e16c2011-04-19 14:29:38 +0200448 if (pg_index > end_index)
Chris Mason771ed682008-11-06 22:02:51 -0500449 break;
450
451 rcu_read_lock();
David Sterba306e16c2011-04-19 14:29:38 +0200452 page = radix_tree_lookup(&mapping->page_tree, pg_index);
Chris Mason771ed682008-11-06 22:02:51 -0500453 rcu_read_unlock();
Johannes Weiner0cd61442014-04-03 14:47:46 -0700454 if (page && !radix_tree_exceptional_entry(page)) {
Chris Mason771ed682008-11-06 22:02:51 -0500455 misses++;
456 if (misses > 4)
457 break;
458 goto next;
459 }
460
Michal Hockoc62d2552015-11-06 16:28:49 -0800461 page = __page_cache_alloc(mapping_gfp_constraint(mapping,
462 ~__GFP_FS));
Chris Mason771ed682008-11-06 22:02:51 -0500463 if (!page)
464 break;
465
Michal Hockoc62d2552015-11-06 16:28:49 -0800466 if (add_to_page_cache_lru(page, mapping, pg_index, GFP_NOFS)) {
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300467 put_page(page);
Chris Mason771ed682008-11-06 22:02:51 -0500468 goto next;
469 }
470
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300471 end = last_offset + PAGE_SIZE - 1;
Chris Mason771ed682008-11-06 22:02:51 -0500472 /*
473 * at this point, we have a locked page in the page cache
474 * for these bytes in the file. But, we have to make
475 * sure they map to this compressed extent on disk.
476 */
477 set_page_extent_mapped(page);
Jeff Mahoneyd0082372012-03-01 14:57:19 +0100478 lock_extent(tree, last_offset, end);
Chris Mason890871b2009-09-02 16:24:52 -0400479 read_lock(&em_tree->lock);
Chris Mason771ed682008-11-06 22:02:51 -0500480 em = lookup_extent_mapping(em_tree, last_offset,
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300481 PAGE_SIZE);
Chris Mason890871b2009-09-02 16:24:52 -0400482 read_unlock(&em_tree->lock);
Chris Mason771ed682008-11-06 22:02:51 -0500483
484 if (!em || last_offset < em->start ||
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300485 (last_offset + PAGE_SIZE > extent_map_end(em)) ||
Kent Overstreet4f024f32013-10-11 15:44:27 -0700486 (em->block_start >> 9) != cb->orig_bio->bi_iter.bi_sector) {
Chris Mason771ed682008-11-06 22:02:51 -0500487 free_extent_map(em);
Jeff Mahoneyd0082372012-03-01 14:57:19 +0100488 unlock_extent(tree, last_offset, end);
Chris Mason771ed682008-11-06 22:02:51 -0500489 unlock_page(page);
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300490 put_page(page);
Chris Mason771ed682008-11-06 22:02:51 -0500491 break;
492 }
493 free_extent_map(em);
494
495 if (page->index == end_index) {
496 char *userpage;
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300497 size_t zero_offset = isize & (PAGE_SIZE - 1);
Chris Mason771ed682008-11-06 22:02:51 -0500498
499 if (zero_offset) {
500 int zeros;
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300501 zeros = PAGE_SIZE - zero_offset;
Cong Wang7ac687d2011-11-25 23:14:28 +0800502 userpage = kmap_atomic(page);
Chris Mason771ed682008-11-06 22:02:51 -0500503 memset(userpage + zero_offset, 0, zeros);
504 flush_dcache_page(page);
Cong Wang7ac687d2011-11-25 23:14:28 +0800505 kunmap_atomic(userpage);
Chris Mason771ed682008-11-06 22:02:51 -0500506 }
507 }
508
509 ret = bio_add_page(cb->orig_bio, page,
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300510 PAGE_SIZE, 0);
Chris Mason771ed682008-11-06 22:02:51 -0500511
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300512 if (ret == PAGE_SIZE) {
Chris Mason771ed682008-11-06 22:02:51 -0500513 nr_pages++;
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300514 put_page(page);
Chris Mason771ed682008-11-06 22:02:51 -0500515 } else {
Jeff Mahoneyd0082372012-03-01 14:57:19 +0100516 unlock_extent(tree, last_offset, end);
Chris Mason771ed682008-11-06 22:02:51 -0500517 unlock_page(page);
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300518 put_page(page);
Chris Mason771ed682008-11-06 22:02:51 -0500519 break;
520 }
521next:
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300522 last_offset += PAGE_SIZE;
Chris Mason771ed682008-11-06 22:02:51 -0500523 }
Chris Mason771ed682008-11-06 22:02:51 -0500524 return 0;
525}
526
Chris Masonc8b97812008-10-29 14:49:59 -0400527/*
528 * for a compressed read, the bio we get passed has all the inode pages
529 * in it. We don't actually do IO on those pages but allocate new ones
530 * to hold the compressed pages on disk.
531 *
Kent Overstreet4f024f32013-10-11 15:44:27 -0700532 * bio->bi_iter.bi_sector points to the compressed extent on disk
Chris Masonc8b97812008-10-29 14:49:59 -0400533 * bio->bi_io_vec points to all of the inode pages
Chris Masonc8b97812008-10-29 14:49:59 -0400534 *
535 * After the compressed pages are read, we copy the bytes into the
536 * bio we were passed and then call the bio end_io calls
537 */
Christoph Hellwig4e4cbee2017-06-03 09:38:06 +0200538blk_status_t btrfs_submit_compressed_read(struct inode *inode, struct bio *bio,
Chris Masonc8b97812008-10-29 14:49:59 -0400539 int mirror_num, unsigned long bio_flags)
540{
Jeff Mahoney0b246af2016-06-22 18:54:23 -0400541 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
Chris Masonc8b97812008-10-29 14:49:59 -0400542 struct extent_io_tree *tree;
543 struct extent_map_tree *em_tree;
544 struct compressed_bio *cb;
Chris Masonc8b97812008-10-29 14:49:59 -0400545 unsigned long compressed_len;
546 unsigned long nr_pages;
David Sterba306e16c2011-04-19 14:29:38 +0200547 unsigned long pg_index;
Chris Masonc8b97812008-10-29 14:49:59 -0400548 struct page *page;
549 struct block_device *bdev;
550 struct bio *comp_bio;
Kent Overstreet4f024f32013-10-11 15:44:27 -0700551 u64 cur_disk_byte = (u64)bio->bi_iter.bi_sector << 9;
Chris Masone04ca622008-11-10 11:44:58 -0500552 u64 em_len;
553 u64 em_start;
Chris Masonc8b97812008-10-29 14:49:59 -0400554 struct extent_map *em;
Christoph Hellwig4e4cbee2017-06-03 09:38:06 +0200555 blk_status_t ret = BLK_STS_RESOURCE;
Josef Bacik15e3004a2012-10-05 13:39:50 -0400556 int faili = 0;
Chris Masond20f7042008-12-08 16:58:54 -0500557 u32 *sums;
Chris Masonc8b97812008-10-29 14:49:59 -0400558
559 tree = &BTRFS_I(inode)->io_tree;
560 em_tree = &BTRFS_I(inode)->extent_tree;
561
562 /* we need the actual starting offset of this extent in the file */
Chris Mason890871b2009-09-02 16:24:52 -0400563 read_lock(&em_tree->lock);
Chris Masonc8b97812008-10-29 14:49:59 -0400564 em = lookup_extent_mapping(em_tree,
565 page_offset(bio->bi_io_vec->bv_page),
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300566 PAGE_SIZE);
Chris Mason890871b2009-09-02 16:24:52 -0400567 read_unlock(&em_tree->lock);
Tsutomu Itoh285190d2012-02-16 16:23:58 +0900568 if (!em)
Christoph Hellwig4e4cbee2017-06-03 09:38:06 +0200569 return BLK_STS_IOERR;
Chris Masonc8b97812008-10-29 14:49:59 -0400570
Chris Masond20f7042008-12-08 16:58:54 -0500571 compressed_len = em->block_len;
Jeff Mahoney2ff7e612016-06-22 18:54:24 -0400572 cb = kmalloc(compressed_bio_size(fs_info, compressed_len), GFP_NOFS);
liubo6b82ce82011-01-26 06:21:39 +0000573 if (!cb)
574 goto out;
575
Elena Reshetovaa50299a2017-03-03 10:55:20 +0200576 refcount_set(&cb->pending_bios, 0);
Chris Masonc8b97812008-10-29 14:49:59 -0400577 cb->errors = 0;
578 cb->inode = inode;
Chris Masond20f7042008-12-08 16:58:54 -0500579 cb->mirror_num = mirror_num;
580 sums = &cb->sums;
Chris Masonc8b97812008-10-29 14:49:59 -0400581
Yan Zhengff5b7ee2008-11-10 07:34:43 -0500582 cb->start = em->orig_start;
Chris Masone04ca622008-11-10 11:44:58 -0500583 em_len = em->len;
584 em_start = em->start;
Chris Masond20f7042008-12-08 16:58:54 -0500585
Chris Masonc8b97812008-10-29 14:49:59 -0400586 free_extent_map(em);
Chris Masone04ca622008-11-10 11:44:58 -0500587 em = NULL;
Chris Masonc8b97812008-10-29 14:49:59 -0400588
Christoph Hellwig81381052016-11-25 09:07:50 +0100589 cb->len = bio->bi_iter.bi_size;
Chris Masonc8b97812008-10-29 14:49:59 -0400590 cb->compressed_len = compressed_len;
Li Zefan261507a02010-12-17 14:21:50 +0800591 cb->compress_type = extent_compress_type(bio_flags);
Chris Masonc8b97812008-10-29 14:49:59 -0400592 cb->orig_bio = bio;
593
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300594 nr_pages = DIV_ROUND_UP(compressed_len, PAGE_SIZE);
David Sterba31e818f2015-02-20 18:00:26 +0100595 cb->compressed_pages = kcalloc(nr_pages, sizeof(struct page *),
Chris Masonc8b97812008-10-29 14:49:59 -0400596 GFP_NOFS);
liubo6b82ce82011-01-26 06:21:39 +0000597 if (!cb->compressed_pages)
598 goto fail1;
599
Jeff Mahoney0b246af2016-06-22 18:54:23 -0400600 bdev = fs_info->fs_devices->latest_bdev;
Chris Masonc8b97812008-10-29 14:49:59 -0400601
David Sterba306e16c2011-04-19 14:29:38 +0200602 for (pg_index = 0; pg_index < nr_pages; pg_index++) {
603 cb->compressed_pages[pg_index] = alloc_page(GFP_NOFS |
Chris Masonc8b97812008-10-29 14:49:59 -0400604 __GFP_HIGHMEM);
Josef Bacik15e3004a2012-10-05 13:39:50 -0400605 if (!cb->compressed_pages[pg_index]) {
606 faili = pg_index - 1;
Dan Carpenter0e9350d2017-06-19 13:55:37 +0300607 ret = BLK_STS_RESOURCE;
liubo6b82ce82011-01-26 06:21:39 +0000608 goto fail2;
Josef Bacik15e3004a2012-10-05 13:39:50 -0400609 }
Chris Masonc8b97812008-10-29 14:49:59 -0400610 }
Josef Bacik15e3004a2012-10-05 13:39:50 -0400611 faili = nr_pages - 1;
Chris Masonc8b97812008-10-29 14:49:59 -0400612 cb->nr_pages = nr_pages;
613
Filipe Manana7f042a82016-01-27 19:17:20 +0000614 add_ra_bio_pages(inode, em_start + em_len, cb);
Chris Mason771ed682008-11-06 22:02:51 -0500615
Chris Mason771ed682008-11-06 22:02:51 -0500616 /* include any pages we added in add_ra-bio_pages */
Christoph Hellwig81381052016-11-25 09:07:50 +0100617 cb->len = bio->bi_iter.bi_size;
Chris Mason771ed682008-11-06 22:02:51 -0500618
David Sterbac821e7f32017-06-02 18:35:36 +0200619 comp_bio = btrfs_bio_alloc(bdev, cur_disk_byte);
Mike Christie37226b22016-06-05 14:31:52 -0500620 bio_set_op_attrs (comp_bio, REQ_OP_READ, 0);
Chris Masonc8b97812008-10-29 14:49:59 -0400621 comp_bio->bi_private = cb;
622 comp_bio->bi_end_io = end_compressed_bio_read;
Elena Reshetovaa50299a2017-03-03 10:55:20 +0200623 refcount_set(&cb->pending_bios, 1);
Chris Masonc8b97812008-10-29 14:49:59 -0400624
David Sterba306e16c2011-04-19 14:29:38 +0200625 for (pg_index = 0; pg_index < nr_pages; pg_index++) {
Christoph Hellwig4e4cbee2017-06-03 09:38:06 +0200626 int submit = 0;
627
David Sterba306e16c2011-04-19 14:29:38 +0200628 page = cb->compressed_pages[pg_index];
Chris Masonc8b97812008-10-29 14:49:59 -0400629 page->mapping = inode->i_mapping;
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300630 page->index = em_start >> PAGE_SHIFT;
Chris Masond20f7042008-12-08 16:58:54 -0500631
Kent Overstreet4f024f32013-10-11 15:44:27 -0700632 if (comp_bio->bi_iter.bi_size)
Christoph Hellwig4e4cbee2017-06-03 09:38:06 +0200633 submit = tree->ops->merge_bio_hook(page, 0,
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300634 PAGE_SIZE,
Chris Masonc8b97812008-10-29 14:49:59 -0400635 comp_bio, 0);
Chris Masonc8b97812008-10-29 14:49:59 -0400636
Chris Mason70b99e62008-10-31 12:46:39 -0400637 page->mapping = NULL;
Christoph Hellwig4e4cbee2017-06-03 09:38:06 +0200638 if (submit || bio_add_page(comp_bio, page, PAGE_SIZE, 0) <
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300639 PAGE_SIZE) {
Chris Masonc8b97812008-10-29 14:49:59 -0400640 bio_get(comp_bio);
641
Jeff Mahoney0b246af2016-06-22 18:54:23 -0400642 ret = btrfs_bio_wq_end_io(fs_info, comp_bio,
643 BTRFS_WQ_ENDIO_DATA);
Jeff Mahoney79787ea2012-03-12 16:03:00 +0100644 BUG_ON(ret); /* -ENOMEM */
Chris Masonc8b97812008-10-29 14:49:59 -0400645
Chris Masonaf09abf2008-11-07 12:35:44 -0500646 /*
647 * inc the count before we submit the bio so
648 * we know the end IO handler won't happen before
649 * we inc the count. Otherwise, the cb might get
650 * freed before we're done setting it up
651 */
Elena Reshetovaa50299a2017-03-03 10:55:20 +0200652 refcount_inc(&cb->pending_bios);
Chris Masonaf09abf2008-11-07 12:35:44 -0500653
Christoph Hellwig6cbff002009-04-17 10:37:41 +0200654 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
Jeff Mahoney2ff7e612016-06-22 18:54:24 -0400655 ret = btrfs_lookup_bio_sums(inode, comp_bio,
656 sums);
Jeff Mahoney79787ea2012-03-12 16:03:00 +0100657 BUG_ON(ret); /* -ENOMEM */
Chris Masond20f7042008-12-08 16:58:54 -0500658 }
David Sterbaed6078f2014-06-05 01:59:57 +0200659 sums += DIV_ROUND_UP(comp_bio->bi_iter.bi_size,
Jeff Mahoney0b246af2016-06-22 18:54:23 -0400660 fs_info->sectorsize);
Chris Masond20f7042008-12-08 16:58:54 -0500661
Jeff Mahoney2ff7e612016-06-22 18:54:24 -0400662 ret = btrfs_map_bio(fs_info, comp_bio, mirror_num, 0);
Christoph Hellwig4246a0b2015-07-20 15:29:37 +0200663 if (ret) {
Christoph Hellwig4e4cbee2017-06-03 09:38:06 +0200664 comp_bio->bi_status = ret;
Christoph Hellwig4246a0b2015-07-20 15:29:37 +0200665 bio_endio(comp_bio);
666 }
Chris Masonc8b97812008-10-29 14:49:59 -0400667
668 bio_put(comp_bio);
669
David Sterbac821e7f32017-06-02 18:35:36 +0200670 comp_bio = btrfs_bio_alloc(bdev, cur_disk_byte);
Mike Christie37226b22016-06-05 14:31:52 -0500671 bio_set_op_attrs(comp_bio, REQ_OP_READ, 0);
Chris Mason771ed682008-11-06 22:02:51 -0500672 comp_bio->bi_private = cb;
673 comp_bio->bi_end_io = end_compressed_bio_read;
674
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300675 bio_add_page(comp_bio, page, PAGE_SIZE, 0);
Chris Masonc8b97812008-10-29 14:49:59 -0400676 }
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300677 cur_disk_byte += PAGE_SIZE;
Chris Masonc8b97812008-10-29 14:49:59 -0400678 }
679 bio_get(comp_bio);
680
Jeff Mahoney0b246af2016-06-22 18:54:23 -0400681 ret = btrfs_bio_wq_end_io(fs_info, comp_bio, BTRFS_WQ_ENDIO_DATA);
Jeff Mahoney79787ea2012-03-12 16:03:00 +0100682 BUG_ON(ret); /* -ENOMEM */
Chris Masonc8b97812008-10-29 14:49:59 -0400683
Tsutomu Itohc2db1072011-03-01 06:48:31 +0000684 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
Jeff Mahoney2ff7e612016-06-22 18:54:24 -0400685 ret = btrfs_lookup_bio_sums(inode, comp_bio, sums);
Jeff Mahoney79787ea2012-03-12 16:03:00 +0100686 BUG_ON(ret); /* -ENOMEM */
Tsutomu Itohc2db1072011-03-01 06:48:31 +0000687 }
Chris Masond20f7042008-12-08 16:58:54 -0500688
Jeff Mahoney2ff7e612016-06-22 18:54:24 -0400689 ret = btrfs_map_bio(fs_info, comp_bio, mirror_num, 0);
Christoph Hellwig4246a0b2015-07-20 15:29:37 +0200690 if (ret) {
Christoph Hellwig4e4cbee2017-06-03 09:38:06 +0200691 comp_bio->bi_status = ret;
Christoph Hellwig4246a0b2015-07-20 15:29:37 +0200692 bio_endio(comp_bio);
693 }
Chris Masonc8b97812008-10-29 14:49:59 -0400694
695 bio_put(comp_bio);
696 return 0;
liubo6b82ce82011-01-26 06:21:39 +0000697
698fail2:
Josef Bacik15e3004a2012-10-05 13:39:50 -0400699 while (faili >= 0) {
700 __free_page(cb->compressed_pages[faili]);
701 faili--;
702 }
liubo6b82ce82011-01-26 06:21:39 +0000703
704 kfree(cb->compressed_pages);
705fail1:
706 kfree(cb);
707out:
708 free_extent_map(em);
709 return ret;
Chris Masonc8b97812008-10-29 14:49:59 -0400710}
Li Zefan261507a02010-12-17 14:21:50 +0800711
Timofey Titovets17b5a6c2017-09-28 17:33:37 +0300712/*
713 * Heuristic uses systematic sampling to collect data from the input data
714 * range, the logic can be tuned by the following constants:
715 *
716 * @SAMPLING_READ_SIZE - how many bytes will be copied from for each sample
717 * @SAMPLING_INTERVAL - range from which the sampled data can be collected
718 */
719#define SAMPLING_READ_SIZE (16)
720#define SAMPLING_INTERVAL (256)
721
722/*
723 * For statistical analysis of the input data we consider bytes that form a
724 * Galois Field of 256 objects. Each object has an attribute count, ie. how
725 * many times the object appeared in the sample.
726 */
727#define BUCKET_SIZE (256)
728
729/*
730 * The size of the sample is based on a statistical sampling rule of thumb.
731 * The common way is to perform sampling tests as long as the number of
732 * elements in each cell is at least 5.
733 *
734 * Instead of 5, we choose 32 to obtain more accurate results.
735 * If the data contain the maximum number of symbols, which is 256, we obtain a
736 * sample size bound by 8192.
737 *
738 * For a sample of at most 8KB of data per data range: 16 consecutive bytes
739 * from up to 512 locations.
740 */
741#define MAX_SAMPLE_SIZE (BTRFS_MAX_UNCOMPRESSED * \
742 SAMPLING_READ_SIZE / SAMPLING_INTERVAL)
743
744struct bucket_item {
745 u32 count;
746};
Timofey Titovets4e439a02017-09-28 17:33:36 +0300747
748struct heuristic_ws {
Timofey Titovets17b5a6c2017-09-28 17:33:37 +0300749 /* Partial copy of input data */
750 u8 *sample;
Timofey Titovetsa440d482017-09-28 17:33:38 +0300751 u32 sample_size;
Timofey Titovets17b5a6c2017-09-28 17:33:37 +0300752 /* Buckets store counters for each byte value */
753 struct bucket_item *bucket;
Timofey Titovets4e439a02017-09-28 17:33:36 +0300754 struct list_head list;
755};
756
757static void free_heuristic_ws(struct list_head *ws)
758{
759 struct heuristic_ws *workspace;
760
761 workspace = list_entry(ws, struct heuristic_ws, list);
762
Timofey Titovets17b5a6c2017-09-28 17:33:37 +0300763 kvfree(workspace->sample);
764 kfree(workspace->bucket);
Timofey Titovets4e439a02017-09-28 17:33:36 +0300765 kfree(workspace);
766}
767
768static struct list_head *alloc_heuristic_ws(void)
769{
770 struct heuristic_ws *ws;
771
772 ws = kzalloc(sizeof(*ws), GFP_KERNEL);
773 if (!ws)
774 return ERR_PTR(-ENOMEM);
775
Timofey Titovets17b5a6c2017-09-28 17:33:37 +0300776 ws->sample = kvmalloc(MAX_SAMPLE_SIZE, GFP_KERNEL);
777 if (!ws->sample)
778 goto fail;
Timofey Titovets4e439a02017-09-28 17:33:36 +0300779
Timofey Titovets17b5a6c2017-09-28 17:33:37 +0300780 ws->bucket = kcalloc(BUCKET_SIZE, sizeof(*ws->bucket), GFP_KERNEL);
781 if (!ws->bucket)
782 goto fail;
783
784 INIT_LIST_HEAD(&ws->list);
Timofey Titovets4e439a02017-09-28 17:33:36 +0300785 return &ws->list;
Timofey Titovets17b5a6c2017-09-28 17:33:37 +0300786fail:
787 free_heuristic_ws(&ws->list);
788 return ERR_PTR(-ENOMEM);
Timofey Titovets4e439a02017-09-28 17:33:36 +0300789}
790
791struct workspaces_list {
Byongho Leed9187642015-10-14 14:05:24 +0900792 struct list_head idle_ws;
793 spinlock_t ws_lock;
David Sterba6ac10a62016-04-27 02:15:15 +0200794 /* Number of free workspaces */
795 int free_ws;
796 /* Total number of allocated workspaces */
797 atomic_t total_ws;
798 /* Waiters for a free workspace */
Byongho Leed9187642015-10-14 14:05:24 +0900799 wait_queue_head_t ws_wait;
Timofey Titovets4e439a02017-09-28 17:33:36 +0300800};
801
802static struct workspaces_list btrfs_comp_ws[BTRFS_COMPRESS_TYPES];
803
804static struct workspaces_list btrfs_heuristic_ws;
Li Zefan261507a02010-12-17 14:21:50 +0800805
David Sterbae8c9f182015-01-02 18:23:10 +0100806static const struct btrfs_compress_op * const btrfs_compress_op[] = {
Li Zefan261507a02010-12-17 14:21:50 +0800807 &btrfs_zlib_compress,
Li Zefana6fa6fa2010-10-25 15:12:26 +0800808 &btrfs_lzo_compress,
Nick Terrell5c1aab12017-08-09 19:39:02 -0700809 &btrfs_zstd_compress,
Li Zefan261507a02010-12-17 14:21:50 +0800810};
811
Jeff Mahoney143bede2012-03-01 14:56:26 +0100812void __init btrfs_init_compress(void)
Li Zefan261507a02010-12-17 14:21:50 +0800813{
Timofey Titovets4e439a02017-09-28 17:33:36 +0300814 struct list_head *workspace;
Li Zefan261507a02010-12-17 14:21:50 +0800815 int i;
816
Timofey Titovets4e439a02017-09-28 17:33:36 +0300817 INIT_LIST_HEAD(&btrfs_heuristic_ws.idle_ws);
818 spin_lock_init(&btrfs_heuristic_ws.ws_lock);
819 atomic_set(&btrfs_heuristic_ws.total_ws, 0);
820 init_waitqueue_head(&btrfs_heuristic_ws.ws_wait);
David Sterbaf77dd0d2016-04-27 02:55:15 +0200821
Timofey Titovets4e439a02017-09-28 17:33:36 +0300822 workspace = alloc_heuristic_ws();
823 if (IS_ERR(workspace)) {
824 pr_warn(
825 "BTRFS: cannot preallocate heuristic workspace, will try later\n");
826 } else {
827 atomic_set(&btrfs_heuristic_ws.total_ws, 1);
828 btrfs_heuristic_ws.free_ws = 1;
829 list_add(workspace, &btrfs_heuristic_ws.idle_ws);
830 }
831
832 for (i = 0; i < BTRFS_COMPRESS_TYPES; i++) {
Byongho Leed9187642015-10-14 14:05:24 +0900833 INIT_LIST_HEAD(&btrfs_comp_ws[i].idle_ws);
834 spin_lock_init(&btrfs_comp_ws[i].ws_lock);
David Sterba6ac10a62016-04-27 02:15:15 +0200835 atomic_set(&btrfs_comp_ws[i].total_ws, 0);
Byongho Leed9187642015-10-14 14:05:24 +0900836 init_waitqueue_head(&btrfs_comp_ws[i].ws_wait);
David Sterbaf77dd0d2016-04-27 02:55:15 +0200837
838 /*
839 * Preallocate one workspace for each compression type so
840 * we can guarantee forward progress in the worst case
841 */
842 workspace = btrfs_compress_op[i]->alloc_workspace();
843 if (IS_ERR(workspace)) {
Jeff Mahoney62e85572016-09-20 10:05:01 -0400844 pr_warn("BTRFS: cannot preallocate compression workspace, will try later\n");
David Sterbaf77dd0d2016-04-27 02:55:15 +0200845 } else {
846 atomic_set(&btrfs_comp_ws[i].total_ws, 1);
847 btrfs_comp_ws[i].free_ws = 1;
848 list_add(workspace, &btrfs_comp_ws[i].idle_ws);
849 }
Li Zefan261507a02010-12-17 14:21:50 +0800850 }
Li Zefan261507a02010-12-17 14:21:50 +0800851}
852
853/*
David Sterbae721e492016-04-27 02:41:17 +0200854 * This finds an available workspace or allocates a new one.
855 * If it's not possible to allocate a new one, waits until there's one.
856 * Preallocation makes a forward progress guarantees and we do not return
857 * errors.
Li Zefan261507a02010-12-17 14:21:50 +0800858 */
Timofey Titovets4e439a02017-09-28 17:33:36 +0300859static struct list_head *__find_workspace(int type, bool heuristic)
Li Zefan261507a02010-12-17 14:21:50 +0800860{
861 struct list_head *workspace;
862 int cpus = num_online_cpus();
863 int idx = type - 1;
David Sterbafe308532017-05-31 17:14:56 +0200864 unsigned nofs_flag;
Timofey Titovets4e439a02017-09-28 17:33:36 +0300865 struct list_head *idle_ws;
866 spinlock_t *ws_lock;
867 atomic_t *total_ws;
868 wait_queue_head_t *ws_wait;
869 int *free_ws;
Li Zefan261507a02010-12-17 14:21:50 +0800870
Timofey Titovets4e439a02017-09-28 17:33:36 +0300871 if (heuristic) {
872 idle_ws = &btrfs_heuristic_ws.idle_ws;
873 ws_lock = &btrfs_heuristic_ws.ws_lock;
874 total_ws = &btrfs_heuristic_ws.total_ws;
875 ws_wait = &btrfs_heuristic_ws.ws_wait;
876 free_ws = &btrfs_heuristic_ws.free_ws;
877 } else {
878 idle_ws = &btrfs_comp_ws[idx].idle_ws;
879 ws_lock = &btrfs_comp_ws[idx].ws_lock;
880 total_ws = &btrfs_comp_ws[idx].total_ws;
881 ws_wait = &btrfs_comp_ws[idx].ws_wait;
882 free_ws = &btrfs_comp_ws[idx].free_ws;
883 }
884
Li Zefan261507a02010-12-17 14:21:50 +0800885again:
Byongho Leed9187642015-10-14 14:05:24 +0900886 spin_lock(ws_lock);
887 if (!list_empty(idle_ws)) {
888 workspace = idle_ws->next;
Li Zefan261507a02010-12-17 14:21:50 +0800889 list_del(workspace);
David Sterba6ac10a62016-04-27 02:15:15 +0200890 (*free_ws)--;
Byongho Leed9187642015-10-14 14:05:24 +0900891 spin_unlock(ws_lock);
Li Zefan261507a02010-12-17 14:21:50 +0800892 return workspace;
893
894 }
David Sterba6ac10a62016-04-27 02:15:15 +0200895 if (atomic_read(total_ws) > cpus) {
Li Zefan261507a02010-12-17 14:21:50 +0800896 DEFINE_WAIT(wait);
897
Byongho Leed9187642015-10-14 14:05:24 +0900898 spin_unlock(ws_lock);
899 prepare_to_wait(ws_wait, &wait, TASK_UNINTERRUPTIBLE);
David Sterba6ac10a62016-04-27 02:15:15 +0200900 if (atomic_read(total_ws) > cpus && !*free_ws)
Li Zefan261507a02010-12-17 14:21:50 +0800901 schedule();
Byongho Leed9187642015-10-14 14:05:24 +0900902 finish_wait(ws_wait, &wait);
Li Zefan261507a02010-12-17 14:21:50 +0800903 goto again;
904 }
David Sterba6ac10a62016-04-27 02:15:15 +0200905 atomic_inc(total_ws);
Byongho Leed9187642015-10-14 14:05:24 +0900906 spin_unlock(ws_lock);
Li Zefan261507a02010-12-17 14:21:50 +0800907
David Sterbafe308532017-05-31 17:14:56 +0200908 /*
909 * Allocation helpers call vmalloc that can't use GFP_NOFS, so we have
910 * to turn it off here because we might get called from the restricted
911 * context of btrfs_compress_bio/btrfs_compress_pages
912 */
913 nofs_flag = memalloc_nofs_save();
Timofey Titovets4e439a02017-09-28 17:33:36 +0300914 if (heuristic)
915 workspace = alloc_heuristic_ws();
916 else
917 workspace = btrfs_compress_op[idx]->alloc_workspace();
David Sterbafe308532017-05-31 17:14:56 +0200918 memalloc_nofs_restore(nofs_flag);
919
Li Zefan261507a02010-12-17 14:21:50 +0800920 if (IS_ERR(workspace)) {
David Sterba6ac10a62016-04-27 02:15:15 +0200921 atomic_dec(total_ws);
Byongho Leed9187642015-10-14 14:05:24 +0900922 wake_up(ws_wait);
David Sterbae721e492016-04-27 02:41:17 +0200923
924 /*
925 * Do not return the error but go back to waiting. There's a
926 * workspace preallocated for each type and the compression
927 * time is bounded so we get to a workspace eventually. This
928 * makes our caller's life easier.
David Sterba523567162016-04-27 03:07:39 +0200929 *
930 * To prevent silent and low-probability deadlocks (when the
931 * initial preallocation fails), check if there are any
932 * workspaces at all.
David Sterbae721e492016-04-27 02:41:17 +0200933 */
David Sterba523567162016-04-27 03:07:39 +0200934 if (atomic_read(total_ws) == 0) {
935 static DEFINE_RATELIMIT_STATE(_rs,
936 /* once per minute */ 60 * HZ,
937 /* no burst */ 1);
938
939 if (__ratelimit(&_rs)) {
Jeff Mahoneyab8d0fc2016-09-20 10:05:02 -0400940 pr_warn("BTRFS: no compression workspaces, low memory, retrying\n");
David Sterba523567162016-04-27 03:07:39 +0200941 }
942 }
David Sterbae721e492016-04-27 02:41:17 +0200943 goto again;
Li Zefan261507a02010-12-17 14:21:50 +0800944 }
945 return workspace;
946}
947
Timofey Titovets4e439a02017-09-28 17:33:36 +0300948static struct list_head *find_workspace(int type)
949{
950 return __find_workspace(type, false);
951}
952
Li Zefan261507a02010-12-17 14:21:50 +0800953/*
954 * put a workspace struct back on the list or free it if we have enough
955 * idle ones sitting around
956 */
Timofey Titovets4e439a02017-09-28 17:33:36 +0300957static void __free_workspace(int type, struct list_head *workspace,
958 bool heuristic)
Li Zefan261507a02010-12-17 14:21:50 +0800959{
960 int idx = type - 1;
Timofey Titovets4e439a02017-09-28 17:33:36 +0300961 struct list_head *idle_ws;
962 spinlock_t *ws_lock;
963 atomic_t *total_ws;
964 wait_queue_head_t *ws_wait;
965 int *free_ws;
966
967 if (heuristic) {
968 idle_ws = &btrfs_heuristic_ws.idle_ws;
969 ws_lock = &btrfs_heuristic_ws.ws_lock;
970 total_ws = &btrfs_heuristic_ws.total_ws;
971 ws_wait = &btrfs_heuristic_ws.ws_wait;
972 free_ws = &btrfs_heuristic_ws.free_ws;
973 } else {
974 idle_ws = &btrfs_comp_ws[idx].idle_ws;
975 ws_lock = &btrfs_comp_ws[idx].ws_lock;
976 total_ws = &btrfs_comp_ws[idx].total_ws;
977 ws_wait = &btrfs_comp_ws[idx].ws_wait;
978 free_ws = &btrfs_comp_ws[idx].free_ws;
979 }
Li Zefan261507a02010-12-17 14:21:50 +0800980
Byongho Leed9187642015-10-14 14:05:24 +0900981 spin_lock(ws_lock);
Nick Terrell26b28dc2017-06-29 10:57:26 -0700982 if (*free_ws <= num_online_cpus()) {
Byongho Leed9187642015-10-14 14:05:24 +0900983 list_add(workspace, idle_ws);
David Sterba6ac10a62016-04-27 02:15:15 +0200984 (*free_ws)++;
Byongho Leed9187642015-10-14 14:05:24 +0900985 spin_unlock(ws_lock);
Li Zefan261507a02010-12-17 14:21:50 +0800986 goto wake;
987 }
Byongho Leed9187642015-10-14 14:05:24 +0900988 spin_unlock(ws_lock);
Li Zefan261507a02010-12-17 14:21:50 +0800989
Timofey Titovets4e439a02017-09-28 17:33:36 +0300990 if (heuristic)
991 free_heuristic_ws(workspace);
992 else
993 btrfs_compress_op[idx]->free_workspace(workspace);
David Sterba6ac10a62016-04-27 02:15:15 +0200994 atomic_dec(total_ws);
Li Zefan261507a02010-12-17 14:21:50 +0800995wake:
David Sterbaa83342a2015-02-16 19:36:47 +0100996 /*
997 * Make sure counter is updated before we wake up waiters.
998 */
Josef Bacik66657b32012-08-01 15:36:24 -0400999 smp_mb();
Byongho Leed9187642015-10-14 14:05:24 +09001000 if (waitqueue_active(ws_wait))
1001 wake_up(ws_wait);
Li Zefan261507a02010-12-17 14:21:50 +08001002}
1003
Timofey Titovets4e439a02017-09-28 17:33:36 +03001004static void free_workspace(int type, struct list_head *ws)
1005{
1006 return __free_workspace(type, ws, false);
1007}
1008
Li Zefan261507a02010-12-17 14:21:50 +08001009/*
1010 * cleanup function for module exit
1011 */
1012static void free_workspaces(void)
1013{
1014 struct list_head *workspace;
1015 int i;
1016
Timofey Titovets4e439a02017-09-28 17:33:36 +03001017 while (!list_empty(&btrfs_heuristic_ws.idle_ws)) {
1018 workspace = btrfs_heuristic_ws.idle_ws.next;
1019 list_del(workspace);
1020 free_heuristic_ws(workspace);
1021 atomic_dec(&btrfs_heuristic_ws.total_ws);
1022 }
1023
Li Zefan261507a02010-12-17 14:21:50 +08001024 for (i = 0; i < BTRFS_COMPRESS_TYPES; i++) {
Byongho Leed9187642015-10-14 14:05:24 +09001025 while (!list_empty(&btrfs_comp_ws[i].idle_ws)) {
1026 workspace = btrfs_comp_ws[i].idle_ws.next;
Li Zefan261507a02010-12-17 14:21:50 +08001027 list_del(workspace);
1028 btrfs_compress_op[i]->free_workspace(workspace);
David Sterba6ac10a62016-04-27 02:15:15 +02001029 atomic_dec(&btrfs_comp_ws[i].total_ws);
Li Zefan261507a02010-12-17 14:21:50 +08001030 }
1031 }
1032}
1033
1034/*
David Sterba38c31462017-02-14 19:04:07 +01001035 * Given an address space and start and length, compress the bytes into @pages
1036 * that are allocated on demand.
Li Zefan261507a02010-12-17 14:21:50 +08001037 *
David Sterbaf51d2b52017-09-15 17:36:57 +02001038 * @type_level is encoded algorithm and level, where level 0 means whatever
1039 * default the algorithm chooses and is opaque here;
1040 * - compression algo are 0-3
1041 * - the level are bits 4-7
1042 *
David Sterba4d3a8002017-02-14 19:04:07 +01001043 * @out_pages is an in/out parameter, holds maximum number of pages to allocate
1044 * and returns number of actually allocated pages
Li Zefan261507a02010-12-17 14:21:50 +08001045 *
David Sterba38c31462017-02-14 19:04:07 +01001046 * @total_in is used to return the number of bytes actually read. It
1047 * may be smaller than the input length if we had to exit early because we
Li Zefan261507a02010-12-17 14:21:50 +08001048 * ran out of room in the pages array or because we cross the
1049 * max_out threshold.
1050 *
David Sterba38c31462017-02-14 19:04:07 +01001051 * @total_out is an in/out parameter, must be set to the input length and will
1052 * be also used to return the total number of compressed bytes
Li Zefan261507a02010-12-17 14:21:50 +08001053 *
David Sterba38c31462017-02-14 19:04:07 +01001054 * @max_out tells us the max number of bytes that we're allowed to
Li Zefan261507a02010-12-17 14:21:50 +08001055 * stuff into pages
1056 */
David Sterbaf51d2b52017-09-15 17:36:57 +02001057int btrfs_compress_pages(unsigned int type_level, struct address_space *mapping,
David Sterba38c31462017-02-14 19:04:07 +01001058 u64 start, struct page **pages,
Li Zefan261507a02010-12-17 14:21:50 +08001059 unsigned long *out_pages,
1060 unsigned long *total_in,
David Sterbae5d74902017-02-14 19:45:05 +01001061 unsigned long *total_out)
Li Zefan261507a02010-12-17 14:21:50 +08001062{
1063 struct list_head *workspace;
1064 int ret;
David Sterbaf51d2b52017-09-15 17:36:57 +02001065 int type = type_level & 0xF;
Li Zefan261507a02010-12-17 14:21:50 +08001066
1067 workspace = find_workspace(type);
Li Zefan261507a02010-12-17 14:21:50 +08001068
David Sterbaf51d2b52017-09-15 17:36:57 +02001069 btrfs_compress_op[type - 1]->set_level(workspace, type_level);
Li Zefan261507a02010-12-17 14:21:50 +08001070 ret = btrfs_compress_op[type-1]->compress_pages(workspace, mapping,
David Sterba38c31462017-02-14 19:04:07 +01001071 start, pages,
David Sterba4d3a8002017-02-14 19:04:07 +01001072 out_pages,
David Sterbae5d74902017-02-14 19:45:05 +01001073 total_in, total_out);
Li Zefan261507a02010-12-17 14:21:50 +08001074 free_workspace(type, workspace);
1075 return ret;
1076}
1077
1078/*
1079 * pages_in is an array of pages with compressed data.
1080 *
1081 * disk_start is the starting logical offset of this array in the file
1082 *
Christoph Hellwig974b1ad2016-11-25 09:07:46 +01001083 * orig_bio contains the pages from the file that we want to decompress into
Li Zefan261507a02010-12-17 14:21:50 +08001084 *
1085 * srclen is the number of bytes in pages_in
1086 *
1087 * The basic idea is that we have a bio that was created by readpages.
1088 * The pages in the bio are for the uncompressed data, and they may not
1089 * be contiguous. They all correspond to the range of bytes covered by
1090 * the compressed extent.
1091 */
Anand Jain8140dc32017-05-26 15:44:58 +08001092static int btrfs_decompress_bio(struct compressed_bio *cb)
Li Zefan261507a02010-12-17 14:21:50 +08001093{
1094 struct list_head *workspace;
1095 int ret;
Anand Jain8140dc32017-05-26 15:44:58 +08001096 int type = cb->compress_type;
Li Zefan261507a02010-12-17 14:21:50 +08001097
1098 workspace = find_workspace(type);
Anand Jaine1ddce72017-05-26 15:44:59 +08001099 ret = btrfs_compress_op[type - 1]->decompress_bio(workspace, cb);
Li Zefan261507a02010-12-17 14:21:50 +08001100 free_workspace(type, workspace);
Anand Jaine1ddce72017-05-26 15:44:59 +08001101
Li Zefan261507a02010-12-17 14:21:50 +08001102 return ret;
1103}
1104
1105/*
1106 * a less complex decompression routine. Our compressed data fits in a
1107 * single page, and we want to read a single page out of it.
1108 * start_byte tells us the offset into the compressed data we're interested in
1109 */
1110int btrfs_decompress(int type, unsigned char *data_in, struct page *dest_page,
1111 unsigned long start_byte, size_t srclen, size_t destlen)
1112{
1113 struct list_head *workspace;
1114 int ret;
1115
1116 workspace = find_workspace(type);
Li Zefan261507a02010-12-17 14:21:50 +08001117
1118 ret = btrfs_compress_op[type-1]->decompress(workspace, data_in,
1119 dest_page, start_byte,
1120 srclen, destlen);
1121
1122 free_workspace(type, workspace);
1123 return ret;
1124}
1125
Alexey Charkov8e4eef72011-02-02 21:15:35 +00001126void btrfs_exit_compress(void)
Li Zefan261507a02010-12-17 14:21:50 +08001127{
1128 free_workspaces();
1129}
Li Zefan3a39c182010-11-08 15:22:19 +08001130
1131/*
1132 * Copy uncompressed data from working buffer to pages.
1133 *
1134 * buf_start is the byte offset we're of the start of our workspace buffer.
1135 *
1136 * total_out is the last byte of the buffer
1137 */
David Sterba14a33572017-02-14 17:58:04 +01001138int btrfs_decompress_buf2page(const char *buf, unsigned long buf_start,
Li Zefan3a39c182010-11-08 15:22:19 +08001139 unsigned long total_out, u64 disk_start,
Christoph Hellwig974b1ad2016-11-25 09:07:46 +01001140 struct bio *bio)
Li Zefan3a39c182010-11-08 15:22:19 +08001141{
1142 unsigned long buf_offset;
1143 unsigned long current_buf_start;
1144 unsigned long start_byte;
Omar Sandoval6e78b3f2017-02-10 15:03:35 -08001145 unsigned long prev_start_byte;
Li Zefan3a39c182010-11-08 15:22:19 +08001146 unsigned long working_bytes = total_out - buf_start;
1147 unsigned long bytes;
1148 char *kaddr;
Christoph Hellwig974b1ad2016-11-25 09:07:46 +01001149 struct bio_vec bvec = bio_iter_iovec(bio, bio->bi_iter);
Li Zefan3a39c182010-11-08 15:22:19 +08001150
1151 /*
1152 * start byte is the first byte of the page we're currently
1153 * copying into relative to the start of the compressed data.
1154 */
Christoph Hellwig974b1ad2016-11-25 09:07:46 +01001155 start_byte = page_offset(bvec.bv_page) - disk_start;
Li Zefan3a39c182010-11-08 15:22:19 +08001156
1157 /* we haven't yet hit data corresponding to this page */
1158 if (total_out <= start_byte)
1159 return 1;
1160
1161 /*
1162 * the start of the data we care about is offset into
1163 * the middle of our working buffer
1164 */
1165 if (total_out > start_byte && buf_start < start_byte) {
1166 buf_offset = start_byte - buf_start;
1167 working_bytes -= buf_offset;
1168 } else {
1169 buf_offset = 0;
1170 }
1171 current_buf_start = buf_start;
1172
1173 /* copy bytes from the working buffer into the pages */
1174 while (working_bytes > 0) {
Christoph Hellwig974b1ad2016-11-25 09:07:46 +01001175 bytes = min_t(unsigned long, bvec.bv_len,
1176 PAGE_SIZE - buf_offset);
Li Zefan3a39c182010-11-08 15:22:19 +08001177 bytes = min(bytes, working_bytes);
Li Zefan3a39c182010-11-08 15:22:19 +08001178
Christoph Hellwig974b1ad2016-11-25 09:07:46 +01001179 kaddr = kmap_atomic(bvec.bv_page);
1180 memcpy(kaddr + bvec.bv_offset, buf + buf_offset, bytes);
1181 kunmap_atomic(kaddr);
1182 flush_dcache_page(bvec.bv_page);
1183
Li Zefan3a39c182010-11-08 15:22:19 +08001184 buf_offset += bytes;
1185 working_bytes -= bytes;
1186 current_buf_start += bytes;
1187
1188 /* check if we need to pick another page */
Christoph Hellwig974b1ad2016-11-25 09:07:46 +01001189 bio_advance(bio, bytes);
1190 if (!bio->bi_iter.bi_size)
1191 return 0;
1192 bvec = bio_iter_iovec(bio, bio->bi_iter);
Omar Sandoval6e78b3f2017-02-10 15:03:35 -08001193 prev_start_byte = start_byte;
Christoph Hellwig974b1ad2016-11-25 09:07:46 +01001194 start_byte = page_offset(bvec.bv_page) - disk_start;
Li Zefan3a39c182010-11-08 15:22:19 +08001195
Christoph Hellwig974b1ad2016-11-25 09:07:46 +01001196 /*
Omar Sandoval6e78b3f2017-02-10 15:03:35 -08001197 * We need to make sure we're only adjusting
1198 * our offset into compression working buffer when
1199 * we're switching pages. Otherwise we can incorrectly
1200 * keep copying when we were actually done.
Christoph Hellwig974b1ad2016-11-25 09:07:46 +01001201 */
Omar Sandoval6e78b3f2017-02-10 15:03:35 -08001202 if (start_byte != prev_start_byte) {
1203 /*
1204 * make sure our new page is covered by this
1205 * working buffer
1206 */
1207 if (total_out <= start_byte)
1208 return 1;
Li Zefan3a39c182010-11-08 15:22:19 +08001209
Omar Sandoval6e78b3f2017-02-10 15:03:35 -08001210 /*
1211 * the next page in the biovec might not be adjacent
1212 * to the last page, but it might still be found
1213 * inside this working buffer. bump our offset pointer
1214 */
1215 if (total_out > start_byte &&
1216 current_buf_start < start_byte) {
1217 buf_offset = start_byte - buf_start;
1218 working_bytes = total_out - start_byte;
1219 current_buf_start = buf_start + buf_offset;
1220 }
Li Zefan3a39c182010-11-08 15:22:19 +08001221 }
1222 }
1223
1224 return 1;
1225}
Timofey Titovetsc2fcdcd2017-07-17 16:52:58 +03001226
Timofey Titovets19562432017-10-08 16:11:59 +03001227/*
1228 * Shannon Entropy calculation
1229 *
1230 * Pure byte distribution analysis fails to determine compressiability of data.
1231 * Try calculating entropy to estimate the average minimum number of bits
1232 * needed to encode the sampled data.
1233 *
1234 * For convenience, return the percentage of needed bits, instead of amount of
1235 * bits directly.
1236 *
1237 * @ENTROPY_LVL_ACEPTABLE - below that threshold, sample has low byte entropy
1238 * and can be compressible with high probability
1239 *
1240 * @ENTROPY_LVL_HIGH - data are not compressible with high probability
1241 *
1242 * Use of ilog2() decreases precision, we lower the LVL to 5 to compensate.
1243 */
1244#define ENTROPY_LVL_ACEPTABLE (65)
1245#define ENTROPY_LVL_HIGH (80)
1246
1247/*
1248 * For increasead precision in shannon_entropy calculation,
1249 * let's do pow(n, M) to save more digits after comma:
1250 *
1251 * - maximum int bit length is 64
1252 * - ilog2(MAX_SAMPLE_SIZE) -> 13
1253 * - 13 * 4 = 52 < 64 -> M = 4
1254 *
1255 * So use pow(n, 4).
1256 */
1257static inline u32 ilog2_w(u64 n)
1258{
1259 return ilog2(n * n * n * n);
1260}
1261
1262static u32 shannon_entropy(struct heuristic_ws *ws)
1263{
1264 const u32 entropy_max = 8 * ilog2_w(2);
1265 u32 entropy_sum = 0;
1266 u32 p, p_base, sz_base;
1267 u32 i;
1268
1269 sz_base = ilog2_w(ws->sample_size);
1270 for (i = 0; i < BUCKET_SIZE && ws->bucket[i].count > 0; i++) {
1271 p = ws->bucket[i].count;
1272 p_base = ilog2_w(p);
1273 entropy_sum += p * (sz_base - p_base);
1274 }
1275
1276 entropy_sum /= ws->sample_size;
1277 return entropy_sum * 100 / entropy_max;
1278}
1279
Timofey Titovets858177d2017-09-28 17:33:41 +03001280/* Compare buckets by size, ascending */
1281static int bucket_comp_rev(const void *lv, const void *rv)
1282{
1283 const struct bucket_item *l = (const struct bucket_item *)lv;
1284 const struct bucket_item *r = (const struct bucket_item *)rv;
1285
1286 return r->count - l->count;
1287}
1288
1289/*
1290 * Size of the core byte set - how many bytes cover 90% of the sample
1291 *
1292 * There are several types of structured binary data that use nearly all byte
1293 * values. The distribution can be uniform and counts in all buckets will be
1294 * nearly the same (eg. encrypted data). Unlikely to be compressible.
1295 *
1296 * Other possibility is normal (Gaussian) distribution, where the data could
1297 * be potentially compressible, but we have to take a few more steps to decide
1298 * how much.
1299 *
1300 * @BYTE_CORE_SET_LOW - main part of byte values repeated frequently,
1301 * compression algo can easy fix that
1302 * @BYTE_CORE_SET_HIGH - data have uniform distribution and with high
1303 * probability is not compressible
1304 */
1305#define BYTE_CORE_SET_LOW (64)
1306#define BYTE_CORE_SET_HIGH (200)
1307
1308static int byte_core_set_size(struct heuristic_ws *ws)
1309{
1310 u32 i;
1311 u32 coreset_sum = 0;
1312 const u32 core_set_threshold = ws->sample_size * 90 / 100;
1313 struct bucket_item *bucket = ws->bucket;
1314
1315 /* Sort in reverse order */
1316 sort(bucket, BUCKET_SIZE, sizeof(*bucket), &bucket_comp_rev, NULL);
1317
1318 for (i = 0; i < BYTE_CORE_SET_LOW; i++)
1319 coreset_sum += bucket[i].count;
1320
1321 if (coreset_sum > core_set_threshold)
1322 return i;
1323
1324 for (; i < BYTE_CORE_SET_HIGH && bucket[i].count > 0; i++) {
1325 coreset_sum += bucket[i].count;
1326 if (coreset_sum > core_set_threshold)
1327 break;
1328 }
1329
1330 return i;
1331}
1332
Timofey Titovetsa288e922017-09-28 17:33:40 +03001333/*
1334 * Count byte values in buckets.
1335 * This heuristic can detect textual data (configs, xml, json, html, etc).
1336 * Because in most text-like data byte set is restricted to limited number of
1337 * possible characters, and that restriction in most cases makes data easy to
1338 * compress.
1339 *
1340 * @BYTE_SET_THRESHOLD - consider all data within this byte set size:
1341 * less - compressible
1342 * more - need additional analysis
1343 */
1344#define BYTE_SET_THRESHOLD (64)
1345
1346static u32 byte_set_size(const struct heuristic_ws *ws)
1347{
1348 u32 i;
1349 u32 byte_set_size = 0;
1350
1351 for (i = 0; i < BYTE_SET_THRESHOLD; i++) {
1352 if (ws->bucket[i].count > 0)
1353 byte_set_size++;
1354 }
1355
1356 /*
1357 * Continue collecting count of byte values in buckets. If the byte
1358 * set size is bigger then the threshold, it's pointless to continue,
1359 * the detection technique would fail for this type of data.
1360 */
1361 for (; i < BUCKET_SIZE; i++) {
1362 if (ws->bucket[i].count > 0) {
1363 byte_set_size++;
1364 if (byte_set_size > BYTE_SET_THRESHOLD)
1365 return byte_set_size;
1366 }
1367 }
1368
1369 return byte_set_size;
1370}
1371
Timofey Titovets1fe4f6f2017-09-28 17:33:39 +03001372static bool sample_repeated_patterns(struct heuristic_ws *ws)
1373{
1374 const u32 half_of_sample = ws->sample_size / 2;
1375 const u8 *data = ws->sample;
1376
1377 return memcmp(&data[0], &data[half_of_sample], half_of_sample) == 0;
1378}
1379
Timofey Titovetsa440d482017-09-28 17:33:38 +03001380static void heuristic_collect_sample(struct inode *inode, u64 start, u64 end,
1381 struct heuristic_ws *ws)
1382{
1383 struct page *page;
1384 u64 index, index_end;
1385 u32 i, curr_sample_pos;
1386 u8 *in_data;
1387
1388 /*
1389 * Compression handles the input data by chunks of 128KiB
1390 * (defined by BTRFS_MAX_UNCOMPRESSED)
1391 *
1392 * We do the same for the heuristic and loop over the whole range.
1393 *
1394 * MAX_SAMPLE_SIZE - calculated under assumption that heuristic will
1395 * process no more than BTRFS_MAX_UNCOMPRESSED at a time.
1396 */
1397 if (end - start > BTRFS_MAX_UNCOMPRESSED)
1398 end = start + BTRFS_MAX_UNCOMPRESSED;
1399
1400 index = start >> PAGE_SHIFT;
1401 index_end = end >> PAGE_SHIFT;
1402
1403 /* Don't miss unaligned end */
1404 if (!IS_ALIGNED(end, PAGE_SIZE))
1405 index_end++;
1406
1407 curr_sample_pos = 0;
1408 while (index < index_end) {
1409 page = find_get_page(inode->i_mapping, index);
1410 in_data = kmap(page);
1411 /* Handle case where the start is not aligned to PAGE_SIZE */
1412 i = start % PAGE_SIZE;
1413 while (i < PAGE_SIZE - SAMPLING_READ_SIZE) {
1414 /* Don't sample any garbage from the last page */
1415 if (start > end - SAMPLING_READ_SIZE)
1416 break;
1417 memcpy(&ws->sample[curr_sample_pos], &in_data[i],
1418 SAMPLING_READ_SIZE);
1419 i += SAMPLING_INTERVAL;
1420 start += SAMPLING_INTERVAL;
1421 curr_sample_pos += SAMPLING_READ_SIZE;
1422 }
1423 kunmap(page);
1424 put_page(page);
1425
1426 index++;
1427 }
1428
1429 ws->sample_size = curr_sample_pos;
1430}
1431
Timofey Titovetsc2fcdcd2017-07-17 16:52:58 +03001432/*
1433 * Compression heuristic.
1434 *
1435 * For now is's a naive and optimistic 'return true', we'll extend the logic to
1436 * quickly (compared to direct compression) detect data characteristics
1437 * (compressible/uncompressible) to avoid wasting CPU time on uncompressible
1438 * data.
1439 *
1440 * The following types of analysis can be performed:
1441 * - detect mostly zero data
1442 * - detect data with low "byte set" size (text, etc)
1443 * - detect data with low/high "core byte" set
1444 *
1445 * Return non-zero if the compression should be done, 0 otherwise.
1446 */
1447int btrfs_compress_heuristic(struct inode *inode, u64 start, u64 end)
1448{
Timofey Titovets4e439a02017-09-28 17:33:36 +03001449 struct list_head *ws_list = __find_workspace(0, true);
1450 struct heuristic_ws *ws;
Timofey Titovetsa440d482017-09-28 17:33:38 +03001451 u32 i;
1452 u8 byte;
Timofey Titovets19562432017-10-08 16:11:59 +03001453 int ret = 0;
Timofey Titovetsc2fcdcd2017-07-17 16:52:58 +03001454
Timofey Titovets4e439a02017-09-28 17:33:36 +03001455 ws = list_entry(ws_list, struct heuristic_ws, list);
1456
Timofey Titovetsa440d482017-09-28 17:33:38 +03001457 heuristic_collect_sample(inode, start, end, ws);
1458
Timofey Titovets1fe4f6f2017-09-28 17:33:39 +03001459 if (sample_repeated_patterns(ws)) {
1460 ret = 1;
1461 goto out;
1462 }
1463
Timofey Titovetsa440d482017-09-28 17:33:38 +03001464 memset(ws->bucket, 0, sizeof(*ws->bucket)*BUCKET_SIZE);
1465
1466 for (i = 0; i < ws->sample_size; i++) {
1467 byte = ws->sample[i];
1468 ws->bucket[byte].count++;
Timofey Titovetsc2fcdcd2017-07-17 16:52:58 +03001469 }
1470
Timofey Titovetsa288e922017-09-28 17:33:40 +03001471 i = byte_set_size(ws);
1472 if (i < BYTE_SET_THRESHOLD) {
1473 ret = 2;
1474 goto out;
1475 }
1476
Timofey Titovets858177d2017-09-28 17:33:41 +03001477 i = byte_core_set_size(ws);
1478 if (i <= BYTE_CORE_SET_LOW) {
1479 ret = 3;
1480 goto out;
1481 }
1482
1483 if (i >= BYTE_CORE_SET_HIGH) {
1484 ret = 0;
1485 goto out;
1486 }
1487
Timofey Titovets19562432017-10-08 16:11:59 +03001488 i = shannon_entropy(ws);
1489 if (i <= ENTROPY_LVL_ACEPTABLE) {
1490 ret = 4;
1491 goto out;
1492 }
1493
1494 /*
1495 * For the levels below ENTROPY_LVL_HIGH, additional analysis would be
1496 * needed to give green light to compression.
1497 *
1498 * For now just assume that compression at that level is not worth the
1499 * resources because:
1500 *
1501 * 1. it is possible to defrag the data later
1502 *
1503 * 2. the data would turn out to be hardly compressible, eg. 150 byte
1504 * values, every bucket has counter at level ~54. The heuristic would
1505 * be confused. This can happen when data have some internal repeated
1506 * patterns like "abbacbbc...". This can be detected by analyzing
1507 * pairs of bytes, which is too costly.
1508 */
1509 if (i < ENTROPY_LVL_HIGH) {
1510 ret = 5;
1511 goto out;
1512 } else {
1513 ret = 0;
1514 goto out;
1515 }
1516
Timofey Titovets1fe4f6f2017-09-28 17:33:39 +03001517out:
Timofey Titovets4e439a02017-09-28 17:33:36 +03001518 __free_workspace(0, ws_list, true);
Timofey Titovetsc2fcdcd2017-07-17 16:52:58 +03001519 return ret;
1520}
David Sterbaf51d2b52017-09-15 17:36:57 +02001521
1522unsigned int btrfs_compress_str2level(const char *str)
1523{
1524 if (strncmp(str, "zlib", 4) != 0)
1525 return 0;
1526
Adam Borowskifa4d8852017-09-15 17:36:58 +02001527 /* Accepted form: zlib:1 up to zlib:9 and nothing left after the number */
1528 if (str[4] == ':' && '1' <= str[5] && str[5] <= '9' && str[6] == 0)
1529 return str[5] - '0';
David Sterbaf51d2b52017-09-15 17:36:57 +02001530
1531 return 0;
1532}