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