compress.c 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950
  1. // SPDX-License-Identifier: GPL-2.0-or-later
  2. /**
  3. * compress.c - NTFS kernel compressed attributes handling.
  4. * Part of the Linux-NTFS project.
  5. *
  6. * Copyright (c) 2001-2004 Anton Altaparmakov
  7. * Copyright (c) 2002 Richard Russon
  8. */
  9. #include <linux/fs.h>
  10. #include <linux/buffer_head.h>
  11. #include <linux/blkdev.h>
  12. #include <linux/vmalloc.h>
  13. #include <linux/slab.h>
  14. #include "attrib.h"
  15. #include "inode.h"
  16. #include "debug.h"
  17. #include "ntfs.h"
  18. /**
  19. * ntfs_compression_constants - enum of constants used in the compression code
  20. */
  21. typedef enum {
  22. /* Token types and access mask. */
  23. NTFS_SYMBOL_TOKEN = 0,
  24. NTFS_PHRASE_TOKEN = 1,
  25. NTFS_TOKEN_MASK = 1,
  26. /* Compression sub-block constants. */
  27. NTFS_SB_SIZE_MASK = 0x0fff,
  28. NTFS_SB_SIZE = 0x1000,
  29. NTFS_SB_IS_COMPRESSED = 0x8000,
  30. /*
  31. * The maximum compression block size is by definition 16 * the cluster
  32. * size, with the maximum supported cluster size being 4kiB. Thus the
  33. * maximum compression buffer size is 64kiB, so we use this when
  34. * initializing the compression buffer.
  35. */
  36. NTFS_MAX_CB_SIZE = 64 * 1024,
  37. } ntfs_compression_constants;
  38. /**
  39. * ntfs_compression_buffer - one buffer for the decompression engine
  40. */
  41. static u8 *ntfs_compression_buffer;
  42. /**
  43. * ntfs_cb_lock - spinlock which protects ntfs_compression_buffer
  44. */
  45. static DEFINE_SPINLOCK(ntfs_cb_lock);
  46. /**
  47. * allocate_compression_buffers - allocate the decompression buffers
  48. *
  49. * Caller has to hold the ntfs_lock mutex.
  50. *
  51. * Return 0 on success or -ENOMEM if the allocations failed.
  52. */
  53. int allocate_compression_buffers(void)
  54. {
  55. BUG_ON(ntfs_compression_buffer);
  56. ntfs_compression_buffer = vmalloc(NTFS_MAX_CB_SIZE);
  57. if (!ntfs_compression_buffer)
  58. return -ENOMEM;
  59. return 0;
  60. }
  61. /**
  62. * free_compression_buffers - free the decompression buffers
  63. *
  64. * Caller has to hold the ntfs_lock mutex.
  65. */
  66. void free_compression_buffers(void)
  67. {
  68. BUG_ON(!ntfs_compression_buffer);
  69. vfree(ntfs_compression_buffer);
  70. ntfs_compression_buffer = NULL;
  71. }
  72. /**
  73. * zero_partial_compressed_page - zero out of bounds compressed page region
  74. */
  75. static void zero_partial_compressed_page(struct page *page,
  76. const s64 initialized_size)
  77. {
  78. u8 *kp = page_address(page);
  79. unsigned int kp_ofs;
  80. ntfs_debug("Zeroing page region outside initialized size.");
  81. if (((s64)page->index << PAGE_SHIFT) >= initialized_size) {
  82. clear_page(kp);
  83. return;
  84. }
  85. kp_ofs = initialized_size & ~PAGE_MASK;
  86. memset(kp + kp_ofs, 0, PAGE_SIZE - kp_ofs);
  87. return;
  88. }
  89. /**
  90. * handle_bounds_compressed_page - test for&handle out of bounds compressed page
  91. */
  92. static inline void handle_bounds_compressed_page(struct page *page,
  93. const loff_t i_size, const s64 initialized_size)
  94. {
  95. if ((page->index >= (initialized_size >> PAGE_SHIFT)) &&
  96. (initialized_size < i_size))
  97. zero_partial_compressed_page(page, initialized_size);
  98. return;
  99. }
  100. /**
  101. * ntfs_decompress - decompress a compression block into an array of pages
  102. * @dest_pages: destination array of pages
  103. * @completed_pages: scratch space to track completed pages
  104. * @dest_index: current index into @dest_pages (IN/OUT)
  105. * @dest_ofs: current offset within @dest_pages[@dest_index] (IN/OUT)
  106. * @dest_max_index: maximum index into @dest_pages (IN)
  107. * @dest_max_ofs: maximum offset within @dest_pages[@dest_max_index] (IN)
  108. * @xpage: the target page (-1 if none) (IN)
  109. * @xpage_done: set to 1 if xpage was completed successfully (IN/OUT)
  110. * @cb_start: compression block to decompress (IN)
  111. * @cb_size: size of compression block @cb_start in bytes (IN)
  112. * @i_size: file size when we started the read (IN)
  113. * @initialized_size: initialized file size when we started the read (IN)
  114. *
  115. * The caller must have disabled preemption. ntfs_decompress() reenables it when
  116. * the critical section is finished.
  117. *
  118. * This decompresses the compression block @cb_start into the array of
  119. * destination pages @dest_pages starting at index @dest_index into @dest_pages
  120. * and at offset @dest_pos into the page @dest_pages[@dest_index].
  121. *
  122. * When the page @dest_pages[@xpage] is completed, @xpage_done is set to 1.
  123. * If xpage is -1 or @xpage has not been completed, @xpage_done is not modified.
  124. *
  125. * @cb_start is a pointer to the compression block which needs decompressing
  126. * and @cb_size is the size of @cb_start in bytes (8-64kiB).
  127. *
  128. * Return 0 if success or -EOVERFLOW on error in the compressed stream.
  129. * @xpage_done indicates whether the target page (@dest_pages[@xpage]) was
  130. * completed during the decompression of the compression block (@cb_start).
  131. *
  132. * Warning: This function *REQUIRES* PAGE_SIZE >= 4096 or it will blow up
  133. * unpredicatbly! You have been warned!
  134. *
  135. * Note to hackers: This function may not sleep until it has finished accessing
  136. * the compression block @cb_start as it is a per-CPU buffer.
  137. */
  138. static int ntfs_decompress(struct page *dest_pages[], int completed_pages[],
  139. int *dest_index, int *dest_ofs, const int dest_max_index,
  140. const int dest_max_ofs, const int xpage, char *xpage_done,
  141. u8 *const cb_start, const u32 cb_size, const loff_t i_size,
  142. const s64 initialized_size)
  143. {
  144. /*
  145. * Pointers into the compressed data, i.e. the compression block (cb),
  146. * and the therein contained sub-blocks (sb).
  147. */
  148. u8 *cb_end = cb_start + cb_size; /* End of cb. */
  149. u8 *cb = cb_start; /* Current position in cb. */
  150. u8 *cb_sb_start = cb; /* Beginning of the current sb in the cb. */
  151. u8 *cb_sb_end; /* End of current sb / beginning of next sb. */
  152. /* Variables for uncompressed data / destination. */
  153. struct page *dp; /* Current destination page being worked on. */
  154. u8 *dp_addr; /* Current pointer into dp. */
  155. u8 *dp_sb_start; /* Start of current sub-block in dp. */
  156. u8 *dp_sb_end; /* End of current sb in dp (dp_sb_start +
  157. NTFS_SB_SIZE). */
  158. u16 do_sb_start; /* @dest_ofs when starting this sub-block. */
  159. u16 do_sb_end; /* @dest_ofs of end of this sb (do_sb_start +
  160. NTFS_SB_SIZE). */
  161. /* Variables for tag and token parsing. */
  162. u8 tag; /* Current tag. */
  163. int token; /* Loop counter for the eight tokens in tag. */
  164. int nr_completed_pages = 0;
  165. /* Default error code. */
  166. int err = -EOVERFLOW;
  167. ntfs_debug("Entering, cb_size = 0x%x.", cb_size);
  168. do_next_sb:
  169. ntfs_debug("Beginning sub-block at offset = 0x%zx in the cb.",
  170. cb - cb_start);
  171. /*
  172. * Have we reached the end of the compression block or the end of the
  173. * decompressed data? The latter can happen for example if the current
  174. * position in the compression block is one byte before its end so the
  175. * first two checks do not detect it.
  176. */
  177. if (cb == cb_end || !le16_to_cpup((le16*)cb) ||
  178. (*dest_index == dest_max_index &&
  179. *dest_ofs == dest_max_ofs)) {
  180. int i;
  181. ntfs_debug("Completed. Returning success (0).");
  182. err = 0;
  183. return_error:
  184. /* We can sleep from now on, so we drop lock. */
  185. spin_unlock(&ntfs_cb_lock);
  186. /* Second stage: finalize completed pages. */
  187. if (nr_completed_pages > 0) {
  188. for (i = 0; i < nr_completed_pages; i++) {
  189. int di = completed_pages[i];
  190. dp = dest_pages[di];
  191. /*
  192. * If we are outside the initialized size, zero
  193. * the out of bounds page range.
  194. */
  195. handle_bounds_compressed_page(dp, i_size,
  196. initialized_size);
  197. flush_dcache_page(dp);
  198. kunmap(dp);
  199. SetPageUptodate(dp);
  200. unlock_page(dp);
  201. if (di == xpage)
  202. *xpage_done = 1;
  203. else
  204. put_page(dp);
  205. dest_pages[di] = NULL;
  206. }
  207. }
  208. return err;
  209. }
  210. /* Setup offsets for the current sub-block destination. */
  211. do_sb_start = *dest_ofs;
  212. do_sb_end = do_sb_start + NTFS_SB_SIZE;
  213. /* Check that we are still within allowed boundaries. */
  214. if (*dest_index == dest_max_index && do_sb_end > dest_max_ofs)
  215. goto return_overflow;
  216. /* Does the minimum size of a compressed sb overflow valid range? */
  217. if (cb + 6 > cb_end)
  218. goto return_overflow;
  219. /* Setup the current sub-block source pointers and validate range. */
  220. cb_sb_start = cb;
  221. cb_sb_end = cb_sb_start + (le16_to_cpup((le16*)cb) & NTFS_SB_SIZE_MASK)
  222. + 3;
  223. if (cb_sb_end > cb_end)
  224. goto return_overflow;
  225. /* Get the current destination page. */
  226. dp = dest_pages[*dest_index];
  227. if (!dp) {
  228. /* No page present. Skip decompression of this sub-block. */
  229. cb = cb_sb_end;
  230. /* Advance destination position to next sub-block. */
  231. *dest_ofs = (*dest_ofs + NTFS_SB_SIZE) & ~PAGE_MASK;
  232. if (!*dest_ofs && (++*dest_index > dest_max_index))
  233. goto return_overflow;
  234. goto do_next_sb;
  235. }
  236. /* We have a valid destination page. Setup the destination pointers. */
  237. dp_addr = (u8*)page_address(dp) + do_sb_start;
  238. /* Now, we are ready to process the current sub-block (sb). */
  239. if (!(le16_to_cpup((le16*)cb) & NTFS_SB_IS_COMPRESSED)) {
  240. ntfs_debug("Found uncompressed sub-block.");
  241. /* This sb is not compressed, just copy it into destination. */
  242. /* Advance source position to first data byte. */
  243. cb += 2;
  244. /* An uncompressed sb must be full size. */
  245. if (cb_sb_end - cb != NTFS_SB_SIZE)
  246. goto return_overflow;
  247. /* Copy the block and advance the source position. */
  248. memcpy(dp_addr, cb, NTFS_SB_SIZE);
  249. cb += NTFS_SB_SIZE;
  250. /* Advance destination position to next sub-block. */
  251. *dest_ofs += NTFS_SB_SIZE;
  252. if (!(*dest_ofs &= ~PAGE_MASK)) {
  253. finalize_page:
  254. /*
  255. * First stage: add current page index to array of
  256. * completed pages.
  257. */
  258. completed_pages[nr_completed_pages++] = *dest_index;
  259. if (++*dest_index > dest_max_index)
  260. goto return_overflow;
  261. }
  262. goto do_next_sb;
  263. }
  264. ntfs_debug("Found compressed sub-block.");
  265. /* This sb is compressed, decompress it into destination. */
  266. /* Setup destination pointers. */
  267. dp_sb_start = dp_addr;
  268. dp_sb_end = dp_sb_start + NTFS_SB_SIZE;
  269. /* Forward to the first tag in the sub-block. */
  270. cb += 2;
  271. do_next_tag:
  272. if (cb == cb_sb_end) {
  273. /* Check if the decompressed sub-block was not full-length. */
  274. if (dp_addr < dp_sb_end) {
  275. int nr_bytes = do_sb_end - *dest_ofs;
  276. ntfs_debug("Filling incomplete sub-block with "
  277. "zeroes.");
  278. /* Zero remainder and update destination position. */
  279. memset(dp_addr, 0, nr_bytes);
  280. *dest_ofs += nr_bytes;
  281. }
  282. /* We have finished the current sub-block. */
  283. if (!(*dest_ofs &= ~PAGE_MASK))
  284. goto finalize_page;
  285. goto do_next_sb;
  286. }
  287. /* Check we are still in range. */
  288. if (cb > cb_sb_end || dp_addr > dp_sb_end)
  289. goto return_overflow;
  290. /* Get the next tag and advance to first token. */
  291. tag = *cb++;
  292. /* Parse the eight tokens described by the tag. */
  293. for (token = 0; token < 8; token++, tag >>= 1) {
  294. u16 lg, pt, length, max_non_overlap;
  295. register u16 i;
  296. u8 *dp_back_addr;
  297. /* Check if we are done / still in range. */
  298. if (cb >= cb_sb_end || dp_addr > dp_sb_end)
  299. break;
  300. /* Determine token type and parse appropriately.*/
  301. if ((tag & NTFS_TOKEN_MASK) == NTFS_SYMBOL_TOKEN) {
  302. /*
  303. * We have a symbol token, copy the symbol across, and
  304. * advance the source and destination positions.
  305. */
  306. *dp_addr++ = *cb++;
  307. ++*dest_ofs;
  308. /* Continue with the next token. */
  309. continue;
  310. }
  311. /*
  312. * We have a phrase token. Make sure it is not the first tag in
  313. * the sb as this is illegal and would confuse the code below.
  314. */
  315. if (dp_addr == dp_sb_start)
  316. goto return_overflow;
  317. /*
  318. * Determine the number of bytes to go back (p) and the number
  319. * of bytes to copy (l). We use an optimized algorithm in which
  320. * we first calculate log2(current destination position in sb),
  321. * which allows determination of l and p in O(1) rather than
  322. * O(n). We just need an arch-optimized log2() function now.
  323. */
  324. lg = 0;
  325. for (i = *dest_ofs - do_sb_start - 1; i >= 0x10; i >>= 1)
  326. lg++;
  327. /* Get the phrase token into i. */
  328. pt = le16_to_cpup((le16*)cb);
  329. /*
  330. * Calculate starting position of the byte sequence in
  331. * the destination using the fact that p = (pt >> (12 - lg)) + 1
  332. * and make sure we don't go too far back.
  333. */
  334. dp_back_addr = dp_addr - (pt >> (12 - lg)) - 1;
  335. if (dp_back_addr < dp_sb_start)
  336. goto return_overflow;
  337. /* Now calculate the length of the byte sequence. */
  338. length = (pt & (0xfff >> lg)) + 3;
  339. /* Advance destination position and verify it is in range. */
  340. *dest_ofs += length;
  341. if (*dest_ofs > do_sb_end)
  342. goto return_overflow;
  343. /* The number of non-overlapping bytes. */
  344. max_non_overlap = dp_addr - dp_back_addr;
  345. if (length <= max_non_overlap) {
  346. /* The byte sequence doesn't overlap, just copy it. */
  347. memcpy(dp_addr, dp_back_addr, length);
  348. /* Advance destination pointer. */
  349. dp_addr += length;
  350. } else {
  351. /*
  352. * The byte sequence does overlap, copy non-overlapping
  353. * part and then do a slow byte by byte copy for the
  354. * overlapping part. Also, advance the destination
  355. * pointer.
  356. */
  357. memcpy(dp_addr, dp_back_addr, max_non_overlap);
  358. dp_addr += max_non_overlap;
  359. dp_back_addr += max_non_overlap;
  360. length -= max_non_overlap;
  361. while (length--)
  362. *dp_addr++ = *dp_back_addr++;
  363. }
  364. /* Advance source position and continue with the next token. */
  365. cb += 2;
  366. }
  367. /* No tokens left in the current tag. Continue with the next tag. */
  368. goto do_next_tag;
  369. return_overflow:
  370. ntfs_error(NULL, "Failed. Returning -EOVERFLOW.");
  371. goto return_error;
  372. }
  373. /**
  374. * ntfs_read_compressed_block - read a compressed block into the page cache
  375. * @page: locked page in the compression block(s) we need to read
  376. *
  377. * When we are called the page has already been verified to be locked and the
  378. * attribute is known to be non-resident, not encrypted, but compressed.
  379. *
  380. * 1. Determine which compression block(s) @page is in.
  381. * 2. Get hold of all pages corresponding to this/these compression block(s).
  382. * 3. Read the (first) compression block.
  383. * 4. Decompress it into the corresponding pages.
  384. * 5. Throw the compressed data away and proceed to 3. for the next compression
  385. * block or return success if no more compression blocks left.
  386. *
  387. * Warning: We have to be careful what we do about existing pages. They might
  388. * have been written to so that we would lose data if we were to just overwrite
  389. * them with the out-of-date uncompressed data.
  390. *
  391. * FIXME: For PAGE_SIZE > cb_size we are not doing the Right Thing(TM) at
  392. * the end of the file I think. We need to detect this case and zero the out
  393. * of bounds remainder of the page in question and mark it as handled. At the
  394. * moment we would just return -EIO on such a page. This bug will only become
  395. * apparent if pages are above 8kiB and the NTFS volume only uses 512 byte
  396. * clusters so is probably not going to be seen by anyone. Still this should
  397. * be fixed. (AIA)
  398. *
  399. * FIXME: Again for PAGE_SIZE > cb_size we are screwing up both in
  400. * handling sparse and compressed cbs. (AIA)
  401. *
  402. * FIXME: At the moment we don't do any zeroing out in the case that
  403. * initialized_size is less than data_size. This should be safe because of the
  404. * nature of the compression algorithm used. Just in case we check and output
  405. * an error message in read inode if the two sizes are not equal for a
  406. * compressed file. (AIA)
  407. */
  408. int ntfs_read_compressed_block(struct page *page)
  409. {
  410. loff_t i_size;
  411. s64 initialized_size;
  412. struct address_space *mapping = page->mapping;
  413. ntfs_inode *ni = NTFS_I(mapping->host);
  414. ntfs_volume *vol = ni->vol;
  415. struct super_block *sb = vol->sb;
  416. runlist_element *rl;
  417. unsigned long flags, block_size = sb->s_blocksize;
  418. unsigned char block_size_bits = sb->s_blocksize_bits;
  419. u8 *cb, *cb_pos, *cb_end;
  420. struct buffer_head **bhs;
  421. unsigned long offset, index = page->index;
  422. u32 cb_size = ni->itype.compressed.block_size;
  423. u64 cb_size_mask = cb_size - 1UL;
  424. VCN vcn;
  425. LCN lcn;
  426. /* The first wanted vcn (minimum alignment is PAGE_SIZE). */
  427. VCN start_vcn = (((s64)index << PAGE_SHIFT) & ~cb_size_mask) >>
  428. vol->cluster_size_bits;
  429. /*
  430. * The first vcn after the last wanted vcn (minimum alignment is again
  431. * PAGE_SIZE.
  432. */
  433. VCN end_vcn = ((((s64)(index + 1UL) << PAGE_SHIFT) + cb_size - 1)
  434. & ~cb_size_mask) >> vol->cluster_size_bits;
  435. /* Number of compression blocks (cbs) in the wanted vcn range. */
  436. unsigned int nr_cbs = (end_vcn - start_vcn) << vol->cluster_size_bits
  437. >> ni->itype.compressed.block_size_bits;
  438. /*
  439. * Number of pages required to store the uncompressed data from all
  440. * compression blocks (cbs) overlapping @page. Due to alignment
  441. * guarantees of start_vcn and end_vcn, no need to round up here.
  442. */
  443. unsigned int nr_pages = (end_vcn - start_vcn) <<
  444. vol->cluster_size_bits >> PAGE_SHIFT;
  445. unsigned int xpage, max_page, cur_page, cur_ofs, i;
  446. unsigned int cb_clusters, cb_max_ofs;
  447. int block, max_block, cb_max_page, bhs_size, nr_bhs, err = 0;
  448. struct page **pages;
  449. int *completed_pages;
  450. unsigned char xpage_done = 0;
  451. ntfs_debug("Entering, page->index = 0x%lx, cb_size = 0x%x, nr_pages = "
  452. "%i.", index, cb_size, nr_pages);
  453. /*
  454. * Bad things happen if we get here for anything that is not an
  455. * unnamed $DATA attribute.
  456. */
  457. BUG_ON(ni->type != AT_DATA);
  458. BUG_ON(ni->name_len);
  459. pages = kmalloc_array(nr_pages, sizeof(struct page *), GFP_NOFS);
  460. completed_pages = kmalloc_array(nr_pages + 1, sizeof(int), GFP_NOFS);
  461. /* Allocate memory to store the buffer heads we need. */
  462. bhs_size = cb_size / block_size * sizeof(struct buffer_head *);
  463. bhs = kmalloc(bhs_size, GFP_NOFS);
  464. if (unlikely(!pages || !bhs || !completed_pages)) {
  465. kfree(bhs);
  466. kfree(pages);
  467. kfree(completed_pages);
  468. unlock_page(page);
  469. ntfs_error(vol->sb, "Failed to allocate internal buffers.");
  470. return -ENOMEM;
  471. }
  472. /*
  473. * We have already been given one page, this is the one we must do.
  474. * Once again, the alignment guarantees keep it simple.
  475. */
  476. offset = start_vcn << vol->cluster_size_bits >> PAGE_SHIFT;
  477. xpage = index - offset;
  478. pages[xpage] = page;
  479. /*
  480. * The remaining pages need to be allocated and inserted into the page
  481. * cache, alignment guarantees keep all the below much simpler. (-8
  482. */
  483. read_lock_irqsave(&ni->size_lock, flags);
  484. i_size = i_size_read(VFS_I(ni));
  485. initialized_size = ni->initialized_size;
  486. read_unlock_irqrestore(&ni->size_lock, flags);
  487. max_page = ((i_size + PAGE_SIZE - 1) >> PAGE_SHIFT) -
  488. offset;
  489. /* Is the page fully outside i_size? (truncate in progress) */
  490. if (xpage >= max_page) {
  491. kfree(bhs);
  492. kfree(pages);
  493. kfree(completed_pages);
  494. zero_user(page, 0, PAGE_SIZE);
  495. ntfs_debug("Compressed read outside i_size - truncated?");
  496. SetPageUptodate(page);
  497. unlock_page(page);
  498. return 0;
  499. }
  500. if (nr_pages < max_page)
  501. max_page = nr_pages;
  502. for (i = 0; i < max_page; i++, offset++) {
  503. if (i != xpage)
  504. pages[i] = grab_cache_page_nowait(mapping, offset);
  505. page = pages[i];
  506. if (page) {
  507. /*
  508. * We only (re)read the page if it isn't already read
  509. * in and/or dirty or we would be losing data or at
  510. * least wasting our time.
  511. */
  512. if (!PageDirty(page) && (!PageUptodate(page) ||
  513. PageError(page))) {
  514. ClearPageError(page);
  515. kmap(page);
  516. continue;
  517. }
  518. unlock_page(page);
  519. put_page(page);
  520. pages[i] = NULL;
  521. }
  522. }
  523. /*
  524. * We have the runlist, and all the destination pages we need to fill.
  525. * Now read the first compression block.
  526. */
  527. cur_page = 0;
  528. cur_ofs = 0;
  529. cb_clusters = ni->itype.compressed.block_clusters;
  530. do_next_cb:
  531. nr_cbs--;
  532. nr_bhs = 0;
  533. /* Read all cb buffer heads one cluster at a time. */
  534. rl = NULL;
  535. for (vcn = start_vcn, start_vcn += cb_clusters; vcn < start_vcn;
  536. vcn++) {
  537. bool is_retry = false;
  538. if (!rl) {
  539. lock_retry_remap:
  540. down_read(&ni->runlist.lock);
  541. rl = ni->runlist.rl;
  542. }
  543. if (likely(rl != NULL)) {
  544. /* Seek to element containing target vcn. */
  545. while (rl->length && rl[1].vcn <= vcn)
  546. rl++;
  547. lcn = ntfs_rl_vcn_to_lcn(rl, vcn);
  548. } else
  549. lcn = LCN_RL_NOT_MAPPED;
  550. ntfs_debug("Reading vcn = 0x%llx, lcn = 0x%llx.",
  551. (unsigned long long)vcn,
  552. (unsigned long long)lcn);
  553. if (lcn < 0) {
  554. /*
  555. * When we reach the first sparse cluster we have
  556. * finished with the cb.
  557. */
  558. if (lcn == LCN_HOLE)
  559. break;
  560. if (is_retry || lcn != LCN_RL_NOT_MAPPED)
  561. goto rl_err;
  562. is_retry = true;
  563. /*
  564. * Attempt to map runlist, dropping lock for the
  565. * duration.
  566. */
  567. up_read(&ni->runlist.lock);
  568. if (!ntfs_map_runlist(ni, vcn))
  569. goto lock_retry_remap;
  570. goto map_rl_err;
  571. }
  572. block = lcn << vol->cluster_size_bits >> block_size_bits;
  573. /* Read the lcn from device in chunks of block_size bytes. */
  574. max_block = block + (vol->cluster_size >> block_size_bits);
  575. do {
  576. ntfs_debug("block = 0x%x.", block);
  577. if (unlikely(!(bhs[nr_bhs] = sb_getblk(sb, block))))
  578. goto getblk_err;
  579. nr_bhs++;
  580. } while (++block < max_block);
  581. }
  582. /* Release the lock if we took it. */
  583. if (rl)
  584. up_read(&ni->runlist.lock);
  585. /* Setup and initiate io on all buffer heads. */
  586. for (i = 0; i < nr_bhs; i++) {
  587. struct buffer_head *tbh = bhs[i];
  588. if (!trylock_buffer(tbh))
  589. continue;
  590. if (unlikely(buffer_uptodate(tbh))) {
  591. unlock_buffer(tbh);
  592. continue;
  593. }
  594. get_bh(tbh);
  595. tbh->b_end_io = end_buffer_read_sync;
  596. submit_bh(REQ_OP_READ, 0, tbh);
  597. }
  598. /* Wait for io completion on all buffer heads. */
  599. for (i = 0; i < nr_bhs; i++) {
  600. struct buffer_head *tbh = bhs[i];
  601. if (buffer_uptodate(tbh))
  602. continue;
  603. wait_on_buffer(tbh);
  604. /*
  605. * We need an optimization barrier here, otherwise we start
  606. * hitting the below fixup code when accessing a loopback
  607. * mounted ntfs partition. This indicates either there is a
  608. * race condition in the loop driver or, more likely, gcc
  609. * overoptimises the code without the barrier and it doesn't
  610. * do the Right Thing(TM).
  611. */
  612. barrier();
  613. if (unlikely(!buffer_uptodate(tbh))) {
  614. ntfs_warning(vol->sb, "Buffer is unlocked but not "
  615. "uptodate! Unplugging the disk queue "
  616. "and rescheduling.");
  617. get_bh(tbh);
  618. io_schedule();
  619. put_bh(tbh);
  620. if (unlikely(!buffer_uptodate(tbh)))
  621. goto read_err;
  622. ntfs_warning(vol->sb, "Buffer is now uptodate. Good.");
  623. }
  624. }
  625. /*
  626. * Get the compression buffer. We must not sleep any more
  627. * until we are finished with it.
  628. */
  629. spin_lock(&ntfs_cb_lock);
  630. cb = ntfs_compression_buffer;
  631. BUG_ON(!cb);
  632. cb_pos = cb;
  633. cb_end = cb + cb_size;
  634. /* Copy the buffer heads into the contiguous buffer. */
  635. for (i = 0; i < nr_bhs; i++) {
  636. memcpy(cb_pos, bhs[i]->b_data, block_size);
  637. cb_pos += block_size;
  638. }
  639. /* Just a precaution. */
  640. if (cb_pos + 2 <= cb + cb_size)
  641. *(u16*)cb_pos = 0;
  642. /* Reset cb_pos back to the beginning. */
  643. cb_pos = cb;
  644. /* We now have both source (if present) and destination. */
  645. ntfs_debug("Successfully read the compression block.");
  646. /* The last page and maximum offset within it for the current cb. */
  647. cb_max_page = (cur_page << PAGE_SHIFT) + cur_ofs + cb_size;
  648. cb_max_ofs = cb_max_page & ~PAGE_MASK;
  649. cb_max_page >>= PAGE_SHIFT;
  650. /* Catch end of file inside a compression block. */
  651. if (cb_max_page > max_page)
  652. cb_max_page = max_page;
  653. if (vcn == start_vcn - cb_clusters) {
  654. /* Sparse cb, zero out page range overlapping the cb. */
  655. ntfs_debug("Found sparse compression block.");
  656. /* We can sleep from now on, so we drop lock. */
  657. spin_unlock(&ntfs_cb_lock);
  658. if (cb_max_ofs)
  659. cb_max_page--;
  660. for (; cur_page < cb_max_page; cur_page++) {
  661. page = pages[cur_page];
  662. if (page) {
  663. if (likely(!cur_ofs))
  664. clear_page(page_address(page));
  665. else
  666. memset(page_address(page) + cur_ofs, 0,
  667. PAGE_SIZE -
  668. cur_ofs);
  669. flush_dcache_page(page);
  670. kunmap(page);
  671. SetPageUptodate(page);
  672. unlock_page(page);
  673. if (cur_page == xpage)
  674. xpage_done = 1;
  675. else
  676. put_page(page);
  677. pages[cur_page] = NULL;
  678. }
  679. cb_pos += PAGE_SIZE - cur_ofs;
  680. cur_ofs = 0;
  681. if (cb_pos >= cb_end)
  682. break;
  683. }
  684. /* If we have a partial final page, deal with it now. */
  685. if (cb_max_ofs && cb_pos < cb_end) {
  686. page = pages[cur_page];
  687. if (page)
  688. memset(page_address(page) + cur_ofs, 0,
  689. cb_max_ofs - cur_ofs);
  690. /*
  691. * No need to update cb_pos at this stage:
  692. * cb_pos += cb_max_ofs - cur_ofs;
  693. */
  694. cur_ofs = cb_max_ofs;
  695. }
  696. } else if (vcn == start_vcn) {
  697. /* We can't sleep so we need two stages. */
  698. unsigned int cur2_page = cur_page;
  699. unsigned int cur_ofs2 = cur_ofs;
  700. u8 *cb_pos2 = cb_pos;
  701. ntfs_debug("Found uncompressed compression block.");
  702. /* Uncompressed cb, copy it to the destination pages. */
  703. /*
  704. * TODO: As a big optimization, we could detect this case
  705. * before we read all the pages and use block_read_full_page()
  706. * on all full pages instead (we still have to treat partial
  707. * pages especially but at least we are getting rid of the
  708. * synchronous io for the majority of pages.
  709. * Or if we choose not to do the read-ahead/-behind stuff, we
  710. * could just return block_read_full_page(pages[xpage]) as long
  711. * as PAGE_SIZE <= cb_size.
  712. */
  713. if (cb_max_ofs)
  714. cb_max_page--;
  715. /* First stage: copy data into destination pages. */
  716. for (; cur_page < cb_max_page; cur_page++) {
  717. page = pages[cur_page];
  718. if (page)
  719. memcpy(page_address(page) + cur_ofs, cb_pos,
  720. PAGE_SIZE - cur_ofs);
  721. cb_pos += PAGE_SIZE - cur_ofs;
  722. cur_ofs = 0;
  723. if (cb_pos >= cb_end)
  724. break;
  725. }
  726. /* If we have a partial final page, deal with it now. */
  727. if (cb_max_ofs && cb_pos < cb_end) {
  728. page = pages[cur_page];
  729. if (page)
  730. memcpy(page_address(page) + cur_ofs, cb_pos,
  731. cb_max_ofs - cur_ofs);
  732. cb_pos += cb_max_ofs - cur_ofs;
  733. cur_ofs = cb_max_ofs;
  734. }
  735. /* We can sleep from now on, so drop lock. */
  736. spin_unlock(&ntfs_cb_lock);
  737. /* Second stage: finalize pages. */
  738. for (; cur2_page < cb_max_page; cur2_page++) {
  739. page = pages[cur2_page];
  740. if (page) {
  741. /*
  742. * If we are outside the initialized size, zero
  743. * the out of bounds page range.
  744. */
  745. handle_bounds_compressed_page(page, i_size,
  746. initialized_size);
  747. flush_dcache_page(page);
  748. kunmap(page);
  749. SetPageUptodate(page);
  750. unlock_page(page);
  751. if (cur2_page == xpage)
  752. xpage_done = 1;
  753. else
  754. put_page(page);
  755. pages[cur2_page] = NULL;
  756. }
  757. cb_pos2 += PAGE_SIZE - cur_ofs2;
  758. cur_ofs2 = 0;
  759. if (cb_pos2 >= cb_end)
  760. break;
  761. }
  762. } else {
  763. /* Compressed cb, decompress it into the destination page(s). */
  764. unsigned int prev_cur_page = cur_page;
  765. ntfs_debug("Found compressed compression block.");
  766. err = ntfs_decompress(pages, completed_pages, &cur_page,
  767. &cur_ofs, cb_max_page, cb_max_ofs, xpage,
  768. &xpage_done, cb_pos, cb_size - (cb_pos - cb),
  769. i_size, initialized_size);
  770. /*
  771. * We can sleep from now on, lock already dropped by
  772. * ntfs_decompress().
  773. */
  774. if (err) {
  775. ntfs_error(vol->sb, "ntfs_decompress() failed in inode "
  776. "0x%lx with error code %i. Skipping "
  777. "this compression block.",
  778. ni->mft_no, -err);
  779. /* Release the unfinished pages. */
  780. for (; prev_cur_page < cur_page; prev_cur_page++) {
  781. page = pages[prev_cur_page];
  782. if (page) {
  783. flush_dcache_page(page);
  784. kunmap(page);
  785. unlock_page(page);
  786. if (prev_cur_page != xpage)
  787. put_page(page);
  788. pages[prev_cur_page] = NULL;
  789. }
  790. }
  791. }
  792. }
  793. /* Release the buffer heads. */
  794. for (i = 0; i < nr_bhs; i++)
  795. brelse(bhs[i]);
  796. /* Do we have more work to do? */
  797. if (nr_cbs)
  798. goto do_next_cb;
  799. /* We no longer need the list of buffer heads. */
  800. kfree(bhs);
  801. /* Clean up if we have any pages left. Should never happen. */
  802. for (cur_page = 0; cur_page < max_page; cur_page++) {
  803. page = pages[cur_page];
  804. if (page) {
  805. ntfs_error(vol->sb, "Still have pages left! "
  806. "Terminating them with extreme "
  807. "prejudice. Inode 0x%lx, page index "
  808. "0x%lx.", ni->mft_no, page->index);
  809. flush_dcache_page(page);
  810. kunmap(page);
  811. unlock_page(page);
  812. if (cur_page != xpage)
  813. put_page(page);
  814. pages[cur_page] = NULL;
  815. }
  816. }
  817. /* We no longer need the list of pages. */
  818. kfree(pages);
  819. kfree(completed_pages);
  820. /* If we have completed the requested page, we return success. */
  821. if (likely(xpage_done))
  822. return 0;
  823. ntfs_debug("Failed. Returning error code %s.", err == -EOVERFLOW ?
  824. "EOVERFLOW" : (!err ? "EIO" : "unknown error"));
  825. return err < 0 ? err : -EIO;
  826. read_err:
  827. ntfs_error(vol->sb, "IO error while reading compressed data.");
  828. /* Release the buffer heads. */
  829. for (i = 0; i < nr_bhs; i++)
  830. brelse(bhs[i]);
  831. goto err_out;
  832. map_rl_err:
  833. ntfs_error(vol->sb, "ntfs_map_runlist() failed. Cannot read "
  834. "compression block.");
  835. goto err_out;
  836. rl_err:
  837. up_read(&ni->runlist.lock);
  838. ntfs_error(vol->sb, "ntfs_rl_vcn_to_lcn() failed. Cannot read "
  839. "compression block.");
  840. goto err_out;
  841. getblk_err:
  842. up_read(&ni->runlist.lock);
  843. ntfs_error(vol->sb, "getblk() failed. Cannot read compression block.");
  844. err_out:
  845. kfree(bhs);
  846. for (i = cur_page; i < max_page; i++) {
  847. page = pages[i];
  848. if (page) {
  849. flush_dcache_page(page);
  850. kunmap(page);
  851. unlock_page(page);
  852. if (i != xpage)
  853. put_page(page);
  854. }
  855. }
  856. kfree(pages);
  857. kfree(completed_pages);
  858. return -EIO;
  859. }