compression.c 42 KB

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