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