compression.c 44 KB

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