compression.c 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632
  1. /*
  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. #include <linux/kernel.h>
  19. #include <linux/bio.h>
  20. #include <linux/buffer_head.h>
  21. #include <linux/file.h>
  22. #include <linux/fs.h>
  23. #include <linux/pagemap.h>
  24. #include <linux/highmem.h>
  25. #include <linux/time.h>
  26. #include <linux/init.h>
  27. #include <linux/string.h>
  28. #include <linux/backing-dev.h>
  29. #include <linux/mpage.h>
  30. #include <linux/swap.h>
  31. #include <linux/writeback.h>
  32. #include <linux/bit_spinlock.h>
  33. #include <linux/slab.h>
  34. #include <linux/sched/mm.h>
  35. #include <linux/log2.h>
  36. #include "ctree.h"
  37. #include "disk-io.h"
  38. #include "transaction.h"
  39. #include "btrfs_inode.h"
  40. #include "volumes.h"
  41. #include "ordered-data.h"
  42. #include "compression.h"
  43. #include "extent_io.h"
  44. #include "extent_map.h"
  45. static const char* const btrfs_compress_types[] = { "", "zlib", "lzo", "zstd" };
  46. const char* btrfs_compress_type2str(enum btrfs_compression_type type)
  47. {
  48. switch (type) {
  49. case BTRFS_COMPRESS_ZLIB:
  50. case BTRFS_COMPRESS_LZO:
  51. case BTRFS_COMPRESS_ZSTD:
  52. case BTRFS_COMPRESS_NONE:
  53. return btrfs_compress_types[type];
  54. }
  55. return NULL;
  56. }
  57. static int btrfs_decompress_bio(struct compressed_bio *cb);
  58. static inline int compressed_bio_size(struct btrfs_fs_info *fs_info,
  59. unsigned long disk_size)
  60. {
  61. u16 csum_size = btrfs_super_csum_size(fs_info->super_copy);
  62. return sizeof(struct compressed_bio) +
  63. (DIV_ROUND_UP(disk_size, fs_info->sectorsize)) * csum_size;
  64. }
  65. static int check_compressed_csum(struct btrfs_inode *inode,
  66. struct compressed_bio *cb,
  67. u64 disk_start)
  68. {
  69. int ret;
  70. struct page *page;
  71. unsigned long i;
  72. char *kaddr;
  73. u32 csum;
  74. u32 *cb_sum = &cb->sums;
  75. if (inode->flags & BTRFS_INODE_NODATASUM)
  76. return 0;
  77. for (i = 0; i < cb->nr_pages; i++) {
  78. page = cb->compressed_pages[i];
  79. csum = ~(u32)0;
  80. kaddr = kmap_atomic(page);
  81. csum = btrfs_csum_data(kaddr, csum, PAGE_SIZE);
  82. btrfs_csum_final(csum, (u8 *)&csum);
  83. kunmap_atomic(kaddr);
  84. if (csum != *cb_sum) {
  85. btrfs_print_data_csum_error(inode, disk_start, csum,
  86. *cb_sum, cb->mirror_num);
  87. ret = -EIO;
  88. goto fail;
  89. }
  90. cb_sum++;
  91. }
  92. ret = 0;
  93. fail:
  94. return ret;
  95. }
  96. /* 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. */
  106. static void end_compressed_bio_read(struct bio *bio)
  107. {
  108. struct compressed_bio *cb = bio->bi_private;
  109. struct inode *inode;
  110. struct page *page;
  111. unsigned long index;
  112. unsigned int mirror = btrfs_io_bio(bio)->mirror_num;
  113. int ret = 0;
  114. if (bio->bi_status)
  115. cb->errors = 1;
  116. /* if there are more bios still pending for this compressed
  117. * extent, just exit
  118. */
  119. if (!refcount_dec_and_test(&cb->pending_bios))
  120. goto out;
  121. /*
  122. * Record the correct mirror_num in cb->orig_bio so that
  123. * read-repair can work properly.
  124. */
  125. ASSERT(btrfs_io_bio(cb->orig_bio));
  126. btrfs_io_bio(cb->orig_bio)->mirror_num = mirror;
  127. cb->mirror_num = mirror;
  128. /*
  129. * Some IO in this cb have failed, just skip checksum as there
  130. * is no way it could be correct.
  131. */
  132. if (cb->errors == 1)
  133. goto csum_failed;
  134. inode = cb->inode;
  135. ret = check_compressed_csum(BTRFS_I(inode), cb,
  136. (u64)bio->bi_iter.bi_sector << 9);
  137. if (ret)
  138. goto csum_failed;
  139. /* ok, we're the last bio for this extent, lets start
  140. * the decompression.
  141. */
  142. ret = btrfs_decompress_bio(cb);
  143. csum_failed:
  144. if (ret)
  145. cb->errors = 1;
  146. /* release the compressed pages */
  147. index = 0;
  148. for (index = 0; index < cb->nr_pages; index++) {
  149. page = cb->compressed_pages[index];
  150. page->mapping = NULL;
  151. put_page(page);
  152. }
  153. /* do io completion on the original bio */
  154. if (cb->errors) {
  155. bio_io_error(cb->orig_bio);
  156. } else {
  157. int i;
  158. struct bio_vec *bvec;
  159. /*
  160. * we have verified the checksum already, set page
  161. * checked so the end_io handlers know about it
  162. */
  163. ASSERT(!bio_flagged(bio, BIO_CLONED));
  164. bio_for_each_segment_all(bvec, cb->orig_bio, i)
  165. SetPageChecked(bvec->bv_page);
  166. bio_endio(cb->orig_bio);
  167. }
  168. /* finally free the cb struct */
  169. kfree(cb->compressed_pages);
  170. kfree(cb);
  171. out:
  172. bio_put(bio);
  173. }
  174. /*
  175. * Clear the writeback bits on all of the file
  176. * pages for a compressed write
  177. */
  178. static noinline void end_compressed_writeback(struct inode *inode,
  179. const struct compressed_bio *cb)
  180. {
  181. unsigned long index = cb->start >> PAGE_SHIFT;
  182. unsigned long end_index = (cb->start + cb->len - 1) >> PAGE_SHIFT;
  183. struct page *pages[16];
  184. unsigned long nr_pages = end_index - index + 1;
  185. int i;
  186. int ret;
  187. if (cb->errors)
  188. mapping_set_error(inode->i_mapping, -EIO);
  189. while (nr_pages > 0) {
  190. ret = find_get_pages_contig(inode->i_mapping, index,
  191. min_t(unsigned long,
  192. nr_pages, ARRAY_SIZE(pages)), pages);
  193. if (ret == 0) {
  194. nr_pages -= 1;
  195. index += 1;
  196. continue;
  197. }
  198. for (i = 0; i < ret; i++) {
  199. if (cb->errors)
  200. SetPageError(pages[i]);
  201. end_page_writeback(pages[i]);
  202. put_page(pages[i]);
  203. }
  204. nr_pages -= ret;
  205. index += ret;
  206. }
  207. /* the inode may be gone now */
  208. }
  209. /*
  210. * do the cleanup once all the compressed pages hit the disk.
  211. * This will clear writeback on the file pages and free the compressed
  212. * pages.
  213. *
  214. * This also calls the writeback end hooks for the file pages so that
  215. * metadata and checksums can be updated in the file.
  216. */
  217. static void end_compressed_bio_write(struct bio *bio)
  218. {
  219. struct extent_io_tree *tree;
  220. struct compressed_bio *cb = bio->bi_private;
  221. struct inode *inode;
  222. struct page *page;
  223. unsigned long index;
  224. if (bio->bi_status)
  225. cb->errors = 1;
  226. /* if there are more bios still pending for this compressed
  227. * extent, just exit
  228. */
  229. if (!refcount_dec_and_test(&cb->pending_bios))
  230. goto out;
  231. /* ok, we're the last bio for this extent, step one is to
  232. * call back into the FS and do all the end_io operations
  233. */
  234. inode = cb->inode;
  235. tree = &BTRFS_I(inode)->io_tree;
  236. cb->compressed_pages[0]->mapping = cb->inode->i_mapping;
  237. tree->ops->writepage_end_io_hook(cb->compressed_pages[0],
  238. cb->start,
  239. cb->start + cb->len - 1,
  240. NULL,
  241. bio->bi_status ?
  242. BLK_STS_OK : BLK_STS_NOTSUPP);
  243. cb->compressed_pages[0]->mapping = NULL;
  244. end_compressed_writeback(inode, cb);
  245. /* note, our inode could be gone now */
  246. /*
  247. * release the compressed pages, these came from alloc_page and
  248. * are not attached to the inode at all
  249. */
  250. index = 0;
  251. for (index = 0; index < cb->nr_pages; index++) {
  252. page = cb->compressed_pages[index];
  253. page->mapping = NULL;
  254. put_page(page);
  255. }
  256. /* finally free the cb struct */
  257. kfree(cb->compressed_pages);
  258. kfree(cb);
  259. out:
  260. bio_put(bio);
  261. }
  262. /*
  263. * worker function to build and submit bios for previously compressed pages.
  264. * The corresponding pages in the inode should be marked for writeback
  265. * and the compressed pages should have a reference on them for dropping
  266. * when the IO is complete.
  267. *
  268. * This also checksums the file bytes and gets things ready for
  269. * the end io hooks.
  270. */
  271. blk_status_t btrfs_submit_compressed_write(struct inode *inode, u64 start,
  272. unsigned long len, u64 disk_start,
  273. unsigned long compressed_len,
  274. struct page **compressed_pages,
  275. unsigned long nr_pages,
  276. unsigned int write_flags)
  277. {
  278. struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
  279. struct bio *bio = NULL;
  280. struct compressed_bio *cb;
  281. unsigned long bytes_left;
  282. struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
  283. int pg_index = 0;
  284. struct page *page;
  285. u64 first_byte = disk_start;
  286. struct block_device *bdev;
  287. blk_status_t ret;
  288. int skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
  289. WARN_ON(start & ((u64)PAGE_SIZE - 1));
  290. cb = kmalloc(compressed_bio_size(fs_info, compressed_len), GFP_NOFS);
  291. if (!cb)
  292. return BLK_STS_RESOURCE;
  293. refcount_set(&cb->pending_bios, 0);
  294. cb->errors = 0;
  295. cb->inode = inode;
  296. cb->start = start;
  297. cb->len = len;
  298. cb->mirror_num = 0;
  299. cb->compressed_pages = compressed_pages;
  300. cb->compressed_len = compressed_len;
  301. cb->orig_bio = NULL;
  302. cb->nr_pages = nr_pages;
  303. bdev = fs_info->fs_devices->latest_bdev;
  304. bio = btrfs_bio_alloc(bdev, first_byte);
  305. bio->bi_opf = REQ_OP_WRITE | write_flags;
  306. bio->bi_private = cb;
  307. bio->bi_end_io = end_compressed_bio_write;
  308. refcount_set(&cb->pending_bios, 1);
  309. /* create and submit bios for the compressed pages */
  310. bytes_left = compressed_len;
  311. for (pg_index = 0; pg_index < cb->nr_pages; pg_index++) {
  312. int submit = 0;
  313. page = compressed_pages[pg_index];
  314. page->mapping = inode->i_mapping;
  315. if (bio->bi_iter.bi_size)
  316. submit = io_tree->ops->merge_bio_hook(page, 0,
  317. PAGE_SIZE,
  318. bio, 0);
  319. page->mapping = NULL;
  320. if (submit || bio_add_page(bio, page, PAGE_SIZE, 0) <
  321. PAGE_SIZE) {
  322. /*
  323. * inc the count before we submit the bio so
  324. * we know the end IO handler won't happen before
  325. * we inc the count. Otherwise, the cb might get
  326. * freed before we're done setting it up
  327. */
  328. refcount_inc(&cb->pending_bios);
  329. ret = btrfs_bio_wq_end_io(fs_info, bio,
  330. BTRFS_WQ_ENDIO_DATA);
  331. BUG_ON(ret); /* -ENOMEM */
  332. if (!skip_sum) {
  333. ret = btrfs_csum_one_bio(inode, bio, start, 1);
  334. BUG_ON(ret); /* -ENOMEM */
  335. }
  336. ret = btrfs_map_bio(fs_info, bio, 0, 1);
  337. if (ret) {
  338. bio->bi_status = ret;
  339. bio_endio(bio);
  340. }
  341. bio = btrfs_bio_alloc(bdev, first_byte);
  342. bio->bi_opf = REQ_OP_WRITE | write_flags;
  343. bio->bi_private = cb;
  344. bio->bi_end_io = end_compressed_bio_write;
  345. bio_add_page(bio, page, PAGE_SIZE, 0);
  346. }
  347. if (bytes_left < PAGE_SIZE) {
  348. btrfs_info(fs_info,
  349. "bytes left %lu compress len %lu nr %lu",
  350. bytes_left, cb->compressed_len, cb->nr_pages);
  351. }
  352. bytes_left -= PAGE_SIZE;
  353. first_byte += PAGE_SIZE;
  354. cond_resched();
  355. }
  356. ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DATA);
  357. BUG_ON(ret); /* -ENOMEM */
  358. if (!skip_sum) {
  359. ret = btrfs_csum_one_bio(inode, bio, start, 1);
  360. BUG_ON(ret); /* -ENOMEM */
  361. }
  362. ret = btrfs_map_bio(fs_info, bio, 0, 1);
  363. if (ret) {
  364. bio->bi_status = ret;
  365. bio_endio(bio);
  366. }
  367. return 0;
  368. }
  369. static u64 bio_end_offset(struct bio *bio)
  370. {
  371. struct bio_vec *last = bio_last_bvec_all(bio);
  372. return page_offset(last->bv_page) + last->bv_len + last->bv_offset;
  373. }
  374. static noinline int add_ra_bio_pages(struct inode *inode,
  375. u64 compressed_end,
  376. struct compressed_bio *cb)
  377. {
  378. unsigned long end_index;
  379. unsigned long pg_index;
  380. u64 last_offset;
  381. u64 isize = i_size_read(inode);
  382. int ret;
  383. struct page *page;
  384. unsigned long nr_pages = 0;
  385. struct extent_map *em;
  386. struct address_space *mapping = inode->i_mapping;
  387. struct extent_map_tree *em_tree;
  388. struct extent_io_tree *tree;
  389. u64 end;
  390. int misses = 0;
  391. last_offset = bio_end_offset(cb->orig_bio);
  392. em_tree = &BTRFS_I(inode)->extent_tree;
  393. tree = &BTRFS_I(inode)->io_tree;
  394. if (isize == 0)
  395. return 0;
  396. end_index = (i_size_read(inode) - 1) >> PAGE_SHIFT;
  397. while (last_offset < compressed_end) {
  398. pg_index = last_offset >> PAGE_SHIFT;
  399. if (pg_index > end_index)
  400. break;
  401. rcu_read_lock();
  402. page = radix_tree_lookup(&mapping->i_pages, pg_index);
  403. rcu_read_unlock();
  404. if (page && !radix_tree_exceptional_entry(page)) {
  405. misses++;
  406. if (misses > 4)
  407. break;
  408. goto next;
  409. }
  410. page = __page_cache_alloc(mapping_gfp_constraint(mapping,
  411. ~__GFP_FS));
  412. if (!page)
  413. break;
  414. if (add_to_page_cache_lru(page, mapping, pg_index, GFP_NOFS)) {
  415. put_page(page);
  416. goto next;
  417. }
  418. end = last_offset + PAGE_SIZE - 1;
  419. /*
  420. * at this point, we have a locked page in the page cache
  421. * for these bytes in the file. But, we have to make
  422. * sure they map to this compressed extent on disk.
  423. */
  424. set_page_extent_mapped(page);
  425. lock_extent(tree, last_offset, end);
  426. read_lock(&em_tree->lock);
  427. em = lookup_extent_mapping(em_tree, last_offset,
  428. PAGE_SIZE);
  429. read_unlock(&em_tree->lock);
  430. if (!em || last_offset < em->start ||
  431. (last_offset + PAGE_SIZE > extent_map_end(em)) ||
  432. (em->block_start >> 9) != cb->orig_bio->bi_iter.bi_sector) {
  433. free_extent_map(em);
  434. unlock_extent(tree, last_offset, end);
  435. unlock_page(page);
  436. put_page(page);
  437. break;
  438. }
  439. free_extent_map(em);
  440. if (page->index == end_index) {
  441. char *userpage;
  442. size_t zero_offset = isize & (PAGE_SIZE - 1);
  443. if (zero_offset) {
  444. int zeros;
  445. zeros = PAGE_SIZE - zero_offset;
  446. userpage = kmap_atomic(page);
  447. memset(userpage + zero_offset, 0, zeros);
  448. flush_dcache_page(page);
  449. kunmap_atomic(userpage);
  450. }
  451. }
  452. ret = bio_add_page(cb->orig_bio, page,
  453. PAGE_SIZE, 0);
  454. if (ret == PAGE_SIZE) {
  455. nr_pages++;
  456. put_page(page);
  457. } else {
  458. unlock_extent(tree, last_offset, end);
  459. unlock_page(page);
  460. put_page(page);
  461. break;
  462. }
  463. next:
  464. last_offset += PAGE_SIZE;
  465. }
  466. return 0;
  467. }
  468. /*
  469. * for a compressed read, the bio we get passed has all the inode pages
  470. * in it. We don't actually do IO on those pages but allocate new ones
  471. * to hold the compressed pages on disk.
  472. *
  473. * bio->bi_iter.bi_sector points to the compressed extent on disk
  474. * bio->bi_io_vec points to all of the inode pages
  475. *
  476. * After the compressed pages are read, we copy the bytes into the
  477. * bio we were passed and then call the bio end_io calls
  478. */
  479. blk_status_t btrfs_submit_compressed_read(struct inode *inode, struct bio *bio,
  480. int mirror_num, unsigned long bio_flags)
  481. {
  482. struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
  483. struct extent_io_tree *tree;
  484. struct extent_map_tree *em_tree;
  485. struct compressed_bio *cb;
  486. unsigned long compressed_len;
  487. unsigned long nr_pages;
  488. unsigned long pg_index;
  489. struct page *page;
  490. struct block_device *bdev;
  491. struct bio *comp_bio;
  492. u64 cur_disk_byte = (u64)bio->bi_iter.bi_sector << 9;
  493. u64 em_len;
  494. u64 em_start;
  495. struct extent_map *em;
  496. blk_status_t ret = BLK_STS_RESOURCE;
  497. int faili = 0;
  498. u32 *sums;
  499. tree = &BTRFS_I(inode)->io_tree;
  500. em_tree = &BTRFS_I(inode)->extent_tree;
  501. /* we need the actual starting offset of this extent in the file */
  502. read_lock(&em_tree->lock);
  503. em = lookup_extent_mapping(em_tree,
  504. page_offset(bio_first_page_all(bio)),
  505. PAGE_SIZE);
  506. read_unlock(&em_tree->lock);
  507. if (!em)
  508. return BLK_STS_IOERR;
  509. compressed_len = em->block_len;
  510. cb = kmalloc(compressed_bio_size(fs_info, compressed_len), GFP_NOFS);
  511. if (!cb)
  512. goto out;
  513. refcount_set(&cb->pending_bios, 0);
  514. cb->errors = 0;
  515. cb->inode = inode;
  516. cb->mirror_num = mirror_num;
  517. sums = &cb->sums;
  518. cb->start = em->orig_start;
  519. em_len = em->len;
  520. em_start = em->start;
  521. free_extent_map(em);
  522. em = NULL;
  523. cb->len = bio->bi_iter.bi_size;
  524. cb->compressed_len = compressed_len;
  525. cb->compress_type = extent_compress_type(bio_flags);
  526. cb->orig_bio = bio;
  527. nr_pages = DIV_ROUND_UP(compressed_len, PAGE_SIZE);
  528. cb->compressed_pages = kcalloc(nr_pages, sizeof(struct page *),
  529. GFP_NOFS);
  530. if (!cb->compressed_pages)
  531. goto fail1;
  532. bdev = fs_info->fs_devices->latest_bdev;
  533. for (pg_index = 0; pg_index < nr_pages; pg_index++) {
  534. cb->compressed_pages[pg_index] = alloc_page(GFP_NOFS |
  535. __GFP_HIGHMEM);
  536. if (!cb->compressed_pages[pg_index]) {
  537. faili = pg_index - 1;
  538. ret = BLK_STS_RESOURCE;
  539. goto fail2;
  540. }
  541. }
  542. faili = nr_pages - 1;
  543. cb->nr_pages = nr_pages;
  544. add_ra_bio_pages(inode, em_start + em_len, cb);
  545. /* include any pages we added in add_ra-bio_pages */
  546. cb->len = bio->bi_iter.bi_size;
  547. comp_bio = btrfs_bio_alloc(bdev, cur_disk_byte);
  548. bio_set_op_attrs (comp_bio, REQ_OP_READ, 0);
  549. comp_bio->bi_private = cb;
  550. comp_bio->bi_end_io = end_compressed_bio_read;
  551. refcount_set(&cb->pending_bios, 1);
  552. for (pg_index = 0; pg_index < nr_pages; pg_index++) {
  553. int submit = 0;
  554. page = cb->compressed_pages[pg_index];
  555. page->mapping = inode->i_mapping;
  556. page->index = em_start >> PAGE_SHIFT;
  557. if (comp_bio->bi_iter.bi_size)
  558. submit = tree->ops->merge_bio_hook(page, 0,
  559. PAGE_SIZE,
  560. comp_bio, 0);
  561. page->mapping = NULL;
  562. if (submit || bio_add_page(comp_bio, page, PAGE_SIZE, 0) <
  563. PAGE_SIZE) {
  564. ret = btrfs_bio_wq_end_io(fs_info, comp_bio,
  565. BTRFS_WQ_ENDIO_DATA);
  566. BUG_ON(ret); /* -ENOMEM */
  567. /*
  568. * inc the count before we submit the bio so
  569. * we know the end IO handler won't happen before
  570. * we inc the count. Otherwise, the cb might get
  571. * freed before we're done setting it up
  572. */
  573. refcount_inc(&cb->pending_bios);
  574. if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
  575. ret = btrfs_lookup_bio_sums(inode, comp_bio,
  576. sums);
  577. BUG_ON(ret); /* -ENOMEM */
  578. }
  579. sums += DIV_ROUND_UP(comp_bio->bi_iter.bi_size,
  580. fs_info->sectorsize);
  581. ret = btrfs_map_bio(fs_info, comp_bio, mirror_num, 0);
  582. if (ret) {
  583. comp_bio->bi_status = ret;
  584. bio_endio(comp_bio);
  585. }
  586. comp_bio = btrfs_bio_alloc(bdev, cur_disk_byte);
  587. bio_set_op_attrs(comp_bio, REQ_OP_READ, 0);
  588. comp_bio->bi_private = cb;
  589. comp_bio->bi_end_io = end_compressed_bio_read;
  590. bio_add_page(comp_bio, page, PAGE_SIZE, 0);
  591. }
  592. cur_disk_byte += PAGE_SIZE;
  593. }
  594. ret = btrfs_bio_wq_end_io(fs_info, comp_bio, BTRFS_WQ_ENDIO_DATA);
  595. BUG_ON(ret); /* -ENOMEM */
  596. if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
  597. ret = btrfs_lookup_bio_sums(inode, comp_bio, sums);
  598. BUG_ON(ret); /* -ENOMEM */
  599. }
  600. ret = btrfs_map_bio(fs_info, comp_bio, mirror_num, 0);
  601. if (ret) {
  602. comp_bio->bi_status = ret;
  603. bio_endio(comp_bio);
  604. }
  605. return 0;
  606. fail2:
  607. while (faili >= 0) {
  608. __free_page(cb->compressed_pages[faili]);
  609. faili--;
  610. }
  611. kfree(cb->compressed_pages);
  612. fail1:
  613. kfree(cb);
  614. out:
  615. free_extent_map(em);
  616. return ret;
  617. }
  618. /*
  619. * Heuristic uses systematic sampling to collect data from the input data
  620. * range, the logic can be tuned by the following constants:
  621. *
  622. * @SAMPLING_READ_SIZE - how many bytes will be copied from for each sample
  623. * @SAMPLING_INTERVAL - range from which the sampled data can be collected
  624. */
  625. #define SAMPLING_READ_SIZE (16)
  626. #define SAMPLING_INTERVAL (256)
  627. /*
  628. * For statistical analysis of the input data we consider bytes that form a
  629. * Galois Field of 256 objects. Each object has an attribute count, ie. how
  630. * many times the object appeared in the sample.
  631. */
  632. #define BUCKET_SIZE (256)
  633. /*
  634. * The size of the sample is based on a statistical sampling rule of thumb.
  635. * The common way is to perform sampling tests as long as the number of
  636. * elements in each cell is at least 5.
  637. *
  638. * Instead of 5, we choose 32 to obtain more accurate results.
  639. * If the data contain the maximum number of symbols, which is 256, we obtain a
  640. * sample size bound by 8192.
  641. *
  642. * For a sample of at most 8KB of data per data range: 16 consecutive bytes
  643. * from up to 512 locations.
  644. */
  645. #define MAX_SAMPLE_SIZE (BTRFS_MAX_UNCOMPRESSED * \
  646. SAMPLING_READ_SIZE / SAMPLING_INTERVAL)
  647. struct bucket_item {
  648. u32 count;
  649. };
  650. struct heuristic_ws {
  651. /* Partial copy of input data */
  652. u8 *sample;
  653. u32 sample_size;
  654. /* Buckets store counters for each byte value */
  655. struct bucket_item *bucket;
  656. /* Sorting buffer */
  657. struct bucket_item *bucket_b;
  658. struct list_head list;
  659. };
  660. static void free_heuristic_ws(struct list_head *ws)
  661. {
  662. struct heuristic_ws *workspace;
  663. workspace = list_entry(ws, struct heuristic_ws, list);
  664. kvfree(workspace->sample);
  665. kfree(workspace->bucket);
  666. kfree(workspace->bucket_b);
  667. kfree(workspace);
  668. }
  669. static struct list_head *alloc_heuristic_ws(void)
  670. {
  671. struct heuristic_ws *ws;
  672. ws = kzalloc(sizeof(*ws), GFP_KERNEL);
  673. if (!ws)
  674. return ERR_PTR(-ENOMEM);
  675. ws->sample = kvmalloc(MAX_SAMPLE_SIZE, GFP_KERNEL);
  676. if (!ws->sample)
  677. goto fail;
  678. ws->bucket = kcalloc(BUCKET_SIZE, sizeof(*ws->bucket), GFP_KERNEL);
  679. if (!ws->bucket)
  680. goto fail;
  681. ws->bucket_b = kcalloc(BUCKET_SIZE, sizeof(*ws->bucket_b), GFP_KERNEL);
  682. if (!ws->bucket_b)
  683. goto fail;
  684. INIT_LIST_HEAD(&ws->list);
  685. return &ws->list;
  686. fail:
  687. free_heuristic_ws(&ws->list);
  688. return ERR_PTR(-ENOMEM);
  689. }
  690. struct workspaces_list {
  691. struct list_head idle_ws;
  692. spinlock_t ws_lock;
  693. /* Number of free workspaces */
  694. int free_ws;
  695. /* Total number of allocated workspaces */
  696. atomic_t total_ws;
  697. /* Waiters for a free workspace */
  698. wait_queue_head_t ws_wait;
  699. };
  700. static struct workspaces_list btrfs_comp_ws[BTRFS_COMPRESS_TYPES];
  701. static struct workspaces_list btrfs_heuristic_ws;
  702. static const struct btrfs_compress_op * const btrfs_compress_op[] = {
  703. &btrfs_zlib_compress,
  704. &btrfs_lzo_compress,
  705. &btrfs_zstd_compress,
  706. };
  707. void __init btrfs_init_compress(void)
  708. {
  709. struct list_head *workspace;
  710. int i;
  711. INIT_LIST_HEAD(&btrfs_heuristic_ws.idle_ws);
  712. spin_lock_init(&btrfs_heuristic_ws.ws_lock);
  713. atomic_set(&btrfs_heuristic_ws.total_ws, 0);
  714. init_waitqueue_head(&btrfs_heuristic_ws.ws_wait);
  715. workspace = alloc_heuristic_ws();
  716. if (IS_ERR(workspace)) {
  717. pr_warn(
  718. "BTRFS: cannot preallocate heuristic workspace, will try later\n");
  719. } else {
  720. atomic_set(&btrfs_heuristic_ws.total_ws, 1);
  721. btrfs_heuristic_ws.free_ws = 1;
  722. list_add(workspace, &btrfs_heuristic_ws.idle_ws);
  723. }
  724. for (i = 0; i < BTRFS_COMPRESS_TYPES; i++) {
  725. INIT_LIST_HEAD(&btrfs_comp_ws[i].idle_ws);
  726. spin_lock_init(&btrfs_comp_ws[i].ws_lock);
  727. atomic_set(&btrfs_comp_ws[i].total_ws, 0);
  728. init_waitqueue_head(&btrfs_comp_ws[i].ws_wait);
  729. /*
  730. * Preallocate one workspace for each compression type so
  731. * we can guarantee forward progress in the worst case
  732. */
  733. workspace = btrfs_compress_op[i]->alloc_workspace();
  734. if (IS_ERR(workspace)) {
  735. pr_warn("BTRFS: cannot preallocate compression workspace, will try later\n");
  736. } else {
  737. atomic_set(&btrfs_comp_ws[i].total_ws, 1);
  738. btrfs_comp_ws[i].free_ws = 1;
  739. list_add(workspace, &btrfs_comp_ws[i].idle_ws);
  740. }
  741. }
  742. }
  743. /*
  744. * This finds an available workspace or allocates a new one.
  745. * If it's not possible to allocate a new one, waits until there's one.
  746. * Preallocation makes a forward progress guarantees and we do not return
  747. * errors.
  748. */
  749. static struct list_head *__find_workspace(int type, bool heuristic)
  750. {
  751. struct list_head *workspace;
  752. int cpus = num_online_cpus();
  753. int idx = type - 1;
  754. unsigned nofs_flag;
  755. struct list_head *idle_ws;
  756. spinlock_t *ws_lock;
  757. atomic_t *total_ws;
  758. wait_queue_head_t *ws_wait;
  759. int *free_ws;
  760. if (heuristic) {
  761. idle_ws = &btrfs_heuristic_ws.idle_ws;
  762. ws_lock = &btrfs_heuristic_ws.ws_lock;
  763. total_ws = &btrfs_heuristic_ws.total_ws;
  764. ws_wait = &btrfs_heuristic_ws.ws_wait;
  765. free_ws = &btrfs_heuristic_ws.free_ws;
  766. } else {
  767. idle_ws = &btrfs_comp_ws[idx].idle_ws;
  768. ws_lock = &btrfs_comp_ws[idx].ws_lock;
  769. total_ws = &btrfs_comp_ws[idx].total_ws;
  770. ws_wait = &btrfs_comp_ws[idx].ws_wait;
  771. free_ws = &btrfs_comp_ws[idx].free_ws;
  772. }
  773. again:
  774. spin_lock(ws_lock);
  775. if (!list_empty(idle_ws)) {
  776. workspace = idle_ws->next;
  777. list_del(workspace);
  778. (*free_ws)--;
  779. spin_unlock(ws_lock);
  780. return workspace;
  781. }
  782. if (atomic_read(total_ws) > cpus) {
  783. DEFINE_WAIT(wait);
  784. spin_unlock(ws_lock);
  785. prepare_to_wait(ws_wait, &wait, TASK_UNINTERRUPTIBLE);
  786. if (atomic_read(total_ws) > cpus && !*free_ws)
  787. schedule();
  788. finish_wait(ws_wait, &wait);
  789. goto again;
  790. }
  791. atomic_inc(total_ws);
  792. spin_unlock(ws_lock);
  793. /*
  794. * Allocation helpers call vmalloc that can't use GFP_NOFS, so we have
  795. * to turn it off here because we might get called from the restricted
  796. * context of btrfs_compress_bio/btrfs_compress_pages
  797. */
  798. nofs_flag = memalloc_nofs_save();
  799. if (heuristic)
  800. workspace = alloc_heuristic_ws();
  801. else
  802. workspace = btrfs_compress_op[idx]->alloc_workspace();
  803. memalloc_nofs_restore(nofs_flag);
  804. if (IS_ERR(workspace)) {
  805. atomic_dec(total_ws);
  806. wake_up(ws_wait);
  807. /*
  808. * Do not return the error but go back to waiting. There's a
  809. * workspace preallocated for each type and the compression
  810. * time is bounded so we get to a workspace eventually. This
  811. * makes our caller's life easier.
  812. *
  813. * To prevent silent and low-probability deadlocks (when the
  814. * initial preallocation fails), check if there are any
  815. * workspaces at all.
  816. */
  817. if (atomic_read(total_ws) == 0) {
  818. static DEFINE_RATELIMIT_STATE(_rs,
  819. /* once per minute */ 60 * HZ,
  820. /* no burst */ 1);
  821. if (__ratelimit(&_rs)) {
  822. pr_warn("BTRFS: no compression workspaces, low memory, retrying\n");
  823. }
  824. }
  825. goto again;
  826. }
  827. return workspace;
  828. }
  829. static struct list_head *find_workspace(int type)
  830. {
  831. return __find_workspace(type, false);
  832. }
  833. /*
  834. * put a workspace struct back on the list or free it if we have enough
  835. * idle ones sitting around
  836. */
  837. static void __free_workspace(int type, struct list_head *workspace,
  838. bool heuristic)
  839. {
  840. int idx = type - 1;
  841. struct list_head *idle_ws;
  842. spinlock_t *ws_lock;
  843. atomic_t *total_ws;
  844. wait_queue_head_t *ws_wait;
  845. int *free_ws;
  846. if (heuristic) {
  847. idle_ws = &btrfs_heuristic_ws.idle_ws;
  848. ws_lock = &btrfs_heuristic_ws.ws_lock;
  849. total_ws = &btrfs_heuristic_ws.total_ws;
  850. ws_wait = &btrfs_heuristic_ws.ws_wait;
  851. free_ws = &btrfs_heuristic_ws.free_ws;
  852. } else {
  853. idle_ws = &btrfs_comp_ws[idx].idle_ws;
  854. ws_lock = &btrfs_comp_ws[idx].ws_lock;
  855. total_ws = &btrfs_comp_ws[idx].total_ws;
  856. ws_wait = &btrfs_comp_ws[idx].ws_wait;
  857. free_ws = &btrfs_comp_ws[idx].free_ws;
  858. }
  859. spin_lock(ws_lock);
  860. if (*free_ws <= num_online_cpus()) {
  861. list_add(workspace, idle_ws);
  862. (*free_ws)++;
  863. spin_unlock(ws_lock);
  864. goto wake;
  865. }
  866. spin_unlock(ws_lock);
  867. if (heuristic)
  868. free_heuristic_ws(workspace);
  869. else
  870. btrfs_compress_op[idx]->free_workspace(workspace);
  871. atomic_dec(total_ws);
  872. wake:
  873. /*
  874. * Make sure counter is updated before we wake up waiters.
  875. */
  876. smp_mb();
  877. if (waitqueue_active(ws_wait))
  878. wake_up(ws_wait);
  879. }
  880. static void free_workspace(int type, struct list_head *ws)
  881. {
  882. return __free_workspace(type, ws, false);
  883. }
  884. /*
  885. * cleanup function for module exit
  886. */
  887. static void free_workspaces(void)
  888. {
  889. struct list_head *workspace;
  890. int i;
  891. while (!list_empty(&btrfs_heuristic_ws.idle_ws)) {
  892. workspace = btrfs_heuristic_ws.idle_ws.next;
  893. list_del(workspace);
  894. free_heuristic_ws(workspace);
  895. atomic_dec(&btrfs_heuristic_ws.total_ws);
  896. }
  897. for (i = 0; i < BTRFS_COMPRESS_TYPES; i++) {
  898. while (!list_empty(&btrfs_comp_ws[i].idle_ws)) {
  899. workspace = btrfs_comp_ws[i].idle_ws.next;
  900. list_del(workspace);
  901. btrfs_compress_op[i]->free_workspace(workspace);
  902. atomic_dec(&btrfs_comp_ws[i].total_ws);
  903. }
  904. }
  905. }
  906. /*
  907. * Given an address space and start and length, compress the bytes into @pages
  908. * that are allocated on demand.
  909. *
  910. * @type_level is encoded algorithm and level, where level 0 means whatever
  911. * default the algorithm chooses and is opaque here;
  912. * - compression algo are 0-3
  913. * - the level are bits 4-7
  914. *
  915. * @out_pages is an in/out parameter, holds maximum number of pages to allocate
  916. * and returns number of actually allocated pages
  917. *
  918. * @total_in is used to return the number of bytes actually read. It
  919. * may be smaller than the input length if we had to exit early because we
  920. * ran out of room in the pages array or because we cross the
  921. * max_out threshold.
  922. *
  923. * @total_out is an in/out parameter, must be set to the input length and will
  924. * be also used to return the total number of compressed bytes
  925. *
  926. * @max_out tells us the max number of bytes that we're allowed to
  927. * stuff into pages
  928. */
  929. int btrfs_compress_pages(unsigned int type_level, struct address_space *mapping,
  930. u64 start, struct page **pages,
  931. unsigned long *out_pages,
  932. unsigned long *total_in,
  933. unsigned long *total_out)
  934. {
  935. struct list_head *workspace;
  936. int ret;
  937. int type = type_level & 0xF;
  938. workspace = find_workspace(type);
  939. btrfs_compress_op[type - 1]->set_level(workspace, type_level);
  940. ret = btrfs_compress_op[type-1]->compress_pages(workspace, mapping,
  941. start, pages,
  942. out_pages,
  943. total_in, total_out);
  944. free_workspace(type, workspace);
  945. return ret;
  946. }
  947. /*
  948. * pages_in is an array of pages with compressed data.
  949. *
  950. * disk_start is the starting logical offset of this array in the file
  951. *
  952. * orig_bio contains the pages from the file that we want to decompress into
  953. *
  954. * srclen is the number of bytes in pages_in
  955. *
  956. * The basic idea is that we have a bio that was created by readpages.
  957. * The pages in the bio are for the uncompressed data, and they may not
  958. * be contiguous. They all correspond to the range of bytes covered by
  959. * the compressed extent.
  960. */
  961. static int btrfs_decompress_bio(struct compressed_bio *cb)
  962. {
  963. struct list_head *workspace;
  964. int ret;
  965. int type = cb->compress_type;
  966. workspace = find_workspace(type);
  967. ret = btrfs_compress_op[type - 1]->decompress_bio(workspace, cb);
  968. free_workspace(type, workspace);
  969. return ret;
  970. }
  971. /*
  972. * a less complex decompression routine. Our compressed data fits in a
  973. * single page, and we want to read a single page out of it.
  974. * start_byte tells us the offset into the compressed data we're interested in
  975. */
  976. int btrfs_decompress(int type, unsigned char *data_in, struct page *dest_page,
  977. unsigned long start_byte, size_t srclen, size_t destlen)
  978. {
  979. struct list_head *workspace;
  980. int ret;
  981. workspace = find_workspace(type);
  982. ret = btrfs_compress_op[type-1]->decompress(workspace, data_in,
  983. dest_page, start_byte,
  984. srclen, destlen);
  985. free_workspace(type, workspace);
  986. return ret;
  987. }
  988. void __cold btrfs_exit_compress(void)
  989. {
  990. free_workspaces();
  991. }
  992. /*
  993. * Copy uncompressed data from working buffer to pages.
  994. *
  995. * buf_start is the byte offset we're of the start of our workspace buffer.
  996. *
  997. * total_out is the last byte of the buffer
  998. */
  999. int btrfs_decompress_buf2page(const char *buf, unsigned long buf_start,
  1000. unsigned long total_out, u64 disk_start,
  1001. struct bio *bio)
  1002. {
  1003. unsigned long buf_offset;
  1004. unsigned long current_buf_start;
  1005. unsigned long start_byte;
  1006. unsigned long prev_start_byte;
  1007. unsigned long working_bytes = total_out - buf_start;
  1008. unsigned long bytes;
  1009. char *kaddr;
  1010. struct bio_vec bvec = bio_iter_iovec(bio, bio->bi_iter);
  1011. /*
  1012. * start byte is the first byte of the page we're currently
  1013. * copying into relative to the start of the compressed data.
  1014. */
  1015. start_byte = page_offset(bvec.bv_page) - disk_start;
  1016. /* we haven't yet hit data corresponding to this page */
  1017. if (total_out <= start_byte)
  1018. return 1;
  1019. /*
  1020. * the start of the data we care about is offset into
  1021. * the middle of our working buffer
  1022. */
  1023. if (total_out > start_byte && buf_start < start_byte) {
  1024. buf_offset = start_byte - buf_start;
  1025. working_bytes -= buf_offset;
  1026. } else {
  1027. buf_offset = 0;
  1028. }
  1029. current_buf_start = buf_start;
  1030. /* copy bytes from the working buffer into the pages */
  1031. while (working_bytes > 0) {
  1032. bytes = min_t(unsigned long, bvec.bv_len,
  1033. PAGE_SIZE - buf_offset);
  1034. bytes = min(bytes, working_bytes);
  1035. kaddr = kmap_atomic(bvec.bv_page);
  1036. memcpy(kaddr + bvec.bv_offset, buf + buf_offset, bytes);
  1037. kunmap_atomic(kaddr);
  1038. flush_dcache_page(bvec.bv_page);
  1039. buf_offset += bytes;
  1040. working_bytes -= bytes;
  1041. current_buf_start += bytes;
  1042. /* check if we need to pick another page */
  1043. bio_advance(bio, bytes);
  1044. if (!bio->bi_iter.bi_size)
  1045. return 0;
  1046. bvec = bio_iter_iovec(bio, bio->bi_iter);
  1047. prev_start_byte = start_byte;
  1048. start_byte = page_offset(bvec.bv_page) - disk_start;
  1049. /*
  1050. * We need to make sure we're only adjusting
  1051. * our offset into compression working buffer when
  1052. * we're switching pages. Otherwise we can incorrectly
  1053. * keep copying when we were actually done.
  1054. */
  1055. if (start_byte != prev_start_byte) {
  1056. /*
  1057. * make sure our new page is covered by this
  1058. * working buffer
  1059. */
  1060. if (total_out <= start_byte)
  1061. return 1;
  1062. /*
  1063. * the next page in the biovec might not be adjacent
  1064. * to the last page, but it might still be found
  1065. * inside this working buffer. bump our offset pointer
  1066. */
  1067. if (total_out > start_byte &&
  1068. current_buf_start < start_byte) {
  1069. buf_offset = start_byte - buf_start;
  1070. working_bytes = total_out - start_byte;
  1071. current_buf_start = buf_start + buf_offset;
  1072. }
  1073. }
  1074. }
  1075. return 1;
  1076. }
  1077. /*
  1078. * Shannon Entropy calculation
  1079. *
  1080. * Pure byte distribution analysis fails to determine compressiability of data.
  1081. * Try calculating entropy to estimate the average minimum number of bits
  1082. * needed to encode the sampled data.
  1083. *
  1084. * For convenience, return the percentage of needed bits, instead of amount of
  1085. * bits directly.
  1086. *
  1087. * @ENTROPY_LVL_ACEPTABLE - below that threshold, sample has low byte entropy
  1088. * and can be compressible with high probability
  1089. *
  1090. * @ENTROPY_LVL_HIGH - data are not compressible with high probability
  1091. *
  1092. * Use of ilog2() decreases precision, we lower the LVL to 5 to compensate.
  1093. */
  1094. #define ENTROPY_LVL_ACEPTABLE (65)
  1095. #define ENTROPY_LVL_HIGH (80)
  1096. /*
  1097. * For increasead precision in shannon_entropy calculation,
  1098. * let's do pow(n, M) to save more digits after comma:
  1099. *
  1100. * - maximum int bit length is 64
  1101. * - ilog2(MAX_SAMPLE_SIZE) -> 13
  1102. * - 13 * 4 = 52 < 64 -> M = 4
  1103. *
  1104. * So use pow(n, 4).
  1105. */
  1106. static inline u32 ilog2_w(u64 n)
  1107. {
  1108. return ilog2(n * n * n * n);
  1109. }
  1110. static u32 shannon_entropy(struct heuristic_ws *ws)
  1111. {
  1112. const u32 entropy_max = 8 * ilog2_w(2);
  1113. u32 entropy_sum = 0;
  1114. u32 p, p_base, sz_base;
  1115. u32 i;
  1116. sz_base = ilog2_w(ws->sample_size);
  1117. for (i = 0; i < BUCKET_SIZE && ws->bucket[i].count > 0; i++) {
  1118. p = ws->bucket[i].count;
  1119. p_base = ilog2_w(p);
  1120. entropy_sum += p * (sz_base - p_base);
  1121. }
  1122. entropy_sum /= ws->sample_size;
  1123. return entropy_sum * 100 / entropy_max;
  1124. }
  1125. #define RADIX_BASE 4U
  1126. #define COUNTERS_SIZE (1U << RADIX_BASE)
  1127. static u8 get4bits(u64 num, int shift) {
  1128. u8 low4bits;
  1129. num >>= shift;
  1130. /* Reverse order */
  1131. low4bits = (COUNTERS_SIZE - 1) - (num % COUNTERS_SIZE);
  1132. return low4bits;
  1133. }
  1134. /*
  1135. * Use 4 bits as radix base
  1136. * Use 16 u32 counters for calculating new possition in buf array
  1137. *
  1138. * @array - array that will be sorted
  1139. * @array_buf - buffer array to store sorting results
  1140. * must be equal in size to @array
  1141. * @num - array size
  1142. */
  1143. static void radix_sort(struct bucket_item *array, struct bucket_item *array_buf,
  1144. int num)
  1145. {
  1146. u64 max_num;
  1147. u64 buf_num;
  1148. u32 counters[COUNTERS_SIZE];
  1149. u32 new_addr;
  1150. u32 addr;
  1151. int bitlen;
  1152. int shift;
  1153. int i;
  1154. /*
  1155. * Try avoid useless loop iterations for small numbers stored in big
  1156. * counters. Example: 48 33 4 ... in 64bit array
  1157. */
  1158. max_num = array[0].count;
  1159. for (i = 1; i < num; i++) {
  1160. buf_num = array[i].count;
  1161. if (buf_num > max_num)
  1162. max_num = buf_num;
  1163. }
  1164. buf_num = ilog2(max_num);
  1165. bitlen = ALIGN(buf_num, RADIX_BASE * 2);
  1166. shift = 0;
  1167. while (shift < bitlen) {
  1168. memset(counters, 0, sizeof(counters));
  1169. for (i = 0; i < num; i++) {
  1170. buf_num = array[i].count;
  1171. addr = get4bits(buf_num, shift);
  1172. counters[addr]++;
  1173. }
  1174. for (i = 1; i < COUNTERS_SIZE; i++)
  1175. counters[i] += counters[i - 1];
  1176. for (i = num - 1; i >= 0; i--) {
  1177. buf_num = array[i].count;
  1178. addr = get4bits(buf_num, shift);
  1179. counters[addr]--;
  1180. new_addr = counters[addr];
  1181. array_buf[new_addr] = array[i];
  1182. }
  1183. shift += RADIX_BASE;
  1184. /*
  1185. * Normal radix expects to move data from a temporary array, to
  1186. * the main one. But that requires some CPU time. Avoid that
  1187. * by doing another sort iteration to original array instead of
  1188. * memcpy()
  1189. */
  1190. memset(counters, 0, sizeof(counters));
  1191. for (i = 0; i < num; i ++) {
  1192. buf_num = array_buf[i].count;
  1193. addr = get4bits(buf_num, shift);
  1194. counters[addr]++;
  1195. }
  1196. for (i = 1; i < COUNTERS_SIZE; i++)
  1197. counters[i] += counters[i - 1];
  1198. for (i = num - 1; i >= 0; i--) {
  1199. buf_num = array_buf[i].count;
  1200. addr = get4bits(buf_num, shift);
  1201. counters[addr]--;
  1202. new_addr = counters[addr];
  1203. array[new_addr] = array_buf[i];
  1204. }
  1205. shift += RADIX_BASE;
  1206. }
  1207. }
  1208. /*
  1209. * Size of the core byte set - how many bytes cover 90% of the sample
  1210. *
  1211. * There are several types of structured binary data that use nearly all byte
  1212. * values. The distribution can be uniform and counts in all buckets will be
  1213. * nearly the same (eg. encrypted data). Unlikely to be compressible.
  1214. *
  1215. * Other possibility is normal (Gaussian) distribution, where the data could
  1216. * be potentially compressible, but we have to take a few more steps to decide
  1217. * how much.
  1218. *
  1219. * @BYTE_CORE_SET_LOW - main part of byte values repeated frequently,
  1220. * compression algo can easy fix that
  1221. * @BYTE_CORE_SET_HIGH - data have uniform distribution and with high
  1222. * probability is not compressible
  1223. */
  1224. #define BYTE_CORE_SET_LOW (64)
  1225. #define BYTE_CORE_SET_HIGH (200)
  1226. static int byte_core_set_size(struct heuristic_ws *ws)
  1227. {
  1228. u32 i;
  1229. u32 coreset_sum = 0;
  1230. const u32 core_set_threshold = ws->sample_size * 90 / 100;
  1231. struct bucket_item *bucket = ws->bucket;
  1232. /* Sort in reverse order */
  1233. radix_sort(ws->bucket, ws->bucket_b, BUCKET_SIZE);
  1234. for (i = 0; i < BYTE_CORE_SET_LOW; i++)
  1235. coreset_sum += bucket[i].count;
  1236. if (coreset_sum > core_set_threshold)
  1237. return i;
  1238. for (; i < BYTE_CORE_SET_HIGH && bucket[i].count > 0; i++) {
  1239. coreset_sum += bucket[i].count;
  1240. if (coreset_sum > core_set_threshold)
  1241. break;
  1242. }
  1243. return i;
  1244. }
  1245. /*
  1246. * Count byte values in buckets.
  1247. * This heuristic can detect textual data (configs, xml, json, html, etc).
  1248. * Because in most text-like data byte set is restricted to limited number of
  1249. * possible characters, and that restriction in most cases makes data easy to
  1250. * compress.
  1251. *
  1252. * @BYTE_SET_THRESHOLD - consider all data within this byte set size:
  1253. * less - compressible
  1254. * more - need additional analysis
  1255. */
  1256. #define BYTE_SET_THRESHOLD (64)
  1257. static u32 byte_set_size(const struct heuristic_ws *ws)
  1258. {
  1259. u32 i;
  1260. u32 byte_set_size = 0;
  1261. for (i = 0; i < BYTE_SET_THRESHOLD; i++) {
  1262. if (ws->bucket[i].count > 0)
  1263. byte_set_size++;
  1264. }
  1265. /*
  1266. * Continue collecting count of byte values in buckets. If the byte
  1267. * set size is bigger then the threshold, it's pointless to continue,
  1268. * the detection technique would fail for this type of data.
  1269. */
  1270. for (; i < BUCKET_SIZE; i++) {
  1271. if (ws->bucket[i].count > 0) {
  1272. byte_set_size++;
  1273. if (byte_set_size > BYTE_SET_THRESHOLD)
  1274. return byte_set_size;
  1275. }
  1276. }
  1277. return byte_set_size;
  1278. }
  1279. static bool sample_repeated_patterns(struct heuristic_ws *ws)
  1280. {
  1281. const u32 half_of_sample = ws->sample_size / 2;
  1282. const u8 *data = ws->sample;
  1283. return memcmp(&data[0], &data[half_of_sample], half_of_sample) == 0;
  1284. }
  1285. static void heuristic_collect_sample(struct inode *inode, u64 start, u64 end,
  1286. struct heuristic_ws *ws)
  1287. {
  1288. struct page *page;
  1289. u64 index, index_end;
  1290. u32 i, curr_sample_pos;
  1291. u8 *in_data;
  1292. /*
  1293. * Compression handles the input data by chunks of 128KiB
  1294. * (defined by BTRFS_MAX_UNCOMPRESSED)
  1295. *
  1296. * We do the same for the heuristic and loop over the whole range.
  1297. *
  1298. * MAX_SAMPLE_SIZE - calculated under assumption that heuristic will
  1299. * process no more than BTRFS_MAX_UNCOMPRESSED at a time.
  1300. */
  1301. if (end - start > BTRFS_MAX_UNCOMPRESSED)
  1302. end = start + BTRFS_MAX_UNCOMPRESSED;
  1303. index = start >> PAGE_SHIFT;
  1304. index_end = end >> PAGE_SHIFT;
  1305. /* Don't miss unaligned end */
  1306. if (!IS_ALIGNED(end, PAGE_SIZE))
  1307. index_end++;
  1308. curr_sample_pos = 0;
  1309. while (index < index_end) {
  1310. page = find_get_page(inode->i_mapping, index);
  1311. in_data = kmap(page);
  1312. /* Handle case where the start is not aligned to PAGE_SIZE */
  1313. i = start % PAGE_SIZE;
  1314. while (i < PAGE_SIZE - SAMPLING_READ_SIZE) {
  1315. /* Don't sample any garbage from the last page */
  1316. if (start > end - SAMPLING_READ_SIZE)
  1317. break;
  1318. memcpy(&ws->sample[curr_sample_pos], &in_data[i],
  1319. SAMPLING_READ_SIZE);
  1320. i += SAMPLING_INTERVAL;
  1321. start += SAMPLING_INTERVAL;
  1322. curr_sample_pos += SAMPLING_READ_SIZE;
  1323. }
  1324. kunmap(page);
  1325. put_page(page);
  1326. index++;
  1327. }
  1328. ws->sample_size = curr_sample_pos;
  1329. }
  1330. /*
  1331. * Compression heuristic.
  1332. *
  1333. * For now is's a naive and optimistic 'return true', we'll extend the logic to
  1334. * quickly (compared to direct compression) detect data characteristics
  1335. * (compressible/uncompressible) to avoid wasting CPU time on uncompressible
  1336. * data.
  1337. *
  1338. * The following types of analysis can be performed:
  1339. * - detect mostly zero data
  1340. * - detect data with low "byte set" size (text, etc)
  1341. * - detect data with low/high "core byte" set
  1342. *
  1343. * Return non-zero if the compression should be done, 0 otherwise.
  1344. */
  1345. int btrfs_compress_heuristic(struct inode *inode, u64 start, u64 end)
  1346. {
  1347. struct list_head *ws_list = __find_workspace(0, true);
  1348. struct heuristic_ws *ws;
  1349. u32 i;
  1350. u8 byte;
  1351. int ret = 0;
  1352. ws = list_entry(ws_list, struct heuristic_ws, list);
  1353. heuristic_collect_sample(inode, start, end, ws);
  1354. if (sample_repeated_patterns(ws)) {
  1355. ret = 1;
  1356. goto out;
  1357. }
  1358. memset(ws->bucket, 0, sizeof(*ws->bucket)*BUCKET_SIZE);
  1359. for (i = 0; i < ws->sample_size; i++) {
  1360. byte = ws->sample[i];
  1361. ws->bucket[byte].count++;
  1362. }
  1363. i = byte_set_size(ws);
  1364. if (i < BYTE_SET_THRESHOLD) {
  1365. ret = 2;
  1366. goto out;
  1367. }
  1368. i = byte_core_set_size(ws);
  1369. if (i <= BYTE_CORE_SET_LOW) {
  1370. ret = 3;
  1371. goto out;
  1372. }
  1373. if (i >= BYTE_CORE_SET_HIGH) {
  1374. ret = 0;
  1375. goto out;
  1376. }
  1377. i = shannon_entropy(ws);
  1378. if (i <= ENTROPY_LVL_ACEPTABLE) {
  1379. ret = 4;
  1380. goto out;
  1381. }
  1382. /*
  1383. * For the levels below ENTROPY_LVL_HIGH, additional analysis would be
  1384. * needed to give green light to compression.
  1385. *
  1386. * For now just assume that compression at that level is not worth the
  1387. * resources because:
  1388. *
  1389. * 1. it is possible to defrag the data later
  1390. *
  1391. * 2. the data would turn out to be hardly compressible, eg. 150 byte
  1392. * values, every bucket has counter at level ~54. The heuristic would
  1393. * be confused. This can happen when data have some internal repeated
  1394. * patterns like "abbacbbc...". This can be detected by analyzing
  1395. * pairs of bytes, which is too costly.
  1396. */
  1397. if (i < ENTROPY_LVL_HIGH) {
  1398. ret = 5;
  1399. goto out;
  1400. } else {
  1401. ret = 0;
  1402. goto out;
  1403. }
  1404. out:
  1405. __free_workspace(0, ws_list, true);
  1406. return ret;
  1407. }
  1408. unsigned int btrfs_compress_str2level(const char *str)
  1409. {
  1410. if (strncmp(str, "zlib", 4) != 0)
  1411. return 0;
  1412. /* Accepted form: zlib:1 up to zlib:9 and nothing left after the number */
  1413. if (str[4] == ':' && '1' <= str[5] && str[5] <= '9' && str[6] == 0)
  1414. return str[5] - '0';
  1415. return BTRFS_ZLIB_DEFAULT_LEVEL;
  1416. }