blob: 5244687dfaa8c62c82e002e686a925f419fde015 [file] [log] [blame]
Linus Torvalds1da177e2005-04-16 15:20:36 -07001/**
2 * runlist.c - NTFS runlist handling code. Part of the Linux-NTFS project.
3 *
Anton Altaparmakov1a0df152005-02-03 12:04:36 +00004 * Copyright (c) 2001-2005 Anton Altaparmakov
Linus Torvalds1da177e2005-04-16 15:20:36 -07005 * Copyright (c) 2002 Richard Russon
6 *
7 * This program/include file is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License as published
9 * by the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
11 *
12 * This program/include file is distributed in the hope that it will be
13 * useful, but WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program (in the main directory of the Linux-NTFS
19 * distribution in the file COPYING); if not, write to the Free Software
20 * Foundation,Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21 */
22
23#include "debug.h"
24#include "dir.h"
25#include "endian.h"
26#include "malloc.h"
27#include "ntfs.h"
28
29/**
30 * ntfs_rl_mm - runlist memmove
31 *
32 * It is up to the caller to serialize access to the runlist @base.
33 */
34static inline void ntfs_rl_mm(runlist_element *base, int dst, int src,
35 int size)
36{
37 if (likely((dst != src) && (size > 0)))
38 memmove(base + dst, base + src, size * sizeof (*base));
39}
40
41/**
42 * ntfs_rl_mc - runlist memory copy
43 *
44 * It is up to the caller to serialize access to the runlists @dstbase and
45 * @srcbase.
46 */
47static inline void ntfs_rl_mc(runlist_element *dstbase, int dst,
48 runlist_element *srcbase, int src, int size)
49{
50 if (likely(size > 0))
51 memcpy(dstbase + dst, srcbase + src, size * sizeof(*dstbase));
52}
53
54/**
55 * ntfs_rl_realloc - Reallocate memory for runlists
56 * @rl: original runlist
57 * @old_size: number of runlist elements in the original runlist @rl
58 * @new_size: number of runlist elements we need space for
59 *
60 * As the runlists grow, more memory will be required. To prevent the
61 * kernel having to allocate and reallocate large numbers of small bits of
Anton Altaparmakov1a0df152005-02-03 12:04:36 +000062 * memory, this function returns an entire page of memory.
Linus Torvalds1da177e2005-04-16 15:20:36 -070063 *
64 * It is up to the caller to serialize access to the runlist @rl.
65 *
66 * N.B. If the new allocation doesn't require a different number of pages in
67 * memory, the function will return the original pointer.
68 *
69 * On success, return a pointer to the newly allocated, or recycled, memory.
70 * On error, return -errno. The following error codes are defined:
71 * -ENOMEM - Not enough memory to allocate runlist array.
72 * -EINVAL - Invalid parameters were passed in.
73 */
74static inline runlist_element *ntfs_rl_realloc(runlist_element *rl,
75 int old_size, int new_size)
76{
77 runlist_element *new_rl;
78
79 old_size = PAGE_ALIGN(old_size * sizeof(*rl));
80 new_size = PAGE_ALIGN(new_size * sizeof(*rl));
81 if (old_size == new_size)
82 return rl;
83
84 new_rl = ntfs_malloc_nofs(new_size);
85 if (unlikely(!new_rl))
86 return ERR_PTR(-ENOMEM);
87
88 if (likely(rl != NULL)) {
89 if (unlikely(old_size > new_size))
90 old_size = new_size;
91 memcpy(new_rl, rl, old_size);
92 ntfs_free(rl);
93 }
94 return new_rl;
95}
96
97/**
98 * ntfs_are_rl_mergeable - test if two runlists can be joined together
99 * @dst: original runlist
100 * @src: new runlist to test for mergeability with @dst
101 *
102 * Test if two runlists can be joined together. For this, their VCNs and LCNs
103 * must be adjacent.
104 *
105 * It is up to the caller to serialize access to the runlists @dst and @src.
106 *
107 * Return: TRUE Success, the runlists can be merged.
108 * FALSE Failure, the runlists cannot be merged.
109 */
110static inline BOOL ntfs_are_rl_mergeable(runlist_element *dst,
111 runlist_element *src)
112{
113 BUG_ON(!dst);
114 BUG_ON(!src);
115
116 if ((dst->lcn < 0) || (src->lcn < 0)) /* Are we merging holes? */
117 return FALSE;
118 if ((dst->lcn + dst->length) != src->lcn) /* Are the runs contiguous? */
119 return FALSE;
120 if ((dst->vcn + dst->length) != src->vcn) /* Are the runs misaligned? */
121 return FALSE;
122
123 return TRUE;
124}
125
126/**
127 * __ntfs_rl_merge - merge two runlists without testing if they can be merged
128 * @dst: original, destination runlist
129 * @src: new runlist to merge with @dst
130 *
131 * Merge the two runlists, writing into the destination runlist @dst. The
132 * caller must make sure the runlists can be merged or this will corrupt the
133 * destination runlist.
134 *
135 * It is up to the caller to serialize access to the runlists @dst and @src.
136 */
137static inline void __ntfs_rl_merge(runlist_element *dst, runlist_element *src)
138{
139 dst->length += src->length;
140}
141
142/**
143 * ntfs_rl_append - append a runlist after a given element
144 * @dst: original runlist to be worked on
145 * @dsize: number of elements in @dst (including end marker)
146 * @src: runlist to be inserted into @dst
147 * @ssize: number of elements in @src (excluding end marker)
148 * @loc: append the new runlist @src after this element in @dst
149 *
150 * Append the runlist @src after element @loc in @dst. Merge the right end of
151 * the new runlist, if necessary. Adjust the size of the hole before the
152 * appended runlist.
153 *
154 * It is up to the caller to serialize access to the runlists @dst and @src.
155 *
156 * On success, return a pointer to the new, combined, runlist. Note, both
157 * runlists @dst and @src are deallocated before returning so you cannot use
158 * the pointers for anything any more. (Strictly speaking the returned runlist
159 * may be the same as @dst but this is irrelevant.)
160 *
161 * On error, return -errno. Both runlists are left unmodified. The following
162 * error codes are defined:
163 * -ENOMEM - Not enough memory to allocate runlist array.
164 * -EINVAL - Invalid parameters were passed in.
165 */
166static inline runlist_element *ntfs_rl_append(runlist_element *dst,
167 int dsize, runlist_element *src, int ssize, int loc)
168{
169 BOOL right;
170 int magic;
171
172 BUG_ON(!dst);
173 BUG_ON(!src);
174
175 /* First, check if the right hand end needs merging. */
176 right = ntfs_are_rl_mergeable(src + ssize - 1, dst + loc + 1);
177
178 /* Space required: @dst size + @src size, less one if we merged. */
179 dst = ntfs_rl_realloc(dst, dsize, dsize + ssize - right);
180 if (IS_ERR(dst))
181 return dst;
182 /*
183 * We are guaranteed to succeed from here so can start modifying the
184 * original runlists.
185 */
186
187 /* First, merge the right hand end, if necessary. */
188 if (right)
189 __ntfs_rl_merge(src + ssize - 1, dst + loc + 1);
190
191 magic = loc + ssize;
192
193 /* Move the tail of @dst out of the way, then copy in @src. */
194 ntfs_rl_mm(dst, magic + 1, loc + 1 + right, dsize - loc - 1 - right);
195 ntfs_rl_mc(dst, loc + 1, src, 0, ssize);
196
197 /* Adjust the size of the preceding hole. */
198 dst[loc].length = dst[loc + 1].vcn - dst[loc].vcn;
199
200 /* We may have changed the length of the file, so fix the end marker */
201 if (dst[magic + 1].lcn == LCN_ENOENT)
202 dst[magic + 1].vcn = dst[magic].vcn + dst[magic].length;
203
204 return dst;
205}
206
207/**
208 * ntfs_rl_insert - insert a runlist into another
209 * @dst: original runlist to be worked on
210 * @dsize: number of elements in @dst (including end marker)
211 * @src: new runlist to be inserted
212 * @ssize: number of elements in @src (excluding end marker)
213 * @loc: insert the new runlist @src before this element in @dst
214 *
215 * Insert the runlist @src before element @loc in the runlist @dst. Merge the
216 * left end of the new runlist, if necessary. Adjust the size of the hole
217 * after the inserted runlist.
218 *
219 * It is up to the caller to serialize access to the runlists @dst and @src.
220 *
221 * On success, return a pointer to the new, combined, runlist. Note, both
222 * runlists @dst and @src are deallocated before returning so you cannot use
223 * the pointers for anything any more. (Strictly speaking the returned runlist
224 * may be the same as @dst but this is irrelevant.)
225 *
226 * On error, return -errno. Both runlists are left unmodified. The following
227 * error codes are defined:
228 * -ENOMEM - Not enough memory to allocate runlist array.
229 * -EINVAL - Invalid parameters were passed in.
230 */
231static inline runlist_element *ntfs_rl_insert(runlist_element *dst,
232 int dsize, runlist_element *src, int ssize, int loc)
233{
234 BOOL left = FALSE;
235 BOOL disc = FALSE; /* Discontinuity */
236 BOOL hole = FALSE; /* Following a hole */
237 int magic;
238
239 BUG_ON(!dst);
240 BUG_ON(!src);
241
242 /* disc => Discontinuity between the end of @dst and the start of @src.
243 * This means we might need to insert a hole.
244 * hole => @dst ends with a hole or an unmapped region which we can
245 * extend to match the discontinuity. */
246 if (loc == 0)
247 disc = (src[0].vcn > 0);
248 else {
249 s64 merged_length;
250
251 left = ntfs_are_rl_mergeable(dst + loc - 1, src);
252
253 merged_length = dst[loc - 1].length;
254 if (left)
255 merged_length += src->length;
256
257 disc = (src[0].vcn > dst[loc - 1].vcn + merged_length);
258 if (disc)
259 hole = (dst[loc - 1].lcn == LCN_HOLE);
260 }
261
262 /* Space required: @dst size + @src size, less one if we merged, plus
263 * one if there was a discontinuity, less one for a trailing hole. */
264 dst = ntfs_rl_realloc(dst, dsize, dsize + ssize - left + disc - hole);
265 if (IS_ERR(dst))
266 return dst;
267 /*
268 * We are guaranteed to succeed from here so can start modifying the
269 * original runlist.
270 */
271
272 if (left)
273 __ntfs_rl_merge(dst + loc - 1, src);
274
275 magic = loc + ssize - left + disc - hole;
276
277 /* Move the tail of @dst out of the way, then copy in @src. */
278 ntfs_rl_mm(dst, magic, loc, dsize - loc);
279 ntfs_rl_mc(dst, loc + disc - hole, src, left, ssize - left);
280
281 /* Adjust the VCN of the last run ... */
282 if (dst[magic].lcn <= LCN_HOLE)
283 dst[magic].vcn = dst[magic - 1].vcn + dst[magic - 1].length;
284 /* ... and the length. */
285 if (dst[magic].lcn == LCN_HOLE || dst[magic].lcn == LCN_RL_NOT_MAPPED)
286 dst[magic].length = dst[magic + 1].vcn - dst[magic].vcn;
287
288 /* Writing beyond the end of the file and there's a discontinuity. */
289 if (disc) {
290 if (hole)
291 dst[loc - 1].length = dst[loc].vcn - dst[loc - 1].vcn;
292 else {
293 if (loc > 0) {
294 dst[loc].vcn = dst[loc - 1].vcn +
295 dst[loc - 1].length;
296 dst[loc].length = dst[loc + 1].vcn -
297 dst[loc].vcn;
298 } else {
299 dst[loc].vcn = 0;
300 dst[loc].length = dst[loc + 1].vcn;
301 }
302 dst[loc].lcn = LCN_RL_NOT_MAPPED;
303 }
304
305 magic += hole;
306
307 if (dst[magic].lcn == LCN_ENOENT)
308 dst[magic].vcn = dst[magic - 1].vcn +
309 dst[magic - 1].length;
310 }
311 return dst;
312}
313
314/**
315 * ntfs_rl_replace - overwrite a runlist element with another runlist
316 * @dst: original runlist to be worked on
317 * @dsize: number of elements in @dst (including end marker)
318 * @src: new runlist to be inserted
319 * @ssize: number of elements in @src (excluding end marker)
320 * @loc: index in runlist @dst to overwrite with @src
321 *
322 * Replace the runlist element @dst at @loc with @src. Merge the left and
323 * right ends of the inserted runlist, if necessary.
324 *
325 * It is up to the caller to serialize access to the runlists @dst and @src.
326 *
327 * On success, return a pointer to the new, combined, runlist. Note, both
328 * runlists @dst and @src are deallocated before returning so you cannot use
329 * the pointers for anything any more. (Strictly speaking the returned runlist
330 * may be the same as @dst but this is irrelevant.)
331 *
332 * On error, return -errno. Both runlists are left unmodified. The following
333 * error codes are defined:
334 * -ENOMEM - Not enough memory to allocate runlist array.
335 * -EINVAL - Invalid parameters were passed in.
336 */
337static inline runlist_element *ntfs_rl_replace(runlist_element *dst,
338 int dsize, runlist_element *src, int ssize, int loc)
339{
340 BOOL left = FALSE;
341 BOOL right;
342 int magic;
343
344 BUG_ON(!dst);
345 BUG_ON(!src);
346
347 /* First, merge the left and right ends, if necessary. */
348 right = ntfs_are_rl_mergeable(src + ssize - 1, dst + loc + 1);
349 if (loc > 0)
350 left = ntfs_are_rl_mergeable(dst + loc - 1, src);
351
352 /* Allocate some space. We'll need less if the left, right, or both
353 * ends were merged. */
354 dst = ntfs_rl_realloc(dst, dsize, dsize + ssize - left - right);
355 if (IS_ERR(dst))
356 return dst;
357 /*
358 * We are guaranteed to succeed from here so can start modifying the
359 * original runlists.
360 */
361 if (right)
362 __ntfs_rl_merge(src + ssize - 1, dst + loc + 1);
363 if (left)
364 __ntfs_rl_merge(dst + loc - 1, src);
365
366 /* FIXME: What does this mean? (AIA) */
367 magic = loc + ssize - left;
368
369 /* Move the tail of @dst out of the way, then copy in @src. */
370 ntfs_rl_mm(dst, magic, loc + right + 1, dsize - loc - right - 1);
371 ntfs_rl_mc(dst, loc, src, left, ssize - left);
372
373 /* We may have changed the length of the file, so fix the end marker */
374 if (dst[magic].lcn == LCN_ENOENT)
375 dst[magic].vcn = dst[magic - 1].vcn + dst[magic - 1].length;
376 return dst;
377}
378
379/**
380 * ntfs_rl_split - insert a runlist into the centre of a hole
381 * @dst: original runlist to be worked on
382 * @dsize: number of elements in @dst (including end marker)
383 * @src: new runlist to be inserted
384 * @ssize: number of elements in @src (excluding end marker)
385 * @loc: index in runlist @dst at which to split and insert @src
386 *
387 * Split the runlist @dst at @loc into two and insert @new in between the two
388 * fragments. No merging of runlists is necessary. Adjust the size of the
389 * holes either side.
390 *
391 * It is up to the caller to serialize access to the runlists @dst and @src.
392 *
393 * On success, return a pointer to the new, combined, runlist. Note, both
394 * runlists @dst and @src are deallocated before returning so you cannot use
395 * the pointers for anything any more. (Strictly speaking the returned runlist
396 * may be the same as @dst but this is irrelevant.)
397 *
398 * On error, return -errno. Both runlists are left unmodified. The following
399 * error codes are defined:
400 * -ENOMEM - Not enough memory to allocate runlist array.
401 * -EINVAL - Invalid parameters were passed in.
402 */
403static inline runlist_element *ntfs_rl_split(runlist_element *dst, int dsize,
404 runlist_element *src, int ssize, int loc)
405{
406 BUG_ON(!dst);
407 BUG_ON(!src);
408
409 /* Space required: @dst size + @src size + one new hole. */
410 dst = ntfs_rl_realloc(dst, dsize, dsize + ssize + 1);
411 if (IS_ERR(dst))
412 return dst;
413 /*
414 * We are guaranteed to succeed from here so can start modifying the
415 * original runlists.
416 */
417
418 /* Move the tail of @dst out of the way, then copy in @src. */
419 ntfs_rl_mm(dst, loc + 1 + ssize, loc, dsize - loc);
420 ntfs_rl_mc(dst, loc + 1, src, 0, ssize);
421
422 /* Adjust the size of the holes either size of @src. */
423 dst[loc].length = dst[loc+1].vcn - dst[loc].vcn;
424 dst[loc+ssize+1].vcn = dst[loc+ssize].vcn + dst[loc+ssize].length;
425 dst[loc+ssize+1].length = dst[loc+ssize+2].vcn - dst[loc+ssize+1].vcn;
426
427 return dst;
428}
429
430/**
431 * ntfs_runlists_merge - merge two runlists into one
432 * @drl: original runlist to be worked on
433 * @srl: new runlist to be merged into @drl
434 *
435 * First we sanity check the two runlists @srl and @drl to make sure that they
436 * are sensible and can be merged. The runlist @srl must be either after the
437 * runlist @drl or completely within a hole (or unmapped region) in @drl.
438 *
439 * It is up to the caller to serialize access to the runlists @drl and @srl.
440 *
441 * Merging of runlists is necessary in two cases:
442 * 1. When attribute lists are used and a further extent is being mapped.
443 * 2. When new clusters are allocated to fill a hole or extend a file.
444 *
445 * There are four possible ways @srl can be merged. It can:
446 * - be inserted at the beginning of a hole,
447 * - split the hole in two and be inserted between the two fragments,
448 * - be appended at the end of a hole, or it can
449 * - replace the whole hole.
450 * It can also be appended to the end of the runlist, which is just a variant
451 * of the insert case.
452 *
453 * On success, return a pointer to the new, combined, runlist. Note, both
454 * runlists @drl and @srl are deallocated before returning so you cannot use
455 * the pointers for anything any more. (Strictly speaking the returned runlist
456 * may be the same as @dst but this is irrelevant.)
457 *
458 * On error, return -errno. Both runlists are left unmodified. The following
459 * error codes are defined:
460 * -ENOMEM - Not enough memory to allocate runlist array.
461 * -EINVAL - Invalid parameters were passed in.
462 * -ERANGE - The runlists overlap and cannot be merged.
463 */
464runlist_element *ntfs_runlists_merge(runlist_element *drl,
465 runlist_element *srl)
466{
467 int di, si; /* Current index into @[ds]rl. */
468 int sstart; /* First index with lcn > LCN_RL_NOT_MAPPED. */
469 int dins; /* Index into @drl at which to insert @srl. */
470 int dend, send; /* Last index into @[ds]rl. */
471 int dfinal, sfinal; /* The last index into @[ds]rl with
472 lcn >= LCN_HOLE. */
473 int marker = 0;
474 VCN marker_vcn = 0;
475
476#ifdef DEBUG
477 ntfs_debug("dst:");
478 ntfs_debug_dump_runlist(drl);
479 ntfs_debug("src:");
480 ntfs_debug_dump_runlist(srl);
481#endif
482
483 /* Check for silly calling... */
484 if (unlikely(!srl))
485 return drl;
486 if (IS_ERR(srl) || IS_ERR(drl))
487 return ERR_PTR(-EINVAL);
488
489 /* Check for the case where the first mapping is being done now. */
490 if (unlikely(!drl)) {
491 drl = srl;
492 /* Complete the source runlist if necessary. */
493 if (unlikely(drl[0].vcn)) {
494 /* Scan to the end of the source runlist. */
495 for (dend = 0; likely(drl[dend].length); dend++)
496 ;
497 drl = ntfs_rl_realloc(drl, dend, dend + 1);
498 if (IS_ERR(drl))
499 return drl;
500 /* Insert start element at the front of the runlist. */
501 ntfs_rl_mm(drl, 1, 0, dend);
502 drl[0].vcn = 0;
503 drl[0].lcn = LCN_RL_NOT_MAPPED;
504 drl[0].length = drl[1].vcn;
505 }
506 goto finished;
507 }
508
509 si = di = 0;
510
511 /* Skip any unmapped start element(s) in the source runlist. */
512 while (srl[si].length && srl[si].lcn < LCN_HOLE)
513 si++;
514
515 /* Can't have an entirely unmapped source runlist. */
516 BUG_ON(!srl[si].length);
517
518 /* Record the starting points. */
519 sstart = si;
520
521 /*
522 * Skip forward in @drl until we reach the position where @srl needs to
523 * be inserted. If we reach the end of @drl, @srl just needs to be
524 * appended to @drl.
525 */
526 for (; drl[di].length; di++) {
527 if (drl[di].vcn + drl[di].length > srl[sstart].vcn)
528 break;
529 }
530 dins = di;
531
532 /* Sanity check for illegal overlaps. */
533 if ((drl[di].vcn == srl[si].vcn) && (drl[di].lcn >= 0) &&
534 (srl[si].lcn >= 0)) {
535 ntfs_error(NULL, "Run lists overlap. Cannot merge!");
536 return ERR_PTR(-ERANGE);
537 }
538
539 /* Scan to the end of both runlists in order to know their sizes. */
540 for (send = si; srl[send].length; send++)
541 ;
542 for (dend = di; drl[dend].length; dend++)
543 ;
544
545 if (srl[send].lcn == LCN_ENOENT)
546 marker_vcn = srl[marker = send].vcn;
547
548 /* Scan to the last element with lcn >= LCN_HOLE. */
549 for (sfinal = send; sfinal >= 0 && srl[sfinal].lcn < LCN_HOLE; sfinal--)
550 ;
551 for (dfinal = dend; dfinal >= 0 && drl[dfinal].lcn < LCN_HOLE; dfinal--)
552 ;
553
554 {
555 BOOL start;
556 BOOL finish;
557 int ds = dend + 1; /* Number of elements in drl & srl */
558 int ss = sfinal - sstart + 1;
559
560 start = ((drl[dins].lcn < LCN_RL_NOT_MAPPED) || /* End of file */
561 (drl[dins].vcn == srl[sstart].vcn)); /* Start of hole */
562 finish = ((drl[dins].lcn >= LCN_RL_NOT_MAPPED) && /* End of file */
563 ((drl[dins].vcn + drl[dins].length) <= /* End of hole */
564 (srl[send - 1].vcn + srl[send - 1].length)));
565
566 /* Or we'll lose an end marker */
567 if (start && finish && (drl[dins].length == 0))
568 ss++;
569 if (marker && (drl[dins].vcn + drl[dins].length > srl[send - 1].vcn))
570 finish = FALSE;
571#if 0
572 ntfs_debug("dfinal = %i, dend = %i", dfinal, dend);
573 ntfs_debug("sstart = %i, sfinal = %i, send = %i", sstart, sfinal, send);
574 ntfs_debug("start = %i, finish = %i", start, finish);
575 ntfs_debug("ds = %i, ss = %i, dins = %i", ds, ss, dins);
576#endif
577 if (start) {
578 if (finish)
579 drl = ntfs_rl_replace(drl, ds, srl + sstart, ss, dins);
580 else
581 drl = ntfs_rl_insert(drl, ds, srl + sstart, ss, dins);
582 } else {
583 if (finish)
584 drl = ntfs_rl_append(drl, ds, srl + sstart, ss, dins);
585 else
586 drl = ntfs_rl_split(drl, ds, srl + sstart, ss, dins);
587 }
588 if (IS_ERR(drl)) {
589 ntfs_error(NULL, "Merge failed.");
590 return drl;
591 }
592 ntfs_free(srl);
593 if (marker) {
594 ntfs_debug("Triggering marker code.");
595 for (ds = dend; drl[ds].length; ds++)
596 ;
597 /* We only need to care if @srl ended after @drl. */
598 if (drl[ds].vcn <= marker_vcn) {
599 int slots = 0;
600
601 if (drl[ds].vcn == marker_vcn) {
602 ntfs_debug("Old marker = 0x%llx, replacing "
603 "with LCN_ENOENT.",
604 (unsigned long long)
605 drl[ds].lcn);
606 drl[ds].lcn = LCN_ENOENT;
607 goto finished;
608 }
609 /*
610 * We need to create an unmapped runlist element in
611 * @drl or extend an existing one before adding the
612 * ENOENT terminator.
613 */
614 if (drl[ds].lcn == LCN_ENOENT) {
615 ds--;
616 slots = 1;
617 }
618 if (drl[ds].lcn != LCN_RL_NOT_MAPPED) {
619 /* Add an unmapped runlist element. */
620 if (!slots) {
621 /* FIXME/TODO: We need to have the
622 * extra memory already! (AIA) */
623 drl = ntfs_rl_realloc(drl, ds, ds + 2);
624 if (!drl)
625 goto critical_error;
626 slots = 2;
627 }
628 ds++;
629 /* Need to set vcn if it isn't set already. */
630 if (slots != 1)
631 drl[ds].vcn = drl[ds - 1].vcn +
632 drl[ds - 1].length;
633 drl[ds].lcn = LCN_RL_NOT_MAPPED;
634 /* We now used up a slot. */
635 slots--;
636 }
637 drl[ds].length = marker_vcn - drl[ds].vcn;
638 /* Finally add the ENOENT terminator. */
639 ds++;
640 if (!slots) {
641 /* FIXME/TODO: We need to have the extra
642 * memory already! (AIA) */
643 drl = ntfs_rl_realloc(drl, ds, ds + 1);
644 if (!drl)
645 goto critical_error;
646 }
647 drl[ds].vcn = marker_vcn;
648 drl[ds].lcn = LCN_ENOENT;
649 drl[ds].length = (s64)0;
650 }
651 }
652 }
653
654finished:
655 /* The merge was completed successfully. */
656 ntfs_debug("Merged runlist:");
657 ntfs_debug_dump_runlist(drl);
658 return drl;
659
660critical_error:
661 /* Critical error! We cannot afford to fail here. */
662 ntfs_error(NULL, "Critical error! Not enough memory.");
663 panic("NTFS: Cannot continue.");
664}
665
666/**
667 * ntfs_mapping_pairs_decompress - convert mapping pairs array to runlist
668 * @vol: ntfs volume on which the attribute resides
669 * @attr: attribute record whose mapping pairs array to decompress
670 * @old_rl: optional runlist in which to insert @attr's runlist
671 *
672 * It is up to the caller to serialize access to the runlist @old_rl.
673 *
674 * Decompress the attribute @attr's mapping pairs array into a runlist. On
675 * success, return the decompressed runlist.
676 *
677 * If @old_rl is not NULL, decompressed runlist is inserted into the
678 * appropriate place in @old_rl and the resultant, combined runlist is
679 * returned. The original @old_rl is deallocated.
680 *
681 * On error, return -errno. @old_rl is left unmodified in that case.
682 *
683 * The following error codes are defined:
684 * -ENOMEM - Not enough memory to allocate runlist array.
685 * -EIO - Corrupt runlist.
686 * -EINVAL - Invalid parameters were passed in.
687 * -ERANGE - The two runlists overlap.
688 *
689 * FIXME: For now we take the conceptionally simplest approach of creating the
690 * new runlist disregarding the already existing one and then splicing the
691 * two into one, if that is possible (we check for overlap and discard the new
692 * runlist if overlap present before returning ERR_PTR(-ERANGE)).
693 */
694runlist_element *ntfs_mapping_pairs_decompress(const ntfs_volume *vol,
695 const ATTR_RECORD *attr, runlist_element *old_rl)
696{
697 VCN vcn; /* Current vcn. */
698 LCN lcn; /* Current lcn. */
699 s64 deltaxcn; /* Change in [vl]cn. */
700 runlist_element *rl; /* The output runlist. */
701 u8 *buf; /* Current position in mapping pairs array. */
702 u8 *attr_end; /* End of attribute. */
703 int rlsize; /* Size of runlist buffer. */
704 u16 rlpos; /* Current runlist position in units of
705 runlist_elements. */
706 u8 b; /* Current byte offset in buf. */
707
708#ifdef DEBUG
709 /* Make sure attr exists and is non-resident. */
710 if (!attr || !attr->non_resident || sle64_to_cpu(
711 attr->data.non_resident.lowest_vcn) < (VCN)0) {
712 ntfs_error(vol->sb, "Invalid arguments.");
713 return ERR_PTR(-EINVAL);
714 }
715#endif
716 /* Start at vcn = lowest_vcn and lcn 0. */
717 vcn = sle64_to_cpu(attr->data.non_resident.lowest_vcn);
718 lcn = 0;
719 /* Get start of the mapping pairs array. */
720 buf = (u8*)attr + le16_to_cpu(
721 attr->data.non_resident.mapping_pairs_offset);
722 attr_end = (u8*)attr + le32_to_cpu(attr->length);
723 if (unlikely(buf < (u8*)attr || buf > attr_end)) {
724 ntfs_error(vol->sb, "Corrupt attribute.");
725 return ERR_PTR(-EIO);
726 }
727 /* Current position in runlist array. */
728 rlpos = 0;
729 /* Allocate first page and set current runlist size to one page. */
730 rl = ntfs_malloc_nofs(rlsize = PAGE_SIZE);
731 if (unlikely(!rl))
732 return ERR_PTR(-ENOMEM);
733 /* Insert unmapped starting element if necessary. */
734 if (vcn) {
735 rl->vcn = 0;
736 rl->lcn = LCN_RL_NOT_MAPPED;
737 rl->length = vcn;
738 rlpos++;
739 }
740 while (buf < attr_end && *buf) {
741 /*
742 * Allocate more memory if needed, including space for the
743 * not-mapped and terminator elements. ntfs_malloc_nofs()
744 * operates on whole pages only.
745 */
746 if (((rlpos + 3) * sizeof(*old_rl)) > rlsize) {
747 runlist_element *rl2;
748
749 rl2 = ntfs_malloc_nofs(rlsize + (int)PAGE_SIZE);
750 if (unlikely(!rl2)) {
751 ntfs_free(rl);
752 return ERR_PTR(-ENOMEM);
753 }
754 memcpy(rl2, rl, rlsize);
755 ntfs_free(rl);
756 rl = rl2;
757 rlsize += PAGE_SIZE;
758 }
759 /* Enter the current vcn into the current runlist element. */
760 rl[rlpos].vcn = vcn;
761 /*
762 * Get the change in vcn, i.e. the run length in clusters.
763 * Doing it this way ensures that we signextend negative values.
764 * A negative run length doesn't make any sense, but hey, I
765 * didn't make up the NTFS specs and Windows NT4 treats the run
766 * length as a signed value so that's how it is...
767 */
768 b = *buf & 0xf;
769 if (b) {
770 if (unlikely(buf + b > attr_end))
771 goto io_error;
772 for (deltaxcn = (s8)buf[b--]; b; b--)
773 deltaxcn = (deltaxcn << 8) + buf[b];
774 } else { /* The length entry is compulsory. */
775 ntfs_error(vol->sb, "Missing length entry in mapping "
776 "pairs array.");
777 deltaxcn = (s64)-1;
778 }
779 /*
780 * Assume a negative length to indicate data corruption and
781 * hence clean-up and return NULL.
782 */
783 if (unlikely(deltaxcn < 0)) {
784 ntfs_error(vol->sb, "Invalid length in mapping pairs "
785 "array.");
786 goto err_out;
787 }
788 /*
789 * Enter the current run length into the current runlist
790 * element.
791 */
792 rl[rlpos].length = deltaxcn;
793 /* Increment the current vcn by the current run length. */
794 vcn += deltaxcn;
795 /*
796 * There might be no lcn change at all, as is the case for
797 * sparse clusters on NTFS 3.0+, in which case we set the lcn
798 * to LCN_HOLE.
799 */
800 if (!(*buf & 0xf0))
801 rl[rlpos].lcn = LCN_HOLE;
802 else {
803 /* Get the lcn change which really can be negative. */
804 u8 b2 = *buf & 0xf;
805 b = b2 + ((*buf >> 4) & 0xf);
806 if (buf + b > attr_end)
807 goto io_error;
808 for (deltaxcn = (s8)buf[b--]; b > b2; b--)
809 deltaxcn = (deltaxcn << 8) + buf[b];
810 /* Change the current lcn to its new value. */
811 lcn += deltaxcn;
812#ifdef DEBUG
813 /*
814 * On NTFS 1.2-, apparently can have lcn == -1 to
815 * indicate a hole. But we haven't verified ourselves
816 * whether it is really the lcn or the deltaxcn that is
817 * -1. So if either is found give us a message so we
818 * can investigate it further!
819 */
820 if (vol->major_ver < 3) {
821 if (unlikely(deltaxcn == (LCN)-1))
822 ntfs_error(vol->sb, "lcn delta == -1");
823 if (unlikely(lcn == (LCN)-1))
824 ntfs_error(vol->sb, "lcn == -1");
825 }
826#endif
827 /* Check lcn is not below -1. */
828 if (unlikely(lcn < (LCN)-1)) {
829 ntfs_error(vol->sb, "Invalid LCN < -1 in "
830 "mapping pairs array.");
831 goto err_out;
832 }
833 /* Enter the current lcn into the runlist element. */
834 rl[rlpos].lcn = lcn;
835 }
836 /* Get to the next runlist element. */
837 rlpos++;
838 /* Increment the buffer position to the next mapping pair. */
839 buf += (*buf & 0xf) + ((*buf >> 4) & 0xf) + 1;
840 }
841 if (unlikely(buf >= attr_end))
842 goto io_error;
843 /*
844 * If there is a highest_vcn specified, it must be equal to the final
845 * vcn in the runlist - 1, or something has gone badly wrong.
846 */
847 deltaxcn = sle64_to_cpu(attr->data.non_resident.highest_vcn);
848 if (unlikely(deltaxcn && vcn - 1 != deltaxcn)) {
849mpa_err:
850 ntfs_error(vol->sb, "Corrupt mapping pairs array in "
851 "non-resident attribute.");
852 goto err_out;
853 }
854 /* Setup not mapped runlist element if this is the base extent. */
855 if (!attr->data.non_resident.lowest_vcn) {
856 VCN max_cluster;
857
Anton Altaparmakov1a0df152005-02-03 12:04:36 +0000858 max_cluster = ((sle64_to_cpu(
Linus Torvalds1da177e2005-04-16 15:20:36 -0700859 attr->data.non_resident.allocated_size) +
860 vol->cluster_size - 1) >>
Anton Altaparmakov1a0df152005-02-03 12:04:36 +0000861 vol->cluster_size_bits) - 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700862 /*
Anton Altaparmakov1a0df152005-02-03 12:04:36 +0000863 * A highest_vcn of zero means this is a single extent
864 * attribute so simply terminate the runlist with LCN_ENOENT).
Linus Torvalds1da177e2005-04-16 15:20:36 -0700865 */
Anton Altaparmakov1a0df152005-02-03 12:04:36 +0000866 if (deltaxcn) {
867 /*
868 * If there is a difference between the highest_vcn and
869 * the highest cluster, the runlist is either corrupt
870 * or, more likely, there are more extents following
871 * this one.
872 */
873 if (deltaxcn < max_cluster) {
874 ntfs_debug("More extents to follow; deltaxcn "
875 "= 0x%llx, max_cluster = "
876 "0x%llx",
877 (unsigned long long)deltaxcn,
878 (unsigned long long)
879 max_cluster);
880 rl[rlpos].vcn = vcn;
881 vcn += rl[rlpos].length = max_cluster -
882 deltaxcn;
883 rl[rlpos].lcn = LCN_RL_NOT_MAPPED;
884 rlpos++;
885 } else if (unlikely(deltaxcn > max_cluster)) {
886 ntfs_error(vol->sb, "Corrupt attribute. "
887 "deltaxcn = 0x%llx, "
888 "max_cluster = 0x%llx",
889 (unsigned long long)deltaxcn,
890 (unsigned long long)
891 max_cluster);
892 goto mpa_err;
893 }
Linus Torvalds1da177e2005-04-16 15:20:36 -0700894 }
895 rl[rlpos].lcn = LCN_ENOENT;
896 } else /* Not the base extent. There may be more extents to follow. */
897 rl[rlpos].lcn = LCN_RL_NOT_MAPPED;
898
899 /* Setup terminating runlist element. */
900 rl[rlpos].vcn = vcn;
901 rl[rlpos].length = (s64)0;
902 /* If no existing runlist was specified, we are done. */
903 if (!old_rl) {
904 ntfs_debug("Mapping pairs array successfully decompressed:");
905 ntfs_debug_dump_runlist(rl);
906 return rl;
907 }
908 /* Now combine the new and old runlists checking for overlaps. */
909 old_rl = ntfs_runlists_merge(old_rl, rl);
910 if (likely(!IS_ERR(old_rl)))
911 return old_rl;
912 ntfs_free(rl);
913 ntfs_error(vol->sb, "Failed to merge runlists.");
914 return old_rl;
915io_error:
916 ntfs_error(vol->sb, "Corrupt attribute.");
917err_out:
918 ntfs_free(rl);
919 return ERR_PTR(-EIO);
920}
921
922/**
923 * ntfs_rl_vcn_to_lcn - convert a vcn into a lcn given a runlist
924 * @rl: runlist to use for conversion
925 * @vcn: vcn to convert
926 *
927 * Convert the virtual cluster number @vcn of an attribute into a logical
928 * cluster number (lcn) of a device using the runlist @rl to map vcns to their
929 * corresponding lcns.
930 *
931 * It is up to the caller to serialize access to the runlist @rl.
932 *
933 * Since lcns must be >= 0, we use negative return values with special meaning:
934 *
935 * Return value Meaning / Description
936 * ==================================================
937 * -1 = LCN_HOLE Hole / not allocated on disk.
938 * -2 = LCN_RL_NOT_MAPPED This is part of the runlist which has not been
939 * inserted into the runlist yet.
940 * -3 = LCN_ENOENT There is no such vcn in the attribute.
941 *
942 * Locking: - The caller must have locked the runlist (for reading or writing).
943 * - This function does not touch the lock.
944 */
945LCN ntfs_rl_vcn_to_lcn(const runlist_element *rl, const VCN vcn)
946{
947 int i;
948
949 BUG_ON(vcn < 0);
950 /*
951 * If rl is NULL, assume that we have found an unmapped runlist. The
952 * caller can then attempt to map it and fail appropriately if
953 * necessary.
954 */
955 if (unlikely(!rl))
956 return LCN_RL_NOT_MAPPED;
957
958 /* Catch out of lower bounds vcn. */
959 if (unlikely(vcn < rl[0].vcn))
960 return LCN_ENOENT;
961
962 for (i = 0; likely(rl[i].length); i++) {
963 if (unlikely(vcn < rl[i+1].vcn)) {
964 if (likely(rl[i].lcn >= (LCN)0))
965 return rl[i].lcn + (vcn - rl[i].vcn);
966 return rl[i].lcn;
967 }
968 }
969 /*
970 * The terminator element is setup to the correct value, i.e. one of
971 * LCN_HOLE, LCN_RL_NOT_MAPPED, or LCN_ENOENT.
972 */
973 if (likely(rl[i].lcn < (LCN)0))
974 return rl[i].lcn;
975 /* Just in case... We could replace this with BUG() some day. */
976 return LCN_ENOENT;
977}
978
979/**
980 * ntfs_get_nr_significant_bytes - get number of bytes needed to store a number
981 * @n: number for which to get the number of bytes for
982 *
983 * Return the number of bytes required to store @n unambiguously as
984 * a signed number.
985 *
986 * This is used in the context of the mapping pairs array to determine how
987 * many bytes will be needed in the array to store a given logical cluster
988 * number (lcn) or a specific run length.
989 *
990 * Return the number of bytes written. This function cannot fail.
991 */
992static inline int ntfs_get_nr_significant_bytes(const s64 n)
993{
994 s64 l = n;
995 int i;
996 s8 j;
997
998 i = 0;
999 do {
1000 l >>= 8;
1001 i++;
1002 } while (l != 0 && l != -1);
1003 j = (n >> 8 * (i - 1)) & 0xff;
1004 /* If the sign bit is wrong, we need an extra byte. */
1005 if ((n < 0 && j >= 0) || (n > 0 && j < 0))
1006 i++;
1007 return i;
1008}
1009
1010/**
1011 * ntfs_get_size_for_mapping_pairs - get bytes needed for mapping pairs array
1012 * @vol: ntfs volume (needed for the ntfs version)
1013 * @rl: locked runlist to determine the size of the mapping pairs of
1014 * @start_vcn: vcn at which to start the mapping pairs array
1015 *
1016 * Walk the locked runlist @rl and calculate the size in bytes of the mapping
1017 * pairs array corresponding to the runlist @rl, starting at vcn @start_vcn.
1018 * This for example allows us to allocate a buffer of the right size when
1019 * building the mapping pairs array.
1020 *
1021 * If @rl is NULL, just return 1 (for the single terminator byte).
1022 *
1023 * Return the calculated size in bytes on success. On error, return -errno.
1024 * The following error codes are defined:
1025 * -EINVAL - Run list contains unmapped elements. Make sure to only pass
1026 * fully mapped runlists to this function.
1027 * -EIO - The runlist is corrupt.
1028 *
1029 * Locking: @rl must be locked on entry (either for reading or writing), it
1030 * remains locked throughout, and is left locked upon return.
1031 */
1032int ntfs_get_size_for_mapping_pairs(const ntfs_volume *vol,
1033 const runlist_element *rl, const VCN start_vcn)
1034{
1035 LCN prev_lcn;
1036 int rls;
1037
1038 BUG_ON(start_vcn < 0);
1039 if (!rl) {
1040 BUG_ON(start_vcn);
1041 return 1;
1042 }
1043 /* Skip to runlist element containing @start_vcn. */
1044 while (rl->length && start_vcn >= rl[1].vcn)
1045 rl++;
1046 if ((!rl->length && start_vcn > rl->vcn) || start_vcn < rl->vcn)
1047 return -EINVAL;
1048 prev_lcn = 0;
1049 /* Always need the termining zero byte. */
1050 rls = 1;
1051 /* Do the first partial run if present. */
1052 if (start_vcn > rl->vcn) {
1053 s64 delta;
1054
1055 /* We know rl->length != 0 already. */
1056 if (rl->length < 0 || rl->lcn < LCN_HOLE)
1057 goto err_out;
1058 delta = start_vcn - rl->vcn;
1059 /* Header byte + length. */
1060 rls += 1 + ntfs_get_nr_significant_bytes(rl->length - delta);
1061 /*
1062 * If the logical cluster number (lcn) denotes a hole and we
1063 * are on NTFS 3.0+, we don't store it at all, i.e. we need
1064 * zero space. On earlier NTFS versions we just store the lcn.
1065 * Note: this assumes that on NTFS 1.2-, holes are stored with
1066 * an lcn of -1 and not a delta_lcn of -1 (unless both are -1).
1067 */
1068 if (rl->lcn >= 0 || vol->major_ver < 3) {
1069 prev_lcn = rl->lcn;
1070 if (rl->lcn >= 0)
1071 prev_lcn += delta;
1072 /* Change in lcn. */
1073 rls += ntfs_get_nr_significant_bytes(prev_lcn);
1074 }
1075 /* Go to next runlist element. */
1076 rl++;
1077 }
1078 /* Do the full runs. */
1079 for (; rl->length; rl++) {
1080 if (rl->length < 0 || rl->lcn < LCN_HOLE)
1081 goto err_out;
1082 /* Header byte + length. */
1083 rls += 1 + ntfs_get_nr_significant_bytes(rl->length);
1084 /*
1085 * If the logical cluster number (lcn) denotes a hole and we
1086 * are on NTFS 3.0+, we don't store it at all, i.e. we need
1087 * zero space. On earlier NTFS versions we just store the lcn.
1088 * Note: this assumes that on NTFS 1.2-, holes are stored with
1089 * an lcn of -1 and not a delta_lcn of -1 (unless both are -1).
1090 */
1091 if (rl->lcn >= 0 || vol->major_ver < 3) {
1092 /* Change in lcn. */
1093 rls += ntfs_get_nr_significant_bytes(rl->lcn -
1094 prev_lcn);
1095 prev_lcn = rl->lcn;
1096 }
1097 }
1098 return rls;
1099err_out:
1100 if (rl->lcn == LCN_RL_NOT_MAPPED)
1101 rls = -EINVAL;
1102 else
1103 rls = -EIO;
1104 return rls;
1105}
1106
1107/**
1108 * ntfs_write_significant_bytes - write the significant bytes of a number
1109 * @dst: destination buffer to write to
1110 * @dst_max: pointer to last byte of destination buffer for bounds checking
1111 * @n: number whose significant bytes to write
1112 *
1113 * Store in @dst, the minimum bytes of the number @n which are required to
1114 * identify @n unambiguously as a signed number, taking care not to exceed
1115 * @dest_max, the maximum position within @dst to which we are allowed to
1116 * write.
1117 *
1118 * This is used when building the mapping pairs array of a runlist to compress
1119 * a given logical cluster number (lcn) or a specific run length to the minumum
1120 * size possible.
1121 *
1122 * Return the number of bytes written on success. On error, i.e. the
1123 * destination buffer @dst is too small, return -ENOSPC.
1124 */
1125static inline int ntfs_write_significant_bytes(s8 *dst, const s8 *dst_max,
1126 const s64 n)
1127{
1128 s64 l = n;
1129 int i;
1130 s8 j;
1131
1132 i = 0;
1133 do {
1134 if (dst > dst_max)
1135 goto err_out;
1136 *dst++ = l & 0xffll;
1137 l >>= 8;
1138 i++;
1139 } while (l != 0 && l != -1);
1140 j = (n >> 8 * (i - 1)) & 0xff;
1141 /* If the sign bit is wrong, we need an extra byte. */
1142 if (n < 0 && j >= 0) {
1143 if (dst > dst_max)
1144 goto err_out;
1145 i++;
1146 *dst = (s8)-1;
1147 } else if (n > 0 && j < 0) {
1148 if (dst > dst_max)
1149 goto err_out;
1150 i++;
1151 *dst = (s8)0;
1152 }
1153 return i;
1154err_out:
1155 return -ENOSPC;
1156}
1157
1158/**
1159 * ntfs_mapping_pairs_build - build the mapping pairs array from a runlist
1160 * @vol: ntfs volume (needed for the ntfs version)
1161 * @dst: destination buffer to which to write the mapping pairs array
1162 * @dst_len: size of destination buffer @dst in bytes
1163 * @rl: locked runlist for which to build the mapping pairs array
1164 * @start_vcn: vcn at which to start the mapping pairs array
1165 * @stop_vcn: first vcn outside destination buffer on success or -ENOSPC
1166 *
1167 * Create the mapping pairs array from the locked runlist @rl, starting at vcn
1168 * @start_vcn and save the array in @dst. @dst_len is the size of @dst in
1169 * bytes and it should be at least equal to the value obtained by calling
1170 * ntfs_get_size_for_mapping_pairs().
1171 *
1172 * If @rl is NULL, just write a single terminator byte to @dst.
1173 *
1174 * On success or -ENOSPC error, if @stop_vcn is not NULL, *@stop_vcn is set to
1175 * the first vcn outside the destination buffer. Note that on error, @dst has
1176 * been filled with all the mapping pairs that will fit, thus it can be treated
1177 * as partial success, in that a new attribute extent needs to be created or
1178 * the next extent has to be used and the mapping pairs build has to be
1179 * continued with @start_vcn set to *@stop_vcn.
1180 *
1181 * Return 0 on success and -errno on error. The following error codes are
1182 * defined:
1183 * -EINVAL - Run list contains unmapped elements. Make sure to only pass
1184 * fully mapped runlists to this function.
1185 * -EIO - The runlist is corrupt.
1186 * -ENOSPC - The destination buffer is too small.
1187 *
1188 * Locking: @rl must be locked on entry (either for reading or writing), it
1189 * remains locked throughout, and is left locked upon return.
1190 */
1191int ntfs_mapping_pairs_build(const ntfs_volume *vol, s8 *dst,
1192 const int dst_len, const runlist_element *rl,
1193 const VCN start_vcn, VCN *const stop_vcn)
1194{
1195 LCN prev_lcn;
1196 s8 *dst_max, *dst_next;
1197 int err = -ENOSPC;
1198 s8 len_len, lcn_len;
1199
1200 BUG_ON(start_vcn < 0);
1201 BUG_ON(dst_len < 1);
1202 if (!rl) {
1203 BUG_ON(start_vcn);
1204 if (stop_vcn)
1205 *stop_vcn = 0;
1206 /* Terminator byte. */
1207 *dst = 0;
1208 return 0;
1209 }
1210 /* Skip to runlist element containing @start_vcn. */
1211 while (rl->length && start_vcn >= rl[1].vcn)
1212 rl++;
1213 if ((!rl->length && start_vcn > rl->vcn) || start_vcn < rl->vcn)
1214 return -EINVAL;
1215 /*
1216 * @dst_max is used for bounds checking in
1217 * ntfs_write_significant_bytes().
1218 */
1219 dst_max = dst + dst_len - 1;
1220 prev_lcn = 0;
1221 /* Do the first partial run if present. */
1222 if (start_vcn > rl->vcn) {
1223 s64 delta;
1224
1225 /* We know rl->length != 0 already. */
1226 if (rl->length < 0 || rl->lcn < LCN_HOLE)
1227 goto err_out;
1228 delta = start_vcn - rl->vcn;
1229 /* Write length. */
1230 len_len = ntfs_write_significant_bytes(dst + 1, dst_max,
1231 rl->length - delta);
1232 if (len_len < 0)
1233 goto size_err;
1234 /*
1235 * If the logical cluster number (lcn) denotes a hole and we
1236 * are on NTFS 3.0+, we don't store it at all, i.e. we need
1237 * zero space. On earlier NTFS versions we just write the lcn
1238 * change. FIXME: Do we need to write the lcn change or just
1239 * the lcn in that case? Not sure as I have never seen this
1240 * case on NT4. - We assume that we just need to write the lcn
1241 * change until someone tells us otherwise... (AIA)
1242 */
1243 if (rl->lcn >= 0 || vol->major_ver < 3) {
1244 prev_lcn = rl->lcn;
1245 if (rl->lcn >= 0)
1246 prev_lcn += delta;
1247 /* Write change in lcn. */
1248 lcn_len = ntfs_write_significant_bytes(dst + 1 +
1249 len_len, dst_max, prev_lcn);
1250 if (lcn_len < 0)
1251 goto size_err;
1252 } else
1253 lcn_len = 0;
1254 dst_next = dst + len_len + lcn_len + 1;
1255 if (dst_next > dst_max)
1256 goto size_err;
1257 /* Update header byte. */
1258 *dst = lcn_len << 4 | len_len;
1259 /* Position at next mapping pairs array element. */
1260 dst = dst_next;
1261 /* Go to next runlist element. */
1262 rl++;
1263 }
1264 /* Do the full runs. */
1265 for (; rl->length; rl++) {
1266 if (rl->length < 0 || rl->lcn < LCN_HOLE)
1267 goto err_out;
1268 /* Write length. */
1269 len_len = ntfs_write_significant_bytes(dst + 1, dst_max,
1270 rl->length);
1271 if (len_len < 0)
1272 goto size_err;
1273 /*
1274 * If the logical cluster number (lcn) denotes a hole and we
1275 * are on NTFS 3.0+, we don't store it at all, i.e. we need
1276 * zero space. On earlier NTFS versions we just write the lcn
1277 * change. FIXME: Do we need to write the lcn change or just
1278 * the lcn in that case? Not sure as I have never seen this
1279 * case on NT4. - We assume that we just need to write the lcn
1280 * change until someone tells us otherwise... (AIA)
1281 */
1282 if (rl->lcn >= 0 || vol->major_ver < 3) {
1283 /* Write change in lcn. */
1284 lcn_len = ntfs_write_significant_bytes(dst + 1 +
1285 len_len, dst_max, rl->lcn - prev_lcn);
1286 if (lcn_len < 0)
1287 goto size_err;
1288 prev_lcn = rl->lcn;
1289 } else
1290 lcn_len = 0;
1291 dst_next = dst + len_len + lcn_len + 1;
1292 if (dst_next > dst_max)
1293 goto size_err;
1294 /* Update header byte. */
1295 *dst = lcn_len << 4 | len_len;
1296 /* Position at next mapping pairs array element. */
1297 dst = dst_next;
1298 }
1299 /* Success. */
1300 err = 0;
1301size_err:
1302 /* Set stop vcn. */
1303 if (stop_vcn)
1304 *stop_vcn = rl->vcn;
1305 /* Add terminator byte. */
1306 *dst = 0;
1307 return err;
1308err_out:
1309 if (rl->lcn == LCN_RL_NOT_MAPPED)
1310 err = -EINVAL;
1311 else
1312 err = -EIO;
1313 return err;
1314}
1315
1316/**
1317 * ntfs_rl_truncate_nolock - truncate a runlist starting at a specified vcn
1318 * @runlist: runlist to truncate
1319 * @new_length: the new length of the runlist in VCNs
1320 *
1321 * Truncate the runlist described by @runlist as well as the memory buffer
1322 * holding the runlist elements to a length of @new_length VCNs.
1323 *
1324 * If @new_length lies within the runlist, the runlist elements with VCNs of
1325 * @new_length and above are discarded.
1326 *
1327 * If @new_length lies beyond the runlist, a sparse runlist element is added to
1328 * the end of the runlist @runlist or if the last runlist element is a sparse
1329 * one already, this is extended.
1330 *
1331 * Return 0 on success and -errno on error.
1332 *
1333 * Locking: The caller must hold @runlist->lock for writing.
1334 */
1335int ntfs_rl_truncate_nolock(const ntfs_volume *vol, runlist *const runlist,
1336 const s64 new_length)
1337{
1338 runlist_element *rl;
1339 int old_size;
1340
1341 ntfs_debug("Entering for new_length 0x%llx.", (long long)new_length);
1342 BUG_ON(!runlist);
1343 BUG_ON(new_length < 0);
1344 rl = runlist->rl;
1345 if (unlikely(!rl)) {
1346 /*
1347 * Create a runlist consisting of a sparse runlist element of
1348 * length @new_length followed by a terminator runlist element.
1349 */
1350 rl = ntfs_malloc_nofs(PAGE_SIZE);
1351 if (unlikely(!rl)) {
1352 ntfs_error(vol->sb, "Not enough memory to allocate "
1353 "runlist element buffer.");
1354 return -ENOMEM;
1355 }
1356 runlist->rl = rl;
1357 rl[1].length = rl->vcn = 0;
1358 rl->lcn = LCN_HOLE;
1359 rl[1].vcn = rl->length = new_length;
1360 rl[1].lcn = LCN_ENOENT;
1361 return 0;
1362 }
1363 BUG_ON(new_length < rl->vcn);
1364 /* Find @new_length in the runlist. */
1365 while (likely(rl->length && new_length >= rl[1].vcn))
1366 rl++;
1367 /*
1368 * If not at the end of the runlist we need to shrink it.
1369 * If at the end of the runlist we need to expand it.
1370 */
1371 if (rl->length) {
1372 runlist_element *trl;
1373 BOOL is_end;
1374
1375 ntfs_debug("Shrinking runlist.");
1376 /* Determine the runlist size. */
1377 trl = rl + 1;
1378 while (likely(trl->length))
1379 trl++;
1380 old_size = trl - runlist->rl + 1;
1381 /* Truncate the run. */
1382 rl->length = new_length - rl->vcn;
1383 /*
1384 * If a run was partially truncated, make the following runlist
1385 * element a terminator.
1386 */
1387 is_end = FALSE;
1388 if (rl->length) {
1389 rl++;
1390 if (!rl->length)
1391 is_end = TRUE;
1392 rl->vcn = new_length;
1393 rl->length = 0;
1394 }
1395 rl->lcn = LCN_ENOENT;
1396 /* Reallocate memory if necessary. */
1397 if (!is_end) {
1398 int new_size = rl - runlist->rl + 1;
1399 rl = ntfs_rl_realloc(runlist->rl, old_size, new_size);
1400 if (IS_ERR(rl))
1401 ntfs_warning(vol->sb, "Failed to shrink "
1402 "runlist buffer. This just "
1403 "wastes a bit of memory "
1404 "temporarily so we ignore it "
1405 "and return success.");
1406 else
1407 runlist->rl = rl;
1408 }
1409 } else if (likely(/* !rl->length && */ new_length > rl->vcn)) {
1410 ntfs_debug("Expanding runlist.");
1411 /*
1412 * If there is a previous runlist element and it is a sparse
1413 * one, extend it. Otherwise need to add a new, sparse runlist
1414 * element.
1415 */
1416 if ((rl > runlist->rl) && ((rl - 1)->lcn == LCN_HOLE))
1417 (rl - 1)->length = new_length - (rl - 1)->vcn;
1418 else {
1419 /* Determine the runlist size. */
1420 old_size = rl - runlist->rl + 1;
1421 /* Reallocate memory if necessary. */
1422 rl = ntfs_rl_realloc(runlist->rl, old_size,
1423 old_size + 1);
1424 if (IS_ERR(rl)) {
1425 ntfs_error(vol->sb, "Failed to expand runlist "
1426 "buffer, aborting.");
1427 return PTR_ERR(rl);
1428 }
1429 runlist->rl = rl;
1430 /*
1431 * Set @rl to the same runlist element in the new
1432 * runlist as before in the old runlist.
1433 */
1434 rl += old_size - 1;
1435 /* Add a new, sparse runlist element. */
1436 rl->lcn = LCN_HOLE;
1437 rl->length = new_length - rl->vcn;
1438 /* Add a new terminator runlist element. */
1439 rl++;
1440 rl->length = 0;
1441 }
1442 rl->vcn = new_length;
1443 rl->lcn = LCN_ENOENT;
1444 } else /* if (unlikely(!rl->length && new_length == rl->vcn)) */ {
1445 /* Runlist already has same size as requested. */
1446 rl->lcn = LCN_ENOENT;
1447 }
1448 ntfs_debug("Done.");
1449 return 0;
1450}