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