compression.c 41 KB

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