GNU Linux-libre 4.19.264-gnu1
[releases.git] / fs / ntfs / attrib.c
1 /**
2  * attrib.c - NTFS attribute operations.  Part of the Linux-NTFS project.
3  *
4  * Copyright (c) 2001-2012 Anton Altaparmakov and Tuxera Inc.
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/sched.h>
25 #include <linux/slab.h>
26 #include <linux/swap.h>
27 #include <linux/writeback.h>
28
29 #include "attrib.h"
30 #include "debug.h"
31 #include "layout.h"
32 #include "lcnalloc.h"
33 #include "malloc.h"
34 #include "mft.h"
35 #include "ntfs.h"
36 #include "types.h"
37
38 /**
39  * ntfs_map_runlist_nolock - map (a part of) a runlist of an ntfs inode
40  * @ni:         ntfs inode for which to map (part of) a runlist
41  * @vcn:        map runlist part containing this vcn
42  * @ctx:        active attribute search context if present or NULL if not
43  *
44  * Map the part of a runlist containing the @vcn of the ntfs inode @ni.
45  *
46  * If @ctx is specified, it is an active search context of @ni and its base mft
47  * record.  This is needed when ntfs_map_runlist_nolock() encounters unmapped
48  * runlist fragments and allows their mapping.  If you do not have the mft
49  * record mapped, you can specify @ctx as NULL and ntfs_map_runlist_nolock()
50  * will perform the necessary mapping and unmapping.
51  *
52  * Note, ntfs_map_runlist_nolock() saves the state of @ctx on entry and
53  * restores it before returning.  Thus, @ctx will be left pointing to the same
54  * attribute on return as on entry.  However, the actual pointers in @ctx may
55  * point to different memory locations on return, so you must remember to reset
56  * any cached pointers from the @ctx, i.e. after the call to
57  * ntfs_map_runlist_nolock(), you will probably want to do:
58  *      m = ctx->mrec;
59  *      a = ctx->attr;
60  * Assuming you cache ctx->attr in a variable @a of type ATTR_RECORD * and that
61  * you cache ctx->mrec in a variable @m of type MFT_RECORD *.
62  *
63  * Return 0 on success and -errno on error.  There is one special error code
64  * which is not an error as such.  This is -ENOENT.  It means that @vcn is out
65  * of bounds of the runlist.
66  *
67  * Note the runlist can be NULL after this function returns if @vcn is zero and
68  * the attribute has zero allocated size, i.e. there simply is no runlist.
69  *
70  * WARNING: If @ctx is supplied, regardless of whether success or failure is
71  *          returned, you need to check IS_ERR(@ctx->mrec) and if 'true' the @ctx
72  *          is no longer valid, i.e. you need to either call
73  *          ntfs_attr_reinit_search_ctx() or ntfs_attr_put_search_ctx() on it.
74  *          In that case PTR_ERR(@ctx->mrec) will give you the error code for
75  *          why the mapping of the old inode failed.
76  *
77  * Locking: - The runlist described by @ni must be locked for writing on entry
78  *            and is locked on return.  Note the runlist will be modified.
79  *          - If @ctx is NULL, the base mft record of @ni must not be mapped on
80  *            entry and it will be left unmapped on return.
81  *          - If @ctx is not NULL, the base mft record must be mapped on entry
82  *            and it will be left mapped on return.
83  */
84 int ntfs_map_runlist_nolock(ntfs_inode *ni, VCN vcn, ntfs_attr_search_ctx *ctx)
85 {
86         VCN end_vcn;
87         unsigned long flags;
88         ntfs_inode *base_ni;
89         MFT_RECORD *m;
90         ATTR_RECORD *a;
91         runlist_element *rl;
92         struct page *put_this_page = NULL;
93         int err = 0;
94         bool ctx_is_temporary, ctx_needs_reset;
95         ntfs_attr_search_ctx old_ctx = { NULL, };
96
97         ntfs_debug("Mapping runlist part containing vcn 0x%llx.",
98                         (unsigned long long)vcn);
99         if (!NInoAttr(ni))
100                 base_ni = ni;
101         else
102                 base_ni = ni->ext.base_ntfs_ino;
103         if (!ctx) {
104                 ctx_is_temporary = ctx_needs_reset = true;
105                 m = map_mft_record(base_ni);
106                 if (IS_ERR(m))
107                         return PTR_ERR(m);
108                 ctx = ntfs_attr_get_search_ctx(base_ni, m);
109                 if (unlikely(!ctx)) {
110                         err = -ENOMEM;
111                         goto err_out;
112                 }
113         } else {
114                 VCN allocated_size_vcn;
115
116                 BUG_ON(IS_ERR(ctx->mrec));
117                 a = ctx->attr;
118                 BUG_ON(!a->non_resident);
119                 ctx_is_temporary = false;
120                 end_vcn = sle64_to_cpu(a->data.non_resident.highest_vcn);
121                 read_lock_irqsave(&ni->size_lock, flags);
122                 allocated_size_vcn = ni->allocated_size >>
123                                 ni->vol->cluster_size_bits;
124                 read_unlock_irqrestore(&ni->size_lock, flags);
125                 if (!a->data.non_resident.lowest_vcn && end_vcn <= 0)
126                         end_vcn = allocated_size_vcn - 1;
127                 /*
128                  * If we already have the attribute extent containing @vcn in
129                  * @ctx, no need to look it up again.  We slightly cheat in
130                  * that if vcn exceeds the allocated size, we will refuse to
131                  * map the runlist below, so there is definitely no need to get
132                  * the right attribute extent.
133                  */
134                 if (vcn >= allocated_size_vcn || (a->type == ni->type &&
135                                 a->name_length == ni->name_len &&
136                                 !memcmp((u8*)a + le16_to_cpu(a->name_offset),
137                                 ni->name, ni->name_len) &&
138                                 sle64_to_cpu(a->data.non_resident.lowest_vcn)
139                                 <= vcn && end_vcn >= vcn))
140                         ctx_needs_reset = false;
141                 else {
142                         /* Save the old search context. */
143                         old_ctx = *ctx;
144                         /*
145                          * If the currently mapped (extent) inode is not the
146                          * base inode we will unmap it when we reinitialize the
147                          * search context which means we need to get a
148                          * reference to the page containing the mapped mft
149                          * record so we do not accidentally drop changes to the
150                          * mft record when it has not been marked dirty yet.
151                          */
152                         if (old_ctx.base_ntfs_ino && old_ctx.ntfs_ino !=
153                                         old_ctx.base_ntfs_ino) {
154                                 put_this_page = old_ctx.ntfs_ino->page;
155                                 get_page(put_this_page);
156                         }
157                         /*
158                          * Reinitialize the search context so we can lookup the
159                          * needed attribute extent.
160                          */
161                         ntfs_attr_reinit_search_ctx(ctx);
162                         ctx_needs_reset = true;
163                 }
164         }
165         if (ctx_needs_reset) {
166                 err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
167                                 CASE_SENSITIVE, vcn, NULL, 0, ctx);
168                 if (unlikely(err)) {
169                         if (err == -ENOENT)
170                                 err = -EIO;
171                         goto err_out;
172                 }
173                 BUG_ON(!ctx->attr->non_resident);
174         }
175         a = ctx->attr;
176         /*
177          * Only decompress the mapping pairs if @vcn is inside it.  Otherwise
178          * we get into problems when we try to map an out of bounds vcn because
179          * we then try to map the already mapped runlist fragment and
180          * ntfs_mapping_pairs_decompress() fails.
181          */
182         end_vcn = sle64_to_cpu(a->data.non_resident.highest_vcn) + 1;
183         if (unlikely(vcn && vcn >= end_vcn)) {
184                 err = -ENOENT;
185                 goto err_out;
186         }
187         rl = ntfs_mapping_pairs_decompress(ni->vol, a, ni->runlist.rl);
188         if (IS_ERR(rl))
189                 err = PTR_ERR(rl);
190         else
191                 ni->runlist.rl = rl;
192 err_out:
193         if (ctx_is_temporary) {
194                 if (likely(ctx))
195                         ntfs_attr_put_search_ctx(ctx);
196                 unmap_mft_record(base_ni);
197         } else if (ctx_needs_reset) {
198                 /*
199                  * If there is no attribute list, restoring the search context
200                  * is accomplished simply by copying the saved context back over
201                  * the caller supplied context.  If there is an attribute list,
202                  * things are more complicated as we need to deal with mapping
203                  * of mft records and resulting potential changes in pointers.
204                  */
205                 if (NInoAttrList(base_ni)) {
206                         /*
207                          * If the currently mapped (extent) inode is not the
208                          * one we had before, we need to unmap it and map the
209                          * old one.
210                          */
211                         if (ctx->ntfs_ino != old_ctx.ntfs_ino) {
212                                 /*
213                                  * If the currently mapped inode is not the
214                                  * base inode, unmap it.
215                                  */
216                                 if (ctx->base_ntfs_ino && ctx->ntfs_ino !=
217                                                 ctx->base_ntfs_ino) {
218                                         unmap_extent_mft_record(ctx->ntfs_ino);
219                                         ctx->mrec = ctx->base_mrec;
220                                         BUG_ON(!ctx->mrec);
221                                 }
222                                 /*
223                                  * If the old mapped inode is not the base
224                                  * inode, map it.
225                                  */
226                                 if (old_ctx.base_ntfs_ino &&
227                                                 old_ctx.ntfs_ino !=
228                                                 old_ctx.base_ntfs_ino) {
229 retry_map:
230                                         ctx->mrec = map_mft_record(
231                                                         old_ctx.ntfs_ino);
232                                         /*
233                                          * Something bad has happened.  If out
234                                          * of memory retry till it succeeds.
235                                          * Any other errors are fatal and we
236                                          * return the error code in ctx->mrec.
237                                          * Let the caller deal with it...  We
238                                          * just need to fudge things so the
239                                          * caller can reinit and/or put the
240                                          * search context safely.
241                                          */
242                                         if (IS_ERR(ctx->mrec)) {
243                                                 if (PTR_ERR(ctx->mrec) ==
244                                                                 -ENOMEM) {
245                                                         schedule();
246                                                         goto retry_map;
247                                                 } else
248                                                         old_ctx.ntfs_ino =
249                                                                 old_ctx.
250                                                                 base_ntfs_ino;
251                                         }
252                                 }
253                         }
254                         /* Update the changed pointers in the saved context. */
255                         if (ctx->mrec != old_ctx.mrec) {
256                                 if (!IS_ERR(ctx->mrec))
257                                         old_ctx.attr = (ATTR_RECORD*)(
258                                                         (u8*)ctx->mrec +
259                                                         ((u8*)old_ctx.attr -
260                                                         (u8*)old_ctx.mrec));
261                                 old_ctx.mrec = ctx->mrec;
262                         }
263                 }
264                 /* Restore the search context to the saved one. */
265                 *ctx = old_ctx;
266                 /*
267                  * We drop the reference on the page we took earlier.  In the
268                  * case that IS_ERR(ctx->mrec) is true this means we might lose
269                  * some changes to the mft record that had been made between
270                  * the last time it was marked dirty/written out and now.  This
271                  * at this stage is not a problem as the mapping error is fatal
272                  * enough that the mft record cannot be written out anyway and
273                  * the caller is very likely to shutdown the whole inode
274                  * immediately and mark the volume dirty for chkdsk to pick up
275                  * the pieces anyway.
276                  */
277                 if (put_this_page)
278                         put_page(put_this_page);
279         }
280         return err;
281 }
282
283 /**
284  * ntfs_map_runlist - map (a part of) a runlist of an ntfs inode
285  * @ni:         ntfs inode for which to map (part of) a runlist
286  * @vcn:        map runlist part containing this vcn
287  *
288  * Map the part of a runlist containing the @vcn of the ntfs inode @ni.
289  *
290  * Return 0 on success and -errno on error.  There is one special error code
291  * which is not an error as such.  This is -ENOENT.  It means that @vcn is out
292  * of bounds of the runlist.
293  *
294  * Locking: - The runlist must be unlocked on entry and is unlocked on return.
295  *          - This function takes the runlist lock for writing and may modify
296  *            the runlist.
297  */
298 int ntfs_map_runlist(ntfs_inode *ni, VCN vcn)
299 {
300         int err = 0;
301
302         down_write(&ni->runlist.lock);
303         /* Make sure someone else didn't do the work while we were sleeping. */
304         if (likely(ntfs_rl_vcn_to_lcn(ni->runlist.rl, vcn) <=
305                         LCN_RL_NOT_MAPPED))
306                 err = ntfs_map_runlist_nolock(ni, vcn, NULL);
307         up_write(&ni->runlist.lock);
308         return err;
309 }
310
311 /**
312  * ntfs_attr_vcn_to_lcn_nolock - convert a vcn into a lcn given an ntfs inode
313  * @ni:                 ntfs inode of the attribute whose runlist to search
314  * @vcn:                vcn to convert
315  * @write_locked:       true if the runlist is locked for writing
316  *
317  * Find the virtual cluster number @vcn in the runlist of the ntfs attribute
318  * described by the ntfs inode @ni and return the corresponding logical cluster
319  * number (lcn).
320  *
321  * If the @vcn is not mapped yet, the attempt is made to map the attribute
322  * extent containing the @vcn and the vcn to lcn conversion is retried.
323  *
324  * If @write_locked is true the caller has locked the runlist for writing and
325  * if false for reading.
326  *
327  * Since lcns must be >= 0, we use negative return codes with special meaning:
328  *
329  * Return code  Meaning / Description
330  * ==========================================
331  *  LCN_HOLE    Hole / not allocated on disk.
332  *  LCN_ENOENT  There is no such vcn in the runlist, i.e. @vcn is out of bounds.
333  *  LCN_ENOMEM  Not enough memory to map runlist.
334  *  LCN_EIO     Critical error (runlist/file is corrupt, i/o error, etc).
335  *
336  * Locking: - The runlist must be locked on entry and is left locked on return.
337  *          - If @write_locked is 'false', i.e. the runlist is locked for reading,
338  *            the lock may be dropped inside the function so you cannot rely on
339  *            the runlist still being the same when this function returns.
340  */
341 LCN ntfs_attr_vcn_to_lcn_nolock(ntfs_inode *ni, const VCN vcn,
342                 const bool write_locked)
343 {
344         LCN lcn;
345         unsigned long flags;
346         bool is_retry = false;
347
348         BUG_ON(!ni);
349         ntfs_debug("Entering for i_ino 0x%lx, vcn 0x%llx, %s_locked.",
350                         ni->mft_no, (unsigned long long)vcn,
351                         write_locked ? "write" : "read");
352         BUG_ON(!NInoNonResident(ni));
353         BUG_ON(vcn < 0);
354         if (!ni->runlist.rl) {
355                 read_lock_irqsave(&ni->size_lock, flags);
356                 if (!ni->allocated_size) {
357                         read_unlock_irqrestore(&ni->size_lock, flags);
358                         return LCN_ENOENT;
359                 }
360                 read_unlock_irqrestore(&ni->size_lock, flags);
361         }
362 retry_remap:
363         /* Convert vcn to lcn.  If that fails map the runlist and retry once. */
364         lcn = ntfs_rl_vcn_to_lcn(ni->runlist.rl, vcn);
365         if (likely(lcn >= LCN_HOLE)) {
366                 ntfs_debug("Done, lcn 0x%llx.", (long long)lcn);
367                 return lcn;
368         }
369         if (lcn != LCN_RL_NOT_MAPPED) {
370                 if (lcn != LCN_ENOENT)
371                         lcn = LCN_EIO;
372         } else if (!is_retry) {
373                 int err;
374
375                 if (!write_locked) {
376                         up_read(&ni->runlist.lock);
377                         down_write(&ni->runlist.lock);
378                         if (unlikely(ntfs_rl_vcn_to_lcn(ni->runlist.rl, vcn) !=
379                                         LCN_RL_NOT_MAPPED)) {
380                                 up_write(&ni->runlist.lock);
381                                 down_read(&ni->runlist.lock);
382                                 goto retry_remap;
383                         }
384                 }
385                 err = ntfs_map_runlist_nolock(ni, vcn, NULL);
386                 if (!write_locked) {
387                         up_write(&ni->runlist.lock);
388                         down_read(&ni->runlist.lock);
389                 }
390                 if (likely(!err)) {
391                         is_retry = true;
392                         goto retry_remap;
393                 }
394                 if (err == -ENOENT)
395                         lcn = LCN_ENOENT;
396                 else if (err == -ENOMEM)
397                         lcn = LCN_ENOMEM;
398                 else
399                         lcn = LCN_EIO;
400         }
401         if (lcn != LCN_ENOENT)
402                 ntfs_error(ni->vol->sb, "Failed with error code %lli.",
403                                 (long long)lcn);
404         return lcn;
405 }
406
407 /**
408  * ntfs_attr_find_vcn_nolock - find a vcn in the runlist of an ntfs inode
409  * @ni:         ntfs inode describing the runlist to search
410  * @vcn:        vcn to find
411  * @ctx:        active attribute search context if present or NULL if not
412  *
413  * Find the virtual cluster number @vcn in the runlist described by the ntfs
414  * inode @ni and return the address of the runlist element containing the @vcn.
415  *
416  * If the @vcn is not mapped yet, the attempt is made to map the attribute
417  * extent containing the @vcn and the vcn to lcn conversion is retried.
418  *
419  * If @ctx is specified, it is an active search context of @ni and its base mft
420  * record.  This is needed when ntfs_attr_find_vcn_nolock() encounters unmapped
421  * runlist fragments and allows their mapping.  If you do not have the mft
422  * record mapped, you can specify @ctx as NULL and ntfs_attr_find_vcn_nolock()
423  * will perform the necessary mapping and unmapping.
424  *
425  * Note, ntfs_attr_find_vcn_nolock() saves the state of @ctx on entry and
426  * restores it before returning.  Thus, @ctx will be left pointing to the same
427  * attribute on return as on entry.  However, the actual pointers in @ctx may
428  * point to different memory locations on return, so you must remember to reset
429  * any cached pointers from the @ctx, i.e. after the call to
430  * ntfs_attr_find_vcn_nolock(), you will probably want to do:
431  *      m = ctx->mrec;
432  *      a = ctx->attr;
433  * Assuming you cache ctx->attr in a variable @a of type ATTR_RECORD * and that
434  * you cache ctx->mrec in a variable @m of type MFT_RECORD *.
435  * Note you need to distinguish between the lcn of the returned runlist element
436  * being >= 0 and LCN_HOLE.  In the later case you have to return zeroes on
437  * read and allocate clusters on write.
438  *
439  * Return the runlist element containing the @vcn on success and
440  * ERR_PTR(-errno) on error.  You need to test the return value with IS_ERR()
441  * to decide if the return is success or failure and PTR_ERR() to get to the
442  * error code if IS_ERR() is true.
443  *
444  * The possible error return codes are:
445  *      -ENOENT - No such vcn in the runlist, i.e. @vcn is out of bounds.
446  *      -ENOMEM - Not enough memory to map runlist.
447  *      -EIO    - Critical error (runlist/file is corrupt, i/o error, etc).
448  *
449  * WARNING: If @ctx is supplied, regardless of whether success or failure is
450  *          returned, you need to check IS_ERR(@ctx->mrec) and if 'true' the @ctx
451  *          is no longer valid, i.e. you need to either call
452  *          ntfs_attr_reinit_search_ctx() or ntfs_attr_put_search_ctx() on it.
453  *          In that case PTR_ERR(@ctx->mrec) will give you the error code for
454  *          why the mapping of the old inode failed.
455  *
456  * Locking: - The runlist described by @ni must be locked for writing on entry
457  *            and is locked on return.  Note the runlist may be modified when
458  *            needed runlist fragments need to be mapped.
459  *          - If @ctx is NULL, the base mft record of @ni must not be mapped on
460  *            entry and it will be left unmapped on return.
461  *          - If @ctx is not NULL, the base mft record must be mapped on entry
462  *            and it will be left mapped on return.
463  */
464 runlist_element *ntfs_attr_find_vcn_nolock(ntfs_inode *ni, const VCN vcn,
465                 ntfs_attr_search_ctx *ctx)
466 {
467         unsigned long flags;
468         runlist_element *rl;
469         int err = 0;
470         bool is_retry = false;
471
472         BUG_ON(!ni);
473         ntfs_debug("Entering for i_ino 0x%lx, vcn 0x%llx, with%s ctx.",
474                         ni->mft_no, (unsigned long long)vcn, ctx ? "" : "out");
475         BUG_ON(!NInoNonResident(ni));
476         BUG_ON(vcn < 0);
477         if (!ni->runlist.rl) {
478                 read_lock_irqsave(&ni->size_lock, flags);
479                 if (!ni->allocated_size) {
480                         read_unlock_irqrestore(&ni->size_lock, flags);
481                         return ERR_PTR(-ENOENT);
482                 }
483                 read_unlock_irqrestore(&ni->size_lock, flags);
484         }
485 retry_remap:
486         rl = ni->runlist.rl;
487         if (likely(rl && vcn >= rl[0].vcn)) {
488                 while (likely(rl->length)) {
489                         if (unlikely(vcn < rl[1].vcn)) {
490                                 if (likely(rl->lcn >= LCN_HOLE)) {
491                                         ntfs_debug("Done.");
492                                         return rl;
493                                 }
494                                 break;
495                         }
496                         rl++;
497                 }
498                 if (likely(rl->lcn != LCN_RL_NOT_MAPPED)) {
499                         if (likely(rl->lcn == LCN_ENOENT))
500                                 err = -ENOENT;
501                         else
502                                 err = -EIO;
503                 }
504         }
505         if (!err && !is_retry) {
506                 /*
507                  * If the search context is invalid we cannot map the unmapped
508                  * region.
509                  */
510                 if (IS_ERR(ctx->mrec))
511                         err = PTR_ERR(ctx->mrec);
512                 else {
513                         /*
514                          * The @vcn is in an unmapped region, map the runlist
515                          * and retry.
516                          */
517                         err = ntfs_map_runlist_nolock(ni, vcn, ctx);
518                         if (likely(!err)) {
519                                 is_retry = true;
520                                 goto retry_remap;
521                         }
522                 }
523                 if (err == -EINVAL)
524                         err = -EIO;
525         } else if (!err)
526                 err = -EIO;
527         if (err != -ENOENT)
528                 ntfs_error(ni->vol->sb, "Failed with error code %i.", err);
529         return ERR_PTR(err);
530 }
531
532 /**
533  * ntfs_attr_find - find (next) attribute in mft record
534  * @type:       attribute type to find
535  * @name:       attribute name to find (optional, i.e. NULL means don't care)
536  * @name_len:   attribute name length (only needed if @name present)
537  * @ic:         IGNORE_CASE or CASE_SENSITIVE (ignored if @name not present)
538  * @val:        attribute value to find (optional, resident attributes only)
539  * @val_len:    attribute value length
540  * @ctx:        search context with mft record and attribute to search from
541  *
542  * You should not need to call this function directly.  Use ntfs_attr_lookup()
543  * instead.
544  *
545  * ntfs_attr_find() takes a search context @ctx as parameter and searches the
546  * mft record specified by @ctx->mrec, beginning at @ctx->attr, for an
547  * attribute of @type, optionally @name and @val.
548  *
549  * If the attribute is found, ntfs_attr_find() returns 0 and @ctx->attr will
550  * point to the found attribute.
551  *
552  * If the attribute is not found, ntfs_attr_find() returns -ENOENT and
553  * @ctx->attr will point to the attribute before which the attribute being
554  * searched for would need to be inserted if such an action were to be desired.
555  *
556  * On actual error, ntfs_attr_find() returns -EIO.  In this case @ctx->attr is
557  * undefined and in particular do not rely on it not changing.
558  *
559  * If @ctx->is_first is 'true', the search begins with @ctx->attr itself.  If it
560  * is 'false', the search begins after @ctx->attr.
561  *
562  * If @ic is IGNORE_CASE, the @name comparisson is not case sensitive and
563  * @ctx->ntfs_ino must be set to the ntfs inode to which the mft record
564  * @ctx->mrec belongs.  This is so we can get at the ntfs volume and hence at
565  * the upcase table.  If @ic is CASE_SENSITIVE, the comparison is case
566  * sensitive.  When @name is present, @name_len is the @name length in Unicode
567  * characters.
568  *
569  * If @name is not present (NULL), we assume that the unnamed attribute is
570  * being searched for.
571  *
572  * Finally, the resident attribute value @val is looked for, if present.  If
573  * @val is not present (NULL), @val_len is ignored.
574  *
575  * ntfs_attr_find() only searches the specified mft record and it ignores the
576  * presence of an attribute list attribute (unless it is the one being searched
577  * for, obviously).  If you need to take attribute lists into consideration,
578  * use ntfs_attr_lookup() instead (see below).  This also means that you cannot
579  * use ntfs_attr_find() to search for extent records of non-resident
580  * attributes, as extents with lowest_vcn != 0 are usually described by the
581  * attribute list attribute only. - Note that it is possible that the first
582  * extent is only in the attribute list while the last extent is in the base
583  * mft record, so do not rely on being able to find the first extent in the
584  * base mft record.
585  *
586  * Warning: Never use @val when looking for attribute types which can be
587  *          non-resident as this most likely will result in a crash!
588  */
589 static int ntfs_attr_find(const ATTR_TYPE type, const ntfschar *name,
590                 const u32 name_len, const IGNORE_CASE_BOOL ic,
591                 const u8 *val, const u32 val_len, ntfs_attr_search_ctx *ctx)
592 {
593         ATTR_RECORD *a;
594         ntfs_volume *vol = ctx->ntfs_ino->vol;
595         ntfschar *upcase = vol->upcase;
596         u32 upcase_len = vol->upcase_len;
597
598         /*
599          * Iterate over attributes in mft record starting at @ctx->attr, or the
600          * attribute following that, if @ctx->is_first is 'true'.
601          */
602         if (ctx->is_first) {
603                 a = ctx->attr;
604                 ctx->is_first = false;
605         } else
606                 a = (ATTR_RECORD*)((u8*)ctx->attr +
607                                 le32_to_cpu(ctx->attr->length));
608         for (;; a = (ATTR_RECORD*)((u8*)a + le32_to_cpu(a->length))) {
609                 u8 *mrec_end = (u8 *)ctx->mrec +
610                                le32_to_cpu(ctx->mrec->bytes_allocated);
611                 u8 *name_end = (u8 *)a + le16_to_cpu(a->name_offset) +
612                                a->name_length * sizeof(ntfschar);
613                 if ((u8*)a < (u8*)ctx->mrec || (u8*)a > mrec_end ||
614                     name_end > mrec_end)
615                         break;
616                 ctx->attr = a;
617                 if (unlikely(le32_to_cpu(a->type) > le32_to_cpu(type) ||
618                                 a->type == AT_END))
619                         return -ENOENT;
620                 if (unlikely(!a->length))
621                         break;
622                 if (a->type != type)
623                         continue;
624                 /*
625                  * If @name is present, compare the two names.  If @name is
626                  * missing, assume we want an unnamed attribute.
627                  */
628                 if (!name) {
629                         /* The search failed if the found attribute is named. */
630                         if (a->name_length)
631                                 return -ENOENT;
632                 } else if (!ntfs_are_names_equal(name, name_len,
633                             (ntfschar*)((u8*)a + le16_to_cpu(a->name_offset)),
634                             a->name_length, ic, upcase, upcase_len)) {
635                         register int rc;
636
637                         rc = ntfs_collate_names(name, name_len,
638                                         (ntfschar*)((u8*)a +
639                                         le16_to_cpu(a->name_offset)),
640                                         a->name_length, 1, IGNORE_CASE,
641                                         upcase, upcase_len);
642                         /*
643                          * If @name collates before a->name, there is no
644                          * matching attribute.
645                          */
646                         if (rc == -1)
647                                 return -ENOENT;
648                         /* If the strings are not equal, continue search. */
649                         if (rc)
650                                 continue;
651                         rc = ntfs_collate_names(name, name_len,
652                                         (ntfschar*)((u8*)a +
653                                         le16_to_cpu(a->name_offset)),
654                                         a->name_length, 1, CASE_SENSITIVE,
655                                         upcase, upcase_len);
656                         if (rc == -1)
657                                 return -ENOENT;
658                         if (rc)
659                                 continue;
660                 }
661                 /*
662                  * The names match or @name not present and attribute is
663                  * unnamed.  If no @val specified, we have found the attribute
664                  * and are done.
665                  */
666                 if (!val)
667                         return 0;
668                 /* @val is present; compare values. */
669                 else {
670                         register int rc;
671
672                         rc = memcmp(val, (u8*)a + le16_to_cpu(
673                                         a->data.resident.value_offset),
674                                         min_t(u32, val_len, le32_to_cpu(
675                                         a->data.resident.value_length)));
676                         /*
677                          * If @val collates before the current attribute's
678                          * value, there is no matching attribute.
679                          */
680                         if (!rc) {
681                                 register u32 avl;
682
683                                 avl = le32_to_cpu(
684                                                 a->data.resident.value_length);
685                                 if (val_len == avl)
686                                         return 0;
687                                 if (val_len < avl)
688                                         return -ENOENT;
689                         } else if (rc < 0)
690                                 return -ENOENT;
691                 }
692         }
693         ntfs_error(vol->sb, "Inode is corrupt.  Run chkdsk.");
694         NVolSetErrors(vol);
695         return -EIO;
696 }
697
698 /**
699  * load_attribute_list - load an attribute list into memory
700  * @vol:                ntfs volume from which to read
701  * @runlist:            runlist of the attribute list
702  * @al_start:           destination buffer
703  * @size:               size of the destination buffer in bytes
704  * @initialized_size:   initialized size of the attribute list
705  *
706  * Walk the runlist @runlist and load all clusters from it copying them into
707  * the linear buffer @al. The maximum number of bytes copied to @al is @size
708  * bytes. Note, @size does not need to be a multiple of the cluster size. If
709  * @initialized_size is less than @size, the region in @al between
710  * @initialized_size and @size will be zeroed and not read from disk.
711  *
712  * Return 0 on success or -errno on error.
713  */
714 int load_attribute_list(ntfs_volume *vol, runlist *runlist, u8 *al_start,
715                 const s64 size, const s64 initialized_size)
716 {
717         LCN lcn;
718         u8 *al = al_start;
719         u8 *al_end = al + initialized_size;
720         runlist_element *rl;
721         struct buffer_head *bh;
722         struct super_block *sb;
723         unsigned long block_size;
724         unsigned long block, max_block;
725         int err = 0;
726         unsigned char block_size_bits;
727
728         ntfs_debug("Entering.");
729         if (!vol || !runlist || !al || size <= 0 || initialized_size < 0 ||
730                         initialized_size > size)
731                 return -EINVAL;
732         if (!initialized_size) {
733                 memset(al, 0, size);
734                 return 0;
735         }
736         sb = vol->sb;
737         block_size = sb->s_blocksize;
738         block_size_bits = sb->s_blocksize_bits;
739         down_read(&runlist->lock);
740         rl = runlist->rl;
741         if (!rl) {
742                 ntfs_error(sb, "Cannot read attribute list since runlist is "
743                                 "missing.");
744                 goto err_out;   
745         }
746         /* Read all clusters specified by the runlist one run at a time. */
747         while (rl->length) {
748                 lcn = ntfs_rl_vcn_to_lcn(rl, rl->vcn);
749                 ntfs_debug("Reading vcn = 0x%llx, lcn = 0x%llx.",
750                                 (unsigned long long)rl->vcn,
751                                 (unsigned long long)lcn);
752                 /* The attribute list cannot be sparse. */
753                 if (lcn < 0) {
754                         ntfs_error(sb, "ntfs_rl_vcn_to_lcn() failed.  Cannot "
755                                         "read attribute list.");
756                         goto err_out;
757                 }
758                 block = lcn << vol->cluster_size_bits >> block_size_bits;
759                 /* Read the run from device in chunks of block_size bytes. */
760                 max_block = block + (rl->length << vol->cluster_size_bits >>
761                                 block_size_bits);
762                 ntfs_debug("max_block = 0x%lx.", max_block);
763                 do {
764                         ntfs_debug("Reading block = 0x%lx.", block);
765                         bh = sb_bread(sb, block);
766                         if (!bh) {
767                                 ntfs_error(sb, "sb_bread() failed. Cannot "
768                                                 "read attribute list.");
769                                 goto err_out;
770                         }
771                         if (al + block_size >= al_end)
772                                 goto do_final;
773                         memcpy(al, bh->b_data, block_size);
774                         brelse(bh);
775                         al += block_size;
776                 } while (++block < max_block);
777                 rl++;
778         }
779         if (initialized_size < size) {
780 initialize:
781                 memset(al_start + initialized_size, 0, size - initialized_size);
782         }
783 done:
784         up_read(&runlist->lock);
785         return err;
786 do_final:
787         if (al < al_end) {
788                 /*
789                  * Partial block.
790                  *
791                  * Note: The attribute list can be smaller than its allocation
792                  * by multiple clusters.  This has been encountered by at least
793                  * two people running Windows XP, thus we cannot do any
794                  * truncation sanity checking here. (AIA)
795                  */
796                 memcpy(al, bh->b_data, al_end - al);
797                 brelse(bh);
798                 if (initialized_size < size)
799                         goto initialize;
800                 goto done;
801         }
802         brelse(bh);
803         /* Real overflow! */
804         ntfs_error(sb, "Attribute list buffer overflow. Read attribute list "
805                         "is truncated.");
806 err_out:
807         err = -EIO;
808         goto done;
809 }
810
811 /**
812  * ntfs_external_attr_find - find an attribute in the attribute list of an inode
813  * @type:       attribute type to find
814  * @name:       attribute name to find (optional, i.e. NULL means don't care)
815  * @name_len:   attribute name length (only needed if @name present)
816  * @ic:         IGNORE_CASE or CASE_SENSITIVE (ignored if @name not present)
817  * @lowest_vcn: lowest vcn to find (optional, non-resident attributes only)
818  * @val:        attribute value to find (optional, resident attributes only)
819  * @val_len:    attribute value length
820  * @ctx:        search context with mft record and attribute to search from
821  *
822  * You should not need to call this function directly.  Use ntfs_attr_lookup()
823  * instead.
824  *
825  * Find an attribute by searching the attribute list for the corresponding
826  * attribute list entry.  Having found the entry, map the mft record if the
827  * attribute is in a different mft record/inode, ntfs_attr_find() the attribute
828  * in there and return it.
829  *
830  * On first search @ctx->ntfs_ino must be the base mft record and @ctx must
831  * have been obtained from a call to ntfs_attr_get_search_ctx().  On subsequent
832  * calls @ctx->ntfs_ino can be any extent inode, too (@ctx->base_ntfs_ino is
833  * then the base inode).
834  *
835  * After finishing with the attribute/mft record you need to call
836  * ntfs_attr_put_search_ctx() to cleanup the search context (unmapping any
837  * mapped inodes, etc).
838  *
839  * If the attribute is found, ntfs_external_attr_find() returns 0 and
840  * @ctx->attr will point to the found attribute.  @ctx->mrec will point to the
841  * mft record in which @ctx->attr is located and @ctx->al_entry will point to
842  * the attribute list entry for the attribute.
843  *
844  * If the attribute is not found, ntfs_external_attr_find() returns -ENOENT and
845  * @ctx->attr will point to the attribute in the base mft record before which
846  * the attribute being searched for would need to be inserted if such an action
847  * were to be desired.  @ctx->mrec will point to the mft record in which
848  * @ctx->attr is located and @ctx->al_entry will point to the attribute list
849  * entry of the attribute before which the attribute being searched for would
850  * need to be inserted if such an action were to be desired.
851  *
852  * Thus to insert the not found attribute, one wants to add the attribute to
853  * @ctx->mrec (the base mft record) and if there is not enough space, the
854  * attribute should be placed in a newly allocated extent mft record.  The
855  * attribute list entry for the inserted attribute should be inserted in the
856  * attribute list attribute at @ctx->al_entry.
857  *
858  * On actual error, ntfs_external_attr_find() returns -EIO.  In this case
859  * @ctx->attr is undefined and in particular do not rely on it not changing.
860  */
861 static int ntfs_external_attr_find(const ATTR_TYPE type,
862                 const ntfschar *name, const u32 name_len,
863                 const IGNORE_CASE_BOOL ic, const VCN lowest_vcn,
864                 const u8 *val, const u32 val_len, ntfs_attr_search_ctx *ctx)
865 {
866         ntfs_inode *base_ni, *ni;
867         ntfs_volume *vol;
868         ATTR_LIST_ENTRY *al_entry, *next_al_entry;
869         u8 *al_start, *al_end;
870         ATTR_RECORD *a;
871         ntfschar *al_name;
872         u32 al_name_len;
873         int err = 0;
874         static const char *es = " Unmount and run chkdsk.";
875
876         ni = ctx->ntfs_ino;
877         base_ni = ctx->base_ntfs_ino;
878         ntfs_debug("Entering for inode 0x%lx, type 0x%x.", ni->mft_no, type);
879         if (!base_ni) {
880                 /* First call happens with the base mft record. */
881                 base_ni = ctx->base_ntfs_ino = ctx->ntfs_ino;
882                 ctx->base_mrec = ctx->mrec;
883         }
884         if (ni == base_ni)
885                 ctx->base_attr = ctx->attr;
886         if (type == AT_END)
887                 goto not_found;
888         vol = base_ni->vol;
889         al_start = base_ni->attr_list;
890         al_end = al_start + base_ni->attr_list_size;
891         if (!ctx->al_entry)
892                 ctx->al_entry = (ATTR_LIST_ENTRY*)al_start;
893         /*
894          * Iterate over entries in attribute list starting at @ctx->al_entry,
895          * or the entry following that, if @ctx->is_first is 'true'.
896          */
897         if (ctx->is_first) {
898                 al_entry = ctx->al_entry;
899                 ctx->is_first = false;
900         } else
901                 al_entry = (ATTR_LIST_ENTRY*)((u8*)ctx->al_entry +
902                                 le16_to_cpu(ctx->al_entry->length));
903         for (;; al_entry = next_al_entry) {
904                 /* Out of bounds check. */
905                 if ((u8*)al_entry < base_ni->attr_list ||
906                                 (u8*)al_entry > al_end)
907                         break;  /* Inode is corrupt. */
908                 ctx->al_entry = al_entry;
909                 /* Catch the end of the attribute list. */
910                 if ((u8*)al_entry == al_end)
911                         goto not_found;
912                 if (!al_entry->length)
913                         break;
914                 if ((u8*)al_entry + 6 > al_end || (u8*)al_entry +
915                                 le16_to_cpu(al_entry->length) > al_end)
916                         break;
917                 next_al_entry = (ATTR_LIST_ENTRY*)((u8*)al_entry +
918                                 le16_to_cpu(al_entry->length));
919                 if (le32_to_cpu(al_entry->type) > le32_to_cpu(type))
920                         goto not_found;
921                 if (type != al_entry->type)
922                         continue;
923                 /*
924                  * If @name is present, compare the two names.  If @name is
925                  * missing, assume we want an unnamed attribute.
926                  */
927                 al_name_len = al_entry->name_length;
928                 al_name = (ntfschar*)((u8*)al_entry + al_entry->name_offset);
929                 if (!name) {
930                         if (al_name_len)
931                                 goto not_found;
932                 } else if (!ntfs_are_names_equal(al_name, al_name_len, name,
933                                 name_len, ic, vol->upcase, vol->upcase_len)) {
934                         register int rc;
935
936                         rc = ntfs_collate_names(name, name_len, al_name,
937                                         al_name_len, 1, IGNORE_CASE,
938                                         vol->upcase, vol->upcase_len);
939                         /*
940                          * If @name collates before al_name, there is no
941                          * matching attribute.
942                          */
943                         if (rc == -1)
944                                 goto not_found;
945                         /* If the strings are not equal, continue search. */
946                         if (rc)
947                                 continue;
948                         /*
949                          * FIXME: Reverse engineering showed 0, IGNORE_CASE but
950                          * that is inconsistent with ntfs_attr_find().  The
951                          * subsequent rc checks were also different.  Perhaps I
952                          * made a mistake in one of the two.  Need to recheck
953                          * which is correct or at least see what is going on...
954                          * (AIA)
955                          */
956                         rc = ntfs_collate_names(name, name_len, al_name,
957                                         al_name_len, 1, CASE_SENSITIVE,
958                                         vol->upcase, vol->upcase_len);
959                         if (rc == -1)
960                                 goto not_found;
961                         if (rc)
962                                 continue;
963                 }
964                 /*
965                  * The names match or @name not present and attribute is
966                  * unnamed.  Now check @lowest_vcn.  Continue search if the
967                  * next attribute list entry still fits @lowest_vcn.  Otherwise
968                  * we have reached the right one or the search has failed.
969                  */
970                 if (lowest_vcn && (u8*)next_al_entry >= al_start            &&
971                                 (u8*)next_al_entry + 6 < al_end             &&
972                                 (u8*)next_al_entry + le16_to_cpu(
973                                         next_al_entry->length) <= al_end    &&
974                                 sle64_to_cpu(next_al_entry->lowest_vcn) <=
975                                         lowest_vcn                          &&
976                                 next_al_entry->type == al_entry->type       &&
977                                 next_al_entry->name_length == al_name_len   &&
978                                 ntfs_are_names_equal((ntfschar*)((u8*)
979                                         next_al_entry +
980                                         next_al_entry->name_offset),
981                                         next_al_entry->name_length,
982                                         al_name, al_name_len, CASE_SENSITIVE,
983                                         vol->upcase, vol->upcase_len))
984                         continue;
985                 if (MREF_LE(al_entry->mft_reference) == ni->mft_no) {
986                         if (MSEQNO_LE(al_entry->mft_reference) != ni->seq_no) {
987                                 ntfs_error(vol->sb, "Found stale mft "
988                                                 "reference in attribute list "
989                                                 "of base inode 0x%lx.%s",
990                                                 base_ni->mft_no, es);
991                                 err = -EIO;
992                                 break;
993                         }
994                 } else { /* Mft references do not match. */
995                         /* If there is a mapped record unmap it first. */
996                         if (ni != base_ni)
997                                 unmap_extent_mft_record(ni);
998                         /* Do we want the base record back? */
999                         if (MREF_LE(al_entry->mft_reference) ==
1000                                         base_ni->mft_no) {
1001                                 ni = ctx->ntfs_ino = base_ni;
1002                                 ctx->mrec = ctx->base_mrec;
1003                         } else {
1004                                 /* We want an extent record. */
1005                                 ctx->mrec = map_extent_mft_record(base_ni,
1006                                                 le64_to_cpu(
1007                                                 al_entry->mft_reference), &ni);
1008                                 if (IS_ERR(ctx->mrec)) {
1009                                         ntfs_error(vol->sb, "Failed to map "
1010                                                         "extent mft record "
1011                                                         "0x%lx of base inode "
1012                                                         "0x%lx.%s",
1013                                                         MREF_LE(al_entry->
1014                                                         mft_reference),
1015                                                         base_ni->mft_no, es);
1016                                         err = PTR_ERR(ctx->mrec);
1017                                         if (err == -ENOENT)
1018                                                 err = -EIO;
1019                                         /* Cause @ctx to be sanitized below. */
1020                                         ni = NULL;
1021                                         break;
1022                                 }
1023                                 ctx->ntfs_ino = ni;
1024                         }
1025                         ctx->attr = (ATTR_RECORD*)((u8*)ctx->mrec +
1026                                         le16_to_cpu(ctx->mrec->attrs_offset));
1027                 }
1028                 /*
1029                  * ctx->vfs_ino, ctx->mrec, and ctx->attr now point to the
1030                  * mft record containing the attribute represented by the
1031                  * current al_entry.
1032                  */
1033                 /*
1034                  * We could call into ntfs_attr_find() to find the right
1035                  * attribute in this mft record but this would be less
1036                  * efficient and not quite accurate as ntfs_attr_find() ignores
1037                  * the attribute instance numbers for example which become
1038                  * important when one plays with attribute lists.  Also,
1039                  * because a proper match has been found in the attribute list
1040                  * entry above, the comparison can now be optimized.  So it is
1041                  * worth re-implementing a simplified ntfs_attr_find() here.
1042                  */
1043                 a = ctx->attr;
1044                 /*
1045                  * Use a manual loop so we can still use break and continue
1046                  * with the same meanings as above.
1047                  */
1048 do_next_attr_loop:
1049                 if ((u8*)a < (u8*)ctx->mrec || (u8*)a > (u8*)ctx->mrec +
1050                                 le32_to_cpu(ctx->mrec->bytes_allocated))
1051                         break;
1052                 if (a->type == AT_END)
1053                         break;
1054                 if (!a->length)
1055                         break;
1056                 if (al_entry->instance != a->instance)
1057                         goto do_next_attr;
1058                 /*
1059                  * If the type and/or the name are mismatched between the
1060                  * attribute list entry and the attribute record, there is
1061                  * corruption so we break and return error EIO.
1062                  */
1063                 if (al_entry->type != a->type)
1064                         break;
1065                 if (!ntfs_are_names_equal((ntfschar*)((u8*)a +
1066                                 le16_to_cpu(a->name_offset)), a->name_length,
1067                                 al_name, al_name_len, CASE_SENSITIVE,
1068                                 vol->upcase, vol->upcase_len))
1069                         break;
1070                 ctx->attr = a;
1071                 /*
1072                  * If no @val specified or @val specified and it matches, we
1073                  * have found it!
1074                  */
1075                 if (!val || (!a->non_resident && le32_to_cpu(
1076                                 a->data.resident.value_length) == val_len &&
1077                                 !memcmp((u8*)a +
1078                                 le16_to_cpu(a->data.resident.value_offset),
1079                                 val, val_len))) {
1080                         ntfs_debug("Done, found.");
1081                         return 0;
1082                 }
1083 do_next_attr:
1084                 /* Proceed to the next attribute in the current mft record. */
1085                 a = (ATTR_RECORD*)((u8*)a + le32_to_cpu(a->length));
1086                 goto do_next_attr_loop;
1087         }
1088         if (!err) {
1089                 ntfs_error(vol->sb, "Base inode 0x%lx contains corrupt "
1090                                 "attribute list attribute.%s", base_ni->mft_no,
1091                                 es);
1092                 err = -EIO;
1093         }
1094         if (ni != base_ni) {
1095                 if (ni)
1096                         unmap_extent_mft_record(ni);
1097                 ctx->ntfs_ino = base_ni;
1098                 ctx->mrec = ctx->base_mrec;
1099                 ctx->attr = ctx->base_attr;
1100         }
1101         if (err != -ENOMEM)
1102                 NVolSetErrors(vol);
1103         return err;
1104 not_found:
1105         /*
1106          * If we were looking for AT_END, we reset the search context @ctx and
1107          * use ntfs_attr_find() to seek to the end of the base mft record.
1108          */
1109         if (type == AT_END) {
1110                 ntfs_attr_reinit_search_ctx(ctx);
1111                 return ntfs_attr_find(AT_END, name, name_len, ic, val, val_len,
1112                                 ctx);
1113         }
1114         /*
1115          * The attribute was not found.  Before we return, we want to ensure
1116          * @ctx->mrec and @ctx->attr indicate the position at which the
1117          * attribute should be inserted in the base mft record.  Since we also
1118          * want to preserve @ctx->al_entry we cannot reinitialize the search
1119          * context using ntfs_attr_reinit_search_ctx() as this would set
1120          * @ctx->al_entry to NULL.  Thus we do the necessary bits manually (see
1121          * ntfs_attr_init_search_ctx() below).  Note, we _only_ preserve
1122          * @ctx->al_entry as the remaining fields (base_*) are identical to
1123          * their non base_ counterparts and we cannot set @ctx->base_attr
1124          * correctly yet as we do not know what @ctx->attr will be set to by
1125          * the call to ntfs_attr_find() below.
1126          */
1127         if (ni != base_ni)
1128                 unmap_extent_mft_record(ni);
1129         ctx->mrec = ctx->base_mrec;
1130         ctx->attr = (ATTR_RECORD*)((u8*)ctx->mrec +
1131                         le16_to_cpu(ctx->mrec->attrs_offset));
1132         ctx->is_first = true;
1133         ctx->ntfs_ino = base_ni;
1134         ctx->base_ntfs_ino = NULL;
1135         ctx->base_mrec = NULL;
1136         ctx->base_attr = NULL;
1137         /*
1138          * In case there are multiple matches in the base mft record, need to
1139          * keep enumerating until we get an attribute not found response (or
1140          * another error), otherwise we would keep returning the same attribute
1141          * over and over again and all programs using us for enumeration would
1142          * lock up in a tight loop.
1143          */
1144         do {
1145                 err = ntfs_attr_find(type, name, name_len, ic, val, val_len,
1146                                 ctx);
1147         } while (!err);
1148         ntfs_debug("Done, not found.");
1149         return err;
1150 }
1151
1152 /**
1153  * ntfs_attr_lookup - find an attribute in an ntfs inode
1154  * @type:       attribute type to find
1155  * @name:       attribute name to find (optional, i.e. NULL means don't care)
1156  * @name_len:   attribute name length (only needed if @name present)
1157  * @ic:         IGNORE_CASE or CASE_SENSITIVE (ignored if @name not present)
1158  * @lowest_vcn: lowest vcn to find (optional, non-resident attributes only)
1159  * @val:        attribute value to find (optional, resident attributes only)
1160  * @val_len:    attribute value length
1161  * @ctx:        search context with mft record and attribute to search from
1162  *
1163  * Find an attribute in an ntfs inode.  On first search @ctx->ntfs_ino must
1164  * be the base mft record and @ctx must have been obtained from a call to
1165  * ntfs_attr_get_search_ctx().
1166  *
1167  * This function transparently handles attribute lists and @ctx is used to
1168  * continue searches where they were left off at.
1169  *
1170  * After finishing with the attribute/mft record you need to call
1171  * ntfs_attr_put_search_ctx() to cleanup the search context (unmapping any
1172  * mapped inodes, etc).
1173  *
1174  * Return 0 if the search was successful and -errno if not.
1175  *
1176  * When 0, @ctx->attr is the found attribute and it is in mft record
1177  * @ctx->mrec.  If an attribute list attribute is present, @ctx->al_entry is
1178  * the attribute list entry of the found attribute.
1179  *
1180  * When -ENOENT, @ctx->attr is the attribute which collates just after the
1181  * attribute being searched for, i.e. if one wants to add the attribute to the
1182  * mft record this is the correct place to insert it into.  If an attribute
1183  * list attribute is present, @ctx->al_entry is the attribute list entry which
1184  * collates just after the attribute list entry of the attribute being searched
1185  * for, i.e. if one wants to add the attribute to the mft record this is the
1186  * correct place to insert its attribute list entry into.
1187  *
1188  * When -errno != -ENOENT, an error occurred during the lookup.  @ctx->attr is
1189  * then undefined and in particular you should not rely on it not changing.
1190  */
1191 int ntfs_attr_lookup(const ATTR_TYPE type, const ntfschar *name,
1192                 const u32 name_len, const IGNORE_CASE_BOOL ic,
1193                 const VCN lowest_vcn, const u8 *val, const u32 val_len,
1194                 ntfs_attr_search_ctx *ctx)
1195 {
1196         ntfs_inode *base_ni;
1197
1198         ntfs_debug("Entering.");
1199         BUG_ON(IS_ERR(ctx->mrec));
1200         if (ctx->base_ntfs_ino)
1201                 base_ni = ctx->base_ntfs_ino;
1202         else
1203                 base_ni = ctx->ntfs_ino;
1204         /* Sanity check, just for debugging really. */
1205         BUG_ON(!base_ni);
1206         if (!NInoAttrList(base_ni) || type == AT_ATTRIBUTE_LIST)
1207                 return ntfs_attr_find(type, name, name_len, ic, val, val_len,
1208                                 ctx);
1209         return ntfs_external_attr_find(type, name, name_len, ic, lowest_vcn,
1210                         val, val_len, ctx);
1211 }
1212
1213 /**
1214  * ntfs_attr_init_search_ctx - initialize an attribute search context
1215  * @ctx:        attribute search context to initialize
1216  * @ni:         ntfs inode with which to initialize the search context
1217  * @mrec:       mft record with which to initialize the search context
1218  *
1219  * Initialize the attribute search context @ctx with @ni and @mrec.
1220  */
1221 static inline void ntfs_attr_init_search_ctx(ntfs_attr_search_ctx *ctx,
1222                 ntfs_inode *ni, MFT_RECORD *mrec)
1223 {
1224         *ctx = (ntfs_attr_search_ctx) {
1225                 .mrec = mrec,
1226                 /* Sanity checks are performed elsewhere. */
1227                 .attr = (ATTR_RECORD*)((u8*)mrec +
1228                                 le16_to_cpu(mrec->attrs_offset)),
1229                 .is_first = true,
1230                 .ntfs_ino = ni,
1231         };
1232 }
1233
1234 /**
1235  * ntfs_attr_reinit_search_ctx - reinitialize an attribute search context
1236  * @ctx:        attribute search context to reinitialize
1237  *
1238  * Reinitialize the attribute search context @ctx, unmapping an associated
1239  * extent mft record if present, and initialize the search context again.
1240  *
1241  * This is used when a search for a new attribute is being started to reset
1242  * the search context to the beginning.
1243  */
1244 void ntfs_attr_reinit_search_ctx(ntfs_attr_search_ctx *ctx)
1245 {
1246         if (likely(!ctx->base_ntfs_ino)) {
1247                 /* No attribute list. */
1248                 ctx->is_first = true;
1249                 /* Sanity checks are performed elsewhere. */
1250                 ctx->attr = (ATTR_RECORD*)((u8*)ctx->mrec +
1251                                 le16_to_cpu(ctx->mrec->attrs_offset));
1252                 /*
1253                  * This needs resetting due to ntfs_external_attr_find() which
1254                  * can leave it set despite having zeroed ctx->base_ntfs_ino.
1255                  */
1256                 ctx->al_entry = NULL;
1257                 return;
1258         } /* Attribute list. */
1259         if (ctx->ntfs_ino != ctx->base_ntfs_ino)
1260                 unmap_extent_mft_record(ctx->ntfs_ino);
1261         ntfs_attr_init_search_ctx(ctx, ctx->base_ntfs_ino, ctx->base_mrec);
1262         return;
1263 }
1264
1265 /**
1266  * ntfs_attr_get_search_ctx - allocate/initialize a new attribute search context
1267  * @ni:         ntfs inode with which to initialize the search context
1268  * @mrec:       mft record with which to initialize the search context
1269  *
1270  * Allocate a new attribute search context, initialize it with @ni and @mrec,
1271  * and return it. Return NULL if allocation failed.
1272  */
1273 ntfs_attr_search_ctx *ntfs_attr_get_search_ctx(ntfs_inode *ni, MFT_RECORD *mrec)
1274 {
1275         ntfs_attr_search_ctx *ctx;
1276
1277         ctx = kmem_cache_alloc(ntfs_attr_ctx_cache, GFP_NOFS);
1278         if (ctx)
1279                 ntfs_attr_init_search_ctx(ctx, ni, mrec);
1280         return ctx;
1281 }
1282
1283 /**
1284  * ntfs_attr_put_search_ctx - release an attribute search context
1285  * @ctx:        attribute search context to free
1286  *
1287  * Release the attribute search context @ctx, unmapping an associated extent
1288  * mft record if present.
1289  */
1290 void ntfs_attr_put_search_ctx(ntfs_attr_search_ctx *ctx)
1291 {
1292         if (ctx->base_ntfs_ino && ctx->ntfs_ino != ctx->base_ntfs_ino)
1293                 unmap_extent_mft_record(ctx->ntfs_ino);
1294         kmem_cache_free(ntfs_attr_ctx_cache, ctx);
1295         return;
1296 }
1297
1298 #ifdef NTFS_RW
1299
1300 /**
1301  * ntfs_attr_find_in_attrdef - find an attribute in the $AttrDef system file
1302  * @vol:        ntfs volume to which the attribute belongs
1303  * @type:       attribute type which to find
1304  *
1305  * Search for the attribute definition record corresponding to the attribute
1306  * @type in the $AttrDef system file.
1307  *
1308  * Return the attribute type definition record if found and NULL if not found.
1309  */
1310 static ATTR_DEF *ntfs_attr_find_in_attrdef(const ntfs_volume *vol,
1311                 const ATTR_TYPE type)
1312 {
1313         ATTR_DEF *ad;
1314
1315         BUG_ON(!vol->attrdef);
1316         BUG_ON(!type);
1317         for (ad = vol->attrdef; (u8*)ad - (u8*)vol->attrdef <
1318                         vol->attrdef_size && ad->type; ++ad) {
1319                 /* We have not found it yet, carry on searching. */
1320                 if (likely(le32_to_cpu(ad->type) < le32_to_cpu(type)))
1321                         continue;
1322                 /* We found the attribute; return it. */
1323                 if (likely(ad->type == type))
1324                         return ad;
1325                 /* We have gone too far already.  No point in continuing. */
1326                 break;
1327         }
1328         /* Attribute not found. */
1329         ntfs_debug("Attribute type 0x%x not found in $AttrDef.",
1330                         le32_to_cpu(type));
1331         return NULL;
1332 }
1333
1334 /**
1335  * ntfs_attr_size_bounds_check - check a size of an attribute type for validity
1336  * @vol:        ntfs volume to which the attribute belongs
1337  * @type:       attribute type which to check
1338  * @size:       size which to check
1339  *
1340  * Check whether the @size in bytes is valid for an attribute of @type on the
1341  * ntfs volume @vol.  This information is obtained from $AttrDef system file.
1342  *
1343  * Return 0 if valid, -ERANGE if not valid, or -ENOENT if the attribute is not
1344  * listed in $AttrDef.
1345  */
1346 int ntfs_attr_size_bounds_check(const ntfs_volume *vol, const ATTR_TYPE type,
1347                 const s64 size)
1348 {
1349         ATTR_DEF *ad;
1350
1351         BUG_ON(size < 0);
1352         /*
1353          * $ATTRIBUTE_LIST has a maximum size of 256kiB, but this is not
1354          * listed in $AttrDef.
1355          */
1356         if (unlikely(type == AT_ATTRIBUTE_LIST && size > 256 * 1024))
1357                 return -ERANGE;
1358         /* Get the $AttrDef entry for the attribute @type. */
1359         ad = ntfs_attr_find_in_attrdef(vol, type);
1360         if (unlikely(!ad))
1361                 return -ENOENT;
1362         /* Do the bounds check. */
1363         if (((sle64_to_cpu(ad->min_size) > 0) &&
1364                         size < sle64_to_cpu(ad->min_size)) ||
1365                         ((sle64_to_cpu(ad->max_size) > 0) && size >
1366                         sle64_to_cpu(ad->max_size)))
1367                 return -ERANGE;
1368         return 0;
1369 }
1370
1371 /**
1372  * ntfs_attr_can_be_non_resident - check if an attribute can be non-resident
1373  * @vol:        ntfs volume to which the attribute belongs
1374  * @type:       attribute type which to check
1375  *
1376  * Check whether the attribute of @type on the ntfs volume @vol is allowed to
1377  * be non-resident.  This information is obtained from $AttrDef system file.
1378  *
1379  * Return 0 if the attribute is allowed to be non-resident, -EPERM if not, and
1380  * -ENOENT if the attribute is not listed in $AttrDef.
1381  */
1382 int ntfs_attr_can_be_non_resident(const ntfs_volume *vol, const ATTR_TYPE type)
1383 {
1384         ATTR_DEF *ad;
1385
1386         /* Find the attribute definition record in $AttrDef. */
1387         ad = ntfs_attr_find_in_attrdef(vol, type);
1388         if (unlikely(!ad))
1389                 return -ENOENT;
1390         /* Check the flags and return the result. */
1391         if (ad->flags & ATTR_DEF_RESIDENT)
1392                 return -EPERM;
1393         return 0;
1394 }
1395
1396 /**
1397  * ntfs_attr_can_be_resident - check if an attribute can be resident
1398  * @vol:        ntfs volume to which the attribute belongs
1399  * @type:       attribute type which to check
1400  *
1401  * Check whether the attribute of @type on the ntfs volume @vol is allowed to
1402  * be resident.  This information is derived from our ntfs knowledge and may
1403  * not be completely accurate, especially when user defined attributes are
1404  * present.  Basically we allow everything to be resident except for index
1405  * allocation and $EA attributes.
1406  *
1407  * Return 0 if the attribute is allowed to be non-resident and -EPERM if not.
1408  *
1409  * Warning: In the system file $MFT the attribute $Bitmap must be non-resident
1410  *          otherwise windows will not boot (blue screen of death)!  We cannot
1411  *          check for this here as we do not know which inode's $Bitmap is
1412  *          being asked about so the caller needs to special case this.
1413  */
1414 int ntfs_attr_can_be_resident(const ntfs_volume *vol, const ATTR_TYPE type)
1415 {
1416         if (type == AT_INDEX_ALLOCATION)
1417                 return -EPERM;
1418         return 0;
1419 }
1420
1421 /**
1422  * ntfs_attr_record_resize - resize an attribute record
1423  * @m:          mft record containing attribute record
1424  * @a:          attribute record to resize
1425  * @new_size:   new size in bytes to which to resize the attribute record @a
1426  *
1427  * Resize the attribute record @a, i.e. the resident part of the attribute, in
1428  * the mft record @m to @new_size bytes.
1429  *
1430  * Return 0 on success and -errno on error.  The following error codes are
1431  * defined:
1432  *      -ENOSPC - Not enough space in the mft record @m to perform the resize.
1433  *
1434  * Note: On error, no modifications have been performed whatsoever.
1435  *
1436  * Warning: If you make a record smaller without having copied all the data you
1437  *          are interested in the data may be overwritten.
1438  */
1439 int ntfs_attr_record_resize(MFT_RECORD *m, ATTR_RECORD *a, u32 new_size)
1440 {
1441         ntfs_debug("Entering for new_size %u.", new_size);
1442         /* Align to 8 bytes if it is not already done. */
1443         if (new_size & 7)
1444                 new_size = (new_size + 7) & ~7;
1445         /* If the actual attribute length has changed, move things around. */
1446         if (new_size != le32_to_cpu(a->length)) {
1447                 u32 new_muse = le32_to_cpu(m->bytes_in_use) -
1448                                 le32_to_cpu(a->length) + new_size;
1449                 /* Not enough space in this mft record. */
1450                 if (new_muse > le32_to_cpu(m->bytes_allocated))
1451                         return -ENOSPC;
1452                 /* Move attributes following @a to their new location. */
1453                 memmove((u8*)a + new_size, (u8*)a + le32_to_cpu(a->length),
1454                                 le32_to_cpu(m->bytes_in_use) - ((u8*)a -
1455                                 (u8*)m) - le32_to_cpu(a->length));
1456                 /* Adjust @m to reflect the change in used space. */
1457                 m->bytes_in_use = cpu_to_le32(new_muse);
1458                 /* Adjust @a to reflect the new size. */
1459                 if (new_size >= offsetof(ATTR_REC, length) + sizeof(a->length))
1460                         a->length = cpu_to_le32(new_size);
1461         }
1462         return 0;
1463 }
1464
1465 /**
1466  * ntfs_resident_attr_value_resize - resize the value of a resident attribute
1467  * @m:          mft record containing attribute record
1468  * @a:          attribute record whose value to resize
1469  * @new_size:   new size in bytes to which to resize the attribute value of @a
1470  *
1471  * Resize the value of the attribute @a in the mft record @m to @new_size bytes.
1472  * If the value is made bigger, the newly allocated space is cleared.
1473  *
1474  * Return 0 on success and -errno on error.  The following error codes are
1475  * defined:
1476  *      -ENOSPC - Not enough space in the mft record @m to perform the resize.
1477  *
1478  * Note: On error, no modifications have been performed whatsoever.
1479  *
1480  * Warning: If you make a record smaller without having copied all the data you
1481  *          are interested in the data may be overwritten.
1482  */
1483 int ntfs_resident_attr_value_resize(MFT_RECORD *m, ATTR_RECORD *a,
1484                 const u32 new_size)
1485 {
1486         u32 old_size;
1487
1488         /* Resize the resident part of the attribute record. */
1489         if (ntfs_attr_record_resize(m, a,
1490                         le16_to_cpu(a->data.resident.value_offset) + new_size))
1491                 return -ENOSPC;
1492         /*
1493          * The resize succeeded!  If we made the attribute value bigger, clear
1494          * the area between the old size and @new_size.
1495          */
1496         old_size = le32_to_cpu(a->data.resident.value_length);
1497         if (new_size > old_size)
1498                 memset((u8*)a + le16_to_cpu(a->data.resident.value_offset) +
1499                                 old_size, 0, new_size - old_size);
1500         /* Finally update the length of the attribute value. */
1501         a->data.resident.value_length = cpu_to_le32(new_size);
1502         return 0;
1503 }
1504
1505 /**
1506  * ntfs_attr_make_non_resident - convert a resident to a non-resident attribute
1507  * @ni:         ntfs inode describing the attribute to convert
1508  * @data_size:  size of the resident data to copy to the non-resident attribute
1509  *
1510  * Convert the resident ntfs attribute described by the ntfs inode @ni to a
1511  * non-resident one.
1512  *
1513  * @data_size must be equal to the attribute value size.  This is needed since
1514  * we need to know the size before we can map the mft record and our callers
1515  * always know it.  The reason we cannot simply read the size from the vfs
1516  * inode i_size is that this is not necessarily uptodate.  This happens when
1517  * ntfs_attr_make_non_resident() is called in the ->truncate call path(s).
1518  *
1519  * Return 0 on success and -errno on error.  The following error return codes
1520  * are defined:
1521  *      -EPERM  - The attribute is not allowed to be non-resident.
1522  *      -ENOMEM - Not enough memory.
1523  *      -ENOSPC - Not enough disk space.
1524  *      -EINVAL - Attribute not defined on the volume.
1525  *      -EIO    - I/o error or other error.
1526  * Note that -ENOSPC is also returned in the case that there is not enough
1527  * space in the mft record to do the conversion.  This can happen when the mft
1528  * record is already very full.  The caller is responsible for trying to make
1529  * space in the mft record and trying again.  FIXME: Do we need a separate
1530  * error return code for this kind of -ENOSPC or is it always worth trying
1531  * again in case the attribute may then fit in a resident state so no need to
1532  * make it non-resident at all?  Ho-hum...  (AIA)
1533  *
1534  * NOTE to self: No changes in the attribute list are required to move from
1535  *               a resident to a non-resident attribute.
1536  *
1537  * Locking: - The caller must hold i_mutex on the inode.
1538  */
1539 int ntfs_attr_make_non_resident(ntfs_inode *ni, const u32 data_size)
1540 {
1541         s64 new_size;
1542         struct inode *vi = VFS_I(ni);
1543         ntfs_volume *vol = ni->vol;
1544         ntfs_inode *base_ni;
1545         MFT_RECORD *m;
1546         ATTR_RECORD *a;
1547         ntfs_attr_search_ctx *ctx;
1548         struct page *page;
1549         runlist_element *rl;
1550         u8 *kaddr;
1551         unsigned long flags;
1552         int mp_size, mp_ofs, name_ofs, arec_size, err, err2;
1553         u32 attr_size;
1554         u8 old_res_attr_flags;
1555
1556         /* Check that the attribute is allowed to be non-resident. */
1557         err = ntfs_attr_can_be_non_resident(vol, ni->type);
1558         if (unlikely(err)) {
1559                 if (err == -EPERM)
1560                         ntfs_debug("Attribute is not allowed to be "
1561                                         "non-resident.");
1562                 else
1563                         ntfs_debug("Attribute not defined on the NTFS "
1564                                         "volume!");
1565                 return err;
1566         }
1567         /*
1568          * FIXME: Compressed and encrypted attributes are not supported when
1569          * writing and we should never have gotten here for them.
1570          */
1571         BUG_ON(NInoCompressed(ni));
1572         BUG_ON(NInoEncrypted(ni));
1573         /*
1574          * The size needs to be aligned to a cluster boundary for allocation
1575          * purposes.
1576          */
1577         new_size = (data_size + vol->cluster_size - 1) &
1578                         ~(vol->cluster_size - 1);
1579         if (new_size > 0) {
1580                 /*
1581                  * Will need the page later and since the page lock nests
1582                  * outside all ntfs locks, we need to get the page now.
1583                  */
1584                 page = find_or_create_page(vi->i_mapping, 0,
1585                                 mapping_gfp_mask(vi->i_mapping));
1586                 if (unlikely(!page))
1587                         return -ENOMEM;
1588                 /* Start by allocating clusters to hold the attribute value. */
1589                 rl = ntfs_cluster_alloc(vol, 0, new_size >>
1590                                 vol->cluster_size_bits, -1, DATA_ZONE, true);
1591                 if (IS_ERR(rl)) {
1592                         err = PTR_ERR(rl);
1593                         ntfs_debug("Failed to allocate cluster%s, error code "
1594                                         "%i.", (new_size >>
1595                                         vol->cluster_size_bits) > 1 ? "s" : "",
1596                                         err);
1597                         goto page_err_out;
1598                 }
1599         } else {
1600                 rl = NULL;
1601                 page = NULL;
1602         }
1603         /* Determine the size of the mapping pairs array. */
1604         mp_size = ntfs_get_size_for_mapping_pairs(vol, rl, 0, -1);
1605         if (unlikely(mp_size < 0)) {
1606                 err = mp_size;
1607                 ntfs_debug("Failed to get size for mapping pairs array, error "
1608                                 "code %i.", err);
1609                 goto rl_err_out;
1610         }
1611         down_write(&ni->runlist.lock);
1612         if (!NInoAttr(ni))
1613                 base_ni = ni;
1614         else
1615                 base_ni = ni->ext.base_ntfs_ino;
1616         m = map_mft_record(base_ni);
1617         if (IS_ERR(m)) {
1618                 err = PTR_ERR(m);
1619                 m = NULL;
1620                 ctx = NULL;
1621                 goto err_out;
1622         }
1623         ctx = ntfs_attr_get_search_ctx(base_ni, m);
1624         if (unlikely(!ctx)) {
1625                 err = -ENOMEM;
1626                 goto err_out;
1627         }
1628         err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
1629                         CASE_SENSITIVE, 0, NULL, 0, ctx);
1630         if (unlikely(err)) {
1631                 if (err == -ENOENT)
1632                         err = -EIO;
1633                 goto err_out;
1634         }
1635         m = ctx->mrec;
1636         a = ctx->attr;
1637         BUG_ON(NInoNonResident(ni));
1638         BUG_ON(a->non_resident);
1639         /*
1640          * Calculate new offsets for the name and the mapping pairs array.
1641          */
1642         if (NInoSparse(ni) || NInoCompressed(ni))
1643                 name_ofs = (offsetof(ATTR_REC,
1644                                 data.non_resident.compressed_size) +
1645                                 sizeof(a->data.non_resident.compressed_size) +
1646                                 7) & ~7;
1647         else
1648                 name_ofs = (offsetof(ATTR_REC,
1649                                 data.non_resident.compressed_size) + 7) & ~7;
1650         mp_ofs = (name_ofs + a->name_length * sizeof(ntfschar) + 7) & ~7;
1651         /*
1652          * Determine the size of the resident part of the now non-resident
1653          * attribute record.
1654          */
1655         arec_size = (mp_ofs + mp_size + 7) & ~7;
1656         /*
1657          * If the page is not uptodate bring it uptodate by copying from the
1658          * attribute value.
1659          */
1660         attr_size = le32_to_cpu(a->data.resident.value_length);
1661         BUG_ON(attr_size != data_size);
1662         if (page && !PageUptodate(page)) {
1663                 kaddr = kmap_atomic(page);
1664                 memcpy(kaddr, (u8*)a +
1665                                 le16_to_cpu(a->data.resident.value_offset),
1666                                 attr_size);
1667                 memset(kaddr + attr_size, 0, PAGE_SIZE - attr_size);
1668                 kunmap_atomic(kaddr);
1669                 flush_dcache_page(page);
1670                 SetPageUptodate(page);
1671         }
1672         /* Backup the attribute flag. */
1673         old_res_attr_flags = a->data.resident.flags;
1674         /* Resize the resident part of the attribute record. */
1675         err = ntfs_attr_record_resize(m, a, arec_size);
1676         if (unlikely(err))
1677                 goto err_out;
1678         /*
1679          * Convert the resident part of the attribute record to describe a
1680          * non-resident attribute.
1681          */
1682         a->non_resident = 1;
1683         /* Move the attribute name if it exists and update the offset. */
1684         if (a->name_length)
1685                 memmove((u8*)a + name_ofs, (u8*)a + le16_to_cpu(a->name_offset),
1686                                 a->name_length * sizeof(ntfschar));
1687         a->name_offset = cpu_to_le16(name_ofs);
1688         /* Setup the fields specific to non-resident attributes. */
1689         a->data.non_resident.lowest_vcn = 0;
1690         a->data.non_resident.highest_vcn = cpu_to_sle64((new_size - 1) >>
1691                         vol->cluster_size_bits);
1692         a->data.non_resident.mapping_pairs_offset = cpu_to_le16(mp_ofs);
1693         memset(&a->data.non_resident.reserved, 0,
1694                         sizeof(a->data.non_resident.reserved));
1695         a->data.non_resident.allocated_size = cpu_to_sle64(new_size);
1696         a->data.non_resident.data_size =
1697                         a->data.non_resident.initialized_size =
1698                         cpu_to_sle64(attr_size);
1699         if (NInoSparse(ni) || NInoCompressed(ni)) {
1700                 a->data.non_resident.compression_unit = 0;
1701                 if (NInoCompressed(ni) || vol->major_ver < 3)
1702                         a->data.non_resident.compression_unit = 4;
1703                 a->data.non_resident.compressed_size =
1704                                 a->data.non_resident.allocated_size;
1705         } else
1706                 a->data.non_resident.compression_unit = 0;
1707         /* Generate the mapping pairs array into the attribute record. */
1708         err = ntfs_mapping_pairs_build(vol, (u8*)a + mp_ofs,
1709                         arec_size - mp_ofs, rl, 0, -1, NULL);
1710         if (unlikely(err)) {
1711                 ntfs_debug("Failed to build mapping pairs, error code %i.",
1712                                 err);
1713                 goto undo_err_out;
1714         }
1715         /* Setup the in-memory attribute structure to be non-resident. */
1716         ni->runlist.rl = rl;
1717         write_lock_irqsave(&ni->size_lock, flags);
1718         ni->allocated_size = new_size;
1719         if (NInoSparse(ni) || NInoCompressed(ni)) {
1720                 ni->itype.compressed.size = ni->allocated_size;
1721                 if (a->data.non_resident.compression_unit) {
1722                         ni->itype.compressed.block_size = 1U << (a->data.
1723                                         non_resident.compression_unit +
1724                                         vol->cluster_size_bits);
1725                         ni->itype.compressed.block_size_bits =
1726                                         ffs(ni->itype.compressed.block_size) -
1727                                         1;
1728                         ni->itype.compressed.block_clusters = 1U <<
1729                                         a->data.non_resident.compression_unit;
1730                 } else {
1731                         ni->itype.compressed.block_size = 0;
1732                         ni->itype.compressed.block_size_bits = 0;
1733                         ni->itype.compressed.block_clusters = 0;
1734                 }
1735                 vi->i_blocks = ni->itype.compressed.size >> 9;
1736         } else
1737                 vi->i_blocks = ni->allocated_size >> 9;
1738         write_unlock_irqrestore(&ni->size_lock, flags);
1739         /*
1740          * This needs to be last since the address space operations ->readpage
1741          * and ->writepage can run concurrently with us as they are not
1742          * serialized on i_mutex.  Note, we are not allowed to fail once we flip
1743          * this switch, which is another reason to do this last.
1744          */
1745         NInoSetNonResident(ni);
1746         /* Mark the mft record dirty, so it gets written back. */
1747         flush_dcache_mft_record_page(ctx->ntfs_ino);
1748         mark_mft_record_dirty(ctx->ntfs_ino);
1749         ntfs_attr_put_search_ctx(ctx);
1750         unmap_mft_record(base_ni);
1751         up_write(&ni->runlist.lock);
1752         if (page) {
1753                 set_page_dirty(page);
1754                 unlock_page(page);
1755                 put_page(page);
1756         }
1757         ntfs_debug("Done.");
1758         return 0;
1759 undo_err_out:
1760         /* Convert the attribute back into a resident attribute. */
1761         a->non_resident = 0;
1762         /* Move the attribute name if it exists and update the offset. */
1763         name_ofs = (offsetof(ATTR_RECORD, data.resident.reserved) +
1764                         sizeof(a->data.resident.reserved) + 7) & ~7;
1765         if (a->name_length)
1766                 memmove((u8*)a + name_ofs, (u8*)a + le16_to_cpu(a->name_offset),
1767                                 a->name_length * sizeof(ntfschar));
1768         mp_ofs = (name_ofs + a->name_length * sizeof(ntfschar) + 7) & ~7;
1769         a->name_offset = cpu_to_le16(name_ofs);
1770         arec_size = (mp_ofs + attr_size + 7) & ~7;
1771         /* Resize the resident part of the attribute record. */
1772         err2 = ntfs_attr_record_resize(m, a, arec_size);
1773         if (unlikely(err2)) {
1774                 /*
1775                  * This cannot happen (well if memory corruption is at work it
1776                  * could happen in theory), but deal with it as well as we can.
1777                  * If the old size is too small, truncate the attribute,
1778                  * otherwise simply give it a larger allocated size.
1779                  * FIXME: Should check whether chkdsk complains when the
1780                  * allocated size is much bigger than the resident value size.
1781                  */
1782                 arec_size = le32_to_cpu(a->length);
1783                 if ((mp_ofs + attr_size) > arec_size) {
1784                         err2 = attr_size;
1785                         attr_size = arec_size - mp_ofs;
1786                         ntfs_error(vol->sb, "Failed to undo partial resident "
1787                                         "to non-resident attribute "
1788                                         "conversion.  Truncating inode 0x%lx, "
1789                                         "attribute type 0x%x from %i bytes to "
1790                                         "%i bytes to maintain metadata "
1791                                         "consistency.  THIS MEANS YOU ARE "
1792                                         "LOSING %i BYTES DATA FROM THIS %s.",
1793                                         vi->i_ino,
1794                                         (unsigned)le32_to_cpu(ni->type),
1795                                         err2, attr_size, err2 - attr_size,
1796                                         ((ni->type == AT_DATA) &&
1797                                         !ni->name_len) ? "FILE": "ATTRIBUTE");
1798                         write_lock_irqsave(&ni->size_lock, flags);
1799                         ni->initialized_size = attr_size;
1800                         i_size_write(vi, attr_size);
1801                         write_unlock_irqrestore(&ni->size_lock, flags);
1802                 }
1803         }
1804         /* Setup the fields specific to resident attributes. */
1805         a->data.resident.value_length = cpu_to_le32(attr_size);
1806         a->data.resident.value_offset = cpu_to_le16(mp_ofs);
1807         a->data.resident.flags = old_res_attr_flags;
1808         memset(&a->data.resident.reserved, 0,
1809                         sizeof(a->data.resident.reserved));
1810         /* Copy the data from the page back to the attribute value. */
1811         if (page) {
1812                 kaddr = kmap_atomic(page);
1813                 memcpy((u8*)a + mp_ofs, kaddr, attr_size);
1814                 kunmap_atomic(kaddr);
1815         }
1816         /* Setup the allocated size in the ntfs inode in case it changed. */
1817         write_lock_irqsave(&ni->size_lock, flags);
1818         ni->allocated_size = arec_size - mp_ofs;
1819         write_unlock_irqrestore(&ni->size_lock, flags);
1820         /* Mark the mft record dirty, so it gets written back. */
1821         flush_dcache_mft_record_page(ctx->ntfs_ino);
1822         mark_mft_record_dirty(ctx->ntfs_ino);
1823 err_out:
1824         if (ctx)
1825                 ntfs_attr_put_search_ctx(ctx);
1826         if (m)
1827                 unmap_mft_record(base_ni);
1828         ni->runlist.rl = NULL;
1829         up_write(&ni->runlist.lock);
1830 rl_err_out:
1831         if (rl) {
1832                 if (ntfs_cluster_free_from_rl(vol, rl) < 0) {
1833                         ntfs_error(vol->sb, "Failed to release allocated "
1834                                         "cluster(s) in error code path.  Run "
1835                                         "chkdsk to recover the lost "
1836                                         "cluster(s).");
1837                         NVolSetErrors(vol);
1838                 }
1839                 ntfs_free(rl);
1840 page_err_out:
1841                 unlock_page(page);
1842                 put_page(page);
1843         }
1844         if (err == -EINVAL)
1845                 err = -EIO;
1846         return err;
1847 }
1848
1849 /**
1850  * ntfs_attr_extend_allocation - extend the allocated space of an attribute
1851  * @ni:                 ntfs inode of the attribute whose allocation to extend
1852  * @new_alloc_size:     new size in bytes to which to extend the allocation to
1853  * @new_data_size:      new size in bytes to which to extend the data to
1854  * @data_start:         beginning of region which is required to be non-sparse
1855  *
1856  * Extend the allocated space of an attribute described by the ntfs inode @ni
1857  * to @new_alloc_size bytes.  If @data_start is -1, the whole extension may be
1858  * implemented as a hole in the file (as long as both the volume and the ntfs
1859  * inode @ni have sparse support enabled).  If @data_start is >= 0, then the
1860  * region between the old allocated size and @data_start - 1 may be made sparse
1861  * but the regions between @data_start and @new_alloc_size must be backed by
1862  * actual clusters.
1863  *
1864  * If @new_data_size is -1, it is ignored.  If it is >= 0, then the data size
1865  * of the attribute is extended to @new_data_size.  Note that the i_size of the
1866  * vfs inode is not updated.  Only the data size in the base attribute record
1867  * is updated.  The caller has to update i_size separately if this is required.
1868  * WARNING: It is a BUG() for @new_data_size to be smaller than the old data
1869  * size as well as for @new_data_size to be greater than @new_alloc_size.
1870  *
1871  * For resident attributes this involves resizing the attribute record and if
1872  * necessary moving it and/or other attributes into extent mft records and/or
1873  * converting the attribute to a non-resident attribute which in turn involves
1874  * extending the allocation of a non-resident attribute as described below.
1875  *
1876  * For non-resident attributes this involves allocating clusters in the data
1877  * zone on the volume (except for regions that are being made sparse) and
1878  * extending the run list to describe the allocated clusters as well as
1879  * updating the mapping pairs array of the attribute.  This in turn involves
1880  * resizing the attribute record and if necessary moving it and/or other
1881  * attributes into extent mft records and/or splitting the attribute record
1882  * into multiple extent attribute records.
1883  *
1884  * Also, the attribute list attribute is updated if present and in some of the
1885  * above cases (the ones where extent mft records/attributes come into play),
1886  * an attribute list attribute is created if not already present.
1887  *
1888  * Return the new allocated size on success and -errno on error.  In the case
1889  * that an error is encountered but a partial extension at least up to
1890  * @data_start (if present) is possible, the allocation is partially extended
1891  * and this is returned.  This means the caller must check the returned size to
1892  * determine if the extension was partial.  If @data_start is -1 then partial
1893  * allocations are not performed.
1894  *
1895  * WARNING: Do not call ntfs_attr_extend_allocation() for $MFT/$DATA.
1896  *
1897  * Locking: This function takes the runlist lock of @ni for writing as well as
1898  * locking the mft record of the base ntfs inode.  These locks are maintained
1899  * throughout execution of the function.  These locks are required so that the
1900  * attribute can be resized safely and so that it can for example be converted
1901  * from resident to non-resident safely.
1902  *
1903  * TODO: At present attribute list attribute handling is not implemented.
1904  *
1905  * TODO: At present it is not safe to call this function for anything other
1906  * than the $DATA attribute(s) of an uncompressed and unencrypted file.
1907  */
1908 s64 ntfs_attr_extend_allocation(ntfs_inode *ni, s64 new_alloc_size,
1909                 const s64 new_data_size, const s64 data_start)
1910 {
1911         VCN vcn;
1912         s64 ll, allocated_size, start = data_start;
1913         struct inode *vi = VFS_I(ni);
1914         ntfs_volume *vol = ni->vol;
1915         ntfs_inode *base_ni;
1916         MFT_RECORD *m;
1917         ATTR_RECORD *a;
1918         ntfs_attr_search_ctx *ctx;
1919         runlist_element *rl, *rl2;
1920         unsigned long flags;
1921         int err, mp_size;
1922         u32 attr_len = 0; /* Silence stupid gcc warning. */
1923         bool mp_rebuilt;
1924
1925 #ifdef DEBUG
1926         read_lock_irqsave(&ni->size_lock, flags);
1927         allocated_size = ni->allocated_size;
1928         read_unlock_irqrestore(&ni->size_lock, flags);
1929         ntfs_debug("Entering for i_ino 0x%lx, attribute type 0x%x, "
1930                         "old_allocated_size 0x%llx, "
1931                         "new_allocated_size 0x%llx, new_data_size 0x%llx, "
1932                         "data_start 0x%llx.", vi->i_ino,
1933                         (unsigned)le32_to_cpu(ni->type),
1934                         (unsigned long long)allocated_size,
1935                         (unsigned long long)new_alloc_size,
1936                         (unsigned long long)new_data_size,
1937                         (unsigned long long)start);
1938 #endif
1939 retry_extend:
1940         /*
1941          * For non-resident attributes, @start and @new_size need to be aligned
1942          * to cluster boundaries for allocation purposes.
1943          */
1944         if (NInoNonResident(ni)) {
1945                 if (start > 0)
1946                         start &= ~(s64)vol->cluster_size_mask;
1947                 new_alloc_size = (new_alloc_size + vol->cluster_size - 1) &
1948                                 ~(s64)vol->cluster_size_mask;
1949         }
1950         BUG_ON(new_data_size >= 0 && new_data_size > new_alloc_size);
1951         /* Check if new size is allowed in $AttrDef. */
1952         err = ntfs_attr_size_bounds_check(vol, ni->type, new_alloc_size);
1953         if (unlikely(err)) {
1954                 /* Only emit errors when the write will fail completely. */
1955                 read_lock_irqsave(&ni->size_lock, flags);
1956                 allocated_size = ni->allocated_size;
1957                 read_unlock_irqrestore(&ni->size_lock, flags);
1958                 if (start < 0 || start >= allocated_size) {
1959                         if (err == -ERANGE) {
1960                                 ntfs_error(vol->sb, "Cannot extend allocation "
1961                                                 "of inode 0x%lx, attribute "
1962                                                 "type 0x%x, because the new "
1963                                                 "allocation would exceed the "
1964                                                 "maximum allowed size for "
1965                                                 "this attribute type.",
1966                                                 vi->i_ino, (unsigned)
1967                                                 le32_to_cpu(ni->type));
1968                         } else {
1969                                 ntfs_error(vol->sb, "Cannot extend allocation "
1970                                                 "of inode 0x%lx, attribute "
1971                                                 "type 0x%x, because this "
1972                                                 "attribute type is not "
1973                                                 "defined on the NTFS volume.  "
1974                                                 "Possible corruption!  You "
1975                                                 "should run chkdsk!",
1976                                                 vi->i_ino, (unsigned)
1977                                                 le32_to_cpu(ni->type));
1978                         }
1979                 }
1980                 /* Translate error code to be POSIX conformant for write(2). */
1981                 if (err == -ERANGE)
1982                         err = -EFBIG;
1983                 else
1984                         err = -EIO;
1985                 return err;
1986         }
1987         if (!NInoAttr(ni))
1988                 base_ni = ni;
1989         else
1990                 base_ni = ni->ext.base_ntfs_ino;
1991         /*
1992          * We will be modifying both the runlist (if non-resident) and the mft
1993          * record so lock them both down.
1994          */
1995         down_write(&ni->runlist.lock);
1996         m = map_mft_record(base_ni);
1997         if (IS_ERR(m)) {
1998                 err = PTR_ERR(m);
1999                 m = NULL;
2000                 ctx = NULL;
2001                 goto err_out;
2002         }
2003         ctx = ntfs_attr_get_search_ctx(base_ni, m);
2004         if (unlikely(!ctx)) {
2005                 err = -ENOMEM;
2006                 goto err_out;
2007         }
2008         read_lock_irqsave(&ni->size_lock, flags);
2009         allocated_size = ni->allocated_size;
2010         read_unlock_irqrestore(&ni->size_lock, flags);
2011         /*
2012          * If non-resident, seek to the last extent.  If resident, there is
2013          * only one extent, so seek to that.
2014          */
2015         vcn = NInoNonResident(ni) ? allocated_size >> vol->cluster_size_bits :
2016                         0;
2017         /*
2018          * Abort if someone did the work whilst we waited for the locks.  If we
2019          * just converted the attribute from resident to non-resident it is
2020          * likely that exactly this has happened already.  We cannot quite
2021          * abort if we need to update the data size.
2022          */
2023         if (unlikely(new_alloc_size <= allocated_size)) {
2024                 ntfs_debug("Allocated size already exceeds requested size.");
2025                 new_alloc_size = allocated_size;
2026                 if (new_data_size < 0)
2027                         goto done;
2028                 /*
2029                  * We want the first attribute extent so that we can update the
2030                  * data size.
2031                  */
2032                 vcn = 0;
2033         }
2034         err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
2035                         CASE_SENSITIVE, vcn, NULL, 0, ctx);
2036         if (unlikely(err)) {
2037                 if (err == -ENOENT)
2038                         err = -EIO;
2039                 goto err_out;
2040         }
2041         m = ctx->mrec;
2042         a = ctx->attr;
2043         /* Use goto to reduce indentation. */
2044         if (a->non_resident)
2045                 goto do_non_resident_extend;
2046         BUG_ON(NInoNonResident(ni));
2047         /* The total length of the attribute value. */
2048         attr_len = le32_to_cpu(a->data.resident.value_length);
2049         /*
2050          * Extend the attribute record to be able to store the new attribute
2051          * size.  ntfs_attr_record_resize() will not do anything if the size is
2052          * not changing.
2053          */
2054         if (new_alloc_size < vol->mft_record_size &&
2055                         !ntfs_attr_record_resize(m, a,
2056                         le16_to_cpu(a->data.resident.value_offset) +
2057                         new_alloc_size)) {
2058                 /* The resize succeeded! */
2059                 write_lock_irqsave(&ni->size_lock, flags);
2060                 ni->allocated_size = le32_to_cpu(a->length) -
2061                                 le16_to_cpu(a->data.resident.value_offset);
2062                 write_unlock_irqrestore(&ni->size_lock, flags);
2063                 if (new_data_size >= 0) {
2064                         BUG_ON(new_data_size < attr_len);
2065                         a->data.resident.value_length =
2066                                         cpu_to_le32((u32)new_data_size);
2067                 }
2068                 goto flush_done;
2069         }
2070         /*
2071          * We have to drop all the locks so we can call
2072          * ntfs_attr_make_non_resident().  This could be optimised by try-
2073          * locking the first page cache page and only if that fails dropping
2074          * the locks, locking the page, and redoing all the locking and
2075          * lookups.  While this would be a huge optimisation, it is not worth
2076          * it as this is definitely a slow code path.
2077          */
2078         ntfs_attr_put_search_ctx(ctx);
2079         unmap_mft_record(base_ni);
2080         up_write(&ni->runlist.lock);
2081         /*
2082          * Not enough space in the mft record, try to make the attribute
2083          * non-resident and if successful restart the extension process.
2084          */
2085         err = ntfs_attr_make_non_resident(ni, attr_len);
2086         if (likely(!err))
2087                 goto retry_extend;
2088         /*
2089          * Could not make non-resident.  If this is due to this not being
2090          * permitted for this attribute type or there not being enough space,
2091          * try to make other attributes non-resident.  Otherwise fail.
2092          */
2093         if (unlikely(err != -EPERM && err != -ENOSPC)) {
2094                 /* Only emit errors when the write will fail completely. */
2095                 read_lock_irqsave(&ni->size_lock, flags);
2096                 allocated_size = ni->allocated_size;
2097                 read_unlock_irqrestore(&ni->size_lock, flags);
2098                 if (start < 0 || start >= allocated_size)
2099                         ntfs_error(vol->sb, "Cannot extend allocation of "
2100                                         "inode 0x%lx, attribute type 0x%x, "
2101                                         "because the conversion from resident "
2102                                         "to non-resident attribute failed "
2103                                         "with error code %i.", vi->i_ino,
2104                                         (unsigned)le32_to_cpu(ni->type), err);
2105                 if (err != -ENOMEM)
2106                         err = -EIO;
2107                 goto conv_err_out;
2108         }
2109         /* TODO: Not implemented from here, abort. */
2110         read_lock_irqsave(&ni->size_lock, flags);
2111         allocated_size = ni->allocated_size;
2112         read_unlock_irqrestore(&ni->size_lock, flags);
2113         if (start < 0 || start >= allocated_size) {
2114                 if (err == -ENOSPC)
2115                         ntfs_error(vol->sb, "Not enough space in the mft "
2116                                         "record/on disk for the non-resident "
2117                                         "attribute value.  This case is not "
2118                                         "implemented yet.");
2119                 else /* if (err == -EPERM) */
2120                         ntfs_error(vol->sb, "This attribute type may not be "
2121                                         "non-resident.  This case is not "
2122                                         "implemented yet.");
2123         }
2124         err = -EOPNOTSUPP;
2125         goto conv_err_out;
2126 #if 0
2127         // TODO: Attempt to make other attributes non-resident.
2128         if (!err)
2129                 goto do_resident_extend;
2130         /*
2131          * Both the attribute list attribute and the standard information
2132          * attribute must remain in the base inode.  Thus, if this is one of
2133          * these attributes, we have to try to move other attributes out into
2134          * extent mft records instead.
2135          */
2136         if (ni->type == AT_ATTRIBUTE_LIST ||
2137                         ni->type == AT_STANDARD_INFORMATION) {
2138                 // TODO: Attempt to move other attributes into extent mft
2139                 // records.
2140                 err = -EOPNOTSUPP;
2141                 if (!err)
2142                         goto do_resident_extend;
2143                 goto err_out;
2144         }
2145         // TODO: Attempt to move this attribute to an extent mft record, but
2146         // only if it is not already the only attribute in an mft record in
2147         // which case there would be nothing to gain.
2148         err = -EOPNOTSUPP;
2149         if (!err)
2150                 goto do_resident_extend;
2151         /* There is nothing we can do to make enough space. )-: */
2152         goto err_out;
2153 #endif
2154 do_non_resident_extend:
2155         BUG_ON(!NInoNonResident(ni));
2156         if (new_alloc_size == allocated_size) {
2157                 BUG_ON(vcn);
2158                 goto alloc_done;
2159         }
2160         /*
2161          * If the data starts after the end of the old allocation, this is a
2162          * $DATA attribute and sparse attributes are enabled on the volume and
2163          * for this inode, then create a sparse region between the old
2164          * allocated size and the start of the data.  Otherwise simply proceed
2165          * with filling the whole space between the old allocated size and the
2166          * new allocated size with clusters.
2167          */
2168         if ((start >= 0 && start <= allocated_size) || ni->type != AT_DATA ||
2169                         !NVolSparseEnabled(vol) || NInoSparseDisabled(ni))
2170                 goto skip_sparse;
2171         // TODO: This is not implemented yet.  We just fill in with real
2172         // clusters for now...
2173         ntfs_debug("Inserting holes is not-implemented yet.  Falling back to "
2174                         "allocating real clusters instead.");
2175 skip_sparse:
2176         rl = ni->runlist.rl;
2177         if (likely(rl)) {
2178                 /* Seek to the end of the runlist. */
2179                 while (rl->length)
2180                         rl++;
2181         }
2182         /* If this attribute extent is not mapped, map it now. */
2183         if (unlikely(!rl || rl->lcn == LCN_RL_NOT_MAPPED ||
2184                         (rl->lcn == LCN_ENOENT && rl > ni->runlist.rl &&
2185                         (rl-1)->lcn == LCN_RL_NOT_MAPPED))) {
2186                 if (!rl && !allocated_size)
2187                         goto first_alloc;
2188                 rl = ntfs_mapping_pairs_decompress(vol, a, ni->runlist.rl);
2189                 if (IS_ERR(rl)) {
2190                         err = PTR_ERR(rl);
2191                         if (start < 0 || start >= allocated_size)
2192                                 ntfs_error(vol->sb, "Cannot extend allocation "
2193                                                 "of inode 0x%lx, attribute "
2194                                                 "type 0x%x, because the "
2195                                                 "mapping of a runlist "
2196                                                 "fragment failed with error "
2197                                                 "code %i.", vi->i_ino,
2198                                                 (unsigned)le32_to_cpu(ni->type),
2199                                                 err);
2200                         if (err != -ENOMEM)
2201                                 err = -EIO;
2202                         goto err_out;
2203                 }
2204                 ni->runlist.rl = rl;
2205                 /* Seek to the end of the runlist. */
2206                 while (rl->length)
2207                         rl++;
2208         }
2209         /*
2210          * We now know the runlist of the last extent is mapped and @rl is at
2211          * the end of the runlist.  We want to begin allocating clusters
2212          * starting at the last allocated cluster to reduce fragmentation.  If
2213          * there are no valid LCNs in the attribute we let the cluster
2214          * allocator choose the starting cluster.
2215          */
2216         /* If the last LCN is a hole or simillar seek back to last real LCN. */
2217         while (rl->lcn < 0 && rl > ni->runlist.rl)
2218                 rl--;
2219 first_alloc:
2220         // FIXME: Need to implement partial allocations so at least part of the
2221         // write can be performed when start >= 0.  (Needed for POSIX write(2)
2222         // conformance.)
2223         rl2 = ntfs_cluster_alloc(vol, allocated_size >> vol->cluster_size_bits,
2224                         (new_alloc_size - allocated_size) >>
2225                         vol->cluster_size_bits, (rl && (rl->lcn >= 0)) ?
2226                         rl->lcn + rl->length : -1, DATA_ZONE, true);
2227         if (IS_ERR(rl2)) {
2228                 err = PTR_ERR(rl2);
2229                 if (start < 0 || start >= allocated_size)
2230                         ntfs_error(vol->sb, "Cannot extend allocation of "
2231                                         "inode 0x%lx, attribute type 0x%x, "
2232                                         "because the allocation of clusters "
2233                                         "failed with error code %i.", vi->i_ino,
2234                                         (unsigned)le32_to_cpu(ni->type), err);
2235                 if (err != -ENOMEM && err != -ENOSPC)
2236                         err = -EIO;
2237                 goto err_out;
2238         }
2239         rl = ntfs_runlists_merge(ni->runlist.rl, rl2);
2240         if (IS_ERR(rl)) {
2241                 err = PTR_ERR(rl);
2242                 if (start < 0 || start >= allocated_size)
2243                         ntfs_error(vol->sb, "Cannot extend allocation of "
2244                                         "inode 0x%lx, attribute type 0x%x, "
2245                                         "because the runlist merge failed "
2246                                         "with error code %i.", vi->i_ino,
2247                                         (unsigned)le32_to_cpu(ni->type), err);
2248                 if (err != -ENOMEM)
2249                         err = -EIO;
2250                 if (ntfs_cluster_free_from_rl(vol, rl2)) {
2251                         ntfs_error(vol->sb, "Failed to release allocated "
2252                                         "cluster(s) in error code path.  Run "
2253                                         "chkdsk to recover the lost "
2254                                         "cluster(s).");
2255                         NVolSetErrors(vol);
2256                 }
2257                 ntfs_free(rl2);
2258                 goto err_out;
2259         }
2260         ni->runlist.rl = rl;
2261         ntfs_debug("Allocated 0x%llx clusters.", (long long)(new_alloc_size -
2262                         allocated_size) >> vol->cluster_size_bits);
2263         /* Find the runlist element with which the attribute extent starts. */
2264         ll = sle64_to_cpu(a->data.non_resident.lowest_vcn);
2265         rl2 = ntfs_rl_find_vcn_nolock(rl, ll);
2266         BUG_ON(!rl2);
2267         BUG_ON(!rl2->length);
2268         BUG_ON(rl2->lcn < LCN_HOLE);
2269         mp_rebuilt = false;
2270         /* Get the size for the new mapping pairs array for this extent. */
2271         mp_size = ntfs_get_size_for_mapping_pairs(vol, rl2, ll, -1);
2272         if (unlikely(mp_size <= 0)) {
2273                 err = mp_size;
2274                 if (start < 0 || start >= allocated_size)
2275                         ntfs_error(vol->sb, "Cannot extend allocation of "
2276                                         "inode 0x%lx, attribute type 0x%x, "
2277                                         "because determining the size for the "
2278                                         "mapping pairs failed with error code "
2279                                         "%i.", vi->i_ino,
2280                                         (unsigned)le32_to_cpu(ni->type), err);
2281                 err = -EIO;
2282                 goto undo_alloc;
2283         }
2284         /* Extend the attribute record to fit the bigger mapping pairs array. */
2285         attr_len = le32_to_cpu(a->length);
2286         err = ntfs_attr_record_resize(m, a, mp_size +
2287                         le16_to_cpu(a->data.non_resident.mapping_pairs_offset));
2288         if (unlikely(err)) {
2289                 BUG_ON(err != -ENOSPC);
2290                 // TODO: Deal with this by moving this extent to a new mft
2291                 // record or by starting a new extent in a new mft record,
2292                 // possibly by extending this extent partially and filling it
2293                 // and creating a new extent for the remainder, or by making
2294                 // other attributes non-resident and/or by moving other
2295                 // attributes out of this mft record.
2296                 if (start < 0 || start >= allocated_size)
2297                         ntfs_error(vol->sb, "Not enough space in the mft "
2298                                         "record for the extended attribute "
2299                                         "record.  This case is not "
2300                                         "implemented yet.");
2301                 err = -EOPNOTSUPP;
2302                 goto undo_alloc;
2303         }
2304         mp_rebuilt = true;
2305         /* Generate the mapping pairs array directly into the attr record. */
2306         err = ntfs_mapping_pairs_build(vol, (u8*)a +
2307                         le16_to_cpu(a->data.non_resident.mapping_pairs_offset),
2308                         mp_size, rl2, ll, -1, NULL);
2309         if (unlikely(err)) {
2310                 if (start < 0 || start >= allocated_size)
2311                         ntfs_error(vol->sb, "Cannot extend allocation of "
2312                                         "inode 0x%lx, attribute type 0x%x, "
2313                                         "because building the mapping pairs "
2314                                         "failed with error code %i.", vi->i_ino,
2315                                         (unsigned)le32_to_cpu(ni->type), err);
2316                 err = -EIO;
2317                 goto undo_alloc;
2318         }
2319         /* Update the highest_vcn. */
2320         a->data.non_resident.highest_vcn = cpu_to_sle64((new_alloc_size >>
2321                         vol->cluster_size_bits) - 1);
2322         /*
2323          * We now have extended the allocated size of the attribute.  Reflect
2324          * this in the ntfs_inode structure and the attribute record.
2325          */
2326         if (a->data.non_resident.lowest_vcn) {
2327                 /*
2328                  * We are not in the first attribute extent, switch to it, but
2329                  * first ensure the changes will make it to disk later.
2330                  */
2331                 flush_dcache_mft_record_page(ctx->ntfs_ino);
2332                 mark_mft_record_dirty(ctx->ntfs_ino);
2333                 ntfs_attr_reinit_search_ctx(ctx);
2334                 err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
2335                                 CASE_SENSITIVE, 0, NULL, 0, ctx);
2336                 if (unlikely(err))
2337                         goto restore_undo_alloc;
2338                 /* @m is not used any more so no need to set it. */
2339                 a = ctx->attr;
2340         }
2341         write_lock_irqsave(&ni->size_lock, flags);
2342         ni->allocated_size = new_alloc_size;
2343         a->data.non_resident.allocated_size = cpu_to_sle64(new_alloc_size);
2344         /*
2345          * FIXME: This would fail if @ni is a directory, $MFT, or an index,
2346          * since those can have sparse/compressed set.  For example can be
2347          * set compressed even though it is not compressed itself and in that
2348          * case the bit means that files are to be created compressed in the
2349          * directory...  At present this is ok as this code is only called for
2350          * regular files, and only for their $DATA attribute(s).
2351          * FIXME: The calculation is wrong if we created a hole above.  For now
2352          * it does not matter as we never create holes.
2353          */
2354         if (NInoSparse(ni) || NInoCompressed(ni)) {
2355                 ni->itype.compressed.size += new_alloc_size - allocated_size;
2356                 a->data.non_resident.compressed_size =
2357                                 cpu_to_sle64(ni->itype.compressed.size);
2358                 vi->i_blocks = ni->itype.compressed.size >> 9;
2359         } else
2360                 vi->i_blocks = new_alloc_size >> 9;
2361         write_unlock_irqrestore(&ni->size_lock, flags);
2362 alloc_done:
2363         if (new_data_size >= 0) {
2364                 BUG_ON(new_data_size <
2365                                 sle64_to_cpu(a->data.non_resident.data_size));
2366                 a->data.non_resident.data_size = cpu_to_sle64(new_data_size);
2367         }
2368 flush_done:
2369         /* Ensure the changes make it to disk. */
2370         flush_dcache_mft_record_page(ctx->ntfs_ino);
2371         mark_mft_record_dirty(ctx->ntfs_ino);
2372 done:
2373         ntfs_attr_put_search_ctx(ctx);
2374         unmap_mft_record(base_ni);
2375         up_write(&ni->runlist.lock);
2376         ntfs_debug("Done, new_allocated_size 0x%llx.",
2377                         (unsigned long long)new_alloc_size);
2378         return new_alloc_size;
2379 restore_undo_alloc:
2380         if (start < 0 || start >= allocated_size)
2381                 ntfs_error(vol->sb, "Cannot complete extension of allocation "
2382                                 "of inode 0x%lx, attribute type 0x%x, because "
2383                                 "lookup of first attribute extent failed with "
2384                                 "error code %i.", vi->i_ino,
2385                                 (unsigned)le32_to_cpu(ni->type), err);
2386         if (err == -ENOENT)
2387                 err = -EIO;
2388         ntfs_attr_reinit_search_ctx(ctx);
2389         if (ntfs_attr_lookup(ni->type, ni->name, ni->name_len, CASE_SENSITIVE,
2390                         allocated_size >> vol->cluster_size_bits, NULL, 0,
2391                         ctx)) {
2392                 ntfs_error(vol->sb, "Failed to find last attribute extent of "
2393                                 "attribute in error code path.  Run chkdsk to "
2394                                 "recover.");
2395                 write_lock_irqsave(&ni->size_lock, flags);
2396                 ni->allocated_size = new_alloc_size;
2397                 /*
2398                  * FIXME: This would fail if @ni is a directory...  See above.
2399                  * FIXME: The calculation is wrong if we created a hole above.
2400                  * For now it does not matter as we never create holes.
2401                  */
2402                 if (NInoSparse(ni) || NInoCompressed(ni)) {
2403                         ni->itype.compressed.size += new_alloc_size -
2404                                         allocated_size;
2405                         vi->i_blocks = ni->itype.compressed.size >> 9;
2406                 } else
2407                         vi->i_blocks = new_alloc_size >> 9;
2408                 write_unlock_irqrestore(&ni->size_lock, flags);
2409                 ntfs_attr_put_search_ctx(ctx);
2410                 unmap_mft_record(base_ni);
2411                 up_write(&ni->runlist.lock);
2412                 /*
2413                  * The only thing that is now wrong is the allocated size of the
2414                  * base attribute extent which chkdsk should be able to fix.
2415                  */
2416                 NVolSetErrors(vol);
2417                 return err;
2418         }
2419         ctx->attr->data.non_resident.highest_vcn = cpu_to_sle64(
2420                         (allocated_size >> vol->cluster_size_bits) - 1);
2421 undo_alloc:
2422         ll = allocated_size >> vol->cluster_size_bits;
2423         if (ntfs_cluster_free(ni, ll, -1, ctx) < 0) {
2424                 ntfs_error(vol->sb, "Failed to release allocated cluster(s) "
2425                                 "in error code path.  Run chkdsk to recover "
2426                                 "the lost cluster(s).");
2427                 NVolSetErrors(vol);
2428         }
2429         m = ctx->mrec;
2430         a = ctx->attr;
2431         /*
2432          * If the runlist truncation fails and/or the search context is no
2433          * longer valid, we cannot resize the attribute record or build the
2434          * mapping pairs array thus we mark the inode bad so that no access to
2435          * the freed clusters can happen.
2436          */
2437         if (ntfs_rl_truncate_nolock(vol, &ni->runlist, ll) || IS_ERR(m)) {
2438                 ntfs_error(vol->sb, "Failed to %s in error code path.  Run "
2439                                 "chkdsk to recover.", IS_ERR(m) ?
2440                                 "restore attribute search context" :
2441                                 "truncate attribute runlist");
2442                 NVolSetErrors(vol);
2443         } else if (mp_rebuilt) {
2444                 if (ntfs_attr_record_resize(m, a, attr_len)) {
2445                         ntfs_error(vol->sb, "Failed to restore attribute "
2446                                         "record in error code path.  Run "
2447                                         "chkdsk to recover.");
2448                         NVolSetErrors(vol);
2449                 } else /* if (success) */ {
2450                         if (ntfs_mapping_pairs_build(vol, (u8*)a + le16_to_cpu(
2451                                         a->data.non_resident.
2452                                         mapping_pairs_offset), attr_len -
2453                                         le16_to_cpu(a->data.non_resident.
2454                                         mapping_pairs_offset), rl2, ll, -1,
2455                                         NULL)) {
2456                                 ntfs_error(vol->sb, "Failed to restore "
2457                                                 "mapping pairs array in error "
2458                                                 "code path.  Run chkdsk to "
2459                                                 "recover.");
2460                                 NVolSetErrors(vol);
2461                         }
2462                         flush_dcache_mft_record_page(ctx->ntfs_ino);
2463                         mark_mft_record_dirty(ctx->ntfs_ino);
2464                 }
2465         }
2466 err_out:
2467         if (ctx)
2468                 ntfs_attr_put_search_ctx(ctx);
2469         if (m)
2470                 unmap_mft_record(base_ni);
2471         up_write(&ni->runlist.lock);
2472 conv_err_out:
2473         ntfs_debug("Failed.  Returning error code %i.", err);
2474         return err;
2475 }
2476
2477 /**
2478  * ntfs_attr_set - fill (a part of) an attribute with a byte
2479  * @ni:         ntfs inode describing the attribute to fill
2480  * @ofs:        offset inside the attribute at which to start to fill
2481  * @cnt:        number of bytes to fill
2482  * @val:        the unsigned 8-bit value with which to fill the attribute
2483  *
2484  * Fill @cnt bytes of the attribute described by the ntfs inode @ni starting at
2485  * byte offset @ofs inside the attribute with the constant byte @val.
2486  *
2487  * This function is effectively like memset() applied to an ntfs attribute.
2488  * Note thie function actually only operates on the page cache pages belonging
2489  * to the ntfs attribute and it marks them dirty after doing the memset().
2490  * Thus it relies on the vm dirty page write code paths to cause the modified
2491  * pages to be written to the mft record/disk.
2492  *
2493  * Return 0 on success and -errno on error.  An error code of -ESPIPE means
2494  * that @ofs + @cnt were outside the end of the attribute and no write was
2495  * performed.
2496  */
2497 int ntfs_attr_set(ntfs_inode *ni, const s64 ofs, const s64 cnt, const u8 val)
2498 {
2499         ntfs_volume *vol = ni->vol;
2500         struct address_space *mapping;
2501         struct page *page;
2502         u8 *kaddr;
2503         pgoff_t idx, end;
2504         unsigned start_ofs, end_ofs, size;
2505
2506         ntfs_debug("Entering for ofs 0x%llx, cnt 0x%llx, val 0x%hx.",
2507                         (long long)ofs, (long long)cnt, val);
2508         BUG_ON(ofs < 0);
2509         BUG_ON(cnt < 0);
2510         if (!cnt)
2511                 goto done;
2512         /*
2513          * FIXME: Compressed and encrypted attributes are not supported when
2514          * writing and we should never have gotten here for them.
2515          */
2516         BUG_ON(NInoCompressed(ni));
2517         BUG_ON(NInoEncrypted(ni));
2518         mapping = VFS_I(ni)->i_mapping;
2519         /* Work out the starting index and page offset. */
2520         idx = ofs >> PAGE_SHIFT;
2521         start_ofs = ofs & ~PAGE_MASK;
2522         /* Work out the ending index and page offset. */
2523         end = ofs + cnt;
2524         end_ofs = end & ~PAGE_MASK;
2525         /* If the end is outside the inode size return -ESPIPE. */
2526         if (unlikely(end > i_size_read(VFS_I(ni)))) {
2527                 ntfs_error(vol->sb, "Request exceeds end of attribute.");
2528                 return -ESPIPE;
2529         }
2530         end >>= PAGE_SHIFT;
2531         /* If there is a first partial page, need to do it the slow way. */
2532         if (start_ofs) {
2533                 page = read_mapping_page(mapping, idx, NULL);
2534                 if (IS_ERR(page)) {
2535                         ntfs_error(vol->sb, "Failed to read first partial "
2536                                         "page (error, index 0x%lx).", idx);
2537                         return PTR_ERR(page);
2538                 }
2539                 /*
2540                  * If the last page is the same as the first page, need to
2541                  * limit the write to the end offset.
2542                  */
2543                 size = PAGE_SIZE;
2544                 if (idx == end)
2545                         size = end_ofs;
2546                 kaddr = kmap_atomic(page);
2547                 memset(kaddr + start_ofs, val, size - start_ofs);
2548                 flush_dcache_page(page);
2549                 kunmap_atomic(kaddr);
2550                 set_page_dirty(page);
2551                 put_page(page);
2552                 balance_dirty_pages_ratelimited(mapping);
2553                 cond_resched();
2554                 if (idx == end)
2555                         goto done;
2556                 idx++;
2557         }
2558         /* Do the whole pages the fast way. */
2559         for (; idx < end; idx++) {
2560                 /* Find or create the current page.  (The page is locked.) */
2561                 page = grab_cache_page(mapping, idx);
2562                 if (unlikely(!page)) {
2563                         ntfs_error(vol->sb, "Insufficient memory to grab "
2564                                         "page (index 0x%lx).", idx);
2565                         return -ENOMEM;
2566                 }
2567                 kaddr = kmap_atomic(page);
2568                 memset(kaddr, val, PAGE_SIZE);
2569                 flush_dcache_page(page);
2570                 kunmap_atomic(kaddr);
2571                 /*
2572                  * If the page has buffers, mark them uptodate since buffer
2573                  * state and not page state is definitive in 2.6 kernels.
2574                  */
2575                 if (page_has_buffers(page)) {
2576                         struct buffer_head *bh, *head;
2577
2578                         bh = head = page_buffers(page);
2579                         do {
2580                                 set_buffer_uptodate(bh);
2581                         } while ((bh = bh->b_this_page) != head);
2582                 }
2583                 /* Now that buffers are uptodate, set the page uptodate, too. */
2584                 SetPageUptodate(page);
2585                 /*
2586                  * Set the page and all its buffers dirty and mark the inode
2587                  * dirty, too.  The VM will write the page later on.
2588                  */
2589                 set_page_dirty(page);
2590                 /* Finally unlock and release the page. */
2591                 unlock_page(page);
2592                 put_page(page);
2593                 balance_dirty_pages_ratelimited(mapping);
2594                 cond_resched();
2595         }
2596         /* If there is a last partial page, need to do it the slow way. */
2597         if (end_ofs) {
2598                 page = read_mapping_page(mapping, idx, NULL);
2599                 if (IS_ERR(page)) {
2600                         ntfs_error(vol->sb, "Failed to read last partial page "
2601                                         "(error, index 0x%lx).", idx);
2602                         return PTR_ERR(page);
2603                 }
2604                 kaddr = kmap_atomic(page);
2605                 memset(kaddr, val, end_ofs);
2606                 flush_dcache_page(page);
2607                 kunmap_atomic(kaddr);
2608                 set_page_dirty(page);
2609                 put_page(page);
2610                 balance_dirty_pages_ratelimited(mapping);
2611                 cond_resched();
2612         }
2613 done:
2614         ntfs_debug("Done.");
2615         return 0;
2616 }
2617
2618 #endif /* NTFS_RW */