compression.c 46 KB

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