1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3 * NTFS kernel compressed attributes handling.
4 *
5 * Copyright (c) 2001-2004 Anton Altaparmakov
6 * Copyright (c) 2002 Richard Russon
7 * Copyright (c) 2025 LG Electronics Co., Ltd.
8 *
9 * Part of this file is based on code from the NTFS-3G.
10 * and is copyrighted by the respective authors below:
11 * Copyright (c) 2004-2005 Anton Altaparmakov
12 * Copyright (c) 2004-2006 Szabolcs Szakacsits
13 * Copyright (c) 2005 Yura Pakhuchiy
14 * Copyright (c) 2009-2014 Jean-Pierre Andre
15 * Copyright (c) 2014 Eric Biggers
16 */
17
18 #include <linux/fs.h>
19 #include <linux/blkdev.h>
20 #include <linux/vmalloc.h>
21 #include <linux/slab.h>
22
23 #include "attrib.h"
24 #include "ntfs_codec.h"
25 #include "inode.h"
26 #include "debug.h"
27 #include "ntfs.h"
28 #include "lcnalloc.h"
29 #include "mft.h"
30
31 /*
32 * Constants used in the compression code
33 */
34 enum {
35 /* Token types and access mask. */
36 NTFS_SYMBOL_TOKEN = 0,
37 NTFS_PHRASE_TOKEN = 1,
38 NTFS_TOKEN_MASK = 1,
39
40 /* Compression sub-block constants. */
41 NTFS_SB_SIZE_MASK = 0x0fff,
42 NTFS_SB_SIZE = 0x1000,
43 NTFS_SB_IS_COMPRESSED = 0x8000,
44
45 /*
46 * The maximum compression block size is by definition 16 * the cluster
47 * size, with the maximum supported cluster size being 4kiB. Thus the
48 * maximum compression buffer size is 64kiB, so we use this when
49 * initializing the compression buffer.
50 */
51 NTFS_MAX_CB_SIZE = 64 * 1024,
52 };
53
54 /*
55 * ntfs_compression_buffer - one buffer for the decompression engine
56 */
57 static u8 *ntfs_compression_buffer;
58
59 /*
60 * ntfs_cb_lock - mutex lock which protects ntfs_compression_buffer
61 */
62 static DEFINE_MUTEX(ntfs_cb_lock);
63
64 /*
65 * allocate_compression_buffers - allocate the decompression buffers
66 *
67 * Caller has to hold the ntfs_lock mutex.
68 *
69 * Return 0 on success or -ENOMEM if the allocations failed.
70 */
allocate_compression_buffers(void)71 int allocate_compression_buffers(void)
72 {
73 if (ntfs_compression_buffer)
74 return 0;
75
76 ntfs_compression_buffer = vmalloc(NTFS_MAX_CB_SIZE);
77 if (!ntfs_compression_buffer)
78 return -ENOMEM;
79 return 0;
80 }
81
82 /*
83 * free_compression_buffers - free the decompression buffers
84 *
85 * Caller has to hold the ntfs_lock mutex.
86 */
free_compression_buffers(void)87 void free_compression_buffers(void)
88 {
89 mutex_lock(&ntfs_cb_lock);
90 if (!ntfs_compression_buffer) {
91 mutex_unlock(&ntfs_cb_lock);
92 return;
93 }
94
95 vfree(ntfs_compression_buffer);
96 ntfs_compression_buffer = NULL;
97 mutex_unlock(&ntfs_cb_lock);
98 }
99
100 /*
101 * handle_bounds_compressed_page - test for&handle out of bounds compressed page
102 * @page: page to check and handle
103 * @i_size: file size
104 * @initialized_size: initialized size of the attribute
105 */
handle_bounds_compressed_page(struct page * page,const loff_t i_size,const s64 initialized_size)106 static inline void handle_bounds_compressed_page(struct page *page,
107 const loff_t i_size, const s64 initialized_size)
108 {
109 loff_t pos = page_offset(page);
110
111 if ((pos + PAGE_SIZE > initialized_size) &&
112 (initialized_size < i_size)) {
113 size_t offset;
114
115 ntfs_debug("Zeroing page region outside initialized size.");
116 if (pos >= initialized_size)
117 offset = 0;
118 else
119 offset = offset_in_page(initialized_size);
120 zero_user_segment(page, offset, PAGE_SIZE);
121 } else {
122 flush_dcache_page(page);
123 }
124 }
125
126 /*
127 * ntfs_decompress - decompress a compression block into an array of pages
128 * @dest_pages: destination array of pages
129 * @completed_pages: scratch space to track completed pages
130 * @dest_index: current index into @dest_pages (IN/OUT)
131 * @dest_ofs: current offset within @dest_pages[@dest_index] (IN/OUT)
132 * @dest_max_index: maximum index into @dest_pages (IN)
133 * @dest_max_ofs: maximum offset within @dest_pages[@dest_max_index] (IN)
134 * @xpage: the target page (-1 if none) (IN)
135 * @xpage_done: set to 1 if xpage was completed successfully (IN/OUT)
136 * @cb_start: compression block to decompress (IN)
137 * @cb_size: size of compression block @cb_start in bytes (IN)
138 * @i_size: file size when we started the read (IN)
139 * @initialized_size: initialized file size when we started the read (IN)
140 *
141 * The caller must have disabled preemption. ntfs_decompress() reenables it when
142 * the critical section is finished.
143 *
144 * This decompresses the compression block @cb_start into the array of
145 * destination pages @dest_pages starting at index @dest_index into @dest_pages
146 * and at offset @dest_pos into the page @dest_pages[@dest_index].
147 *
148 * When the page @dest_pages[@xpage] is completed, @xpage_done is set to 1.
149 * If xpage is -1 or @xpage has not been completed, @xpage_done is not modified.
150 *
151 * @cb_start is a pointer to the compression block which needs decompressing
152 * and @cb_size is the size of @cb_start in bytes (8-64kiB).
153 *
154 * Return 0 if success or -EOVERFLOW on error in the compressed stream.
155 * @xpage_done indicates whether the target page (@dest_pages[@xpage]) was
156 * completed during the decompression of the compression block (@cb_start).
157 *
158 * Warning: This function *REQUIRES* PAGE_SIZE >= 4096 or it will blow up
159 * unpredicatbly! You have been warned!
160 *
161 * Note to hackers: This function may not sleep until it has finished accessing
162 * the compression block @cb_start as it is a per-CPU buffer.
163 */
ntfs_decompress(struct page * dest_pages[],int completed_pages[],int * dest_index,int * dest_ofs,const int dest_max_index,const int dest_max_ofs,const int xpage,char * xpage_done,u8 * const cb_start,const u32 cb_size,const loff_t i_size,const s64 initialized_size)164 static int ntfs_decompress(struct page *dest_pages[], int completed_pages[],
165 int *dest_index, int *dest_ofs, const int dest_max_index,
166 const int dest_max_ofs, const int xpage, char *xpage_done,
167 u8 *const cb_start, const u32 cb_size, const loff_t i_size,
168 const s64 initialized_size)
169 {
170 /*
171 * Pointers into the compressed data, i.e. the compression block (cb),
172 * and the therein contained sub-blocks (sb).
173 */
174 u8 *cb_end = cb_start + cb_size; /* End of cb. */
175 u8 *cb = cb_start; /* Current position in cb. */
176 u8 *cb_sb_start = cb; /* Beginning of the current sb in the cb. */
177 u8 *cb_sb_end; /* End of current sb / beginning of next sb. */
178
179 /* Variables for uncompressed data / destination. */
180 struct page *dp; /* Current destination page being worked on. */
181 u8 *dp_kaddr; /* Local kmap for the current destination page. */
182 u8 *dp_addr; /* Current pointer into dp. */
183 u8 *dp_sb_start; /* Start of current sub-block in dp. */
184 u8 *dp_sb_end; /* End of current sb in dp (dp_sb_start + NTFS_SB_SIZE). */
185 u16 do_sb_start; /* @dest_ofs when starting this sub-block. */
186 u16 do_sb_end; /* @dest_ofs of end of this sb (do_sb_start + NTFS_SB_SIZE). */
187
188 /* Variables for tag and token parsing. */
189 u8 tag; /* Current tag. */
190 int token; /* Loop counter for the eight tokens in tag. */
191 int nr_completed_pages = 0;
192
193 /* Default error code. */
194 int err = -EOVERFLOW;
195
196 dp_kaddr = NULL;
197 ntfs_debug("Entering, cb_size = 0x%x.", cb_size);
198 do_next_sb:
199 ntfs_debug("Beginning sub-block at offset = 0x%zx in the cb.",
200 cb - cb_start);
201 /*
202 * Have we reached the end of the compression block or the end of the
203 * decompressed data? The latter can happen for example if the current
204 * position in the compression block is one byte before its end so the
205 * first two checks do not detect it.
206 */
207 if (cb == cb_end || !le16_to_cpup((__le16 *)cb) ||
208 (*dest_index == dest_max_index &&
209 *dest_ofs == dest_max_ofs)) {
210 int i;
211
212 ntfs_debug("Completed. Returning success (0).");
213 err = 0;
214 return_error:
215 /* We can sleep from now on, so we drop lock. */
216 mutex_unlock(&ntfs_cb_lock);
217 /* Second stage: finalize completed pages. */
218 if (nr_completed_pages > 0) {
219 for (i = 0; i < nr_completed_pages; i++) {
220 int di = completed_pages[i];
221
222 dp = dest_pages[di];
223 /*
224 * If we are outside the initialized size, zero
225 * the out of bounds page range.
226 */
227 handle_bounds_compressed_page(dp, i_size,
228 initialized_size);
229 SetPageUptodate(dp);
230 unlock_page(dp);
231 if (di == xpage)
232 *xpage_done = 1;
233 else
234 put_page(dp);
235 dest_pages[di] = NULL;
236 }
237 }
238 return err;
239 }
240
241 /* Setup offsets for the current sub-block destination. */
242 do_sb_start = *dest_ofs;
243 do_sb_end = do_sb_start + NTFS_SB_SIZE;
244
245 /* Check that we are still within allowed boundaries. */
246 if (*dest_index == dest_max_index && do_sb_end > dest_max_ofs)
247 goto return_overflow;
248
249 /* Does the minimum size of a compressed sb overflow valid range? */
250 if (cb + 6 > cb_end)
251 goto return_overflow;
252
253 /* Setup the current sub-block source pointers and validate range. */
254 cb_sb_start = cb;
255 cb_sb_end = cb_sb_start + (le16_to_cpup((__le16 *)cb) & NTFS_SB_SIZE_MASK)
256 + 3;
257 if (cb_sb_end > cb_end)
258 goto return_overflow;
259
260 /* Get the current destination page. */
261 dp = dest_pages[*dest_index];
262 if (!dp) {
263 /* No page present. Skip decompression of this sub-block. */
264 cb = cb_sb_end;
265
266 /* Advance destination position to next sub-block. */
267 *dest_ofs = (*dest_ofs + NTFS_SB_SIZE) & ~PAGE_MASK;
268 if (!*dest_ofs && (++*dest_index > dest_max_index))
269 goto return_overflow;
270 goto do_next_sb;
271 }
272
273 /* We have a valid destination page. Setup the destination pointers. */
274 dp_kaddr = kmap_local_page(dp);
275 dp_addr = dp_kaddr + do_sb_start;
276
277 /* Now, we are ready to process the current sub-block (sb). */
278 if (!(le16_to_cpup((__le16 *)cb) & NTFS_SB_IS_COMPRESSED)) {
279 ntfs_debug("Found uncompressed sub-block.");
280 /* This sb is not compressed, just copy it into destination. */
281
282 /* Advance source position to first data byte. */
283 cb += 2;
284
285 /* An uncompressed sb must be full size. */
286 if (cb_sb_end - cb != NTFS_SB_SIZE)
287 goto return_overflow;
288
289 /* Copy the block and advance the source position. */
290 memcpy(dp_addr, cb, NTFS_SB_SIZE);
291 cb += NTFS_SB_SIZE;
292
293 /* Advance destination position to next sub-block. */
294 *dest_ofs += NTFS_SB_SIZE;
295 *dest_ofs &= ~PAGE_MASK;
296 kunmap_local(dp_kaddr);
297 dp_kaddr = NULL;
298 if (!(*dest_ofs)) {
299 finalize_page:
300 /*
301 * First stage: add current page index to array of
302 * completed pages.
303 */
304 completed_pages[nr_completed_pages++] = *dest_index;
305 if (++*dest_index > dest_max_index)
306 goto return_overflow;
307 }
308 goto do_next_sb;
309 }
310 ntfs_debug("Found compressed sub-block.");
311 /* This sb is compressed, decompress it into destination. */
312
313 /* Setup destination pointers. */
314 dp_sb_start = dp_addr;
315 dp_sb_end = dp_sb_start + NTFS_SB_SIZE;
316
317 /* Forward to the first tag in the sub-block. */
318 cb += 2;
319 do_next_tag:
320 if (cb == cb_sb_end) {
321 /* Check if the decompressed sub-block was not full-length. */
322 if (dp_addr < dp_sb_end) {
323 int nr_bytes = do_sb_end - *dest_ofs;
324
325 ntfs_debug("Filling incomplete sub-block with 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 *dest_ofs &= ~PAGE_MASK;
332 kunmap_local(dp_kaddr);
333 dp_kaddr = NULL;
334 if (!(*dest_ofs))
335 goto finalize_page;
336 goto do_next_sb;
337 }
338
339 /* Check we are still in range. */
340 if (cb > cb_sb_end || dp_addr > dp_sb_end)
341 goto return_overflow;
342
343 /* Get the next tag and advance to first token. */
344 tag = *cb++;
345
346 /* Parse the eight tokens described by the tag. */
347 for (token = 0; token < 8; token++, tag >>= 1) {
348 register u16 i;
349 u16 lg, pt, length, max_non_overlap;
350 u8 *dp_back_addr;
351
352 /* Check if we are done / still in range. */
353 if (cb >= cb_sb_end || dp_addr >= dp_sb_end)
354 break;
355
356 /* Determine token type and parse appropriately.*/
357 if ((tag & NTFS_TOKEN_MASK) == NTFS_SYMBOL_TOKEN) {
358 /*
359 * We have a symbol token, copy the symbol across, and
360 * advance the source and destination positions.
361 */
362 *dp_addr++ = *cb++;
363 ++*dest_ofs;
364
365 /* Continue with the next token. */
366 continue;
367 }
368
369 /*
370 * We have a phrase token. Make sure it is not the first tag in
371 * the sb as this is illegal and would confuse the code below.
372 */
373 if (dp_addr == dp_sb_start)
374 goto return_overflow;
375
376 /*
377 * Determine the number of bytes to go back (p) and the number
378 * of bytes to copy (l). We use an optimized algorithm in which
379 * we first calculate log2(current destination position in sb),
380 * which allows determination of l and p in O(1) rather than
381 * O(n). We just need an arch-optimized log2() function now.
382 */
383 lg = 0;
384 for (i = *dest_ofs - do_sb_start - 1; i >= 0x10; i >>= 1)
385 lg++;
386
387 /* Get the phrase token into i. */
388 pt = le16_to_cpup((__le16 *)cb);
389
390 /*
391 * Calculate starting position of the byte sequence in
392 * the destination using the fact that p = (pt >> (12 - lg)) + 1
393 * and make sure we don't go too far back.
394 */
395 dp_back_addr = dp_addr - (pt >> (12 - lg)) - 1;
396 if (dp_back_addr < dp_sb_start)
397 goto return_overflow;
398
399 /* Now calculate the length of the byte sequence. */
400 length = (pt & (0xfff >> lg)) + 3;
401
402 /* Advance destination position and verify it is in range. */
403 *dest_ofs += length;
404 if (*dest_ofs > do_sb_end)
405 goto return_overflow;
406
407 /* The number of non-overlapping bytes. */
408 max_non_overlap = dp_addr - dp_back_addr;
409
410 if (length <= max_non_overlap) {
411 /* The byte sequence doesn't overlap, just copy it. */
412 memcpy(dp_addr, dp_back_addr, length);
413
414 /* Advance destination pointer. */
415 dp_addr += length;
416 } else {
417 /*
418 * The byte sequence does overlap, copy non-overlapping
419 * part and then do a slow byte by byte copy for the
420 * overlapping part. Also, advance the destination
421 * pointer.
422 */
423 memcpy(dp_addr, dp_back_addr, max_non_overlap);
424 dp_addr += max_non_overlap;
425 dp_back_addr += max_non_overlap;
426 length -= max_non_overlap;
427 while (length--)
428 *dp_addr++ = *dp_back_addr++;
429 }
430
431 /* Advance source position and continue with the next token. */
432 cb += 2;
433 }
434
435 /* No tokens left in the current tag. Continue with the next tag. */
436 goto do_next_tag;
437
438 return_overflow:
439 if (dp_kaddr)
440 kunmap_local(dp_kaddr);
441 ntfs_error(NULL, "Failed. Returning -EOVERFLOW.");
442 goto return_error;
443 }
444
445 /*
446 * ntfs_read_compressed_block - read a compressed block into the page cache
447 * @folio: locked folio in the compression block(s) we need to read
448 *
449 * When we are called the page has already been verified to be locked and the
450 * attribute is known to be non-resident, not encrypted, but compressed.
451 *
452 * 1. Determine which compression block(s) @page is in.
453 * 2. Get hold of all pages corresponding to this/these compression block(s).
454 * 3. Read the (first) compression block.
455 * 4. Decompress it into the corresponding pages.
456 * 5. Throw the compressed data away and proceed to 3. for the next compression
457 * block or return success if no more compression blocks left.
458 *
459 * Warning: We have to be careful what we do about existing pages. They might
460 * have been written to so that we would lose data if we were to just overwrite
461 * them with the out-of-date uncompressed data.
462 */
ntfs_read_compressed_block(struct folio * folio)463 int ntfs_read_compressed_block(struct folio *folio)
464 {
465 struct page *page = &folio->page;
466 loff_t i_size;
467 s64 initialized_size;
468 struct address_space *mapping = folio->mapping;
469 struct ntfs_inode *ni = NTFS_I(mapping->host);
470 struct ntfs_volume *vol = ni->vol;
471 struct super_block *sb = vol->sb;
472 struct runlist_element *rl;
473 unsigned long flags;
474 u8 *cb, *cb_pos, *cb_end;
475 unsigned long offset, index = folio->index;
476 u32 cb_size = ni->itype.compressed.block_size;
477 u64 cb_size_mask = cb_size - 1UL;
478 s64 vcn;
479 s64 lcn;
480 /* The first wanted vcn (minimum alignment is PAGE_SIZE). */
481 s64 start_vcn = (((s64)index << PAGE_SHIFT) & ~cb_size_mask) >>
482 vol->cluster_size_bits;
483 /*
484 * The first vcn after the last wanted vcn (minimum alignment is again
485 * PAGE_SIZE.
486 */
487 s64 end_vcn = ((((s64)(index + 1UL) << PAGE_SHIFT) + cb_size - 1)
488 & ~cb_size_mask) >> vol->cluster_size_bits;
489 /* Number of compression blocks (cbs) in the wanted vcn range. */
490 unsigned int nr_cbs = ntfs_cluster_to_bytes(vol, end_vcn - start_vcn) >>
491 ni->itype.compressed.block_size_bits;
492 /*
493 * Number of pages required to store the uncompressed data from all
494 * compression blocks (cbs) overlapping @page. Due to alignment
495 * guarantees of start_vcn and end_vcn, no need to round up here.
496 */
497 unsigned int nr_pages = ntfs_cluster_to_pidx(vol, end_vcn - start_vcn);
498 unsigned int xpage, max_page, cur_page, cur_ofs, i, page_ofs, page_index;
499 unsigned int cb_clusters, cb_max_ofs;
500 int cb_max_page, err = 0;
501 struct page **pages;
502 int *completed_pages;
503 unsigned char xpage_done = 0;
504 struct page *lpage;
505
506 ntfs_debug("Entering, page->index = 0x%lx, cb_size = 0x%x, nr_pages = %i.",
507 index, cb_size, nr_pages);
508 /*
509 * Bad things happen if we get here for anything that is not an
510 * unnamed $DATA attribute.
511 */
512 if (ni->type != AT_DATA || ni->name_len) {
513 unlock_page(page);
514 return -EIO;
515 }
516
517 pages = kmalloc_objs(struct page *, nr_pages, GFP_NOFS);
518 completed_pages = kmalloc_objs(int, nr_pages + 1, GFP_NOFS);
519
520 if (unlikely(!pages || !completed_pages)) {
521 kfree(pages);
522 kfree(completed_pages);
523 unlock_page(page);
524 ntfs_error(vol->sb, "Failed to allocate internal buffers.");
525 return -ENOMEM;
526 }
527
528 /*
529 * We have already been given one page, this is the one we must do.
530 * Once again, the alignment guarantees keep it simple.
531 */
532 offset = ntfs_cluster_to_pidx(vol, start_vcn);
533 xpage = index - offset;
534 pages[xpage] = page;
535 /*
536 * The remaining pages need to be allocated and inserted into the page
537 * cache, alignment guarantees keep all the below much simpler. (-8
538 */
539 read_lock_irqsave(&ni->size_lock, flags);
540 i_size = i_size_read(VFS_I(ni));
541 initialized_size = ni->initialized_size;
542 read_unlock_irqrestore(&ni->size_lock, flags);
543 max_page = ((i_size + PAGE_SIZE - 1) >> PAGE_SHIFT) -
544 offset;
545 /* Is the page fully outside i_size? (truncate in progress) */
546 if (xpage >= max_page) {
547 kfree(pages);
548 kfree(completed_pages);
549 zero_user_segments(page, 0, PAGE_SIZE, 0, 0);
550 ntfs_debug("Compressed read outside i_size - truncated?");
551 SetPageUptodate(page);
552 unlock_page(page);
553 return 0;
554 }
555 if (nr_pages < max_page)
556 max_page = nr_pages;
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 continue;
570 }
571 unlock_page(page);
572 put_page(page);
573 pages[i] = NULL;
574 }
575 }
576
577 /*
578 * We have the runlist, 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
587 mutex_lock(&ntfs_cb_lock);
588 if (!ntfs_compression_buffer)
589 if (allocate_compression_buffers()) {
590 mutex_unlock(&ntfs_cb_lock);
591 goto err_out;
592 }
593
594
595 cb = ntfs_compression_buffer;
596 cb_pos = cb;
597 cb_end = cb + cb_size;
598
599 rl = NULL;
600 for (vcn = start_vcn, start_vcn += cb_clusters; vcn < start_vcn;
601 vcn++) {
602 bool is_retry = false;
603
604 if (!rl) {
605 lock_retry_remap:
606 down_read(&ni->runlist.lock);
607 rl = ni->runlist.rl;
608 }
609 if (likely(rl != NULL)) {
610 /* Seek to element containing target vcn. */
611 while (rl->length && rl[1].vcn <= vcn)
612 rl++;
613 lcn = ntfs_rl_vcn_to_lcn(rl, vcn);
614 } else
615 lcn = LCN_RL_NOT_MAPPED;
616 ntfs_debug("Reading vcn = 0x%llx, lcn = 0x%llx.",
617 (unsigned long long)vcn,
618 (unsigned long long)lcn);
619 if (lcn < 0) {
620 /*
621 * When we reach the first sparse cluster we have
622 * finished with the cb.
623 */
624 if (lcn == LCN_HOLE)
625 break;
626 if (is_retry || lcn != LCN_RL_NOT_MAPPED) {
627 mutex_unlock(&ntfs_cb_lock);
628 goto rl_err;
629 }
630 is_retry = true;
631 /*
632 * Attempt to map runlist, dropping lock for the
633 * duration.
634 */
635 up_read(&ni->runlist.lock);
636 if (!ntfs_map_runlist(ni, vcn))
637 goto lock_retry_remap;
638 mutex_unlock(&ntfs_cb_lock);
639 goto map_rl_err;
640 }
641
642 page_ofs = ntfs_cluster_to_poff(vol, lcn);
643 page_index = ntfs_cluster_to_pidx(vol, lcn);
644
645 lpage = read_mapping_page(sb->s_bdev->bd_mapping,
646 page_index, NULL);
647 if (IS_ERR(lpage)) {
648 err = PTR_ERR(lpage);
649 mutex_unlock(&ntfs_cb_lock);
650 goto read_err;
651 }
652
653 lock_page(lpage);
654 memcpy_from_page(cb_pos, lpage, page_ofs, vol->cluster_size);
655 unlock_page(lpage);
656 put_page(lpage);
657 cb_pos += vol->cluster_size;
658 }
659
660 /* Release the lock if we took it. */
661 if (rl)
662 up_read(&ni->runlist.lock);
663
664 /* Just a precaution. */
665 if (cb_pos + 2 <= cb + cb_size)
666 *(u16 *)cb_pos = 0;
667
668 /* Reset cb_pos back to the beginning. */
669 cb_pos = cb;
670
671 /* We now have both source (if present) and destination. */
672 ntfs_debug("Successfully read the compression block.");
673
674 /* The last page and maximum offset within it for the current cb. */
675 cb_max_page = (cur_page << PAGE_SHIFT) + cur_ofs + cb_size;
676 cb_max_ofs = cb_max_page & ~PAGE_MASK;
677 cb_max_page >>= PAGE_SHIFT;
678
679 /* Catch end of file inside a compression block. */
680 if (cb_max_page > max_page)
681 cb_max_page = max_page;
682
683 if (vcn == start_vcn - cb_clusters) {
684 /* Sparse cb, zero out page range overlapping the cb. */
685 ntfs_debug("Found sparse compression block.");
686 /* We can sleep from now on, so we drop lock. */
687 mutex_unlock(&ntfs_cb_lock);
688 if (cb_max_ofs)
689 cb_max_page--;
690 for (; cur_page < cb_max_page; cur_page++) {
691 page = pages[cur_page];
692 if (page) {
693 memzero_page(page, cur_ofs, PAGE_SIZE - cur_ofs);
694 SetPageUptodate(page);
695 unlock_page(page);
696 if (cur_page == xpage)
697 xpage_done = 1;
698 else
699 put_page(page);
700 pages[cur_page] = NULL;
701 }
702 cb_pos += PAGE_SIZE - cur_ofs;
703 cur_ofs = 0;
704 if (cb_pos >= cb_end)
705 break;
706 }
707 /* If we have a partial final page, deal with it now. */
708 if (cb_max_ofs && cb_pos < cb_end) {
709 page = pages[cur_page];
710 if (page)
711 memzero_page(page, cur_ofs, cb_max_ofs - cur_ofs);
712 /*
713 * No need to update cb_pos at this stage:
714 * cb_pos += cb_max_ofs - cur_ofs;
715 */
716 cur_ofs = cb_max_ofs;
717 }
718 } else if (vcn == start_vcn) {
719 /* We can't sleep so we need two stages. */
720 unsigned int cur2_page = cur_page;
721 unsigned int cur_ofs2 = cur_ofs;
722 u8 *cb_pos2 = cb_pos;
723
724 ntfs_debug("Found uncompressed compression block.");
725 /* Uncompressed cb, copy it to the destination pages. */
726 if (cb_max_ofs)
727 cb_max_page--;
728 /* First stage: copy data into destination pages. */
729 for (; cur_page < cb_max_page; cur_page++) {
730 page = pages[cur_page];
731 if (page)
732 memcpy_to_page(page, cur_ofs, cb_pos,
733 PAGE_SIZE - cur_ofs);
734 cb_pos += PAGE_SIZE - cur_ofs;
735 cur_ofs = 0;
736 if (cb_pos >= cb_end)
737 break;
738 }
739 /* If we have a partial final page, deal with it now. */
740 if (cb_max_ofs && cb_pos < cb_end) {
741 page = pages[cur_page];
742 if (page)
743 memcpy_to_page(page, cur_ofs, cb_pos,
744 cb_max_ofs - cur_ofs);
745 cb_pos += cb_max_ofs - cur_ofs;
746 cur_ofs = cb_max_ofs;
747 }
748 /* We can sleep from now on, so drop lock. */
749 mutex_unlock(&ntfs_cb_lock);
750 /* Second stage: finalize pages. */
751 for (; cur2_page < cb_max_page; cur2_page++) {
752 page = pages[cur2_page];
753 if (page) {
754 /*
755 * If we are outside the initialized size, zero
756 * the out of bounds page range.
757 */
758 handle_bounds_compressed_page(page, i_size,
759 initialized_size);
760 SetPageUptodate(page);
761 unlock_page(page);
762 if (cur2_page == xpage)
763 xpage_done = 1;
764 else
765 put_page(page);
766 pages[cur2_page] = NULL;
767 }
768 cb_pos2 += PAGE_SIZE - cur_ofs2;
769 cur_ofs2 = 0;
770 if (cb_pos2 >= cb_end)
771 break;
772 }
773 } else {
774 /* Compressed cb, decompress it into the destination page(s). */
775 unsigned int prev_cur_page = cur_page;
776
777 ntfs_debug("Found compressed compression block.");
778 err = ntfs_lznt1_codec_ops.decompress_pages(pages, completed_pages, &cur_page,
779 &cur_ofs, cb_max_page, cb_max_ofs, xpage,
780 &xpage_done, cb_pos, cb_size - (cb_pos - cb),
781 i_size, initialized_size);
782 /*
783 * We can sleep from now on, lock already dropped by
784 * ntfs_decompress().
785 */
786 if (err) {
787 ntfs_error(vol->sb,
788 "ntfs_decompress() failed in inode 0x%llx with error code %i. Skipping this compression block.",
789 ni->mft_no, -err);
790 /* Release the unfinished pages. */
791 for (; prev_cur_page < cur_page; prev_cur_page++) {
792 page = pages[prev_cur_page];
793 if (page) {
794 flush_dcache_page(page);
795 unlock_page(page);
796 if (prev_cur_page != xpage)
797 put_page(page);
798 pages[prev_cur_page] = NULL;
799 }
800 }
801 }
802 }
803
804 /* Do we have more work to do? */
805 if (nr_cbs)
806 goto do_next_cb;
807
808 /* Clean up if we have any pages left. Should never happen. */
809 for (cur_page = 0; cur_page < max_page; cur_page++) {
810 page = pages[cur_page];
811 if (page) {
812 folio = page_folio(page);
813
814 ntfs_error(vol->sb,
815 "Still have pages left! Terminating them with extreme prejudice. Inode 0x%llx, page index 0x%lx.",
816 ni->mft_no, folio->index);
817 flush_dcache_folio(folio);
818 folio_unlock(folio);
819 if (cur_page != xpage)
820 folio_put(folio);
821 pages[cur_page] = NULL;
822 }
823 }
824
825 /* We no longer need the list of pages. */
826 kfree(pages);
827 kfree(completed_pages);
828
829 /* If we have completed the requested page, we return success. */
830 if (likely(xpage_done))
831 return 0;
832
833 ntfs_debug("Failed. Returning error code %s.", err == -EOVERFLOW ?
834 "EOVERFLOW" : (!err ? "EIO" : "unknown error"));
835 return err < 0 ? err : -EIO;
836
837 map_rl_err:
838 ntfs_error(vol->sb, "ntfs_map_runlist() failed. Cannot read compression block.");
839 goto err_out;
840
841 rl_err:
842 up_read(&ni->runlist.lock);
843 ntfs_error(vol->sb, "ntfs_rl_vcn_to_lcn() failed. Cannot read compression block.");
844 goto err_out;
845
846 read_err:
847 up_read(&ni->runlist.lock);
848 ntfs_error(vol->sb, "IO error while reading compressed data.");
849
850 err_out:
851 for (i = cur_page; i < max_page; i++) {
852 page = pages[i];
853 if (page) {
854 flush_dcache_page(page);
855 unlock_page(page);
856 if (i != xpage)
857 put_page(page);
858 }
859 }
860 kfree(pages);
861 kfree(completed_pages);
862 return -EIO;
863 }
864
865 /*
866 * Match length at or above which ntfs_best_match() will stop searching for
867 * longer matches.
868 */
869 #define NICE_MATCH_LEN 18
870
871 /*
872 * Maximum number of potential matches that ntfs_best_match() will consider at
873 * each position.
874 */
875 #define MAX_SEARCH_DEPTH 24
876
877 /* log base 2 of the number of entries in the hash table for match-finding. */
878 #define HASH_SHIFT 14
879
880 /*
881 * Constant for the multiplicative hash function. These hashing constants
882 * are used solely for the match-finding algorithm during compression.
883 * They are NOT part of the on-disk format. The decompressor does not
884 * utilize this hash.
885 */
886 #define HASH_MULTIPLIER 0x1E35A7BD
887
888 struct compress_context {
889 const unsigned char *inbuf;
890 int bufsize;
891 int size;
892 int rel;
893 int mxsz;
894 s16 head[1 << HASH_SHIFT];
895 s16 prev[NTFS_SB_SIZE];
896 };
897
898 struct ntfs_compress_workspace {
899 struct page **pages;
900 char *outbuf;
901 unsigned int nr_pages;
902 };
903
904 /*
905 * Hash the next 3-byte sequence in the input buffer
906 */
ntfs_hash(const u8 * p)907 static inline unsigned int ntfs_hash(const u8 *p)
908 {
909 u32 str;
910 u32 hash;
911
912 /*
913 * Unaligned access allowed, and little endian CPU.
914 * Callers ensure that at least 4 (not 3) bytes are remaining.
915 */
916 str = *(const u32 *)p & 0xFFFFFF;
917 hash = str * HASH_MULTIPLIER;
918
919 /* High bits are more random than the low bits. */
920 return hash >> (32 - HASH_SHIFT);
921 }
922
923 /*
924 * Search for the longest sequence matching current position
925 *
926 * A hash table, each entry of which points to a chain of sequence
927 * positions sharing the corresponding hash code, is maintained to speed up
928 * searching for matches. To maintain the hash table, either
929 * ntfs_best_match() or ntfs_skip_position() has to be called for each
930 * consecutive position.
931 *
932 * This function is heavily used; it has to be optimized carefully.
933 *
934 * This function sets pctx->size and pctx->rel to the length and offset,
935 * respectively, of the longest match found.
936 *
937 * The minimum match length is assumed to be 3, and the maximum match
938 * length is assumed to be pctx->mxsz. If this function produces
939 * pctx->size < 3, then no match was found.
940 *
941 * Note: for the following reasons, this function is not guaranteed to find
942 * *the* longest match up to pctx->mxsz:
943 *
944 * (1) If this function finds a match of NICE_MATCH_LEN bytes or greater,
945 * it ends early because a match this long is good enough and it's not
946 * worth spending more time searching.
947 *
948 * (2) If this function considers MAX_SEARCH_DEPTH matches with a single
949 * position, it ends early and returns the longest match found so far.
950 * This saves a lot of time on degenerate inputs.
951 */
ntfs_best_match(struct compress_context * pctx,const int i,int best_len)952 static void ntfs_best_match(struct compress_context *pctx, const int i,
953 int best_len)
954 {
955 const u8 * const inbuf = pctx->inbuf;
956 const u8 * const strptr = &inbuf[i]; /* String we're matching against */
957 s16 * const prev = pctx->prev;
958 const int max_len = min(pctx->bufsize - i, pctx->mxsz);
959 const int nice_len = min(NICE_MATCH_LEN, max_len);
960 int depth_remaining = MAX_SEARCH_DEPTH;
961 const u8 *best_matchptr = strptr;
962 unsigned int hash;
963 s16 cur_match;
964 const u8 *matchptr;
965 int len;
966
967 if (max_len < 4)
968 goto out;
969
970 /* Insert the current sequence into the appropriate hash chain. */
971 hash = ntfs_hash(strptr);
972 cur_match = pctx->head[hash];
973 prev[i] = cur_match;
974 pctx->head[hash] = i;
975
976 if (best_len >= max_len) {
977 /*
978 * Lazy match is being attempted, but there aren't enough length
979 * bits remaining to code a longer match.
980 */
981 goto out;
982 }
983
984 /* Search the appropriate hash chain for matches. */
985
986 for (; cur_match >= 0 && depth_remaining--; cur_match = prev[cur_match]) {
987 matchptr = &inbuf[cur_match];
988
989 /*
990 * Considering the potential match at 'matchptr': is it longer
991 * than 'best_len'?
992 *
993 * The bytes at index 'best_len' are the most likely to differ,
994 * so check them first.
995 *
996 * The bytes at indices 'best_len - 1' and '0' are less
997 * important to check separately. But doing so still gives a
998 * slight performance improvement, at least on x86_64, probably
999 * because they create separate branches for the CPU to predict
1000 * independently of the branches in the main comparison loops.
1001 */
1002 if (matchptr[best_len] != strptr[best_len] ||
1003 matchptr[best_len - 1] != strptr[best_len - 1] ||
1004 matchptr[0] != strptr[0])
1005 goto next_match;
1006
1007 for (len = 1; len < best_len - 1; len++)
1008 if (matchptr[len] != strptr[len])
1009 goto next_match;
1010
1011 /*
1012 * The match is the longest found so far ---
1013 * at least 'best_len' + 1 bytes. Continue extending it.
1014 */
1015
1016 best_matchptr = matchptr;
1017
1018 do {
1019 if (++best_len >= nice_len) {
1020 /*
1021 * 'nice_len' reached; don't waste time
1022 * searching for longer matches. Extend the
1023 * match as far as possible and terminate the
1024 * search.
1025 */
1026 while (best_len < max_len &&
1027 (best_matchptr[best_len] ==
1028 strptr[best_len]))
1029 best_len++;
1030 goto out;
1031 }
1032 } while (best_matchptr[best_len] == strptr[best_len]);
1033
1034 /* Found a longer match, but 'nice_len' not yet reached. */
1035
1036 next_match:
1037 /* Continue to next match in the chain. */
1038 ;
1039 }
1040
1041 /*
1042 * Reached end of chain, or ended early due to reaching the maximum
1043 * search depth.
1044 */
1045
1046 out:
1047 /* Return the longest match we were able to find. */
1048 pctx->size = best_len;
1049 pctx->rel = best_matchptr - strptr; /* given as a negative number! */
1050 }
1051
1052 /*
1053 * Advance the match-finder, but don't search for matches.
1054 */
ntfs_skip_position(struct compress_context * pctx,const int i)1055 static void ntfs_skip_position(struct compress_context *pctx, const int i)
1056 {
1057 unsigned int hash;
1058
1059 if (pctx->bufsize - i < 4)
1060 return;
1061
1062 /* Insert the current sequence into the appropriate hash chain. */
1063 hash = ntfs_hash(pctx->inbuf + i);
1064 pctx->prev[i] = pctx->head[hash];
1065 pctx->head[hash] = i;
1066 }
1067
1068 /*
1069 * Compress a 4096-byte block
1070 *
1071 * Returns a header of two bytes followed by the compressed data.
1072 * If compression is not effective, the header and an uncompressed
1073 * block is returned.
1074 *
1075 * Note : two bytes may be output before output buffer overflow
1076 * is detected, so a 4100-bytes output buffer must be reserved.
1077 *
1078 * Returns the size of the compressed block, including the
1079 * header (minimal size is 2, maximum size is 4098)
1080 * A negative error code if an error has been met.
1081 */
ntfs_compress_block(struct compress_context * pctx,const char * inbuf,const int bufsize,char * outbuf)1082 static int ntfs_compress_block(struct compress_context *pctx,
1083 const char *inbuf, const int bufsize, char *outbuf)
1084 {
1085 int i; /* current position */
1086 int j; /* end of best match from current position */
1087 int k; /* end of best match from next position */
1088 int offs; /* offset to best match */
1089 int bp; /* bits to store offset */
1090 int bp_cur; /* saved bits to store offset at current position */
1091 int mxoff; /* max match offset : 1 << bp */
1092 unsigned int xout;
1093 unsigned int q; /* aggregated offset and size */
1094 int have_match; /* do we have a match at the current position? */
1095 char *ptag; /* location reserved for a tag */
1096 int tag; /* current value of tag */
1097 int ntag; /* count of bits still undefined in tag */
1098
1099 /*
1100 * All hash chains start as empty. The special value '-1' indicates the
1101 * end of each hash chain.
1102 */
1103 memset(pctx->head, 0xFF, sizeof(pctx->head));
1104
1105 pctx->inbuf = (const unsigned char *)inbuf;
1106 pctx->bufsize = bufsize;
1107 xout = 2;
1108 i = 0;
1109 bp = 4;
1110 mxoff = 1 << bp;
1111 pctx->mxsz = (1 << (16 - bp)) + 2;
1112 have_match = 0;
1113 tag = 0;
1114 ntag = 8;
1115 ptag = &outbuf[xout++];
1116
1117 while ((i < bufsize) && (xout < (NTFS_SB_SIZE + 2))) {
1118
1119 /*
1120 * This implementation uses "lazy" parsing: it always chooses
1121 * the longest match, unless the match at the next position is
1122 * longer. This is the same strategy used by the high
1123 * compression modes of zlib.
1124 */
1125 if (!have_match) {
1126 /*
1127 * Find the longest match at the current position. But
1128 * first adjust the maximum match length if needed.
1129 * (This loop might need to run more than one time in
1130 * the case that we just output a long match.)
1131 */
1132 while (mxoff < i) {
1133 bp++;
1134 mxoff <<= 1;
1135 pctx->mxsz = (pctx->mxsz + 2) >> 1;
1136 }
1137 ntfs_best_match(pctx, i, 2);
1138 }
1139
1140 if (pctx->size >= 3) {
1141 /* Found a match at the current position. */
1142 j = i + pctx->size;
1143 bp_cur = bp;
1144 offs = pctx->rel;
1145
1146 if (pctx->size >= NICE_MATCH_LEN) {
1147 /* Choose long matches immediately. */
1148 q = (~offs << (16 - bp_cur)) + (j - i - 3);
1149 outbuf[xout++] = q & 255;
1150 outbuf[xout++] = (q >> 8) & 255;
1151 tag |= (1 << (8 - ntag));
1152
1153 if (j == bufsize) {
1154 /*
1155 * Shortcut if the match extends to the
1156 * end of the buffer.
1157 */
1158 i = j;
1159 --ntag;
1160 break;
1161 }
1162 i += 1;
1163 do {
1164 ntfs_skip_position(pctx, i);
1165 } while (++i != j);
1166 have_match = 0;
1167 } else {
1168 /*
1169 * Check for a longer match at the next
1170 * position.
1171 */
1172
1173 /*
1174 * Doesn't need to be while() since we just
1175 * adjusted the maximum match length at the
1176 * previous position.
1177 */
1178 if (mxoff < i + 1) {
1179 bp++;
1180 mxoff <<= 1;
1181 pctx->mxsz = (pctx->mxsz + 2) >> 1;
1182 }
1183 ntfs_best_match(pctx, i + 1, pctx->size);
1184 k = i + 1 + pctx->size;
1185
1186 if (k > (j + 1)) {
1187 /*
1188 * Next match is longer.
1189 * Output a literal.
1190 */
1191 outbuf[xout++] = inbuf[i++];
1192 have_match = 1;
1193 } else {
1194 /*
1195 * Next match isn't longer.
1196 * Output the current match.
1197 */
1198 q = (~offs << (16 - bp_cur)) +
1199 (j - i - 3);
1200 outbuf[xout++] = q & 255;
1201 outbuf[xout++] = (q >> 8) & 255;
1202 tag |= (1 << (8 - ntag));
1203
1204 /*
1205 * The minimum match length is 3, and
1206 * we've run two bytes through the
1207 * matchfinder already. So the minimum
1208 * number of positions we need to skip
1209 * is 1.
1210 */
1211 i += 2;
1212 do {
1213 ntfs_skip_position(pctx, i);
1214 } while (++i != j);
1215 have_match = 0;
1216 }
1217 }
1218 } else {
1219 /* No match at current position. Output a literal. */
1220 outbuf[xout++] = inbuf[i++];
1221 have_match = 0;
1222 }
1223
1224 /* Store the tag if fully used. */
1225 if (!--ntag) {
1226 *ptag = tag;
1227 ntag = 8;
1228 ptag = &outbuf[xout++];
1229 tag = 0;
1230 }
1231 }
1232
1233 /* Store the last tag if partially used. */
1234 if (ntag == 8)
1235 xout--;
1236 else
1237 *ptag = tag;
1238
1239 /* Determine whether to store the data compressed or uncompressed. */
1240 if ((i >= bufsize) && (xout < (NTFS_SB_SIZE + 2))) {
1241 /* Compressed. */
1242 outbuf[0] = (xout - 3) & 255;
1243 outbuf[1] = 0xb0 + (((xout - 3) >> 8) & 15);
1244 } else {
1245 /* Uncompressed. */
1246 memcpy(&outbuf[2], inbuf, bufsize);
1247 if (bufsize < NTFS_SB_SIZE)
1248 memset(&outbuf[bufsize + 2], 0, NTFS_SB_SIZE - bufsize);
1249 outbuf[0] = 0xff;
1250 outbuf[1] = 0x3f;
1251 xout = NTFS_SB_SIZE + 2;
1252 }
1253
1254 return xout;
1255 }
1256
ntfs_compress_workspace_init(struct ntfs_inode * ni,struct ntfs_compress_workspace * ws)1257 static int ntfs_compress_workspace_init(struct ntfs_inode *ni,
1258 struct ntfs_compress_workspace *ws)
1259 {
1260 unsigned int size, i;
1261
1262 size = ni->itype.compressed.block_size + 2 *
1263 (ni->itype.compressed.block_size / NTFS_SB_SIZE) + 2;
1264 ws->nr_pages = DIV_ROUND_UP(size, PAGE_SIZE);
1265 ws->pages = kzalloc_objs(*ws->pages, ws->nr_pages, GFP_NOFS);
1266 if (!ws->pages)
1267 return -ENOMEM;
1268
1269 for (i = 0; i < ws->nr_pages; i++) {
1270 ws->pages[i] = alloc_page(GFP_NOFS);
1271 if (!ws->pages[i])
1272 goto free_pages;
1273 }
1274
1275 ws->outbuf = vmap(ws->pages, ws->nr_pages, VM_MAP, PAGE_KERNEL);
1276 if (!ws->outbuf)
1277 goto free_pages;
1278 return 0;
1279
1280 free_pages:
1281 while (i)
1282 put_page(ws->pages[--i]);
1283 kfree(ws->pages);
1284 return -ENOMEM;
1285 }
1286
ntfs_compress_workspace_free(struct ntfs_compress_workspace * ws)1287 static void ntfs_compress_workspace_free(struct ntfs_compress_workspace *ws)
1288 {
1289 unsigned int i;
1290
1291 vunmap(ws->outbuf);
1292 for (i = 0; i < ws->nr_pages; i++)
1293 put_page(ws->pages[i]);
1294 kfree(ws->pages);
1295 }
1296
ntfs_copy_cb(struct page ** pages,int pages_per_cb,unsigned int page_offset,struct ntfs_compress_workspace * ws,unsigned int bytes)1297 static void ntfs_copy_cb(struct page **pages, int pages_per_cb,
1298 unsigned int page_offset,
1299 struct ntfs_compress_workspace *ws, unsigned int bytes)
1300 {
1301 unsigned int copied = 0, i;
1302
1303 for (i = 0; i < pages_per_cb && copied < bytes; i++) {
1304 unsigned int offset = i ? 0 : page_offset;
1305 unsigned int len = min(bytes - copied, PAGE_SIZE - offset);
1306 void *addr = kmap_local_page(pages[i]);
1307
1308 memcpy(ws->outbuf + copied, addr + offset, len);
1309 kunmap_local(addr);
1310 copied += len;
1311 }
1312 }
1313
ntfs_write_cb(struct ntfs_inode * ni,loff_t pos,struct page ** pages,int pages_per_cb,unsigned int page_offset,struct compress_context * ctx,struct ntfs_compress_workspace * ws)1314 static int ntfs_write_cb(struct ntfs_inode *ni, loff_t pos, struct page **pages,
1315 int pages_per_cb, unsigned int page_offset,
1316 struct compress_context *ctx, struct ntfs_compress_workspace *ws)
1317 {
1318 struct ntfs_volume *vol = ni->vol;
1319 char *outbuf = ws->outbuf, *pbuf;
1320 u32 compsz, p, insz = ni->itype.compressed.block_size;
1321 s32 rounded, bio_size;
1322 int sz;
1323 unsigned int bsz;
1324 bool fail = false, allzeroes;
1325 /* a single compressed zero */
1326 static char onezero[] = {0x01, 0xb0, 0x00, 0x00};
1327 /* a couple of compressed zeroes */
1328 static char twozeroes[] = {0x02, 0xb0, 0x00, 0x00, 0x00};
1329 /* more compressed zeroes, to be followed by some count */
1330 static char morezeroes[] = {0x03, 0xb0, 0x02, 0x00};
1331 s64 bio_lcn, bio_pos;
1332 struct runlist_element *rlc, *rl;
1333 int i, err;
1334 u32 cb_clusters = ni->itype.compressed.block_clusters;
1335 size_t new_rl_count;
1336 struct bio *bio = NULL;
1337 loff_t cb_pos, new_length;
1338 s64 new_vcn;
1339
1340 compsz = 0;
1341 allzeroes = true;
1342 for (p = 0; (p < insz) && !fail; p += NTFS_SB_SIZE) {
1343 unsigned int input_offset = page_offset + p;
1344 unsigned int page_idx = input_offset >> PAGE_SHIFT;
1345 const char *input;
1346 void *addr;
1347
1348 if ((p + NTFS_SB_SIZE) < insz)
1349 bsz = NTFS_SB_SIZE;
1350 else
1351 bsz = insz - p;
1352 pbuf = &outbuf[compsz];
1353 addr = kmap_local_page(pages[page_idx]);
1354 input = addr + offset_in_page(input_offset);
1355 sz = ntfs_lznt1_codec_ops.compress_subblock(ctx, input, bsz, pbuf);
1356 kunmap_local(addr);
1357 if (sz < 0) {
1358 err = sz;
1359 goto out;
1360 }
1361 /* fail if all the clusters (or more) are needed */
1362 if (!sz || ((compsz + sz + vol->cluster_size + 2) >
1363 ni->itype.compressed.block_size))
1364 fail = true;
1365 else {
1366 if (allzeroes) {
1367 /* check whether this is all zeroes */
1368 switch (sz) {
1369 case 4:
1370 allzeroes = !memcmp(pbuf, onezero, 4);
1371 break;
1372 case 5:
1373 allzeroes = !memcmp(pbuf, twozeroes, 5);
1374 break;
1375 case 6:
1376 allzeroes = !memcmp(pbuf, morezeroes, 4);
1377 break;
1378 default:
1379 allzeroes = false;
1380 break;
1381 }
1382 }
1383 compsz += sz;
1384 }
1385 }
1386
1387 cb_pos = pos & ~((loff_t)ni->itype.compressed.block_size - 1);
1388 new_vcn = ntfs_bytes_to_cluster(vol, cb_pos);
1389
1390 if (!fail && !allzeroes) {
1391 outbuf[compsz++] = 0;
1392 outbuf[compsz++] = 0;
1393 rounded = ((compsz - 1) | (vol->cluster_size - 1)) + 1;
1394 memset(&outbuf[compsz], 0, rounded - compsz);
1395 bio_size = rounded;
1396 } else if (allzeroes) {
1397 err = ntfs_non_resident_attr_punch_hole(ni, new_vcn, cb_clusters);
1398 goto out;
1399 } else {
1400 ntfs_copy_cb(pages, pages_per_cb, page_offset, ws, insz);
1401 bio_size = insz;
1402 }
1403
1404 new_length = ntfs_bytes_to_cluster(vol, round_up(bio_size, vol->cluster_size));
1405
1406 rlc = ntfs_cluster_alloc(vol, new_vcn, new_length, -1, DATA_ZONE,
1407 false, true, true);
1408 if (IS_ERR(rlc)) {
1409 err = PTR_ERR(rlc);
1410 goto out;
1411 }
1412
1413 bio_lcn = rlc->lcn;
1414 bio_pos = ntfs_cluster_to_bytes(vol, bio_lcn);
1415 bio = bio_alloc(vol->sb->s_bdev, DIV_ROUND_UP(bio_size, PAGE_SIZE),
1416 REQ_OP_WRITE, GFP_NOIO);
1417 bio->bi_iter.bi_sector = ntfs_bytes_to_bio_sector(bio_pos);
1418
1419 for (i = 0; bio_size; i++) {
1420 unsigned int len = min_t(unsigned int, bio_size, PAGE_SIZE);
1421
1422 if (bio_add_page(bio, ws->pages[i], len, 0) != len) {
1423 err = -EIO;
1424 bio_put(bio);
1425 goto free_rlc;
1426 }
1427 bio_size -= len;
1428 }
1429
1430 err = submit_bio_wait(bio);
1431 bio_put(bio);
1432 if (err)
1433 goto free_rlc;
1434
1435 /* Do not discard the old compression block until the new one is safe. */
1436 err = ntfs_non_resident_attr_punch_hole(ni, new_vcn, cb_clusters);
1437 if (err)
1438 goto free_rlc;
1439
1440 down_write(&ni->runlist.lock);
1441 rl = ntfs_runlists_merge(&ni->runlist, rlc, 0, &new_rl_count);
1442 if (IS_ERR(rl)) {
1443 up_write(&ni->runlist.lock);
1444 ntfs_error(vol->sb, "Failed to merge runlists");
1445 err = PTR_ERR(rl);
1446 goto free_rlc;
1447 }
1448
1449 ni->runlist.count = new_rl_count;
1450 ni->runlist.rl = rl;
1451 rlc = NULL;
1452
1453 err = ntfs_attr_update_mapping_pairs(ni, 0);
1454 up_write(&ni->runlist.lock);
1455 if (err)
1456 err = -EIO;
1457 goto out;
1458
1459 free_rlc:
1460 if (ntfs_cluster_free_from_rl(vol, rlc))
1461 ntfs_error(vol->sb, "Failed to free hot clusters.");
1462 kvfree(rlc);
1463 out:
1464 NInoSetFileNameDirty(ni);
1465 mark_mft_record_dirty(ni);
1466
1467 return err;
1468 }
1469
ntfs_compress_write(struct ntfs_inode * ni,loff_t pos,size_t count,struct iov_iter * from)1470 int ntfs_compress_write(struct ntfs_inode *ni, loff_t pos, size_t count,
1471 struct iov_iter *from)
1472 {
1473 struct ntfs_compress_workspace ws = {};
1474 struct compress_context *ctx;
1475 struct folio *folio;
1476 struct page **pages = NULL, *page;
1477 int pages_per_cb;
1478 int cb_size = ni->itype.compressed.block_size, cb_off, err = 0;
1479 int i, ip;
1480 size_t written = 0;
1481 struct address_space *mapping = VFS_I(ni)->i_mapping;
1482
1483 pages_per_cb = DIV_ROUND_UP(offset_in_page(pos & ~(cb_size - 1)) +
1484 cb_size, PAGE_SIZE);
1485
1486 pages = kmalloc_objs(struct page *, pages_per_cb, GFP_NOFS);
1487 if (!pages)
1488 return -ENOMEM;
1489 ctx = kvzalloc_obj(*ctx, GFP_NOFS);
1490 if (!ctx) {
1491 kfree(pages);
1492 return -ENOMEM;
1493 }
1494 err = ntfs_compress_workspace_init(ni, &ws);
1495 if (err) {
1496 kvfree(ctx);
1497 kfree(pages);
1498 return err;
1499 }
1500
1501 while (count) {
1502 pgoff_t index;
1503 size_t copied, bytes;
1504 unsigned int page_offset;
1505 bool full_cb;
1506 int off;
1507
1508 off = pos & (cb_size - 1);
1509 bytes = cb_size - off;
1510 if (bytes > count)
1511 bytes = count;
1512
1513 cb_off = pos & ~(cb_size - 1);
1514 page_offset = offset_in_page(cb_off);
1515 pages_per_cb = DIV_ROUND_UP(page_offset + cb_size, PAGE_SIZE);
1516 index = cb_off >> PAGE_SHIFT;
1517 full_cb = !off && bytes == cb_size && !page_offset &&
1518 !(cb_size & (PAGE_SIZE - 1));
1519
1520 if (unlikely(fault_in_iov_iter_readable(from, bytes))) {
1521 err = -EFAULT;
1522 goto out;
1523 }
1524
1525 for (i = 0; i < pages_per_cb; i++) {
1526 if (full_cb)
1527 folio = filemap_grab_folio(mapping, index + i);
1528 else
1529 folio = read_mapping_folio(mapping, index + i, NULL);
1530 if (IS_ERR(folio)) {
1531 for (ip = 0; ip < i; ip++) {
1532 folio_unlock(page_folio(pages[ip]));
1533 folio_put(page_folio(pages[ip]));
1534 }
1535 err = PTR_ERR(folio);
1536 goto out;
1537 }
1538
1539 if (!full_cb)
1540 folio_lock(folio);
1541 pages[i] = folio_page(folio, 0);
1542 }
1543
1544 WARN_ON(!bytes);
1545 copied = 0;
1546 ip = off >> PAGE_SHIFT;
1547 off = offset_in_page(pos);
1548
1549 for (;;) {
1550 size_t cp, tail = PAGE_SIZE - off;
1551
1552 page = pages[ip];
1553 cp = copy_folio_from_iter_atomic(page_folio(page), off,
1554 min(tail, bytes), from);
1555 flush_dcache_page(page);
1556
1557 copied += cp;
1558 bytes -= cp;
1559 if (!bytes || !cp)
1560 break;
1561
1562 if (cp < tail) {
1563 off += cp;
1564 } else {
1565 ip++;
1566 off = 0;
1567 }
1568 }
1569
1570 if (!copied) {
1571 err = -EFAULT;
1572 goto release_pages;
1573 }
1574
1575 err = ntfs_write_cb(ni, pos, pages, pages_per_cb, page_offset, ctx, &ws);
1576 if (!err && pos + copied > ni->initialized_size) {
1577 mutex_lock(&ni->mrec_lock);
1578 err = ntfs_attr_set_initialized_size(ni, pos + copied);
1579 mutex_unlock(&ni->mrec_lock);
1580 }
1581
1582 release_pages:
1583 for (i = 0; i < pages_per_cb; i++) {
1584 folio = page_folio(pages[i]);
1585 if (!err) {
1586 folio_clear_dirty(folio);
1587 folio_mark_uptodate(folio);
1588 } else {
1589 folio_clear_uptodate(folio);
1590 }
1591 folio_unlock(folio);
1592 folio_put(folio);
1593 }
1594
1595 if (err)
1596 goto out;
1597
1598 cond_resched();
1599 pos += copied;
1600 written += copied;
1601 count = iov_iter_count(from);
1602 }
1603
1604 out:
1605 ntfs_compress_workspace_free(&ws);
1606 kvfree(ctx);
1607 kfree(pages);
1608 if (err < 0)
1609 written = err;
1610
1611 return written;
1612 }
1613
1614 const struct ntfs_codec_ops ntfs_lznt1_codec_ops = {
1615 .id = NTFS_CODEC_LZNT1,
1616 .name = "lznt1",
1617 .decompress_pages = ntfs_decompress,
1618 .compress_subblock = ntfs_compress_block,
1619 };
1620