blob: 8cd48d7c3f76abeed9cf0226aa7125ed5013a2a8 [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
Anand Jain8140dc32017-05-26 15:44:58 +080047static int btrfs_decompress_bio(struct compressed_bio *cb);
Eric Sandeen48a3b632013-04-25 20:41:01 +000048
Jeff Mahoney2ff7e612016-06-22 18:54:24 -040049static inline int compressed_bio_size(struct btrfs_fs_info *fs_info,
Chris Masond20f7042008-12-08 16:58:54 -050050 unsigned long disk_size)
51{
Jeff Mahoney0b246af2016-06-22 18:54:23 -040052 u16 csum_size = btrfs_super_csum_size(fs_info->super_copy);
David Sterba6c417612011-04-13 15:41:04 +020053
Chris Masond20f7042008-12-08 16:58:54 -050054 return sizeof(struct compressed_bio) +
Jeff Mahoney0b246af2016-06-22 18:54:23 -040055 (DIV_ROUND_UP(disk_size, fs_info->sectorsize)) * csum_size;
Chris Masond20f7042008-12-08 16:58:54 -050056}
57
Nikolay Borisovf898ac62017-02-20 13:50:54 +020058static int check_compressed_csum(struct btrfs_inode *inode,
Chris Masond20f7042008-12-08 16:58:54 -050059 struct compressed_bio *cb,
60 u64 disk_start)
61{
62 int ret;
Chris Masond20f7042008-12-08 16:58:54 -050063 struct page *page;
64 unsigned long i;
65 char *kaddr;
66 u32 csum;
67 u32 *cb_sum = &cb->sums;
68
Nikolay Borisovf898ac62017-02-20 13:50:54 +020069 if (inode->flags & BTRFS_INODE_NODATASUM)
Chris Masond20f7042008-12-08 16:58:54 -050070 return 0;
71
72 for (i = 0; i < cb->nr_pages; i++) {
73 page = cb->compressed_pages[i];
74 csum = ~(u32)0;
75
Cong Wang7ac687d2011-11-25 23:14:28 +080076 kaddr = kmap_atomic(page);
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +030077 csum = btrfs_csum_data(kaddr, csum, PAGE_SIZE);
Domagoj Tršan0b5e3da2016-10-27 08:52:33 +010078 btrfs_csum_final(csum, (u8 *)&csum);
Cong Wang7ac687d2011-11-25 23:14:28 +080079 kunmap_atomic(kaddr);
Chris Masond20f7042008-12-08 16:58:54 -050080
81 if (csum != *cb_sum) {
Nikolay Borisovf898ac62017-02-20 13:50:54 +020082 btrfs_print_data_csum_error(inode, disk_start, csum,
Nikolay Borisov0970a222017-02-20 13:50:53 +020083 *cb_sum, cb->mirror_num);
Chris Masond20f7042008-12-08 16:58:54 -050084 ret = -EIO;
85 goto fail;
86 }
87 cb_sum++;
88
89 }
90 ret = 0;
91fail:
92 return ret;
93}
94
Chris Masonc8b97812008-10-29 14:49:59 -040095/* when we finish reading compressed pages from the disk, we
96 * decompress them and then run the bio end_io routines on the
97 * decompressed pages (in the inode address space).
98 *
99 * This allows the checksumming and other IO error handling routines
100 * to work normally
101 *
102 * The compressed pages are freed here, and it must be run
103 * in process context
104 */
Christoph Hellwig4246a0b2015-07-20 15:29:37 +0200105static void end_compressed_bio_read(struct bio *bio)
Chris Masonc8b97812008-10-29 14:49:59 -0400106{
Chris Masonc8b97812008-10-29 14:49:59 -0400107 struct compressed_bio *cb = bio->bi_private;
108 struct inode *inode;
109 struct page *page;
110 unsigned long index;
Liu Bocf1167d2017-09-20 17:50:18 -0600111 unsigned int mirror = btrfs_io_bio(bio)->mirror_num;
Liu Boe6311f22017-09-20 17:50:19 -0600112 int ret = 0;
Chris Masonc8b97812008-10-29 14:49:59 -0400113
Christoph Hellwig4e4cbee2017-06-03 09:38:06 +0200114 if (bio->bi_status)
Chris Masonc8b97812008-10-29 14:49:59 -0400115 cb->errors = 1;
116
117 /* if there are more bios still pending for this compressed
118 * extent, just exit
119 */
Elena Reshetovaa50299a2017-03-03 10:55:20 +0200120 if (!refcount_dec_and_test(&cb->pending_bios))
Chris Masonc8b97812008-10-29 14:49:59 -0400121 goto out;
122
Liu Bocf1167d2017-09-20 17:50:18 -0600123 /*
124 * Record the correct mirror_num in cb->orig_bio so that
125 * read-repair can work properly.
126 */
127 ASSERT(btrfs_io_bio(cb->orig_bio));
128 btrfs_io_bio(cb->orig_bio)->mirror_num = mirror;
129 cb->mirror_num = mirror;
130
Liu Boe6311f22017-09-20 17:50:19 -0600131 /*
132 * Some IO in this cb have failed, just skip checksum as there
133 * is no way it could be correct.
134 */
135 if (cb->errors == 1)
136 goto csum_failed;
137
Chris Masond20f7042008-12-08 16:58:54 -0500138 inode = cb->inode;
Nikolay Borisovf898ac62017-02-20 13:50:54 +0200139 ret = check_compressed_csum(BTRFS_I(inode), cb,
Kent Overstreet4f024f32013-10-11 15:44:27 -0700140 (u64)bio->bi_iter.bi_sector << 9);
Chris Masond20f7042008-12-08 16:58:54 -0500141 if (ret)
142 goto csum_failed;
143
Chris Masonc8b97812008-10-29 14:49:59 -0400144 /* ok, we're the last bio for this extent, lets start
145 * the decompression.
146 */
Anand Jain8140dc32017-05-26 15:44:58 +0800147 ret = btrfs_decompress_bio(cb);
148
Chris Masond20f7042008-12-08 16:58:54 -0500149csum_failed:
Chris Masonc8b97812008-10-29 14:49:59 -0400150 if (ret)
151 cb->errors = 1;
152
153 /* release the compressed pages */
154 index = 0;
155 for (index = 0; index < cb->nr_pages; index++) {
156 page = cb->compressed_pages[index];
157 page->mapping = NULL;
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300158 put_page(page);
Chris Masonc8b97812008-10-29 14:49:59 -0400159 }
160
161 /* do io completion on the original bio */
Chris Mason771ed682008-11-06 22:02:51 -0500162 if (cb->errors) {
Chris Masonc8b97812008-10-29 14:49:59 -0400163 bio_io_error(cb->orig_bio);
Chris Masond20f7042008-12-08 16:58:54 -0500164 } else {
Kent Overstreet2c30c712013-11-07 12:20:26 -0800165 int i;
166 struct bio_vec *bvec;
Chris Masond20f7042008-12-08 16:58:54 -0500167
168 /*
169 * we have verified the checksum already, set page
170 * checked so the end_io handlers know about it
171 */
David Sterbac09abff2017-07-13 18:10:07 +0200172 ASSERT(!bio_flagged(bio, BIO_CLONED));
Kent Overstreet2c30c712013-11-07 12:20:26 -0800173 bio_for_each_segment_all(bvec, cb->orig_bio, i)
Chris Masond20f7042008-12-08 16:58:54 -0500174 SetPageChecked(bvec->bv_page);
Kent Overstreet2c30c712013-11-07 12:20:26 -0800175
Christoph Hellwig4246a0b2015-07-20 15:29:37 +0200176 bio_endio(cb->orig_bio);
Chris Masond20f7042008-12-08 16:58:54 -0500177 }
Chris Masonc8b97812008-10-29 14:49:59 -0400178
179 /* finally free the cb struct */
180 kfree(cb->compressed_pages);
181 kfree(cb);
182out:
183 bio_put(bio);
184}
185
186/*
187 * Clear the writeback bits on all of the file
188 * pages for a compressed write
189 */
Filipe Manana7bdcefc2014-10-07 01:48:26 +0100190static noinline void end_compressed_writeback(struct inode *inode,
191 const struct compressed_bio *cb)
Chris Masonc8b97812008-10-29 14:49:59 -0400192{
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300193 unsigned long index = cb->start >> PAGE_SHIFT;
194 unsigned long end_index = (cb->start + cb->len - 1) >> PAGE_SHIFT;
Chris Masonc8b97812008-10-29 14:49:59 -0400195 struct page *pages[16];
196 unsigned long nr_pages = end_index - index + 1;
197 int i;
198 int ret;
199
Filipe Manana7bdcefc2014-10-07 01:48:26 +0100200 if (cb->errors)
201 mapping_set_error(inode->i_mapping, -EIO);
202
Chris Masond3977122009-01-05 21:25:51 -0500203 while (nr_pages > 0) {
Chris Masonc8b97812008-10-29 14:49:59 -0400204 ret = find_get_pages_contig(inode->i_mapping, index,
Chris Mason5b050f02008-11-11 09:34:41 -0500205 min_t(unsigned long,
206 nr_pages, ARRAY_SIZE(pages)), pages);
Chris Masonc8b97812008-10-29 14:49:59 -0400207 if (ret == 0) {
208 nr_pages -= 1;
209 index += 1;
210 continue;
211 }
212 for (i = 0; i < ret; i++) {
Filipe Manana7bdcefc2014-10-07 01:48:26 +0100213 if (cb->errors)
214 SetPageError(pages[i]);
Chris Masonc8b97812008-10-29 14:49:59 -0400215 end_page_writeback(pages[i]);
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300216 put_page(pages[i]);
Chris Masonc8b97812008-10-29 14:49:59 -0400217 }
218 nr_pages -= ret;
219 index += ret;
220 }
221 /* the inode may be gone now */
Chris Masonc8b97812008-10-29 14:49:59 -0400222}
223
224/*
225 * do the cleanup once all the compressed pages hit the disk.
226 * This will clear writeback on the file pages and free the compressed
227 * pages.
228 *
229 * This also calls the writeback end hooks for the file pages so that
230 * metadata and checksums can be updated in the file.
231 */
Christoph Hellwig4246a0b2015-07-20 15:29:37 +0200232static void end_compressed_bio_write(struct bio *bio)
Chris Masonc8b97812008-10-29 14:49:59 -0400233{
234 struct extent_io_tree *tree;
235 struct compressed_bio *cb = bio->bi_private;
236 struct inode *inode;
237 struct page *page;
238 unsigned long index;
239
Christoph Hellwig4e4cbee2017-06-03 09:38:06 +0200240 if (bio->bi_status)
Chris Masonc8b97812008-10-29 14:49:59 -0400241 cb->errors = 1;
242
243 /* if there are more bios still pending for this compressed
244 * extent, just exit
245 */
Elena Reshetovaa50299a2017-03-03 10:55:20 +0200246 if (!refcount_dec_and_test(&cb->pending_bios))
Chris Masonc8b97812008-10-29 14:49:59 -0400247 goto out;
248
249 /* ok, we're the last bio for this extent, step one is to
250 * call back into the FS and do all the end_io operations
251 */
252 inode = cb->inode;
253 tree = &BTRFS_I(inode)->io_tree;
Chris Mason70b99e62008-10-31 12:46:39 -0400254 cb->compressed_pages[0]->mapping = cb->inode->i_mapping;
Chris Masonc8b97812008-10-29 14:49:59 -0400255 tree->ops->writepage_end_io_hook(cb->compressed_pages[0],
256 cb->start,
257 cb->start + cb->len - 1,
Filipe Manana7bdcefc2014-10-07 01:48:26 +0100258 NULL,
Anand Jain2dbe0c72017-10-14 08:35:56 +0800259 bio->bi_status ?
260 BLK_STS_OK : BLK_STS_NOTSUPP);
Chris Mason70b99e62008-10-31 12:46:39 -0400261 cb->compressed_pages[0]->mapping = NULL;
Chris Masonc8b97812008-10-29 14:49:59 -0400262
Filipe Manana7bdcefc2014-10-07 01:48:26 +0100263 end_compressed_writeback(inode, cb);
Chris Masonc8b97812008-10-29 14:49:59 -0400264 /* note, our inode could be gone now */
265
266 /*
267 * release the compressed pages, these came from alloc_page and
268 * are not attached to the inode at all
269 */
270 index = 0;
271 for (index = 0; index < cb->nr_pages; index++) {
272 page = cb->compressed_pages[index];
273 page->mapping = NULL;
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300274 put_page(page);
Chris Masonc8b97812008-10-29 14:49:59 -0400275 }
276
277 /* finally free the cb struct */
278 kfree(cb->compressed_pages);
279 kfree(cb);
280out:
281 bio_put(bio);
282}
283
284/*
285 * worker function to build and submit bios for previously compressed pages.
286 * The corresponding pages in the inode should be marked for writeback
287 * and the compressed pages should have a reference on them for dropping
288 * when the IO is complete.
289 *
290 * This also checksums the file bytes and gets things ready for
291 * the end io hooks.
292 */
Christoph Hellwig4e4cbee2017-06-03 09:38:06 +0200293blk_status_t btrfs_submit_compressed_write(struct inode *inode, u64 start,
Chris Masonc8b97812008-10-29 14:49:59 -0400294 unsigned long len, u64 disk_start,
295 unsigned long compressed_len,
296 struct page **compressed_pages,
Liu Bof82b7352017-10-23 23:18:16 -0600297 unsigned long nr_pages,
298 unsigned int write_flags)
Chris Masonc8b97812008-10-29 14:49:59 -0400299{
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);
Liu Bof82b7352017-10-23 23:18:16 -0600330 bio->bi_opf = REQ_OP_WRITE | write_flags;
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);
Liu Bof82b7352017-10-23 23:18:16 -0600377 bio->bi_opf = REQ_OP_WRITE | write_flags;
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 Titovets440c8402017-12-04 00:30:33 +0300754 /* Sorting buffer */
755 struct bucket_item *bucket_b;
Timofey Titovets4e439a02017-09-28 17:33:36 +0300756 struct list_head list;
757};
758
759static void free_heuristic_ws(struct list_head *ws)
760{
761 struct heuristic_ws *workspace;
762
763 workspace = list_entry(ws, struct heuristic_ws, list);
764
Timofey Titovets17b5a6c2017-09-28 17:33:37 +0300765 kvfree(workspace->sample);
766 kfree(workspace->bucket);
Timofey Titovets440c8402017-12-04 00:30:33 +0300767 kfree(workspace->bucket_b);
Timofey Titovets4e439a02017-09-28 17:33:36 +0300768 kfree(workspace);
769}
770
771static struct list_head *alloc_heuristic_ws(void)
772{
773 struct heuristic_ws *ws;
774
775 ws = kzalloc(sizeof(*ws), GFP_KERNEL);
776 if (!ws)
777 return ERR_PTR(-ENOMEM);
778
Timofey Titovets17b5a6c2017-09-28 17:33:37 +0300779 ws->sample = kvmalloc(MAX_SAMPLE_SIZE, GFP_KERNEL);
780 if (!ws->sample)
781 goto fail;
Timofey Titovets4e439a02017-09-28 17:33:36 +0300782
Timofey Titovets17b5a6c2017-09-28 17:33:37 +0300783 ws->bucket = kcalloc(BUCKET_SIZE, sizeof(*ws->bucket), GFP_KERNEL);
784 if (!ws->bucket)
785 goto fail;
786
Timofey Titovets440c8402017-12-04 00:30:33 +0300787 ws->bucket_b = kcalloc(BUCKET_SIZE, sizeof(*ws->bucket_b), GFP_KERNEL);
788 if (!ws->bucket_b)
789 goto fail;
790
Timofey Titovets17b5a6c2017-09-28 17:33:37 +0300791 INIT_LIST_HEAD(&ws->list);
Timofey Titovets4e439a02017-09-28 17:33:36 +0300792 return &ws->list;
Timofey Titovets17b5a6c2017-09-28 17:33:37 +0300793fail:
794 free_heuristic_ws(&ws->list);
795 return ERR_PTR(-ENOMEM);
Timofey Titovets4e439a02017-09-28 17:33:36 +0300796}
797
798struct workspaces_list {
Byongho Leed9187642015-10-14 14:05:24 +0900799 struct list_head idle_ws;
800 spinlock_t ws_lock;
David Sterba6ac10a62016-04-27 02:15:15 +0200801 /* Number of free workspaces */
802 int free_ws;
803 /* Total number of allocated workspaces */
804 atomic_t total_ws;
805 /* Waiters for a free workspace */
Byongho Leed9187642015-10-14 14:05:24 +0900806 wait_queue_head_t ws_wait;
Timofey Titovets4e439a02017-09-28 17:33:36 +0300807};
808
809static struct workspaces_list btrfs_comp_ws[BTRFS_COMPRESS_TYPES];
810
811static struct workspaces_list btrfs_heuristic_ws;
Li Zefan261507a02010-12-17 14:21:50 +0800812
David Sterbae8c9f182015-01-02 18:23:10 +0100813static const struct btrfs_compress_op * const btrfs_compress_op[] = {
Li Zefan261507a02010-12-17 14:21:50 +0800814 &btrfs_zlib_compress,
Li Zefana6fa6fa2010-10-25 15:12:26 +0800815 &btrfs_lzo_compress,
Nick Terrell5c1aab12017-08-09 19:39:02 -0700816 &btrfs_zstd_compress,
Li Zefan261507a02010-12-17 14:21:50 +0800817};
818
Jeff Mahoney143bede2012-03-01 14:56:26 +0100819void __init btrfs_init_compress(void)
Li Zefan261507a02010-12-17 14:21:50 +0800820{
Timofey Titovets4e439a02017-09-28 17:33:36 +0300821 struct list_head *workspace;
Li Zefan261507a02010-12-17 14:21:50 +0800822 int i;
823
Timofey Titovets4e439a02017-09-28 17:33:36 +0300824 INIT_LIST_HEAD(&btrfs_heuristic_ws.idle_ws);
825 spin_lock_init(&btrfs_heuristic_ws.ws_lock);
826 atomic_set(&btrfs_heuristic_ws.total_ws, 0);
827 init_waitqueue_head(&btrfs_heuristic_ws.ws_wait);
David Sterbaf77dd0d2016-04-27 02:55:15 +0200828
Timofey Titovets4e439a02017-09-28 17:33:36 +0300829 workspace = alloc_heuristic_ws();
830 if (IS_ERR(workspace)) {
831 pr_warn(
832 "BTRFS: cannot preallocate heuristic workspace, will try later\n");
833 } else {
834 atomic_set(&btrfs_heuristic_ws.total_ws, 1);
835 btrfs_heuristic_ws.free_ws = 1;
836 list_add(workspace, &btrfs_heuristic_ws.idle_ws);
837 }
838
839 for (i = 0; i < BTRFS_COMPRESS_TYPES; i++) {
Byongho Leed9187642015-10-14 14:05:24 +0900840 INIT_LIST_HEAD(&btrfs_comp_ws[i].idle_ws);
841 spin_lock_init(&btrfs_comp_ws[i].ws_lock);
David Sterba6ac10a62016-04-27 02:15:15 +0200842 atomic_set(&btrfs_comp_ws[i].total_ws, 0);
Byongho Leed9187642015-10-14 14:05:24 +0900843 init_waitqueue_head(&btrfs_comp_ws[i].ws_wait);
David Sterbaf77dd0d2016-04-27 02:55:15 +0200844
845 /*
846 * Preallocate one workspace for each compression type so
847 * we can guarantee forward progress in the worst case
848 */
849 workspace = btrfs_compress_op[i]->alloc_workspace();
850 if (IS_ERR(workspace)) {
Jeff Mahoney62e85572016-09-20 10:05:01 -0400851 pr_warn("BTRFS: cannot preallocate compression workspace, will try later\n");
David Sterbaf77dd0d2016-04-27 02:55:15 +0200852 } else {
853 atomic_set(&btrfs_comp_ws[i].total_ws, 1);
854 btrfs_comp_ws[i].free_ws = 1;
855 list_add(workspace, &btrfs_comp_ws[i].idle_ws);
856 }
Li Zefan261507a02010-12-17 14:21:50 +0800857 }
Li Zefan261507a02010-12-17 14:21:50 +0800858}
859
860/*
David Sterbae721e492016-04-27 02:41:17 +0200861 * This finds an available workspace or allocates a new one.
862 * If it's not possible to allocate a new one, waits until there's one.
863 * Preallocation makes a forward progress guarantees and we do not return
864 * errors.
Li Zefan261507a02010-12-17 14:21:50 +0800865 */
Timofey Titovets4e439a02017-09-28 17:33:36 +0300866static struct list_head *__find_workspace(int type, bool heuristic)
Li Zefan261507a02010-12-17 14:21:50 +0800867{
868 struct list_head *workspace;
869 int cpus = num_online_cpus();
870 int idx = type - 1;
David Sterbafe308532017-05-31 17:14:56 +0200871 unsigned nofs_flag;
Timofey Titovets4e439a02017-09-28 17:33:36 +0300872 struct list_head *idle_ws;
873 spinlock_t *ws_lock;
874 atomic_t *total_ws;
875 wait_queue_head_t *ws_wait;
876 int *free_ws;
Li Zefan261507a02010-12-17 14:21:50 +0800877
Timofey Titovets4e439a02017-09-28 17:33:36 +0300878 if (heuristic) {
879 idle_ws = &btrfs_heuristic_ws.idle_ws;
880 ws_lock = &btrfs_heuristic_ws.ws_lock;
881 total_ws = &btrfs_heuristic_ws.total_ws;
882 ws_wait = &btrfs_heuristic_ws.ws_wait;
883 free_ws = &btrfs_heuristic_ws.free_ws;
884 } else {
885 idle_ws = &btrfs_comp_ws[idx].idle_ws;
886 ws_lock = &btrfs_comp_ws[idx].ws_lock;
887 total_ws = &btrfs_comp_ws[idx].total_ws;
888 ws_wait = &btrfs_comp_ws[idx].ws_wait;
889 free_ws = &btrfs_comp_ws[idx].free_ws;
890 }
891
Li Zefan261507a02010-12-17 14:21:50 +0800892again:
Byongho Leed9187642015-10-14 14:05:24 +0900893 spin_lock(ws_lock);
894 if (!list_empty(idle_ws)) {
895 workspace = idle_ws->next;
Li Zefan261507a02010-12-17 14:21:50 +0800896 list_del(workspace);
David Sterba6ac10a62016-04-27 02:15:15 +0200897 (*free_ws)--;
Byongho Leed9187642015-10-14 14:05:24 +0900898 spin_unlock(ws_lock);
Li Zefan261507a02010-12-17 14:21:50 +0800899 return workspace;
900
901 }
David Sterba6ac10a62016-04-27 02:15:15 +0200902 if (atomic_read(total_ws) > cpus) {
Li Zefan261507a02010-12-17 14:21:50 +0800903 DEFINE_WAIT(wait);
904
Byongho Leed9187642015-10-14 14:05:24 +0900905 spin_unlock(ws_lock);
906 prepare_to_wait(ws_wait, &wait, TASK_UNINTERRUPTIBLE);
David Sterba6ac10a62016-04-27 02:15:15 +0200907 if (atomic_read(total_ws) > cpus && !*free_ws)
Li Zefan261507a02010-12-17 14:21:50 +0800908 schedule();
Byongho Leed9187642015-10-14 14:05:24 +0900909 finish_wait(ws_wait, &wait);
Li Zefan261507a02010-12-17 14:21:50 +0800910 goto again;
911 }
David Sterba6ac10a62016-04-27 02:15:15 +0200912 atomic_inc(total_ws);
Byongho Leed9187642015-10-14 14:05:24 +0900913 spin_unlock(ws_lock);
Li Zefan261507a02010-12-17 14:21:50 +0800914
David Sterbafe308532017-05-31 17:14:56 +0200915 /*
916 * Allocation helpers call vmalloc that can't use GFP_NOFS, so we have
917 * to turn it off here because we might get called from the restricted
918 * context of btrfs_compress_bio/btrfs_compress_pages
919 */
920 nofs_flag = memalloc_nofs_save();
Timofey Titovets4e439a02017-09-28 17:33:36 +0300921 if (heuristic)
922 workspace = alloc_heuristic_ws();
923 else
924 workspace = btrfs_compress_op[idx]->alloc_workspace();
David Sterbafe308532017-05-31 17:14:56 +0200925 memalloc_nofs_restore(nofs_flag);
926
Li Zefan261507a02010-12-17 14:21:50 +0800927 if (IS_ERR(workspace)) {
David Sterba6ac10a62016-04-27 02:15:15 +0200928 atomic_dec(total_ws);
Byongho Leed9187642015-10-14 14:05:24 +0900929 wake_up(ws_wait);
David Sterbae721e492016-04-27 02:41:17 +0200930
931 /*
932 * Do not return the error but go back to waiting. There's a
933 * workspace preallocated for each type and the compression
934 * time is bounded so we get to a workspace eventually. This
935 * makes our caller's life easier.
David Sterba523567162016-04-27 03:07:39 +0200936 *
937 * To prevent silent and low-probability deadlocks (when the
938 * initial preallocation fails), check if there are any
939 * workspaces at all.
David Sterbae721e492016-04-27 02:41:17 +0200940 */
David Sterba523567162016-04-27 03:07:39 +0200941 if (atomic_read(total_ws) == 0) {
942 static DEFINE_RATELIMIT_STATE(_rs,
943 /* once per minute */ 60 * HZ,
944 /* no burst */ 1);
945
946 if (__ratelimit(&_rs)) {
Jeff Mahoneyab8d0fc2016-09-20 10:05:02 -0400947 pr_warn("BTRFS: no compression workspaces, low memory, retrying\n");
David Sterba523567162016-04-27 03:07:39 +0200948 }
949 }
David Sterbae721e492016-04-27 02:41:17 +0200950 goto again;
Li Zefan261507a02010-12-17 14:21:50 +0800951 }
952 return workspace;
953}
954
Timofey Titovets4e439a02017-09-28 17:33:36 +0300955static struct list_head *find_workspace(int type)
956{
957 return __find_workspace(type, false);
958}
959
Li Zefan261507a02010-12-17 14:21:50 +0800960/*
961 * put a workspace struct back on the list or free it if we have enough
962 * idle ones sitting around
963 */
Timofey Titovets4e439a02017-09-28 17:33:36 +0300964static void __free_workspace(int type, struct list_head *workspace,
965 bool heuristic)
Li Zefan261507a02010-12-17 14:21:50 +0800966{
967 int idx = type - 1;
Timofey Titovets4e439a02017-09-28 17:33:36 +0300968 struct list_head *idle_ws;
969 spinlock_t *ws_lock;
970 atomic_t *total_ws;
971 wait_queue_head_t *ws_wait;
972 int *free_ws;
973
974 if (heuristic) {
975 idle_ws = &btrfs_heuristic_ws.idle_ws;
976 ws_lock = &btrfs_heuristic_ws.ws_lock;
977 total_ws = &btrfs_heuristic_ws.total_ws;
978 ws_wait = &btrfs_heuristic_ws.ws_wait;
979 free_ws = &btrfs_heuristic_ws.free_ws;
980 } else {
981 idle_ws = &btrfs_comp_ws[idx].idle_ws;
982 ws_lock = &btrfs_comp_ws[idx].ws_lock;
983 total_ws = &btrfs_comp_ws[idx].total_ws;
984 ws_wait = &btrfs_comp_ws[idx].ws_wait;
985 free_ws = &btrfs_comp_ws[idx].free_ws;
986 }
Li Zefan261507a02010-12-17 14:21:50 +0800987
Byongho Leed9187642015-10-14 14:05:24 +0900988 spin_lock(ws_lock);
Nick Terrell26b28dc2017-06-29 10:57:26 -0700989 if (*free_ws <= num_online_cpus()) {
Byongho Leed9187642015-10-14 14:05:24 +0900990 list_add(workspace, idle_ws);
David Sterba6ac10a62016-04-27 02:15:15 +0200991 (*free_ws)++;
Byongho Leed9187642015-10-14 14:05:24 +0900992 spin_unlock(ws_lock);
Li Zefan261507a02010-12-17 14:21:50 +0800993 goto wake;
994 }
Byongho Leed9187642015-10-14 14:05:24 +0900995 spin_unlock(ws_lock);
Li Zefan261507a02010-12-17 14:21:50 +0800996
Timofey Titovets4e439a02017-09-28 17:33:36 +0300997 if (heuristic)
998 free_heuristic_ws(workspace);
999 else
1000 btrfs_compress_op[idx]->free_workspace(workspace);
David Sterba6ac10a62016-04-27 02:15:15 +02001001 atomic_dec(total_ws);
Li Zefan261507a02010-12-17 14:21:50 +08001002wake:
David Sterbaa83342a2015-02-16 19:36:47 +01001003 /*
1004 * Make sure counter is updated before we wake up waiters.
1005 */
Josef Bacik66657b32012-08-01 15:36:24 -04001006 smp_mb();
Byongho Leed9187642015-10-14 14:05:24 +09001007 if (waitqueue_active(ws_wait))
1008 wake_up(ws_wait);
Li Zefan261507a02010-12-17 14:21:50 +08001009}
1010
Timofey Titovets4e439a02017-09-28 17:33:36 +03001011static void free_workspace(int type, struct list_head *ws)
1012{
1013 return __free_workspace(type, ws, false);
1014}
1015
Li Zefan261507a02010-12-17 14:21:50 +08001016/*
1017 * cleanup function for module exit
1018 */
1019static void free_workspaces(void)
1020{
1021 struct list_head *workspace;
1022 int i;
1023
Timofey Titovets4e439a02017-09-28 17:33:36 +03001024 while (!list_empty(&btrfs_heuristic_ws.idle_ws)) {
1025 workspace = btrfs_heuristic_ws.idle_ws.next;
1026 list_del(workspace);
1027 free_heuristic_ws(workspace);
1028 atomic_dec(&btrfs_heuristic_ws.total_ws);
1029 }
1030
Li Zefan261507a02010-12-17 14:21:50 +08001031 for (i = 0; i < BTRFS_COMPRESS_TYPES; i++) {
Byongho Leed9187642015-10-14 14:05:24 +09001032 while (!list_empty(&btrfs_comp_ws[i].idle_ws)) {
1033 workspace = btrfs_comp_ws[i].idle_ws.next;
Li Zefan261507a02010-12-17 14:21:50 +08001034 list_del(workspace);
1035 btrfs_compress_op[i]->free_workspace(workspace);
David Sterba6ac10a62016-04-27 02:15:15 +02001036 atomic_dec(&btrfs_comp_ws[i].total_ws);
Li Zefan261507a02010-12-17 14:21:50 +08001037 }
1038 }
1039}
1040
1041/*
David Sterba38c31462017-02-14 19:04:07 +01001042 * Given an address space and start and length, compress the bytes into @pages
1043 * that are allocated on demand.
Li Zefan261507a02010-12-17 14:21:50 +08001044 *
David Sterbaf51d2b52017-09-15 17:36:57 +02001045 * @type_level is encoded algorithm and level, where level 0 means whatever
1046 * default the algorithm chooses and is opaque here;
1047 * - compression algo are 0-3
1048 * - the level are bits 4-7
1049 *
David Sterba4d3a8002017-02-14 19:04:07 +01001050 * @out_pages is an in/out parameter, holds maximum number of pages to allocate
1051 * and returns number of actually allocated pages
Li Zefan261507a02010-12-17 14:21:50 +08001052 *
David Sterba38c31462017-02-14 19:04:07 +01001053 * @total_in is used to return the number of bytes actually read. It
1054 * may be smaller than the input length if we had to exit early because we
Li Zefan261507a02010-12-17 14:21:50 +08001055 * ran out of room in the pages array or because we cross the
1056 * max_out threshold.
1057 *
David Sterba38c31462017-02-14 19:04:07 +01001058 * @total_out is an in/out parameter, must be set to the input length and will
1059 * be also used to return the total number of compressed bytes
Li Zefan261507a02010-12-17 14:21:50 +08001060 *
David Sterba38c31462017-02-14 19:04:07 +01001061 * @max_out tells us the max number of bytes that we're allowed to
Li Zefan261507a02010-12-17 14:21:50 +08001062 * stuff into pages
1063 */
David Sterbaf51d2b52017-09-15 17:36:57 +02001064int btrfs_compress_pages(unsigned int type_level, struct address_space *mapping,
David Sterba38c31462017-02-14 19:04:07 +01001065 u64 start, struct page **pages,
Li Zefan261507a02010-12-17 14:21:50 +08001066 unsigned long *out_pages,
1067 unsigned long *total_in,
David Sterbae5d74902017-02-14 19:45:05 +01001068 unsigned long *total_out)
Li Zefan261507a02010-12-17 14:21:50 +08001069{
1070 struct list_head *workspace;
1071 int ret;
David Sterbaf51d2b52017-09-15 17:36:57 +02001072 int type = type_level & 0xF;
Li Zefan261507a02010-12-17 14:21:50 +08001073
1074 workspace = find_workspace(type);
Li Zefan261507a02010-12-17 14:21:50 +08001075
David Sterbaf51d2b52017-09-15 17:36:57 +02001076 btrfs_compress_op[type - 1]->set_level(workspace, type_level);
Li Zefan261507a02010-12-17 14:21:50 +08001077 ret = btrfs_compress_op[type-1]->compress_pages(workspace, mapping,
David Sterba38c31462017-02-14 19:04:07 +01001078 start, pages,
David Sterba4d3a8002017-02-14 19:04:07 +01001079 out_pages,
David Sterbae5d74902017-02-14 19:45:05 +01001080 total_in, total_out);
Li Zefan261507a02010-12-17 14:21:50 +08001081 free_workspace(type, workspace);
1082 return ret;
1083}
1084
1085/*
1086 * pages_in is an array of pages with compressed data.
1087 *
1088 * disk_start is the starting logical offset of this array in the file
1089 *
Christoph Hellwig974b1ad2016-11-25 09:07:46 +01001090 * orig_bio contains the pages from the file that we want to decompress into
Li Zefan261507a02010-12-17 14:21:50 +08001091 *
1092 * srclen is the number of bytes in pages_in
1093 *
1094 * The basic idea is that we have a bio that was created by readpages.
1095 * The pages in the bio are for the uncompressed data, and they may not
1096 * be contiguous. They all correspond to the range of bytes covered by
1097 * the compressed extent.
1098 */
Anand Jain8140dc32017-05-26 15:44:58 +08001099static int btrfs_decompress_bio(struct compressed_bio *cb)
Li Zefan261507a02010-12-17 14:21:50 +08001100{
1101 struct list_head *workspace;
1102 int ret;
Anand Jain8140dc32017-05-26 15:44:58 +08001103 int type = cb->compress_type;
Li Zefan261507a02010-12-17 14:21:50 +08001104
1105 workspace = find_workspace(type);
Anand Jaine1ddce72017-05-26 15:44:59 +08001106 ret = btrfs_compress_op[type - 1]->decompress_bio(workspace, cb);
Li Zefan261507a02010-12-17 14:21:50 +08001107 free_workspace(type, workspace);
Anand Jaine1ddce72017-05-26 15:44:59 +08001108
Li Zefan261507a02010-12-17 14:21:50 +08001109 return ret;
1110}
1111
1112/*
1113 * a less complex decompression routine. Our compressed data fits in a
1114 * single page, and we want to read a single page out of it.
1115 * start_byte tells us the offset into the compressed data we're interested in
1116 */
1117int btrfs_decompress(int type, unsigned char *data_in, struct page *dest_page,
1118 unsigned long start_byte, size_t srclen, size_t destlen)
1119{
1120 struct list_head *workspace;
1121 int ret;
1122
1123 workspace = find_workspace(type);
Li Zefan261507a02010-12-17 14:21:50 +08001124
1125 ret = btrfs_compress_op[type-1]->decompress(workspace, data_in,
1126 dest_page, start_byte,
1127 srclen, destlen);
1128
1129 free_workspace(type, workspace);
1130 return ret;
1131}
1132
Alexey Charkov8e4eef72011-02-02 21:15:35 +00001133void btrfs_exit_compress(void)
Li Zefan261507a02010-12-17 14:21:50 +08001134{
1135 free_workspaces();
1136}
Li Zefan3a39c182010-11-08 15:22:19 +08001137
1138/*
1139 * Copy uncompressed data from working buffer to pages.
1140 *
1141 * buf_start is the byte offset we're of the start of our workspace buffer.
1142 *
1143 * total_out is the last byte of the buffer
1144 */
David Sterba14a33572017-02-14 17:58:04 +01001145int btrfs_decompress_buf2page(const char *buf, unsigned long buf_start,
Li Zefan3a39c182010-11-08 15:22:19 +08001146 unsigned long total_out, u64 disk_start,
Christoph Hellwig974b1ad2016-11-25 09:07:46 +01001147 struct bio *bio)
Li Zefan3a39c182010-11-08 15:22:19 +08001148{
1149 unsigned long buf_offset;
1150 unsigned long current_buf_start;
1151 unsigned long start_byte;
Omar Sandoval6e78b3f2017-02-10 15:03:35 -08001152 unsigned long prev_start_byte;
Li Zefan3a39c182010-11-08 15:22:19 +08001153 unsigned long working_bytes = total_out - buf_start;
1154 unsigned long bytes;
1155 char *kaddr;
Christoph Hellwig974b1ad2016-11-25 09:07:46 +01001156 struct bio_vec bvec = bio_iter_iovec(bio, bio->bi_iter);
Li Zefan3a39c182010-11-08 15:22:19 +08001157
1158 /*
1159 * start byte is the first byte of the page we're currently
1160 * copying into relative to the start of the compressed data.
1161 */
Christoph Hellwig974b1ad2016-11-25 09:07:46 +01001162 start_byte = page_offset(bvec.bv_page) - disk_start;
Li Zefan3a39c182010-11-08 15:22:19 +08001163
1164 /* we haven't yet hit data corresponding to this page */
1165 if (total_out <= start_byte)
1166 return 1;
1167
1168 /*
1169 * the start of the data we care about is offset into
1170 * the middle of our working buffer
1171 */
1172 if (total_out > start_byte && buf_start < start_byte) {
1173 buf_offset = start_byte - buf_start;
1174 working_bytes -= buf_offset;
1175 } else {
1176 buf_offset = 0;
1177 }
1178 current_buf_start = buf_start;
1179
1180 /* copy bytes from the working buffer into the pages */
1181 while (working_bytes > 0) {
Christoph Hellwig974b1ad2016-11-25 09:07:46 +01001182 bytes = min_t(unsigned long, bvec.bv_len,
1183 PAGE_SIZE - buf_offset);
Li Zefan3a39c182010-11-08 15:22:19 +08001184 bytes = min(bytes, working_bytes);
Li Zefan3a39c182010-11-08 15:22:19 +08001185
Christoph Hellwig974b1ad2016-11-25 09:07:46 +01001186 kaddr = kmap_atomic(bvec.bv_page);
1187 memcpy(kaddr + bvec.bv_offset, buf + buf_offset, bytes);
1188 kunmap_atomic(kaddr);
1189 flush_dcache_page(bvec.bv_page);
1190
Li Zefan3a39c182010-11-08 15:22:19 +08001191 buf_offset += bytes;
1192 working_bytes -= bytes;
1193 current_buf_start += bytes;
1194
1195 /* check if we need to pick another page */
Christoph Hellwig974b1ad2016-11-25 09:07:46 +01001196 bio_advance(bio, bytes);
1197 if (!bio->bi_iter.bi_size)
1198 return 0;
1199 bvec = bio_iter_iovec(bio, bio->bi_iter);
Omar Sandoval6e78b3f2017-02-10 15:03:35 -08001200 prev_start_byte = start_byte;
Christoph Hellwig974b1ad2016-11-25 09:07:46 +01001201 start_byte = page_offset(bvec.bv_page) - disk_start;
Li Zefan3a39c182010-11-08 15:22:19 +08001202
Christoph Hellwig974b1ad2016-11-25 09:07:46 +01001203 /*
Omar Sandoval6e78b3f2017-02-10 15:03:35 -08001204 * We need to make sure we're only adjusting
1205 * our offset into compression working buffer when
1206 * we're switching pages. Otherwise we can incorrectly
1207 * keep copying when we were actually done.
Christoph Hellwig974b1ad2016-11-25 09:07:46 +01001208 */
Omar Sandoval6e78b3f2017-02-10 15:03:35 -08001209 if (start_byte != prev_start_byte) {
1210 /*
1211 * make sure our new page is covered by this
1212 * working buffer
1213 */
1214 if (total_out <= start_byte)
1215 return 1;
Li Zefan3a39c182010-11-08 15:22:19 +08001216
Omar Sandoval6e78b3f2017-02-10 15:03:35 -08001217 /*
1218 * the next page in the biovec might not be adjacent
1219 * to the last page, but it might still be found
1220 * inside this working buffer. bump our offset pointer
1221 */
1222 if (total_out > start_byte &&
1223 current_buf_start < start_byte) {
1224 buf_offset = start_byte - buf_start;
1225 working_bytes = total_out - start_byte;
1226 current_buf_start = buf_start + buf_offset;
1227 }
Li Zefan3a39c182010-11-08 15:22:19 +08001228 }
1229 }
1230
1231 return 1;
1232}
Timofey Titovetsc2fcdcd2017-07-17 16:52:58 +03001233
Timofey Titovets19562432017-10-08 16:11:59 +03001234/*
1235 * Shannon Entropy calculation
1236 *
1237 * Pure byte distribution analysis fails to determine compressiability of data.
1238 * Try calculating entropy to estimate the average minimum number of bits
1239 * needed to encode the sampled data.
1240 *
1241 * For convenience, return the percentage of needed bits, instead of amount of
1242 * bits directly.
1243 *
1244 * @ENTROPY_LVL_ACEPTABLE - below that threshold, sample has low byte entropy
1245 * and can be compressible with high probability
1246 *
1247 * @ENTROPY_LVL_HIGH - data are not compressible with high probability
1248 *
1249 * Use of ilog2() decreases precision, we lower the LVL to 5 to compensate.
1250 */
1251#define ENTROPY_LVL_ACEPTABLE (65)
1252#define ENTROPY_LVL_HIGH (80)
1253
1254/*
1255 * For increasead precision in shannon_entropy calculation,
1256 * let's do pow(n, M) to save more digits after comma:
1257 *
1258 * - maximum int bit length is 64
1259 * - ilog2(MAX_SAMPLE_SIZE) -> 13
1260 * - 13 * 4 = 52 < 64 -> M = 4
1261 *
1262 * So use pow(n, 4).
1263 */
1264static inline u32 ilog2_w(u64 n)
1265{
1266 return ilog2(n * n * n * n);
1267}
1268
1269static u32 shannon_entropy(struct heuristic_ws *ws)
1270{
1271 const u32 entropy_max = 8 * ilog2_w(2);
1272 u32 entropy_sum = 0;
1273 u32 p, p_base, sz_base;
1274 u32 i;
1275
1276 sz_base = ilog2_w(ws->sample_size);
1277 for (i = 0; i < BUCKET_SIZE && ws->bucket[i].count > 0; i++) {
1278 p = ws->bucket[i].count;
1279 p_base = ilog2_w(p);
1280 entropy_sum += p * (sz_base - p_base);
1281 }
1282
1283 entropy_sum /= ws->sample_size;
1284 return entropy_sum * 100 / entropy_max;
1285}
1286
Timofey Titovets440c8402017-12-04 00:30:33 +03001287#define RADIX_BASE 4U
1288#define COUNTERS_SIZE (1U << RADIX_BASE)
Timofey Titovets858177d2017-09-28 17:33:41 +03001289
Timofey Titovets440c8402017-12-04 00:30:33 +03001290static u8 get4bits(u64 num, int shift) {
1291 u8 low4bits;
1292
1293 num >>= shift;
1294 /* Reverse order */
1295 low4bits = (COUNTERS_SIZE - 1) - (num % COUNTERS_SIZE);
1296 return low4bits;
1297}
1298
1299static void copy_cell(void *dst, int dest_i, void *src, int src_i)
1300{
1301 struct bucket_item *dstv = (struct bucket_item *)dst;
1302 struct bucket_item *srcv = (struct bucket_item *)src;
1303 dstv[dest_i] = srcv[src_i];
1304}
1305
1306static u64 get_num(const void *a, int i)
1307{
1308 struct bucket_item *av = (struct bucket_item *)a;
1309 return av[i].count;
1310}
1311
1312/*
1313 * Use 4 bits as radix base
1314 * Use 16 u32 counters for calculating new possition in buf array
1315 *
1316 * @array - array that will be sorted
1317 * @array_buf - buffer array to store sorting results
1318 * must be equal in size to @array
1319 * @num - array size
1320 * @get_num - function to extract number from array
1321 * @copy_cell - function to copy data from array to array_buf and vice versa
1322 * @get4bits - function to get 4 bits from number at specified offset
1323 */
1324static void radix_sort(void *array, void *array_buf, int num,
1325 u64 (*get_num)(const void *, int i),
1326 void (*copy_cell)(void *dest, int dest_i,
1327 void* src, int src_i),
1328 u8 (*get4bits)(u64 num, int shift))
1329{
1330 u64 max_num;
1331 u64 buf_num;
1332 u32 counters[COUNTERS_SIZE];
1333 u32 new_addr;
1334 u32 addr;
1335 int bitlen;
1336 int shift;
1337 int i;
1338
1339 /*
1340 * Try avoid useless loop iterations for small numbers stored in big
1341 * counters. Example: 48 33 4 ... in 64bit array
1342 */
1343 max_num = get_num(array, 0);
1344 for (i = 1; i < num; i++) {
1345 buf_num = get_num(array, i);
1346 if (buf_num > max_num)
1347 max_num = buf_num;
1348 }
1349
1350 buf_num = ilog2(max_num);
1351 bitlen = ALIGN(buf_num, RADIX_BASE * 2);
1352
1353 shift = 0;
1354 while (shift < bitlen) {
1355 memset(counters, 0, sizeof(counters));
1356
1357 for (i = 0; i < num; i++) {
1358 buf_num = get_num(array, i);
1359 addr = get4bits(buf_num, shift);
1360 counters[addr]++;
1361 }
1362
1363 for (i = 1; i < COUNTERS_SIZE; i++)
1364 counters[i] += counters[i - 1];
1365
1366 for (i = num - 1; i >= 0; i--) {
1367 buf_num = get_num(array, i);
1368 addr = get4bits(buf_num, shift);
1369 counters[addr]--;
1370 new_addr = counters[addr];
1371 copy_cell(array_buf, new_addr, array, i);
1372 }
1373
1374 shift += RADIX_BASE;
1375
1376 /*
1377 * Normal radix expects to move data from a temporary array, to
1378 * the main one. But that requires some CPU time. Avoid that
1379 * by doing another sort iteration to original array instead of
1380 * memcpy()
1381 */
1382 memset(counters, 0, sizeof(counters));
1383
1384 for (i = 0; i < num; i ++) {
1385 buf_num = get_num(array_buf, i);
1386 addr = get4bits(buf_num, shift);
1387 counters[addr]++;
1388 }
1389
1390 for (i = 1; i < COUNTERS_SIZE; i++)
1391 counters[i] += counters[i - 1];
1392
1393 for (i = num - 1; i >= 0; i--) {
1394 buf_num = get_num(array_buf, i);
1395 addr = get4bits(buf_num, shift);
1396 counters[addr]--;
1397 new_addr = counters[addr];
1398 copy_cell(array, new_addr, array_buf, i);
1399 }
1400
1401 shift += RADIX_BASE;
1402 }
Timofey Titovets858177d2017-09-28 17:33:41 +03001403}
1404
1405/*
1406 * Size of the core byte set - how many bytes cover 90% of the sample
1407 *
1408 * There are several types of structured binary data that use nearly all byte
1409 * values. The distribution can be uniform and counts in all buckets will be
1410 * nearly the same (eg. encrypted data). Unlikely to be compressible.
1411 *
1412 * Other possibility is normal (Gaussian) distribution, where the data could
1413 * be potentially compressible, but we have to take a few more steps to decide
1414 * how much.
1415 *
1416 * @BYTE_CORE_SET_LOW - main part of byte values repeated frequently,
1417 * compression algo can easy fix that
1418 * @BYTE_CORE_SET_HIGH - data have uniform distribution and with high
1419 * probability is not compressible
1420 */
1421#define BYTE_CORE_SET_LOW (64)
1422#define BYTE_CORE_SET_HIGH (200)
1423
1424static int byte_core_set_size(struct heuristic_ws *ws)
1425{
1426 u32 i;
1427 u32 coreset_sum = 0;
1428 const u32 core_set_threshold = ws->sample_size * 90 / 100;
1429 struct bucket_item *bucket = ws->bucket;
1430
1431 /* Sort in reverse order */
Timofey Titovets440c8402017-12-04 00:30:33 +03001432 radix_sort(ws->bucket, ws->bucket_b, BUCKET_SIZE, get_num, copy_cell,
1433 get4bits);
Timofey Titovets858177d2017-09-28 17:33:41 +03001434
1435 for (i = 0; i < BYTE_CORE_SET_LOW; i++)
1436 coreset_sum += bucket[i].count;
1437
1438 if (coreset_sum > core_set_threshold)
1439 return i;
1440
1441 for (; i < BYTE_CORE_SET_HIGH && bucket[i].count > 0; i++) {
1442 coreset_sum += bucket[i].count;
1443 if (coreset_sum > core_set_threshold)
1444 break;
1445 }
1446
1447 return i;
1448}
1449
Timofey Titovetsa288e922017-09-28 17:33:40 +03001450/*
1451 * Count byte values in buckets.
1452 * This heuristic can detect textual data (configs, xml, json, html, etc).
1453 * Because in most text-like data byte set is restricted to limited number of
1454 * possible characters, and that restriction in most cases makes data easy to
1455 * compress.
1456 *
1457 * @BYTE_SET_THRESHOLD - consider all data within this byte set size:
1458 * less - compressible
1459 * more - need additional analysis
1460 */
1461#define BYTE_SET_THRESHOLD (64)
1462
1463static u32 byte_set_size(const struct heuristic_ws *ws)
1464{
1465 u32 i;
1466 u32 byte_set_size = 0;
1467
1468 for (i = 0; i < BYTE_SET_THRESHOLD; i++) {
1469 if (ws->bucket[i].count > 0)
1470 byte_set_size++;
1471 }
1472
1473 /*
1474 * Continue collecting count of byte values in buckets. If the byte
1475 * set size is bigger then the threshold, it's pointless to continue,
1476 * the detection technique would fail for this type of data.
1477 */
1478 for (; i < BUCKET_SIZE; i++) {
1479 if (ws->bucket[i].count > 0) {
1480 byte_set_size++;
1481 if (byte_set_size > BYTE_SET_THRESHOLD)
1482 return byte_set_size;
1483 }
1484 }
1485
1486 return byte_set_size;
1487}
1488
Timofey Titovets1fe4f6f2017-09-28 17:33:39 +03001489static bool sample_repeated_patterns(struct heuristic_ws *ws)
1490{
1491 const u32 half_of_sample = ws->sample_size / 2;
1492 const u8 *data = ws->sample;
1493
1494 return memcmp(&data[0], &data[half_of_sample], half_of_sample) == 0;
1495}
1496
Timofey Titovetsa440d482017-09-28 17:33:38 +03001497static void heuristic_collect_sample(struct inode *inode, u64 start, u64 end,
1498 struct heuristic_ws *ws)
1499{
1500 struct page *page;
1501 u64 index, index_end;
1502 u32 i, curr_sample_pos;
1503 u8 *in_data;
1504
1505 /*
1506 * Compression handles the input data by chunks of 128KiB
1507 * (defined by BTRFS_MAX_UNCOMPRESSED)
1508 *
1509 * We do the same for the heuristic and loop over the whole range.
1510 *
1511 * MAX_SAMPLE_SIZE - calculated under assumption that heuristic will
1512 * process no more than BTRFS_MAX_UNCOMPRESSED at a time.
1513 */
1514 if (end - start > BTRFS_MAX_UNCOMPRESSED)
1515 end = start + BTRFS_MAX_UNCOMPRESSED;
1516
1517 index = start >> PAGE_SHIFT;
1518 index_end = end >> PAGE_SHIFT;
1519
1520 /* Don't miss unaligned end */
1521 if (!IS_ALIGNED(end, PAGE_SIZE))
1522 index_end++;
1523
1524 curr_sample_pos = 0;
1525 while (index < index_end) {
1526 page = find_get_page(inode->i_mapping, index);
1527 in_data = kmap(page);
1528 /* Handle case where the start is not aligned to PAGE_SIZE */
1529 i = start % PAGE_SIZE;
1530 while (i < PAGE_SIZE - SAMPLING_READ_SIZE) {
1531 /* Don't sample any garbage from the last page */
1532 if (start > end - SAMPLING_READ_SIZE)
1533 break;
1534 memcpy(&ws->sample[curr_sample_pos], &in_data[i],
1535 SAMPLING_READ_SIZE);
1536 i += SAMPLING_INTERVAL;
1537 start += SAMPLING_INTERVAL;
1538 curr_sample_pos += SAMPLING_READ_SIZE;
1539 }
1540 kunmap(page);
1541 put_page(page);
1542
1543 index++;
1544 }
1545
1546 ws->sample_size = curr_sample_pos;
1547}
1548
Timofey Titovetsc2fcdcd2017-07-17 16:52:58 +03001549/*
1550 * Compression heuristic.
1551 *
1552 * For now is's a naive and optimistic 'return true', we'll extend the logic to
1553 * quickly (compared to direct compression) detect data characteristics
1554 * (compressible/uncompressible) to avoid wasting CPU time on uncompressible
1555 * data.
1556 *
1557 * The following types of analysis can be performed:
1558 * - detect mostly zero data
1559 * - detect data with low "byte set" size (text, etc)
1560 * - detect data with low/high "core byte" set
1561 *
1562 * Return non-zero if the compression should be done, 0 otherwise.
1563 */
1564int btrfs_compress_heuristic(struct inode *inode, u64 start, u64 end)
1565{
Timofey Titovets4e439a02017-09-28 17:33:36 +03001566 struct list_head *ws_list = __find_workspace(0, true);
1567 struct heuristic_ws *ws;
Timofey Titovetsa440d482017-09-28 17:33:38 +03001568 u32 i;
1569 u8 byte;
Timofey Titovets19562432017-10-08 16:11:59 +03001570 int ret = 0;
Timofey Titovetsc2fcdcd2017-07-17 16:52:58 +03001571
Timofey Titovets4e439a02017-09-28 17:33:36 +03001572 ws = list_entry(ws_list, struct heuristic_ws, list);
1573
Timofey Titovetsa440d482017-09-28 17:33:38 +03001574 heuristic_collect_sample(inode, start, end, ws);
1575
Timofey Titovets1fe4f6f2017-09-28 17:33:39 +03001576 if (sample_repeated_patterns(ws)) {
1577 ret = 1;
1578 goto out;
1579 }
1580
Timofey Titovetsa440d482017-09-28 17:33:38 +03001581 memset(ws->bucket, 0, sizeof(*ws->bucket)*BUCKET_SIZE);
1582
1583 for (i = 0; i < ws->sample_size; i++) {
1584 byte = ws->sample[i];
1585 ws->bucket[byte].count++;
Timofey Titovetsc2fcdcd2017-07-17 16:52:58 +03001586 }
1587
Timofey Titovetsa288e922017-09-28 17:33:40 +03001588 i = byte_set_size(ws);
1589 if (i < BYTE_SET_THRESHOLD) {
1590 ret = 2;
1591 goto out;
1592 }
1593
Timofey Titovets858177d2017-09-28 17:33:41 +03001594 i = byte_core_set_size(ws);
1595 if (i <= BYTE_CORE_SET_LOW) {
1596 ret = 3;
1597 goto out;
1598 }
1599
1600 if (i >= BYTE_CORE_SET_HIGH) {
1601 ret = 0;
1602 goto out;
1603 }
1604
Timofey Titovets19562432017-10-08 16:11:59 +03001605 i = shannon_entropy(ws);
1606 if (i <= ENTROPY_LVL_ACEPTABLE) {
1607 ret = 4;
1608 goto out;
1609 }
1610
1611 /*
1612 * For the levels below ENTROPY_LVL_HIGH, additional analysis would be
1613 * needed to give green light to compression.
1614 *
1615 * For now just assume that compression at that level is not worth the
1616 * resources because:
1617 *
1618 * 1. it is possible to defrag the data later
1619 *
1620 * 2. the data would turn out to be hardly compressible, eg. 150 byte
1621 * values, every bucket has counter at level ~54. The heuristic would
1622 * be confused. This can happen when data have some internal repeated
1623 * patterns like "abbacbbc...". This can be detected by analyzing
1624 * pairs of bytes, which is too costly.
1625 */
1626 if (i < ENTROPY_LVL_HIGH) {
1627 ret = 5;
1628 goto out;
1629 } else {
1630 ret = 0;
1631 goto out;
1632 }
1633
Timofey Titovets1fe4f6f2017-09-28 17:33:39 +03001634out:
Timofey Titovets4e439a02017-09-28 17:33:36 +03001635 __free_workspace(0, ws_list, true);
Timofey Titovetsc2fcdcd2017-07-17 16:52:58 +03001636 return ret;
1637}
David Sterbaf51d2b52017-09-15 17:36:57 +02001638
1639unsigned int btrfs_compress_str2level(const char *str)
1640{
1641 if (strncmp(str, "zlib", 4) != 0)
1642 return 0;
1643
Adam Borowskifa4d8852017-09-15 17:36:58 +02001644 /* Accepted form: zlib:1 up to zlib:9 and nothing left after the number */
1645 if (str[4] == ':' && '1' <= str[5] && str[5] <= '9' && str[6] == 0)
1646 return str[5] - '0';
David Sterbaf51d2b52017-09-15 17:36:57 +02001647
Qu Wenruoeae8d822017-11-06 10:43:18 +08001648 return BTRFS_ZLIB_DEFAULT_LEVEL;
David Sterbaf51d2b52017-09-15 17:36:57 +02001649}