compression.c 41 KB

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