patch-2_6_7-vs1_9_1_12
[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.");
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, 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         if (nr_pages < max_page)
554                 max_page = nr_pages;
555         for (i = 0; i < max_page; i++, offset++) {
556                 if (i != xpage)
557                         pages[i] = grab_cache_page_nowait(mapping, offset);
558                 page = pages[i];
559                 if (page) {
560                         /*
561                          * We only (re)read the page if it isn't already read
562                          * in and/or dirty or we would be losing data or at
563                          * least wasting our time.
564                          */
565                         if (!PageDirty(page) && (!PageUptodate(page) ||
566                                         PageError(page))) {
567                                 ClearPageError(page);
568                                 kmap(page);
569                                 continue;
570                         }
571                         unlock_page(page);
572                         page_cache_release(page);
573                         pages[i] = NULL;
574                 }
575         }
576
577         /*
578          * We have the run list, and all the destination pages we need to fill.
579          * Now read the first compression block.
580          */
581         cur_page = 0;
582         cur_ofs = 0;
583         cb_clusters = ni->itype.compressed.block_clusters;
584 do_next_cb:
585         nr_cbs--;
586         nr_bhs = 0;
587
588         /* Read all cb buffer heads one cluster at a time. */
589         rl = NULL;
590         for (vcn = start_vcn, start_vcn += cb_clusters; vcn < start_vcn;
591                         vcn++) {
592                 BOOL is_retry = FALSE;
593
594                 if (!rl) {
595 lock_retry_remap:
596                         down_read(&ni->run_list.lock);
597                         rl = ni->run_list.rl;
598                 }
599                 if (likely(rl != NULL)) {
600                         /* Seek to element containing target vcn. */
601                         while (rl->length && rl[1].vcn <= vcn)
602                                 rl++;
603                         lcn = vcn_to_lcn(rl, vcn);
604                 } else
605                         lcn = (LCN)LCN_RL_NOT_MAPPED;
606                 ntfs_debug("Reading vcn = 0x%llx, lcn = 0x%llx.",
607                                 (unsigned long long)vcn,
608                                 (unsigned long long)lcn);
609                 if (lcn < 0) {
610                         /*
611                          * When we reach the first sparse cluster we have
612                          * finished with the cb.
613                          */
614                         if (lcn == LCN_HOLE)
615                                 break;
616                         if (is_retry || lcn != LCN_RL_NOT_MAPPED)
617                                 goto rl_err;
618                         is_retry = TRUE;
619                         /*
620                          * Attempt to map run list, dropping lock for the
621                          * duration.
622                          */
623                         up_read(&ni->run_list.lock);
624                         if (!map_run_list(ni, vcn))
625                                 goto lock_retry_remap;
626                         goto map_rl_err;
627                 }
628                 block = lcn << vol->cluster_size_bits >> block_size_bits;
629                 /* Read the lcn from device in chunks of block_size bytes. */
630                 max_block = block + (vol->cluster_size >> block_size_bits);
631                 do {
632                         ntfs_debug("block = 0x%x.", block);
633                         if (unlikely(!(bhs[nr_bhs] = sb_getblk(sb, block))))
634                                 goto getblk_err;
635                         nr_bhs++;
636                 } while (++block < max_block);
637         }
638
639         /* Release the lock if we took it. */
640         if (rl)
641                 up_read(&ni->run_list.lock);
642
643         /* Setup and initiate io on all buffer heads. */
644         for (i = 0; i < nr_bhs; i++) {
645                 struct buffer_head *tbh = bhs[i];
646
647                 if (unlikely(test_set_buffer_locked(tbh)))
648                         continue;
649                 if (unlikely(buffer_uptodate(tbh))) {
650                         unlock_buffer(tbh);
651                         continue;
652                 }
653                 get_bh(tbh);
654                 tbh->b_end_io = end_buffer_read_sync;
655                 submit_bh(READ, tbh);
656         }
657
658         /* Wait for io completion on all buffer heads. */
659         for (i = 0; i < nr_bhs; i++) {
660                 struct buffer_head *tbh = bhs[i];
661
662                 if (buffer_uptodate(tbh))
663                         continue;
664                 wait_on_buffer(tbh);
665                 /*
666                  * We need an optimization barrier here, otherwise we start
667                  * hitting the below fixup code when accessing a loopback
668                  * mounted ntfs partition. This indicates either there is a
669                  * race condition in the loop driver or, more likely, gcc
670                  * overoptimises the code without the barrier and it doesn't
671                  * do the Right Thing(TM).
672                  */
673                 barrier();
674                 if (unlikely(!buffer_uptodate(tbh))) {
675                         ntfs_warning(vol->sb, "Buffer is unlocked but not "
676                                         "uptodate! Unplugging the disk queue "
677                                         "and rescheduling.");
678                         get_bh(tbh);
679                         blk_run_address_space(mapping);
680                         schedule();
681                         put_bh(tbh);
682                         if (unlikely(!buffer_uptodate(tbh)))
683                                 goto read_err;
684                         ntfs_warning(vol->sb, "Buffer is now uptodate. Good.");
685                 }
686         }
687
688         /*
689          * Get the compression buffer. We must not sleep any more
690          * until we are finished with it.
691          */
692         spin_lock(&ntfs_cb_lock);
693         cb = ntfs_compression_buffer;
694
695         BUG_ON(!cb);
696
697         cb_pos = cb;
698         cb_end = cb + cb_size;
699
700         /* Copy the buffer heads into the contiguous buffer. */
701         for (i = 0; i < nr_bhs; i++) {
702                 memcpy(cb_pos, bhs[i]->b_data, block_size);
703                 cb_pos += block_size;
704         }
705
706         /* Just a precaution. */
707         if (cb_pos + 2 <= cb + cb_size)
708                 *(u16*)cb_pos = 0;
709
710         /* Reset cb_pos back to the beginning. */
711         cb_pos = cb;
712
713         /* We now have both source (if present) and destination. */
714         ntfs_debug("Successfully read the compression block.");
715
716         /* The last page and maximum offset within it for the current cb. */
717         cb_max_page = (cur_page << PAGE_CACHE_SHIFT) + cur_ofs + cb_size;
718         cb_max_ofs = cb_max_page & ~PAGE_CACHE_MASK;
719         cb_max_page >>= PAGE_CACHE_SHIFT;
720
721         /* Catch end of file inside a compression block. */
722         if (cb_max_page > max_page)
723                 cb_max_page = max_page;
724
725         if (vcn == start_vcn - cb_clusters) {
726                 /* Sparse cb, zero out page range overlapping the cb. */
727                 ntfs_debug("Found sparse compression block.");
728                 /* We can sleep from now on, so we drop lock. */
729                 spin_unlock(&ntfs_cb_lock);
730                 if (cb_max_ofs)
731                         cb_max_page--;
732                 for (; cur_page < cb_max_page; cur_page++) {
733                         page = pages[cur_page];
734                         if (page) {
735                                 /*
736                                  * FIXME: Using clear_page() will become wrong
737                                  * when we get PAGE_CACHE_SIZE != PAGE_SIZE but
738                                  * for now there is no problem.
739                                  */
740                                 if (likely(!cur_ofs))
741                                         clear_page(page_address(page));
742                                 else
743                                         memset(page_address(page) + cur_ofs, 0,
744                                                         PAGE_CACHE_SIZE -
745                                                         cur_ofs);
746                                 flush_dcache_page(page);
747                                 kunmap(page);
748                                 SetPageUptodate(page);
749                                 unlock_page(page);
750                                 if (cur_page == xpage)
751                                         xpage_done = 1;
752                                 else
753                                         page_cache_release(page);
754                                 pages[cur_page] = NULL;
755                         }
756                         cb_pos += PAGE_CACHE_SIZE - cur_ofs;
757                         cur_ofs = 0;
758                         if (cb_pos >= cb_end)
759                                 break;
760                 }
761                 /* If we have a partial final page, deal with it now. */
762                 if (cb_max_ofs && cb_pos < cb_end) {
763                         page = pages[cur_page];
764                         if (page)
765                                 memset(page_address(page) + cur_ofs, 0,
766                                                 cb_max_ofs - cur_ofs);
767                         /*
768                          * No need to update cb_pos at this stage:
769                          *      cb_pos += cb_max_ofs - cur_ofs;
770                          */
771                         cur_ofs = cb_max_ofs;
772                 }
773         } else if (vcn == start_vcn) {
774                 /* We can't sleep so we need two stages. */
775                 unsigned int cur2_page = cur_page;
776                 unsigned int cur_ofs2 = cur_ofs;
777                 u8 *cb_pos2 = cb_pos;
778
779                 ntfs_debug("Found uncompressed compression block.");
780                 /* Uncompressed cb, copy it to the destination pages. */
781                 /*
782                  * TODO: As a big optimization, we could detect this case
783                  * before we read all the pages and use block_read_full_page()
784                  * on all full pages instead (we still have to treat partial
785                  * pages especially but at least we are getting rid of the
786                  * synchronous io for the majority of pages.
787                  * Or if we choose not to do the read-ahead/-behind stuff, we
788                  * could just return block_read_full_page(pages[xpage]) as long
789                  * as PAGE_CACHE_SIZE <= cb_size.
790                  */
791                 if (cb_max_ofs)
792                         cb_max_page--;
793                 /* First stage: copy data into destination pages. */
794                 for (; cur_page < cb_max_page; cur_page++) {
795                         page = pages[cur_page];
796                         if (page)
797                                 memcpy(page_address(page) + cur_ofs, cb_pos,
798                                                 PAGE_CACHE_SIZE - cur_ofs);
799                         cb_pos += PAGE_CACHE_SIZE - cur_ofs;
800                         cur_ofs = 0;
801                         if (cb_pos >= cb_end)
802                                 break;
803                 }
804                 /* If we have a partial final page, deal with it now. */
805                 if (cb_max_ofs && cb_pos < cb_end) {
806                         page = pages[cur_page];
807                         if (page)
808                                 memcpy(page_address(page) + cur_ofs, cb_pos,
809                                                 cb_max_ofs - cur_ofs);
810                         cb_pos += cb_max_ofs - cur_ofs;
811                         cur_ofs = cb_max_ofs;
812                 }
813                 /* We can sleep from now on, so drop lock. */
814                 spin_unlock(&ntfs_cb_lock);
815                 /* Second stage: finalize pages. */
816                 for (; cur2_page < cb_max_page; cur2_page++) {
817                         page = pages[cur2_page];
818                         if (page) {
819                                 /*
820                                  * If we are outside the initialized size, zero
821                                  * the out of bounds page range.
822                                  */
823                                 handle_bounds_compressed_page(ni, page);
824                                 flush_dcache_page(page);
825                                 kunmap(page);
826                                 SetPageUptodate(page);
827                                 unlock_page(page);
828                                 if (cur2_page == xpage)
829                                         xpage_done = 1;
830                                 else
831                                         page_cache_release(page);
832                                 pages[cur2_page] = NULL;
833                         }
834                         cb_pos2 += PAGE_CACHE_SIZE - cur_ofs2;
835                         cur_ofs2 = 0;
836                         if (cb_pos2 >= cb_end)
837                                 break;
838                 }
839         } else {
840                 /* Compressed cb, decompress it into the destination page(s). */
841                 unsigned int prev_cur_page = cur_page;
842
843                 ntfs_debug("Found compressed compression block.");
844                 err = ntfs_decompress(pages, &cur_page, &cur_ofs,
845                                 cb_max_page, cb_max_ofs, xpage, &xpage_done,
846                                 cb_pos, cb_size - (cb_pos - cb));
847                 /*
848                  * We can sleep from now on, lock already dropped by
849                  * ntfs_decompress().
850                  */
851                 if (err) {
852                         ntfs_error(vol->sb, "ntfs_decompress() failed in inode "
853                                         "0x%lx with error code %i. Skipping "
854                                         "this compression block.",
855                                         ni->mft_no, -err);
856                         /* Release the unfinished pages. */
857                         for (; prev_cur_page < cur_page; prev_cur_page++) {
858                                 page = pages[prev_cur_page];
859                                 if (page) {
860                                         if (prev_cur_page == xpage &&
861                                                         !xpage_done)
862                                                 SetPageError(page);
863                                         flush_dcache_page(page);
864                                         kunmap(page);
865                                         unlock_page(page);
866                                         if (prev_cur_page != xpage)
867                                                 page_cache_release(page);
868                                         pages[prev_cur_page] = NULL;
869                                 }
870                         }
871                 }
872         }
873
874         /* Release the buffer heads. */
875         for (i = 0; i < nr_bhs; i++)
876                 brelse(bhs[i]);
877
878         /* Do we have more work to do? */
879         if (nr_cbs)
880                 goto do_next_cb;
881
882         /* We no longer need the list of buffer heads. */
883         kfree(bhs);
884
885         /* Clean up if we have any pages left. Should never happen. */
886         for (cur_page = 0; cur_page < max_page; cur_page++) {
887                 page = pages[cur_page];
888                 if (page) {
889                         ntfs_error(vol->sb, "Still have pages left! "
890                                         "Terminating them with extreme "
891                                         "prejudice.  Inode 0x%lx, page index "
892                                         "0x%lx.", ni->mft_no, page->index);
893                         if (cur_page == xpage && !xpage_done)
894                                 SetPageError(page);
895                         flush_dcache_page(page);
896                         kunmap(page);
897                         unlock_page(page);
898                         if (cur_page != xpage)
899                                 page_cache_release(page);
900                         pages[cur_page] = NULL;
901                 }
902         }
903
904         /* We no longer need the list of pages. */
905         kfree(pages);
906
907         /* If we have completed the requested page, we return success. */
908         if (likely(xpage_done))
909                 return 0;
910
911         ntfs_debug("Failed. Returning error code %s.", err == -EOVERFLOW ?
912                         "EOVERFLOW" : (!err ? "EIO" : "unkown error"));
913         return err < 0 ? err : -EIO;
914
915 read_err:
916         ntfs_error(vol->sb, "IO error while reading compressed data.");
917         /* Release the buffer heads. */
918         for (i = 0; i < nr_bhs; i++)
919                 brelse(bhs[i]);
920         goto err_out;
921
922 map_rl_err:
923         ntfs_error(vol->sb, "map_run_list() failed. Cannot read compression "
924                         "block.");
925         goto err_out;
926
927 rl_err:
928         up_read(&ni->run_list.lock);
929         ntfs_error(vol->sb, "vcn_to_lcn() failed. Cannot read compression "
930                         "block.");
931         goto err_out;
932
933 getblk_err:
934         up_read(&ni->run_list.lock);
935         ntfs_error(vol->sb, "getblk() failed. Cannot read compression block.");
936
937 err_out:
938         kfree(bhs);
939         for (i = cur_page; i < max_page; i++) {
940                 page = pages[i];
941                 if (page) {
942                         if (i == xpage && !xpage_done)
943                                 SetPageError(page);
944                         flush_dcache_page(page);
945                         kunmap(page);
946                         unlock_page(page);
947                         if (i != xpage)
948                                 page_cache_release(page);
949                 }
950         }
951         kfree(pages);
952         return -EIO;
953 }