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