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