compression.c 40 KB

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