compression.c 41 KB

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