compression.c 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606
  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. rcu_read_lock();
  382. page = radix_tree_lookup(&mapping->i_pages, pg_index);
  383. rcu_read_unlock();
  384. if (page && !xa_is_value(page)) {
  385. misses++;
  386. if (misses > 4)
  387. break;
  388. goto next;
  389. }
  390. page = __page_cache_alloc(mapping_gfp_constraint(mapping,
  391. ~__GFP_FS));
  392. if (!page)
  393. break;
  394. if (add_to_page_cache_lru(page, mapping, pg_index, GFP_NOFS)) {
  395. put_page(page);
  396. goto next;
  397. }
  398. end = last_offset + PAGE_SIZE - 1;
  399. /*
  400. * at this point, we have a locked page in the page cache
  401. * for these bytes in the file. But, we have to make
  402. * sure they map to this compressed extent on disk.
  403. */
  404. set_page_extent_mapped(page);
  405. lock_extent(tree, last_offset, end);
  406. read_lock(&em_tree->lock);
  407. em = lookup_extent_mapping(em_tree, last_offset,
  408. PAGE_SIZE);
  409. read_unlock(&em_tree->lock);
  410. if (!em || last_offset < em->start ||
  411. (last_offset + PAGE_SIZE > extent_map_end(em)) ||
  412. (em->block_start >> 9) != cb->orig_bio->bi_iter.bi_sector) {
  413. free_extent_map(em);
  414. unlock_extent(tree, last_offset, end);
  415. unlock_page(page);
  416. put_page(page);
  417. break;
  418. }
  419. free_extent_map(em);
  420. if (page->index == end_index) {
  421. char *userpage;
  422. size_t zero_offset = isize & (PAGE_SIZE - 1);
  423. if (zero_offset) {
  424. int zeros;
  425. zeros = PAGE_SIZE - zero_offset;
  426. userpage = kmap_atomic(page);
  427. memset(userpage + zero_offset, 0, zeros);
  428. flush_dcache_page(page);
  429. kunmap_atomic(userpage);
  430. }
  431. }
  432. ret = bio_add_page(cb->orig_bio, page,
  433. PAGE_SIZE, 0);
  434. if (ret == PAGE_SIZE) {
  435. nr_pages++;
  436. put_page(page);
  437. } else {
  438. unlock_extent(tree, last_offset, end);
  439. unlock_page(page);
  440. put_page(page);
  441. break;
  442. }
  443. next:
  444. last_offset += PAGE_SIZE;
  445. }
  446. return 0;
  447. }
  448. /*
  449. * for a compressed read, the bio we get passed has all the inode pages
  450. * in it. We don't actually do IO on those pages but allocate new ones
  451. * to hold the compressed pages on disk.
  452. *
  453. * bio->bi_iter.bi_sector points to the compressed extent on disk
  454. * bio->bi_io_vec points to all of the inode pages
  455. *
  456. * After the compressed pages are read, we copy the bytes into the
  457. * bio we were passed and then call the bio end_io calls
  458. */
  459. blk_status_t btrfs_submit_compressed_read(struct inode *inode, struct bio *bio,
  460. int mirror_num, unsigned long bio_flags)
  461. {
  462. struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
  463. struct extent_io_tree *tree;
  464. struct extent_map_tree *em_tree;
  465. struct compressed_bio *cb;
  466. unsigned long compressed_len;
  467. unsigned long nr_pages;
  468. unsigned long pg_index;
  469. struct page *page;
  470. struct block_device *bdev;
  471. struct bio *comp_bio;
  472. u64 cur_disk_byte = (u64)bio->bi_iter.bi_sector << 9;
  473. u64 em_len;
  474. u64 em_start;
  475. struct extent_map *em;
  476. blk_status_t ret = BLK_STS_RESOURCE;
  477. int faili = 0;
  478. u32 *sums;
  479. tree = &BTRFS_I(inode)->io_tree;
  480. em_tree = &BTRFS_I(inode)->extent_tree;
  481. /* we need the actual starting offset of this extent in the file */
  482. read_lock(&em_tree->lock);
  483. em = lookup_extent_mapping(em_tree,
  484. page_offset(bio_first_page_all(bio)),
  485. PAGE_SIZE);
  486. read_unlock(&em_tree->lock);
  487. if (!em)
  488. return BLK_STS_IOERR;
  489. compressed_len = em->block_len;
  490. cb = kmalloc(compressed_bio_size(fs_info, compressed_len), GFP_NOFS);
  491. if (!cb)
  492. goto out;
  493. refcount_set(&cb->pending_bios, 0);
  494. cb->errors = 0;
  495. cb->inode = inode;
  496. cb->mirror_num = mirror_num;
  497. sums = &cb->sums;
  498. cb->start = em->orig_start;
  499. em_len = em->len;
  500. em_start = em->start;
  501. free_extent_map(em);
  502. em = NULL;
  503. cb->len = bio->bi_iter.bi_size;
  504. cb->compressed_len = compressed_len;
  505. cb->compress_type = extent_compress_type(bio_flags);
  506. cb->orig_bio = bio;
  507. nr_pages = DIV_ROUND_UP(compressed_len, PAGE_SIZE);
  508. cb->compressed_pages = kcalloc(nr_pages, sizeof(struct page *),
  509. GFP_NOFS);
  510. if (!cb->compressed_pages)
  511. goto fail1;
  512. bdev = fs_info->fs_devices->latest_bdev;
  513. for (pg_index = 0; pg_index < nr_pages; pg_index++) {
  514. cb->compressed_pages[pg_index] = alloc_page(GFP_NOFS |
  515. __GFP_HIGHMEM);
  516. if (!cb->compressed_pages[pg_index]) {
  517. faili = pg_index - 1;
  518. ret = BLK_STS_RESOURCE;
  519. goto fail2;
  520. }
  521. }
  522. faili = nr_pages - 1;
  523. cb->nr_pages = nr_pages;
  524. add_ra_bio_pages(inode, em_start + em_len, cb);
  525. /* include any pages we added in add_ra-bio_pages */
  526. cb->len = bio->bi_iter.bi_size;
  527. comp_bio = btrfs_bio_alloc(bdev, cur_disk_byte);
  528. comp_bio->bi_opf = REQ_OP_READ;
  529. comp_bio->bi_private = cb;
  530. comp_bio->bi_end_io = end_compressed_bio_read;
  531. refcount_set(&cb->pending_bios, 1);
  532. for (pg_index = 0; pg_index < nr_pages; pg_index++) {
  533. int submit = 0;
  534. page = cb->compressed_pages[pg_index];
  535. page->mapping = inode->i_mapping;
  536. page->index = em_start >> PAGE_SHIFT;
  537. if (comp_bio->bi_iter.bi_size)
  538. submit = btrfs_merge_bio_hook(page, 0, PAGE_SIZE,
  539. comp_bio, 0);
  540. page->mapping = NULL;
  541. if (submit || bio_add_page(comp_bio, page, PAGE_SIZE, 0) <
  542. PAGE_SIZE) {
  543. ret = btrfs_bio_wq_end_io(fs_info, comp_bio,
  544. BTRFS_WQ_ENDIO_DATA);
  545. BUG_ON(ret); /* -ENOMEM */
  546. /*
  547. * inc the count before we submit the bio so
  548. * we know the end IO handler won't happen before
  549. * we inc the count. Otherwise, the cb might get
  550. * freed before we're done setting it up
  551. */
  552. refcount_inc(&cb->pending_bios);
  553. if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
  554. ret = btrfs_lookup_bio_sums(inode, comp_bio,
  555. sums);
  556. BUG_ON(ret); /* -ENOMEM */
  557. }
  558. sums += DIV_ROUND_UP(comp_bio->bi_iter.bi_size,
  559. fs_info->sectorsize);
  560. ret = btrfs_map_bio(fs_info, comp_bio, mirror_num, 0);
  561. if (ret) {
  562. comp_bio->bi_status = ret;
  563. bio_endio(comp_bio);
  564. }
  565. comp_bio = btrfs_bio_alloc(bdev, cur_disk_byte);
  566. comp_bio->bi_opf = REQ_OP_READ;
  567. comp_bio->bi_private = cb;
  568. comp_bio->bi_end_io = end_compressed_bio_read;
  569. bio_add_page(comp_bio, page, PAGE_SIZE, 0);
  570. }
  571. cur_disk_byte += PAGE_SIZE;
  572. }
  573. ret = btrfs_bio_wq_end_io(fs_info, comp_bio, BTRFS_WQ_ENDIO_DATA);
  574. BUG_ON(ret); /* -ENOMEM */
  575. if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
  576. ret = btrfs_lookup_bio_sums(inode, comp_bio, sums);
  577. BUG_ON(ret); /* -ENOMEM */
  578. }
  579. ret = btrfs_map_bio(fs_info, comp_bio, mirror_num, 0);
  580. if (ret) {
  581. comp_bio->bi_status = ret;
  582. bio_endio(comp_bio);
  583. }
  584. return 0;
  585. fail2:
  586. while (faili >= 0) {
  587. __free_page(cb->compressed_pages[faili]);
  588. faili--;
  589. }
  590. kfree(cb->compressed_pages);
  591. fail1:
  592. kfree(cb);
  593. out:
  594. free_extent_map(em);
  595. return ret;
  596. }
  597. /*
  598. * Heuristic uses systematic sampling to collect data from the input data
  599. * range, the logic can be tuned by the following constants:
  600. *
  601. * @SAMPLING_READ_SIZE - how many bytes will be copied from for each sample
  602. * @SAMPLING_INTERVAL - range from which the sampled data can be collected
  603. */
  604. #define SAMPLING_READ_SIZE (16)
  605. #define SAMPLING_INTERVAL (256)
  606. /*
  607. * For statistical analysis of the input data we consider bytes that form a
  608. * Galois Field of 256 objects. Each object has an attribute count, ie. how
  609. * many times the object appeared in the sample.
  610. */
  611. #define BUCKET_SIZE (256)
  612. /*
  613. * The size of the sample is based on a statistical sampling rule of thumb.
  614. * The common way is to perform sampling tests as long as the number of
  615. * elements in each cell is at least 5.
  616. *
  617. * Instead of 5, we choose 32 to obtain more accurate results.
  618. * If the data contain the maximum number of symbols, which is 256, we obtain a
  619. * sample size bound by 8192.
  620. *
  621. * For a sample of at most 8KB of data per data range: 16 consecutive bytes
  622. * from up to 512 locations.
  623. */
  624. #define MAX_SAMPLE_SIZE (BTRFS_MAX_UNCOMPRESSED * \
  625. SAMPLING_READ_SIZE / SAMPLING_INTERVAL)
  626. struct bucket_item {
  627. u32 count;
  628. };
  629. struct heuristic_ws {
  630. /* Partial copy of input data */
  631. u8 *sample;
  632. u32 sample_size;
  633. /* Buckets store counters for each byte value */
  634. struct bucket_item *bucket;
  635. /* Sorting buffer */
  636. struct bucket_item *bucket_b;
  637. struct list_head list;
  638. };
  639. static void free_heuristic_ws(struct list_head *ws)
  640. {
  641. struct heuristic_ws *workspace;
  642. workspace = list_entry(ws, struct heuristic_ws, list);
  643. kvfree(workspace->sample);
  644. kfree(workspace->bucket);
  645. kfree(workspace->bucket_b);
  646. kfree(workspace);
  647. }
  648. static struct list_head *alloc_heuristic_ws(void)
  649. {
  650. struct heuristic_ws *ws;
  651. ws = kzalloc(sizeof(*ws), GFP_KERNEL);
  652. if (!ws)
  653. return ERR_PTR(-ENOMEM);
  654. ws->sample = kvmalloc(MAX_SAMPLE_SIZE, GFP_KERNEL);
  655. if (!ws->sample)
  656. goto fail;
  657. ws->bucket = kcalloc(BUCKET_SIZE, sizeof(*ws->bucket), GFP_KERNEL);
  658. if (!ws->bucket)
  659. goto fail;
  660. ws->bucket_b = kcalloc(BUCKET_SIZE, sizeof(*ws->bucket_b), GFP_KERNEL);
  661. if (!ws->bucket_b)
  662. goto fail;
  663. INIT_LIST_HEAD(&ws->list);
  664. return &ws->list;
  665. fail:
  666. free_heuristic_ws(&ws->list);
  667. return ERR_PTR(-ENOMEM);
  668. }
  669. struct workspaces_list {
  670. struct list_head idle_ws;
  671. spinlock_t ws_lock;
  672. /* Number of free workspaces */
  673. int free_ws;
  674. /* Total number of allocated workspaces */
  675. atomic_t total_ws;
  676. /* Waiters for a free workspace */
  677. wait_queue_head_t ws_wait;
  678. };
  679. static struct workspaces_list btrfs_comp_ws[BTRFS_COMPRESS_TYPES];
  680. static struct workspaces_list btrfs_heuristic_ws;
  681. static const struct btrfs_compress_op * const btrfs_compress_op[] = {
  682. &btrfs_zlib_compress,
  683. &btrfs_lzo_compress,
  684. &btrfs_zstd_compress,
  685. };
  686. void __init btrfs_init_compress(void)
  687. {
  688. struct list_head *workspace;
  689. int i;
  690. INIT_LIST_HEAD(&btrfs_heuristic_ws.idle_ws);
  691. spin_lock_init(&btrfs_heuristic_ws.ws_lock);
  692. atomic_set(&btrfs_heuristic_ws.total_ws, 0);
  693. init_waitqueue_head(&btrfs_heuristic_ws.ws_wait);
  694. workspace = alloc_heuristic_ws();
  695. if (IS_ERR(workspace)) {
  696. pr_warn(
  697. "BTRFS: cannot preallocate heuristic workspace, will try later\n");
  698. } else {
  699. atomic_set(&btrfs_heuristic_ws.total_ws, 1);
  700. btrfs_heuristic_ws.free_ws = 1;
  701. list_add(workspace, &btrfs_heuristic_ws.idle_ws);
  702. }
  703. for (i = 0; i < BTRFS_COMPRESS_TYPES; i++) {
  704. INIT_LIST_HEAD(&btrfs_comp_ws[i].idle_ws);
  705. spin_lock_init(&btrfs_comp_ws[i].ws_lock);
  706. atomic_set(&btrfs_comp_ws[i].total_ws, 0);
  707. init_waitqueue_head(&btrfs_comp_ws[i].ws_wait);
  708. /*
  709. * Preallocate one workspace for each compression type so
  710. * we can guarantee forward progress in the worst case
  711. */
  712. workspace = btrfs_compress_op[i]->alloc_workspace();
  713. if (IS_ERR(workspace)) {
  714. pr_warn("BTRFS: cannot preallocate compression workspace, will try later\n");
  715. } else {
  716. atomic_set(&btrfs_comp_ws[i].total_ws, 1);
  717. btrfs_comp_ws[i].free_ws = 1;
  718. list_add(workspace, &btrfs_comp_ws[i].idle_ws);
  719. }
  720. }
  721. }
  722. /*
  723. * This finds an available workspace or allocates a new one.
  724. * If it's not possible to allocate a new one, waits until there's one.
  725. * Preallocation makes a forward progress guarantees and we do not return
  726. * errors.
  727. */
  728. static struct list_head *__find_workspace(int type, bool heuristic)
  729. {
  730. struct list_head *workspace;
  731. int cpus = num_online_cpus();
  732. int idx = type - 1;
  733. unsigned nofs_flag;
  734. struct list_head *idle_ws;
  735. spinlock_t *ws_lock;
  736. atomic_t *total_ws;
  737. wait_queue_head_t *ws_wait;
  738. int *free_ws;
  739. if (heuristic) {
  740. idle_ws = &btrfs_heuristic_ws.idle_ws;
  741. ws_lock = &btrfs_heuristic_ws.ws_lock;
  742. total_ws = &btrfs_heuristic_ws.total_ws;
  743. ws_wait = &btrfs_heuristic_ws.ws_wait;
  744. free_ws = &btrfs_heuristic_ws.free_ws;
  745. } else {
  746. idle_ws = &btrfs_comp_ws[idx].idle_ws;
  747. ws_lock = &btrfs_comp_ws[idx].ws_lock;
  748. total_ws = &btrfs_comp_ws[idx].total_ws;
  749. ws_wait = &btrfs_comp_ws[idx].ws_wait;
  750. free_ws = &btrfs_comp_ws[idx].free_ws;
  751. }
  752. again:
  753. spin_lock(ws_lock);
  754. if (!list_empty(idle_ws)) {
  755. workspace = idle_ws->next;
  756. list_del(workspace);
  757. (*free_ws)--;
  758. spin_unlock(ws_lock);
  759. return workspace;
  760. }
  761. if (atomic_read(total_ws) > cpus) {
  762. DEFINE_WAIT(wait);
  763. spin_unlock(ws_lock);
  764. prepare_to_wait(ws_wait, &wait, TASK_UNINTERRUPTIBLE);
  765. if (atomic_read(total_ws) > cpus && !*free_ws)
  766. schedule();
  767. finish_wait(ws_wait, &wait);
  768. goto again;
  769. }
  770. atomic_inc(total_ws);
  771. spin_unlock(ws_lock);
  772. /*
  773. * Allocation helpers call vmalloc that can't use GFP_NOFS, so we have
  774. * to turn it off here because we might get called from the restricted
  775. * context of btrfs_compress_bio/btrfs_compress_pages
  776. */
  777. nofs_flag = memalloc_nofs_save();
  778. if (heuristic)
  779. workspace = alloc_heuristic_ws();
  780. else
  781. workspace = btrfs_compress_op[idx]->alloc_workspace();
  782. memalloc_nofs_restore(nofs_flag);
  783. if (IS_ERR(workspace)) {
  784. atomic_dec(total_ws);
  785. wake_up(ws_wait);
  786. /*
  787. * Do not return the error but go back to waiting. There's a
  788. * workspace preallocated for each type and the compression
  789. * time is bounded so we get to a workspace eventually. This
  790. * makes our caller's life easier.
  791. *
  792. * To prevent silent and low-probability deadlocks (when the
  793. * initial preallocation fails), check if there are any
  794. * workspaces at all.
  795. */
  796. if (atomic_read(total_ws) == 0) {
  797. static DEFINE_RATELIMIT_STATE(_rs,
  798. /* once per minute */ 60 * HZ,
  799. /* no burst */ 1);
  800. if (__ratelimit(&_rs)) {
  801. pr_warn("BTRFS: no compression workspaces, low memory, retrying\n");
  802. }
  803. }
  804. goto again;
  805. }
  806. return workspace;
  807. }
  808. static struct list_head *find_workspace(int type)
  809. {
  810. return __find_workspace(type, false);
  811. }
  812. /*
  813. * put a workspace struct back on the list or free it if we have enough
  814. * idle ones sitting around
  815. */
  816. static void __free_workspace(int type, struct list_head *workspace,
  817. bool heuristic)
  818. {
  819. int idx = type - 1;
  820. struct list_head *idle_ws;
  821. spinlock_t *ws_lock;
  822. atomic_t *total_ws;
  823. wait_queue_head_t *ws_wait;
  824. int *free_ws;
  825. if (heuristic) {
  826. idle_ws = &btrfs_heuristic_ws.idle_ws;
  827. ws_lock = &btrfs_heuristic_ws.ws_lock;
  828. total_ws = &btrfs_heuristic_ws.total_ws;
  829. ws_wait = &btrfs_heuristic_ws.ws_wait;
  830. free_ws = &btrfs_heuristic_ws.free_ws;
  831. } else {
  832. idle_ws = &btrfs_comp_ws[idx].idle_ws;
  833. ws_lock = &btrfs_comp_ws[idx].ws_lock;
  834. total_ws = &btrfs_comp_ws[idx].total_ws;
  835. ws_wait = &btrfs_comp_ws[idx].ws_wait;
  836. free_ws = &btrfs_comp_ws[idx].free_ws;
  837. }
  838. spin_lock(ws_lock);
  839. if (*free_ws <= num_online_cpus()) {
  840. list_add(workspace, idle_ws);
  841. (*free_ws)++;
  842. spin_unlock(ws_lock);
  843. goto wake;
  844. }
  845. spin_unlock(ws_lock);
  846. if (heuristic)
  847. free_heuristic_ws(workspace);
  848. else
  849. btrfs_compress_op[idx]->free_workspace(workspace);
  850. atomic_dec(total_ws);
  851. wake:
  852. cond_wake_up(ws_wait);
  853. }
  854. static void free_workspace(int type, struct list_head *ws)
  855. {
  856. return __free_workspace(type, ws, false);
  857. }
  858. /*
  859. * cleanup function for module exit
  860. */
  861. static void free_workspaces(void)
  862. {
  863. struct list_head *workspace;
  864. int i;
  865. while (!list_empty(&btrfs_heuristic_ws.idle_ws)) {
  866. workspace = btrfs_heuristic_ws.idle_ws.next;
  867. list_del(workspace);
  868. free_heuristic_ws(workspace);
  869. atomic_dec(&btrfs_heuristic_ws.total_ws);
  870. }
  871. for (i = 0; i < BTRFS_COMPRESS_TYPES; i++) {
  872. while (!list_empty(&btrfs_comp_ws[i].idle_ws)) {
  873. workspace = btrfs_comp_ws[i].idle_ws.next;
  874. list_del(workspace);
  875. btrfs_compress_op[i]->free_workspace(workspace);
  876. atomic_dec(&btrfs_comp_ws[i].total_ws);
  877. }
  878. }
  879. }
  880. /*
  881. * Given an address space and start and length, compress the bytes into @pages
  882. * that are allocated on demand.
  883. *
  884. * @type_level is encoded algorithm and level, where level 0 means whatever
  885. * default the algorithm chooses and is opaque here;
  886. * - compression algo are 0-3
  887. * - the level are bits 4-7
  888. *
  889. * @out_pages is an in/out parameter, holds maximum number of pages to allocate
  890. * and returns number of actually allocated pages
  891. *
  892. * @total_in is used to return the number of bytes actually read. It
  893. * may be smaller than the input length if we had to exit early because we
  894. * ran out of room in the pages array or because we cross the
  895. * max_out threshold.
  896. *
  897. * @total_out is an in/out parameter, must be set to the input length and will
  898. * be also used to return the total number of compressed bytes
  899. *
  900. * @max_out tells us the max number of bytes that we're allowed to
  901. * stuff into pages
  902. */
  903. int btrfs_compress_pages(unsigned int type_level, struct address_space *mapping,
  904. u64 start, struct page **pages,
  905. unsigned long *out_pages,
  906. unsigned long *total_in,
  907. unsigned long *total_out)
  908. {
  909. struct list_head *workspace;
  910. int ret;
  911. int type = type_level & 0xF;
  912. workspace = find_workspace(type);
  913. btrfs_compress_op[type - 1]->set_level(workspace, type_level);
  914. ret = btrfs_compress_op[type-1]->compress_pages(workspace, mapping,
  915. start, pages,
  916. out_pages,
  917. total_in, total_out);
  918. free_workspace(type, workspace);
  919. return ret;
  920. }
  921. /*
  922. * pages_in is an array of pages with compressed data.
  923. *
  924. * disk_start is the starting logical offset of this array in the file
  925. *
  926. * orig_bio contains the pages from the file that we want to decompress into
  927. *
  928. * srclen is the number of bytes in pages_in
  929. *
  930. * The basic idea is that we have a bio that was created by readpages.
  931. * The pages in the bio are for the uncompressed data, and they may not
  932. * be contiguous. They all correspond to the range of bytes covered by
  933. * the compressed extent.
  934. */
  935. static int btrfs_decompress_bio(struct compressed_bio *cb)
  936. {
  937. struct list_head *workspace;
  938. int ret;
  939. int type = cb->compress_type;
  940. workspace = find_workspace(type);
  941. ret = btrfs_compress_op[type - 1]->decompress_bio(workspace, cb);
  942. free_workspace(type, workspace);
  943. return ret;
  944. }
  945. /*
  946. * a less complex decompression routine. Our compressed data fits in a
  947. * single page, and we want to read a single page out of it.
  948. * start_byte tells us the offset into the compressed data we're interested in
  949. */
  950. int btrfs_decompress(int type, unsigned char *data_in, struct page *dest_page,
  951. unsigned long start_byte, size_t srclen, size_t destlen)
  952. {
  953. struct list_head *workspace;
  954. int ret;
  955. workspace = find_workspace(type);
  956. ret = btrfs_compress_op[type-1]->decompress(workspace, data_in,
  957. dest_page, start_byte,
  958. srclen, destlen);
  959. free_workspace(type, workspace);
  960. return ret;
  961. }
  962. void __cold btrfs_exit_compress(void)
  963. {
  964. free_workspaces();
  965. }
  966. /*
  967. * Copy uncompressed data from working buffer to pages.
  968. *
  969. * buf_start is the byte offset we're of the start of our workspace buffer.
  970. *
  971. * total_out is the last byte of the buffer
  972. */
  973. int btrfs_decompress_buf2page(const char *buf, unsigned long buf_start,
  974. unsigned long total_out, u64 disk_start,
  975. struct bio *bio)
  976. {
  977. unsigned long buf_offset;
  978. unsigned long current_buf_start;
  979. unsigned long start_byte;
  980. unsigned long prev_start_byte;
  981. unsigned long working_bytes = total_out - buf_start;
  982. unsigned long bytes;
  983. char *kaddr;
  984. struct bio_vec bvec = bio_iter_iovec(bio, bio->bi_iter);
  985. /*
  986. * start byte is the first byte of the page we're currently
  987. * copying into relative to the start of the compressed data.
  988. */
  989. start_byte = page_offset(bvec.bv_page) - disk_start;
  990. /* we haven't yet hit data corresponding to this page */
  991. if (total_out <= start_byte)
  992. return 1;
  993. /*
  994. * the start of the data we care about is offset into
  995. * the middle of our working buffer
  996. */
  997. if (total_out > start_byte && buf_start < start_byte) {
  998. buf_offset = start_byte - buf_start;
  999. working_bytes -= buf_offset;
  1000. } else {
  1001. buf_offset = 0;
  1002. }
  1003. current_buf_start = buf_start;
  1004. /* copy bytes from the working buffer into the pages */
  1005. while (working_bytes > 0) {
  1006. bytes = min_t(unsigned long, bvec.bv_len,
  1007. PAGE_SIZE - buf_offset);
  1008. bytes = min(bytes, working_bytes);
  1009. kaddr = kmap_atomic(bvec.bv_page);
  1010. memcpy(kaddr + bvec.bv_offset, buf + buf_offset, bytes);
  1011. kunmap_atomic(kaddr);
  1012. flush_dcache_page(bvec.bv_page);
  1013. buf_offset += bytes;
  1014. working_bytes -= bytes;
  1015. current_buf_start += bytes;
  1016. /* check if we need to pick another page */
  1017. bio_advance(bio, bytes);
  1018. if (!bio->bi_iter.bi_size)
  1019. return 0;
  1020. bvec = bio_iter_iovec(bio, bio->bi_iter);
  1021. prev_start_byte = start_byte;
  1022. start_byte = page_offset(bvec.bv_page) - disk_start;
  1023. /*
  1024. * We need to make sure we're only adjusting
  1025. * our offset into compression working buffer when
  1026. * we're switching pages. Otherwise we can incorrectly
  1027. * keep copying when we were actually done.
  1028. */
  1029. if (start_byte != prev_start_byte) {
  1030. /*
  1031. * make sure our new page is covered by this
  1032. * working buffer
  1033. */
  1034. if (total_out <= start_byte)
  1035. return 1;
  1036. /*
  1037. * the next page in the biovec might not be adjacent
  1038. * to the last page, but it might still be found
  1039. * inside this working buffer. bump our offset pointer
  1040. */
  1041. if (total_out > start_byte &&
  1042. current_buf_start < start_byte) {
  1043. buf_offset = start_byte - buf_start;
  1044. working_bytes = total_out - start_byte;
  1045. current_buf_start = buf_start + buf_offset;
  1046. }
  1047. }
  1048. }
  1049. return 1;
  1050. }
  1051. /*
  1052. * Shannon Entropy calculation
  1053. *
  1054. * Pure byte distribution analysis fails to determine compressiability of data.
  1055. * Try calculating entropy to estimate the average minimum number of bits
  1056. * needed to encode the sampled data.
  1057. *
  1058. * For convenience, return the percentage of needed bits, instead of amount of
  1059. * bits directly.
  1060. *
  1061. * @ENTROPY_LVL_ACEPTABLE - below that threshold, sample has low byte entropy
  1062. * and can be compressible with high probability
  1063. *
  1064. * @ENTROPY_LVL_HIGH - data are not compressible with high probability
  1065. *
  1066. * Use of ilog2() decreases precision, we lower the LVL to 5 to compensate.
  1067. */
  1068. #define ENTROPY_LVL_ACEPTABLE (65)
  1069. #define ENTROPY_LVL_HIGH (80)
  1070. /*
  1071. * For increasead precision in shannon_entropy calculation,
  1072. * let's do pow(n, M) to save more digits after comma:
  1073. *
  1074. * - maximum int bit length is 64
  1075. * - ilog2(MAX_SAMPLE_SIZE) -> 13
  1076. * - 13 * 4 = 52 < 64 -> M = 4
  1077. *
  1078. * So use pow(n, 4).
  1079. */
  1080. static inline u32 ilog2_w(u64 n)
  1081. {
  1082. return ilog2(n * n * n * n);
  1083. }
  1084. static u32 shannon_entropy(struct heuristic_ws *ws)
  1085. {
  1086. const u32 entropy_max = 8 * ilog2_w(2);
  1087. u32 entropy_sum = 0;
  1088. u32 p, p_base, sz_base;
  1089. u32 i;
  1090. sz_base = ilog2_w(ws->sample_size);
  1091. for (i = 0; i < BUCKET_SIZE && ws->bucket[i].count > 0; i++) {
  1092. p = ws->bucket[i].count;
  1093. p_base = ilog2_w(p);
  1094. entropy_sum += p * (sz_base - p_base);
  1095. }
  1096. entropy_sum /= ws->sample_size;
  1097. return entropy_sum * 100 / entropy_max;
  1098. }
  1099. #define RADIX_BASE 4U
  1100. #define COUNTERS_SIZE (1U << RADIX_BASE)
  1101. static u8 get4bits(u64 num, int shift) {
  1102. u8 low4bits;
  1103. num >>= shift;
  1104. /* Reverse order */
  1105. low4bits = (COUNTERS_SIZE - 1) - (num % COUNTERS_SIZE);
  1106. return low4bits;
  1107. }
  1108. /*
  1109. * Use 4 bits as radix base
  1110. * Use 16 u32 counters for calculating new possition in buf array
  1111. *
  1112. * @array - array that will be sorted
  1113. * @array_buf - buffer array to store sorting results
  1114. * must be equal in size to @array
  1115. * @num - array size
  1116. */
  1117. static void radix_sort(struct bucket_item *array, struct bucket_item *array_buf,
  1118. int num)
  1119. {
  1120. u64 max_num;
  1121. u64 buf_num;
  1122. u32 counters[COUNTERS_SIZE];
  1123. u32 new_addr;
  1124. u32 addr;
  1125. int bitlen;
  1126. int shift;
  1127. int i;
  1128. /*
  1129. * Try avoid useless loop iterations for small numbers stored in big
  1130. * counters. Example: 48 33 4 ... in 64bit array
  1131. */
  1132. max_num = array[0].count;
  1133. for (i = 1; i < num; i++) {
  1134. buf_num = array[i].count;
  1135. if (buf_num > max_num)
  1136. max_num = buf_num;
  1137. }
  1138. buf_num = ilog2(max_num);
  1139. bitlen = ALIGN(buf_num, RADIX_BASE * 2);
  1140. shift = 0;
  1141. while (shift < bitlen) {
  1142. memset(counters, 0, sizeof(counters));
  1143. for (i = 0; i < num; i++) {
  1144. buf_num = array[i].count;
  1145. addr = get4bits(buf_num, shift);
  1146. counters[addr]++;
  1147. }
  1148. for (i = 1; i < COUNTERS_SIZE; i++)
  1149. counters[i] += counters[i - 1];
  1150. for (i = num - 1; i >= 0; i--) {
  1151. buf_num = array[i].count;
  1152. addr = get4bits(buf_num, shift);
  1153. counters[addr]--;
  1154. new_addr = counters[addr];
  1155. array_buf[new_addr] = array[i];
  1156. }
  1157. shift += RADIX_BASE;
  1158. /*
  1159. * Normal radix expects to move data from a temporary array, to
  1160. * the main one. But that requires some CPU time. Avoid that
  1161. * by doing another sort iteration to original array instead of
  1162. * memcpy()
  1163. */
  1164. memset(counters, 0, sizeof(counters));
  1165. for (i = 0; i < num; i ++) {
  1166. buf_num = array_buf[i].count;
  1167. addr = get4bits(buf_num, shift);
  1168. counters[addr]++;
  1169. }
  1170. for (i = 1; i < COUNTERS_SIZE; i++)
  1171. counters[i] += counters[i - 1];
  1172. for (i = num - 1; i >= 0; i--) {
  1173. buf_num = array_buf[i].count;
  1174. addr = get4bits(buf_num, shift);
  1175. counters[addr]--;
  1176. new_addr = counters[addr];
  1177. array[new_addr] = array_buf[i];
  1178. }
  1179. shift += RADIX_BASE;
  1180. }
  1181. }
  1182. /*
  1183. * Size of the core byte set - how many bytes cover 90% of the sample
  1184. *
  1185. * There are several types of structured binary data that use nearly all byte
  1186. * values. The distribution can be uniform and counts in all buckets will be
  1187. * nearly the same (eg. encrypted data). Unlikely to be compressible.
  1188. *
  1189. * Other possibility is normal (Gaussian) distribution, where the data could
  1190. * be potentially compressible, but we have to take a few more steps to decide
  1191. * how much.
  1192. *
  1193. * @BYTE_CORE_SET_LOW - main part of byte values repeated frequently,
  1194. * compression algo can easy fix that
  1195. * @BYTE_CORE_SET_HIGH - data have uniform distribution and with high
  1196. * probability is not compressible
  1197. */
  1198. #define BYTE_CORE_SET_LOW (64)
  1199. #define BYTE_CORE_SET_HIGH (200)
  1200. static int byte_core_set_size(struct heuristic_ws *ws)
  1201. {
  1202. u32 i;
  1203. u32 coreset_sum = 0;
  1204. const u32 core_set_threshold = ws->sample_size * 90 / 100;
  1205. struct bucket_item *bucket = ws->bucket;
  1206. /* Sort in reverse order */
  1207. radix_sort(ws->bucket, ws->bucket_b, BUCKET_SIZE);
  1208. for (i = 0; i < BYTE_CORE_SET_LOW; i++)
  1209. coreset_sum += bucket[i].count;
  1210. if (coreset_sum > core_set_threshold)
  1211. return i;
  1212. for (; i < BYTE_CORE_SET_HIGH && bucket[i].count > 0; i++) {
  1213. coreset_sum += bucket[i].count;
  1214. if (coreset_sum > core_set_threshold)
  1215. break;
  1216. }
  1217. return i;
  1218. }
  1219. /*
  1220. * Count byte values in buckets.
  1221. * This heuristic can detect textual data (configs, xml, json, html, etc).
  1222. * Because in most text-like data byte set is restricted to limited number of
  1223. * possible characters, and that restriction in most cases makes data easy to
  1224. * compress.
  1225. *
  1226. * @BYTE_SET_THRESHOLD - consider all data within this byte set size:
  1227. * less - compressible
  1228. * more - need additional analysis
  1229. */
  1230. #define BYTE_SET_THRESHOLD (64)
  1231. static u32 byte_set_size(const struct heuristic_ws *ws)
  1232. {
  1233. u32 i;
  1234. u32 byte_set_size = 0;
  1235. for (i = 0; i < BYTE_SET_THRESHOLD; i++) {
  1236. if (ws->bucket[i].count > 0)
  1237. byte_set_size++;
  1238. }
  1239. /*
  1240. * Continue collecting count of byte values in buckets. If the byte
  1241. * set size is bigger then the threshold, it's pointless to continue,
  1242. * the detection technique would fail for this type of data.
  1243. */
  1244. for (; i < BUCKET_SIZE; i++) {
  1245. if (ws->bucket[i].count > 0) {
  1246. byte_set_size++;
  1247. if (byte_set_size > BYTE_SET_THRESHOLD)
  1248. return byte_set_size;
  1249. }
  1250. }
  1251. return byte_set_size;
  1252. }
  1253. static bool sample_repeated_patterns(struct heuristic_ws *ws)
  1254. {
  1255. const u32 half_of_sample = ws->sample_size / 2;
  1256. const u8 *data = ws->sample;
  1257. return memcmp(&data[0], &data[half_of_sample], half_of_sample) == 0;
  1258. }
  1259. static void heuristic_collect_sample(struct inode *inode, u64 start, u64 end,
  1260. struct heuristic_ws *ws)
  1261. {
  1262. struct page *page;
  1263. u64 index, index_end;
  1264. u32 i, curr_sample_pos;
  1265. u8 *in_data;
  1266. /*
  1267. * Compression handles the input data by chunks of 128KiB
  1268. * (defined by BTRFS_MAX_UNCOMPRESSED)
  1269. *
  1270. * We do the same for the heuristic and loop over the whole range.
  1271. *
  1272. * MAX_SAMPLE_SIZE - calculated under assumption that heuristic will
  1273. * process no more than BTRFS_MAX_UNCOMPRESSED at a time.
  1274. */
  1275. if (end - start > BTRFS_MAX_UNCOMPRESSED)
  1276. end = start + BTRFS_MAX_UNCOMPRESSED;
  1277. index = start >> PAGE_SHIFT;
  1278. index_end = end >> PAGE_SHIFT;
  1279. /* Don't miss unaligned end */
  1280. if (!IS_ALIGNED(end, PAGE_SIZE))
  1281. index_end++;
  1282. curr_sample_pos = 0;
  1283. while (index < index_end) {
  1284. page = find_get_page(inode->i_mapping, index);
  1285. in_data = kmap(page);
  1286. /* Handle case where the start is not aligned to PAGE_SIZE */
  1287. i = start % PAGE_SIZE;
  1288. while (i < PAGE_SIZE - SAMPLING_READ_SIZE) {
  1289. /* Don't sample any garbage from the last page */
  1290. if (start > end - SAMPLING_READ_SIZE)
  1291. break;
  1292. memcpy(&ws->sample[curr_sample_pos], &in_data[i],
  1293. SAMPLING_READ_SIZE);
  1294. i += SAMPLING_INTERVAL;
  1295. start += SAMPLING_INTERVAL;
  1296. curr_sample_pos += SAMPLING_READ_SIZE;
  1297. }
  1298. kunmap(page);
  1299. put_page(page);
  1300. index++;
  1301. }
  1302. ws->sample_size = curr_sample_pos;
  1303. }
  1304. /*
  1305. * Compression heuristic.
  1306. *
  1307. * For now is's a naive and optimistic 'return true', we'll extend the logic to
  1308. * quickly (compared to direct compression) detect data characteristics
  1309. * (compressible/uncompressible) to avoid wasting CPU time on uncompressible
  1310. * data.
  1311. *
  1312. * The following types of analysis can be performed:
  1313. * - detect mostly zero data
  1314. * - detect data with low "byte set" size (text, etc)
  1315. * - detect data with low/high "core byte" set
  1316. *
  1317. * Return non-zero if the compression should be done, 0 otherwise.
  1318. */
  1319. int btrfs_compress_heuristic(struct inode *inode, u64 start, u64 end)
  1320. {
  1321. struct list_head *ws_list = __find_workspace(0, true);
  1322. struct heuristic_ws *ws;
  1323. u32 i;
  1324. u8 byte;
  1325. int ret = 0;
  1326. ws = list_entry(ws_list, struct heuristic_ws, list);
  1327. heuristic_collect_sample(inode, start, end, ws);
  1328. if (sample_repeated_patterns(ws)) {
  1329. ret = 1;
  1330. goto out;
  1331. }
  1332. memset(ws->bucket, 0, sizeof(*ws->bucket)*BUCKET_SIZE);
  1333. for (i = 0; i < ws->sample_size; i++) {
  1334. byte = ws->sample[i];
  1335. ws->bucket[byte].count++;
  1336. }
  1337. i = byte_set_size(ws);
  1338. if (i < BYTE_SET_THRESHOLD) {
  1339. ret = 2;
  1340. goto out;
  1341. }
  1342. i = byte_core_set_size(ws);
  1343. if (i <= BYTE_CORE_SET_LOW) {
  1344. ret = 3;
  1345. goto out;
  1346. }
  1347. if (i >= BYTE_CORE_SET_HIGH) {
  1348. ret = 0;
  1349. goto out;
  1350. }
  1351. i = shannon_entropy(ws);
  1352. if (i <= ENTROPY_LVL_ACEPTABLE) {
  1353. ret = 4;
  1354. goto out;
  1355. }
  1356. /*
  1357. * For the levels below ENTROPY_LVL_HIGH, additional analysis would be
  1358. * needed to give green light to compression.
  1359. *
  1360. * For now just assume that compression at that level is not worth the
  1361. * resources because:
  1362. *
  1363. * 1. it is possible to defrag the data later
  1364. *
  1365. * 2. the data would turn out to be hardly compressible, eg. 150 byte
  1366. * values, every bucket has counter at level ~54. The heuristic would
  1367. * be confused. This can happen when data have some internal repeated
  1368. * patterns like "abbacbbc...". This can be detected by analyzing
  1369. * pairs of bytes, which is too costly.
  1370. */
  1371. if (i < ENTROPY_LVL_HIGH) {
  1372. ret = 5;
  1373. goto out;
  1374. } else {
  1375. ret = 0;
  1376. goto out;
  1377. }
  1378. out:
  1379. __free_workspace(0, ws_list, true);
  1380. return ret;
  1381. }
  1382. unsigned int btrfs_compress_str2level(const char *str)
  1383. {
  1384. if (strncmp(str, "zlib", 4) != 0)
  1385. return 0;
  1386. /* Accepted form: zlib:1 up to zlib:9 and nothing left after the number */
  1387. if (str[4] == ':' && '1' <= str[5] && str[5] <= '9' && str[6] == 0)
  1388. return str[5] - '0';
  1389. return BTRFS_ZLIB_DEFAULT_LEVEL;
  1390. }