xref: /linux/fs/ntfs/runlist.c (revision 9d19ca5d0e8b4a3f4b2eaa14e86a25f1c93ff35b)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * NTFS runlist handling code.
4  *
5  * Copyright (c) 2001-2007 Anton Altaparmakov
6  * Copyright (c) 2002-2005 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) 2002-2005 Anton Altaparmakov
12  * Copyright (c) 2002-2005 Richard Russon
13  * Copyright (c) 2002-2008 Szabolcs Szakacsits
14  * Copyright (c) 2004 Yura Pakhuchiy
15  * Copyright (c) 2007-2022 Jean-Pierre Andre
16  */
17 
18 #include <linux/overflow.h>
19 
20 #include "ntfs.h"
21 #include "attrib.h"
22 
23 /*
24  * ntfs_rl_mm - runlist memmove
25  * @base: base runlist array
26  * @dst: destination index in @base
27  * @src: source index in @base
28  * @size: number of elements to move
29  *
30  * It is up to the caller to serialize access to the runlist @base.
31  */
32 static inline void ntfs_rl_mm(struct runlist_element *base, int dst, int src, int size)
33 {
34 	if (likely((dst != src) && (size > 0)))
35 		memmove(base + dst, base + src, size * sizeof(*base));
36 }
37 
38 /*
39  * ntfs_rl_mc - runlist memory copy
40  * @dstbase: destination runlist array
41  * @dst: destination index in @dstbase
42  * @srcbase: source runlist array
43  * @src: source index in @srcbase
44  * @size: number of elements to copy
45  *
46  * It is up to the caller to serialize access to the runlists @dstbase and
47  * @srcbase.
48  */
49 static inline void ntfs_rl_mc(struct runlist_element *dstbase, int dst,
50 		struct runlist_element *srcbase, int src, int size)
51 {
52 	if (likely(size > 0))
53 		memcpy(dstbase + dst, srcbase + src, size * sizeof(*dstbase));
54 }
55 
56 /*
57  * ntfs_rl_realloc - Reallocate memory for runlists
58  * @rl:		original runlist
59  * @old_size:	number of runlist elements in the original runlist @rl
60  * @new_size:	number of runlist elements we need space for
61  *
62  * As the runlists grow, more memory will be required.  To prevent the
63  * kernel having to allocate and reallocate large numbers of small bits of
64  * memory, this function returns an entire page of memory.
65  *
66  * It is up to the caller to serialize access to the runlist @rl.
67  *
68  * N.B.  If the new allocation doesn't require a different number of pages in
69  *       memory, the function will return the original pointer.
70  *
71  * On success, return a pointer to the newly allocated, or recycled, memory.
72  * On error, return -errno.
73  */
74 static inline struct runlist_element *ntfs_rl_realloc_gfp(struct runlist_element *rl,
75 		int old_size, int new_size, gfp_t gfp)
76 {
77 	struct runlist_element *new_rl;
78 	size_t new_bytes;
79 
80 	if (old_size < 0 || new_size < 0)
81 		return ERR_PTR(-EINVAL);
82 
83 	if (old_size == new_size)
84 		return rl;
85 
86 	if (check_mul_overflow(new_size, sizeof(*rl), &new_bytes))
87 		return ERR_PTR(-EINVAL);
88 
89 	new_rl = kvzalloc(new_bytes, gfp);
90 	if (unlikely(!new_rl))
91 		return ERR_PTR(-ENOMEM);
92 
93 	if (likely(rl != NULL)) {
94 		size_t old_bytes;
95 
96 		if (check_mul_overflow(old_size, sizeof(*rl), &old_bytes)) {
97 			kvfree(new_rl);
98 			return ERR_PTR(-EINVAL);
99 		}
100 		if (unlikely(old_bytes > new_bytes))
101 			old_bytes = new_bytes;
102 		memcpy(new_rl, rl, old_bytes);
103 		kvfree(rl);
104 	}
105 	return new_rl;
106 }
107 
108 struct runlist_element *ntfs_rl_realloc(struct runlist_element *rl,
109 		int old_size, int new_size)
110 {
111 	return ntfs_rl_realloc_gfp(rl, old_size, new_size, GFP_NOFS);
112 }
113 
114 /*
115  * ntfs_rl_realloc_nofail - Reallocate memory for runlists
116  * @rl:		original runlist
117  * @old_size:	number of runlist elements in the original runlist @rl
118  * @new_size:	number of runlist elements we need space for
119  *
120  * As the runlists grow, more memory will be required.  To prevent the
121  * kernel having to allocate and reallocate large numbers of small bits of
122  * memory, this function returns an entire page of memory.
123  *
124  * This function guarantees that the allocation will succeed.  It will sleep
125  * for as long as it takes to complete the allocation.
126  *
127  * It is up to the caller to serialize access to the runlist @rl.
128  *
129  * N.B.  If the new allocation doesn't require a different number of pages in
130  *       memory, the function will return the original pointer.
131  *
132  * On success, return a pointer to the newly allocated, or recycled, memory.
133  * On error, return -errno.
134  */
135 static inline struct runlist_element *ntfs_rl_realloc_nofail(struct runlist_element *rl,
136 		int old_size, int new_size)
137 {
138 	return ntfs_rl_realloc_gfp(rl, old_size, new_size,
139 			GFP_NOFS | __GFP_NOFAIL);
140 }
141 
142 /*
143  * ntfs_are_rl_mergeable - test if two runlists can be joined together
144  * @dst:	original runlist
145  * @src:	new runlist to test for mergeability with @dst
146  *
147  * Test if two runlists can be joined together. For this, their VCNs and LCNs
148  * must be adjacent.
149  *
150  * It is up to the caller to serialize access to the runlists @dst and @src.
151  *
152  * Return: true   Success, the runlists can be merged.
153  *	   false  Failure, the runlists cannot be merged.
154  */
155 static inline bool ntfs_are_rl_mergeable(struct runlist_element *dst,
156 		struct runlist_element *src)
157 {
158 	/* We can merge unmapped regions even if they are misaligned. */
159 	if ((dst->lcn == LCN_RL_NOT_MAPPED) && (src->lcn == LCN_RL_NOT_MAPPED))
160 		return true;
161 	/* If the runs are misaligned, we cannot merge them. */
162 	if ((dst->vcn + dst->length) != src->vcn)
163 		return false;
164 	/* If both runs are non-sparse and contiguous, we can merge them. */
165 	if ((dst->lcn >= 0) && (src->lcn >= 0) &&
166 			((dst->lcn + dst->length) == src->lcn))
167 		return true;
168 	/* If we are merging two holes, we can merge them. */
169 	if ((dst->lcn == LCN_HOLE) && (src->lcn == LCN_HOLE))
170 		return true;
171 	/* If we are merging two dealloc, we can merge them. */
172 	if ((dst->lcn == LCN_DELALLOC) && (src->lcn == LCN_DELALLOC))
173 		return true;
174 	/* Cannot merge. */
175 	return false;
176 }
177 
178 /*
179  * __ntfs_rl_merge - merge two runlists without testing if they can be merged
180  * @dst:	original, destination runlist
181  * @src:	new runlist to merge with @dst
182  *
183  * Merge the two runlists, writing into the destination runlist @dst. The
184  * caller must make sure the runlists can be merged or this will corrupt the
185  * destination runlist.
186  *
187  * It is up to the caller to serialize access to the runlists @dst and @src.
188  */
189 static inline void __ntfs_rl_merge(struct runlist_element *dst, struct runlist_element *src)
190 {
191 	dst->length += src->length;
192 }
193 
194 /*
195  * ntfs_rl_append - append a runlist after a given element
196  * @dst: destination runlist to append to
197  * @dsize: number of elements in @dst
198  * @src: source runlist to append from
199  * @ssize: number of elements in @src
200  * @loc: index in @dst after which to append @src
201  * @new_size: on success, set to the new combined size
202  *
203  * Append the runlist @src after element @loc in @dst.  Merge the right end of
204  * the new runlist, if necessary. Adjust the size of the hole before the
205  * appended runlist.
206  *
207  * It is up to the caller to serialize access to the runlists @dst and @src.
208  *
209  * On success, return a pointer to the new, combined, runlist. Note, both
210  * runlists @dst and @src are deallocated before returning so you cannot use
211  * the pointers for anything any more. (Strictly speaking the returned runlist
212  * may be the same as @dst but this is irrelevant.)
213  *
214  * On error, return -errno. Both runlists are left unmodified.
215  */
216 static inline struct runlist_element *ntfs_rl_append(struct runlist_element *dst,
217 		int dsize, struct runlist_element *src, int ssize, int loc,
218 		size_t *new_size)
219 {
220 	bool right = false;	/* Right end of @src needs merging. */
221 	int marker;		/* End of the inserted runs. */
222 
223 	/* First, check if the right hand end needs merging. */
224 	if ((loc + 1) < dsize)
225 		right = ntfs_are_rl_mergeable(src + ssize - 1, dst + loc + 1);
226 
227 	/* Space required: @dst size + @src size, less one if we merged. */
228 	dst = ntfs_rl_realloc(dst, dsize, dsize + ssize - right);
229 	if (IS_ERR(dst))
230 		return dst;
231 
232 	*new_size = dsize + ssize - right;
233 	/*
234 	 * We are guaranteed to succeed from here so can start modifying the
235 	 * original runlists.
236 	 */
237 
238 	/* First, merge the right hand end, if necessary. */
239 	if (right)
240 		__ntfs_rl_merge(src + ssize - 1, dst + loc + 1);
241 
242 	/* First run after the @src runs that have been inserted. */
243 	marker = loc + ssize + 1;
244 
245 	/* Move the tail of @dst out of the way, then copy in @src. */
246 	ntfs_rl_mm(dst, marker, loc + 1 + right, dsize - (loc + 1 + right));
247 	ntfs_rl_mc(dst, loc + 1, src, 0, ssize);
248 
249 	/* Adjust the size of the preceding hole. */
250 	dst[loc].length = dst[loc + 1].vcn - dst[loc].vcn;
251 
252 	/* We may have changed the length of the file, so fix the end marker */
253 	if (dst[marker].lcn == LCN_ENOENT)
254 		dst[marker].vcn = dst[marker - 1].vcn + dst[marker - 1].length;
255 
256 	return dst;
257 }
258 
259 /*
260  * ntfs_rl_insert - insert a runlist into another
261  * @dst: destination runlist to insert into
262  * @dsize: number of elements in @dst
263  * @src: source runlist to insert from
264  * @ssize: number of elements in @src
265  * @loc: index in @dst at which to insert @src
266  * @new_size: on success, set to the new combined size
267  *
268  * Insert the runlist @src before element @loc in the runlist @dst. Merge the
269  * left end of the new runlist, if necessary. Adjust the size of the hole
270  * after the inserted runlist.
271  *
272  * It is up to the caller to serialize access to the runlists @dst and @src.
273  *
274  * On success, return a pointer to the new, combined, runlist. Note, both
275  * runlists @dst and @src are deallocated before returning so you cannot use
276  * the pointers for anything any more. (Strictly speaking the returned runlist
277  * may be the same as @dst but this is irrelevant.)
278  *
279  * On error, return -errno. Both runlists are left unmodified.
280  */
281 static inline struct runlist_element *ntfs_rl_insert(struct runlist_element *dst,
282 		int dsize, struct runlist_element *src, int ssize, int loc,
283 		size_t *new_size)
284 {
285 	bool left = false;	/* Left end of @src needs merging. */
286 	bool disc = false;	/* Discontinuity between @dst and @src. */
287 	int marker;		/* End of the inserted runs. */
288 
289 	/*
290 	 * disc => Discontinuity between the end of @dst and the start of @src.
291 	 *	   This means we might need to insert a "not mapped" run.
292 	 */
293 	if (loc == 0)
294 		disc = (src[0].vcn > 0);
295 	else {
296 		s64 merged_length;
297 
298 		left = ntfs_are_rl_mergeable(dst + loc - 1, src);
299 
300 		merged_length = dst[loc - 1].length;
301 		if (left)
302 			merged_length += src->length;
303 
304 		disc = (src[0].vcn > dst[loc - 1].vcn + merged_length);
305 	}
306 	/*
307 	 * Space required: @dst size + @src size, less one if we merged, plus
308 	 * one if there was a discontinuity.
309 	 */
310 	dst = ntfs_rl_realloc(dst, dsize, dsize + ssize - left + disc);
311 	if (IS_ERR(dst))
312 		return dst;
313 
314 	*new_size = dsize + ssize - left + disc;
315 	/*
316 	 * We are guaranteed to succeed from here so can start modifying the
317 	 * original runlist.
318 	 */
319 	if (left)
320 		__ntfs_rl_merge(dst + loc - 1, src);
321 	/*
322 	 * First run after the @src runs that have been inserted.
323 	 * Nominally,  @marker equals @loc + @ssize, i.e. location + number of
324 	 * runs in @src.  However, if @left, then the first run in @src has
325 	 * been merged with one in @dst.  And if @disc, then @dst and @src do
326 	 * not meet and we need an extra run to fill the gap.
327 	 */
328 	marker = loc + ssize - left + disc;
329 
330 	/* Move the tail of @dst out of the way, then copy in @src. */
331 	ntfs_rl_mm(dst, marker, loc, dsize - loc);
332 	ntfs_rl_mc(dst, loc + disc, src, left, ssize - left);
333 
334 	/* Adjust the VCN of the first run after the insertion... */
335 	dst[marker].vcn = dst[marker - 1].vcn + dst[marker - 1].length;
336 	/* ... and the length. */
337 	if (dst[marker].lcn == LCN_HOLE || dst[marker].lcn == LCN_RL_NOT_MAPPED ||
338 	    dst[marker].lcn == LCN_DELALLOC)
339 		dst[marker].length = dst[marker + 1].vcn - dst[marker].vcn;
340 
341 	/* Writing beyond the end of the file and there is a discontinuity. */
342 	if (disc) {
343 		if (loc > 0) {
344 			dst[loc].vcn = dst[loc - 1].vcn + dst[loc - 1].length;
345 			dst[loc].length = dst[loc + 1].vcn - dst[loc].vcn;
346 		} else {
347 			dst[loc].vcn = 0;
348 			dst[loc].length = dst[loc + 1].vcn;
349 		}
350 		dst[loc].lcn = LCN_RL_NOT_MAPPED;
351 	}
352 	return dst;
353 }
354 
355 /*
356  * ntfs_rl_replace - overwrite a runlist element with another runlist
357  * @dst: destination runlist to replace in
358  * @dsize: number of elements in @dst
359  * @src: source runlist to replace with
360  * @ssize: number of elements in @src
361  * @loc: index in @dst to replace
362  * @new_size: on success, set to the new combined size
363  *
364  * Replace the runlist element @dst at @loc with @src. Merge the left and
365  * right ends of the inserted runlist, if necessary.
366  *
367  * It is up to the caller to serialize access to the runlists @dst and @src.
368  *
369  * On success, return a pointer to the new, combined, runlist. Note, both
370  * runlists @dst and @src are deallocated before returning so you cannot use
371  * the pointers for anything any more. (Strictly speaking the returned runlist
372  * may be the same as @dst but this is irrelevant.)
373  *
374  * On error, return -errno. Both runlists are left unmodified.
375  */
376 static inline struct runlist_element *ntfs_rl_replace(struct runlist_element *dst,
377 		int dsize, struct runlist_element *src, int ssize, int loc,
378 		size_t *new_size)
379 {
380 	int delta;
381 	bool left = false;	/* Left end of @src needs merging. */
382 	bool right = false;	/* Right end of @src needs merging. */
383 	int tail;		/* Start of tail of @dst. */
384 	int marker;		/* End of the inserted runs. */
385 
386 	/* First, see if the left and right ends need merging. */
387 	if ((loc + 1) < dsize)
388 		right = ntfs_are_rl_mergeable(src + ssize - 1, dst + loc + 1);
389 	if (loc > 0)
390 		left = ntfs_are_rl_mergeable(dst + loc - 1, src);
391 	/*
392 	 * Allocate some space.  We will need less if the left, right, or both
393 	 * ends get merged.  The -1 accounts for the run being replaced.
394 	 */
395 	delta = ssize - 1 - left - right;
396 	if (delta > 0) {
397 		dst = ntfs_rl_realloc(dst, dsize, dsize + delta);
398 		if (IS_ERR(dst))
399 			return dst;
400 	}
401 
402 	*new_size = dsize + delta;
403 	/*
404 	 * We are guaranteed to succeed from here so can start modifying the
405 	 * original runlists.
406 	 */
407 
408 	/* First, merge the left and right ends, if necessary. */
409 	if (right)
410 		__ntfs_rl_merge(src + ssize - 1, dst + loc + 1);
411 	if (left)
412 		__ntfs_rl_merge(dst + loc - 1, src);
413 	/*
414 	 * Offset of the tail of @dst.  This needs to be moved out of the way
415 	 * to make space for the runs to be copied from @src, i.e. the first
416 	 * run of the tail of @dst.
417 	 * Nominally, @tail equals @loc + 1, i.e. location, skipping the
418 	 * replaced run.  However, if @right, then one of @dst's runs is
419 	 * already merged into @src.
420 	 */
421 	tail = loc + right + 1;
422 	/*
423 	 * First run after the @src runs that have been inserted, i.e. where
424 	 * the tail of @dst needs to be moved to.
425 	 * Nominally, @marker equals @loc + @ssize, i.e. location + number of
426 	 * runs in @src.  However, if @left, then the first run in @src has
427 	 * been merged with one in @dst.
428 	 */
429 	marker = loc + ssize - left;
430 
431 	/* Move the tail of @dst out of the way, then copy in @src. */
432 	ntfs_rl_mm(dst, marker, tail, dsize - tail);
433 	ntfs_rl_mc(dst, loc, src, left, ssize - left);
434 
435 	/* We may have changed the length of the file, so fix the end marker. */
436 	if (dsize - tail > 0 && dst[marker].lcn == LCN_ENOENT)
437 		dst[marker].vcn = dst[marker - 1].vcn + dst[marker - 1].length;
438 	return dst;
439 }
440 
441 /*
442  * ntfs_rl_split - insert a runlist into the centre of a hole
443  * @dst: destination runlist with a hole
444  * @dsize: number of elements in @dst
445  * @src: source runlist to insert
446  * @ssize: number of elements in @src
447  * @loc: index in @dst of the hole to split
448  * @new_size: on success, set to the new combined size
449  *
450  * Split the runlist @dst at @loc into two and insert @new in between the two
451  * fragments. No merging of runlists is necessary. Adjust the size of the
452  * holes either side.
453  *
454  * It is up to the caller to serialize access to the runlists @dst and @src.
455  *
456  * On success, return a pointer to the new, combined, runlist. Note, both
457  * runlists @dst and @src 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.)
460  *
461  * On error, return -errno. Both runlists are left unmodified.
462  */
463 static inline struct runlist_element *ntfs_rl_split(struct runlist_element *dst, int dsize,
464 		struct runlist_element *src, int ssize, int loc,
465 		size_t *new_size)
466 {
467 	/* Space required: @dst size + @src size + one new hole. */
468 	dst = ntfs_rl_realloc(dst, dsize, dsize + ssize + 1);
469 	if (IS_ERR(dst))
470 		return dst;
471 
472 	*new_size = dsize + ssize + 1;
473 	/*
474 	 * We are guaranteed to succeed from here so can start modifying the
475 	 * original runlists.
476 	 */
477 
478 	/* Move the tail of @dst out of the way, then copy in @src. */
479 	ntfs_rl_mm(dst, loc + 1 + ssize, loc, dsize - loc);
480 	ntfs_rl_mc(dst, loc + 1, src, 0, ssize);
481 
482 	/* Adjust the size of the holes either size of @src. */
483 	dst[loc].length		= dst[loc+1].vcn       - dst[loc].vcn;
484 	dst[loc+ssize+1].vcn    = dst[loc+ssize].vcn   + dst[loc+ssize].length;
485 	dst[loc+ssize+1].length = dst[loc+ssize+2].vcn - dst[loc+ssize+1].vcn;
486 
487 	return dst;
488 }
489 
490 /*
491  * ntfs_runlists_merge - merge two runlists into one
492  * @d_runlist: destination runlist structure to merge into
493  * @srl: source runlist to merge from
494  * @s_rl_count: number of elements in @srl (0 to auto-detect)
495  * @new_rl_count: on success, set to the new combined runlist size
496  *
497  * First we sanity check the two runlists @srl and @drl to make sure that they
498  * are sensible and can be merged. The runlist @srl must be either after the
499  * runlist @drl or completely within a hole (or unmapped region) in @drl.
500  *
501  * It is up to the caller to serialize access to the runlists @drl and @srl.
502  *
503  * Merging of runlists is necessary in two cases:
504  *   1. When attribute lists are used and a further extent is being mapped.
505  *   2. When new clusters are allocated to fill a hole or extend a file.
506  *
507  * There are four possible ways @srl can be merged. It can:
508  *	- be inserted at the beginning of a hole,
509  *	- split the hole in two and be inserted between the two fragments,
510  *	- be appended at the end of a hole, or it can
511  *	- replace the whole hole.
512  * It can also be appended to the end of the runlist, which is just a variant
513  * of the insert case.
514  *
515  * On success, return a pointer to the new, combined, runlist. Note, both
516  * runlists @drl and @srl are deallocated before returning so you cannot use
517  * the pointers for anything any more. (Strictly speaking the returned runlist
518  * may be the same as @dst but this is irrelevant.)
519  *
520  * On error, return -errno. Both runlists are left unmodified.
521  */
522 struct runlist_element *ntfs_runlists_merge(struct runlist *d_runlist,
523 				     struct runlist_element *srl, size_t s_rl_count,
524 				     size_t *new_rl_count)
525 {
526 	int di, si;		/* Current index into @[ds]rl. */
527 	int sstart;		/* First index with lcn > LCN_RL_NOT_MAPPED. */
528 	int dins;		/* Index into @drl at which to insert @srl. */
529 	int dend, send;		/* Last index into @[ds]rl. */
530 	int dfinal, sfinal;	/* The last index into @[ds]rl with lcn >= LCN_HOLE. */
531 	int marker = 0;
532 	s64 marker_vcn = 0;
533 	struct runlist_element *drl = d_runlist->rl, *rl;
534 
535 #ifdef DEBUG
536 	ntfs_debug("dst:");
537 	ntfs_debug_dump_runlist(drl);
538 	ntfs_debug("src:");
539 	ntfs_debug_dump_runlist(srl);
540 #endif
541 
542 	/* Check for silly calling... */
543 	if (unlikely(!srl))
544 		return drl;
545 	if (IS_ERR(srl) || IS_ERR(drl))
546 		return ERR_PTR(-EINVAL);
547 
548 	if (s_rl_count == 0) {
549 		for (; srl[s_rl_count].length; s_rl_count++)
550 			;
551 		s_rl_count++;
552 	}
553 
554 	/* Check for the case where the first mapping is being done now. */
555 	if (unlikely(!drl)) {
556 		drl = srl;
557 		/* Complete the source runlist if necessary. */
558 		if (unlikely(drl[0].vcn)) {
559 			/* Scan to the end of the source runlist. */
560 			drl = ntfs_rl_realloc(drl, s_rl_count, s_rl_count + 1);
561 			if (IS_ERR(drl))
562 				return drl;
563 			/* Insert start element at the front of the runlist. */
564 			ntfs_rl_mm(drl, 1, 0, s_rl_count);
565 			drl[0].vcn = 0;
566 			drl[0].lcn = LCN_RL_NOT_MAPPED;
567 			drl[0].length = drl[1].vcn;
568 			s_rl_count++;
569 		}
570 
571 		*new_rl_count = s_rl_count;
572 		goto finished;
573 	}
574 
575 	if (d_runlist->count < 1 || s_rl_count < 2)
576 		return ERR_PTR(-EINVAL);
577 
578 	si = di = 0;
579 
580 	/* Skip any unmapped start element(s) in the source runlist. */
581 	while (srl[si].length && srl[si].lcn < LCN_HOLE)
582 		si++;
583 
584 	/* Can't have an entirely unmapped source runlist. */
585 	WARN_ON(!srl[si].length);
586 
587 	/* Record the starting points. */
588 	sstart = si;
589 
590 	/*
591 	 * Skip forward in @drl until we reach the position where @srl needs to
592 	 * be inserted. If we reach the end of @drl, @srl just needs to be
593 	 * appended to @drl.
594 	 */
595 	rl = __ntfs_attr_find_vcn_nolock(d_runlist, srl[sstart].vcn);
596 	if (IS_ERR(rl))
597 		di = (int)d_runlist->count - 1;
598 	else
599 		di = (int)(rl - d_runlist->rl);
600 	dins = di;
601 
602 	/* Sanity check for illegal overlaps. */
603 	if ((drl[di].vcn == srl[si].vcn) && (drl[di].lcn >= 0) &&
604 			(srl[si].lcn >= 0)) {
605 		ntfs_error(NULL, "Run lists overlap. Cannot merge!");
606 		return ERR_PTR(-ERANGE);
607 	}
608 
609 	/* Scan to the end of both runlists in order to know their sizes. */
610 	send = (int)s_rl_count - 1;
611 	dend = (int)d_runlist->count - 1;
612 
613 	if (srl[send].lcn == LCN_ENOENT)
614 		marker_vcn = srl[marker = send].vcn;
615 
616 	/* Scan to the last element with lcn >= LCN_HOLE. */
617 	for (sfinal = send; sfinal >= 0 && srl[sfinal].lcn < LCN_HOLE; sfinal--)
618 		;
619 	for (dfinal = dend; dfinal >= 0 && drl[dfinal].lcn < LCN_HOLE; dfinal--)
620 		;
621 
622 	{
623 	bool start;
624 	bool finish;
625 	int ds = dend + 1;		/* Number of elements in drl & srl */
626 	int ss = sfinal - sstart + 1;
627 
628 	start  = ((drl[dins].lcn <  LCN_RL_NOT_MAPPED) ||    /* End of file   */
629 		  (drl[dins].vcn == srl[sstart].vcn));	     /* Start of hole */
630 	finish = ((drl[dins].lcn >= LCN_RL_NOT_MAPPED) &&    /* End of file   */
631 		 ((drl[dins].vcn + drl[dins].length) <=      /* End of hole   */
632 		  (srl[send - 1].vcn + srl[send - 1].length)));
633 
634 	/* Or we will lose an end marker. */
635 	if (finish && !drl[dins].length)
636 		ss++;
637 	if (marker && (drl[dins].vcn + drl[dins].length > srl[send - 1].vcn))
638 		finish = false;
639 
640 	if (start) {
641 		if (finish)
642 			drl = ntfs_rl_replace(drl, ds, srl + sstart, ss, dins, new_rl_count);
643 		else
644 			drl = ntfs_rl_insert(drl, ds, srl + sstart, ss, dins, new_rl_count);
645 	} else {
646 		if (finish)
647 			drl = ntfs_rl_append(drl, ds, srl + sstart, ss, dins, new_rl_count);
648 		else
649 			drl = ntfs_rl_split(drl, ds, srl + sstart, ss, dins, new_rl_count);
650 	}
651 	if (IS_ERR(drl)) {
652 		ntfs_error(NULL, "Merge failed.");
653 		return drl;
654 	}
655 	kvfree(srl);
656 	if (marker) {
657 		ntfs_debug("Triggering marker code.");
658 		for (ds = dend; drl[ds].length; ds++)
659 			;
660 		/* We only need to care if @srl ended after @drl. */
661 		if (drl[ds].vcn <= marker_vcn) {
662 			int slots = 0;
663 
664 			if (drl[ds].vcn == marker_vcn) {
665 				ntfs_debug("Old marker = 0x%llx, replacing with LCN_ENOENT.",
666 						drl[ds].lcn);
667 				drl[ds].lcn = LCN_ENOENT;
668 				goto finished;
669 			}
670 			/*
671 			 * We need to create an unmapped runlist element in
672 			 * @drl or extend an existing one before adding the
673 			 * ENOENT terminator.
674 			 */
675 			if (drl[ds].lcn == LCN_ENOENT) {
676 				ds--;
677 				slots = 1;
678 			}
679 			if (drl[ds].lcn != LCN_RL_NOT_MAPPED) {
680 				/* Add an unmapped runlist element. */
681 				if (!slots) {
682 					drl = ntfs_rl_realloc_nofail(drl, ds,
683 							ds + 2);
684 					slots = 2;
685 					*new_rl_count += 2;
686 				}
687 				ds++;
688 				/* Need to set vcn if it isn't set already. */
689 				if (slots != 1)
690 					drl[ds].vcn = drl[ds - 1].vcn +
691 							drl[ds - 1].length;
692 				drl[ds].lcn = LCN_RL_NOT_MAPPED;
693 				/* We now used up a slot. */
694 				slots--;
695 			}
696 			drl[ds].length = marker_vcn - drl[ds].vcn;
697 			/* Finally add the ENOENT terminator. */
698 			ds++;
699 			if (!slots) {
700 				drl = ntfs_rl_realloc_nofail(drl, ds, ds + 1);
701 				*new_rl_count += 1;
702 			}
703 			drl[ds].vcn = marker_vcn;
704 			drl[ds].lcn = LCN_ENOENT;
705 			drl[ds].length = (s64)0;
706 		}
707 	}
708 	}
709 
710 finished:
711 	/* The merge was completed successfully. */
712 	ntfs_debug("Merged runlist:");
713 	ntfs_debug_dump_runlist(drl);
714 	return drl;
715 }
716 
717 /*
718  * ntfs_mapping_pairs_decompress - convert mapping pairs array to runlist
719  * @vol: ntfs volume
720  * @attr: attribute record whose mapping pairs to decompress
721  * @old_runlist: optional runlist to merge the decompressed runlist into
722  * @new_rl_count: on success, set to the new runlist size
723  *
724  * It is up to the caller to serialize access to the runlist @old_rl.
725  *
726  * Decompress the attribute @attr's mapping pairs array into a runlist. On
727  * success, return the decompressed runlist.
728  *
729  * If @old_rl is not NULL, decompressed runlist is inserted into the
730  * appropriate place in @old_rl and the resultant, combined runlist is
731  * returned. The original @old_rl is deallocated.
732  *
733  * On error, return -errno. @old_rl is left unmodified in that case.
734  */
735 struct runlist_element *ntfs_mapping_pairs_decompress(const struct ntfs_volume *vol,
736 		const struct attr_record *attr, struct runlist *old_runlist,
737 		size_t *new_rl_count)
738 {
739 	s64 vcn;		/* Current vcn. */
740 	s64 lcn;		/* Current lcn. */
741 	s64 deltaxcn;		/* Change in [vl]cn. */
742 	struct runlist_element *rl, *new_rl;	/* The output runlist. */
743 	u8 *buf;		/* Current position in mapping pairs array. */
744 	u8 *attr_end;		/* End of attribute. */
745 	int rlsize;		/* Size of runlist buffer. */
746 	u16 rlpos;		/* Current runlist position in units of struct runlist_elements. */
747 	u8 b;			/* Current byte offset in buf. */
748 	u64 lowest_vcn;		/* Raw on-disk lowest_vcn. */
749 
750 #ifdef DEBUG
751 	/* Make sure attr exists and is non-resident. */
752 	if (!attr || !attr->non_resident) {
753 		ntfs_error(vol->sb, "Invalid arguments.");
754 		return ERR_PTR(-EINVAL);
755 	}
756 #endif
757 	lowest_vcn = le64_to_cpu(attr->data.non_resident.lowest_vcn);
758 	/* Validate lowest_vcn from on-disk metadata to ensure it is sane. */
759 	if (overflows_type(lowest_vcn, vcn)) {
760 		ntfs_error(vol->sb, "Invalid lowest_vcn in mapping pairs.");
761 		return ERR_PTR(-EIO);
762 	}
763 	/* Start at vcn = lowest_vcn and lcn 0. */
764 	vcn = lowest_vcn;
765 	lcn = 0;
766 	/* Get start of the mapping pairs array. */
767 	buf = (u8 *)attr +
768 		le16_to_cpu(attr->data.non_resident.mapping_pairs_offset);
769 	attr_end = (u8 *)attr + le32_to_cpu(attr->length);
770 	if (unlikely(buf < (u8 *)attr || buf >= attr_end)) {
771 		ntfs_error(vol->sb, "Corrupt attribute.");
772 		return ERR_PTR(-EIO);
773 	}
774 
775 	/* Current position in runlist array. */
776 	rlpos = 0;
777 	/* Allocate first page and set current runlist size to one page. */
778 	rl = kvzalloc(rlsize = PAGE_SIZE, GFP_NOFS);
779 	if (unlikely(!rl))
780 		return ERR_PTR(-ENOMEM);
781 	/* Insert unmapped starting element if necessary. */
782 	if (vcn) {
783 		rl->vcn = 0;
784 		rl->lcn = LCN_RL_NOT_MAPPED;
785 		rl->length = vcn;
786 		rlpos++;
787 	}
788 	while (buf < attr_end && *buf) {
789 		/*
790 		 * Allocate more memory if needed, including space for the
791 		 * not-mapped and terminator elements. kvzalloc()
792 		 * operates on whole pages only.
793 		 */
794 		if (((rlpos + 3) * sizeof(*rl)) > rlsize) {
795 			struct runlist_element *rl2;
796 
797 			rl2 = kvzalloc(rlsize + PAGE_SIZE, GFP_NOFS);
798 			if (unlikely(!rl2)) {
799 				kvfree(rl);
800 				return ERR_PTR(-ENOMEM);
801 			}
802 			memcpy(rl2, rl, rlsize);
803 			kvfree(rl);
804 			rl = rl2;
805 			rlsize += PAGE_SIZE;
806 		}
807 		/* Enter the current vcn into the current runlist element. */
808 		rl[rlpos].vcn = vcn;
809 		/*
810 		 * Get the change in vcn, i.e. the run length in clusters.
811 		 * Doing it this way ensures that we signextend negative values.
812 		 * A negative run length doesn't make any sense, but hey, I
813 		 * didn't make up the NTFS specs and Windows NT4 treats the run
814 		 * length as a signed value so that's how it is...
815 		 */
816 		b = *buf & 0xf;
817 		if (b) {
818 			if (unlikely(buf + b >= attr_end))
819 				goto io_error;
820 			for (deltaxcn = (s8)buf[b--]; b; b--)
821 				deltaxcn = (deltaxcn << 8) + buf[b];
822 		} else { /* The length entry is compulsory. */
823 			ntfs_error(vol->sb, "Missing length entry in mapping pairs array.");
824 			deltaxcn = (s64)-1;
825 		}
826 		/*
827 		 * Assume a negative length to indicate data corruption and
828 		 * hence clean-up and return NULL.
829 		 */
830 		if (unlikely(deltaxcn < 0)) {
831 			ntfs_error(vol->sb, "Invalid length in mapping pairs array.");
832 			goto err_out;
833 		}
834 		/*
835 		 * Enter the current run length into the current runlist
836 		 * element.
837 		 */
838 		rl[rlpos].length = deltaxcn;
839 		/*
840 		 * Increment the current vcn by the current run length.
841 		 * Guard against s64 overflow from a crafted mapping
842 		 * pairs array to preserve the monotonically-increasing
843 		 * vcn invariant.
844 		 */
845 		if (unlikely(check_add_overflow(vcn, deltaxcn, &vcn))) {
846 			ntfs_error(vol->sb, "VCN overflow in mapping pairs array.");
847 			goto err_out;
848 		}
849 
850 		/*
851 		 * There might be no lcn change at all, as is the case for
852 		 * sparse clusters on NTFS 3.0+, in which case we set the lcn
853 		 * to LCN_HOLE.
854 		 */
855 		if (!(*buf & 0xf0))
856 			rl[rlpos].lcn = LCN_HOLE;
857 		else {
858 			/* Get the lcn change which really can be negative. */
859 			u8 b2 = *buf & 0xf;
860 
861 			b = b2 + ((*buf >> 4) & 0xf);
862 			if (buf + b >= attr_end)
863 				goto io_error;
864 			for (deltaxcn = (s8)buf[b--]; b > b2; b--)
865 				deltaxcn = (deltaxcn << 8) + buf[b];
866 			/* Change the current lcn to its new value. */
867 			if (unlikely(check_add_overflow(lcn, deltaxcn, &lcn))) {
868 				ntfs_error(vol->sb,
869 						"LCN overflow in mapping pairs array.");
870 				goto err_out;
871 			}
872 #ifdef DEBUG
873 			/*
874 			 * On NTFS 1.2-, apparently can have lcn == -1 to
875 			 * indicate a hole. But we haven't verified ourselves
876 			 * whether it is really the lcn or the deltaxcn that is
877 			 * -1. So if either is found give us a message so we
878 			 * can investigate it further!
879 			 */
880 			if (vol->major_ver < 3) {
881 				if (unlikely(deltaxcn == -1))
882 					ntfs_error(vol->sb, "lcn delta == -1");
883 				if (unlikely(lcn == -1))
884 					ntfs_error(vol->sb, "lcn == -1");
885 			}
886 #endif
887 			/* Check lcn is not below -1. */
888 			if (unlikely(lcn < -1)) {
889 				ntfs_error(vol->sb, "Invalid s64 < -1 in mapping pairs array.");
890 				goto err_out;
891 			}
892 
893 			/* chkdsk accepts zero-sized runs only for holes */
894 			if ((lcn != -1) && !rl[rlpos].length) {
895 				ntfs_error(vol->sb,
896 					   "Invalid zero-sized data run(lcn : %lld).\n",
897 					   lcn);
898 				goto err_out;
899 			}
900 
901 			/* Enter the current lcn into the runlist element. */
902 			rl[rlpos].lcn = lcn;
903 		}
904 		/* Get to the next runlist element, skipping zero-sized holes */
905 		if (rl[rlpos].length)
906 			rlpos++;
907 		/* Increment the buffer position to the next mapping pair. */
908 		buf += (*buf & 0xf) + ((*buf >> 4) & 0xf) + 1;
909 	}
910 	if (unlikely(buf >= attr_end))
911 		goto io_error;
912 	/*
913 	 * If there is a highest_vcn specified, it must be equal to the final
914 	 * vcn in the runlist - 1, or something has gone badly wrong.
915 	 */
916 	deltaxcn = le64_to_cpu(attr->data.non_resident.highest_vcn);
917 	if (unlikely(deltaxcn && vcn - 1 != deltaxcn)) {
918 mpa_err:
919 		ntfs_error(vol->sb, "Corrupt mapping pairs array in non-resident attribute.");
920 		goto err_out;
921 	}
922 	/* Setup not mapped runlist element if this is the base extent. */
923 	if (!attr->data.non_resident.lowest_vcn) {
924 		s64 max_cluster;
925 
926 		max_cluster = ((le64_to_cpu(attr->data.non_resident.allocated_size) +
927 				vol->cluster_size - 1) >>
928 				vol->cluster_size_bits) - 1;
929 		/*
930 		 * A highest_vcn of zero means this is a single extent
931 		 * attribute so simply terminate the runlist with LCN_ENOENT).
932 		 */
933 		if (deltaxcn) {
934 			/*
935 			 * If there is a difference between the highest_vcn and
936 			 * the highest cluster, the runlist is either corrupt
937 			 * or, more likely, there are more extents following
938 			 * this one.
939 			 */
940 			if (deltaxcn < max_cluster) {
941 				ntfs_debug("More extents to follow; deltaxcn = 0x%llx, max_cluster = 0x%llx",
942 						deltaxcn, max_cluster);
943 				rl[rlpos].vcn = vcn;
944 				vcn += rl[rlpos].length = max_cluster -
945 						deltaxcn;
946 				rl[rlpos].lcn = LCN_RL_NOT_MAPPED;
947 				rlpos++;
948 			} else if (unlikely(deltaxcn > max_cluster)) {
949 				ntfs_error(vol->sb,
950 					   "Corrupt attribute. deltaxcn = 0x%llx, max_cluster = 0x%llx",
951 					   deltaxcn, max_cluster);
952 				goto mpa_err;
953 			}
954 		}
955 		rl[rlpos].lcn = LCN_ENOENT;
956 	} else /* Not the base extent. There may be more extents to follow. */
957 		rl[rlpos].lcn = LCN_RL_NOT_MAPPED;
958 
959 	/* Setup terminating runlist element. */
960 	rl[rlpos].vcn = vcn;
961 	rl[rlpos].length = (s64)0;
962 	/* If no existing runlist was specified, we are done. */
963 	if (!old_runlist || !old_runlist->rl) {
964 		*new_rl_count = rlpos + 1;
965 		ntfs_debug("Mapping pairs array successfully decompressed:");
966 		ntfs_debug_dump_runlist(rl);
967 		return rl;
968 	}
969 	/* Now combine the new and old runlists checking for overlaps. */
970 	new_rl = ntfs_runlists_merge(old_runlist, rl, rlpos + 1, new_rl_count);
971 	if (!IS_ERR(new_rl))
972 		return new_rl;
973 	kvfree(rl);
974 	ntfs_error(vol->sb, "Failed to merge runlists.");
975 	return new_rl;
976 io_error:
977 	ntfs_error(vol->sb, "Corrupt attribute.");
978 err_out:
979 	kvfree(rl);
980 	return ERR_PTR(-EIO);
981 }
982 
983 /*
984  * ntfs_rl_vcn_to_lcn - convert a vcn into a lcn given a runlist
985  * @rl:		runlist to use for conversion
986  * @vcn:	vcn to convert
987  *
988  * Convert the virtual cluster number @vcn of an attribute into a logical
989  * cluster number (lcn) of a device using the runlist @rl to map vcns to their
990  * corresponding lcns.
991  *
992  * It is up to the caller to serialize access to the runlist @rl.
993  *
994  * Since lcns must be >= 0, we use negative return codes with special meaning:
995  *
996  * Return code		Meaning / Description
997  * ==================================================
998  *  LCN_HOLE		Hole / not allocated on disk.
999  *  LCN_RL_NOT_MAPPED	This is part of the runlist which has not been
1000  *			inserted into the runlist yet.
1001  *  LCN_ENOENT		There is no such vcn in the attribute.
1002  *
1003  * Locking: - The caller must have locked the runlist (for reading or writing).
1004  *	    - This function does not touch the lock, nor does it modify the
1005  *	      runlist.
1006  */
1007 s64 ntfs_rl_vcn_to_lcn(const struct runlist_element *rl, const s64 vcn)
1008 {
1009 	int i;
1010 
1011 	/*
1012 	 * If rl is NULL, assume that we have found an unmapped runlist. The
1013 	 * caller can then attempt to map it and fail appropriately if
1014 	 * necessary.
1015 	 */
1016 	if (unlikely(!rl))
1017 		return LCN_RL_NOT_MAPPED;
1018 
1019 	/* Catch out of lower bounds vcn. */
1020 	if (unlikely(vcn < rl[0].vcn))
1021 		return LCN_ENOENT;
1022 
1023 	for (i = 0; likely(rl[i].length); i++) {
1024 		if (vcn < rl[i+1].vcn) {
1025 			if (likely(rl[i].lcn >= 0))
1026 				return rl[i].lcn + (vcn - rl[i].vcn);
1027 			return rl[i].lcn;
1028 		}
1029 	}
1030 	/*
1031 	 * The terminator element is setup to the correct value, i.e. one of
1032 	 * LCN_HOLE, LCN_RL_NOT_MAPPED, or LCN_ENOENT.
1033 	 */
1034 	if (likely(rl[i].lcn < 0))
1035 		return rl[i].lcn;
1036 	/* Just in case... We could replace this with BUG() some day. */
1037 	return LCN_ENOENT;
1038 }
1039 
1040 /*
1041  * ntfs_rl_find_vcn_nolock - find a vcn in a runlist
1042  * @rl:		runlist to search
1043  * @vcn:	vcn to find
1044  *
1045  * Find the virtual cluster number @vcn in the runlist @rl and return the
1046  * address of the runlist element containing the @vcn on success.
1047  *
1048  * Return NULL if @rl is NULL or @vcn is in an unmapped part/out of bounds of
1049  * the runlist.
1050  *
1051  * Locking: The runlist must be locked on entry.
1052  */
1053 struct runlist_element *ntfs_rl_find_vcn_nolock(struct runlist_element *rl, const s64 vcn)
1054 {
1055 	if (unlikely(!rl || vcn < rl[0].vcn))
1056 		return NULL;
1057 	while (likely(rl->length)) {
1058 		if (unlikely(vcn < rl[1].vcn)) {
1059 			if (likely(rl->lcn >= LCN_HOLE))
1060 				return rl;
1061 			return NULL;
1062 		}
1063 		rl++;
1064 	}
1065 	if (likely(rl->lcn == LCN_ENOENT))
1066 		return rl;
1067 	return NULL;
1068 }
1069 
1070 /*
1071  * ntfs_get_nr_significant_bytes - get number of bytes needed to store a number
1072  * @n:		number for which to get the number of bytes for
1073  *
1074  * Return the number of bytes required to store @n unambiguously as
1075  * a signed number.
1076  *
1077  * This is used in the context of the mapping pairs array to determine how
1078  * many bytes will be needed in the array to store a given logical cluster
1079  * number (lcn) or a specific run length.
1080  *
1081  * Return the number of bytes written.  This function cannot fail.
1082  */
1083 static inline int ntfs_get_nr_significant_bytes(const s64 n)
1084 {
1085 	s64 l = n;
1086 	int i;
1087 	s8 j;
1088 
1089 	i = 0;
1090 	do {
1091 		l >>= 8;
1092 		i++;
1093 	} while (l != 0 && l != -1);
1094 	j = (n >> 8 * (i - 1)) & 0xff;
1095 	/* If the sign bit is wrong, we need an extra byte. */
1096 	if ((n < 0 && j >= 0) || (n > 0 && j < 0))
1097 		i++;
1098 	return i;
1099 }
1100 
1101 /*
1102  * ntfs_get_size_for_mapping_pairs - get bytes needed for mapping pairs array
1103  * @vol: ntfs volume
1104  * @rl: runlist to calculate the mapping pairs array size for
1105  * @first_vcn: first vcn which to include in the mapping pairs array
1106  * @last_vcn: last vcn which to include in the mapping pairs array
1107  * @max_mp_size: maximum size to return (0 or less means unlimited)
1108  *
1109  * Walk the locked runlist @rl and calculate the size in bytes of the mapping
1110  * pairs array corresponding to the runlist @rl, starting at vcn @first_vcn and
1111  * finishing with vcn @last_vcn.
1112  *
1113  * A @last_vcn of -1 means end of runlist and in that case the size of the
1114  * mapping pairs array corresponding to the runlist starting at vcn @first_vcn
1115  * and finishing at the end of the runlist is determined.
1116  *
1117  * This for example allows us to allocate a buffer of the right size when
1118  * building the mapping pairs array.
1119  *
1120  * If @rl is NULL, just return 1 (for the single terminator byte).
1121  *
1122  * Return the calculated size in bytes on success.  On error, return -errno.
1123  */
1124 int ntfs_get_size_for_mapping_pairs(const struct ntfs_volume *vol,
1125 		const struct runlist_element *rl, const s64 first_vcn,
1126 		const s64 last_vcn, int max_mp_size)
1127 {
1128 	s64 prev_lcn;
1129 	int rls;
1130 	bool the_end = false;
1131 
1132 	if (first_vcn < 0 || last_vcn < -1)
1133 		return -EINVAL;
1134 
1135 	if (last_vcn >= 0 && first_vcn > last_vcn)
1136 		return -EINVAL;
1137 
1138 	if (!rl) {
1139 		WARN_ON(first_vcn);
1140 		WARN_ON(last_vcn > 0);
1141 		return 1;
1142 	}
1143 	if (max_mp_size <= 0)
1144 		max_mp_size = INT_MAX;
1145 	/* Skip to runlist element containing @first_vcn. */
1146 	while (rl->length && first_vcn >= rl[1].vcn)
1147 		rl++;
1148 	if (unlikely((!rl->length && first_vcn > rl->vcn) ||
1149 			first_vcn < rl->vcn))
1150 		return -EINVAL;
1151 	prev_lcn = 0;
1152 	/* Always need the termining zero byte. */
1153 	rls = 1;
1154 	/* Do the first partial run if present. */
1155 	if (first_vcn > rl->vcn) {
1156 		s64 delta, length = rl->length;
1157 
1158 		/* We know rl->length != 0 already. */
1159 		if (unlikely(length < 0 || rl->lcn < LCN_HOLE))
1160 			goto err_out;
1161 		/*
1162 		 * If @stop_vcn is given and finishes inside this run, cap the
1163 		 * run length.
1164 		 */
1165 		if (unlikely(last_vcn >= 0 && rl[1].vcn > last_vcn)) {
1166 			s64 s1 = last_vcn + 1;
1167 
1168 			if (unlikely(rl[1].vcn > s1))
1169 				length = s1 - rl->vcn;
1170 			the_end = true;
1171 		}
1172 		delta = first_vcn - rl->vcn;
1173 		/* Header byte + length. */
1174 		rls += 1 + ntfs_get_nr_significant_bytes(length - delta);
1175 		/*
1176 		 * If the logical cluster number (lcn) denotes a hole and we
1177 		 * are on NTFS 3.0+, we don't store it at all, i.e. we need
1178 		 * zero space.  On earlier NTFS versions we just store the lcn.
1179 		 * Note: this assumes that on NTFS 1.2-, holes are stored with
1180 		 * an lcn of -1 and not a delta_lcn of -1 (unless both are -1).
1181 		 */
1182 		if (likely(rl->lcn >= 0 || vol->major_ver < 3)) {
1183 			prev_lcn = rl->lcn;
1184 			if (likely(rl->lcn >= 0))
1185 				prev_lcn += delta;
1186 			/* Change in lcn. */
1187 			rls += ntfs_get_nr_significant_bytes(prev_lcn);
1188 		}
1189 		/* Go to next runlist element. */
1190 		rl++;
1191 	}
1192 	/* Do the full runs. */
1193 	for (; rl->length && !the_end; rl++) {
1194 		s64 length = rl->length;
1195 
1196 		if (unlikely(length < 0 || rl->lcn < LCN_HOLE))
1197 			goto err_out;
1198 		/*
1199 		 * If @stop_vcn is given and finishes inside this run, cap the
1200 		 * run length.
1201 		 */
1202 		if (unlikely(last_vcn >= 0 && rl[1].vcn > last_vcn)) {
1203 			s64 s1 = last_vcn + 1;
1204 
1205 			if (unlikely(rl[1].vcn > s1))
1206 				length = s1 - rl->vcn;
1207 			the_end = true;
1208 		}
1209 		/* Header byte + length. */
1210 		rls += 1 + ntfs_get_nr_significant_bytes(length);
1211 		/*
1212 		 * If the logical cluster number (lcn) denotes a hole and we
1213 		 * are on NTFS 3.0+, we don't store it at all, i.e. we need
1214 		 * zero space.  On earlier NTFS versions we just store the lcn.
1215 		 * Note: this assumes that on NTFS 1.2-, holes are stored with
1216 		 * an lcn of -1 and not a delta_lcn of -1 (unless both are -1).
1217 		 */
1218 		if (likely(rl->lcn >= 0 || vol->major_ver < 3)) {
1219 			/* Change in lcn. */
1220 			rls += ntfs_get_nr_significant_bytes(rl->lcn -
1221 					prev_lcn);
1222 			prev_lcn = rl->lcn;
1223 		}
1224 
1225 		if (rls > max_mp_size)
1226 			break;
1227 	}
1228 	return rls;
1229 err_out:
1230 	if (rl->lcn == LCN_RL_NOT_MAPPED)
1231 		rls = -EINVAL;
1232 	else
1233 		rls = -EIO;
1234 	return rls;
1235 }
1236 
1237 /*
1238  * ntfs_write_significant_bytes - write the significant bytes of a number
1239  * @dst:	destination buffer to write to
1240  * @dst_max:	pointer to last byte of destination buffer for bounds checking
1241  * @n:		number whose significant bytes to write
1242  *
1243  * Store in @dst, the minimum bytes of the number @n which are required to
1244  * identify @n unambiguously as a signed number, taking care not to exceed
1245  * @dest_max, the maximum position within @dst to which we are allowed to
1246  * write.
1247  *
1248  * This is used when building the mapping pairs array of a runlist to compress
1249  * a given logical cluster number (lcn) or a specific run length to the minimum
1250  * size possible.
1251  *
1252  * Return the number of bytes written on success.  On error, i.e. the
1253  * destination buffer @dst is too small, return -ENOSPC.
1254  */
1255 static inline int ntfs_write_significant_bytes(s8 *dst, const s8 *dst_max,
1256 		const s64 n)
1257 {
1258 	s64 l = n;
1259 	int i;
1260 	s8 j;
1261 
1262 	i = 0;
1263 	do {
1264 		if (unlikely(dst > dst_max))
1265 			goto err_out;
1266 		*dst++ = l & 0xffll;
1267 		l >>= 8;
1268 		i++;
1269 	} while (l != 0 && l != -1);
1270 	j = (n >> 8 * (i - 1)) & 0xff;
1271 	/* If the sign bit is wrong, we need an extra byte. */
1272 	if (n < 0 && j >= 0) {
1273 		if (unlikely(dst > dst_max))
1274 			goto err_out;
1275 		i++;
1276 		*dst = (s8)-1;
1277 	} else if (n > 0 && j < 0) {
1278 		if (unlikely(dst > dst_max))
1279 			goto err_out;
1280 		i++;
1281 		*dst = (s8)0;
1282 	}
1283 	return i;
1284 err_out:
1285 	return -ENOSPC;
1286 }
1287 
1288 /*
1289  * ntfs_mapping_pairs_build - build the mapping pairs array from a runlist
1290  * @vol: ntfs volume
1291  * @dst: destination buffer to build mapping pairs array into
1292  * @dst_len: size of @dst in bytes
1293  * @rl: runlist to build the mapping pairs array from
1294  * @first_vcn: first vcn which to include in the mapping pairs array
1295  * @last_vcn: last vcn which to include in the mapping pairs array
1296  * @stop_vcn: on return, set to the first vcn outside the destination buffer
1297  * @stop_rl: on return, set to the runlist element where encoding stopped
1298  * @de_cluster_count: on return, set to the number of clusters encoded
1299  *
1300  * Create the mapping pairs array from the locked runlist @rl, starting at vcn
1301  * @first_vcn and finishing with vcn @last_vcn and save the array in @dst.
1302  * @dst_len is the size of @dst in bytes and it should be at least equal to the
1303  * value obtained by calling ntfs_get_size_for_mapping_pairs().
1304  *
1305  * A @last_vcn of -1 means end of runlist and in that case the mapping pairs
1306  * array corresponding to the runlist starting at vcn @first_vcn and finishing
1307  * at the end of the runlist is created.
1308  *
1309  * If @rl is NULL, just write a single terminator byte to @dst.
1310  *
1311  * On success or -ENOSPC error, if @stop_vcn is not NULL, *@stop_vcn is set to
1312  * the first vcn outside the destination buffer.  Note that on error, @dst has
1313  * been filled with all the mapping pairs that will fit, thus it can be treated
1314  * as partial success, in that a new attribute extent needs to be created or
1315  * the next extent has to be used and the mapping pairs build has to be
1316  * continued with @first_vcn set to *@stop_vcn.
1317  *
1318  * Return 0 on success and -errno on error.  The following error codes are
1319  * defined:
1320  *	-EINVAL	- Run list contains unmapped elements.  Make sure to only pass
1321  *		  fully mapped runlists to this function.
1322  *	-EIO	- The runlist is corrupt.
1323  *	-ENOSPC	- The destination buffer is too small.
1324  *
1325  * Locking: @rl must be locked on entry (either for reading or writing), it
1326  *	    remains locked throughout, and is left locked upon return.
1327  */
1328 int ntfs_mapping_pairs_build(const struct ntfs_volume *vol, s8 *dst,
1329 		const int dst_len, const struct runlist_element *rl,
1330 		const s64 first_vcn, const s64 last_vcn, s64 *const stop_vcn,
1331 		struct runlist_element **stop_rl, unsigned int *de_cluster_count)
1332 {
1333 	s64 prev_lcn;
1334 	s8 *dst_max, *dst_next;
1335 	int err = -ENOSPC;
1336 	bool the_end = false;
1337 	s8 len_len, lcn_len;
1338 	unsigned int de_cnt = 0;
1339 
1340 	if (first_vcn < 0 || last_vcn < -1 || dst_len < 1)
1341 		return -EINVAL;
1342 	if (last_vcn >= 0 && first_vcn > last_vcn)
1343 		return -EINVAL;
1344 
1345 	if (!rl) {
1346 		WARN_ON(first_vcn || last_vcn > 0);
1347 		if (stop_vcn)
1348 			*stop_vcn = 0;
1349 		/* Terminator byte. */
1350 		*dst = 0;
1351 		return 0;
1352 	}
1353 	/* Skip to runlist element containing @first_vcn. */
1354 	while (rl->length && first_vcn >= rl[1].vcn)
1355 		rl++;
1356 	if (unlikely((!rl->length && first_vcn > rl->vcn) ||
1357 			first_vcn < rl->vcn))
1358 		return -EINVAL;
1359 	/*
1360 	 * @dst_max is used for bounds checking in
1361 	 * ntfs_write_significant_bytes().
1362 	 */
1363 	dst_max = dst + dst_len - 1;
1364 	prev_lcn = 0;
1365 	/* Do the first partial run if present. */
1366 	if (first_vcn > rl->vcn) {
1367 		s64 delta, length = rl->length;
1368 
1369 		/* We know rl->length != 0 already. */
1370 		if (unlikely(length < 0 || rl->lcn < LCN_HOLE))
1371 			goto err_out;
1372 		/*
1373 		 * If @stop_vcn is given and finishes inside this run, cap the
1374 		 * run length.
1375 		 */
1376 		if (unlikely(last_vcn >= 0 && rl[1].vcn > last_vcn)) {
1377 			s64 s1 = last_vcn + 1;
1378 
1379 			if (unlikely(rl[1].vcn > s1))
1380 				length = s1 - rl->vcn;
1381 			the_end = true;
1382 		}
1383 		delta = first_vcn - rl->vcn;
1384 		/* Write length. */
1385 		len_len = ntfs_write_significant_bytes(dst + 1, dst_max,
1386 				length - delta);
1387 		if (unlikely(len_len < 0))
1388 			goto size_err;
1389 		/*
1390 		 * If the logical cluster number (lcn) denotes a hole and we
1391 		 * are on NTFS 3.0+, we don't store it at all, i.e. we need
1392 		 * zero space.  On earlier NTFS versions we just write the lcn
1393 		 * change.
1394 		 */
1395 		if (likely(rl->lcn >= 0 || vol->major_ver < 3)) {
1396 			prev_lcn = rl->lcn;
1397 			if (likely(rl->lcn >= 0))
1398 				prev_lcn += delta;
1399 			/* Write change in lcn. */
1400 			lcn_len = ntfs_write_significant_bytes(dst + 1 +
1401 					len_len, dst_max, prev_lcn);
1402 			if (unlikely(lcn_len < 0))
1403 				goto size_err;
1404 		} else
1405 			lcn_len = 0;
1406 		dst_next = dst + len_len + lcn_len + 1;
1407 		if (unlikely(dst_next > dst_max))
1408 			goto size_err;
1409 		/* Update header byte. */
1410 		*dst = lcn_len << 4 | len_len;
1411 		/* Position at next mapping pairs array element. */
1412 		dst = dst_next;
1413 		/* Go to next runlist element. */
1414 		rl++;
1415 	}
1416 	/* Do the full runs. */
1417 	for (; rl->length && !the_end; rl++) {
1418 		s64 length = rl->length;
1419 
1420 		if (unlikely(length < 0 || rl->lcn < LCN_HOLE))
1421 			goto err_out;
1422 		/*
1423 		 * If @stop_vcn is given and finishes inside this run, cap the
1424 		 * run length.
1425 		 */
1426 		if (unlikely(last_vcn >= 0 && rl[1].vcn > last_vcn)) {
1427 			s64 s1 = last_vcn + 1;
1428 
1429 			if (unlikely(rl[1].vcn > s1))
1430 				length = s1 - rl->vcn;
1431 			the_end = true;
1432 		}
1433 		/* Write length. */
1434 		len_len = ntfs_write_significant_bytes(dst + 1, dst_max,
1435 				length);
1436 		if (unlikely(len_len < 0))
1437 			goto size_err;
1438 		/*
1439 		 * If the logical cluster number (lcn) denotes a hole and we
1440 		 * are on NTFS 3.0+, we don't store it at all, i.e. we need
1441 		 * zero space.  On earlier NTFS versions we just write the lcn
1442 		 * change.
1443 		 */
1444 		if (likely(rl->lcn >= 0 || vol->major_ver < 3)) {
1445 			/* Write change in lcn. */
1446 			lcn_len = ntfs_write_significant_bytes(dst + 1 +
1447 					len_len, dst_max, rl->lcn - prev_lcn);
1448 			if (unlikely(lcn_len < 0))
1449 				goto size_err;
1450 			prev_lcn = rl->lcn;
1451 		} else {
1452 			if (rl->lcn == LCN_DELALLOC)
1453 				de_cnt += rl->length;
1454 			lcn_len = 0;
1455 		}
1456 		dst_next = dst + len_len + lcn_len + 1;
1457 		if (unlikely(dst_next > dst_max))
1458 			goto size_err;
1459 		/* Update header byte. */
1460 		*dst = lcn_len << 4 | len_len;
1461 		/* Position at next mapping pairs array element. */
1462 		dst = dst_next;
1463 	}
1464 	/* Success. */
1465 	if (de_cluster_count)
1466 		*de_cluster_count = de_cnt;
1467 	err = 0;
1468 size_err:
1469 	/* Set stop vcn. */
1470 	if (stop_vcn)
1471 		*stop_vcn = rl->vcn;
1472 	if (stop_rl)
1473 		*stop_rl = (struct runlist_element *)rl;
1474 	/* Add terminator byte. */
1475 	*dst = 0;
1476 	return err;
1477 err_out:
1478 	if (rl->lcn == LCN_RL_NOT_MAPPED)
1479 		err = -EINVAL;
1480 	else
1481 		err = -EIO;
1482 	return err;
1483 }
1484 
1485 /*
1486  * ntfs_rl_truncate_nolock - truncate a runlist starting at a specified vcn
1487  * @vol:	ntfs volume (needed for error output)
1488  * @runlist:	runlist to truncate
1489  * @new_length:	the new length of the runlist in VCNs
1490  *
1491  * Truncate the runlist described by @runlist as well as the memory buffer
1492  * holding the runlist elements to a length of @new_length VCNs.
1493  *
1494  * If @new_length lies within the runlist, the runlist elements with VCNs of
1495  * @new_length and above are discarded.  As a special case if @new_length is
1496  * zero, the runlist is discarded and set to NULL.
1497  *
1498  * If @new_length lies beyond the runlist, a sparse runlist element is added to
1499  * the end of the runlist @runlist or if the last runlist element is a sparse
1500  * one already, this is extended.
1501  *
1502  * Note, no checking is done for unmapped runlist elements.  It is assumed that
1503  * the caller has mapped any elements that need to be mapped already.
1504  *
1505  * Return 0 on success and -errno on error.
1506  *
1507  * Locking: The caller must hold @runlist->lock for writing.
1508  */
1509 int ntfs_rl_truncate_nolock(const struct ntfs_volume *vol, struct runlist *const runlist,
1510 		const s64 new_length)
1511 {
1512 	struct runlist_element *rl;
1513 	int old_size;
1514 
1515 	ntfs_debug("Entering for new_length 0x%llx.", (long long)new_length);
1516 
1517 	if (!runlist || new_length < 0)
1518 		return -EINVAL;
1519 
1520 	rl = runlist->rl;
1521 	if (new_length < rl->vcn)
1522 		return -EINVAL;
1523 
1524 	/* Find @new_length in the runlist. */
1525 	while (likely(rl->length && new_length >= rl[1].vcn))
1526 		rl++;
1527 	/*
1528 	 * If not at the end of the runlist we need to shrink it.
1529 	 * If at the end of the runlist we need to expand it.
1530 	 */
1531 	if (rl->length) {
1532 		struct runlist_element *trl;
1533 		bool is_end;
1534 
1535 		ntfs_debug("Shrinking runlist.");
1536 		/* Determine the runlist size. */
1537 		trl = rl + 1;
1538 		while (likely(trl->length))
1539 			trl++;
1540 		old_size = trl - runlist->rl + 1;
1541 		/* Truncate the run. */
1542 		rl->length = new_length - rl->vcn;
1543 		/*
1544 		 * If a run was partially truncated, make the following runlist
1545 		 * element a terminator.
1546 		 */
1547 		is_end = false;
1548 		if (rl->length) {
1549 			rl++;
1550 			if (!rl->length)
1551 				is_end = true;
1552 			rl->vcn = new_length;
1553 			rl->length = 0;
1554 		}
1555 		rl->lcn = LCN_ENOENT;
1556 		runlist->count = rl - runlist->rl + 1;
1557 		/* Reallocate memory if necessary. */
1558 		if (!is_end) {
1559 			int new_size = rl - runlist->rl + 1;
1560 
1561 			rl = ntfs_rl_realloc(runlist->rl, old_size, new_size);
1562 			if (IS_ERR(rl))
1563 				ntfs_warning(vol->sb,
1564 					"Failed to shrink runlist buffer.  This just wastes a bit of memory temporarily so we ignore it and return success.");
1565 			else
1566 				runlist->rl = rl;
1567 		}
1568 	} else if (likely(/* !rl->length && */ new_length > rl->vcn)) {
1569 		ntfs_debug("Expanding runlist.");
1570 		/*
1571 		 * If there is a previous runlist element and it is a sparse
1572 		 * one, extend it.  Otherwise need to add a new, sparse runlist
1573 		 * element.
1574 		 */
1575 		if ((rl > runlist->rl) && ((rl - 1)->lcn == LCN_HOLE))
1576 			(rl - 1)->length = new_length - (rl - 1)->vcn;
1577 		else {
1578 			/* Determine the runlist size. */
1579 			old_size = rl - runlist->rl + 1;
1580 			/* Reallocate memory if necessary. */
1581 			rl = ntfs_rl_realloc(runlist->rl, old_size,
1582 					old_size + 1);
1583 			if (IS_ERR(rl)) {
1584 				ntfs_error(vol->sb, "Failed to expand runlist buffer, aborting.");
1585 				return PTR_ERR(rl);
1586 			}
1587 			runlist->rl = rl;
1588 			/*
1589 			 * Set @rl to the same runlist element in the new
1590 			 * runlist as before in the old runlist.
1591 			 */
1592 			rl += old_size - 1;
1593 			/* Add a new, sparse runlist element. */
1594 			rl->lcn = LCN_HOLE;
1595 			rl->length = new_length - rl->vcn;
1596 			/* Add a new terminator runlist element. */
1597 			rl++;
1598 			rl->length = 0;
1599 			runlist->count = old_size + 1;
1600 		}
1601 		rl->vcn = new_length;
1602 		rl->lcn = LCN_ENOENT;
1603 	} else /* if (unlikely(!rl->length && new_length == rl->vcn)) */ {
1604 		/* Runlist already has same size as requested. */
1605 		rl->lcn = LCN_ENOENT;
1606 	}
1607 	ntfs_debug("Done.");
1608 	return 0;
1609 }
1610 
1611 /*
1612  * ntfs_rl_sparse - check whether runlist have sparse regions or not.
1613  * @rl:         runlist to check
1614  *
1615  * Return 1 if have, 0 if not, -errno on error.
1616  */
1617 int ntfs_rl_sparse(struct runlist_element *rl)
1618 {
1619 	struct runlist_element *rlc;
1620 
1621 	if (!rl)
1622 		return -EINVAL;
1623 
1624 	for (rlc = rl; rlc->length; rlc++)
1625 		if (rlc->lcn < 0) {
1626 			if (rlc->lcn != LCN_HOLE && rlc->lcn != LCN_DELALLOC) {
1627 				pr_err("%s: bad runlist\n", __func__);
1628 				return -EINVAL;
1629 			}
1630 			return 1;
1631 		}
1632 	return 0;
1633 }
1634 
1635 /*
1636  * ntfs_rl_get_compressed_size - calculate length of non sparse regions
1637  * @vol:        ntfs volume (need for cluster size)
1638  * @rl:         runlist to calculate for
1639  *
1640  * Return compressed size or -errno on error.
1641  */
1642 s64 ntfs_rl_get_compressed_size(struct ntfs_volume *vol, struct runlist_element *rl)
1643 {
1644 	struct runlist_element *rlc;
1645 	s64 ret = 0;
1646 
1647 	if (!rl)
1648 		return -EINVAL;
1649 
1650 	for (rlc = rl; rlc->length; rlc++) {
1651 		if (rlc->lcn < 0) {
1652 			if (rlc->lcn != LCN_HOLE && rlc->lcn != LCN_DELALLOC) {
1653 				ntfs_error(vol->sb, "%s: bad runlist, rlc->lcn : %lld",
1654 						__func__, rlc->lcn);
1655 				return -EINVAL;
1656 			}
1657 		} else
1658 			ret += rlc->length;
1659 	}
1660 	return NTFS_CLU_TO_B(vol, ret);
1661 }
1662 
1663 static inline bool ntfs_rle_lcn_contiguous(struct runlist_element *left_rle,
1664 					   struct runlist_element *right_rle)
1665 {
1666 	if (left_rle->lcn > LCN_HOLE &&
1667 	    left_rle->lcn + left_rle->length == right_rle->lcn)
1668 		return true;
1669 	else if (left_rle->lcn == LCN_HOLE && right_rle->lcn == LCN_HOLE)
1670 		return true;
1671 	else
1672 		return false;
1673 }
1674 
1675 static inline bool ntfs_rle_contain(struct runlist_element *rle, s64 vcn)
1676 {
1677 	if (rle->length > 0 &&
1678 	    vcn >= rle->vcn && vcn < rle->vcn + rle->length)
1679 		return true;
1680 	else
1681 		return false;
1682 }
1683 
1684 struct runlist_element *ntfs_rl_insert_range(struct runlist_element *dst_rl, int dst_cnt,
1685 				      struct runlist_element *src_rl, int src_cnt,
1686 				      size_t *new_rl_cnt)
1687 {
1688 	struct runlist_element *i_rl, *new_rl, *src_rl_origin = src_rl;
1689 	struct runlist_element dst_rl_split;
1690 	s64 start_vcn;
1691 	int new_1st_cnt, new_2nd_cnt, new_3rd_cnt, new_cnt;
1692 
1693 	if (!dst_rl || !src_rl || !new_rl_cnt)
1694 		return ERR_PTR(-EINVAL);
1695 	if (dst_cnt <= 0 || src_cnt <= 0)
1696 		return ERR_PTR(-EINVAL);
1697 	if (!(dst_rl[dst_cnt - 1].lcn == LCN_ENOENT &&
1698 	      dst_rl[dst_cnt - 1].length == 0) ||
1699 	    src_rl[src_cnt - 1].lcn < LCN_HOLE)
1700 		return ERR_PTR(-EINVAL);
1701 
1702 	start_vcn = src_rl[0].vcn;
1703 
1704 	i_rl = ntfs_rl_find_vcn_nolock(dst_rl, start_vcn);
1705 	if (!i_rl ||
1706 	    (i_rl->lcn == LCN_ENOENT && i_rl->vcn != start_vcn) ||
1707 	    (i_rl->lcn != LCN_ENOENT && !ntfs_rle_contain(i_rl, start_vcn)))
1708 		return ERR_PTR(-EINVAL);
1709 
1710 	new_1st_cnt = (int)(i_rl - dst_rl);
1711 	if (new_1st_cnt > dst_cnt)
1712 		return ERR_PTR(-EINVAL);
1713 	new_3rd_cnt = dst_cnt - new_1st_cnt;
1714 	if (new_3rd_cnt < 1)
1715 		return ERR_PTR(-EINVAL);
1716 
1717 	if (i_rl[0].vcn != start_vcn) {
1718 		if (i_rl[0].lcn == LCN_HOLE && src_rl[0].lcn == LCN_HOLE)
1719 			goto merge_src_rle;
1720 
1721 		/* split @i_rl[0] and create @dst_rl_split */
1722 		dst_rl_split.vcn = i_rl[0].vcn;
1723 		dst_rl_split.length = start_vcn - i_rl[0].vcn;
1724 		dst_rl_split.lcn = i_rl[0].lcn;
1725 
1726 		i_rl[0].vcn = start_vcn;
1727 		i_rl[0].length -= dst_rl_split.length;
1728 		i_rl[0].lcn += dst_rl_split.length;
1729 	} else {
1730 		struct runlist_element *dst_rle, *src_rle;
1731 merge_src_rle:
1732 
1733 		/* not split @i_rl[0] */
1734 		dst_rl_split.lcn = LCN_ENOENT;
1735 
1736 		/* merge @src_rl's first run and @i_rl[0]'s left run if possible */
1737 		dst_rle = &dst_rl[new_1st_cnt - 1];
1738 		src_rle = &src_rl[0];
1739 		if (new_1st_cnt > 0 && ntfs_rle_lcn_contiguous(dst_rle, src_rle)) {
1740 			WARN_ON(dst_rle->vcn + dst_rle->length != src_rle->vcn);
1741 			dst_rle->length += src_rle->length;
1742 			src_rl++;
1743 			src_cnt--;
1744 		} else {
1745 			/* merge @src_rl's last run and @i_rl[0]'s right if possible */
1746 			dst_rle = &dst_rl[new_1st_cnt];
1747 			src_rle = &src_rl[src_cnt - 1];
1748 
1749 			if (ntfs_rle_lcn_contiguous(dst_rle, src_rle)) {
1750 				dst_rle->length += src_rle->length;
1751 				src_cnt--;
1752 			}
1753 		}
1754 	}
1755 
1756 	new_2nd_cnt = src_cnt;
1757 	new_cnt = new_1st_cnt + new_2nd_cnt + new_3rd_cnt;
1758 	new_cnt += dst_rl_split.lcn >= LCN_HOLE ? 1 : 0;
1759 	new_rl = kvcalloc(new_cnt, sizeof(*new_rl), GFP_NOFS);
1760 	if (!new_rl)
1761 		return ERR_PTR(-ENOMEM);
1762 
1763 	/* Copy the @dst_rl's first half to @new_rl */
1764 	ntfs_rl_mc(new_rl, 0, dst_rl, 0, new_1st_cnt);
1765 	if (dst_rl_split.lcn >= LCN_HOLE) {
1766 		ntfs_rl_mc(new_rl, new_1st_cnt, &dst_rl_split, 0, 1);
1767 		new_1st_cnt++;
1768 	}
1769 	/* Copy the @src_rl to @new_rl */
1770 	ntfs_rl_mc(new_rl, new_1st_cnt, src_rl, 0, new_2nd_cnt);
1771 	/* Copy the @dst_rl's second half to @new_rl */
1772 	if (new_3rd_cnt >= 1) {
1773 		struct runlist_element *rl, *rl_3rd;
1774 		int dst_1st_cnt = dst_rl_split.lcn >= LCN_HOLE ?
1775 			new_1st_cnt - 1 : new_1st_cnt;
1776 
1777 		ntfs_rl_mc(new_rl, new_1st_cnt + new_2nd_cnt,
1778 			   dst_rl, dst_1st_cnt, new_3rd_cnt);
1779 		/* Update vcn of the @dst_rl's second half runs to reflect
1780 		 * appended @src_rl.
1781 		 */
1782 		if (new_1st_cnt + new_2nd_cnt == 0) {
1783 			rl_3rd = &new_rl[new_1st_cnt + new_2nd_cnt + 1];
1784 			rl = &new_rl[new_1st_cnt + new_2nd_cnt];
1785 		} else {
1786 			rl_3rd = &new_rl[new_1st_cnt + new_2nd_cnt];
1787 			rl = &new_rl[new_1st_cnt + new_2nd_cnt - 1];
1788 		}
1789 		do {
1790 			rl_3rd->vcn = rl->vcn + rl->length;
1791 			if (rl_3rd->length <= 0)
1792 				break;
1793 			rl = rl_3rd;
1794 			rl_3rd++;
1795 		} while (1);
1796 	}
1797 	*new_rl_cnt = new_1st_cnt + new_2nd_cnt + new_3rd_cnt;
1798 
1799 	kvfree(dst_rl);
1800 	kvfree(src_rl_origin);
1801 	return new_rl;
1802 }
1803 
1804 struct runlist_element *ntfs_rl_punch_hole(struct runlist_element *dst_rl, int dst_cnt,
1805 				    s64 start_vcn, s64 len,
1806 				    struct runlist_element **punch_rl,
1807 				    size_t *new_rl_cnt)
1808 {
1809 	struct runlist_element *s_rl, *e_rl, *new_rl, *dst_3rd_rl, hole_rl[1];
1810 	s64 end_vcn;
1811 	int new_1st_cnt, dst_3rd_cnt, new_cnt, punch_cnt, merge_cnt;
1812 	bool begin_split, end_split, one_split_3;
1813 
1814 	if (dst_cnt < 2 ||
1815 	    !(dst_rl[dst_cnt - 1].lcn == LCN_ENOENT &&
1816 	      dst_rl[dst_cnt - 1].length == 0))
1817 		return ERR_PTR(-EINVAL);
1818 
1819 	end_vcn = min(start_vcn + len - 1,
1820 		      dst_rl[dst_cnt - 2].vcn + dst_rl[dst_cnt - 2].length - 1);
1821 
1822 	s_rl = ntfs_rl_find_vcn_nolock(dst_rl, start_vcn);
1823 	if (!s_rl ||
1824 	    s_rl->lcn <= LCN_ENOENT ||
1825 	    !ntfs_rle_contain(s_rl, start_vcn))
1826 		return ERR_PTR(-EINVAL);
1827 
1828 	begin_split = s_rl->vcn != start_vcn;
1829 
1830 	e_rl = ntfs_rl_find_vcn_nolock(dst_rl, end_vcn);
1831 	if (!e_rl ||
1832 	    e_rl->lcn <= LCN_ENOENT ||
1833 	    !ntfs_rle_contain(e_rl, end_vcn))
1834 		return ERR_PTR(-EINVAL);
1835 
1836 	end_split = e_rl->vcn + e_rl->length - 1 != end_vcn;
1837 
1838 	/* @s_rl has to be split into left, punched hole, and right */
1839 	one_split_3 = e_rl == s_rl && begin_split && end_split;
1840 
1841 	punch_cnt = (int)(e_rl - s_rl) + 1;
1842 
1843 	*punch_rl = kvcalloc(punch_cnt + 1, sizeof(struct runlist_element),
1844 			GFP_NOFS);
1845 	if (!*punch_rl)
1846 		return ERR_PTR(-ENOMEM);
1847 
1848 	new_cnt = dst_cnt - (int)(e_rl - s_rl + 1) + 3;
1849 	new_rl = kvcalloc(new_cnt, sizeof(struct runlist_element), GFP_NOFS);
1850 	if (!new_rl) {
1851 		kvfree(*punch_rl);
1852 		*punch_rl = NULL;
1853 		return ERR_PTR(-ENOMEM);
1854 	}
1855 
1856 	new_1st_cnt = (int)(s_rl - dst_rl) + 1;
1857 	ntfs_rl_mc(*punch_rl, 0, dst_rl, new_1st_cnt - 1, punch_cnt);
1858 
1859 	(*punch_rl)[punch_cnt].lcn = LCN_ENOENT;
1860 	(*punch_rl)[punch_cnt].length = 0;
1861 
1862 	if (!begin_split)
1863 		new_1st_cnt--;
1864 	dst_3rd_rl = e_rl;
1865 	dst_3rd_cnt = (int)(&dst_rl[dst_cnt - 1] - e_rl) + 1;
1866 	if (!end_split) {
1867 		dst_3rd_rl++;
1868 		dst_3rd_cnt--;
1869 	}
1870 
1871 	/* Copy the 1st part of @dst_rl into @new_rl */
1872 	ntfs_rl_mc(new_rl, 0, dst_rl, 0, new_1st_cnt);
1873 	if (begin_split) {
1874 		/* the @e_rl has to be splited and copied into the last of @new_rl
1875 		 * and the first of @punch_rl
1876 		 */
1877 		s64 first_cnt = start_vcn - dst_rl[new_1st_cnt - 1].vcn;
1878 
1879 		if (new_1st_cnt)
1880 			new_rl[new_1st_cnt - 1].length = first_cnt;
1881 
1882 		(*punch_rl)[0].vcn = start_vcn;
1883 		(*punch_rl)[0].length -= first_cnt;
1884 		if ((*punch_rl)[0].lcn > LCN_HOLE)
1885 			(*punch_rl)[0].lcn += first_cnt;
1886 	}
1887 
1888 	/* Copy a hole into @new_rl */
1889 	hole_rl[0].vcn = start_vcn;
1890 	hole_rl[0].length = (s64)len;
1891 	hole_rl[0].lcn = LCN_HOLE;
1892 	ntfs_rl_mc(new_rl, new_1st_cnt, hole_rl, 0, 1);
1893 
1894 	/* Copy the 3rd part of @dst_rl into @new_rl */
1895 	ntfs_rl_mc(new_rl, new_1st_cnt + 1, dst_3rd_rl, 0, dst_3rd_cnt);
1896 	if (end_split) {
1897 		/* the @e_rl has to be splited and copied into the first of
1898 		 * @new_rl and the last of @punch_rl
1899 		 */
1900 		s64 first_cnt = end_vcn - dst_3rd_rl[0].vcn + 1;
1901 
1902 		new_rl[new_1st_cnt + 1].vcn = end_vcn + 1;
1903 		new_rl[new_1st_cnt + 1].length -= first_cnt;
1904 		if (new_rl[new_1st_cnt + 1].lcn > LCN_HOLE)
1905 			new_rl[new_1st_cnt + 1].lcn += first_cnt;
1906 
1907 		if (one_split_3)
1908 			(*punch_rl)[punch_cnt - 1].length -=
1909 				new_rl[new_1st_cnt + 1].length;
1910 		else
1911 			(*punch_rl)[punch_cnt - 1].length = first_cnt;
1912 	}
1913 
1914 	/* Merge left and hole, or hole and right in @new_rl, if left or right
1915 	 * consists of holes.
1916 	 */
1917 	merge_cnt = 0;
1918 	if (new_1st_cnt > 0 && new_rl[new_1st_cnt - 1].lcn == LCN_HOLE) {
1919 		/* Merge right and hole */
1920 		s_rl =  &new_rl[new_1st_cnt - 1];
1921 		s_rl->length += s_rl[1].length;
1922 		merge_cnt = 1;
1923 		/* Merge left and right */
1924 		if (new_1st_cnt + 1 < new_cnt &&
1925 		    new_rl[new_1st_cnt + 1].lcn == LCN_HOLE) {
1926 			s_rl->length += s_rl[2].length;
1927 			merge_cnt++;
1928 		}
1929 	} else if (new_1st_cnt + 1 < new_cnt &&
1930 		   new_rl[new_1st_cnt + 1].lcn == LCN_HOLE) {
1931 		/* Merge left and hole */
1932 		s_rl = &new_rl[new_1st_cnt];
1933 		s_rl->length += s_rl[1].length;
1934 		merge_cnt = 1;
1935 	}
1936 	if (merge_cnt) {
1937 		struct runlist_element *d_rl, *src_rl;
1938 
1939 		d_rl = s_rl + 1;
1940 		src_rl = s_rl + 1 + merge_cnt;
1941 		ntfs_rl_mm(new_rl, (int)(d_rl - new_rl), (int)(src_rl - new_rl),
1942 			   (int)(&new_rl[new_cnt - 1] - src_rl) + 1);
1943 	}
1944 
1945 	(*punch_rl)[punch_cnt].vcn = (*punch_rl)[punch_cnt - 1].vcn +
1946 		(*punch_rl)[punch_cnt - 1].length;
1947 
1948 	/* punch_cnt elements of dst are replaced with one hole */
1949 	*new_rl_cnt = dst_cnt - (punch_cnt - (int)begin_split - (int)end_split) +
1950 		1 - merge_cnt;
1951 	kvfree(dst_rl);
1952 	return new_rl;
1953 }
1954 
1955 struct runlist_element *ntfs_rl_collapse_range(struct runlist_element *dst_rl, int dst_cnt,
1956 					s64 start_vcn, s64 len,
1957 					struct runlist_element **punch_rl,
1958 					size_t *new_rl_cnt)
1959 {
1960 	struct runlist_element *s_rl, *e_rl, *new_rl, *dst_3rd_rl;
1961 	s64 end_vcn;
1962 	int new_1st_cnt, dst_3rd_cnt, new_cnt, punch_cnt, merge_cnt, i;
1963 	bool begin_split, end_split, one_split_3;
1964 
1965 	if (dst_cnt < 2 ||
1966 	    !(dst_rl[dst_cnt - 1].lcn == LCN_ENOENT &&
1967 	      dst_rl[dst_cnt - 1].length == 0))
1968 		return ERR_PTR(-EINVAL);
1969 
1970 	end_vcn = min(start_vcn + len - 1,
1971 			dst_rl[dst_cnt - 1].vcn - 1);
1972 
1973 	s_rl = ntfs_rl_find_vcn_nolock(dst_rl, start_vcn);
1974 	if (!s_rl ||
1975 	    s_rl->lcn <= LCN_ENOENT ||
1976 	    !ntfs_rle_contain(s_rl, start_vcn))
1977 		return ERR_PTR(-EINVAL);
1978 
1979 	begin_split = s_rl->vcn != start_vcn;
1980 
1981 	e_rl = ntfs_rl_find_vcn_nolock(dst_rl, end_vcn);
1982 	if (!e_rl ||
1983 	    e_rl->lcn <= LCN_ENOENT ||
1984 	    !ntfs_rle_contain(e_rl, end_vcn))
1985 		return ERR_PTR(-EINVAL);
1986 
1987 	end_split = e_rl->vcn + e_rl->length - 1 != end_vcn;
1988 
1989 	/* @s_rl has to be split into left, collapsed, and right */
1990 	one_split_3 = e_rl == s_rl && begin_split && end_split;
1991 
1992 	punch_cnt = (int)(e_rl - s_rl) + 1;
1993 	*punch_rl = kvcalloc(punch_cnt + 1, sizeof(struct runlist_element),
1994 			GFP_NOFS);
1995 	if (!*punch_rl)
1996 		return ERR_PTR(-ENOMEM);
1997 
1998 	new_cnt = dst_cnt - (int)(e_rl - s_rl + 1) + 3;
1999 	new_rl = kvcalloc(new_cnt, sizeof(struct runlist_element), GFP_NOFS);
2000 	if (!new_rl) {
2001 		kvfree(*punch_rl);
2002 		*punch_rl = NULL;
2003 		return ERR_PTR(-ENOMEM);
2004 	}
2005 
2006 	new_1st_cnt = (int)(s_rl - dst_rl) + 1;
2007 	ntfs_rl_mc(*punch_rl, 0, dst_rl, new_1st_cnt - 1, punch_cnt);
2008 	(*punch_rl)[punch_cnt].lcn = LCN_ENOENT;
2009 	(*punch_rl)[punch_cnt].length = 0;
2010 
2011 	if (!begin_split)
2012 		new_1st_cnt--;
2013 	dst_3rd_rl = e_rl;
2014 	dst_3rd_cnt = (int)(&dst_rl[dst_cnt - 1] - e_rl) + 1;
2015 	if (!end_split) {
2016 		dst_3rd_rl++;
2017 		dst_3rd_cnt--;
2018 	}
2019 
2020 	/* Copy the 1st part of @dst_rl into @new_rl */
2021 	ntfs_rl_mc(new_rl, 0, dst_rl, 0, new_1st_cnt);
2022 	if (begin_split) {
2023 		/* the @e_rl has to be splited and copied into the last of @new_rl
2024 		 * and the first of @punch_rl
2025 		 */
2026 		s64 first_cnt = start_vcn - dst_rl[new_1st_cnt - 1].vcn;
2027 
2028 		new_rl[new_1st_cnt - 1].length = first_cnt;
2029 
2030 		(*punch_rl)[0].vcn = start_vcn;
2031 		(*punch_rl)[0].length -= first_cnt;
2032 		if ((*punch_rl)[0].lcn > LCN_HOLE)
2033 			(*punch_rl)[0].lcn += first_cnt;
2034 	}
2035 
2036 	/* Copy the 3rd part of @dst_rl into @new_rl */
2037 	ntfs_rl_mc(new_rl, new_1st_cnt, dst_3rd_rl, 0, dst_3rd_cnt);
2038 	if (end_split) {
2039 		/* the @e_rl has to be splited and copied into the first of
2040 		 * @new_rl and the last of @punch_rl
2041 		 */
2042 		s64 first_cnt = end_vcn - dst_3rd_rl[0].vcn + 1;
2043 
2044 		new_rl[new_1st_cnt].vcn = end_vcn + 1;
2045 		new_rl[new_1st_cnt].length -= first_cnt;
2046 		if (new_rl[new_1st_cnt].lcn > LCN_HOLE)
2047 			new_rl[new_1st_cnt].lcn += first_cnt;
2048 
2049 		if (one_split_3)
2050 			(*punch_rl)[punch_cnt - 1].length -=
2051 				new_rl[new_1st_cnt].length;
2052 		else
2053 			(*punch_rl)[punch_cnt - 1].length = first_cnt;
2054 	}
2055 
2056 	/* Adjust vcn */
2057 	if (new_1st_cnt == 0)
2058 		new_rl[new_1st_cnt].vcn = 0;
2059 	for (i = new_1st_cnt == 0 ? 1 : new_1st_cnt; new_rl[i].length; i++)
2060 		new_rl[i].vcn = new_rl[i - 1].vcn + new_rl[i - 1].length;
2061 	new_rl[i].vcn = new_rl[i - 1].vcn + new_rl[i - 1].length;
2062 
2063 	/* Merge left and hole, or hole and right in @new_rl, if left or right
2064 	 * consists of holes.
2065 	 */
2066 	merge_cnt = 0;
2067 	if (new_1st_cnt > 0 &&
2068 	    ntfs_rle_lcn_contiguous(&new_rl[new_1st_cnt - 1],
2069 				    &new_rl[new_1st_cnt])) {
2070 		/* Merge right and left. */
2071 		s_rl = &new_rl[new_1st_cnt - 1];
2072 		s_rl->length += s_rl[1].length;
2073 		merge_cnt = 1;
2074 	}
2075 	if (merge_cnt) {
2076 		struct runlist_element *d_rl, *src_rl;
2077 
2078 		d_rl = s_rl + 1;
2079 		src_rl = s_rl + 1 + merge_cnt;
2080 		ntfs_rl_mm(new_rl, (int)(d_rl - new_rl), (int)(src_rl - new_rl),
2081 			   (int)(&new_rl[new_cnt - 1] - src_rl) + 1);
2082 	}
2083 
2084 	(*punch_rl)[punch_cnt].vcn = (*punch_rl)[punch_cnt - 1].vcn +
2085 		(*punch_rl)[punch_cnt - 1].length;
2086 
2087 	/* punch_cnt elements of dst are extracted */
2088 	*new_rl_cnt = dst_cnt - (punch_cnt - (int)begin_split - (int)end_split) -
2089 		merge_cnt;
2090 
2091 	kvfree(dst_rl);
2092 	return new_rl;
2093 }
2094