compression.c 42 KB

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