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