compression.c 42 KB

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