compress.c 29 KB

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