merge ROS Shell without integrated explorer part into trunk
[reactos.git] / reactos / drivers / fs / ntfs / linux-ntfs / attrib.c
1 /**
2 * attrib.c - NTFS attribute operations. Part of the Linux-NTFS project.
3 *
4 * Copyright (c) 2001-2003 Anton Altaparmakov
5 * 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 <linux/buffer_head.h>
24 #include "ntfs.h"
25 #include "dir.h"
26
27 /* Temporary helper functions -- might become macros */
28
29 /**
30 * ntfs_rl_mm - run_list memmove
31 *
32 * It is up to the caller to serialize access to the run list @base.
33 */
34 static inline void ntfs_rl_mm(run_list_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 - run_list memory copy
43 *
44 * It is up to the caller to serialize access to the run lists @dstbase and
45 * @srcbase.
46 */
47 static inline void ntfs_rl_mc(run_list_element *dstbase, int dst,
48 run_list_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 run_lists
56 * @rl: original run list
57 * @old_size: number of run list elements in the original run list @rl
58 * @new_size: number of run list elements we need space for
59 *
60 * As the run_lists grow, more memory will be required. To prevent the
61 * kernel having to allocate and reallocate large numbers of small bits of
62 * memory, this function returns and entire page of memory.
63 *
64 * It is up to the caller to serialize access to the run list @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 run list array.
72 * -EINVAL - Invalid parameters were passed in.
73 */
74 static inline run_list_element *ntfs_rl_realloc(run_list_element *rl,
75 int old_size, int new_size)
76 {
77 run_list_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 run lists can be joined together
99 * @dst: original run list
100 * @src: new run list to test for mergeability with @dst
101 *
102 * Test if two run lists 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 run lists @dst and @src.
106 *
107 * Return: TRUE Success, the run lists can be merged.
108 * FALSE Failure, the run lists cannot be merged.
109 */
110 static inline BOOL ntfs_are_rl_mergeable(run_list_element *dst,
111 run_list_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 run lists without testing if they can be merged
128 * @dst: original, destination run list
129 * @src: new run list to merge with @dst
130 *
131 * Merge the two run lists, writing into the destination run list @dst. The
132 * caller must make sure the run lists can be merged or this will corrupt the
133 * destination run list.
134 *
135 * It is up to the caller to serialize access to the run lists @dst and @src.
136 */
137 static inline void __ntfs_rl_merge(run_list_element *dst, run_list_element *src)
138 {
139 dst->length += src->length;
140 }
141
142 /**
143 * ntfs_rl_merge - test if two run lists can be joined together and merge them
144 * @dst: original, destination run list
145 * @src: new run list to merge with @dst
146 *
147 * Test if two run lists can be joined together. For this, their VCNs and LCNs
148 * must be adjacent. If they can be merged, perform the merge, writing into
149 * the destination run list @dst.
150 *
151 * It is up to the caller to serialize access to the run lists @dst and @src.
152 *
153 * Return: TRUE Success, the run lists have been merged.
154 * FALSE Failure, the run lists cannot be merged and have not been
155 * modified.
156 */
157 static inline BOOL ntfs_rl_merge(run_list_element *dst, run_list_element *src)
158 {
159 BOOL merge = ntfs_are_rl_mergeable(dst, src);
160
161 if (merge)
162 __ntfs_rl_merge(dst, src);
163 return merge;
164 }
165
166 /**
167 * ntfs_rl_append - append a run list after a given element
168 * @dst: original run list to be worked on
169 * @dsize: number of elements in @dst (including end marker)
170 * @src: run list to be inserted into @dst
171 * @ssize: number of elements in @src (excluding end marker)
172 * @loc: append the new run list @src after this element in @dst
173 *
174 * Append the run list @src after element @loc in @dst. Merge the right end of
175 * the new run list, if necessary. Adjust the size of the hole before the
176 * appended run list.
177 *
178 * It is up to the caller to serialize access to the run lists @dst and @src.
179 *
180 * On success, return a pointer to the new, combined, run list. Note, both
181 * run lists @dst and @src are deallocated before returning so you cannot use
182 * the pointers for anything any more. (Strictly speaking the returned run list
183 * may be the same as @dst but this is irrelevant.)
184 *
185 * On error, return -errno. Both run lists are left unmodified. The following
186 * error codes are defined:
187 * -ENOMEM - Not enough memory to allocate run list array.
188 * -EINVAL - Invalid parameters were passed in.
189 */
190 static inline run_list_element *ntfs_rl_append(run_list_element *dst,
191 int dsize, run_list_element *src, int ssize, int loc)
192 {
193 BOOL right;
194 int magic;
195
196 BUG_ON(!dst);
197 BUG_ON(!src);
198
199 /* First, check if the right hand end needs merging. */
200 right = ntfs_are_rl_mergeable(src + ssize - 1, dst + loc + 1);
201
202 /* Space required: @dst size + @src size, less one if we merged. */
203 dst = ntfs_rl_realloc(dst, dsize, dsize + ssize - right);
204 if (IS_ERR(dst))
205 return dst;
206 /*
207 * We are guaranteed to succeed from here so can start modifying the
208 * original run lists.
209 */
210
211 /* First, merge the right hand end, if necessary. */
212 if (right)
213 __ntfs_rl_merge(src + ssize - 1, dst + loc + 1);
214
215 magic = loc + ssize;
216
217 /* Move the tail of @dst out of the way, then copy in @src. */
218 ntfs_rl_mm(dst, magic + 1, loc + 1 + right, dsize - loc - 1 - right);
219 ntfs_rl_mc(dst, loc + 1, src, 0, ssize);
220
221 /* Adjust the size of the preceding hole. */
222 dst[loc].length = dst[loc + 1].vcn - dst[loc].vcn;
223
224 /* We may have changed the length of the file, so fix the end marker */
225 if (dst[magic + 1].lcn == LCN_ENOENT)
226 dst[magic + 1].vcn = dst[magic].vcn + dst[magic].length;
227
228 return dst;
229 }
230
231 /**
232 * ntfs_rl_insert - insert a run list into another
233 * @dst: original run list to be worked on
234 * @dsize: number of elements in @dst (including end marker)
235 * @src: new run list to be inserted
236 * @ssize: number of elements in @src (excluding end marker)
237 * @loc: insert the new run list @src before this element in @dst
238 *
239 * Insert the run list @src before element @loc in the run list @dst. Merge the
240 * left end of the new run list, if necessary. Adjust the size of the hole
241 * after the inserted run list.
242 *
243 * It is up to the caller to serialize access to the run lists @dst and @src.
244 *
245 * On success, return a pointer to the new, combined, run list. Note, both
246 * run lists @dst and @src are deallocated before returning so you cannot use
247 * the pointers for anything any more. (Strictly speaking the returned run list
248 * may be the same as @dst but this is irrelevant.)
249 *
250 * On error, return -errno. Both run lists are left unmodified. The following
251 * error codes are defined:
252 * -ENOMEM - Not enough memory to allocate run list array.
253 * -EINVAL - Invalid parameters were passed in.
254 */
255 static inline run_list_element *ntfs_rl_insert(run_list_element *dst,
256 int dsize, run_list_element *src, int ssize, int loc)
257 {
258 BOOL left = FALSE;
259 BOOL disc = FALSE; /* Discontinuity */
260 BOOL hole = FALSE; /* Following a hole */
261 int magic;
262
263 BUG_ON(!dst);
264 BUG_ON(!src);
265
266 /* disc => Discontinuity between the end of @dst and the start of @src.
267 * This means we might need to insert a hole.
268 * hole => @dst ends with a hole or an unmapped region which we can
269 * extend to match the discontinuity. */
270 if (loc == 0)
271 disc = (src[0].vcn > 0);
272 else {
273 s64 merged_length;
274
275 left = ntfs_are_rl_mergeable(dst + loc - 1, src);
276
277 merged_length = dst[loc - 1].length;
278 if (left)
279 merged_length += src->length;
280
281 disc = (src[0].vcn > dst[loc - 1].vcn + merged_length);
282 if (disc)
283 hole = (dst[loc - 1].lcn == LCN_HOLE);
284 }
285
286 /* Space required: @dst size + @src size, less one if we merged, plus
287 * one if there was a discontinuity, less one for a trailing hole. */
288 dst = ntfs_rl_realloc(dst, dsize, dsize + ssize - left + disc - hole);
289 if (IS_ERR(dst))
290 return dst;
291 /*
292 * We are guaranteed to succeed from here so can start modifying the
293 * original run list.
294 */
295
296 if (left)
297 __ntfs_rl_merge(dst + loc - 1, src);
298
299 magic = loc + ssize - left + disc - hole;
300
301 /* Move the tail of @dst out of the way, then copy in @src. */
302 ntfs_rl_mm(dst, magic, loc, dsize - loc);
303 ntfs_rl_mc(dst, loc + disc - hole, src, left, ssize - left);
304
305 /* Adjust the VCN of the last run ... */
306 if (dst[magic].lcn <= LCN_HOLE)
307 dst[magic].vcn = dst[magic - 1].vcn + dst[magic - 1].length;
308 /* ... and the length. */
309 if (dst[magic].lcn == LCN_HOLE || dst[magic].lcn == LCN_RL_NOT_MAPPED)
310 dst[magic].length = dst[magic + 1].vcn - dst[magic].vcn;
311
312 /* Writing beyond the end of the file and there's a discontinuity. */
313 if (disc) {
314 if (hole)
315 dst[loc - 1].length = dst[loc].vcn - dst[loc - 1].vcn;
316 else {
317 if (loc > 0) {
318 dst[loc].vcn = dst[loc - 1].vcn +
319 dst[loc - 1].length;
320 dst[loc].length = dst[loc + 1].vcn -
321 dst[loc].vcn;
322 } else {
323 dst[loc].vcn = 0;
324 dst[loc].length = dst[loc + 1].vcn;
325 }
326 dst[loc].lcn = LCN_RL_NOT_MAPPED;
327 }
328
329 magic += hole;
330
331 if (dst[magic].lcn == LCN_ENOENT)
332 dst[magic].vcn = dst[magic - 1].vcn +
333 dst[magic - 1].length;
334 }
335 return dst;
336 }
337
338 /**
339 * ntfs_rl_replace - overwrite a run_list element with another run list
340 * @dst: original run list to be worked on
341 * @dsize: number of elements in @dst (including end marker)
342 * @src: new run list to be inserted
343 * @ssize: number of elements in @src (excluding end marker)
344 * @loc: index in run list @dst to overwrite with @src
345 *
346 * Replace the run list element @dst at @loc with @src. Merge the left and
347 * right ends of the inserted run list, if necessary.
348 *
349 * It is up to the caller to serialize access to the run lists @dst and @src.
350 *
351 * On success, return a pointer to the new, combined, run list. Note, both
352 * run lists @dst and @src are deallocated before returning so you cannot use
353 * the pointers for anything any more. (Strictly speaking the returned run list
354 * may be the same as @dst but this is irrelevant.)
355 *
356 * On error, return -errno. Both run lists are left unmodified. The following
357 * error codes are defined:
358 * -ENOMEM - Not enough memory to allocate run list array.
359 * -EINVAL - Invalid parameters were passed in.
360 */
361 static inline run_list_element *ntfs_rl_replace(run_list_element *dst,
362 int dsize, run_list_element *src, int ssize, int loc)
363 {
364 BOOL left = FALSE;
365 BOOL right;
366 int magic;
367
368 BUG_ON(!dst);
369 BUG_ON(!src);
370
371 /* First, merge the left and right ends, if necessary. */
372 right = ntfs_are_rl_mergeable(src + ssize - 1, dst + loc + 1);
373 if (loc > 0)
374 left = ntfs_are_rl_mergeable(dst + loc - 1, src);
375
376 /* Allocate some space. We'll need less if the left, right, or both
377 * ends were merged. */
378 dst = ntfs_rl_realloc(dst, dsize, dsize + ssize - left - right);
379 if (IS_ERR(dst))
380 return dst;
381 /*
382 * We are guaranteed to succeed from here so can start modifying the
383 * original run lists.
384 */
385 if (right)
386 __ntfs_rl_merge(src + ssize - 1, dst + loc + 1);
387 if (left)
388 __ntfs_rl_merge(dst + loc - 1, src);
389
390 /* FIXME: What does this mean? (AIA) */
391 magic = loc + ssize - left;
392
393 /* Move the tail of @dst out of the way, then copy in @src. */
394 ntfs_rl_mm(dst, magic, loc + right + 1, dsize - loc - right - 1);
395 ntfs_rl_mc(dst, loc, src, left, ssize - left);
396
397 /* We may have changed the length of the file, so fix the end marker */
398 if (dst[magic].lcn == LCN_ENOENT)
399 dst[magic].vcn = dst[magic - 1].vcn + dst[magic - 1].length;
400 return dst;
401 }
402
403 /**
404 * ntfs_rl_split - insert a run list into the centre of a hole
405 * @dst: original run list to be worked on
406 * @dsize: number of elements in @dst (including end marker)
407 * @src: new run list to be inserted
408 * @ssize: number of elements in @src (excluding end marker)
409 * @loc: index in run list @dst at which to split and insert @src
410 *
411 * Split the run list @dst at @loc into two and insert @new in between the two
412 * fragments. No merging of run lists is necessary. Adjust the size of the
413 * holes either side.
414 *
415 * It is up to the caller to serialize access to the run lists @dst and @src.
416 *
417 * On success, return a pointer to the new, combined, run list. Note, both
418 * run lists @dst and @src are deallocated before returning so you cannot use
419 * the pointers for anything any more. (Strictly speaking the returned run list
420 * may be the same as @dst but this is irrelevant.)
421 *
422 * On error, return -errno. Both run lists are left unmodified. The following
423 * error codes are defined:
424 * -ENOMEM - Not enough memory to allocate run list array.
425 * -EINVAL - Invalid parameters were passed in.
426 */
427 static inline run_list_element *ntfs_rl_split(run_list_element *dst, int dsize,
428 run_list_element *src, int ssize, int loc)
429 {
430 BUG_ON(!dst);
431 BUG_ON(!src);
432
433 /* Space required: @dst size + @src size + one new hole. */
434 dst = ntfs_rl_realloc(dst, dsize, dsize + ssize + 1);
435 if (IS_ERR(dst))
436 return dst;
437 /*
438 * We are guaranteed to succeed from here so can start modifying the
439 * original run lists.
440 */
441
442 /* Move the tail of @dst out of the way, then copy in @src. */
443 ntfs_rl_mm(dst, loc + 1 + ssize, loc, dsize - loc);
444 ntfs_rl_mc(dst, loc + 1, src, 0, ssize);
445
446 /* Adjust the size of the holes either size of @src. */
447 dst[loc].length = dst[loc+1].vcn - dst[loc].vcn;
448 dst[loc+ssize+1].vcn = dst[loc+ssize].vcn + dst[loc+ssize].length;
449 dst[loc+ssize+1].length = dst[loc+ssize+2].vcn - dst[loc+ssize+1].vcn;
450
451 return dst;
452 }
453
454 /**
455 * ntfs_merge_run_lists - merge two run_lists into one
456 * @drl: original run list to be worked on
457 * @srl: new run list to be merged into @drl
458 *
459 * First we sanity check the two run lists @srl and @drl to make sure that they
460 * are sensible and can be merged. The run list @srl must be either after the
461 * run list @drl or completely within a hole (or unmapped region) in @drl.
462 *
463 * It is up to the caller to serialize access to the run lists @drl and @srl.
464 *
465 * Merging of run lists is necessary in two cases:
466 * 1. When attribute lists are used and a further extent is being mapped.
467 * 2. When new clusters are allocated to fill a hole or extend a file.
468 *
469 * There are four possible ways @srl can be merged. It can:
470 * - be inserted at the beginning of a hole,
471 * - split the hole in two and be inserted between the two fragments,
472 * - be appended at the end of a hole, or it can
473 * - replace the whole hole.
474 * It can also be appended to the end of the run list, which is just a variant
475 * of the insert case.
476 *
477 * On success, return a pointer to the new, combined, run list. Note, both
478 * run lists @drl and @srl are deallocated before returning so you cannot use
479 * the pointers for anything any more. (Strictly speaking the returned run list
480 * may be the same as @dst but this is irrelevant.)
481 *
482 * On error, return -errno. Both run lists are left unmodified. The following
483 * error codes are defined:
484 * -ENOMEM - Not enough memory to allocate run list array.
485 * -EINVAL - Invalid parameters were passed in.
486 * -ERANGE - The run lists overlap and cannot be merged.
487 */
488 run_list_element *ntfs_merge_run_lists(run_list_element *drl,
489 run_list_element *srl)
490 {
491 int di, si; /* Current index into @[ds]rl. */
492 int sstart; /* First index with lcn > LCN_RL_NOT_MAPPED. */
493 int dins; /* Index into @drl at which to insert @srl. */
494 int dend, send; /* Last index into @[ds]rl. */
495 int dfinal, sfinal; /* The last index into @[ds]rl with
496 lcn >= LCN_HOLE. */
497 int marker = 0;
498 VCN marker_vcn = 0;
499
500 #ifdef DEBUG
501 ntfs_debug("dst:");
502 ntfs_debug_dump_runlist(drl);
503 ntfs_debug("src:");
504 ntfs_debug_dump_runlist(srl);
505 #endif
506
507 /* Check for silly calling... */
508 if (unlikely(!srl))
509 return drl;
510 if (unlikely(IS_ERR(srl) || IS_ERR(drl)))
511 return ERR_PTR(-EINVAL);
512
513 /* Check for the case where the first mapping is being done now. */
514 if (unlikely(!drl)) {
515 drl = srl;
516 /* Complete the source run list if necessary. */
517 if (unlikely(drl[0].vcn)) {
518 /* Scan to the end of the source run list. */
519 for (dend = 0; likely(drl[dend].length); dend++)
520 ;
521 drl = ntfs_rl_realloc(drl, dend, dend + 1);
522 if (IS_ERR(drl))
523 return drl;
524 /* Insert start element at the front of the run list. */
525 ntfs_rl_mm(drl, 1, 0, dend);
526 drl[0].vcn = 0;
527 drl[0].lcn = LCN_RL_NOT_MAPPED;
528 drl[0].length = drl[1].vcn;
529 }
530 goto finished;
531 }
532
533 si = di = 0;
534
535 /* Skip any unmapped start element(s) in the source run_list. */
536 while (srl[si].length && srl[si].lcn < (LCN)LCN_HOLE)
537 si++;
538
539 /* Can't have an entirely unmapped source run list. */
540 BUG_ON(!srl[si].length);
541
542 /* Record the starting points. */
543 sstart = si;
544
545 /*
546 * Skip forward in @drl until we reach the position where @srl needs to
547 * be inserted. If we reach the end of @drl, @srl just needs to be
548 * appended to @drl.
549 */
550 for (; drl[di].length; di++) {
551 if (drl[di].vcn + drl[di].length > srl[sstart].vcn)
552 break;
553 }
554 dins = di;
555
556 /* Sanity check for illegal overlaps. */
557 if ((drl[di].vcn == srl[si].vcn) && (drl[di].lcn >= 0) &&
558 (srl[si].lcn >= 0)) {
559 ntfs_error(NULL, "Run lists overlap. Cannot merge!");
560 return ERR_PTR(-ERANGE);
561 }
562
563 /* Scan to the end of both run lists in order to know their sizes. */
564 for (send = si; srl[send].length; send++)
565 ;
566 for (dend = di; drl[dend].length; dend++)
567 ;
568
569 if (srl[send].lcn == (LCN)LCN_ENOENT)
570 marker_vcn = srl[marker = send].vcn;
571
572 /* Scan to the last element with lcn >= LCN_HOLE. */
573 for (sfinal = send; sfinal >= 0 && srl[sfinal].lcn < LCN_HOLE; sfinal--)
574 ;
575 for (dfinal = dend; dfinal >= 0 && drl[dfinal].lcn < LCN_HOLE; dfinal--)
576 ;
577
578 {
579 BOOL start;
580 BOOL finish;
581 int ds = dend + 1; /* Number of elements in drl & srl */
582 int ss = sfinal - sstart + 1;
583
584 start = ((drl[dins].lcn < LCN_RL_NOT_MAPPED) || /* End of file */
585 (drl[dins].vcn == srl[sstart].vcn)); /* Start of hole */
586 finish = ((drl[dins].lcn >= LCN_RL_NOT_MAPPED) && /* End of file */
587 ((drl[dins].vcn + drl[dins].length) <= /* End of hole */
588 (srl[send - 1].vcn + srl[send - 1].length)));
589
590 /* Or we'll lose an end marker */
591 if (start && finish && (drl[dins].length == 0))
592 ss++;
593 if (marker && (drl[dins].vcn + drl[dins].length > srl[send - 1].vcn))
594 finish = FALSE;
595 #if 0
596 ntfs_debug("dfinal = %i, dend = %i", dfinal, dend);
597 ntfs_debug("sstart = %i, sfinal = %i, send = %i", sstart, sfinal, send);
598 ntfs_debug("start = %i, finish = %i", start, finish);
599 ntfs_debug("ds = %i, ss = %i, dins = %i", ds, ss, dins);
600 #endif
601 if (start) {
602 if (finish)
603 drl = ntfs_rl_replace(drl, ds, srl + sstart, ss, dins);
604 else
605 drl = ntfs_rl_insert(drl, ds, srl + sstart, ss, dins);
606 } else {
607 if (finish)
608 drl = ntfs_rl_append(drl, ds, srl + sstart, ss, dins);
609 else
610 drl = ntfs_rl_split(drl, ds, srl + sstart, ss, dins);
611 }
612 if (IS_ERR(drl)) {
613 ntfs_error(NULL, "Merge failed.");
614 return drl;
615 }
616 ntfs_free(srl);
617 if (marker) {
618 ntfs_debug("Triggering marker code.");
619 for (ds = dend; drl[ds].length; ds++)
620 ;
621 /* We only need to care if @srl ended after @drl. */
622 if (drl[ds].vcn <= marker_vcn) {
623 int slots = 0;
624
625 if (drl[ds].vcn == marker_vcn) {
626 ntfs_debug("Old marker = 0x%Lx, replacing with "
627 "LCN_ENOENT.\n",
628 (unsigned long long)
629 drl[ds].lcn);
630 drl[ds].lcn = (LCN)LCN_ENOENT;
631 goto finished;
632 }
633 /*
634 * We need to create an unmapped run list element in
635 * @drl or extend an existing one before adding the
636 * ENOENT terminator.
637 */
638 if (drl[ds].lcn == (LCN)LCN_ENOENT) {
639 ds--;
640 slots = 1;
641 }
642 if (drl[ds].lcn != (LCN)LCN_RL_NOT_MAPPED) {
643 /* Add an unmapped run list element. */
644 if (!slots) {
645 /* FIXME/TODO: We need to have the
646 * extra memory already! (AIA) */
647 drl = ntfs_rl_realloc(drl, ds, ds + 2);
648 if (!drl)
649 goto critical_error;
650 slots = 2;
651 }
652 ds++;
653 /* Need to set vcn if it isn't set already. */
654 if (slots != 1)
655 drl[ds].vcn = drl[ds - 1].vcn +
656 drl[ds - 1].length;
657 drl[ds].lcn = (LCN)LCN_RL_NOT_MAPPED;
658 /* We now used up a slot. */
659 slots--;
660 }
661 drl[ds].length = marker_vcn - drl[ds].vcn;
662 /* Finally add the ENOENT terminator. */
663 ds++;
664 if (!slots) {
665 /* FIXME/TODO: We need to have the extra
666 * memory already! (AIA) */
667 drl = ntfs_rl_realloc(drl, ds, ds + 1);
668 if (!drl)
669 goto critical_error;
670 }
671 drl[ds].vcn = marker_vcn;
672 drl[ds].lcn = (LCN)LCN_ENOENT;
673 drl[ds].length = (s64)0;
674 }
675 }
676 }
677
678 finished:
679 /* The merge was completed successfully. */
680 ntfs_debug("Merged run list:");
681 ntfs_debug_dump_runlist(drl);
682 return drl;
683
684 critical_error:
685 /* Critical error! We cannot afford to fail here. */
686 ntfs_error(NULL, "Critical error! Not enough memory.");
687 panic("NTFS: Cannot continue.");
688 }
689
690 /**
691 * decompress_mapping_pairs - convert mapping pairs array to run list
692 * @vol: ntfs volume on which the attribute resides
693 * @attr: attribute record whose mapping pairs array to decompress
694 * @old_rl: optional run list in which to insert @attr's run list
695 *
696 * It is up to the caller to serialize access to the run list @old_rl.
697 *
698 * Decompress the attribute @attr's mapping pairs array into a run list. On
699 * success, return the decompressed run list.
700 *
701 * If @old_rl is not NULL, decompressed run list is inserted into the
702 * appropriate place in @old_rl and the resultant, combined run list is
703 * returned. The original @old_rl is deallocated.
704 *
705 * On error, return -errno. @old_rl is left unmodified in that case.
706 *
707 * The following error codes are defined:
708 * -ENOMEM - Not enough memory to allocate run list array.
709 * -EIO - Corrupt run list.
710 * -EINVAL - Invalid parameters were passed in.
711 * -ERANGE - The two run lists overlap.
712 *
713 * FIXME: For now we take the conceptionally simplest approach of creating the
714 * new run list disregarding the already existing one and then splicing the
715 * two into one, if that is possible (we check for overlap and discard the new
716 * run list if overlap present before returning ERR_PTR(-ERANGE)).
717 */
718 run_list_element *decompress_mapping_pairs(const ntfs_volume *vol,
719 const ATTR_RECORD *attr, run_list_element *old_rl)
720 {
721 VCN vcn; /* Current vcn. */
722 LCN lcn; /* Current lcn. */
723 s64 deltaxcn; /* Change in [vl]cn. */
724 run_list_element *rl; /* The output run list. */
725 u8 *buf; /* Current position in mapping pairs array. */
726 u8 *attr_end; /* End of attribute. */
727 int rlsize; /* Size of run list buffer. */
728 u16 rlpos; /* Current run list position in units of
729 run_list_elements. */
730 u8 b; /* Current byte offset in buf. */
731
732 #ifdef DEBUG
733 /* Make sure attr exists and is non-resident. */
734 if (!attr || !attr->non_resident || sle64_to_cpu(
735 attr->data.non_resident.lowest_vcn) < (VCN)0) {
736 ntfs_error(vol->sb, "Invalid arguments.");
737 return ERR_PTR(-EINVAL);
738 }
739 #endif
740 /* Start at vcn = lowest_vcn and lcn 0. */
741 vcn = sle64_to_cpu(attr->data.non_resident.lowest_vcn);
742 lcn = 0;
743 /* Get start of the mapping pairs array. */
744 buf = (u8*)attr + le16_to_cpu(
745 attr->data.non_resident.mapping_pairs_offset);
746 attr_end = (u8*)attr + le32_to_cpu(attr->length);
747 if (unlikely(buf < (u8*)attr || buf > attr_end)) {
748 ntfs_error(vol->sb, "Corrupt attribute.");
749 return ERR_PTR(-EIO);
750 }
751 /* Current position in run list array. */
752 rlpos = 0;
753 /* Allocate first page and set current run list size to one page. */
754 rl = ntfs_malloc_nofs(rlsize = PAGE_SIZE);
755 if (unlikely(!rl))
756 return ERR_PTR(-ENOMEM);
757 /* Insert unmapped starting element if necessary. */
758 if (vcn) {
759 rl->vcn = (VCN)0;
760 rl->lcn = (LCN)LCN_RL_NOT_MAPPED;
761 rl->length = vcn;
762 rlpos++;
763 }
764 while (buf < attr_end && *buf) {
765 /*
766 * Allocate more memory if needed, including space for the
767 * not-mapped and terminator elements. ntfs_malloc_nofs()
768 * operates on whole pages only.
769 */
770 if (((rlpos + 3) * sizeof(*old_rl)) > rlsize) {
771 run_list_element *rl2;
772
773 rl2 = ntfs_malloc_nofs(rlsize + (int)PAGE_SIZE);
774 if (unlikely(!rl2)) {
775 ntfs_free(rl);
776 return ERR_PTR(-ENOMEM);
777 }
778 memcpy(rl2, rl, rlsize);
779 ntfs_free(rl);
780 rl = rl2;
781 rlsize += PAGE_SIZE;
782 }
783 /* Enter the current vcn into the current run_list element. */
784 rl[rlpos].vcn = vcn;
785 /*
786 * Get the change in vcn, i.e. the run length in clusters.
787 * Doing it this way ensures that we signextend negative values.
788 * A negative run length doesn't make any sense, but hey, I
789 * didn't make up the NTFS specs and Windows NT4 treats the run
790 * length as a signed value so that's how it is...
791 */
792 b = *buf & 0xf;
793 if (b) {
794 if (unlikely(buf + b > attr_end))
795 goto io_error;
796 for (deltaxcn = (s8)buf[b--]; b; b--)
797 deltaxcn = (deltaxcn << 8) + buf[b];
798 } else { /* The length entry is compulsory. */
799 ntfs_error(vol->sb, "Missing length entry in mapping "
800 "pairs array.");
801 deltaxcn = (s64)-1;
802 }
803 /*
804 * Assume a negative length to indicate data corruption and
805 * hence clean-up and return NULL.
806 */
807 if (unlikely(deltaxcn < 0)) {
808 ntfs_error(vol->sb, "Invalid length in mapping pairs "
809 "array.");
810 goto err_out;
811 }
812 /*
813 * Enter the current run length into the current run list
814 * element.
815 */
816 rl[rlpos].length = deltaxcn;
817 /* Increment the current vcn by the current run length. */
818 vcn += deltaxcn;
819 /*
820 * There might be no lcn change at all, as is the case for
821 * sparse clusters on NTFS 3.0+, in which case we set the lcn
822 * to LCN_HOLE.
823 */
824 if (!(*buf & 0xf0))
825 rl[rlpos].lcn = (LCN)LCN_HOLE;
826 else {
827 /* Get the lcn change which really can be negative. */
828 u8 b2 = *buf & 0xf;
829 b = b2 + ((*buf >> 4) & 0xf);
830 if (buf + b > attr_end)
831 goto io_error;
832 for (deltaxcn = (s8)buf[b--]; b > b2; b--)
833 deltaxcn = (deltaxcn << 8) + buf[b];
834 /* Change the current lcn to its new value. */
835 lcn += deltaxcn;
836 #ifdef DEBUG
837 /*
838 * On NTFS 1.2-, apparently can have lcn == -1 to
839 * indicate a hole. But we haven't verified ourselves
840 * whether it is really the lcn or the deltaxcn that is
841 * -1. So if either is found give us a message so we
842 * can investigate it further!
843 */
844 if (vol->major_ver < 3) {
845 if (unlikely(deltaxcn == (LCN)-1))
846 ntfs_error(vol->sb, "lcn delta == -1");
847 if (unlikely(lcn == (LCN)-1))
848 ntfs_error(vol->sb, "lcn == -1");
849 }
850 #endif
851 /* Check lcn is not below -1. */
852 if (unlikely(lcn < (LCN)-1)) {
853 ntfs_error(vol->sb, "Invalid LCN < -1 in "
854 "mapping pairs array.");
855 goto err_out;
856 }
857 /* Enter the current lcn into the run_list element. */
858 rl[rlpos].lcn = lcn;
859 }
860 /* Get to the next run_list element. */
861 rlpos++;
862 /* Increment the buffer position to the next mapping pair. */
863 buf += (*buf & 0xf) + ((*buf >> 4) & 0xf) + 1;
864 }
865 if (unlikely(buf >= attr_end))
866 goto io_error;
867 /*
868 * If there is a highest_vcn specified, it must be equal to the final
869 * vcn in the run list - 1, or something has gone badly wrong.
870 */
871 deltaxcn = sle64_to_cpu(attr->data.non_resident.highest_vcn);
872 if (unlikely(deltaxcn && vcn - 1 != deltaxcn)) {
873 mpa_err:
874 ntfs_error(vol->sb, "Corrupt mapping pairs array in "
875 "non-resident attribute.");
876 goto err_out;
877 }
878 /* Setup not mapped run list element if this is the base extent. */
879 if (!attr->data.non_resident.lowest_vcn) {
880 VCN max_cluster;
881
882 max_cluster = (sle64_to_cpu(
883 attr->data.non_resident.allocated_size) +
884 vol->cluster_size - 1) >>
885 vol->cluster_size_bits;
886 /*
887 * If there is a difference between the highest_vcn and the
888 * highest cluster, the run list is either corrupt or, more
889 * likely, there are more extents following this one.
890 */
891 if (deltaxcn < --max_cluster) {
892 ntfs_debug("More extents to follow; deltaxcn = 0x%Lx, "
893 "max_cluster = 0x%Lx",
894 (long long)deltaxcn,
895 (long long)max_cluster);
896 rl[rlpos].vcn = vcn;
897 vcn += rl[rlpos].length = max_cluster - deltaxcn;
898 rl[rlpos].lcn = (LCN)LCN_RL_NOT_MAPPED;
899 rlpos++;
900 } else if (unlikely(deltaxcn > max_cluster)) {
901 ntfs_error(vol->sb, "Corrupt attribute. deltaxcn = "
902 "0x%Lx, max_cluster = 0x%Lx",
903 (long long)deltaxcn,
904 (long long)max_cluster);
905 goto mpa_err;
906 }
907 rl[rlpos].lcn = (LCN)LCN_ENOENT;
908 } else /* Not the base extent. There may be more extents to follow. */
909 rl[rlpos].lcn = (LCN)LCN_RL_NOT_MAPPED;
910
911 /* Setup terminating run_list element. */
912 rl[rlpos].vcn = vcn;
913 rl[rlpos].length = (s64)0;
914 /* If no existing run list was specified, we are done. */
915 if (!old_rl) {
916 ntfs_debug("Mapping pairs array successfully decompressed:");
917 ntfs_debug_dump_runlist(rl);
918 return rl;
919 }
920 /* Now combine the new and old run lists checking for overlaps. */
921 old_rl = ntfs_merge_run_lists(old_rl, rl);
922 if (likely(!IS_ERR(old_rl)))
923 return old_rl;
924 ntfs_free(rl);
925 ntfs_error(vol->sb, "Failed to merge run lists.");
926 return old_rl;
927 io_error:
928 ntfs_error(vol->sb, "Corrupt attribute.");
929 err_out:
930 ntfs_free(rl);
931 return ERR_PTR(-EIO);
932 }
933
934 /**
935 * map_run_list - map (a part of) a run list of an ntfs inode
936 * @ni: ntfs inode for which to map (part of) a run list
937 * @vcn: map run list part containing this vcn
938 *
939 * Map the part of a run list containing the @vcn of an the ntfs inode @ni.
940 *
941 * Return 0 on success and -errno on error.
942 */
943 int map_run_list(ntfs_inode *ni, VCN vcn)
944 {
945 ntfs_inode *base_ni;
946 attr_search_context *ctx;
947 MFT_RECORD *mrec;
948 int err = 0;
949
950 ntfs_debug("Mapping run list part containing vcn 0x%Lx.",
951 (long long)vcn);
952
953 if (!NInoAttr(ni))
954 base_ni = ni;
955 else
956 base_ni = ni->ext.base_ntfs_ino;
957
958 mrec = map_mft_record(base_ni);
959 if (IS_ERR(mrec))
960 return PTR_ERR(mrec);
961 ctx = get_attr_search_ctx(base_ni, mrec);
962 if (!ctx) {
963 err = -ENOMEM;
964 goto err_out;
965 }
966 if (!lookup_attr(ni->type, ni->name, ni->name_len, IGNORE_CASE, vcn,
967 NULL, 0, ctx)) {
968 put_attr_search_ctx(ctx);
969 err = -ENOENT;
970 goto err_out;
971 }
972
973 down_write(&ni->run_list.lock);
974 /* Make sure someone else didn't do the work while we were sleeping. */
975 if (likely(vcn_to_lcn(ni->run_list.rl, vcn) <= LCN_RL_NOT_MAPPED)) {
976 run_list_element *rl;
977
978 rl = decompress_mapping_pairs(ni->vol, ctx->attr,
979 ni->run_list.rl);
980 if (unlikely(IS_ERR(rl)))
981 err = PTR_ERR(rl);
982 else
983 ni->run_list.rl = rl;
984 }
985 up_write(&ni->run_list.lock);
986
987 put_attr_search_ctx(ctx);
988 err_out:
989 unmap_mft_record(base_ni);
990 return err;
991 }
992
993 /**
994 * vcn_to_lcn - convert a vcn into a lcn given a run list
995 * @rl: run list to use for conversion
996 * @vcn: vcn to convert
997 *
998 * Convert the virtual cluster number @vcn of an attribute into a logical
999 * cluster number (lcn) of a device using the run list @rl to map vcns to their
1000 * corresponding lcns.
1001 *
1002 * It is up to the caller to serialize access to the run list @rl.
1003 *
1004 * Since lcns must be >= 0, we use negative return values with special meaning:
1005 *
1006 * Return value Meaning / Description
1007 * ==================================================
1008 * -1 = LCN_HOLE Hole / not allocated on disk.
1009 * -2 = LCN_RL_NOT_MAPPED This is part of the run list which has not been
1010 * inserted into the run list yet.
1011 * -3 = LCN_ENOENT There is no such vcn in the attribute.
1012 * -4 = LCN_EINVAL Input parameter error (if debug enabled).
1013 */
1014 LCN vcn_to_lcn(const run_list_element *rl, const VCN vcn)
1015 {
1016 int i;
1017
1018 #ifdef DEBUG
1019 if (vcn < (VCN)0)
1020 return (LCN)LCN_EINVAL;
1021 #endif
1022 /*
1023 * If rl is NULL, assume that we have found an unmapped run list. The
1024 * caller can then attempt to map it and fail appropriately if
1025 * necessary.
1026 */
1027 if (unlikely(!rl))
1028 return (LCN)LCN_RL_NOT_MAPPED;
1029
1030 /* Catch out of lower bounds vcn. */
1031 if (unlikely(vcn < rl[0].vcn))
1032 return (LCN)LCN_ENOENT;
1033
1034 for (i = 0; likely(rl[i].length); i++) {
1035 if (unlikely(vcn < rl[i+1].vcn)) {
1036 if (likely(rl[i].lcn >= (LCN)0))
1037 return rl[i].lcn + (vcn - rl[i].vcn);
1038 return rl[i].lcn;
1039 }
1040 }
1041 /*
1042 * The terminator element is setup to the correct value, i.e. one of
1043 * LCN_HOLE, LCN_RL_NOT_MAPPED, or LCN_ENOENT.
1044 */
1045 if (likely(rl[i].lcn < (LCN)0))
1046 return rl[i].lcn;
1047 /* Just in case... We could replace this with BUG() some day. */
1048 return (LCN)LCN_ENOENT;
1049 }
1050
1051 /**
1052 * find_attr - find (next) attribute in mft record
1053 * @type: attribute type to find
1054 * @name: attribute name to find (optional, i.e. NULL means don't care)
1055 * @name_len: attribute name length (only needed if @name present)
1056 * @ic: IGNORE_CASE or CASE_SENSITIVE (ignored if @name not present)
1057 * @val: attribute value to find (optional, resident attributes only)
1058 * @val_len: attribute value length
1059 * @ctx: search context with mft record and attribute to search from
1060 *
1061 * You shouldn't need to call this function directly. Use lookup_attr() instead.
1062 *
1063 * find_attr() takes a search context @ctx as parameter and searches the mft
1064 * record specified by @ctx->mrec, beginning at @ctx->attr, for an attribute of
1065 * @type, optionally @name and @val. If found, find_attr() returns TRUE and
1066 * @ctx->attr will point to the found attribute. If not found, find_attr()
1067 * returns FALSE and @ctx->attr is undefined (i.e. do not rely on it not
1068 * changing).
1069 *
1070 * If @ctx->is_first is TRUE, the search begins with @ctx->attr itself. If it
1071 * is FALSE, the search begins after @ctx->attr.
1072 *
1073 * If @ic is IGNORE_CASE, the @name comparisson is not case sensitive and
1074 * @ctx->ntfs_ino must be set to the ntfs inode to which the mft record
1075 * @ctx->mrec belongs. This is so we can get at the ntfs volume and hence at
1076 * the upcase table. If @ic is CASE_SENSITIVE, the comparison is case
1077 * sensitive. When @name is present, @name_len is the @name length in Unicode
1078 * characters.
1079 *
1080 * If @name is not present (NULL), we assume that the unnamed attribute is
1081 * being searched for.
1082 *
1083 * Finally, the resident attribute value @val is looked for, if present. If @val
1084 * is not present (NULL), @val_len is ignored.
1085 *
1086 * find_attr() only searches the specified mft record and it ignores the
1087 * presence of an attribute list attribute (unless it is the one being searched
1088 * for, obviously). If you need to take attribute lists into consideration, use
1089 * lookup_attr() instead (see below). This also means that you cannot use
1090 * find_attr() to search for extent records of non-resident attributes, as
1091 * extents with lowest_vcn != 0 are usually described by the attribute list
1092 * attribute only. - Note that it is possible that the first extent is only in
1093 * the attribute list while the last extent is in the base mft record, so don't
1094 * rely on being able to find the first extent in the base mft record.
1095 *
1096 * Warning: Never use @val when looking for attribute types which can be
1097 * non-resident as this most likely will result in a crash!
1098 */
1099 BOOL find_attr(const ATTR_TYPES type, const uchar_t *name, const u32 name_len,
1100 const IGNORE_CASE_BOOL ic, const u8 *val, const u32 val_len,
1101 attr_search_context *ctx)
1102 {
1103 ATTR_RECORD *a;
1104 ntfs_volume *vol;
1105 uchar_t *upcase;
1106 u32 upcase_len;
1107
1108 if (ic == IGNORE_CASE) {
1109 vol = ctx->ntfs_ino->vol;
1110 upcase = vol->upcase;
1111 upcase_len = vol->upcase_len;
1112 } else {
1113 vol = NULL;
1114 upcase = NULL;
1115 upcase_len = 0;
1116 }
1117 /*
1118 * Iterate over attributes in mft record starting at @ctx->attr, or the
1119 * attribute following that, if @ctx->is_first is TRUE.
1120 */
1121 if (ctx->is_first) {
1122 a = ctx->attr;
1123 ctx->is_first = FALSE;
1124 } else
1125 a = (ATTR_RECORD*)((u8*)ctx->attr +
1126 le32_to_cpu(ctx->attr->length));
1127 for (;; a = (ATTR_RECORD*)((u8*)a + le32_to_cpu(a->length))) {
1128 if ((u8*)a < (u8*)ctx->mrec || (u8*)a > (u8*)ctx->mrec +
1129 le32_to_cpu(ctx->mrec->bytes_allocated))
1130 break;
1131 ctx->attr = a;
1132 /* We catch $END with this more general check, too... */
1133 if (le32_to_cpu(a->type) > le32_to_cpu(type))
1134 return FALSE;
1135 if (unlikely(!a->length))
1136 break;
1137 if (a->type != type)
1138 continue;
1139 /*
1140 * If @name is present, compare the two names. If @name is
1141 * missing, assume we want an unnamed attribute.
1142 */
1143 if (!name) {
1144 /* The search failed if the found attribute is named. */
1145 if (a->name_length)
1146 return FALSE;
1147 } else if (!ntfs_are_names_equal(name, name_len,
1148 (uchar_t*)((u8*)a + le16_to_cpu(a->name_offset)),
1149 a->name_length, ic, upcase, upcase_len)) {
1150 register int rc;
1151
1152 rc = ntfs_collate_names(name, name_len,
1153 (uchar_t*)((u8*)a +
1154 le16_to_cpu(a->name_offset)),
1155 a->name_length, 1, IGNORE_CASE,
1156 upcase, upcase_len);
1157 /*
1158 * If @name collates before a->name, there is no
1159 * matching attribute.
1160 */
1161 if (rc == -1)
1162 return FALSE;
1163 /* If the strings are not equal, continue search. */
1164 if (rc)
1165 continue;
1166 rc = ntfs_collate_names(name, name_len,
1167 (uchar_t*)((u8*)a +
1168 le16_to_cpu(a->name_offset)),
1169 a->name_length, 1, CASE_SENSITIVE,
1170 upcase, upcase_len);
1171 if (rc == -1)
1172 return FALSE;
1173 if (rc)
1174 continue;
1175 }
1176 /*
1177 * The names match or @name not present and attribute is
1178 * unnamed. If no @val specified, we have found the attribute
1179 * and are done.
1180 */
1181 if (!val)
1182 return TRUE;
1183 /* @val is present; compare values. */
1184 else {
1185 u32 vl;
1186 register int rc;
1187
1188 vl = le32_to_cpu(a->data.resident.value_length);
1189 if (vl > val_len)
1190 vl = val_len;
1191
1192 rc = memcmp(val, (u8*)a + le16_to_cpu(
1193 a->data.resident.value_offset), vl);
1194 /*
1195 * If @val collates before the current attribute's
1196 * value, there is no matching attribute.
1197 */
1198 if (!rc) {
1199 register u32 avl;
1200 avl = le32_to_cpu(
1201 a->data.resident.value_length);
1202 if (val_len == avl)
1203 return TRUE;
1204 if (val_len < avl)
1205 return FALSE;
1206 } else if (rc < 0)
1207 return FALSE;
1208 }
1209 }
1210 ntfs_error(NULL, "Inode is corrupt. Run chkdsk.");
1211 return FALSE;
1212 }
1213
1214 /**
1215 * load_attribute_list - load an attribute list into memory
1216 * @vol: ntfs volume from which to read
1217 * @run_list: run list of the attribute list
1218 * @al_start: destination buffer
1219 * @size: size of the destination buffer in bytes
1220 * @initialized_size: initialized size of the attribute list
1221 *
1222 * Walk the run list @run_list and load all clusters from it copying them into
1223 * the linear buffer @al. The maximum number of bytes copied to @al is @size
1224 * bytes. Note, @size does not need to be a multiple of the cluster size. If
1225 * @initialized_size is less than @size, the region in @al between
1226 * @initialized_size and @size will be zeroed and not read from disk.
1227 *
1228 * Return 0 on success or -errno on error.
1229 */
1230 int load_attribute_list(ntfs_volume *vol, run_list *run_list, u8 *al_start,
1231 const s64 size, const s64 initialized_size)
1232 {
1233 LCN lcn;
1234 u8 *al = al_start;
1235 u8 *al_end = al + initialized_size;
1236 run_list_element *rl;
1237 struct buffer_head *bh;
1238 struct super_block *sb = vol->sb;
1239 unsigned long block_size = sb->s_blocksize;
1240 unsigned long block, max_block;
1241 int err = 0;
1242 unsigned char block_size_bits = sb->s_blocksize_bits;
1243
1244 ntfs_debug("Entering.");
1245 if (!vol || !run_list || !al || size <= 0 || initialized_size < 0 ||
1246 initialized_size > size)
1247 return -EINVAL;
1248 if (!initialized_size) {
1249 memset(al, 0, size);
1250 return 0;
1251 }
1252 down_read(&run_list->lock);
1253 rl = run_list->rl;
1254 /* Read all clusters specified by the run list one run at a time. */
1255 while (rl->length) {
1256 lcn = vcn_to_lcn(rl, rl->vcn);
1257 ntfs_debug("Reading vcn = 0x%Lx, lcn = 0x%Lx.",
1258 (long long)rl->vcn, (long long)lcn);
1259 /* The attribute list cannot be sparse. */
1260 if (lcn < 0) {
1261 ntfs_error(sb, "vcn_to_lcn() failed. Cannot read "
1262 "attribute list.");
1263 goto err_out;
1264 }
1265 block = lcn << vol->cluster_size_bits >> block_size_bits;
1266 /* Read the run from device in chunks of block_size bytes. */
1267 max_block = block + (rl->length << vol->cluster_size_bits >>
1268 block_size_bits);
1269 ntfs_debug("max_block = 0x%lx.", max_block);
1270 do {
1271 ntfs_debug("Reading block = 0x%lx.", block);
1272 bh = sb_bread(sb, block);
1273 if (!bh) {
1274 ntfs_error(sb, "sb_bread() failed. Cannot "
1275 "read attribute list.");
1276 goto err_out;
1277 }
1278 if (al + block_size >= al_end)
1279 goto do_final;
1280 memcpy(al, bh->b_data, block_size);
1281 brelse(bh);
1282 al += block_size;
1283 } while (++block < max_block);
1284 rl++;
1285 }
1286 if (initialized_size < size) {
1287 initialize:
1288 memset(al_start + initialized_size, 0, size - initialized_size);
1289 }
1290 done:
1291 up_read(&run_list->lock);
1292 return err;
1293 do_final:
1294 if (al < al_end) {
1295 /*
1296 * Partial block.
1297 *
1298 * Note: The attribute list can be smaller than its allocation
1299 * by multiple clusters. This has been encountered by at least
1300 * two people running Windows XP, thus we cannot do any
1301 * truncation sanity checking here. (AIA)
1302 */
1303 memcpy(al, bh->b_data, al_end - al);
1304 brelse(bh);
1305 if (initialized_size < size)
1306 goto initialize;
1307 goto done;
1308 }
1309 brelse(bh);
1310 /* Real overflow! */
1311 ntfs_error(sb, "Attribute list buffer overflow. Read attribute list "
1312 "is truncated.");
1313 err_out:
1314 err = -EIO;
1315 goto done;
1316 }
1317
1318 /**
1319 * find_external_attr - find an attribute in the attribute list of an ntfs inode
1320 * @type: attribute type to find
1321 * @name: attribute name to find (optional, i.e. NULL means don't care)
1322 * @name_len: attribute name length (only needed if @name present)
1323 * @ic: IGNORE_CASE or CASE_SENSITIVE (ignored if @name not present)
1324 * @lowest_vcn: lowest vcn to find (optional, non-resident attributes only)
1325 * @val: attribute value to find (optional, resident attributes only)
1326 * @val_len: attribute value length
1327 * @ctx: search context with mft record and attribute to search from
1328 *
1329 * You shouldn't need to call this function directly. Use lookup_attr() instead.
1330 *
1331 * Find an attribute by searching the attribute list for the corresponding
1332 * attribute list entry. Having found the entry, map the mft record for read
1333 * if the attribute is in a different mft record/inode, find_attr the attribute
1334 * in there and return it.
1335 *
1336 * On first search @ctx->ntfs_ino must be the base mft record and @ctx must
1337 * have been obtained from a call to get_attr_search_ctx(). On subsequent calls
1338 * @ctx->ntfs_ino can be any extent inode, too (@ctx->base_ntfs_ino is then the
1339 * base inode).
1340 *
1341 * After finishing with the attribute/mft record you need to call
1342 * release_attr_search_ctx() to cleanup the search context (unmapping any
1343 * mapped inodes, etc).
1344 *
1345 * Return TRUE if the search was successful and FALSE if not. When TRUE,
1346 * @ctx->attr is the found attribute and it is in mft record @ctx->mrec. When
1347 * FALSE, @ctx->attr is the attribute which collates just after the attribute
1348 * being searched for in the base ntfs inode, i.e. if one wants to add the
1349 * attribute to the mft record this is the correct place to insert it into
1350 * and if there is not enough space, the attribute should be placed in an
1351 * extent mft record.
1352 */
1353 static BOOL find_external_attr(const ATTR_TYPES type, const uchar_t *name,
1354 const u32 name_len, const IGNORE_CASE_BOOL ic,
1355 const VCN lowest_vcn, const u8 *val, const u32 val_len,
1356 attr_search_context *ctx)
1357 {
1358 ntfs_inode *base_ni, *ni;
1359 ntfs_volume *vol;
1360 ATTR_LIST_ENTRY *al_entry, *next_al_entry;
1361 u8 *al_start, *al_end;
1362 ATTR_RECORD *a;
1363 uchar_t *al_name;
1364 u32 al_name_len;
1365
1366 ni = ctx->ntfs_ino;
1367 base_ni = ctx->base_ntfs_ino;
1368 ntfs_debug("Entering for inode 0x%lx, type 0x%x.", ni->mft_no, type);
1369 if (!base_ni) {
1370 /* First call happens with the base mft record. */
1371 base_ni = ctx->base_ntfs_ino = ctx->ntfs_ino;
1372 ctx->base_mrec = ctx->mrec;
1373 }
1374 if (ni == base_ni)
1375 ctx->base_attr = ctx->attr;
1376 vol = base_ni->vol;
1377 al_start = base_ni->attr_list;
1378 al_end = al_start + base_ni->attr_list_size;
1379 if (!ctx->al_entry)
1380 ctx->al_entry = (ATTR_LIST_ENTRY*)al_start;
1381 /*
1382 * Iterate over entries in attribute list starting at @ctx->al_entry,
1383 * or the entry following that, if @ctx->is_first is TRUE.
1384 */
1385 if (ctx->is_first) {
1386 al_entry = ctx->al_entry;
1387 ctx->is_first = FALSE;
1388 } else
1389 al_entry = (ATTR_LIST_ENTRY*)((u8*)ctx->al_entry +
1390 le16_to_cpu(ctx->al_entry->length));
1391 for (;; al_entry = next_al_entry) {
1392 /* Out of bounds check. */
1393 if ((u8*)al_entry < base_ni->attr_list ||
1394 (u8*)al_entry > al_end)
1395 break; /* Inode is corrupt. */
1396 ctx->al_entry = al_entry;
1397 /* Catch the end of the attribute list. */
1398 if ((u8*)al_entry == al_end)
1399 goto not_found;
1400 if (!al_entry->length)
1401 break;
1402 if ((u8*)al_entry + 6 > al_end || (u8*)al_entry +
1403 le16_to_cpu(al_entry->length) > al_end)
1404 break;
1405 next_al_entry = (ATTR_LIST_ENTRY*)((u8*)al_entry +
1406 le16_to_cpu(al_entry->length));
1407 if (le32_to_cpu(al_entry->type) > le32_to_cpu(type))
1408 goto not_found;
1409 if (type != al_entry->type)
1410 continue;
1411 /*
1412 * If @name is present, compare the two names. If @name is
1413 * missing, assume we want an unnamed attribute.
1414 */
1415 al_name_len = al_entry->name_length;
1416 al_name = (uchar_t*)((u8*)al_entry + al_entry->name_offset);
1417 if (!name) {
1418 if (al_name_len)
1419 goto not_found;
1420 } else if (!ntfs_are_names_equal(al_name, al_name_len, name,
1421 name_len, ic, vol->upcase, vol->upcase_len)) {
1422 register int rc;
1423
1424 rc = ntfs_collate_names(name, name_len, al_name,
1425 al_name_len, 1, IGNORE_CASE,
1426 vol->upcase, vol->upcase_len);
1427 /*
1428 * If @name collates before al_name, there is no
1429 * matching attribute.
1430 */
1431 if (rc == -1)
1432 goto not_found;
1433 /* If the strings are not equal, continue search. */
1434 if (rc)
1435 continue;
1436 /*
1437 * FIXME: Reverse engineering showed 0, IGNORE_CASE but
1438 * that is inconsistent with find_attr(). The subsequent
1439 * rc checks were also different. Perhaps I made a
1440 * mistake in one of the two. Need to recheck which is
1441 * correct or at least see what is going on... (AIA)
1442 */
1443 rc = ntfs_collate_names(name, name_len, al_name,
1444 al_name_len, 1, CASE_SENSITIVE,
1445 vol->upcase, vol->upcase_len);
1446 if (rc == -1)
1447 goto not_found;
1448 if (rc)
1449 continue;
1450 }
1451 /*
1452 * The names match or @name not present and attribute is
1453 * unnamed. Now check @lowest_vcn. Continue search if the
1454 * next attribute list entry still fits @lowest_vcn. Otherwise
1455 * we have reached the right one or the search has failed.
1456 */
1457 if (lowest_vcn && (u8*)next_al_entry >= al_start &&
1458 (u8*)next_al_entry + 6 < al_end &&
1459 (u8*)next_al_entry + le16_to_cpu(
1460 next_al_entry->length) <= al_end &&
1461 sle64_to_cpu(next_al_entry->lowest_vcn) <=
1462 sle64_to_cpu(lowest_vcn) &&
1463 next_al_entry->type == al_entry->type &&
1464 next_al_entry->name_length == al_name_len &&
1465 ntfs_are_names_equal((uchar_t*)((u8*)
1466 next_al_entry +
1467 next_al_entry->name_offset),
1468 next_al_entry->name_length,
1469 al_name, al_name_len, CASE_SENSITIVE,
1470 vol->upcase, vol->upcase_len))
1471 continue;
1472 if (MREF_LE(al_entry->mft_reference) == ni->mft_no) {
1473 if (MSEQNO_LE(al_entry->mft_reference) != ni->seq_no) {
1474 ntfs_error(vol->sb, "Found stale mft "
1475 "reference in attribute list!");
1476 break;
1477 }
1478 } else { /* Mft references do not match. */
1479 /* If there is a mapped record unmap it first. */
1480 if (ni != base_ni)
1481 unmap_extent_mft_record(ni);
1482 /* Do we want the base record back? */
1483 if (MREF_LE(al_entry->mft_reference) ==
1484 base_ni->mft_no) {
1485 ni = ctx->ntfs_ino = base_ni;
1486 ctx->mrec = ctx->base_mrec;
1487 } else {
1488 /* We want an extent record. */
1489 ctx->mrec = map_extent_mft_record(base_ni,
1490 al_entry->mft_reference, &ni);
1491 ctx->ntfs_ino = ni;
1492 if (IS_ERR(ctx->mrec)) {
1493 ntfs_error(vol->sb, "Failed to map mft "
1494 "record, error code "
1495 "%ld.",
1496 -PTR_ERR(ctx->mrec));
1497 break;
1498 }
1499 }
1500 ctx->attr = (ATTR_RECORD*)((u8*)ctx->mrec +
1501 le16_to_cpu(ctx->mrec->attrs_offset));
1502 }
1503 /*
1504 * ctx->vfs_ino, ctx->mrec, and ctx->attr now point to the
1505 * mft record containing the attribute represented by the
1506 * current al_entry.
1507 */
1508 /*
1509 * We could call into find_attr() to find the right attribute
1510 * in this mft record but this would be less efficient and not
1511 * quite accurate as find_attr() ignores the attribute instance
1512 * numbers for example which become important when one plays
1513 * with attribute lists. Also, because a proper match has been
1514 * found in the attribute list entry above, the comparison can
1515 * now be optimized. So it is worth re-implementing a
1516 * simplified find_attr() here.
1517 */
1518 a = ctx->attr;
1519 /*
1520 * Use a manual loop so we can still use break and continue
1521 * with the same meanings as above.
1522 */
1523 do_next_attr_loop:
1524 if ((u8*)a < (u8*)ctx->mrec || (u8*)a > (u8*)ctx->mrec +
1525 le32_to_cpu(ctx->mrec->bytes_allocated))
1526 break;
1527 if (a->type == AT_END)
1528 continue;
1529 if (!a->length)
1530 break;
1531 if (al_entry->instance != a->instance)
1532 goto do_next_attr;
1533 if (al_entry->type != a->type)
1534 continue;
1535 if (name) {
1536 if (a->name_length != al_name_len)
1537 continue;
1538 if (!ntfs_are_names_equal((uchar_t*)((u8*)a +
1539 le16_to_cpu(a->name_offset)),
1540 a->name_length, al_name, al_name_len,
1541 CASE_SENSITIVE, vol->upcase,
1542 vol->upcase_len))
1543 continue;
1544 }
1545 ctx->attr = a;
1546 /*
1547 * If no @val specified or @val specified and it matches, we
1548 * have found it!
1549 */
1550 if (!val || (!a->non_resident && le32_to_cpu(
1551 a->data.resident.value_length) == val_len &&
1552 !memcmp((u8*)a +
1553 le16_to_cpu(a->data.resident.value_offset),
1554 val, val_len))) {
1555 ntfs_debug("Done, found.");
1556 return TRUE;
1557 }
1558 do_next_attr:
1559 /* Proceed to the next attribute in the current mft record. */
1560 a = (ATTR_RECORD*)((u8*)a + le32_to_cpu(a->length));
1561 goto do_next_attr_loop;
1562 }
1563 ntfs_error(base_ni->vol->sb, "Inode contains corrupt attribute list "
1564 "attribute.\n");
1565 if (ni != base_ni) {
1566 unmap_extent_mft_record(ni);
1567 ctx->ntfs_ino = base_ni;
1568 ctx->mrec = ctx->base_mrec;
1569 ctx->attr = ctx->base_attr;
1570 }
1571 /*
1572 * FIXME: We absolutely have to return ERROR status instead of just
1573 * false or we will blow up or even worse cause corruption when we add
1574 * write support and we reach this code path!
1575 */
1576 printk(KERN_CRIT "NTFS: FIXME: Hit unfinished error code path!!!\n");
1577 return FALSE;
1578 not_found:
1579 /*
1580 * Seek to the end of the base mft record, i.e. when we return false,
1581 * ctx->mrec and ctx->attr indicate where the attribute should be
1582 * inserted into the attribute record.
1583 * And of course ctx->al_entry points to the end of the attribute
1584 * list inside NTFS_I(ctx->base_vfs_ino)->attr_list.
1585 *
1586 * FIXME: Do we really want to do this here? Think about it... (AIA)
1587 */
1588 reinit_attr_search_ctx(ctx);
1589 find_attr(type, name, name_len, ic, val, val_len, ctx);
1590 ntfs_debug("Done, not found.");
1591 return FALSE;
1592 }
1593
1594 /**
1595 * lookup_attr - find an attribute in an ntfs inode
1596 * @type: attribute type to find
1597 * @name: attribute name to find (optional, i.e. NULL means don't care)
1598 * @name_len: attribute name length (only needed if @name present)
1599 * @ic: IGNORE_CASE or CASE_SENSITIVE (ignored if @name not present)
1600 * @lowest_vcn: lowest vcn to find (optional, non-resident attributes only)
1601 * @val: attribute value to find (optional, resident attributes only)
1602 * @val_len: attribute value length
1603 * @ctx: search context with mft record and attribute to search from
1604 *
1605 * Find an attribute in an ntfs inode. On first search @ctx->ntfs_ino must
1606 * be the base mft record and @ctx must have been obtained from a call to
1607 * get_attr_search_ctx().
1608 *
1609 * This function transparently handles attribute lists and @ctx is used to
1610 * continue searches where they were left off at.
1611 *
1612 * After finishing with the attribute/mft record you need to call
1613 * release_attr_search_ctx() to cleanup the search context (unmapping any
1614 * mapped inodes, etc).
1615 *
1616 * Return TRUE if the search was successful and FALSE if not. When TRUE,
1617 * @ctx->attr is the found attribute and it is in mft record @ctx->mrec. When
1618 * FALSE, @ctx->attr is the attribute which collates just after the attribute
1619 * being searched for, i.e. if one wants to add the attribute to the mft
1620 * record this is the correct place to insert it into.
1621 */
1622 BOOL lookup_attr(const ATTR_TYPES type, const uchar_t *name, const u32 name_len,
1623 const IGNORE_CASE_BOOL ic, const VCN lowest_vcn, const u8 *val,
1624 const u32 val_len, attr_search_context *ctx)
1625 {
1626 ntfs_inode *base_ni;
1627
1628 ntfs_debug("Entering.");
1629 if (ctx->base_ntfs_ino)
1630 base_ni = ctx->base_ntfs_ino;
1631 else
1632 base_ni = ctx->ntfs_ino;
1633 /* Sanity check, just for debugging really. */
1634 BUG_ON(!base_ni);
1635 if (!NInoAttrList(base_ni))
1636 return find_attr(type, name, name_len, ic, val, val_len, ctx);
1637 return find_external_attr(type, name, name_len, ic, lowest_vcn, val,
1638 val_len, ctx);
1639 }
1640
1641 /**
1642 * init_attr_search_ctx - initialize an attribute search context
1643 * @ctx: attribute search context to initialize
1644 * @ni: ntfs inode with which to initialize the search context
1645 * @mrec: mft record with which to initialize the search context
1646 *
1647 * Initialize the attribute search context @ctx with @ni and @mrec.
1648 */
1649 static inline void init_attr_search_ctx(attr_search_context *ctx,
1650 ntfs_inode *ni, MFT_RECORD *mrec)
1651 {
1652 ctx->mrec = mrec;
1653 /* Sanity checks are performed elsewhere. */
1654 ctx->attr = (ATTR_RECORD*)((u8*)mrec + le16_to_cpu(mrec->attrs_offset));
1655 ctx->is_first = TRUE;
1656 ctx->ntfs_ino = ni;
1657 ctx->al_entry = NULL;
1658 ctx->base_ntfs_ino = NULL;
1659 ctx->base_mrec = NULL;
1660 ctx->base_attr = NULL;
1661 }
1662
1663 /**
1664 * reinit_attr_search_ctx - reinitialize an attribute search context
1665 * @ctx: attribute search context to reinitialize
1666 *
1667 * Reinitialize the attribute search context @ctx, unmapping an associated
1668 * extent mft record if present, and initialize the search context again.
1669 *
1670 * This is used when a search for a new attribute is being started to reset
1671 * the search context to the beginning.
1672 */
1673 void reinit_attr_search_ctx(attr_search_context *ctx)
1674 {
1675 if (likely(!ctx->base_ntfs_ino)) {
1676 /* No attribute list. */
1677 ctx->is_first = TRUE;
1678 /* Sanity checks are performed elsewhere. */
1679 ctx->attr = (ATTR_RECORD*)((u8*)ctx->mrec +
1680 le16_to_cpu(ctx->mrec->attrs_offset));
1681 return;
1682 } /* Attribute list. */
1683 if (ctx->ntfs_ino != ctx->base_ntfs_ino)
1684 unmap_extent_mft_record(ctx->ntfs_ino);
1685 init_attr_search_ctx(ctx, ctx->base_ntfs_ino, ctx->base_mrec);
1686 return;
1687 }
1688
1689 /**
1690 * get_attr_search_ctx - allocate and initialize a new attribute search context
1691 * @ni: ntfs inode with which to initialize the search context
1692 * @mrec: mft record with which to initialize the search context
1693 *
1694 * Allocate a new attribute search context, initialize it with @ni and @mrec,
1695 * and return it. Return NULL if allocation failed.
1696 */
1697 attr_search_context *get_attr_search_ctx(ntfs_inode *ni, MFT_RECORD *mrec)
1698 {
1699 attr_search_context *ctx;
1700
1701 ctx = kmem_cache_alloc(ntfs_attr_ctx_cache, SLAB_NOFS);
1702 if (ctx)
1703 init_attr_search_ctx(ctx, ni, mrec);
1704 return ctx;
1705 }
1706
1707 /**
1708 * put_attr_search_ctx - release an attribute search context
1709 * @ctx: attribute search context to free
1710 *
1711 * Release the attribute search context @ctx, unmapping an associated extent
1712 * mft record if present.
1713 */
1714 void put_attr_search_ctx(attr_search_context *ctx)
1715 {
1716 if (ctx->base_ntfs_ino && ctx->ntfs_ino != ctx->base_ntfs_ino)
1717 unmap_extent_mft_record(ctx->ntfs_ino);
1718 kmem_cache_free(ntfs_attr_ctx_cache, ctx);
1719 return;
1720 }
1721