compression.c 39 KB

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