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