NTFS: Fix sign of various error return values to be negative in
[linux-block.git] / fs / ntfs / attrib.c
CommitLineData
1da177e4
LT
1/**
2 * attrib.c - NTFS attribute operations. Part of the Linux-NTFS project.
3 *
b6ad6c52 4 * Copyright (c) 2001-2005 Anton Altaparmakov
1da177e4
LT
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
25#include "attrib.h"
26#include "debug.h"
27#include "layout.h"
2bfb4fff
AA
28#include "lcnalloc.h"
29#include "malloc.h"
1da177e4
LT
30#include "mft.h"
31#include "ntfs.h"
32#include "types.h"
33
34/**
b6ad6c52 35 * ntfs_map_runlist_nolock - map (a part of) a runlist of an ntfs inode
1da177e4
LT
36 * @ni: ntfs inode for which to map (part of) a runlist
37 * @vcn: map runlist part containing this vcn
38 *
39 * Map the part of a runlist containing the @vcn of the ntfs inode @ni.
40 *
41 * Return 0 on success and -errno on error.
42 *
b6ad6c52
AA
43 * Locking: - The runlist must be locked for writing.
44 * - This function modifies the runlist.
1da177e4 45 */
b6ad6c52 46int ntfs_map_runlist_nolock(ntfs_inode *ni, VCN vcn)
1da177e4
LT
47{
48 ntfs_inode *base_ni;
1da177e4 49 MFT_RECORD *mrec;
b6ad6c52
AA
50 ntfs_attr_search_ctx *ctx;
51 runlist_element *rl;
1da177e4
LT
52 int err = 0;
53
54 ntfs_debug("Mapping runlist part containing vcn 0x%llx.",
55 (unsigned long long)vcn);
1da177e4
LT
56 if (!NInoAttr(ni))
57 base_ni = ni;
58 else
59 base_ni = ni->ext.base_ntfs_ino;
1da177e4
LT
60 mrec = map_mft_record(base_ni);
61 if (IS_ERR(mrec))
62 return PTR_ERR(mrec);
63 ctx = ntfs_attr_get_search_ctx(base_ni, mrec);
64 if (unlikely(!ctx)) {
65 err = -ENOMEM;
66 goto err_out;
67 }
68 err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
69 CASE_SENSITIVE, vcn, NULL, 0, ctx);
b6ad6c52 70 if (likely(!err)) {
1da177e4
LT
71 rl = ntfs_mapping_pairs_decompress(ni->vol, ctx->attr,
72 ni->runlist.rl);
73 if (IS_ERR(rl))
74 err = PTR_ERR(rl);
75 else
76 ni->runlist.rl = rl;
77 }
1da177e4
LT
78 ntfs_attr_put_search_ctx(ctx);
79err_out:
80 unmap_mft_record(base_ni);
81 return err;
82}
83
84/**
b6ad6c52
AA
85 * ntfs_map_runlist - map (a part of) a runlist of an ntfs inode
86 * @ni: ntfs inode for which to map (part of) a runlist
87 * @vcn: map runlist part containing this vcn
88 *
89 * Map the part of a runlist containing the @vcn of the ntfs inode @ni.
90 *
91 * Return 0 on success and -errno on error.
92 *
93 * Locking: - The runlist must be unlocked on entry and is unlocked on return.
94 * - This function takes the runlist lock for writing and modifies the
95 * runlist.
96 */
97int ntfs_map_runlist(ntfs_inode *ni, VCN vcn)
98{
99 int err = 0;
100
101 down_write(&ni->runlist.lock);
102 /* Make sure someone else didn't do the work while we were sleeping. */
103 if (likely(ntfs_rl_vcn_to_lcn(ni->runlist.rl, vcn) <=
104 LCN_RL_NOT_MAPPED))
105 err = ntfs_map_runlist_nolock(ni, vcn);
106 up_write(&ni->runlist.lock);
107 return err;
108}
109
271849a9
AA
110/**
111 * ntfs_attr_vcn_to_lcn_nolock - convert a vcn into a lcn given an ntfs inode
112 * @ni: ntfs inode of the attribute whose runlist to search
113 * @vcn: vcn to convert
114 * @write_locked: true if the runlist is locked for writing
115 *
116 * Find the virtual cluster number @vcn in the runlist of the ntfs attribute
117 * described by the ntfs inode @ni and return the corresponding logical cluster
118 * number (lcn).
119 *
120 * If the @vcn is not mapped yet, the attempt is made to map the attribute
121 * extent containing the @vcn and the vcn to lcn conversion is retried.
122 *
123 * If @write_locked is true the caller has locked the runlist for writing and
124 * if false for reading.
125 *
126 * Since lcns must be >= 0, we use negative return codes with special meaning:
127 *
128 * Return code Meaning / Description
129 * ==========================================
130 * LCN_HOLE Hole / not allocated on disk.
131 * LCN_ENOENT There is no such vcn in the runlist, i.e. @vcn is out of bounds.
132 * LCN_ENOMEM Not enough memory to map runlist.
133 * LCN_EIO Critical error (runlist/file is corrupt, i/o error, etc).
134 *
135 * Locking: - The runlist must be locked on entry and is left locked on return.
136 * - If @write_locked is FALSE, i.e. the runlist is locked for reading,
137 * the lock may be dropped inside the function so you cannot rely on
138 * the runlist still being the same when this function returns.
139 */
140LCN ntfs_attr_vcn_to_lcn_nolock(ntfs_inode *ni, const VCN vcn,
141 const BOOL write_locked)
142{
143 LCN lcn;
144 BOOL is_retry = FALSE;
145
146 ntfs_debug("Entering for i_ino 0x%lx, vcn 0x%llx, %s_locked.",
147 ni->mft_no, (unsigned long long)vcn,
148 write_locked ? "write" : "read");
149 BUG_ON(!ni);
150 BUG_ON(!NInoNonResident(ni));
151 BUG_ON(vcn < 0);
152retry_remap:
153 /* Convert vcn to lcn. If that fails map the runlist and retry once. */
154 lcn = ntfs_rl_vcn_to_lcn(ni->runlist.rl, vcn);
155 if (likely(lcn >= LCN_HOLE)) {
156 ntfs_debug("Done, lcn 0x%llx.", (long long)lcn);
157 return lcn;
158 }
159 if (lcn != LCN_RL_NOT_MAPPED) {
160 if (lcn != LCN_ENOENT)
161 lcn = LCN_EIO;
162 } else if (!is_retry) {
163 int err;
164
165 if (!write_locked) {
166 up_read(&ni->runlist.lock);
167 down_write(&ni->runlist.lock);
168 if (unlikely(ntfs_rl_vcn_to_lcn(ni->runlist.rl, vcn) !=
169 LCN_RL_NOT_MAPPED)) {
170 up_write(&ni->runlist.lock);
171 down_read(&ni->runlist.lock);
172 goto retry_remap;
173 }
174 }
175 err = ntfs_map_runlist_nolock(ni, vcn);
176 if (!write_locked) {
177 up_write(&ni->runlist.lock);
178 down_read(&ni->runlist.lock);
179 }
180 if (likely(!err)) {
181 is_retry = TRUE;
182 goto retry_remap;
183 }
184 if (err == -ENOENT)
185 lcn = LCN_ENOENT;
186 else if (err == -ENOMEM)
187 lcn = LCN_ENOMEM;
188 else
189 lcn = LCN_EIO;
190 }
191 if (lcn != LCN_ENOENT)
192 ntfs_error(ni->vol->sb, "Failed with error code %lli.",
193 (long long)lcn);
194 return lcn;
195}
196
b6ad6c52 197/**
c0c1cc0e 198 * ntfs_attr_find_vcn_nolock - find a vcn in the runlist of an ntfs inode
b6ad6c52
AA
199 * @ni: ntfs inode describing the runlist to search
200 * @vcn: vcn to find
201 * @write_locked: true if the runlist is locked for writing
1da177e4
LT
202 *
203 * Find the virtual cluster number @vcn in the runlist described by the ntfs
204 * inode @ni and return the address of the runlist element containing the @vcn.
b6ad6c52 205 *
c0c1cc0e
AA
206 * If the @vcn is not mapped yet, the attempt is made to map the attribute
207 * extent containing the @vcn and the vcn to lcn conversion is retried.
208 *
209 * If @write_locked is true the caller has locked the runlist for writing and
210 * if false for reading.
1da177e4
LT
211 *
212 * Note you need to distinguish between the lcn of the returned runlist element
213 * being >= 0 and LCN_HOLE. In the later case you have to return zeroes on
214 * read and allocate clusters on write.
215 *
216 * Return the runlist element containing the @vcn on success and
217 * ERR_PTR(-errno) on error. You need to test the return value with IS_ERR()
218 * to decide if the return is success or failure and PTR_ERR() to get to the
219 * error code if IS_ERR() is true.
220 *
221 * The possible error return codes are:
222 * -ENOENT - No such vcn in the runlist, i.e. @vcn is out of bounds.
223 * -ENOMEM - Not enough memory to map runlist.
224 * -EIO - Critical error (runlist/file is corrupt, i/o error, etc).
225 *
c0c1cc0e
AA
226 * Locking: - The runlist must be locked on entry and is left locked on return.
227 * - If @write_locked is FALSE, i.e. the runlist is locked for reading,
228 * the lock may be dropped inside the function so you cannot rely on
229 * the runlist still being the same when this function returns.
1da177e4 230 */
c0c1cc0e 231runlist_element *ntfs_attr_find_vcn_nolock(ntfs_inode *ni, const VCN vcn,
b6ad6c52 232 const BOOL write_locked)
1da177e4
LT
233{
234 runlist_element *rl;
235 int err = 0;
236 BOOL is_retry = FALSE;
237
b6ad6c52 238 ntfs_debug("Entering for i_ino 0x%lx, vcn 0x%llx, %s_locked.",
1da177e4 239 ni->mft_no, (unsigned long long)vcn,
b6ad6c52 240 write_locked ? "write" : "read");
1da177e4
LT
241 BUG_ON(!ni);
242 BUG_ON(!NInoNonResident(ni));
243 BUG_ON(vcn < 0);
b6ad6c52 244retry_remap:
1da177e4
LT
245 rl = ni->runlist.rl;
246 if (likely(rl && vcn >= rl[0].vcn)) {
247 while (likely(rl->length)) {
b6ad6c52 248 if (unlikely(vcn < rl[1].vcn)) {
1da177e4
LT
249 if (likely(rl->lcn >= LCN_HOLE)) {
250 ntfs_debug("Done.");
251 return rl;
252 }
253 break;
254 }
255 rl++;
256 }
257 if (likely(rl->lcn != LCN_RL_NOT_MAPPED)) {
258 if (likely(rl->lcn == LCN_ENOENT))
259 err = -ENOENT;
260 else
261 err = -EIO;
262 }
263 }
1da177e4
LT
264 if (!err && !is_retry) {
265 /*
266 * The @vcn is in an unmapped region, map the runlist and
267 * retry.
268 */
b6ad6c52
AA
269 if (!write_locked) {
270 up_read(&ni->runlist.lock);
271 down_write(&ni->runlist.lock);
c0c1cc0e
AA
272 if (unlikely(ntfs_rl_vcn_to_lcn(ni->runlist.rl, vcn) !=
273 LCN_RL_NOT_MAPPED)) {
274 up_write(&ni->runlist.lock);
275 down_read(&ni->runlist.lock);
276 goto retry_remap;
277 }
b6ad6c52
AA
278 }
279 err = ntfs_map_runlist_nolock(ni, vcn);
280 if (!write_locked) {
281 up_write(&ni->runlist.lock);
282 down_read(&ni->runlist.lock);
283 }
1da177e4
LT
284 if (likely(!err)) {
285 is_retry = TRUE;
b6ad6c52 286 goto retry_remap;
1da177e4
LT
287 }
288 /*
289 * -EINVAL and -ENOENT coming from a failed mapping attempt are
290 * equivalent to i/o errors for us as they should not happen in
291 * our code paths.
292 */
293 if (err == -EINVAL || err == -ENOENT)
294 err = -EIO;
295 } else if (!err)
296 err = -EIO;
b6ad6c52
AA
297 if (err != -ENOENT)
298 ntfs_error(ni->vol->sb, "Failed with error code %i.", err);
1da177e4
LT
299 return ERR_PTR(err);
300}
301
302/**
303 * ntfs_attr_find - find (next) attribute in mft record
304 * @type: attribute type to find
305 * @name: attribute name to find (optional, i.e. NULL means don't care)
306 * @name_len: attribute name length (only needed if @name present)
307 * @ic: IGNORE_CASE or CASE_SENSITIVE (ignored if @name not present)
308 * @val: attribute value to find (optional, resident attributes only)
309 * @val_len: attribute value length
310 * @ctx: search context with mft record and attribute to search from
311 *
312 * You should not need to call this function directly. Use ntfs_attr_lookup()
313 * instead.
314 *
315 * ntfs_attr_find() takes a search context @ctx as parameter and searches the
316 * mft record specified by @ctx->mrec, beginning at @ctx->attr, for an
317 * attribute of @type, optionally @name and @val.
318 *
319 * If the attribute is found, ntfs_attr_find() returns 0 and @ctx->attr will
320 * point to the found attribute.
321 *
322 * If the attribute is not found, ntfs_attr_find() returns -ENOENT and
323 * @ctx->attr will point to the attribute before which the attribute being
324 * searched for would need to be inserted if such an action were to be desired.
325 *
326 * On actual error, ntfs_attr_find() returns -EIO. In this case @ctx->attr is
327 * undefined and in particular do not rely on it not changing.
328 *
329 * If @ctx->is_first is TRUE, the search begins with @ctx->attr itself. If it
330 * is FALSE, the search begins after @ctx->attr.
331 *
332 * If @ic is IGNORE_CASE, the @name comparisson is not case sensitive and
333 * @ctx->ntfs_ino must be set to the ntfs inode to which the mft record
334 * @ctx->mrec belongs. This is so we can get at the ntfs volume and hence at
335 * the upcase table. If @ic is CASE_SENSITIVE, the comparison is case
336 * sensitive. When @name is present, @name_len is the @name length in Unicode
337 * characters.
338 *
339 * If @name is not present (NULL), we assume that the unnamed attribute is
340 * being searched for.
341 *
342 * Finally, the resident attribute value @val is looked for, if present. If
343 * @val is not present (NULL), @val_len is ignored.
344 *
345 * ntfs_attr_find() only searches the specified mft record and it ignores the
346 * presence of an attribute list attribute (unless it is the one being searched
347 * for, obviously). If you need to take attribute lists into consideration,
348 * use ntfs_attr_lookup() instead (see below). This also means that you cannot
349 * use ntfs_attr_find() to search for extent records of non-resident
350 * attributes, as extents with lowest_vcn != 0 are usually described by the
351 * attribute list attribute only. - Note that it is possible that the first
352 * extent is only in the attribute list while the last extent is in the base
353 * mft record, so do not rely on being able to find the first extent in the
354 * base mft record.
355 *
356 * Warning: Never use @val when looking for attribute types which can be
357 * non-resident as this most likely will result in a crash!
358 */
359static int ntfs_attr_find(const ATTR_TYPE type, const ntfschar *name,
360 const u32 name_len, const IGNORE_CASE_BOOL ic,
361 const u8 *val, const u32 val_len, ntfs_attr_search_ctx *ctx)
362{
363 ATTR_RECORD *a;
364 ntfs_volume *vol = ctx->ntfs_ino->vol;
365 ntfschar *upcase = vol->upcase;
366 u32 upcase_len = vol->upcase_len;
367
368 /*
369 * Iterate over attributes in mft record starting at @ctx->attr, or the
370 * attribute following that, if @ctx->is_first is TRUE.
371 */
372 if (ctx->is_first) {
373 a = ctx->attr;
374 ctx->is_first = FALSE;
375 } else
376 a = (ATTR_RECORD*)((u8*)ctx->attr +
377 le32_to_cpu(ctx->attr->length));
378 for (;; a = (ATTR_RECORD*)((u8*)a + le32_to_cpu(a->length))) {
379 if ((u8*)a < (u8*)ctx->mrec || (u8*)a > (u8*)ctx->mrec +
380 le32_to_cpu(ctx->mrec->bytes_allocated))
381 break;
382 ctx->attr = a;
383 if (unlikely(le32_to_cpu(a->type) > le32_to_cpu(type) ||
384 a->type == AT_END))
385 return -ENOENT;
386 if (unlikely(!a->length))
387 break;
388 if (a->type != type)
389 continue;
390 /*
391 * If @name is present, compare the two names. If @name is
392 * missing, assume we want an unnamed attribute.
393 */
394 if (!name) {
395 /* The search failed if the found attribute is named. */
396 if (a->name_length)
397 return -ENOENT;
398 } else if (!ntfs_are_names_equal(name, name_len,
399 (ntfschar*)((u8*)a + le16_to_cpu(a->name_offset)),
400 a->name_length, ic, upcase, upcase_len)) {
401 register int rc;
402
403 rc = ntfs_collate_names(name, name_len,
404 (ntfschar*)((u8*)a +
405 le16_to_cpu(a->name_offset)),
406 a->name_length, 1, IGNORE_CASE,
407 upcase, upcase_len);
408 /*
409 * If @name collates before a->name, there is no
410 * matching attribute.
411 */
412 if (rc == -1)
413 return -ENOENT;
414 /* If the strings are not equal, continue search. */
415 if (rc)
416 continue;
417 rc = ntfs_collate_names(name, name_len,
418 (ntfschar*)((u8*)a +
419 le16_to_cpu(a->name_offset)),
420 a->name_length, 1, CASE_SENSITIVE,
421 upcase, upcase_len);
422 if (rc == -1)
423 return -ENOENT;
424 if (rc)
425 continue;
426 }
427 /*
428 * The names match or @name not present and attribute is
429 * unnamed. If no @val specified, we have found the attribute
430 * and are done.
431 */
432 if (!val)
433 return 0;
434 /* @val is present; compare values. */
435 else {
436 register int rc;
437
438 rc = memcmp(val, (u8*)a + le16_to_cpu(
439 a->data.resident.value_offset),
440 min_t(u32, val_len, le32_to_cpu(
441 a->data.resident.value_length)));
442 /*
443 * If @val collates before the current attribute's
444 * value, there is no matching attribute.
445 */
446 if (!rc) {
447 register u32 avl;
448
449 avl = le32_to_cpu(
450 a->data.resident.value_length);
451 if (val_len == avl)
452 return 0;
453 if (val_len < avl)
454 return -ENOENT;
455 } else if (rc < 0)
456 return -ENOENT;
457 }
458 }
459 ntfs_error(vol->sb, "Inode is corrupt. Run chkdsk.");
460 NVolSetErrors(vol);
461 return -EIO;
462}
463
464/**
465 * load_attribute_list - load an attribute list into memory
466 * @vol: ntfs volume from which to read
467 * @runlist: runlist of the attribute list
468 * @al_start: destination buffer
469 * @size: size of the destination buffer in bytes
470 * @initialized_size: initialized size of the attribute list
471 *
472 * Walk the runlist @runlist and load all clusters from it copying them into
473 * the linear buffer @al. The maximum number of bytes copied to @al is @size
474 * bytes. Note, @size does not need to be a multiple of the cluster size. If
475 * @initialized_size is less than @size, the region in @al between
476 * @initialized_size and @size will be zeroed and not read from disk.
477 *
478 * Return 0 on success or -errno on error.
479 */
480int load_attribute_list(ntfs_volume *vol, runlist *runlist, u8 *al_start,
481 const s64 size, const s64 initialized_size)
482{
483 LCN lcn;
484 u8 *al = al_start;
485 u8 *al_end = al + initialized_size;
486 runlist_element *rl;
487 struct buffer_head *bh;
488 struct super_block *sb;
489 unsigned long block_size;
490 unsigned long block, max_block;
491 int err = 0;
492 unsigned char block_size_bits;
493
494 ntfs_debug("Entering.");
495 if (!vol || !runlist || !al || size <= 0 || initialized_size < 0 ||
496 initialized_size > size)
497 return -EINVAL;
498 if (!initialized_size) {
499 memset(al, 0, size);
500 return 0;
501 }
502 sb = vol->sb;
503 block_size = sb->s_blocksize;
504 block_size_bits = sb->s_blocksize_bits;
505 down_read(&runlist->lock);
506 rl = runlist->rl;
507 /* Read all clusters specified by the runlist one run at a time. */
508 while (rl->length) {
509 lcn = ntfs_rl_vcn_to_lcn(rl, rl->vcn);
510 ntfs_debug("Reading vcn = 0x%llx, lcn = 0x%llx.",
511 (unsigned long long)rl->vcn,
512 (unsigned long long)lcn);
513 /* The attribute list cannot be sparse. */
514 if (lcn < 0) {
515 ntfs_error(sb, "ntfs_rl_vcn_to_lcn() failed. Cannot "
516 "read attribute list.");
517 goto err_out;
518 }
519 block = lcn << vol->cluster_size_bits >> block_size_bits;
520 /* Read the run from device in chunks of block_size bytes. */
521 max_block = block + (rl->length << vol->cluster_size_bits >>
522 block_size_bits);
523 ntfs_debug("max_block = 0x%lx.", max_block);
524 do {
525 ntfs_debug("Reading block = 0x%lx.", block);
526 bh = sb_bread(sb, block);
527 if (!bh) {
528 ntfs_error(sb, "sb_bread() failed. Cannot "
529 "read attribute list.");
530 goto err_out;
531 }
532 if (al + block_size >= al_end)
533 goto do_final;
534 memcpy(al, bh->b_data, block_size);
535 brelse(bh);
536 al += block_size;
537 } while (++block < max_block);
538 rl++;
539 }
540 if (initialized_size < size) {
541initialize:
542 memset(al_start + initialized_size, 0, size - initialized_size);
543 }
544done:
545 up_read(&runlist->lock);
546 return err;
547do_final:
548 if (al < al_end) {
549 /*
550 * Partial block.
551 *
552 * Note: The attribute list can be smaller than its allocation
553 * by multiple clusters. This has been encountered by at least
554 * two people running Windows XP, thus we cannot do any
555 * truncation sanity checking here. (AIA)
556 */
557 memcpy(al, bh->b_data, al_end - al);
558 brelse(bh);
559 if (initialized_size < size)
560 goto initialize;
561 goto done;
562 }
563 brelse(bh);
564 /* Real overflow! */
565 ntfs_error(sb, "Attribute list buffer overflow. Read attribute list "
566 "is truncated.");
567err_out:
568 err = -EIO;
569 goto done;
570}
571
572/**
573 * ntfs_external_attr_find - find an attribute in the attribute list of an inode
574 * @type: attribute type to find
575 * @name: attribute name to find (optional, i.e. NULL means don't care)
576 * @name_len: attribute name length (only needed if @name present)
577 * @ic: IGNORE_CASE or CASE_SENSITIVE (ignored if @name not present)
578 * @lowest_vcn: lowest vcn to find (optional, non-resident attributes only)
579 * @val: attribute value to find (optional, resident attributes only)
580 * @val_len: attribute value length
581 * @ctx: search context with mft record and attribute to search from
582 *
583 * You should not need to call this function directly. Use ntfs_attr_lookup()
584 * instead.
585 *
586 * Find an attribute by searching the attribute list for the corresponding
587 * attribute list entry. Having found the entry, map the mft record if the
588 * attribute is in a different mft record/inode, ntfs_attr_find() the attribute
589 * in there and return it.
590 *
591 * On first search @ctx->ntfs_ino must be the base mft record and @ctx must
592 * have been obtained from a call to ntfs_attr_get_search_ctx(). On subsequent
593 * calls @ctx->ntfs_ino can be any extent inode, too (@ctx->base_ntfs_ino is
594 * then the base inode).
595 *
596 * After finishing with the attribute/mft record you need to call
597 * ntfs_attr_put_search_ctx() to cleanup the search context (unmapping any
598 * mapped inodes, etc).
599 *
600 * If the attribute is found, ntfs_external_attr_find() returns 0 and
601 * @ctx->attr will point to the found attribute. @ctx->mrec will point to the
602 * mft record in which @ctx->attr is located and @ctx->al_entry will point to
603 * the attribute list entry for the attribute.
604 *
605 * If the attribute is not found, ntfs_external_attr_find() returns -ENOENT and
606 * @ctx->attr will point to the attribute in the base mft record before which
607 * the attribute being searched for would need to be inserted if such an action
608 * were to be desired. @ctx->mrec will point to the mft record in which
609 * @ctx->attr is located and @ctx->al_entry will point to the attribute list
610 * entry of the attribute before which the attribute being searched for would
611 * need to be inserted if such an action were to be desired.
612 *
613 * Thus to insert the not found attribute, one wants to add the attribute to
614 * @ctx->mrec (the base mft record) and if there is not enough space, the
615 * attribute should be placed in a newly allocated extent mft record. The
616 * attribute list entry for the inserted attribute should be inserted in the
617 * attribute list attribute at @ctx->al_entry.
618 *
619 * On actual error, ntfs_external_attr_find() returns -EIO. In this case
620 * @ctx->attr is undefined and in particular do not rely on it not changing.
621 */
622static int ntfs_external_attr_find(const ATTR_TYPE type,
623 const ntfschar *name, const u32 name_len,
624 const IGNORE_CASE_BOOL ic, const VCN lowest_vcn,
625 const u8 *val, const u32 val_len, ntfs_attr_search_ctx *ctx)
626{
627 ntfs_inode *base_ni, *ni;
628 ntfs_volume *vol;
629 ATTR_LIST_ENTRY *al_entry, *next_al_entry;
630 u8 *al_start, *al_end;
631 ATTR_RECORD *a;
632 ntfschar *al_name;
633 u32 al_name_len;
634 int err = 0;
635 static const char *es = " Unmount and run chkdsk.";
636
637 ni = ctx->ntfs_ino;
638 base_ni = ctx->base_ntfs_ino;
639 ntfs_debug("Entering for inode 0x%lx, type 0x%x.", ni->mft_no, type);
640 if (!base_ni) {
641 /* First call happens with the base mft record. */
642 base_ni = ctx->base_ntfs_ino = ctx->ntfs_ino;
643 ctx->base_mrec = ctx->mrec;
644 }
645 if (ni == base_ni)
646 ctx->base_attr = ctx->attr;
647 if (type == AT_END)
648 goto not_found;
649 vol = base_ni->vol;
650 al_start = base_ni->attr_list;
651 al_end = al_start + base_ni->attr_list_size;
652 if (!ctx->al_entry)
653 ctx->al_entry = (ATTR_LIST_ENTRY*)al_start;
654 /*
655 * Iterate over entries in attribute list starting at @ctx->al_entry,
656 * or the entry following that, if @ctx->is_first is TRUE.
657 */
658 if (ctx->is_first) {
659 al_entry = ctx->al_entry;
660 ctx->is_first = FALSE;
661 } else
662 al_entry = (ATTR_LIST_ENTRY*)((u8*)ctx->al_entry +
663 le16_to_cpu(ctx->al_entry->length));
664 for (;; al_entry = next_al_entry) {
665 /* Out of bounds check. */
666 if ((u8*)al_entry < base_ni->attr_list ||
667 (u8*)al_entry > al_end)
668 break; /* Inode is corrupt. */
669 ctx->al_entry = al_entry;
670 /* Catch the end of the attribute list. */
671 if ((u8*)al_entry == al_end)
672 goto not_found;
673 if (!al_entry->length)
674 break;
675 if ((u8*)al_entry + 6 > al_end || (u8*)al_entry +
676 le16_to_cpu(al_entry->length) > al_end)
677 break;
678 next_al_entry = (ATTR_LIST_ENTRY*)((u8*)al_entry +
679 le16_to_cpu(al_entry->length));
680 if (le32_to_cpu(al_entry->type) > le32_to_cpu(type))
681 goto not_found;
682 if (type != al_entry->type)
683 continue;
684 /*
685 * If @name is present, compare the two names. If @name is
686 * missing, assume we want an unnamed attribute.
687 */
688 al_name_len = al_entry->name_length;
689 al_name = (ntfschar*)((u8*)al_entry + al_entry->name_offset);
690 if (!name) {
691 if (al_name_len)
692 goto not_found;
693 } else if (!ntfs_are_names_equal(al_name, al_name_len, name,
694 name_len, ic, vol->upcase, vol->upcase_len)) {
695 register int rc;
696
697 rc = ntfs_collate_names(name, name_len, al_name,
698 al_name_len, 1, IGNORE_CASE,
699 vol->upcase, vol->upcase_len);
700 /*
701 * If @name collates before al_name, there is no
702 * matching attribute.
703 */
704 if (rc == -1)
705 goto not_found;
706 /* If the strings are not equal, continue search. */
707 if (rc)
708 continue;
709 /*
710 * FIXME: Reverse engineering showed 0, IGNORE_CASE but
711 * that is inconsistent with ntfs_attr_find(). The
712 * subsequent rc checks were also different. Perhaps I
713 * made a mistake in one of the two. Need to recheck
714 * which is correct or at least see what is going on...
715 * (AIA)
716 */
717 rc = ntfs_collate_names(name, name_len, al_name,
718 al_name_len, 1, CASE_SENSITIVE,
719 vol->upcase, vol->upcase_len);
720 if (rc == -1)
721 goto not_found;
722 if (rc)
723 continue;
724 }
725 /*
726 * The names match or @name not present and attribute is
727 * unnamed. Now check @lowest_vcn. Continue search if the
728 * next attribute list entry still fits @lowest_vcn. Otherwise
729 * we have reached the right one or the search has failed.
730 */
731 if (lowest_vcn && (u8*)next_al_entry >= al_start &&
732 (u8*)next_al_entry + 6 < al_end &&
733 (u8*)next_al_entry + le16_to_cpu(
734 next_al_entry->length) <= al_end &&
735 sle64_to_cpu(next_al_entry->lowest_vcn) <=
736 lowest_vcn &&
737 next_al_entry->type == al_entry->type &&
738 next_al_entry->name_length == al_name_len &&
739 ntfs_are_names_equal((ntfschar*)((u8*)
740 next_al_entry +
741 next_al_entry->name_offset),
742 next_al_entry->name_length,
743 al_name, al_name_len, CASE_SENSITIVE,
744 vol->upcase, vol->upcase_len))
745 continue;
746 if (MREF_LE(al_entry->mft_reference) == ni->mft_no) {
747 if (MSEQNO_LE(al_entry->mft_reference) != ni->seq_no) {
748 ntfs_error(vol->sb, "Found stale mft "
749 "reference in attribute list "
750 "of base inode 0x%lx.%s",
751 base_ni->mft_no, es);
752 err = -EIO;
753 break;
754 }
755 } else { /* Mft references do not match. */
756 /* If there is a mapped record unmap it first. */
757 if (ni != base_ni)
758 unmap_extent_mft_record(ni);
759 /* Do we want the base record back? */
760 if (MREF_LE(al_entry->mft_reference) ==
761 base_ni->mft_no) {
762 ni = ctx->ntfs_ino = base_ni;
763 ctx->mrec = ctx->base_mrec;
764 } else {
765 /* We want an extent record. */
766 ctx->mrec = map_extent_mft_record(base_ni,
767 le64_to_cpu(
768 al_entry->mft_reference), &ni);
769 if (IS_ERR(ctx->mrec)) {
770 ntfs_error(vol->sb, "Failed to map "
771 "extent mft record "
772 "0x%lx of base inode "
773 "0x%lx.%s",
774 MREF_LE(al_entry->
775 mft_reference),
776 base_ni->mft_no, es);
777 err = PTR_ERR(ctx->mrec);
778 if (err == -ENOENT)
779 err = -EIO;
780 /* Cause @ctx to be sanitized below. */
781 ni = NULL;
782 break;
783 }
784 ctx->ntfs_ino = ni;
785 }
786 ctx->attr = (ATTR_RECORD*)((u8*)ctx->mrec +
787 le16_to_cpu(ctx->mrec->attrs_offset));
788 }
789 /*
790 * ctx->vfs_ino, ctx->mrec, and ctx->attr now point to the
791 * mft record containing the attribute represented by the
792 * current al_entry.
793 */
794 /*
795 * We could call into ntfs_attr_find() to find the right
796 * attribute in this mft record but this would be less
797 * efficient and not quite accurate as ntfs_attr_find() ignores
798 * the attribute instance numbers for example which become
799 * important when one plays with attribute lists. Also,
800 * because a proper match has been found in the attribute list
801 * entry above, the comparison can now be optimized. So it is
802 * worth re-implementing a simplified ntfs_attr_find() here.
803 */
804 a = ctx->attr;
805 /*
806 * Use a manual loop so we can still use break and continue
807 * with the same meanings as above.
808 */
809do_next_attr_loop:
810 if ((u8*)a < (u8*)ctx->mrec || (u8*)a > (u8*)ctx->mrec +
811 le32_to_cpu(ctx->mrec->bytes_allocated))
812 break;
813 if (a->type == AT_END)
814 continue;
815 if (!a->length)
816 break;
817 if (al_entry->instance != a->instance)
818 goto do_next_attr;
819 /*
820 * If the type and/or the name are mismatched between the
821 * attribute list entry and the attribute record, there is
822 * corruption so we break and return error EIO.
823 */
824 if (al_entry->type != a->type)
825 break;
826 if (!ntfs_are_names_equal((ntfschar*)((u8*)a +
827 le16_to_cpu(a->name_offset)), a->name_length,
828 al_name, al_name_len, CASE_SENSITIVE,
829 vol->upcase, vol->upcase_len))
830 break;
831 ctx->attr = a;
832 /*
833 * If no @val specified or @val specified and it matches, we
834 * have found it!
835 */
836 if (!val || (!a->non_resident && le32_to_cpu(
837 a->data.resident.value_length) == val_len &&
838 !memcmp((u8*)a +
839 le16_to_cpu(a->data.resident.value_offset),
840 val, val_len))) {
841 ntfs_debug("Done, found.");
842 return 0;
843 }
844do_next_attr:
845 /* Proceed to the next attribute in the current mft record. */
846 a = (ATTR_RECORD*)((u8*)a + le32_to_cpu(a->length));
847 goto do_next_attr_loop;
848 }
849 if (!err) {
850 ntfs_error(vol->sb, "Base inode 0x%lx contains corrupt "
851 "attribute list attribute.%s", base_ni->mft_no,
852 es);
853 err = -EIO;
854 }
855 if (ni != base_ni) {
856 if (ni)
857 unmap_extent_mft_record(ni);
858 ctx->ntfs_ino = base_ni;
859 ctx->mrec = ctx->base_mrec;
860 ctx->attr = ctx->base_attr;
861 }
862 if (err != -ENOMEM)
863 NVolSetErrors(vol);
864 return err;
865not_found:
866 /*
867 * If we were looking for AT_END, we reset the search context @ctx and
868 * use ntfs_attr_find() to seek to the end of the base mft record.
869 */
870 if (type == AT_END) {
871 ntfs_attr_reinit_search_ctx(ctx);
872 return ntfs_attr_find(AT_END, name, name_len, ic, val, val_len,
873 ctx);
874 }
875 /*
876 * The attribute was not found. Before we return, we want to ensure
877 * @ctx->mrec and @ctx->attr indicate the position at which the
878 * attribute should be inserted in the base mft record. Since we also
879 * want to preserve @ctx->al_entry we cannot reinitialize the search
880 * context using ntfs_attr_reinit_search_ctx() as this would set
881 * @ctx->al_entry to NULL. Thus we do the necessary bits manually (see
882 * ntfs_attr_init_search_ctx() below). Note, we _only_ preserve
883 * @ctx->al_entry as the remaining fields (base_*) are identical to
884 * their non base_ counterparts and we cannot set @ctx->base_attr
885 * correctly yet as we do not know what @ctx->attr will be set to by
886 * the call to ntfs_attr_find() below.
887 */
888 if (ni != base_ni)
889 unmap_extent_mft_record(ni);
890 ctx->mrec = ctx->base_mrec;
891 ctx->attr = (ATTR_RECORD*)((u8*)ctx->mrec +
892 le16_to_cpu(ctx->mrec->attrs_offset));
893 ctx->is_first = TRUE;
894 ctx->ntfs_ino = base_ni;
895 ctx->base_ntfs_ino = NULL;
896 ctx->base_mrec = NULL;
897 ctx->base_attr = NULL;
898 /*
899 * In case there are multiple matches in the base mft record, need to
900 * keep enumerating until we get an attribute not found response (or
901 * another error), otherwise we would keep returning the same attribute
902 * over and over again and all programs using us for enumeration would
903 * lock up in a tight loop.
904 */
905 do {
906 err = ntfs_attr_find(type, name, name_len, ic, val, val_len,
907 ctx);
908 } while (!err);
909 ntfs_debug("Done, not found.");
910 return err;
911}
912
913/**
914 * ntfs_attr_lookup - find an attribute in an ntfs inode
915 * @type: attribute type to find
916 * @name: attribute name to find (optional, i.e. NULL means don't care)
917 * @name_len: attribute name length (only needed if @name present)
918 * @ic: IGNORE_CASE or CASE_SENSITIVE (ignored if @name not present)
919 * @lowest_vcn: lowest vcn to find (optional, non-resident attributes only)
920 * @val: attribute value to find (optional, resident attributes only)
921 * @val_len: attribute value length
922 * @ctx: search context with mft record and attribute to search from
923 *
924 * Find an attribute in an ntfs inode. On first search @ctx->ntfs_ino must
925 * be the base mft record and @ctx must have been obtained from a call to
926 * ntfs_attr_get_search_ctx().
927 *
928 * This function transparently handles attribute lists and @ctx is used to
929 * continue searches where they were left off at.
930 *
931 * After finishing with the attribute/mft record you need to call
932 * ntfs_attr_put_search_ctx() to cleanup the search context (unmapping any
933 * mapped inodes, etc).
934 *
935 * Return 0 if the search was successful and -errno if not.
936 *
937 * When 0, @ctx->attr is the found attribute and it is in mft record
938 * @ctx->mrec. If an attribute list attribute is present, @ctx->al_entry is
939 * the attribute list entry of the found attribute.
940 *
941 * When -ENOENT, @ctx->attr is the attribute which collates just after the
942 * attribute being searched for, i.e. if one wants to add the attribute to the
943 * mft record this is the correct place to insert it into. If an attribute
944 * list attribute is present, @ctx->al_entry is the attribute list entry which
945 * collates just after the attribute list entry of the attribute being searched
946 * for, i.e. if one wants to add the attribute to the mft record this is the
947 * correct place to insert its attribute list entry into.
948 *
949 * When -errno != -ENOENT, an error occured during the lookup. @ctx->attr is
950 * then undefined and in particular you should not rely on it not changing.
951 */
952int ntfs_attr_lookup(const ATTR_TYPE type, const ntfschar *name,
953 const u32 name_len, const IGNORE_CASE_BOOL ic,
954 const VCN lowest_vcn, const u8 *val, const u32 val_len,
955 ntfs_attr_search_ctx *ctx)
956{
957 ntfs_inode *base_ni;
958
959 ntfs_debug("Entering.");
960 if (ctx->base_ntfs_ino)
961 base_ni = ctx->base_ntfs_ino;
962 else
963 base_ni = ctx->ntfs_ino;
964 /* Sanity check, just for debugging really. */
965 BUG_ON(!base_ni);
966 if (!NInoAttrList(base_ni) || type == AT_ATTRIBUTE_LIST)
967 return ntfs_attr_find(type, name, name_len, ic, val, val_len,
968 ctx);
969 return ntfs_external_attr_find(type, name, name_len, ic, lowest_vcn,
970 val, val_len, ctx);
971}
972
973/**
974 * ntfs_attr_init_search_ctx - initialize an attribute search context
975 * @ctx: attribute search context to initialize
976 * @ni: ntfs inode with which to initialize the search context
977 * @mrec: mft record with which to initialize the search context
978 *
979 * Initialize the attribute search context @ctx with @ni and @mrec.
980 */
981static inline void ntfs_attr_init_search_ctx(ntfs_attr_search_ctx *ctx,
982 ntfs_inode *ni, MFT_RECORD *mrec)
983{
984 ctx->mrec = mrec;
985 /* Sanity checks are performed elsewhere. */
986 ctx->attr = (ATTR_RECORD*)((u8*)mrec + le16_to_cpu(mrec->attrs_offset));
987 ctx->is_first = TRUE;
988 ctx->ntfs_ino = ni;
989 ctx->al_entry = NULL;
990 ctx->base_ntfs_ino = NULL;
991 ctx->base_mrec = NULL;
992 ctx->base_attr = NULL;
993}
994
995/**
996 * ntfs_attr_reinit_search_ctx - reinitialize an attribute search context
997 * @ctx: attribute search context to reinitialize
998 *
999 * Reinitialize the attribute search context @ctx, unmapping an associated
1000 * extent mft record if present, and initialize the search context again.
1001 *
1002 * This is used when a search for a new attribute is being started to reset
1003 * the search context to the beginning.
1004 */
1005void ntfs_attr_reinit_search_ctx(ntfs_attr_search_ctx *ctx)
1006{
1007 if (likely(!ctx->base_ntfs_ino)) {
1008 /* No attribute list. */
1009 ctx->is_first = TRUE;
1010 /* Sanity checks are performed elsewhere. */
1011 ctx->attr = (ATTR_RECORD*)((u8*)ctx->mrec +
1012 le16_to_cpu(ctx->mrec->attrs_offset));
1013 /*
1014 * This needs resetting due to ntfs_external_attr_find() which
1015 * can leave it set despite having zeroed ctx->base_ntfs_ino.
1016 */
1017 ctx->al_entry = NULL;
1018 return;
1019 } /* Attribute list. */
1020 if (ctx->ntfs_ino != ctx->base_ntfs_ino)
1021 unmap_extent_mft_record(ctx->ntfs_ino);
1022 ntfs_attr_init_search_ctx(ctx, ctx->base_ntfs_ino, ctx->base_mrec);
1023 return;
1024}
1025
1026/**
1027 * ntfs_attr_get_search_ctx - allocate/initialize a new attribute search context
1028 * @ni: ntfs inode with which to initialize the search context
1029 * @mrec: mft record with which to initialize the search context
1030 *
1031 * Allocate a new attribute search context, initialize it with @ni and @mrec,
1032 * and return it. Return NULL if allocation failed.
1033 */
1034ntfs_attr_search_ctx *ntfs_attr_get_search_ctx(ntfs_inode *ni, MFT_RECORD *mrec)
1035{
1036 ntfs_attr_search_ctx *ctx;
1037
1038 ctx = kmem_cache_alloc(ntfs_attr_ctx_cache, SLAB_NOFS);
1039 if (ctx)
1040 ntfs_attr_init_search_ctx(ctx, ni, mrec);
1041 return ctx;
1042}
1043
1044/**
1045 * ntfs_attr_put_search_ctx - release an attribute search context
1046 * @ctx: attribute search context to free
1047 *
1048 * Release the attribute search context @ctx, unmapping an associated extent
1049 * mft record if present.
1050 */
1051void ntfs_attr_put_search_ctx(ntfs_attr_search_ctx *ctx)
1052{
1053 if (ctx->base_ntfs_ino && ctx->ntfs_ino != ctx->base_ntfs_ino)
1054 unmap_extent_mft_record(ctx->ntfs_ino);
1055 kmem_cache_free(ntfs_attr_ctx_cache, ctx);
1056 return;
1057}
1058
1059/**
1060 * ntfs_attr_find_in_attrdef - find an attribute in the $AttrDef system file
1061 * @vol: ntfs volume to which the attribute belongs
1062 * @type: attribute type which to find
1063 *
1064 * Search for the attribute definition record corresponding to the attribute
1065 * @type in the $AttrDef system file.
1066 *
1067 * Return the attribute type definition record if found and NULL if not found.
1068 */
1069static ATTR_DEF *ntfs_attr_find_in_attrdef(const ntfs_volume *vol,
1070 const ATTR_TYPE type)
1071{
1072 ATTR_DEF *ad;
1073
1074 BUG_ON(!vol->attrdef);
1075 BUG_ON(!type);
1076 for (ad = vol->attrdef; (u8*)ad - (u8*)vol->attrdef <
1077 vol->attrdef_size && ad->type; ++ad) {
1078 /* We have not found it yet, carry on searching. */
1079 if (likely(le32_to_cpu(ad->type) < le32_to_cpu(type)))
1080 continue;
1081 /* We found the attribute; return it. */
1082 if (likely(ad->type == type))
1083 return ad;
1084 /* We have gone too far already. No point in continuing. */
1085 break;
1086 }
1087 /* Attribute not found. */
1088 ntfs_debug("Attribute type 0x%x not found in $AttrDef.",
1089 le32_to_cpu(type));
1090 return NULL;
1091}
1092
1093/**
1094 * ntfs_attr_size_bounds_check - check a size of an attribute type for validity
1095 * @vol: ntfs volume to which the attribute belongs
1096 * @type: attribute type which to check
1097 * @size: size which to check
1098 *
1099 * Check whether the @size in bytes is valid for an attribute of @type on the
1100 * ntfs volume @vol. This information is obtained from $AttrDef system file.
1101 *
1102 * Return 0 if valid, -ERANGE if not valid, or -ENOENT if the attribute is not
1103 * listed in $AttrDef.
1104 */
1105int ntfs_attr_size_bounds_check(const ntfs_volume *vol, const ATTR_TYPE type,
1106 const s64 size)
1107{
1108 ATTR_DEF *ad;
1109
1110 BUG_ON(size < 0);
1111 /*
1112 * $ATTRIBUTE_LIST has a maximum size of 256kiB, but this is not
1113 * listed in $AttrDef.
1114 */
1115 if (unlikely(type == AT_ATTRIBUTE_LIST && size > 256 * 1024))
1116 return -ERANGE;
1117 /* Get the $AttrDef entry for the attribute @type. */
1118 ad = ntfs_attr_find_in_attrdef(vol, type);
1119 if (unlikely(!ad))
1120 return -ENOENT;
1121 /* Do the bounds check. */
1122 if (((sle64_to_cpu(ad->min_size) > 0) &&
1123 size < sle64_to_cpu(ad->min_size)) ||
1124 ((sle64_to_cpu(ad->max_size) > 0) && size >
1125 sle64_to_cpu(ad->max_size)))
1126 return -ERANGE;
1127 return 0;
1128}
1129
1130/**
1131 * ntfs_attr_can_be_non_resident - check if an attribute can be non-resident
1132 * @vol: ntfs volume to which the attribute belongs
1133 * @type: attribute type which to check
1134 *
1135 * Check whether the attribute of @type on the ntfs volume @vol is allowed to
1136 * be non-resident. This information is obtained from $AttrDef system file.
1137 *
1138 * Return 0 if the attribute is allowed to be non-resident, -EPERM if not, or
1139 * -ENOENT if the attribute is not listed in $AttrDef.
1140 */
1141int ntfs_attr_can_be_non_resident(const ntfs_volume *vol, const ATTR_TYPE type)
1142{
1143 ATTR_DEF *ad;
1144
1145 /*
7e693073
AA
1146 * $DATA and $EA are always allowed to be non-resident even if $AttrDef
1147 * does not specify this in the flags of the $DATA attribute definition
1148 * record.
1da177e4 1149 */
7e693073 1150 if (type == AT_DATA || type == AT_EA)
1da177e4
LT
1151 return 0;
1152 /* Find the attribute definition record in $AttrDef. */
1153 ad = ntfs_attr_find_in_attrdef(vol, type);
1154 if (unlikely(!ad))
1155 return -ENOENT;
1156 /* Check the flags and return the result. */
1157 if (ad->flags & CAN_BE_NON_RESIDENT)
1158 return 0;
1159 return -EPERM;
1160}
1161
1162/**
1163 * ntfs_attr_can_be_resident - check if an attribute can be resident
1164 * @vol: ntfs volume to which the attribute belongs
1165 * @type: attribute type which to check
1166 *
1167 * Check whether the attribute of @type on the ntfs volume @vol is allowed to
1168 * be resident. This information is derived from our ntfs knowledge and may
1169 * not be completely accurate, especially when user defined attributes are
1170 * present. Basically we allow everything to be resident except for index
1171 * allocation and $EA attributes.
1172 *
1173 * Return 0 if the attribute is allowed to be non-resident and -EPERM if not.
1174 *
1175 * Warning: In the system file $MFT the attribute $Bitmap must be non-resident
1176 * otherwise windows will not boot (blue screen of death)! We cannot
1177 * check for this here as we do not know which inode's $Bitmap is
1178 * being asked about so the caller needs to special case this.
1179 */
1180int ntfs_attr_can_be_resident(const ntfs_volume *vol, const ATTR_TYPE type)
1181{
1182 if (type != AT_INDEX_ALLOCATION && type != AT_EA)
1183 return 0;
1184 return -EPERM;
1185}
1186
1187/**
1188 * ntfs_attr_record_resize - resize an attribute record
1189 * @m: mft record containing attribute record
1190 * @a: attribute record to resize
1191 * @new_size: new size in bytes to which to resize the attribute record @a
1192 *
1193 * Resize the attribute record @a, i.e. the resident part of the attribute, in
1194 * the mft record @m to @new_size bytes.
1195 *
1196 * Return 0 on success and -errno on error. The following error codes are
1197 * defined:
1198 * -ENOSPC - Not enough space in the mft record @m to perform the resize.
1199 *
1200 * Note: On error, no modifications have been performed whatsoever.
1201 *
1202 * Warning: If you make a record smaller without having copied all the data you
1203 * are interested in the data may be overwritten.
1204 */
1205int ntfs_attr_record_resize(MFT_RECORD *m, ATTR_RECORD *a, u32 new_size)
1206{
1207 ntfs_debug("Entering for new_size %u.", new_size);
1208 /* Align to 8 bytes if it is not already done. */
1209 if (new_size & 7)
1210 new_size = (new_size + 7) & ~7;
1211 /* If the actual attribute length has changed, move things around. */
1212 if (new_size != le32_to_cpu(a->length)) {
1213 u32 new_muse = le32_to_cpu(m->bytes_in_use) -
1214 le32_to_cpu(a->length) + new_size;
1215 /* Not enough space in this mft record. */
1216 if (new_muse > le32_to_cpu(m->bytes_allocated))
1217 return -ENOSPC;
1218 /* Move attributes following @a to their new location. */
1219 memmove((u8*)a + new_size, (u8*)a + le32_to_cpu(a->length),
1220 le32_to_cpu(m->bytes_in_use) - ((u8*)a -
1221 (u8*)m) - le32_to_cpu(a->length));
1222 /* Adjust @m to reflect the change in used space. */
1223 m->bytes_in_use = cpu_to_le32(new_muse);
1224 /* Adjust @a to reflect the new size. */
1225 if (new_size >= offsetof(ATTR_REC, length) + sizeof(a->length))
1226 a->length = cpu_to_le32(new_size);
1227 }
1228 return 0;
1229}
1230
2bfb4fff
AA
1231/**
1232 * ntfs_attr_make_non_resident - convert a resident to a non-resident attribute
1233 * @ni: ntfs inode describing the attribute to convert
1234 *
1235 * Convert the resident ntfs attribute described by the ntfs inode @ni to a
1236 * non-resident one.
1237 *
1238 * Return 0 on success and -errno on error. The following error return codes
1239 * are defined:
1240 * -EPERM - The attribute is not allowed to be non-resident.
1241 * -ENOMEM - Not enough memory.
1242 * -ENOSPC - Not enough disk space.
1243 * -EINVAL - Attribute not defined on the volume.
1244 * -EIO - I/o error or other error.
1245 *
1246 * NOTE to self: No changes in the attribute list are required to move from
1247 * a resident to a non-resident attribute.
1248 *
1249 * Locking: - The caller must hold i_sem on the inode.
1250 */
1251int ntfs_attr_make_non_resident(ntfs_inode *ni)
1252{
1253 s64 new_size;
1254 struct inode *vi = VFS_I(ni);
1255 ntfs_volume *vol = ni->vol;
1256 ntfs_inode *base_ni;
1257 MFT_RECORD *m;
1258 ATTR_RECORD *a;
1259 ntfs_attr_search_ctx *ctx;
1260 struct page *page;
1261 runlist_element *rl;
1262 u8 *kaddr;
1263 unsigned long flags;
1264 int mp_size, mp_ofs, name_ofs, arec_size, err, err2;
1265 u32 attr_size;
1266 u8 old_res_attr_flags;
1267
1268 /* Check that the attribute is allowed to be non-resident. */
1269 err = ntfs_attr_can_be_non_resident(vol, ni->type);
1270 if (unlikely(err)) {
1271 if (err == -EPERM)
1272 ntfs_debug("Attribute is not allowed to be "
1273 "non-resident.");
1274 else
1275 ntfs_debug("Attribute not defined on the NTFS "
1276 "volume!");
1277 return err;
1278 }
1279 /*
1280 * The size needs to be aligned to a cluster boundary for allocation
1281 * purposes.
1282 */
1283 new_size = (i_size_read(vi) + vol->cluster_size - 1) &
1284 ~(vol->cluster_size - 1);
1285 if (new_size > 0) {
1286 /*
1287 * Will need the page later and since the page lock nests
1288 * outside all ntfs locks, we need to get the page now.
1289 */
1290 page = find_or_create_page(vi->i_mapping, 0,
1291 mapping_gfp_mask(vi->i_mapping));
1292 if (unlikely(!page))
1293 return -ENOMEM;
1294 /* Start by allocating clusters to hold the attribute value. */
1295 rl = ntfs_cluster_alloc(vol, 0, new_size >>
1296 vol->cluster_size_bits, -1, DATA_ZONE);
1297 if (IS_ERR(rl)) {
1298 err = PTR_ERR(rl);
1299 ntfs_debug("Failed to allocate cluster%s, error code "
1300 "%i.\n", (new_size >>
1301 vol->cluster_size_bits) > 1 ? "s" : "",
1302 err);
1303 goto page_err_out;
1304 }
1305 } else {
1306 rl = NULL;
1307 page = NULL;
1308 }
1309 /* Determine the size of the mapping pairs array. */
1310 mp_size = ntfs_get_size_for_mapping_pairs(vol, rl, 0);
1311 if (unlikely(mp_size < 0)) {
1312 err = mp_size;
1313 ntfs_debug("Failed to get size for mapping pairs array, error "
1314 "code %i.", err);
1315 goto rl_err_out;
1316 }
1317 down_write(&ni->runlist.lock);
1318 if (!NInoAttr(ni))
1319 base_ni = ni;
1320 else
1321 base_ni = ni->ext.base_ntfs_ino;
1322 m = map_mft_record(base_ni);
1323 if (IS_ERR(m)) {
1324 err = PTR_ERR(m);
1325 m = NULL;
1326 ctx = NULL;
1327 goto err_out;
1328 }
1329 ctx = ntfs_attr_get_search_ctx(base_ni, m);
1330 if (unlikely(!ctx)) {
1331 err = -ENOMEM;
1332 goto err_out;
1333 }
1334 err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
1335 CASE_SENSITIVE, 0, NULL, 0, ctx);
1336 if (unlikely(err)) {
1337 if (err == -ENOENT)
1338 err = -EIO;
1339 goto err_out;
1340 }
1341 m = ctx->mrec;
1342 a = ctx->attr;
1343 BUG_ON(NInoNonResident(ni));
1344 BUG_ON(a->non_resident);
1345 /*
1346 * Calculate new offsets for the name and the mapping pairs array.
1347 * We assume the attribute is not compressed or sparse.
1348 */
1349 name_ofs = (offsetof(ATTR_REC,
1350 data.non_resident.compressed_size) + 7) & ~7;
1351 mp_ofs = (name_ofs + a->name_length * sizeof(ntfschar) + 7) & ~7;
1352 /*
1353 * Determine the size of the resident part of the now non-resident
1354 * attribute record.
1355 */
1356 arec_size = (mp_ofs + mp_size + 7) & ~7;
1357 /*
1358 * If the page is not uptodate bring it uptodate by copying from the
1359 * attribute value.
1360 */
1361 attr_size = le32_to_cpu(a->data.resident.value_length);
1362 BUG_ON(attr_size != i_size_read(vi));
1363 if (page && !PageUptodate(page)) {
1364 kaddr = kmap_atomic(page, KM_USER0);
1365 memcpy(kaddr, (u8*)a +
1366 le16_to_cpu(a->data.resident.value_offset),
1367 attr_size);
1368 memset(kaddr + attr_size, 0, PAGE_CACHE_SIZE - attr_size);
1369 kunmap_atomic(kaddr, KM_USER0);
1370 flush_dcache_page(page);
1371 SetPageUptodate(page);
1372 }
1373 /* Backup the attribute flag. */
1374 old_res_attr_flags = a->data.resident.flags;
1375 /* Resize the resident part of the attribute record. */
1376 err = ntfs_attr_record_resize(m, a, arec_size);
1377 if (unlikely(err))
1378 goto err_out;
1379 /* Setup the in-memory attribute structure to be non-resident. */
1380 NInoSetNonResident(ni);
1381 ni->runlist.rl = rl;
1382 write_lock_irqsave(&ni->size_lock, flags);
1383 ni->allocated_size = new_size;
1384 write_unlock_irqrestore(&ni->size_lock, flags);
1385 /*
1386 * FIXME: For now just clear all of these as we do not support them
1387 * when writing.
1388 */
1389 NInoClearCompressed(ni);
1390 NInoClearSparse(ni);
1391 NInoClearEncrypted(ni);
1392 /*
1393 * Convert the resident part of the attribute record to describe a
1394 * non-resident attribute.
1395 */
1396 a->non_resident = 1;
1397 /* Move the attribute name if it exists and update the offset. */
1398 if (a->name_length)
1399 memmove((u8*)a + name_ofs, (u8*)a + le16_to_cpu(a->name_offset),
1400 a->name_length * sizeof(ntfschar));
1401 a->name_offset = cpu_to_le16(name_ofs);
1402 /* Update the flags to match the in-memory ones. */
1403 a->flags &= cpu_to_le16(0xffff & ~le16_to_cpu(ATTR_IS_SPARSE |
1404 ATTR_IS_ENCRYPTED | ATTR_COMPRESSION_MASK));
1405 /* Setup the fields specific to non-resident attributes. */
1406 a->data.non_resident.lowest_vcn = 0;
1407 a->data.non_resident.highest_vcn = cpu_to_sle64((new_size - 1) >>
1408 vol->cluster_size_bits);
1409 a->data.non_resident.mapping_pairs_offset = cpu_to_le16(mp_ofs);
1410 a->data.non_resident.compression_unit = 0;
1411 memset(&a->data.non_resident.reserved, 0,
1412 sizeof(a->data.non_resident.reserved));
1413 a->data.non_resident.allocated_size = cpu_to_sle64(new_size);
1414 a->data.non_resident.data_size =
1415 a->data.non_resident.initialized_size =
1416 cpu_to_sle64(attr_size);
1417 /* Generate the mapping pairs array into the attribute record. */
1418 err = ntfs_mapping_pairs_build(vol, (u8*)a + mp_ofs,
1419 arec_size - mp_ofs, rl, 0, NULL);
1420 if (unlikely(err)) {
1421 ntfs_debug("Failed to build mapping pairs, error code %i.",
1422 err);
1423 goto undo_err_out;
1424 }
1425 /* Mark the mft record dirty, so it gets written back. */
1426 flush_dcache_mft_record_page(ctx->ntfs_ino);
1427 mark_mft_record_dirty(ctx->ntfs_ino);
1428 ntfs_attr_put_search_ctx(ctx);
1429 unmap_mft_record(base_ni);
1430 up_write(&ni->runlist.lock);
1431 if (page) {
1432 set_page_dirty(page);
1433 unlock_page(page);
1434 page_cache_release(page);
1435 }
1436 ntfs_debug("Done.");
1437 return 0;
1438undo_err_out:
1439 /* Convert the attribute back into a resident attribute. */
1440 a->non_resident = 0;
1441 /* Move the attribute name if it exists and update the offset. */
1442 name_ofs = (offsetof(ATTR_RECORD, data.resident.reserved) +
1443 sizeof(a->data.resident.reserved) + 7) & ~7;
1444 if (a->name_length)
1445 memmove((u8*)a + name_ofs, (u8*)a + le16_to_cpu(a->name_offset),
1446 a->name_length * sizeof(ntfschar));
1447 mp_ofs = (name_ofs + a->name_length * sizeof(ntfschar) + 7) & ~7;
1448 a->name_offset = cpu_to_le16(name_ofs);
1449 arec_size = (mp_ofs + attr_size + 7) & ~7;
1450 /* Resize the resident part of the attribute record. */
1451 err2 = ntfs_attr_record_resize(m, a, arec_size);
1452 if (unlikely(err2)) {
1453 /*
1454 * This cannot happen (well if memory corruption is at work it
1455 * could happen in theory), but deal with it as well as we can.
1456 * If the old size is too small, truncate the attribute,
1457 * otherwise simply give it a larger allocated size.
1458 * FIXME: Should check whether chkdsk complains when the
1459 * allocated size is much bigger than the resident value size.
1460 */
1461 arec_size = le32_to_cpu(a->length);
1462 if ((mp_ofs + attr_size) > arec_size) {
1463 err2 = attr_size;
1464 attr_size = arec_size - mp_ofs;
1465 ntfs_error(vol->sb, "Failed to undo partial resident "
1466 "to non-resident attribute "
1467 "conversion. Truncating inode 0x%lx, "
1468 "attribute type 0x%x from %i bytes to "
1469 "%i bytes to maintain metadata "
1470 "consistency. THIS MEANS YOU ARE "
1471 "LOSING %i BYTES DATA FROM THIS %s.",
1472 vi->i_ino,
1473 (unsigned)le32_to_cpu(ni->type),
1474 err2, attr_size, err2 - attr_size,
1475 ((ni->type == AT_DATA) &&
1476 !ni->name_len) ? "FILE": "ATTRIBUTE");
1477 write_lock_irqsave(&ni->size_lock, flags);
1478 ni->initialized_size = attr_size;
1479 i_size_write(vi, attr_size);
1480 write_unlock_irqrestore(&ni->size_lock, flags);
1481 }
1482 }
1483 /* Setup the fields specific to resident attributes. */
1484 a->data.resident.value_length = cpu_to_le32(attr_size);
1485 a->data.resident.value_offset = cpu_to_le16(mp_ofs);
1486 a->data.resident.flags = old_res_attr_flags;
1487 memset(&a->data.resident.reserved, 0,
1488 sizeof(a->data.resident.reserved));
1489 /* Copy the data from the page back to the attribute value. */
1490 if (page) {
1491 kaddr = kmap_atomic(page, KM_USER0);
1492 memcpy((u8*)a + mp_ofs, kaddr, attr_size);
1493 kunmap_atomic(kaddr, KM_USER0);
1494 }
1495 /* Finally setup the ntfs inode appropriately. */
1496 write_lock_irqsave(&ni->size_lock, flags);
1497 ni->allocated_size = arec_size - mp_ofs;
1498 write_unlock_irqrestore(&ni->size_lock, flags);
1499 NInoClearNonResident(ni);
1500 /* Mark the mft record dirty, so it gets written back. */
1501 flush_dcache_mft_record_page(ctx->ntfs_ino);
1502 mark_mft_record_dirty(ctx->ntfs_ino);
1503err_out:
1504 if (ctx)
1505 ntfs_attr_put_search_ctx(ctx);
1506 if (m)
1507 unmap_mft_record(base_ni);
1508 ni->runlist.rl = NULL;
1509 up_write(&ni->runlist.lock);
1510rl_err_out:
1511 if (rl) {
1512 if (ntfs_cluster_free_from_rl(vol, rl) < 0) {
1513 ntfs_free(rl);
1514 ntfs_error(vol->sb, "Failed to release allocated "
1515 "cluster(s) in error code path. Run "
1516 "chkdsk to recover the lost "
1517 "cluster(s).");
1518 NVolSetErrors(vol);
1519 }
1520page_err_out:
1521 unlock_page(page);
1522 page_cache_release(page);
1523 }
1524 if (err == -EINVAL)
1525 err = -EIO;
1526 return err;
1527}
1528
1da177e4
LT
1529/**
1530 * ntfs_attr_set - fill (a part of) an attribute with a byte
1531 * @ni: ntfs inode describing the attribute to fill
1532 * @ofs: offset inside the attribute at which to start to fill
1533 * @cnt: number of bytes to fill
1534 * @val: the unsigned 8-bit value with which to fill the attribute
1535 *
1536 * Fill @cnt bytes of the attribute described by the ntfs inode @ni starting at
1537 * byte offset @ofs inside the attribute with the constant byte @val.
1538 *
1539 * This function is effectively like memset() applied to an ntfs attribute.
da28438c
AA
1540 * Note thie function actually only operates on the page cache pages belonging
1541 * to the ntfs attribute and it marks them dirty after doing the memset().
1542 * Thus it relies on the vm dirty page write code paths to cause the modified
1543 * pages to be written to the mft record/disk.
1da177e4
LT
1544 *
1545 * Return 0 on success and -errno on error. An error code of -ESPIPE means
1546 * that @ofs + @cnt were outside the end of the attribute and no write was
1547 * performed.
1548 */
1549int ntfs_attr_set(ntfs_inode *ni, const s64 ofs, const s64 cnt, const u8 val)
1550{
1551 ntfs_volume *vol = ni->vol;
1552 struct address_space *mapping;
1553 struct page *page;
1554 u8 *kaddr;
1555 pgoff_t idx, end;
1556 unsigned int start_ofs, end_ofs, size;
1557
1558 ntfs_debug("Entering for ofs 0x%llx, cnt 0x%llx, val 0x%hx.",
1559 (long long)ofs, (long long)cnt, val);
1560 BUG_ON(ofs < 0);
1561 BUG_ON(cnt < 0);
1562 if (!cnt)
1563 goto done;
1564 mapping = VFS_I(ni)->i_mapping;
1565 /* Work out the starting index and page offset. */
1566 idx = ofs >> PAGE_CACHE_SHIFT;
1567 start_ofs = ofs & ~PAGE_CACHE_MASK;
1568 /* Work out the ending index and page offset. */
1569 end = ofs + cnt;
1570 end_ofs = end & ~PAGE_CACHE_MASK;
1571 /* If the end is outside the inode size return -ESPIPE. */
da28438c 1572 if (unlikely(end > i_size_read(VFS_I(ni)))) {
1da177e4
LT
1573 ntfs_error(vol->sb, "Request exceeds end of attribute.");
1574 return -ESPIPE;
1575 }
1576 end >>= PAGE_CACHE_SHIFT;
1577 /* If there is a first partial page, need to do it the slow way. */
1578 if (start_ofs) {
1579 page = read_cache_page(mapping, idx,
1580 (filler_t*)mapping->a_ops->readpage, NULL);
1581 if (IS_ERR(page)) {
1582 ntfs_error(vol->sb, "Failed to read first partial "
1583 "page (sync error, index 0x%lx).", idx);
1584 return PTR_ERR(page);
1585 }
1586 wait_on_page_locked(page);
1587 if (unlikely(!PageUptodate(page))) {
1588 ntfs_error(vol->sb, "Failed to read first partial page "
1589 "(async error, index 0x%lx).", idx);
1590 page_cache_release(page);
1591 return PTR_ERR(page);
1592 }
1593 /*
1594 * If the last page is the same as the first page, need to
1595 * limit the write to the end offset.
1596 */
1597 size = PAGE_CACHE_SIZE;
1598 if (idx == end)
1599 size = end_ofs;
1600 kaddr = kmap_atomic(page, KM_USER0);
1601 memset(kaddr + start_ofs, val, size - start_ofs);
1602 flush_dcache_page(page);
1603 kunmap_atomic(kaddr, KM_USER0);
1604 set_page_dirty(page);
1605 page_cache_release(page);
1606 if (idx == end)
1607 goto done;
1608 idx++;
1609 }
1610 /* Do the whole pages the fast way. */
1611 for (; idx < end; idx++) {
1612 /* Find or create the current page. (The page is locked.) */
1613 page = grab_cache_page(mapping, idx);
1614 if (unlikely(!page)) {
1615 ntfs_error(vol->sb, "Insufficient memory to grab "
1616 "page (index 0x%lx).", idx);
1617 return -ENOMEM;
1618 }
1619 kaddr = kmap_atomic(page, KM_USER0);
1620 memset(kaddr, val, PAGE_CACHE_SIZE);
1621 flush_dcache_page(page);
1622 kunmap_atomic(kaddr, KM_USER0);
1623 /*
1624 * If the page has buffers, mark them uptodate since buffer
1625 * state and not page state is definitive in 2.6 kernels.
1626 */
1627 if (page_has_buffers(page)) {
1628 struct buffer_head *bh, *head;
1629
1630 bh = head = page_buffers(page);
1631 do {
1632 set_buffer_uptodate(bh);
1633 } while ((bh = bh->b_this_page) != head);
1634 }
1635 /* Now that buffers are uptodate, set the page uptodate, too. */
1636 SetPageUptodate(page);
1637 /*
1638 * Set the page and all its buffers dirty and mark the inode
1639 * dirty, too. The VM will write the page later on.
1640 */
1641 set_page_dirty(page);
1642 /* Finally unlock and release the page. */
1643 unlock_page(page);
1644 page_cache_release(page);
1645 }
1646 /* If there is a last partial page, need to do it the slow way. */
1647 if (end_ofs) {
1648 page = read_cache_page(mapping, idx,
1649 (filler_t*)mapping->a_ops->readpage, NULL);
1650 if (IS_ERR(page)) {
1651 ntfs_error(vol->sb, "Failed to read last partial page "
1652 "(sync error, index 0x%lx).", idx);
1653 return PTR_ERR(page);
1654 }
1655 wait_on_page_locked(page);
1656 if (unlikely(!PageUptodate(page))) {
1657 ntfs_error(vol->sb, "Failed to read last partial page "
1658 "(async error, index 0x%lx).", idx);
1659 page_cache_release(page);
1660 return PTR_ERR(page);
1661 }
1662 kaddr = kmap_atomic(page, KM_USER0);
1663 memset(kaddr, val, end_ofs);
1664 flush_dcache_page(page);
1665 kunmap_atomic(kaddr, KM_USER0);
1666 set_page_dirty(page);
1667 page_cache_release(page);
1668 }
1669done:
1670 ntfs_debug("Done.");
1671 return 0;
1672}