2 * runlist.c - NTFS runlist handling code. Part of the Linux-NTFS project.
4 * Copyright (c) 2001-2005 Anton Altaparmakov
5 * Copyright (c) 2002 Richard Russon
7 * This program/include file is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License as published
9 * by the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * This program/include file is distributed in the hope that it will be
13 * useful, but WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program (in the main directory of the Linux-NTFS
19 * distribution in the file COPYING); if not, write to the Free Software
20 * Foundation,Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
30 * ntfs_rl_mm - runlist memmove
32 * It is up to the caller to serialize access to the runlist @base.
34 static inline void ntfs_rl_mm(runlist_element *base, int dst, int src,
37 if (likely((dst != src) && (size > 0)))
38 memmove(base + dst, base + src, size * sizeof (*base));
42 * ntfs_rl_mc - runlist memory copy
44 * It is up to the caller to serialize access to the runlists @dstbase and
47 static inline void ntfs_rl_mc(runlist_element *dstbase, int dst,
48 runlist_element *srcbase, int src, int size)
51 memcpy(dstbase + dst, srcbase + src, size * sizeof(*dstbase));
55 * ntfs_rl_realloc - Reallocate memory for runlists
56 * @rl: original runlist
57 * @old_size: number of runlist elements in the original runlist @rl
58 * @new_size: number of runlist elements we need space for
60 * As the runlists grow, more memory will be required. To prevent the
61 * kernel having to allocate and reallocate large numbers of small bits of
62 * memory, this function returns an entire page of memory.
64 * It is up to the caller to serialize access to the runlist @rl.
66 * N.B. If the new allocation doesn't require a different number of pages in
67 * memory, the function will return the original pointer.
69 * On success, return a pointer to the newly allocated, or recycled, memory.
70 * On error, return -errno. The following error codes are defined:
71 * -ENOMEM - Not enough memory to allocate runlist array.
72 * -EINVAL - Invalid parameters were passed in.
74 static inline runlist_element *ntfs_rl_realloc(runlist_element *rl,
75 int old_size, int new_size)
77 runlist_element *new_rl;
79 old_size = PAGE_ALIGN(old_size * sizeof(*rl));
80 new_size = PAGE_ALIGN(new_size * sizeof(*rl));
81 if (old_size == new_size)
84 new_rl = ntfs_malloc_nofs(new_size);
85 if (unlikely(!new_rl))
86 return ERR_PTR(-ENOMEM);
88 if (likely(rl != NULL)) {
89 if (unlikely(old_size > new_size))
91 memcpy(new_rl, rl, old_size);
98 * ntfs_are_rl_mergeable - test if two runlists can be joined together
99 * @dst: original runlist
100 * @src: new runlist to test for mergeability with @dst
102 * Test if two runlists can be joined together. For this, their VCNs and LCNs
105 * It is up to the caller to serialize access to the runlists @dst and @src.
107 * Return: TRUE Success, the runlists can be merged.
108 * FALSE Failure, the runlists cannot be merged.
110 static inline BOOL ntfs_are_rl_mergeable(runlist_element *dst,
111 runlist_element *src)
116 if ((dst->lcn < 0) || (src->lcn < 0)) { /* Are we merging holes? */
117 if (dst->lcn == LCN_HOLE && src->lcn == LCN_HOLE)
121 if ((dst->lcn + dst->length) != src->lcn) /* Are the runs contiguous? */
123 if ((dst->vcn + dst->length) != src->vcn) /* Are the runs misaligned? */
130 * __ntfs_rl_merge - merge two runlists without testing if they can be merged
131 * @dst: original, destination runlist
132 * @src: new runlist to merge with @dst
134 * Merge the two runlists, writing into the destination runlist @dst. The
135 * caller must make sure the runlists can be merged or this will corrupt the
136 * destination runlist.
138 * It is up to the caller to serialize access to the runlists @dst and @src.
140 static inline void __ntfs_rl_merge(runlist_element *dst, runlist_element *src)
142 dst->length += src->length;
146 * ntfs_rl_append - append a runlist after a given element
147 * @dst: original runlist to be worked on
148 * @dsize: number of elements in @dst (including end marker)
149 * @src: runlist to be inserted into @dst
150 * @ssize: number of elements in @src (excluding end marker)
151 * @loc: append the new runlist @src after this element in @dst
153 * Append the runlist @src after element @loc in @dst. Merge the right end of
154 * the new runlist, if necessary. Adjust the size of the hole before the
157 * It is up to the caller to serialize access to the runlists @dst and @src.
159 * On success, return a pointer to the new, combined, runlist. Note, both
160 * runlists @dst and @src are deallocated before returning so you cannot use
161 * the pointers for anything any more. (Strictly speaking the returned runlist
162 * may be the same as @dst but this is irrelevant.)
164 * On error, return -errno. Both runlists are left unmodified. The following
165 * error codes are defined:
166 * -ENOMEM - Not enough memory to allocate runlist array.
167 * -EINVAL - Invalid parameters were passed in.
169 static inline runlist_element *ntfs_rl_append(runlist_element *dst,
170 int dsize, runlist_element *src, int ssize, int loc)
178 /* First, check if the right hand end needs merging. */
179 right = ntfs_are_rl_mergeable(src + ssize - 1, dst + loc + 1);
181 /* Space required: @dst size + @src size, less one if we merged. */
182 dst = ntfs_rl_realloc(dst, dsize, dsize + ssize - right);
186 * We are guaranteed to succeed from here so can start modifying the
190 /* First, merge the right hand end, if necessary. */
192 __ntfs_rl_merge(src + ssize - 1, dst + loc + 1);
196 /* Move the tail of @dst out of the way, then copy in @src. */
197 ntfs_rl_mm(dst, magic + 1, loc + 1 + right, dsize - loc - 1 - right);
198 ntfs_rl_mc(dst, loc + 1, src, 0, ssize);
200 /* Adjust the size of the preceding hole. */
201 dst[loc].length = dst[loc + 1].vcn - dst[loc].vcn;
203 /* We may have changed the length of the file, so fix the end marker */
204 if (dst[magic + 1].lcn == LCN_ENOENT)
205 dst[magic + 1].vcn = dst[magic].vcn + dst[magic].length;
211 * ntfs_rl_insert - insert a runlist into another
212 * @dst: original runlist to be worked on
213 * @dsize: number of elements in @dst (including end marker)
214 * @src: new runlist to be inserted
215 * @ssize: number of elements in @src (excluding end marker)
216 * @loc: insert the new runlist @src before this element in @dst
218 * Insert the runlist @src before element @loc in the runlist @dst. Merge the
219 * left end of the new runlist, if necessary. Adjust the size of the hole
220 * after the inserted runlist.
222 * It is up to the caller to serialize access to the runlists @dst and @src.
224 * On success, return a pointer to the new, combined, runlist. Note, both
225 * runlists @dst and @src are deallocated before returning so you cannot use
226 * the pointers for anything any more. (Strictly speaking the returned runlist
227 * may be the same as @dst but this is irrelevant.)
229 * On error, return -errno. Both runlists are left unmodified. The following
230 * error codes are defined:
231 * -ENOMEM - Not enough memory to allocate runlist array.
232 * -EINVAL - Invalid parameters were passed in.
234 static inline runlist_element *ntfs_rl_insert(runlist_element *dst,
235 int dsize, runlist_element *src, int ssize, int loc)
238 BOOL disc = FALSE; /* Discontinuity */
239 BOOL hole = FALSE; /* Following a hole */
245 /* disc => Discontinuity between the end of @dst and the start of @src.
246 * This means we might need to insert a hole.
247 * hole => @dst ends with a hole or an unmapped region which we can
248 * extend to match the discontinuity. */
250 disc = (src[0].vcn > 0);
254 left = ntfs_are_rl_mergeable(dst + loc - 1, src);
256 merged_length = dst[loc - 1].length;
258 merged_length += src->length;
260 disc = (src[0].vcn > dst[loc - 1].vcn + merged_length);
262 hole = (dst[loc - 1].lcn == LCN_HOLE);
265 /* Space required: @dst size + @src size, less one if we merged, plus
266 * one if there was a discontinuity, less one for a trailing hole. */
267 dst = ntfs_rl_realloc(dst, dsize, dsize + ssize - left + disc - hole);
271 * We are guaranteed to succeed from here so can start modifying the
276 __ntfs_rl_merge(dst + loc - 1, src);
278 magic = loc + ssize - left + disc - hole;
280 /* Move the tail of @dst out of the way, then copy in @src. */
281 ntfs_rl_mm(dst, magic, loc, dsize - loc);
282 ntfs_rl_mc(dst, loc + disc - hole, src, left, ssize - left);
284 /* Adjust the VCN of the last run ... */
285 if (dst[magic].lcn <= LCN_HOLE)
286 dst[magic].vcn = dst[magic - 1].vcn + dst[magic - 1].length;
287 /* ... and the length. */
288 if (dst[magic].lcn == LCN_HOLE || dst[magic].lcn == LCN_RL_NOT_MAPPED)
289 dst[magic].length = dst[magic + 1].vcn - dst[magic].vcn;
291 /* Writing beyond the end of the file and there's a discontinuity. */
294 dst[loc - 1].length = dst[loc].vcn - dst[loc - 1].vcn;
297 dst[loc].vcn = dst[loc - 1].vcn +
299 dst[loc].length = dst[loc + 1].vcn -
303 dst[loc].length = dst[loc + 1].vcn;
305 dst[loc].lcn = LCN_RL_NOT_MAPPED;
310 if (dst[magic].lcn == LCN_ENOENT)
311 dst[magic].vcn = dst[magic - 1].vcn +
312 dst[magic - 1].length;
318 * ntfs_rl_replace - overwrite a runlist element with another runlist
319 * @dst: original runlist to be worked on
320 * @dsize: number of elements in @dst (including end marker)
321 * @src: new runlist to be inserted
322 * @ssize: number of elements in @src (excluding end marker)
323 * @loc: index in runlist @dst to overwrite with @src
325 * Replace the runlist element @dst at @loc with @src. Merge the left and
326 * right ends of the inserted runlist, if necessary.
328 * It is up to the caller to serialize access to the runlists @dst and @src.
330 * On success, return a pointer to the new, combined, runlist. Note, both
331 * runlists @dst and @src are deallocated before returning so you cannot use
332 * the pointers for anything any more. (Strictly speaking the returned runlist
333 * may be the same as @dst but this is irrelevant.)
335 * On error, return -errno. Both runlists are left unmodified. The following
336 * error codes are defined:
337 * -ENOMEM - Not enough memory to allocate runlist array.
338 * -EINVAL - Invalid parameters were passed in.
340 static inline runlist_element *ntfs_rl_replace(runlist_element *dst,
341 int dsize, runlist_element *src, int ssize, int loc)
350 /* First, merge the left and right ends, if necessary. */
351 right = ntfs_are_rl_mergeable(src + ssize - 1, dst + loc + 1);
353 left = ntfs_are_rl_mergeable(dst + loc - 1, src);
355 /* Allocate some space. We'll need less if the left, right, or both
356 * ends were merged. */
357 dst = ntfs_rl_realloc(dst, dsize, dsize + ssize - left - right);
361 * We are guaranteed to succeed from here so can start modifying the
365 __ntfs_rl_merge(src + ssize - 1, dst + loc + 1);
367 __ntfs_rl_merge(dst + loc - 1, src);
369 /* FIXME: What does this mean? (AIA) */
370 magic = loc + ssize - left;
372 /* Move the tail of @dst out of the way, then copy in @src. */
373 ntfs_rl_mm(dst, magic, loc + right + 1, dsize - loc - right - 1);
374 ntfs_rl_mc(dst, loc, src, left, ssize - left);
376 /* We may have changed the length of the file, so fix the end marker */
377 if (dst[magic].lcn == LCN_ENOENT)
378 dst[magic].vcn = dst[magic - 1].vcn + dst[magic - 1].length;
383 * ntfs_rl_split - insert a runlist into the centre of a hole
384 * @dst: original runlist to be worked on
385 * @dsize: number of elements in @dst (including end marker)
386 * @src: new runlist to be inserted
387 * @ssize: number of elements in @src (excluding end marker)
388 * @loc: index in runlist @dst at which to split and insert @src
390 * Split the runlist @dst at @loc into two and insert @new in between the two
391 * fragments. No merging of runlists is necessary. Adjust the size of the
394 * It is up to the caller to serialize access to the runlists @dst and @src.
396 * On success, return a pointer to the new, combined, runlist. Note, both
397 * runlists @dst and @src are deallocated before returning so you cannot use
398 * the pointers for anything any more. (Strictly speaking the returned runlist
399 * may be the same as @dst but this is irrelevant.)
401 * On error, return -errno. Both runlists are left unmodified. The following
402 * error codes are defined:
403 * -ENOMEM - Not enough memory to allocate runlist array.
404 * -EINVAL - Invalid parameters were passed in.
406 static inline runlist_element *ntfs_rl_split(runlist_element *dst, int dsize,
407 runlist_element *src, int ssize, int loc)
412 /* Space required: @dst size + @src size + one new hole. */
413 dst = ntfs_rl_realloc(dst, dsize, dsize + ssize + 1);
417 * We are guaranteed to succeed from here so can start modifying the
421 /* Move the tail of @dst out of the way, then copy in @src. */
422 ntfs_rl_mm(dst, loc + 1 + ssize, loc, dsize - loc);
423 ntfs_rl_mc(dst, loc + 1, src, 0, ssize);
425 /* Adjust the size of the holes either size of @src. */
426 dst[loc].length = dst[loc+1].vcn - dst[loc].vcn;
427 dst[loc+ssize+1].vcn = dst[loc+ssize].vcn + dst[loc+ssize].length;
428 dst[loc+ssize+1].length = dst[loc+ssize+2].vcn - dst[loc+ssize+1].vcn;
434 * ntfs_runlists_merge - merge two runlists into one
435 * @drl: original runlist to be worked on
436 * @srl: new runlist to be merged into @drl
438 * First we sanity check the two runlists @srl and @drl to make sure that they
439 * are sensible and can be merged. The runlist @srl must be either after the
440 * runlist @drl or completely within a hole (or unmapped region) in @drl.
442 * It is up to the caller to serialize access to the runlists @drl and @srl.
444 * Merging of runlists is necessary in two cases:
445 * 1. When attribute lists are used and a further extent is being mapped.
446 * 2. When new clusters are allocated to fill a hole or extend a file.
448 * There are four possible ways @srl can be merged. It can:
449 * - be inserted at the beginning of a hole,
450 * - split the hole in two and be inserted between the two fragments,
451 * - be appended at the end of a hole, or it can
452 * - replace the whole hole.
453 * It can also be appended to the end of the runlist, which is just a variant
454 * of the insert case.
456 * On success, return a pointer to the new, combined, runlist. Note, both
457 * runlists @drl and @srl are deallocated before returning so you cannot use
458 * the pointers for anything any more. (Strictly speaking the returned runlist
459 * may be the same as @dst but this is irrelevant.)
461 * On error, return -errno. Both runlists are left unmodified. The following
462 * error codes are defined:
463 * -ENOMEM - Not enough memory to allocate runlist array.
464 * -EINVAL - Invalid parameters were passed in.
465 * -ERANGE - The runlists overlap and cannot be merged.
467 runlist_element *ntfs_runlists_merge(runlist_element *drl,
468 runlist_element *srl)
470 int di, si; /* Current index into @[ds]rl. */
471 int sstart; /* First index with lcn > LCN_RL_NOT_MAPPED. */
472 int dins; /* Index into @drl at which to insert @srl. */
473 int dend, send; /* Last index into @[ds]rl. */
474 int dfinal, sfinal; /* The last index into @[ds]rl with
481 ntfs_debug_dump_runlist(drl);
483 ntfs_debug_dump_runlist(srl);
486 /* Check for silly calling... */
489 if (IS_ERR(srl) || IS_ERR(drl))
490 return ERR_PTR(-EINVAL);
492 /* Check for the case where the first mapping is being done now. */
493 if (unlikely(!drl)) {
495 /* Complete the source runlist if necessary. */
496 if (unlikely(drl[0].vcn)) {
497 /* Scan to the end of the source runlist. */
498 for (dend = 0; likely(drl[dend].length); dend++)
500 drl = ntfs_rl_realloc(drl, dend, dend + 1);
503 /* Insert start element at the front of the runlist. */
504 ntfs_rl_mm(drl, 1, 0, dend);
506 drl[0].lcn = LCN_RL_NOT_MAPPED;
507 drl[0].length = drl[1].vcn;
514 /* Skip any unmapped start element(s) in the source runlist. */
515 while (srl[si].length && srl[si].lcn < LCN_HOLE)
518 /* Can't have an entirely unmapped source runlist. */
519 BUG_ON(!srl[si].length);
521 /* Record the starting points. */
525 * Skip forward in @drl until we reach the position where @srl needs to
526 * be inserted. If we reach the end of @drl, @srl just needs to be
529 for (; drl[di].length; di++) {
530 if (drl[di].vcn + drl[di].length > srl[sstart].vcn)
535 /* Sanity check for illegal overlaps. */
536 if ((drl[di].vcn == srl[si].vcn) && (drl[di].lcn >= 0) &&
537 (srl[si].lcn >= 0)) {
538 ntfs_error(NULL, "Run lists overlap. Cannot merge!");
539 return ERR_PTR(-ERANGE);
542 /* Scan to the end of both runlists in order to know their sizes. */
543 for (send = si; srl[send].length; send++)
545 for (dend = di; drl[dend].length; dend++)
548 if (srl[send].lcn == LCN_ENOENT)
549 marker_vcn = srl[marker = send].vcn;
551 /* Scan to the last element with lcn >= LCN_HOLE. */
552 for (sfinal = send; sfinal >= 0 && srl[sfinal].lcn < LCN_HOLE; sfinal--)
554 for (dfinal = dend; dfinal >= 0 && drl[dfinal].lcn < LCN_HOLE; dfinal--)
560 int ds = dend + 1; /* Number of elements in drl & srl */
561 int ss = sfinal - sstart + 1;
563 start = ((drl[dins].lcn < LCN_RL_NOT_MAPPED) || /* End of file */
564 (drl[dins].vcn == srl[sstart].vcn)); /* Start of hole */
565 finish = ((drl[dins].lcn >= LCN_RL_NOT_MAPPED) && /* End of file */
566 ((drl[dins].vcn + drl[dins].length) <= /* End of hole */
567 (srl[send - 1].vcn + srl[send - 1].length)));
569 /* Or we'll lose an end marker */
570 if (start && finish && (drl[dins].length == 0))
572 if (marker && (drl[dins].vcn + drl[dins].length > srl[send - 1].vcn))
575 ntfs_debug("dfinal = %i, dend = %i", dfinal, dend);
576 ntfs_debug("sstart = %i, sfinal = %i, send = %i", sstart, sfinal, send);
577 ntfs_debug("start = %i, finish = %i", start, finish);
578 ntfs_debug("ds = %i, ss = %i, dins = %i", ds, ss, dins);
582 drl = ntfs_rl_replace(drl, ds, srl + sstart, ss, dins);
584 drl = ntfs_rl_insert(drl, ds, srl + sstart, ss, dins);
587 drl = ntfs_rl_append(drl, ds, srl + sstart, ss, dins);
589 drl = ntfs_rl_split(drl, ds, srl + sstart, ss, dins);
592 ntfs_error(NULL, "Merge failed.");
597 ntfs_debug("Triggering marker code.");
598 for (ds = dend; drl[ds].length; ds++)
600 /* We only need to care if @srl ended after @drl. */
601 if (drl[ds].vcn <= marker_vcn) {
604 if (drl[ds].vcn == marker_vcn) {
605 ntfs_debug("Old marker = 0x%llx, replacing "
609 drl[ds].lcn = LCN_ENOENT;
613 * We need to create an unmapped runlist element in
614 * @drl or extend an existing one before adding the
617 if (drl[ds].lcn == LCN_ENOENT) {
621 if (drl[ds].lcn != LCN_RL_NOT_MAPPED) {
622 /* Add an unmapped runlist element. */
624 /* FIXME/TODO: We need to have the
625 * extra memory already! (AIA) */
626 drl = ntfs_rl_realloc(drl, ds, ds + 2);
632 /* Need to set vcn if it isn't set already. */
634 drl[ds].vcn = drl[ds - 1].vcn +
636 drl[ds].lcn = LCN_RL_NOT_MAPPED;
637 /* We now used up a slot. */
640 drl[ds].length = marker_vcn - drl[ds].vcn;
641 /* Finally add the ENOENT terminator. */
644 /* FIXME/TODO: We need to have the extra
645 * memory already! (AIA) */
646 drl = ntfs_rl_realloc(drl, ds, ds + 1);
650 drl[ds].vcn = marker_vcn;
651 drl[ds].lcn = LCN_ENOENT;
652 drl[ds].length = (s64)0;
658 /* The merge was completed successfully. */
659 ntfs_debug("Merged runlist:");
660 ntfs_debug_dump_runlist(drl);
664 /* Critical error! We cannot afford to fail here. */
665 ntfs_error(NULL, "Critical error! Not enough memory.");
666 panic("NTFS: Cannot continue.");
670 * ntfs_mapping_pairs_decompress - convert mapping pairs array to runlist
671 * @vol: ntfs volume on which the attribute resides
672 * @attr: attribute record whose mapping pairs array to decompress
673 * @old_rl: optional runlist in which to insert @attr's runlist
675 * It is up to the caller to serialize access to the runlist @old_rl.
677 * Decompress the attribute @attr's mapping pairs array into a runlist. On
678 * success, return the decompressed runlist.
680 * If @old_rl is not NULL, decompressed runlist is inserted into the
681 * appropriate place in @old_rl and the resultant, combined runlist is
682 * returned. The original @old_rl is deallocated.
684 * On error, return -errno. @old_rl is left unmodified in that case.
686 * The following error codes are defined:
687 * -ENOMEM - Not enough memory to allocate runlist array.
688 * -EIO - Corrupt runlist.
689 * -EINVAL - Invalid parameters were passed in.
690 * -ERANGE - The two runlists overlap.
692 * FIXME: For now we take the conceptionally simplest approach of creating the
693 * new runlist disregarding the already existing one and then splicing the
694 * two into one, if that is possible (we check for overlap and discard the new
695 * runlist if overlap present before returning ERR_PTR(-ERANGE)).
697 runlist_element *ntfs_mapping_pairs_decompress(const ntfs_volume *vol,
698 const ATTR_RECORD *attr, runlist_element *old_rl)
700 VCN vcn; /* Current vcn. */
701 LCN lcn; /* Current lcn. */
702 s64 deltaxcn; /* Change in [vl]cn. */
703 runlist_element *rl; /* The output runlist. */
704 u8 *buf; /* Current position in mapping pairs array. */
705 u8 *attr_end; /* End of attribute. */
706 int rlsize; /* Size of runlist buffer. */
707 u16 rlpos; /* Current runlist position in units of
709 u8 b; /* Current byte offset in buf. */
712 /* Make sure attr exists and is non-resident. */
713 if (!attr || !attr->non_resident || sle64_to_cpu(
714 attr->data.non_resident.lowest_vcn) < (VCN)0) {
715 ntfs_error(vol->sb, "Invalid arguments.");
716 return ERR_PTR(-EINVAL);
719 /* Start at vcn = lowest_vcn and lcn 0. */
720 vcn = sle64_to_cpu(attr->data.non_resident.lowest_vcn);
722 /* Get start of the mapping pairs array. */
723 buf = (u8*)attr + le16_to_cpu(
724 attr->data.non_resident.mapping_pairs_offset);
725 attr_end = (u8*)attr + le32_to_cpu(attr->length);
726 if (unlikely(buf < (u8*)attr || buf > attr_end)) {
727 ntfs_error(vol->sb, "Corrupt attribute.");
728 return ERR_PTR(-EIO);
730 /* Current position in runlist array. */
732 /* Allocate first page and set current runlist size to one page. */
733 rl = ntfs_malloc_nofs(rlsize = PAGE_SIZE);
735 return ERR_PTR(-ENOMEM);
736 /* Insert unmapped starting element if necessary. */
739 rl->lcn = LCN_RL_NOT_MAPPED;
743 while (buf < attr_end && *buf) {
745 * Allocate more memory if needed, including space for the
746 * not-mapped and terminator elements. ntfs_malloc_nofs()
747 * operates on whole pages only.
749 if (((rlpos + 3) * sizeof(*old_rl)) > rlsize) {
750 runlist_element *rl2;
752 rl2 = ntfs_malloc_nofs(rlsize + (int)PAGE_SIZE);
753 if (unlikely(!rl2)) {
755 return ERR_PTR(-ENOMEM);
757 memcpy(rl2, rl, rlsize);
762 /* Enter the current vcn into the current runlist element. */
765 * Get the change in vcn, i.e. the run length in clusters.
766 * Doing it this way ensures that we signextend negative values.
767 * A negative run length doesn't make any sense, but hey, I
768 * didn't make up the NTFS specs and Windows NT4 treats the run
769 * length as a signed value so that's how it is...
773 if (unlikely(buf + b > attr_end))
775 for (deltaxcn = (s8)buf[b--]; b; b--)
776 deltaxcn = (deltaxcn << 8) + buf[b];
777 } else { /* The length entry is compulsory. */
778 ntfs_error(vol->sb, "Missing length entry in mapping "
783 * Assume a negative length to indicate data corruption and
784 * hence clean-up and return NULL.
786 if (unlikely(deltaxcn < 0)) {
787 ntfs_error(vol->sb, "Invalid length in mapping pairs "
792 * Enter the current run length into the current runlist
795 rl[rlpos].length = deltaxcn;
796 /* Increment the current vcn by the current run length. */
799 * There might be no lcn change at all, as is the case for
800 * sparse clusters on NTFS 3.0+, in which case we set the lcn
804 rl[rlpos].lcn = LCN_HOLE;
806 /* Get the lcn change which really can be negative. */
808 b = b2 + ((*buf >> 4) & 0xf);
809 if (buf + b > attr_end)
811 for (deltaxcn = (s8)buf[b--]; b > b2; b--)
812 deltaxcn = (deltaxcn << 8) + buf[b];
813 /* Change the current lcn to its new value. */
817 * On NTFS 1.2-, apparently can have lcn == -1 to
818 * indicate a hole. But we haven't verified ourselves
819 * whether it is really the lcn or the deltaxcn that is
820 * -1. So if either is found give us a message so we
821 * can investigate it further!
823 if (vol->major_ver < 3) {
824 if (unlikely(deltaxcn == (LCN)-1))
825 ntfs_error(vol->sb, "lcn delta == -1");
826 if (unlikely(lcn == (LCN)-1))
827 ntfs_error(vol->sb, "lcn == -1");
830 /* Check lcn is not below -1. */
831 if (unlikely(lcn < (LCN)-1)) {
832 ntfs_error(vol->sb, "Invalid LCN < -1 in "
833 "mapping pairs array.");
836 /* Enter the current lcn into the runlist element. */
839 /* Get to the next runlist element. */
841 /* Increment the buffer position to the next mapping pair. */
842 buf += (*buf & 0xf) + ((*buf >> 4) & 0xf) + 1;
844 if (unlikely(buf >= attr_end))
847 * If there is a highest_vcn specified, it must be equal to the final
848 * vcn in the runlist - 1, or something has gone badly wrong.
850 deltaxcn = sle64_to_cpu(attr->data.non_resident.highest_vcn);
851 if (unlikely(deltaxcn && vcn - 1 != deltaxcn)) {
853 ntfs_error(vol->sb, "Corrupt mapping pairs array in "
854 "non-resident attribute.");
857 /* Setup not mapped runlist element if this is the base extent. */
858 if (!attr->data.non_resident.lowest_vcn) {
861 max_cluster = ((sle64_to_cpu(
862 attr->data.non_resident.allocated_size) +
863 vol->cluster_size - 1) >>
864 vol->cluster_size_bits) - 1;
866 * A highest_vcn of zero means this is a single extent
867 * attribute so simply terminate the runlist with LCN_ENOENT).
871 * If there is a difference between the highest_vcn and
872 * the highest cluster, the runlist is either corrupt
873 * or, more likely, there are more extents following
876 if (deltaxcn < max_cluster) {
877 ntfs_debug("More extents to follow; deltaxcn "
878 "= 0x%llx, max_cluster = "
880 (unsigned long long)deltaxcn,
884 vcn += rl[rlpos].length = max_cluster -
886 rl[rlpos].lcn = LCN_RL_NOT_MAPPED;
888 } else if (unlikely(deltaxcn > max_cluster)) {
889 ntfs_error(vol->sb, "Corrupt attribute. "
890 "deltaxcn = 0x%llx, "
891 "max_cluster = 0x%llx",
892 (unsigned long long)deltaxcn,
898 rl[rlpos].lcn = LCN_ENOENT;
899 } else /* Not the base extent. There may be more extents to follow. */
900 rl[rlpos].lcn = LCN_RL_NOT_MAPPED;
902 /* Setup terminating runlist element. */
904 rl[rlpos].length = (s64)0;
905 /* If no existing runlist was specified, we are done. */
907 ntfs_debug("Mapping pairs array successfully decompressed:");
908 ntfs_debug_dump_runlist(rl);
911 /* Now combine the new and old runlists checking for overlaps. */
912 old_rl = ntfs_runlists_merge(old_rl, rl);
913 if (likely(!IS_ERR(old_rl)))
916 ntfs_error(vol->sb, "Failed to merge runlists.");
919 ntfs_error(vol->sb, "Corrupt attribute.");
922 return ERR_PTR(-EIO);
926 * ntfs_rl_vcn_to_lcn - convert a vcn into a lcn given a runlist
927 * @rl: runlist to use for conversion
928 * @vcn: vcn to convert
930 * Convert the virtual cluster number @vcn of an attribute into a logical
931 * cluster number (lcn) of a device using the runlist @rl to map vcns to their
932 * corresponding lcns.
934 * It is up to the caller to serialize access to the runlist @rl.
936 * Since lcns must be >= 0, we use negative return codes with special meaning:
938 * Return code Meaning / Description
939 * ==================================================
940 * LCN_HOLE Hole / not allocated on disk.
941 * LCN_RL_NOT_MAPPED This is part of the runlist which has not been
942 * inserted into the runlist yet.
943 * LCN_ENOENT There is no such vcn in the attribute.
945 * Locking: - The caller must have locked the runlist (for reading or writing).
946 * - This function does not touch the lock, nor does it modify the
949 LCN ntfs_rl_vcn_to_lcn(const runlist_element *rl, const VCN vcn)
955 * If rl is NULL, assume that we have found an unmapped runlist. The
956 * caller can then attempt to map it and fail appropriately if
960 return LCN_RL_NOT_MAPPED;
962 /* Catch out of lower bounds vcn. */
963 if (unlikely(vcn < rl[0].vcn))
966 for (i = 0; likely(rl[i].length); i++) {
967 if (unlikely(vcn < rl[i+1].vcn)) {
968 if (likely(rl[i].lcn >= (LCN)0))
969 return rl[i].lcn + (vcn - rl[i].vcn);
974 * The terminator element is setup to the correct value, i.e. one of
975 * LCN_HOLE, LCN_RL_NOT_MAPPED, or LCN_ENOENT.
977 if (likely(rl[i].lcn < (LCN)0))
979 /* Just in case... We could replace this with BUG() some day. */
986 * ntfs_rl_find_vcn_nolock - find a vcn in a runlist
987 * @rl: runlist to search
990 * Find the virtual cluster number @vcn in the runlist @rl and return the
991 * address of the runlist element containing the @vcn on success.
993 * Return NULL if @rl is NULL or @vcn is in an unmapped part/out of bounds of
996 * Locking: The runlist must be locked on entry.
998 runlist_element *ntfs_rl_find_vcn_nolock(runlist_element *rl, const VCN vcn)
1001 if (unlikely(!rl || vcn < rl[0].vcn))
1003 while (likely(rl->length)) {
1004 if (unlikely(vcn < rl[1].vcn)) {
1005 if (likely(rl->lcn >= LCN_HOLE))
1011 if (likely(rl->lcn == LCN_ENOENT))
1017 * ntfs_get_nr_significant_bytes - get number of bytes needed to store a number
1018 * @n: number for which to get the number of bytes for
1020 * Return the number of bytes required to store @n unambiguously as
1023 * This is used in the context of the mapping pairs array to determine how
1024 * many bytes will be needed in the array to store a given logical cluster
1025 * number (lcn) or a specific run length.
1027 * Return the number of bytes written. This function cannot fail.
1029 static inline int ntfs_get_nr_significant_bytes(const s64 n)
1039 } while (l != 0 && l != -1);
1040 j = (n >> 8 * (i - 1)) & 0xff;
1041 /* If the sign bit is wrong, we need an extra byte. */
1042 if ((n < 0 && j >= 0) || (n > 0 && j < 0))
1048 * ntfs_get_size_for_mapping_pairs - get bytes needed for mapping pairs array
1049 * @vol: ntfs volume (needed for the ntfs version)
1050 * @rl: locked runlist to determine the size of the mapping pairs of
1051 * @first_vcn: first vcn which to include in the mapping pairs array
1052 * @last_vcn: last vcn which to include in the mapping pairs array
1054 * Walk the locked runlist @rl and calculate the size in bytes of the mapping
1055 * pairs array corresponding to the runlist @rl, starting at vcn @first_vcn and
1056 * finishing with vcn @last_vcn.
1058 * A @last_vcn of -1 means end of runlist and in that case the size of the
1059 * mapping pairs array corresponding to the runlist starting at vcn @first_vcn
1060 * and finishing at the end of the runlist is determined.
1062 * This for example allows us to allocate a buffer of the right size when
1063 * building the mapping pairs array.
1065 * If @rl is NULL, just return 1 (for the single terminator byte).
1067 * Return the calculated size in bytes on success. On error, return -errno.
1068 * The following error codes are defined:
1069 * -EINVAL - Run list contains unmapped elements. Make sure to only pass
1070 * fully mapped runlists to this function.
1071 * -EIO - The runlist is corrupt.
1073 * Locking: @rl must be locked on entry (either for reading or writing), it
1074 * remains locked throughout, and is left locked upon return.
1076 int ntfs_get_size_for_mapping_pairs(const ntfs_volume *vol,
1077 const runlist_element *rl, const VCN first_vcn,
1082 BOOL the_end = FALSE;
1084 BUG_ON(first_vcn < 0);
1085 BUG_ON(last_vcn < -1);
1086 BUG_ON(last_vcn >= 0 && first_vcn > last_vcn);
1089 BUG_ON(last_vcn > 0);
1092 /* Skip to runlist element containing @first_vcn. */
1093 while (rl->length && first_vcn >= rl[1].vcn)
1095 if (unlikely((!rl->length && first_vcn > rl->vcn) ||
1096 first_vcn < rl->vcn))
1099 /* Always need the termining zero byte. */
1101 /* Do the first partial run if present. */
1102 if (first_vcn > rl->vcn) {
1103 s64 delta, length = rl->length;
1105 /* We know rl->length != 0 already. */
1106 if (unlikely(length < 0 || rl->lcn < LCN_HOLE))
1109 * If @stop_vcn is given and finishes inside this run, cap the
1112 if (unlikely(last_vcn >= 0 && rl[1].vcn > last_vcn)) {
1113 s64 s1 = last_vcn + 1;
1114 if (unlikely(rl[1].vcn > s1))
1115 length = s1 - rl->vcn;
1118 delta = first_vcn - rl->vcn;
1119 /* Header byte + length. */
1120 rls += 1 + ntfs_get_nr_significant_bytes(length - delta);
1122 * If the logical cluster number (lcn) denotes a hole and we
1123 * are on NTFS 3.0+, we don't store it at all, i.e. we need
1124 * zero space. On earlier NTFS versions we just store the lcn.
1125 * Note: this assumes that on NTFS 1.2-, holes are stored with
1126 * an lcn of -1 and not a delta_lcn of -1 (unless both are -1).
1128 if (likely(rl->lcn >= 0 || vol->major_ver < 3)) {
1130 if (likely(rl->lcn >= 0))
1132 /* Change in lcn. */
1133 rls += ntfs_get_nr_significant_bytes(prev_lcn);
1135 /* Go to next runlist element. */
1138 /* Do the full runs. */
1139 for (; rl->length && !the_end; rl++) {
1140 s64 length = rl->length;
1142 if (unlikely(length < 0 || rl->lcn < LCN_HOLE))
1145 * If @stop_vcn is given and finishes inside this run, cap the
1148 if (unlikely(last_vcn >= 0 && rl[1].vcn > last_vcn)) {
1149 s64 s1 = last_vcn + 1;
1150 if (unlikely(rl[1].vcn > s1))
1151 length = s1 - rl->vcn;
1154 /* Header byte + length. */
1155 rls += 1 + ntfs_get_nr_significant_bytes(length);
1157 * If the logical cluster number (lcn) denotes a hole and we
1158 * are on NTFS 3.0+, we don't store it at all, i.e. we need
1159 * zero space. On earlier NTFS versions we just store the lcn.
1160 * Note: this assumes that on NTFS 1.2-, holes are stored with
1161 * an lcn of -1 and not a delta_lcn of -1 (unless both are -1).
1163 if (likely(rl->lcn >= 0 || vol->major_ver < 3)) {
1164 /* Change in lcn. */
1165 rls += ntfs_get_nr_significant_bytes(rl->lcn -
1172 if (rl->lcn == LCN_RL_NOT_MAPPED)
1180 * ntfs_write_significant_bytes - write the significant bytes of a number
1181 * @dst: destination buffer to write to
1182 * @dst_max: pointer to last byte of destination buffer for bounds checking
1183 * @n: number whose significant bytes to write
1185 * Store in @dst, the minimum bytes of the number @n which are required to
1186 * identify @n unambiguously as a signed number, taking care not to exceed
1187 * @dest_max, the maximum position within @dst to which we are allowed to
1190 * This is used when building the mapping pairs array of a runlist to compress
1191 * a given logical cluster number (lcn) or a specific run length to the minumum
1194 * Return the number of bytes written on success. On error, i.e. the
1195 * destination buffer @dst is too small, return -ENOSPC.
1197 static inline int ntfs_write_significant_bytes(s8 *dst, const s8 *dst_max,
1206 if (unlikely(dst > dst_max))
1208 *dst++ = l & 0xffll;
1211 } while (l != 0 && l != -1);
1212 j = (n >> 8 * (i - 1)) & 0xff;
1213 /* If the sign bit is wrong, we need an extra byte. */
1214 if (n < 0 && j >= 0) {
1215 if (unlikely(dst > dst_max))
1219 } else if (n > 0 && j < 0) {
1220 if (unlikely(dst > dst_max))
1231 * ntfs_mapping_pairs_build - build the mapping pairs array from a runlist
1232 * @vol: ntfs volume (needed for the ntfs version)
1233 * @dst: destination buffer to which to write the mapping pairs array
1234 * @dst_len: size of destination buffer @dst in bytes
1235 * @rl: locked runlist for which to build the mapping pairs array
1236 * @first_vcn: first vcn which to include in the mapping pairs array
1237 * @last_vcn: last vcn which to include in the mapping pairs array
1238 * @stop_vcn: first vcn outside destination buffer on success or -ENOSPC
1240 * Create the mapping pairs array from the locked runlist @rl, starting at vcn
1241 * @first_vcn and finishing with vcn @last_vcn and save the array in @dst.
1242 * @dst_len is the size of @dst in bytes and it should be at least equal to the
1243 * value obtained by calling ntfs_get_size_for_mapping_pairs().
1245 * A @last_vcn of -1 means end of runlist and in that case the mapping pairs
1246 * array corresponding to the runlist starting at vcn @first_vcn and finishing
1247 * at the end of the runlist is created.
1249 * If @rl is NULL, just write a single terminator byte to @dst.
1251 * On success or -ENOSPC error, if @stop_vcn is not NULL, *@stop_vcn is set to
1252 * the first vcn outside the destination buffer. Note that on error, @dst has
1253 * been filled with all the mapping pairs that will fit, thus it can be treated
1254 * as partial success, in that a new attribute extent needs to be created or
1255 * the next extent has to be used and the mapping pairs build has to be
1256 * continued with @first_vcn set to *@stop_vcn.
1258 * Return 0 on success and -errno on error. The following error codes are
1260 * -EINVAL - Run list contains unmapped elements. Make sure to only pass
1261 * fully mapped runlists to this function.
1262 * -EIO - The runlist is corrupt.
1263 * -ENOSPC - The destination buffer is too small.
1265 * Locking: @rl must be locked on entry (either for reading or writing), it
1266 * remains locked throughout, and is left locked upon return.
1268 int ntfs_mapping_pairs_build(const ntfs_volume *vol, s8 *dst,
1269 const int dst_len, const runlist_element *rl,
1270 const VCN first_vcn, const VCN last_vcn, VCN *const stop_vcn)
1273 s8 *dst_max, *dst_next;
1275 BOOL the_end = FALSE;
1276 s8 len_len, lcn_len;
1278 BUG_ON(first_vcn < 0);
1279 BUG_ON(last_vcn < -1);
1280 BUG_ON(last_vcn >= 0 && first_vcn > last_vcn);
1281 BUG_ON(dst_len < 1);
1284 BUG_ON(last_vcn > 0);
1287 /* Terminator byte. */
1291 /* Skip to runlist element containing @first_vcn. */
1292 while (rl->length && first_vcn >= rl[1].vcn)
1294 if (unlikely((!rl->length && first_vcn > rl->vcn) ||
1295 first_vcn < rl->vcn))
1298 * @dst_max is used for bounds checking in
1299 * ntfs_write_significant_bytes().
1301 dst_max = dst + dst_len - 1;
1303 /* Do the first partial run if present. */
1304 if (first_vcn > rl->vcn) {
1305 s64 delta, length = rl->length;
1307 /* We know rl->length != 0 already. */
1308 if (unlikely(length < 0 || rl->lcn < LCN_HOLE))
1311 * If @stop_vcn is given and finishes inside this run, cap the
1314 if (unlikely(last_vcn >= 0 && rl[1].vcn > last_vcn)) {
1315 s64 s1 = last_vcn + 1;
1316 if (unlikely(rl[1].vcn > s1))
1317 length = s1 - rl->vcn;
1320 delta = first_vcn - rl->vcn;
1322 len_len = ntfs_write_significant_bytes(dst + 1, dst_max,
1324 if (unlikely(len_len < 0))
1327 * If the logical cluster number (lcn) denotes a hole and we
1328 * are on NTFS 3.0+, we don't store it at all, i.e. we need
1329 * zero space. On earlier NTFS versions we just write the lcn
1330 * change. FIXME: Do we need to write the lcn change or just
1331 * the lcn in that case? Not sure as I have never seen this
1332 * case on NT4. - We assume that we just need to write the lcn
1333 * change until someone tells us otherwise... (AIA)
1335 if (likely(rl->lcn >= 0 || vol->major_ver < 3)) {
1337 if (likely(rl->lcn >= 0))
1339 /* Write change in lcn. */
1340 lcn_len = ntfs_write_significant_bytes(dst + 1 +
1341 len_len, dst_max, prev_lcn);
1342 if (unlikely(lcn_len < 0))
1346 dst_next = dst + len_len + lcn_len + 1;
1347 if (unlikely(dst_next > dst_max))
1349 /* Update header byte. */
1350 *dst = lcn_len << 4 | len_len;
1351 /* Position at next mapping pairs array element. */
1353 /* Go to next runlist element. */
1356 /* Do the full runs. */
1357 for (; rl->length && !the_end; rl++) {
1358 s64 length = rl->length;
1360 if (unlikely(length < 0 || rl->lcn < LCN_HOLE))
1363 * If @stop_vcn is given and finishes inside this run, cap the
1366 if (unlikely(last_vcn >= 0 && rl[1].vcn > last_vcn)) {
1367 s64 s1 = last_vcn + 1;
1368 if (unlikely(rl[1].vcn > s1))
1369 length = s1 - rl->vcn;
1373 len_len = ntfs_write_significant_bytes(dst + 1, dst_max,
1375 if (unlikely(len_len < 0))
1378 * If the logical cluster number (lcn) denotes a hole and we
1379 * are on NTFS 3.0+, we don't store it at all, i.e. we need
1380 * zero space. On earlier NTFS versions we just write the lcn
1381 * change. FIXME: Do we need to write the lcn change or just
1382 * the lcn in that case? Not sure as I have never seen this
1383 * case on NT4. - We assume that we just need to write the lcn
1384 * change until someone tells us otherwise... (AIA)
1386 if (likely(rl->lcn >= 0 || vol->major_ver < 3)) {
1387 /* Write change in lcn. */
1388 lcn_len = ntfs_write_significant_bytes(dst + 1 +
1389 len_len, dst_max, rl->lcn - prev_lcn);
1390 if (unlikely(lcn_len < 0))
1395 dst_next = dst + len_len + lcn_len + 1;
1396 if (unlikely(dst_next > dst_max))
1398 /* Update header byte. */
1399 *dst = lcn_len << 4 | len_len;
1400 /* Position at next mapping pairs array element. */
1408 *stop_vcn = rl->vcn;
1409 /* Add terminator byte. */
1413 if (rl->lcn == LCN_RL_NOT_MAPPED)
1421 * ntfs_rl_truncate_nolock - truncate a runlist starting at a specified vcn
1422 * @runlist: runlist to truncate
1423 * @new_length: the new length of the runlist in VCNs
1425 * Truncate the runlist described by @runlist as well as the memory buffer
1426 * holding the runlist elements to a length of @new_length VCNs.
1428 * If @new_length lies within the runlist, the runlist elements with VCNs of
1429 * @new_length and above are discarded.
1431 * If @new_length lies beyond the runlist, a sparse runlist element is added to
1432 * the end of the runlist @runlist or if the last runlist element is a sparse
1433 * one already, this is extended.
1435 * Return 0 on success and -errno on error.
1437 * Locking: The caller must hold @runlist->lock for writing.
1439 int ntfs_rl_truncate_nolock(const ntfs_volume *vol, runlist *const runlist,
1440 const s64 new_length)
1442 runlist_element *rl;
1445 ntfs_debug("Entering for new_length 0x%llx.", (long long)new_length);
1447 BUG_ON(new_length < 0);
1449 if (unlikely(!rl)) {
1451 * Create a runlist consisting of a sparse runlist element of
1452 * length @new_length followed by a terminator runlist element.
1454 rl = ntfs_malloc_nofs(PAGE_SIZE);
1455 if (unlikely(!rl)) {
1456 ntfs_error(vol->sb, "Not enough memory to allocate "
1457 "runlist element buffer.");
1461 rl[1].length = rl->vcn = 0;
1463 rl[1].vcn = rl->length = new_length;
1464 rl[1].lcn = LCN_ENOENT;
1467 BUG_ON(new_length < rl->vcn);
1468 /* Find @new_length in the runlist. */
1469 while (likely(rl->length && new_length >= rl[1].vcn))
1472 * If not at the end of the runlist we need to shrink it.
1473 * If at the end of the runlist we need to expand it.
1476 runlist_element *trl;
1479 ntfs_debug("Shrinking runlist.");
1480 /* Determine the runlist size. */
1482 while (likely(trl->length))
1484 old_size = trl - runlist->rl + 1;
1485 /* Truncate the run. */
1486 rl->length = new_length - rl->vcn;
1488 * If a run was partially truncated, make the following runlist
1489 * element a terminator.
1496 rl->vcn = new_length;
1499 rl->lcn = LCN_ENOENT;
1500 /* Reallocate memory if necessary. */
1502 int new_size = rl - runlist->rl + 1;
1503 rl = ntfs_rl_realloc(runlist->rl, old_size, new_size);
1505 ntfs_warning(vol->sb, "Failed to shrink "
1506 "runlist buffer. This just "
1507 "wastes a bit of memory "
1508 "temporarily so we ignore it "
1509 "and return success.");
1513 } else if (likely(/* !rl->length && */ new_length > rl->vcn)) {
1514 ntfs_debug("Expanding runlist.");
1516 * If there is a previous runlist element and it is a sparse
1517 * one, extend it. Otherwise need to add a new, sparse runlist
1520 if ((rl > runlist->rl) && ((rl - 1)->lcn == LCN_HOLE))
1521 (rl - 1)->length = new_length - (rl - 1)->vcn;
1523 /* Determine the runlist size. */
1524 old_size = rl - runlist->rl + 1;
1525 /* Reallocate memory if necessary. */
1526 rl = ntfs_rl_realloc(runlist->rl, old_size,
1529 ntfs_error(vol->sb, "Failed to expand runlist "
1530 "buffer, aborting.");
1535 * Set @rl to the same runlist element in the new
1536 * runlist as before in the old runlist.
1539 /* Add a new, sparse runlist element. */
1541 rl->length = new_length - rl->vcn;
1542 /* Add a new terminator runlist element. */
1546 rl->vcn = new_length;
1547 rl->lcn = LCN_ENOENT;
1548 } else /* if (unlikely(!rl->length && new_length == rl->vcn)) */ {
1549 /* Runlist already has same size as requested. */
1550 rl->lcn = LCN_ENOENT;
1552 ntfs_debug("Done.");
1556 #endif /* NTFS_RW */