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