xref: /linux/fs/ntfs/attrib.c (revision fcf5bf0e8570798970e3ae8c95d04765ba2c5b97)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * NTFS attribute operations.
4  *
5  * Copyright (c) 2001-2012 Anton Altaparmakov and Tuxera Inc.
6  * Copyright (c) 2002 Richard Russon
7  * Copyright (c) 2025 LG Electronics Co., Ltd.
8  *
9  * Part of this file is based on code from the NTFS-3G.
10  * and is copyrighted by the respective authors below:
11  * Copyright (c) 2000-2010 Anton Altaparmakov
12  * Copyright (c) 2002-2005 Richard Russon
13  * Copyright (c) 2002-2008 Szabolcs Szakacsits
14  * Copyright (c) 2004-2007 Yura Pakhuchiy
15  * Copyright (c) 2007-2021 Jean-Pierre Andre
16  * Copyright (c) 2010 Erik Larsson
17  */
18 
19 #include <linux/string_choices.h>
20 #include <linux/writeback.h>
21 #include <linux/iomap.h>
22 
23 #include "attrib.h"
24 #include "attrlist.h"
25 #include "lcnalloc.h"
26 #include "debug.h"
27 #include "mft.h"
28 #include "ntfs.h"
29 #include "iomap.h"
30 
31 __le16 AT_UNNAMED[] = { cpu_to_le16('\0') };
32 
33 /*
34  * Maximum size allowed for reading attributes by ntfs_attr_readall().
35  * Extended attribute, reparse point are not expected to be larger than this size.
36  */
37 
38 #define NTFS_ATTR_READALL_MAX_SIZE	(64 * 1024)
39 
40 /*
41  * ntfs_map_runlist_nolock - map (a part of) a runlist of an ntfs inode
42  * @ni:		ntfs inode for which to map (part of) a runlist
43  * @vcn:	map runlist part containing this vcn
44  * @ctx:	active attribute search context if present or NULL if not
45  *
46  * Map the part of a runlist containing the @vcn of the ntfs inode @ni.
47  *
48  * If @ctx is specified, it is an active search context of @ni and its base mft
49  * record.  This is needed when ntfs_map_runlist_nolock() encounters unmapped
50  * runlist fragments and allows their mapping.  If you do not have the mft
51  * record mapped, you can specify @ctx as NULL and ntfs_map_runlist_nolock()
52  * will perform the necessary mapping and unmapping.
53  *
54  * Note, ntfs_map_runlist_nolock() saves the state of @ctx on entry and
55  * restores it before returning.  Thus, @ctx will be left pointing to the same
56  * attribute on return as on entry.  However, the actual pointers in @ctx may
57  * point to different memory locations on return, so you must remember to reset
58  * any cached pointers from the @ctx, i.e. after the call to
59  * ntfs_map_runlist_nolock(), you will probably want to do:
60  *	m = ctx->mrec;
61  *	a = ctx->attr;
62  * Assuming you cache ctx->attr in a variable @a of type struct attr_record *
63  * and that you cache ctx->mrec in a variable @m of type struct mft_record *.
64  *
65  * Return 0 on success and -errno on error.  There is one special error code
66  * which is not an error as such.  This is -ENOENT.  It means that @vcn is out
67  * of bounds of the runlist.
68  *
69  * Note the runlist can be NULL after this function returns if @vcn is zero and
70  * the attribute has zero allocated size, i.e. there simply is no runlist.
71  *
72  * WARNING: If @ctx is supplied, regardless of whether success or failure is
73  *	    returned, you need to check IS_ERR(@ctx->mrec) and if 'true' the @ctx
74  *	    is no longer valid, i.e. you need to either call
75  *	    ntfs_attr_reinit_search_ctx() or ntfs_attr_put_search_ctx() on it.
76  *	    In that case PTR_ERR(@ctx->mrec) will give you the error code for
77  *	    why the mapping of the old inode failed.
78  *
79  * Locking: - The runlist described by @ni must be locked for writing on entry
80  *	      and is locked on return.  Note the runlist will be modified.
81  *	    - If @ctx is NULL, the base mft record of @ni must not be mapped on
82  *	      entry and it will be left unmapped on return.
83  *	    - If @ctx is not NULL, the base mft record must be mapped on entry
84  *	      and it will be left mapped on return.
85  */
86 int ntfs_map_runlist_nolock(struct ntfs_inode *ni, s64 vcn, struct ntfs_attr_search_ctx *ctx)
87 {
88 	s64 end_vcn;
89 	unsigned long flags;
90 	struct ntfs_inode *base_ni;
91 	struct mft_record *m;
92 	struct attr_record *a;
93 	struct runlist_element *rl;
94 	struct folio *put_this_folio = NULL;
95 	int err = 0;
96 	bool ctx_is_temporary = false, ctx_needs_reset = false;
97 	struct ntfs_attr_search_ctx old_ctx = { NULL, };
98 	size_t new_rl_count;
99 
100 	ntfs_debug("Mapping runlist part containing vcn 0x%llx.",
101 			(unsigned long long)vcn);
102 	if (!NInoAttr(ni))
103 		base_ni = ni;
104 	else
105 		base_ni = ni->ext.base_ntfs_ino;
106 	if (!ctx) {
107 		ctx_is_temporary = ctx_needs_reset = true;
108 		m = map_mft_record(base_ni);
109 		if (IS_ERR(m))
110 			return PTR_ERR(m);
111 		ctx = ntfs_attr_get_search_ctx(base_ni, m);
112 		if (unlikely(!ctx)) {
113 			err = -ENOMEM;
114 			goto err_out;
115 		}
116 	} else {
117 		s64 allocated_size_vcn;
118 
119 		WARN_ON(IS_ERR(ctx->mrec));
120 		a = ctx->attr;
121 		if (!a->non_resident) {
122 			err = -EIO;
123 			goto err_out;
124 		}
125 		end_vcn = le64_to_cpu(a->data.non_resident.highest_vcn);
126 		read_lock_irqsave(&ni->size_lock, flags);
127 		allocated_size_vcn =
128 			ntfs_bytes_to_cluster(ni->vol, ni->allocated_size);
129 		read_unlock_irqrestore(&ni->size_lock, flags);
130 		if (!a->data.non_resident.lowest_vcn && end_vcn <= 0)
131 			end_vcn = allocated_size_vcn - 1;
132 		/*
133 		 * If we already have the attribute extent containing @vcn in
134 		 * @ctx, no need to look it up again.  We slightly cheat in
135 		 * that if vcn exceeds the allocated size, we will refuse to
136 		 * map the runlist below, so there is definitely no need to get
137 		 * the right attribute extent.
138 		 */
139 		if (vcn >= allocated_size_vcn || (a->type == ni->type &&
140 				a->name_length == ni->name_len &&
141 				!memcmp((u8 *)a + le16_to_cpu(a->name_offset),
142 				ni->name, ni->name_len) &&
143 				le64_to_cpu(a->data.non_resident.lowest_vcn)
144 				<= vcn && end_vcn >= vcn))
145 			ctx_needs_reset = false;
146 		else {
147 			/* Save the old search context. */
148 			old_ctx = *ctx;
149 			/*
150 			 * If the currently mapped (extent) inode is not the
151 			 * base inode we will unmap it when we reinitialize the
152 			 * search context which means we need to get a
153 			 * reference to the page containing the mapped mft
154 			 * record so we do not accidentally drop changes to the
155 			 * mft record when it has not been marked dirty yet.
156 			 */
157 			if (old_ctx.base_ntfs_ino && old_ctx.ntfs_ino !=
158 					old_ctx.base_ntfs_ino) {
159 				put_this_folio = old_ctx.ntfs_ino->folio;
160 				folio_get(put_this_folio);
161 			}
162 			/*
163 			 * Reinitialize the search context so we can lookup the
164 			 * needed attribute extent.
165 			 */
166 			ntfs_attr_reinit_search_ctx(ctx);
167 			ctx_needs_reset = true;
168 		}
169 	}
170 	if (ctx_needs_reset) {
171 		err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
172 				CASE_SENSITIVE, vcn, NULL, 0, ctx);
173 		if (unlikely(err)) {
174 			if (err == -ENOENT)
175 				err = -EIO;
176 			goto err_out;
177 		}
178 		WARN_ON(!ctx->attr->non_resident);
179 	}
180 	a = ctx->attr;
181 	/*
182 	 * Only decompress the mapping pairs if @vcn is inside it.  Otherwise
183 	 * we get into problems when we try to map an out of bounds vcn because
184 	 * we then try to map the already mapped runlist fragment and
185 	 * ntfs_mapping_pairs_decompress() fails.
186 	 */
187 	end_vcn = le64_to_cpu(a->data.non_resident.highest_vcn) + 1;
188 	if (unlikely(vcn && vcn >= end_vcn)) {
189 		err = -ENOENT;
190 		goto err_out;
191 	}
192 	rl = ntfs_mapping_pairs_decompress(ni->vol, a, &ni->runlist, &new_rl_count);
193 	if (IS_ERR(rl))
194 		err = PTR_ERR(rl);
195 	else {
196 		ni->runlist.rl = rl;
197 		ni->runlist.count = new_rl_count;
198 	}
199 err_out:
200 	if (ctx_is_temporary) {
201 		if (likely(ctx))
202 			ntfs_attr_put_search_ctx(ctx);
203 		unmap_mft_record(base_ni);
204 	} else if (ctx_needs_reset) {
205 		/*
206 		 * If there is no attribute list, restoring the search context
207 		 * is accomplished simply by copying the saved context back over
208 		 * the caller supplied context.  If there is an attribute list,
209 		 * things are more complicated as we need to deal with mapping
210 		 * of mft records and resulting potential changes in pointers.
211 		 */
212 		if (NInoAttrList(base_ni)) {
213 			/*
214 			 * If the currently mapped (extent) inode is not the
215 			 * one we had before, we need to unmap it and map the
216 			 * old one.
217 			 */
218 			if (ctx->ntfs_ino != old_ctx.ntfs_ino) {
219 				/*
220 				 * If the currently mapped inode is not the
221 				 * base inode, unmap it.
222 				 */
223 				if (ctx->base_ntfs_ino && ctx->ntfs_ino !=
224 						ctx->base_ntfs_ino) {
225 					unmap_extent_mft_record(ctx->ntfs_ino);
226 					ctx->mrec = ctx->base_mrec;
227 					WARN_ON(!ctx->mrec);
228 				}
229 				/*
230 				 * If the old mapped inode is not the base
231 				 * inode, map it.
232 				 */
233 				if (old_ctx.base_ntfs_ino &&
234 				    old_ctx.ntfs_ino !=	old_ctx.base_ntfs_ino) {
235 retry_map:
236 					ctx->mrec = map_mft_record(old_ctx.ntfs_ino);
237 					/*
238 					 * Something bad has happened.  If out
239 					 * of memory retry till it succeeds.
240 					 * Any other errors are fatal and we
241 					 * return the error code in ctx->mrec.
242 					 * Let the caller deal with it...  We
243 					 * just need to fudge things so the
244 					 * caller can reinit and/or put the
245 					 * search context safely.
246 					 */
247 					if (IS_ERR(ctx->mrec)) {
248 						if (PTR_ERR(ctx->mrec) == -ENOMEM) {
249 							schedule();
250 							goto retry_map;
251 						} else
252 							old_ctx.ntfs_ino =
253 								old_ctx.base_ntfs_ino;
254 					}
255 				}
256 			}
257 			/* Update the changed pointers in the saved context. */
258 			if (ctx->mrec != old_ctx.mrec) {
259 				if (!IS_ERR(ctx->mrec))
260 					old_ctx.attr = (struct attr_record *)(
261 							(u8 *)ctx->mrec +
262 							((u8 *)old_ctx.attr -
263 							(u8 *)old_ctx.mrec));
264 				old_ctx.mrec = ctx->mrec;
265 			}
266 		}
267 		/* Restore the search context to the saved one. */
268 		*ctx = old_ctx;
269 		/*
270 		 * We drop the reference on the page we took earlier.  In the
271 		 * case that IS_ERR(ctx->mrec) is true this means we might lose
272 		 * some changes to the mft record that had been made between
273 		 * the last time it was marked dirty/written out and now.  This
274 		 * at this stage is not a problem as the mapping error is fatal
275 		 * enough that the mft record cannot be written out anyway and
276 		 * the caller is very likely to shutdown the whole inode
277 		 * immediately and mark the volume dirty for chkdsk to pick up
278 		 * the pieces anyway.
279 		 */
280 		if (put_this_folio)
281 			folio_put(put_this_folio);
282 	}
283 	return err;
284 }
285 
286 /*
287  * ntfs_map_runlist - map (a part of) a runlist of an ntfs inode
288  * @ni:		ntfs inode for which to map (part of) a runlist
289  * @vcn:	map runlist part containing this vcn
290  *
291  * Map the part of a runlist containing the @vcn of the ntfs inode @ni.
292  *
293  * Return 0 on success and -errno on error.  There is one special error code
294  * which is not an error as such.  This is -ENOENT.  It means that @vcn is out
295  * of bounds of the runlist.
296  *
297  * Locking: - The runlist must be unlocked on entry and is unlocked on return.
298  *	    - This function takes the runlist lock for writing and may modify
299  *	      the runlist.
300  */
301 int ntfs_map_runlist(struct ntfs_inode *ni, s64 vcn)
302 {
303 	int err = 0;
304 
305 	down_write(&ni->runlist.lock);
306 	/* Make sure someone else didn't do the work while we were sleeping. */
307 	if (likely(ntfs_rl_vcn_to_lcn(ni->runlist.rl, vcn) <=
308 			LCN_RL_NOT_MAPPED))
309 		err = ntfs_map_runlist_nolock(ni, vcn, NULL);
310 	up_write(&ni->runlist.lock);
311 	return err;
312 }
313 
314 struct runlist_element *ntfs_attr_vcn_to_rl(struct ntfs_inode *ni, s64 vcn, s64 *lcn)
315 {
316 	struct runlist_element *rl = ni->runlist.rl;
317 	int err;
318 	bool is_retry = false;
319 
320 	if (!rl) {
321 		err = ntfs_attr_map_whole_runlist(ni);
322 		if (err)
323 			return ERR_PTR(-ENOENT);
324 		rl = ni->runlist.rl;
325 	}
326 
327 remap_rl:
328 	/* Seek to element containing target vcn. */
329 	while (rl->length && rl[1].vcn <= vcn)
330 		rl++;
331 	*lcn = ntfs_rl_vcn_to_lcn(rl, vcn);
332 
333 	if (*lcn <= LCN_RL_NOT_MAPPED && is_retry == false) {
334 		is_retry = true;
335 		if (!ntfs_map_runlist_nolock(ni, vcn, NULL)) {
336 			rl = ni->runlist.rl;
337 			goto remap_rl;
338 		}
339 	}
340 
341 	return rl;
342 }
343 
344 /*
345  * ntfs_attr_vcn_to_lcn_nolock - convert a vcn into a lcn given an ntfs inode
346  * @ni:			ntfs inode of the attribute whose runlist to search
347  * @vcn:		vcn to convert
348  * @write_locked:	true if the runlist is locked for writing
349  *
350  * Find the virtual cluster number @vcn in the runlist of the ntfs attribute
351  * described by the ntfs inode @ni and return the corresponding logical cluster
352  * number (lcn).
353  *
354  * If the @vcn is not mapped yet, the attempt is made to map the attribute
355  * extent containing the @vcn and the vcn to lcn conversion is retried.
356  *
357  * If @write_locked is true the caller has locked the runlist for writing and
358  * if false for reading.
359  *
360  * Since lcns must be >= 0, we use negative return codes with special meaning:
361  *
362  * Return code	Meaning / Description
363  * ==========================================
364  *  LCN_HOLE	Hole / not allocated on disk.
365  *  LCN_ENOENT	There is no such vcn in the runlist, i.e. @vcn is out of bounds.
366  *  LCN_ENOMEM	Not enough memory to map runlist.
367  *  LCN_EIO	Critical error (runlist/file is corrupt, i/o error, etc).
368  *
369  * Locking: - The runlist must be locked on entry and is left locked on return.
370  *	    - If @write_locked is 'false', i.e. the runlist is locked for reading,
371  *	      the lock may be dropped inside the function so you cannot rely on
372  *	      the runlist still being the same when this function returns.
373  */
374 s64 ntfs_attr_vcn_to_lcn_nolock(struct ntfs_inode *ni, const s64 vcn,
375 		const bool write_locked)
376 {
377 	s64 lcn;
378 	unsigned long flags;
379 	bool is_retry = false;
380 
381 	ntfs_debug("Entering for i_ino 0x%llx, vcn 0x%llx, %s_locked.",
382 			ni->mft_no, (unsigned long long)vcn,
383 			write_locked ? "write" : "read");
384 	if (!ni->runlist.rl) {
385 		read_lock_irqsave(&ni->size_lock, flags);
386 		if (!ni->allocated_size) {
387 			read_unlock_irqrestore(&ni->size_lock, flags);
388 			return LCN_ENOENT;
389 		}
390 		read_unlock_irqrestore(&ni->size_lock, flags);
391 	}
392 retry_remap:
393 	/* Convert vcn to lcn.  If that fails map the runlist and retry once. */
394 	lcn = ntfs_rl_vcn_to_lcn(ni->runlist.rl, vcn);
395 	if (likely(lcn >= LCN_HOLE)) {
396 		ntfs_debug("Done, lcn 0x%llx.", (long long)lcn);
397 		return lcn;
398 	}
399 	if (lcn != LCN_RL_NOT_MAPPED) {
400 		if (lcn != LCN_ENOENT)
401 			lcn = LCN_EIO;
402 	} else if (!is_retry) {
403 		int err;
404 
405 		if (!write_locked) {
406 			up_read(&ni->runlist.lock);
407 			down_write(&ni->runlist.lock);
408 			if (unlikely(ntfs_rl_vcn_to_lcn(ni->runlist.rl, vcn) !=
409 					LCN_RL_NOT_MAPPED)) {
410 				up_write(&ni->runlist.lock);
411 				down_read(&ni->runlist.lock);
412 				goto retry_remap;
413 			}
414 		}
415 		err = ntfs_map_runlist_nolock(ni, vcn, NULL);
416 		if (!write_locked) {
417 			up_write(&ni->runlist.lock);
418 			down_read(&ni->runlist.lock);
419 		}
420 		if (likely(!err)) {
421 			is_retry = true;
422 			goto retry_remap;
423 		}
424 		if (err == -ENOENT)
425 			lcn = LCN_ENOENT;
426 		else if (err == -ENOMEM)
427 			lcn = LCN_ENOMEM;
428 		else
429 			lcn = LCN_EIO;
430 	}
431 	if (lcn != LCN_ENOENT)
432 		ntfs_error(ni->vol->sb, "Failed with error code %lli.",
433 				(long long)lcn);
434 	return lcn;
435 }
436 
437 struct runlist_element *__ntfs_attr_find_vcn_nolock(struct runlist *runlist, const s64 vcn)
438 {
439 	size_t lower_idx, upper_idx, idx;
440 	struct runlist_element *run;
441 	int rh = runlist->rl_hint;
442 
443 	if (runlist->count <= 1)
444 		return ERR_PTR(-ENOENT);
445 
446 	if (runlist->count - 1 > rh && runlist->rl[rh].vcn <= vcn) {
447 		if (vcn < runlist->rl[rh].vcn + runlist->rl[rh].length)
448 			return &runlist->rl[rh];
449 		if (runlist->count - 2 == rh)
450 			return ERR_PTR(-ENOENT);
451 
452 		lower_idx = rh + 1;
453 	} else {
454 		run = &runlist->rl[0];
455 		if (vcn < run->vcn)
456 			return ERR_PTR(-ENOENT);
457 		else if (vcn < run->vcn + run->length) {
458 			runlist->rl_hint = 0;
459 			return run;
460 		}
461 
462 		lower_idx = 1;
463 	}
464 
465 	run = &runlist->rl[runlist->count - 2];
466 	if (vcn >= run->vcn && vcn < run->vcn + run->length) {
467 		runlist->rl_hint = runlist->count - 2;
468 		return run;
469 	}
470 	if (vcn >= run->vcn + run->length)
471 		return ERR_PTR(-ENOENT);
472 
473 	upper_idx = runlist->count - 2;
474 
475 	while (lower_idx <= upper_idx) {
476 		idx = (lower_idx + upper_idx) >> 1;
477 		run = &runlist->rl[idx];
478 
479 		if (vcn < run->vcn)
480 			upper_idx = idx - 1;
481 		else if (vcn >= run->vcn + run->length)
482 			lower_idx = idx + 1;
483 		else {
484 			runlist->rl_hint = idx;
485 			return run;
486 		}
487 	}
488 
489 	return ERR_PTR(-ENOENT);
490 }
491 
492 /*
493  * ntfs_attr_find_vcn_nolock - find a vcn in the runlist of an ntfs inode
494  * @ni:		ntfs inode describing the runlist to search
495  * @vcn:	vcn to find
496  * @ctx:	active attribute search context if present or NULL if not
497  *
498  * Find the virtual cluster number @vcn in the runlist described by the ntfs
499  * inode @ni and return the address of the runlist element containing the @vcn.
500  *
501  * If the @vcn is not mapped yet, the attempt is made to map the attribute
502  * extent containing the @vcn and the vcn to lcn conversion is retried.
503  *
504  * If @ctx is specified, it is an active search context of @ni and its base mft
505  * record.  This is needed when ntfs_attr_find_vcn_nolock() encounters unmapped
506  * runlist fragments and allows their mapping.  If you do not have the mft
507  * record mapped, you can specify @ctx as NULL and ntfs_attr_find_vcn_nolock()
508  * will perform the necessary mapping and unmapping.
509  *
510  * Note, ntfs_attr_find_vcn_nolock() saves the state of @ctx on entry and
511  * restores it before returning.  Thus, @ctx will be left pointing to the same
512  * attribute on return as on entry.  However, the actual pointers in @ctx may
513  * point to different memory locations on return, so you must remember to reset
514  * any cached pointers from the @ctx, i.e. after the call to
515  * ntfs_attr_find_vcn_nolock(), you will probably want to do:
516  *	m = ctx->mrec;
517  *	a = ctx->attr;
518  * Assuming you cache ctx->attr in a variable @a of type attr_record * and that
519  * you cache ctx->mrec in a variable @m of type struct mft_record *.
520  * Note you need to distinguish between the lcn of the returned runlist element
521  * being >= 0 and LCN_HOLE.  In the later case you have to return zeroes on
522  * read and allocate clusters on write.
523  */
524 struct runlist_element *ntfs_attr_find_vcn_nolock(struct ntfs_inode *ni, const s64 vcn,
525 		struct ntfs_attr_search_ctx *ctx)
526 {
527 	unsigned long flags;
528 	struct runlist_element *rl;
529 	int err = 0;
530 	bool is_retry = false;
531 
532 	ntfs_debug("Entering for i_ino 0x%llx, vcn 0x%llx, with%s ctx.",
533 			ni->mft_no, (unsigned long long)vcn, ctx ? "" : "out");
534 	if (!ni->runlist.rl) {
535 		read_lock_irqsave(&ni->size_lock, flags);
536 		if (!ni->allocated_size) {
537 			read_unlock_irqrestore(&ni->size_lock, flags);
538 			return ERR_PTR(-ENOENT);
539 		}
540 		read_unlock_irqrestore(&ni->size_lock, flags);
541 	}
542 
543 retry_remap:
544 	rl = ni->runlist.rl;
545 	if (likely(rl && vcn >= rl[0].vcn)) {
546 		rl = __ntfs_attr_find_vcn_nolock(&ni->runlist, vcn);
547 		if (IS_ERR(rl))
548 			err = PTR_ERR(rl);
549 		else if (rl->lcn >= LCN_HOLE)
550 			return rl;
551 		else if (rl->lcn <= LCN_ENOENT)
552 			err = -EIO;
553 	}
554 	if (!err && !is_retry) {
555 		/*
556 		 * If the search context is invalid we cannot map the unmapped
557 		 * region.
558 		 */
559 		if (ctx && IS_ERR(ctx->mrec))
560 			err = PTR_ERR(ctx->mrec);
561 		else {
562 			/*
563 			 * The @vcn is in an unmapped region, map the runlist
564 			 * and retry.
565 			 */
566 			err = ntfs_map_runlist_nolock(ni, vcn, ctx);
567 			if (likely(!err)) {
568 				is_retry = true;
569 				goto retry_remap;
570 			}
571 		}
572 		if (err == -EINVAL)
573 			err = -EIO;
574 	} else if (!err)
575 		err = -EIO;
576 	if (err != -ENOENT)
577 		ntfs_error(ni->vol->sb, "Failed with error code %i.", err);
578 	return ERR_PTR(err);
579 }
580 
581 static u32 ntfs_resident_attr_min_value_length(const __le32 type)
582 {
583 	switch (type) {
584 	case AT_STANDARD_INFORMATION:
585 		return offsetof(struct standard_information, ver) +
586 		       sizeof(((struct standard_information *)0)->ver.v1.reserved12);
587 	case AT_FILE_NAME:
588 		return offsetof(struct file_name_attr, file_name) +
589 			sizeof(__le16) * 1;
590 	case AT_VOLUME_INFORMATION:
591 		return sizeof(struct volume_information);
592 	case AT_INDEX_ROOT:
593 		return sizeof(struct index_root);
594 	case AT_EA_INFORMATION:
595 		return sizeof(struct ea_information);
596 	default:
597 		return 0;
598 	}
599 }
600 
601 static bool ntfs_attr_type_is_resident_only(const __le32 type)
602 {
603 	switch (type) {
604 	case AT_STANDARD_INFORMATION:
605 	case AT_FILE_NAME:
606 	case AT_OBJECT_ID:
607 	case AT_VOLUME_NAME:
608 	case AT_VOLUME_INFORMATION:
609 	case AT_INDEX_ROOT:
610 	case AT_EA_INFORMATION:
611 		return true;
612 	default:
613 		return false;
614 	}
615 }
616 
617 static bool ntfs_file_name_attr_value_is_valid(const u8 *value, const u32 value_length)
618 {
619 	const struct file_name_attr *fn;
620 	u32 file_name_size;
621 
622 	fn = (const struct file_name_attr *)value;
623 	file_name_size = fn->file_name_length * sizeof(__le16);
624 
625 	return file_name_size <=
626 			value_length - offsetof(struct file_name_attr, file_name);
627 }
628 
629 static bool ntfs_volume_name_attr_value_is_valid(const u32 value_length)
630 {
631 	if (value_length & 1)
632 		return false;
633 
634 	return value_length <= NTFS_MAX_LABEL_LEN * sizeof(__le16);
635 }
636 
637 static bool ntfs_index_root_attr_value_is_valid(const u8 *value, const u32 value_length)
638 {
639 	const struct index_root *ir;
640 	u32 index_size;
641 	u32 entries_offset;
642 	u32 index_length;
643 	u32 allocated_size;
644 
645 	ir = (const struct index_root *)value;
646 	index_size = value_length - offsetof(struct index_root, index);
647 	entries_offset = le32_to_cpu(ir->index.entries_offset);
648 	index_length = le32_to_cpu(ir->index.index_length);
649 	allocated_size = le32_to_cpu(ir->index.allocated_size);
650 
651 	if ((entries_offset | index_length | allocated_size) & 7 ||
652 	    entries_offset < sizeof(struct index_header) ||
653 	    entries_offset > index_length ||
654 	    index_length > allocated_size ||
655 	    allocated_size > index_size ||
656 	    index_length - entries_offset < sizeof(struct index_entry_header))
657 		return false;
658 
659 	return true;
660 }
661 
662 struct ntfs_resident_attr_value {
663 	const u8 *data;
664 	u32 len;
665 };
666 
667 static bool ntfs_resident_attr_value_get(const struct attr_record *a,
668 					 struct ntfs_resident_attr_value *value)
669 {
670 	u32 attr_len;
671 	u16 value_offset;
672 
673 	attr_len = le32_to_cpu(a->length);
674 	if (attr_len < offsetof(struct attr_record, data.resident.reserved) +
675 			sizeof(a->data.resident.reserved))
676 		return false;
677 
678 	value->len = le32_to_cpu(a->data.resident.value_length);
679 	value_offset = le16_to_cpu(a->data.resident.value_offset);
680 
681 	if (value->len > attr_len || value_offset > attr_len - value->len)
682 		return false;
683 
684 	value->data = (const u8 *)a + value_offset;
685 	return true;
686 }
687 
688 static bool ntfs_non_resident_attr_value_is_valid(const struct attr_record *a)
689 {
690 	u32 attr_len;
691 	u32 min_len;
692 	u16 mp_offset;
693 
694 	attr_len = le32_to_cpu(a->length);
695 	min_len = offsetof(struct attr_record, data.non_resident.initialized_size) +
696 		  sizeof(a->data.non_resident.initialized_size);
697 	if (attr_len < min_len)
698 		return false;
699 
700 	mp_offset = le16_to_cpu(a->data.non_resident.mapping_pairs_offset);
701 	return mp_offset >= min_len && mp_offset <= attr_len;
702 }
703 
704 static bool ntfs_attr_value_is_valid(struct ntfs_volume *vol,
705 				     const struct attr_record *a,
706 				     const u64 mft_no)
707 {
708 	struct ntfs_resident_attr_value value;
709 	u32 min_len;
710 
711 	if (a->non_resident) {
712 		if (ntfs_attr_type_is_resident_only(a->type))
713 			goto corrupt;
714 		if (!ntfs_non_resident_attr_value_is_valid(a))
715 			goto corrupt;
716 		return true;
717 	}
718 
719 	if (!ntfs_resident_attr_value_get(a, &value))
720 		goto corrupt;
721 
722 	min_len = ntfs_resident_attr_min_value_length(a->type);
723 	if (min_len && value.len < min_len)
724 		goto corrupt;
725 
726 	switch (a->type) {
727 	case AT_FILE_NAME:
728 		if (!ntfs_file_name_attr_value_is_valid(value.data, value.len))
729 			goto corrupt;
730 		break;
731 	case AT_VOLUME_NAME:
732 		if (!ntfs_volume_name_attr_value_is_valid(value.len))
733 			goto corrupt;
734 		break;
735 	case AT_INDEX_ROOT:
736 		if (!ntfs_index_root_attr_value_is_valid(value.data, value.len))
737 			goto corrupt;
738 		break;
739 	}
740 	return true;
741 
742 corrupt:
743 	ntfs_error(vol->sb,
744 		   "Corrupt %#x attribute in MFT record %llu\n",
745 		   le32_to_cpu(a->type), mft_no);
746 	return false;
747 }
748 
749 /*
750  * ntfs_attr_find - find (next) attribute in mft record
751  * @type:	attribute type to find
752  * @name:	attribute name to find (optional, i.e. NULL means don't care)
753  * @name_len:	attribute name length (only needed if @name present)
754  * @ic:		IGNORE_CASE or CASE_SENSITIVE (ignored if @name not present)
755  * @val:	attribute value to find (optional, resident attributes only)
756  * @val_len:	attribute value length
757  * @ctx:	search context with mft record and attribute to search from
758  *
759  * You should not need to call this function directly.  Use ntfs_attr_lookup()
760  * instead.
761  *
762  * ntfs_attr_find() takes a search context @ctx as parameter and searches the
763  * mft record specified by @ctx->mrec, beginning at @ctx->attr, for an
764  * attribute of @type, optionally @name and @val.
765  *
766  * If the attribute is found, ntfs_attr_find() returns 0 and @ctx->attr will
767  * point to the found attribute.
768  *
769  * If the attribute is not found, ntfs_attr_find() returns -ENOENT and
770  * @ctx->attr will point to the attribute before which the attribute being
771  * searched for would need to be inserted if such an action were to be desired.
772  *
773  * On actual error, ntfs_attr_find() returns -EIO.  In this case @ctx->attr is
774  * undefined and in particular do not rely on it not changing.
775  *
776  * If @ctx->is_first is 'true', the search begins with @ctx->attr itself.  If it
777  * is 'false', the search begins after @ctx->attr.
778  *
779  * If @ic is IGNORE_CASE, the @name comparisson is not case sensitive and
780  * @ctx->ntfs_ino must be set to the ntfs inode to which the mft record
781  * @ctx->mrec belongs.  This is so we can get at the ntfs volume and hence at
782  * the upcase table.  If @ic is CASE_SENSITIVE, the comparison is case
783  * sensitive.  When @name is present, @name_len is the @name length in Unicode
784  * characters.
785  *
786  * If @name is not present (NULL), we assume that the unnamed attribute is
787  * being searched for.
788  *
789  * Finally, the resident attribute value @val is looked for, if present.  If
790  * @val is not present (NULL), @val_len is ignored.
791  *
792  * ntfs_attr_find() only searches the specified mft record and it ignores the
793  * presence of an attribute list attribute (unless it is the one being searched
794  * for, obviously).  If you need to take attribute lists into consideration,
795  * use ntfs_attr_lookup() instead (see below).  This also means that you cannot
796  * use ntfs_attr_find() to search for extent records of non-resident
797  * attributes, as extents with lowest_vcn != 0 are usually described by the
798  * attribute list attribute only. - Note that it is possible that the first
799  * extent is only in the attribute list while the last extent is in the base
800  * mft record, so do not rely on being able to find the first extent in the
801  * base mft record.
802  *
803  * Warning: Never use @val when looking for attribute types which can be
804  *	    non-resident as this most likely will result in a crash!
805  */
806 static int ntfs_attr_find(const __le32 type, const __le16 *name,
807 		const u32 name_len, const u32 ic,
808 		const u8 *val, const u32 val_len, struct ntfs_attr_search_ctx *ctx)
809 {
810 	struct attr_record *a;
811 	struct ntfs_volume *vol = ctx->ntfs_ino->vol;
812 	__le16 *upcase = vol->upcase;
813 	u32 upcase_len = vol->upcase_len;
814 	unsigned int space;
815 	u16 name_offset;
816 	u32 attr_len;
817 	u32 name_size;
818 
819 	/*
820 	 * Iterate over attributes in mft record starting at @ctx->attr, or the
821 	 * attribute following that, if @ctx->is_first is 'true'.
822 	 */
823 	if (ctx->is_first) {
824 		a = ctx->attr;
825 		ctx->is_first = false;
826 	} else
827 		a = (struct attr_record *)((u8 *)ctx->attr +
828 				le32_to_cpu(ctx->attr->length));
829 	for (;;	a = (struct attr_record *)((u8 *)a + le32_to_cpu(a->length))) {
830 		if ((u8 *)a < (u8 *)ctx->mrec || (u8 *)a > (u8 *)ctx->mrec +
831 				le32_to_cpu(ctx->mrec->bytes_allocated))
832 			break;
833 
834 		space = le32_to_cpu(ctx->mrec->bytes_in_use) - ((u8 *)a - (u8 *)ctx->mrec);
835 		if ((space < offsetof(struct attr_record, data.resident.reserved) + 1 ||
836 		      space < le32_to_cpu(a->length)) && (space < 4 || a->type != AT_END))
837 			break;
838 
839 		ctx->attr = a;
840 		if (((type != AT_UNUSED) && (le32_to_cpu(a->type) > le32_to_cpu(type))) ||
841 				a->type == AT_END)
842 			return -ENOENT;
843 		if (unlikely(!a->length))
844 			break;
845 		if (a->name_length) {
846 			name_offset = le16_to_cpu(a->name_offset);
847 			attr_len = le32_to_cpu(a->length);
848 			name_size = a->name_length * sizeof(__le16);
849 
850 			if (name_offset > attr_len ||
851 			    attr_len - name_offset < name_size) {
852 				ntfs_error(vol->sb,
853 					   "Corrupt attribute name in MFT record %llu\n",
854 					   ctx->ntfs_ino->mft_no);
855 				break;
856 			}
857 		}
858 
859 		if (type == AT_UNUSED) {
860 			if (!ntfs_attr_value_is_valid(vol, a, ctx->ntfs_ino->mft_no))
861 				break;
862 			return 0;
863 		}
864 		if (a->type != type)
865 			continue;
866 		/*
867 		 * If @name is present, compare the two names.  If @name is
868 		 * missing, assume we want an unnamed attribute.
869 		 */
870 		if (!name || name == AT_UNNAMED) {
871 			/* The search failed if the found attribute is named. */
872 			if (a->name_length)
873 				return -ENOENT;
874 		} else {
875 			if (!ntfs_are_names_equal(name, name_len,
876 					(__le16 *)((u8 *)a + le16_to_cpu(a->name_offset)),
877 					a->name_length, ic, upcase, upcase_len)) {
878 				register int rc;
879 
880 				rc = ntfs_collate_names(name, name_len,
881 						(__le16 *)((u8 *)a + le16_to_cpu(a->name_offset)),
882 						a->name_length, 1, IGNORE_CASE,
883 						upcase, upcase_len);
884 				/*
885 				 * If @name collates before a->name, there is no
886 				 * matching attribute.
887 				 */
888 				if (rc == -1)
889 					return -ENOENT;
890 				/* If the strings are not equal, continue search. */
891 				if (rc)
892 					continue;
893 				rc = ntfs_collate_names(name, name_len,
894 						(__le16 *)((u8 *)a + le16_to_cpu(a->name_offset)),
895 						a->name_length, 1, CASE_SENSITIVE,
896 						upcase, upcase_len);
897 				if (rc == -1)
898 					return -ENOENT;
899 				if (rc)
900 					continue;
901 			}
902 		}
903 
904 		if (!ntfs_attr_value_is_valid(vol, a, ctx->ntfs_ino->mft_no))
905 			break;
906 
907 		/*
908 		 * The names match or @name not present and attribute is
909 		 * unnamed.  If no @val specified, we have found the attribute
910 		 * and are done.
911 		 */
912 		if (!val || a->non_resident)
913 			return 0;
914 		/* @val is present; compare values. */
915 		else {
916 			u32 value_length = le32_to_cpu(a->data.resident.value_length);
917 			int rc;
918 
919 			rc = memcmp(val, (u8 *)a + le16_to_cpu(
920 					a->data.resident.value_offset),
921 					min_t(u32, val_len, value_length));
922 			/*
923 			 * If @val collates before the current attribute's
924 			 * value, there is no matching attribute.
925 			 */
926 			if (!rc) {
927 				if (val_len == value_length)
928 					return 0;
929 				if (val_len < value_length)
930 					return -ENOENT;
931 			} else if (rc < 0)
932 				return -ENOENT;
933 		}
934 	}
935 	ntfs_error(vol->sb, "mft %#llx, type %#x is corrupt. Run chkdsk.",
936 		   (long long)ctx->ntfs_ino->mft_no, le32_to_cpu(type));
937 	NVolSetErrors(vol);
938 	return -EIO;
939 }
940 
941 void ntfs_attr_name_free(unsigned char **name)
942 {
943 	if (*name) {
944 		kfree(*name);
945 		*name = NULL;
946 	}
947 }
948 
949 char *ntfs_attr_name_get(const struct ntfs_volume *vol, const __le16 *uname,
950 		const int uname_len)
951 {
952 	unsigned char *name = NULL;
953 	int name_len;
954 
955 	name_len = ntfs_ucstonls(vol, uname, uname_len, &name, 0);
956 	if (name_len < 0) {
957 		ntfs_error(vol->sb, "ntfs_ucstonls error");
958 		/* This function when returns -1, memory for name might
959 		 * be allocated. So lets free this memory.
960 		 */
961 		ntfs_attr_name_free(&name);
962 		return NULL;
963 
964 	} else if (name_len > 0)
965 		return name;
966 
967 	ntfs_attr_name_free(&name);
968 	return NULL;
969 }
970 
971 /*
972  * ntfs_attr_list_entry_is_valid - sanity check one $ATTRIBUTE_LIST entry
973  * @ale:	the attribute-list entry to check
974  * @al_end:	end of the attribute-list buffer @ale lives in
975  *
976  * Verify that @ale is a well-formed attr_list_entry wholly contained in
977  * [.., @al_end): its fixed header must lie in range before any field is
978  * dereferenced, its length must be a multiple of 8 that covers the fixed
979  * header plus the name, the name must lie within the buffer, the entry must
980  * be in use and carry a live MFT reference.  Return true if valid.
981  */
982 bool ntfs_attr_list_entry_is_valid(const struct attr_list_entry *ale,
983 				   const u8 *al_end)
984 {
985 	const u8 *al = (const u8 *)ale;
986 	u16 ale_len;
987 
988 	/* The fixed header must be in bounds before it is parsed. */
989 	if (al + offsetof(struct attr_list_entry, name) > al_end)
990 		return false;
991 	ale_len = le16_to_cpu(ale->length);
992 	/* On-disk entries are 8-byte aligned (see struct attr_list_entry). */
993 	if (ale_len & 7)
994 		return false;
995 	if (ale->name_offset != sizeof(struct attr_list_entry))
996 		return false;
997 	if ((u32)ale->name_offset +
998 	    (u32)ale->name_length * sizeof(__le16) > ale_len ||
999 	    al + ale_len > al_end)
1000 		return false;
1001 	if (ale->type == AT_UNUSED)
1002 		return false;
1003 	if (MSEQNO_LE(ale->mft_reference) == 0)
1004 		return false;
1005 	return true;
1006 }
1007 
1008 /*
1009  * ntfs_attr_list_is_valid - sanity check an in-memory $ATTRIBUTE_LIST
1010  * @al_start:	start of the attribute list buffer
1011  * @size:	length of the attribute list in bytes
1012  *
1013  * Verify that [@al_start, @al_start + @size) is a sequence of valid
1014  * attr_list_entry records (see ntfs_attr_list_entry_is_valid()) that tile the
1015  * buffer exactly.  Return true if valid, false otherwise.
1016  */
1017 bool ntfs_attr_list_is_valid(const u8 *al_start, s64 size)
1018 {
1019 	const u8 *al = al_start;
1020 	const u8 *al_end = al_start + size;
1021 
1022 	while (al < al_end) {
1023 		const struct attr_list_entry *ale =
1024 				(const struct attr_list_entry *)al;
1025 
1026 		if (!ntfs_attr_list_entry_is_valid(ale, al_end))
1027 			return false;
1028 		al += le16_to_cpu(ale->length);
1029 	}
1030 	return al == al_end;
1031 }
1032 
1033 int load_attribute_list(struct ntfs_inode *base_ni, u8 *al_start, const s64 size)
1034 {
1035 	struct inode *attr_vi = NULL;
1036 
1037 	if (!al_start || size <= 0)
1038 		return -EINVAL;
1039 
1040 	attr_vi = ntfs_attr_iget(VFS_I(base_ni), AT_ATTRIBUTE_LIST, AT_UNNAMED, 0);
1041 	if (IS_ERR(attr_vi)) {
1042 		ntfs_error(base_ni->vol->sb,
1043 			   "Failed to open an inode for Attribute list, mft = %llu",
1044 			   base_ni->mft_no);
1045 		return PTR_ERR(attr_vi);
1046 	}
1047 
1048 	if (ntfs_inode_attr_pread(attr_vi, 0, size, al_start) != size) {
1049 		iput(attr_vi);
1050 		ntfs_error(base_ni->vol->sb,
1051 			   "Failed to read attribute list, mft = %llu",
1052 			   base_ni->mft_no);
1053 		return -EIO;
1054 	}
1055 	iput(attr_vi);
1056 
1057 	if (!ntfs_attr_list_is_valid(al_start, size)) {
1058 		ntfs_error(base_ni->vol->sb, "Corrupt attribute list, mft = %llu",
1059 			   base_ni->mft_no);
1060 		return -EIO;
1061 	}
1062 	return 0;
1063 }
1064 
1065 /*
1066  * ntfs_external_attr_find - find an attribute in the attribute list of an inode
1067  * @type:	attribute type to find
1068  * @name:	attribute name to find (optional, i.e. NULL means don't care)
1069  * @name_len:	attribute name length (only needed if @name present)
1070  * @ic:		IGNORE_CASE or CASE_SENSITIVE (ignored if @name not present)
1071  * @lowest_vcn:	lowest vcn to find (optional, non-resident attributes only)
1072  * @val:	attribute value to find (optional, resident attributes only)
1073  * @val_len:	attribute value length
1074  * @ctx:	search context with mft record and attribute to search from
1075  *
1076  * You should not need to call this function directly.  Use ntfs_attr_lookup()
1077  * instead.
1078  *
1079  * Find an attribute by searching the attribute list for the corresponding
1080  * attribute list entry.  Having found the entry, map the mft record if the
1081  * attribute is in a different mft record/inode, ntfs_attr_find() the attribute
1082  * in there and return it.
1083  *
1084  * On first search @ctx->ntfs_ino must be the base mft record and @ctx must
1085  * have been obtained from a call to ntfs_attr_get_search_ctx().  On subsequent
1086  * calls @ctx->ntfs_ino can be any extent inode, too (@ctx->base_ntfs_ino is
1087  * then the base inode).
1088  *
1089  * After finishing with the attribute/mft record you need to call
1090  * ntfs_attr_put_search_ctx() to cleanup the search context (unmapping any
1091  * mapped inodes, etc).
1092  *
1093  * If the attribute is found, ntfs_external_attr_find() returns 0 and
1094  * @ctx->attr will point to the found attribute.  @ctx->mrec will point to the
1095  * mft record in which @ctx->attr is located and @ctx->al_entry will point to
1096  * the attribute list entry for the attribute.
1097  *
1098  * If the attribute is not found, ntfs_external_attr_find() returns -ENOENT and
1099  * @ctx->attr will point to the attribute in the base mft record before which
1100  * the attribute being searched for would need to be inserted if such an action
1101  * were to be desired.  @ctx->mrec will point to the mft record in which
1102  * @ctx->attr is located and @ctx->al_entry will point to the attribute list
1103  * entry of the attribute before which the attribute being searched for would
1104  * need to be inserted if such an action were to be desired.
1105  *
1106  * Thus to insert the not found attribute, one wants to add the attribute to
1107  * @ctx->mrec (the base mft record) and if there is not enough space, the
1108  * attribute should be placed in a newly allocated extent mft record.  The
1109  * attribute list entry for the inserted attribute should be inserted in the
1110  * attribute list attribute at @ctx->al_entry.
1111  *
1112  * On actual error, ntfs_external_attr_find() returns -EIO.  In this case
1113  * @ctx->attr is undefined and in particular do not rely on it not changing.
1114  */
1115 static int ntfs_external_attr_find(const __le32 type,
1116 		const __le16 *name, const u32 name_len,
1117 		const u32 ic, const s64 lowest_vcn,
1118 		const u8 *val, const u32 val_len, struct ntfs_attr_search_ctx *ctx)
1119 {
1120 	struct ntfs_inode *base_ni = ctx->base_ntfs_ino, *ni = ctx->ntfs_ino;
1121 	struct ntfs_volume *vol;
1122 	struct attr_list_entry *al_entry, *next_al_entry;
1123 	u8 *al_start, *al_end;
1124 	struct attr_record *a;
1125 	__le16 *al_name;
1126 	u32 al_name_len;
1127 	u32 attr_len, mft_free_len;
1128 	bool is_first_search = false;
1129 	int err = 0;
1130 	static const char *es = " Unmount and run chkdsk.";
1131 
1132 	ntfs_debug("Entering for inode 0x%llx, type 0x%x.", ni->mft_no, type);
1133 	if (!base_ni) {
1134 		/* First call happens with the base mft record. */
1135 		base_ni = ctx->base_ntfs_ino = ctx->ntfs_ino;
1136 		ctx->base_mrec = ctx->mrec;
1137 		ctx->mapped_base_mrec = ctx->mapped_mrec;
1138 	}
1139 	if (ni == base_ni)
1140 		ctx->base_attr = ctx->attr;
1141 	if (type == AT_END)
1142 		goto not_found;
1143 	vol = base_ni->vol;
1144 	al_start = base_ni->attr_list;
1145 	al_end = al_start + base_ni->attr_list_size;
1146 	if (!ctx->al_entry) {
1147 		ctx->al_entry = (struct attr_list_entry *)al_start;
1148 		is_first_search = true;
1149 	}
1150 	/*
1151 	 * Iterate over entries in attribute list starting at @ctx->al_entry,
1152 	 * or the entry following that, if @ctx->is_first is 'true'.
1153 	 */
1154 	if (ctx->is_first) {
1155 		al_entry = ctx->al_entry;
1156 		ctx->is_first = false;
1157 		/*
1158 		 * If an enumeration and the first attribute is higher than
1159 		 * the attribute list itself, need to return the attribute list
1160 		 * attribute.
1161 		 */
1162 		if ((type == AT_UNUSED) && is_first_search &&
1163 				le32_to_cpu(al_entry->type) >
1164 				le32_to_cpu(AT_ATTRIBUTE_LIST))
1165 			goto find_attr_list_attr;
1166 	} else {
1167 		/* Check for small entry */
1168 		if (((al_end - (u8 *)ctx->al_entry) <
1169 		      (long)offsetof(struct attr_list_entry, name)) ||
1170 		    (le16_to_cpu(ctx->al_entry->length) & 7) ||
1171 		    (le16_to_cpu(ctx->al_entry->length) < offsetof(struct attr_list_entry, name)))
1172 			goto corrupt;
1173 
1174 		al_entry = (struct attr_list_entry *)((u8 *)ctx->al_entry +
1175 				le16_to_cpu(ctx->al_entry->length));
1176 
1177 		if ((u8 *)al_entry == al_end)
1178 			goto not_found;
1179 
1180 		/* Preliminary check for small entry */
1181 		if ((al_end - (u8 *)al_entry) <
1182 		    (long)offsetof(struct attr_list_entry, name))
1183 			goto corrupt;
1184 
1185 		/*
1186 		 * If this is an enumeration and the attribute list attribute
1187 		 * is the next one in the enumeration sequence, just return the
1188 		 * attribute list attribute from the base mft record as it is
1189 		 * not listed in the attribute list itself.
1190 		 */
1191 		if ((type == AT_UNUSED) && le32_to_cpu(ctx->al_entry->type) <
1192 				le32_to_cpu(AT_ATTRIBUTE_LIST) &&
1193 				le32_to_cpu(al_entry->type) >
1194 				le32_to_cpu(AT_ATTRIBUTE_LIST)) {
1195 find_attr_list_attr:
1196 
1197 			/* Check for bogus calls. */
1198 			if (name || name_len || val || val_len || lowest_vcn)
1199 				return -EINVAL;
1200 
1201 			/* We want the base record. */
1202 			if (ctx->ntfs_ino != base_ni)
1203 				unmap_mft_record(ctx->ntfs_ino);
1204 			ctx->ntfs_ino = base_ni;
1205 			ctx->mapped_mrec = ctx->mapped_base_mrec;
1206 			ctx->mrec = ctx->base_mrec;
1207 			ctx->is_first = true;
1208 
1209 			/* Sanity checks are performed elsewhere. */
1210 			ctx->attr = (struct attr_record *)((u8 *)ctx->mrec +
1211 					le16_to_cpu(ctx->mrec->attrs_offset));
1212 
1213 			/* Find the attribute list attribute. */
1214 			err = ntfs_attr_find(AT_ATTRIBUTE_LIST, NULL, 0,
1215 					IGNORE_CASE, NULL, 0, ctx);
1216 
1217 			/*
1218 			 * Setup the search context so the correct
1219 			 * attribute is returned next time round.
1220 			 */
1221 			ctx->al_entry = al_entry;
1222 			ctx->is_first = true;
1223 
1224 			/* Got it. Done. */
1225 			if (!err)
1226 				return 0;
1227 
1228 			/* Error! If other than not found return it. */
1229 			if (err != -ENOENT)
1230 				return err;
1231 
1232 			/* Not found?!? Absurd! */
1233 			ntfs_error(ctx->ntfs_ino->vol->sb, "Attribute list wasn't found");
1234 			return -EIO;
1235 		}
1236 	}
1237 	for (;; al_entry = next_al_entry) {
1238 		/* Out of bounds check. */
1239 		if ((u8 *)al_entry < base_ni->attr_list ||
1240 				(u8 *)al_entry > al_end)
1241 			break;	/* Inode is corrupt. */
1242 		ctx->al_entry = al_entry;
1243 		/* Catch the end of the attribute list. */
1244 		if ((u8 *)al_entry == al_end)
1245 			goto not_found;
1246 
1247 		if ((((u8 *)al_entry + offsetof(struct attr_list_entry, name)) > al_end) ||
1248 		    ((u8 *)al_entry + le16_to_cpu(al_entry->length) > al_end) ||
1249 		    (le16_to_cpu(al_entry->length) & 7) ||
1250 		    (le16_to_cpu(al_entry->length) <
1251 		     offsetof(struct attr_list_entry, name_length)) ||
1252 		    (al_entry->name_length && ((u8 *)al_entry + al_entry->name_offset +
1253 					       al_entry->name_length * sizeof(__le16)) > al_end))
1254 			break; /* corrupt */
1255 
1256 		next_al_entry = (struct attr_list_entry *)((u8 *)al_entry +
1257 				le16_to_cpu(al_entry->length));
1258 		if (type != AT_UNUSED) {
1259 			if (le32_to_cpu(al_entry->type) > le32_to_cpu(type))
1260 				goto not_found;
1261 			if (type != al_entry->type)
1262 				continue;
1263 		}
1264 		/*
1265 		 * If @name is present, compare the two names.  If @name is
1266 		 * missing, assume we want an unnamed attribute.
1267 		 */
1268 		al_name_len = al_entry->name_length;
1269 		al_name = (__le16 *)((u8 *)al_entry + al_entry->name_offset);
1270 
1271 		/*
1272 		 * If !@type we want the attribute represented by this
1273 		 * attribute list entry.
1274 		 */
1275 		if (type == AT_UNUSED)
1276 			goto is_enumeration;
1277 
1278 		if (!name || name == AT_UNNAMED) {
1279 			if (al_name_len)
1280 				goto not_found;
1281 		} else if (!ntfs_are_names_equal(al_name, al_name_len, name,
1282 				name_len, ic, vol->upcase, vol->upcase_len)) {
1283 			register int rc;
1284 
1285 			rc = ntfs_collate_names(name, name_len, al_name,
1286 					al_name_len, 1, IGNORE_CASE,
1287 					vol->upcase, vol->upcase_len);
1288 			/*
1289 			 * If @name collates before al_name, there is no
1290 			 * matching attribute.
1291 			 */
1292 			if (rc == -1)
1293 				goto not_found;
1294 			/* If the strings are not equal, continue search. */
1295 			if (rc)
1296 				continue;
1297 
1298 			rc = ntfs_collate_names(name, name_len, al_name,
1299 					al_name_len, 1, CASE_SENSITIVE,
1300 					vol->upcase, vol->upcase_len);
1301 			if (rc == -1)
1302 				goto not_found;
1303 			if (rc)
1304 				continue;
1305 		}
1306 		/*
1307 		 * The names match or @name not present and attribute is
1308 		 * unnamed.  Now check @lowest_vcn.  Continue search if the
1309 		 * next attribute list entry still fits @lowest_vcn.  Otherwise
1310 		 * we have reached the right one or the search has failed.
1311 		 */
1312 		if (lowest_vcn && (u8 *)next_al_entry >= al_start &&
1313 				ntfs_attr_list_entry_is_valid(next_al_entry,
1314 							      al_end) &&
1315 				le64_to_cpu(next_al_entry->lowest_vcn) <=
1316 					lowest_vcn &&
1317 				next_al_entry->type == al_entry->type &&
1318 				next_al_entry->name_length == al_name_len &&
1319 				ntfs_are_names_equal((__le16 *)((u8 *)
1320 					next_al_entry +
1321 					next_al_entry->name_offset),
1322 					next_al_entry->name_length,
1323 					al_name, al_name_len, CASE_SENSITIVE,
1324 					vol->upcase, vol->upcase_len))
1325 			continue;
1326 
1327 is_enumeration:
1328 		if (MREF_LE(al_entry->mft_reference) == ni->mft_no) {
1329 			if (MSEQNO_LE(al_entry->mft_reference) != ni->seq_no) {
1330 				ntfs_error(vol->sb,
1331 					"Found stale mft reference in attribute list of base inode 0x%llx.%s",
1332 					base_ni->mft_no, es);
1333 				err = -EIO;
1334 				break;
1335 			}
1336 		} else { /* Mft references do not match. */
1337 			/* If there is a mapped record unmap it first. */
1338 			if (ni != base_ni)
1339 				unmap_extent_mft_record(ni);
1340 			/* Do we want the base record back? */
1341 			if (MREF_LE(al_entry->mft_reference) ==
1342 					base_ni->mft_no) {
1343 				ni = ctx->ntfs_ino = base_ni;
1344 				ctx->mrec = ctx->base_mrec;
1345 				ctx->mapped_mrec = ctx->mapped_base_mrec;
1346 			} else {
1347 				/* We want an extent record. */
1348 				ctx->mrec = map_extent_mft_record(base_ni,
1349 						le64_to_cpu(
1350 						al_entry->mft_reference), &ni);
1351 				if (IS_ERR(ctx->mrec)) {
1352 					ntfs_error(vol->sb,
1353 							"Failed to map extent mft record 0x%lx of base inode 0x%llx.%s",
1354 							MREF_LE(al_entry->mft_reference),
1355 							base_ni->mft_no, es);
1356 					err = PTR_ERR(ctx->mrec);
1357 					if (err == -ENOENT)
1358 						err = -EIO;
1359 					/* Cause @ctx to be sanitized below. */
1360 					ni = NULL;
1361 					break;
1362 				}
1363 				ctx->ntfs_ino = ni;
1364 				ctx->mapped_mrec = true;
1365 
1366 			}
1367 		}
1368 		a = ctx->attr = (struct attr_record *)((u8 *)ctx->mrec +
1369 					le16_to_cpu(ctx->mrec->attrs_offset));
1370 		/*
1371 		 * ctx->vfs_ino, ctx->mrec, and ctx->attr now point to the
1372 		 * mft record containing the attribute represented by the
1373 		 * current al_entry.
1374 		 */
1375 		/*
1376 		 * We could call into ntfs_attr_find() to find the right
1377 		 * attribute in this mft record but this would be less
1378 		 * efficient and not quite accurate as ntfs_attr_find() ignores
1379 		 * the attribute instance numbers for example which become
1380 		 * important when one plays with attribute lists.  Also,
1381 		 * because a proper match has been found in the attribute list
1382 		 * entry above, the comparison can now be optimized.  So it is
1383 		 * worth re-implementing a simplified ntfs_attr_find() here.
1384 		 */
1385 		/*
1386 		 * Use a manual loop so we can still use break and continue
1387 		 * with the same meanings as above.
1388 		 */
1389 do_next_attr_loop:
1390 		if ((u8 *)a < (u8 *)ctx->mrec ||
1391 		    (u8 *)a >= (u8 *)ctx->mrec + le32_to_cpu(ctx->mrec->bytes_allocated) ||
1392 		    (u8 *)a >= (u8 *)ctx->mrec + le32_to_cpu(ctx->mrec->bytes_in_use))
1393 			break;
1394 
1395 		mft_free_len = le32_to_cpu(ctx->mrec->bytes_in_use) -
1396 			       ((u8 *)a - (u8 *)ctx->mrec);
1397 		if (mft_free_len >= sizeof(a->type) && a->type == AT_END)
1398 			continue;
1399 
1400 		attr_len = le32_to_cpu(a->length);
1401 		if (!attr_len ||
1402 		    attr_len < offsetof(struct attr_record, data.resident.reserved) +
1403 		    sizeof(a->data.resident.reserved) ||
1404 		    attr_len > mft_free_len)
1405 			break;
1406 
1407 		if (al_entry->instance != a->instance)
1408 			goto do_next_attr;
1409 		/*
1410 		 * If the type and/or the name are mismatched between the
1411 		 * attribute list entry and the attribute record, there is
1412 		 * corruption so we break and return error EIO.
1413 		 */
1414 		if (al_entry->type != a->type)
1415 			break;
1416 		if (a->name_length && ((le16_to_cpu(a->name_offset) +
1417 			       a->name_length * sizeof(__le16)) > attr_len))
1418 			break;
1419 		if (!ntfs_are_names_equal((__le16 *)((u8 *)a +
1420 				le16_to_cpu(a->name_offset)), a->name_length,
1421 				al_name, al_name_len, CASE_SENSITIVE,
1422 				vol->upcase, vol->upcase_len))
1423 			break;
1424 
1425 		ctx->attr = a;
1426 
1427 		if (!ntfs_attr_value_is_valid(vol, a, ctx->ntfs_ino->mft_no))
1428 			break;
1429 
1430 		/*
1431 		 * If no @val specified or @val specified and it matches, we
1432 		 * have found it!
1433 		 */
1434 		if ((type == AT_UNUSED) || !val)
1435 			goto attr_found;
1436 		if (!a->non_resident) {
1437 			u32 value_length = le32_to_cpu(a->data.resident.value_length);
1438 			u16 value_offset = le16_to_cpu(a->data.resident.value_offset);
1439 
1440 			if (value_length == val_len &&
1441 			    !memcmp((u8 *)a + value_offset, val, val_len)) {
1442 attr_found:
1443 				ntfs_debug("Done, found.");
1444 				return 0;
1445 			}
1446 		}
1447 do_next_attr:
1448 		/* Proceed to the next attribute in the current mft record. */
1449 		a = (struct attr_record *)((u8 *)a + attr_len);
1450 		goto do_next_attr_loop;
1451 	}
1452 
1453 corrupt:
1454 	if (ni != base_ni) {
1455 		if (ni)
1456 			unmap_extent_mft_record(ni);
1457 		ctx->ntfs_ino = base_ni;
1458 		ctx->mrec = ctx->base_mrec;
1459 		ctx->attr = ctx->base_attr;
1460 		ctx->mapped_mrec = ctx->mapped_base_mrec;
1461 	}
1462 
1463 	if (!err) {
1464 		u64 mft_no = ctx->al_entry ? MREF_LE(ctx->al_entry->mft_reference) : 0;
1465 		u32 type = ctx->al_entry ? le32_to_cpu(ctx->al_entry->type) : 0;
1466 
1467 		ntfs_error(vol->sb,
1468 			"Base inode 0x%llx contains corrupt attribute, mft %#llx, type %#x. %s",
1469 			(long long)base_ni->mft_no, (long long)mft_no, type,
1470 			"Unmount and run chkdsk.");
1471 		err = -EIO;
1472 	}
1473 
1474 	if (err != -ENOMEM)
1475 		NVolSetErrors(vol);
1476 	return err;
1477 not_found:
1478 	/*
1479 	 * If we were looking for AT_END, we reset the search context @ctx and
1480 	 * use ntfs_attr_find() to seek to the end of the base mft record.
1481 	 */
1482 	if (type == AT_UNUSED || type == AT_END) {
1483 		ntfs_attr_reinit_search_ctx(ctx);
1484 		return ntfs_attr_find(AT_END, name, name_len, ic, val, val_len,
1485 				ctx);
1486 	}
1487 	/*
1488 	 * The attribute was not found.  Before we return, we want to ensure
1489 	 * @ctx->mrec and @ctx->attr indicate the position at which the
1490 	 * attribute should be inserted in the base mft record.  Since we also
1491 	 * want to preserve @ctx->al_entry we cannot reinitialize the search
1492 	 * context using ntfs_attr_reinit_search_ctx() as this would set
1493 	 * @ctx->al_entry to NULL.  Thus we do the necessary bits manually (see
1494 	 * ntfs_attr_init_search_ctx() below).  Note, we _only_ preserve
1495 	 * @ctx->al_entry as the remaining fields (base_*) are identical to
1496 	 * their non base_ counterparts and we cannot set @ctx->base_attr
1497 	 * correctly yet as we do not know what @ctx->attr will be set to by
1498 	 * the call to ntfs_attr_find() below.
1499 	 */
1500 	if (ni != base_ni)
1501 		unmap_extent_mft_record(ni);
1502 	ctx->mrec = ctx->base_mrec;
1503 	ctx->attr = (struct attr_record *)((u8 *)ctx->mrec +
1504 			le16_to_cpu(ctx->mrec->attrs_offset));
1505 	ctx->is_first = true;
1506 	ctx->ntfs_ino = base_ni;
1507 	ctx->base_ntfs_ino = NULL;
1508 	ctx->base_mrec = NULL;
1509 	ctx->base_attr = NULL;
1510 	ctx->mapped_mrec = ctx->mapped_base_mrec;
1511 	/*
1512 	 * In case there are multiple matches in the base mft record, need to
1513 	 * keep enumerating until we get an attribute not found response (or
1514 	 * another error), otherwise we would keep returning the same attribute
1515 	 * over and over again and all programs using us for enumeration would
1516 	 * lock up in a tight loop.
1517 	 */
1518 	do {
1519 		err = ntfs_attr_find(type, name, name_len, ic, val, val_len,
1520 				ctx);
1521 	} while (!err);
1522 	ntfs_debug("Done, not found.");
1523 	return err;
1524 }
1525 
1526 /*
1527  * ntfs_attr_lookup - find an attribute in an ntfs inode
1528  * @type:	attribute type to find
1529  * @name:	attribute name to find (optional, i.e. NULL means don't care)
1530  * @name_len:	attribute name length (only needed if @name present)
1531  * @ic:		IGNORE_CASE or CASE_SENSITIVE (ignored if @name not present)
1532  * @lowest_vcn:	lowest vcn to find (optional, non-resident attributes only)
1533  * @val:	attribute value to find (optional, resident attributes only)
1534  * @val_len:	attribute value length
1535  * @ctx:	search context with mft record and attribute to search from
1536  *
1537  * Find an attribute in an ntfs inode.  On first search @ctx->ntfs_ino must
1538  * be the base mft record and @ctx must have been obtained from a call to
1539  * ntfs_attr_get_search_ctx().
1540  *
1541  * This function transparently handles attribute lists and @ctx is used to
1542  * continue searches where they were left off at.
1543  *
1544  * After finishing with the attribute/mft record you need to call
1545  * ntfs_attr_put_search_ctx() to cleanup the search context (unmapping any
1546  * mapped inodes, etc).
1547  *
1548  * Return 0 if the search was successful and -errno if not.
1549  *
1550  * When 0, @ctx->attr is the found attribute and it is in mft record
1551  * @ctx->mrec.  If an attribute list attribute is present, @ctx->al_entry is
1552  * the attribute list entry of the found attribute.
1553  *
1554  * When -ENOENT, @ctx->attr is the attribute which collates just after the
1555  * attribute being searched for, i.e. if one wants to add the attribute to the
1556  * mft record this is the correct place to insert it into.  If an attribute
1557  * list attribute is present, @ctx->al_entry is the attribute list entry which
1558  * collates just after the attribute list entry of the attribute being searched
1559  * for, i.e. if one wants to add the attribute to the mft record this is the
1560  * correct place to insert its attribute list entry into.
1561  */
1562 int ntfs_attr_lookup(const __le32 type, const __le16 *name,
1563 		const u32 name_len, const u32 ic,
1564 		const s64 lowest_vcn, const u8 *val, const u32 val_len,
1565 		struct ntfs_attr_search_ctx *ctx)
1566 {
1567 	struct ntfs_inode *base_ni;
1568 
1569 	ntfs_debug("Entering.");
1570 	if (ctx->base_ntfs_ino)
1571 		base_ni = ctx->base_ntfs_ino;
1572 	else
1573 		base_ni = ctx->ntfs_ino;
1574 	/* Sanity check, just for debugging really. */
1575 	if (!base_ni || !NInoAttrList(base_ni) || type == AT_ATTRIBUTE_LIST)
1576 		return ntfs_attr_find(type, name, name_len, ic, val, val_len,
1577 				ctx);
1578 	return ntfs_external_attr_find(type, name, name_len, ic, lowest_vcn,
1579 			val, val_len, ctx);
1580 }
1581 
1582 /**
1583  * ntfs_attr_init_search_ctx - initialize an attribute search context
1584  * @ctx:        attribute search context to initialize
1585  * @ni:         ntfs inode with which to initialize the search context
1586  * @mrec:       mft record with which to initialize the search context
1587  *
1588  * Initialize the attribute search context @ctx with @ni and @mrec.
1589  */
1590 static bool ntfs_attr_init_search_ctx(struct ntfs_attr_search_ctx *ctx,
1591 		struct ntfs_inode *ni, struct mft_record *mrec)
1592 {
1593 	if (!mrec) {
1594 		mrec = map_mft_record(ni);
1595 		if (IS_ERR(mrec))
1596 			return false;
1597 		ctx->mapped_mrec = true;
1598 	} else {
1599 		ctx->mapped_mrec = false;
1600 	}
1601 
1602 	ctx->mrec = mrec;
1603 	/* Sanity checks are performed elsewhere. */
1604 	ctx->attr = (struct attr_record *)((u8 *)mrec + le16_to_cpu(mrec->attrs_offset));
1605 	ctx->is_first = true;
1606 	ctx->ntfs_ino = ni;
1607 	ctx->al_entry = NULL;
1608 	ctx->base_ntfs_ino = NULL;
1609 	ctx->base_mrec = NULL;
1610 	ctx->base_attr = NULL;
1611 	ctx->mapped_base_mrec = false;
1612 	return true;
1613 }
1614 
1615 /*
1616  * ntfs_attr_reinit_search_ctx - reinitialize an attribute search context
1617  * @ctx:	attribute search context to reinitialize
1618  *
1619  * Reinitialize the attribute search context @ctx, unmapping an associated
1620  * extent mft record if present, and initialize the search context again.
1621  *
1622  * This is used when a search for a new attribute is being started to reset
1623  * the search context to the beginning.
1624  */
1625 void ntfs_attr_reinit_search_ctx(struct ntfs_attr_search_ctx *ctx)
1626 {
1627 	bool mapped_mrec;
1628 
1629 	if (likely(!ctx->base_ntfs_ino)) {
1630 		/* No attribute list. */
1631 		ctx->is_first = true;
1632 		/* Sanity checks are performed elsewhere. */
1633 		ctx->attr = (struct attr_record *)((u8 *)ctx->mrec +
1634 				le16_to_cpu(ctx->mrec->attrs_offset));
1635 		/*
1636 		 * This needs resetting due to ntfs_external_attr_find() which
1637 		 * can leave it set despite having zeroed ctx->base_ntfs_ino.
1638 		 */
1639 		ctx->al_entry = NULL;
1640 		return;
1641 	} /* Attribute list. */
1642 	if (ctx->ntfs_ino != ctx->base_ntfs_ino && ctx->ntfs_ino)
1643 		unmap_extent_mft_record(ctx->ntfs_ino);
1644 
1645 	mapped_mrec = ctx->mapped_base_mrec;
1646 	ntfs_attr_init_search_ctx(ctx, ctx->base_ntfs_ino, ctx->base_mrec);
1647 	ctx->mapped_mrec = mapped_mrec;
1648 }
1649 
1650 /*
1651  * ntfs_attr_get_search_ctx - allocate/initialize a new attribute search context
1652  * @ni:		ntfs inode with which to initialize the search context
1653  * @mrec:	mft record with which to initialize the search context
1654  *
1655  * Allocate a new attribute search context, initialize it with @ni and @mrec,
1656  * and return it. Return NULL if allocation failed.
1657  */
1658 struct ntfs_attr_search_ctx *ntfs_attr_get_search_ctx(struct ntfs_inode *ni,
1659 		struct mft_record *mrec)
1660 {
1661 	struct ntfs_attr_search_ctx *ctx;
1662 	bool init;
1663 
1664 	ctx = kmem_cache_alloc(ntfs_attr_ctx_cache, GFP_NOFS);
1665 	if (ctx) {
1666 		init = ntfs_attr_init_search_ctx(ctx, ni, mrec);
1667 		if (init == false) {
1668 			kmem_cache_free(ntfs_attr_ctx_cache, ctx);
1669 			ctx = NULL;
1670 		}
1671 	}
1672 
1673 	return ctx;
1674 }
1675 
1676 /*
1677  * ntfs_attr_put_search_ctx - release an attribute search context
1678  * @ctx:	attribute search context to free
1679  *
1680  * Release the attribute search context @ctx, unmapping an associated extent
1681  * mft record if present.
1682  */
1683 void ntfs_attr_put_search_ctx(struct ntfs_attr_search_ctx *ctx)
1684 {
1685 	if (ctx->mapped_mrec)
1686 		unmap_mft_record(ctx->ntfs_ino);
1687 
1688 	if (ctx->mapped_base_mrec && ctx->base_ntfs_ino &&
1689 	    ctx->ntfs_ino != ctx->base_ntfs_ino)
1690 		unmap_extent_mft_record(ctx->base_ntfs_ino);
1691 	kmem_cache_free(ntfs_attr_ctx_cache, ctx);
1692 }
1693 
1694 /*
1695  * ntfs_attr_find_in_attrdef - find an attribute in the $AttrDef system file
1696  * @vol:	ntfs volume to which the attribute belongs
1697  * @type:	attribute type which to find
1698  *
1699  * Search for the attribute definition record corresponding to the attribute
1700  * @type in the $AttrDef system file.
1701  *
1702  * Return the attribute type definition record if found and NULL if not found.
1703  */
1704 static struct attr_def *ntfs_attr_find_in_attrdef(const struct ntfs_volume *vol,
1705 		const __le32 type)
1706 {
1707 	struct attr_def *ad;
1708 
1709 	WARN_ON(!type);
1710 	for (ad = vol->attrdef; (u8 *)ad - (u8 *)vol->attrdef <
1711 			vol->attrdef_size && ad->type; ++ad) {
1712 		/* We have not found it yet, carry on searching. */
1713 		if (likely(le32_to_cpu(ad->type) < le32_to_cpu(type)))
1714 			continue;
1715 		/* We found the attribute; return it. */
1716 		if (likely(ad->type == type))
1717 			return ad;
1718 		/* We have gone too far already.  No point in continuing. */
1719 		break;
1720 	}
1721 	/* Attribute not found. */
1722 	ntfs_debug("Attribute type 0x%x not found in $AttrDef.",
1723 			le32_to_cpu(type));
1724 	return NULL;
1725 }
1726 
1727 /*
1728  * ntfs_attr_size_bounds_check - check a size of an attribute type for validity
1729  * @vol:	ntfs volume to which the attribute belongs
1730  * @type:	attribute type which to check
1731  * @size:	size which to check
1732  *
1733  * Check whether the @size in bytes is valid for an attribute of @type on the
1734  * ntfs volume @vol.  This information is obtained from $AttrDef system file.
1735  */
1736 int ntfs_attr_size_bounds_check(const struct ntfs_volume *vol, const __le32 type,
1737 		const s64 size)
1738 {
1739 	struct attr_def *ad;
1740 
1741 	if (size < 0)
1742 		return -EINVAL;
1743 
1744 	/*
1745 	 * $ATTRIBUTE_LIST has a maximum size of 256kiB, but this is not
1746 	 * listed in $AttrDef.
1747 	 */
1748 	if (unlikely(type == AT_ATTRIBUTE_LIST && size > 256 * 1024))
1749 		return -ERANGE;
1750 	/* Get the $AttrDef entry for the attribute @type. */
1751 	ad = ntfs_attr_find_in_attrdef(vol, type);
1752 	if (unlikely(!ad))
1753 		return -ENOENT;
1754 	/* Do the bounds check. */
1755 	if (((le64_to_cpu(ad->min_size) > 0) &&
1756 			size < le64_to_cpu(ad->min_size)) ||
1757 			((le64_to_cpu(ad->max_size) > 0) && size >
1758 			le64_to_cpu(ad->max_size)))
1759 		return -ERANGE;
1760 	return 0;
1761 }
1762 
1763 /*
1764  * ntfs_attr_can_be_non_resident - check if an attribute can be non-resident
1765  * @vol:	ntfs volume to which the attribute belongs
1766  * @type:	attribute type which to check
1767  *
1768  * Check whether the attribute of @type on the ntfs volume @vol is allowed to
1769  * be non-resident.  This information is obtained from $AttrDef system file.
1770  */
1771 static int ntfs_attr_can_be_non_resident(const struct ntfs_volume *vol,
1772 		const __le32 type)
1773 {
1774 	struct attr_def *ad;
1775 
1776 	/* Find the attribute definition record in $AttrDef. */
1777 	ad = ntfs_attr_find_in_attrdef(vol, type);
1778 	if (unlikely(!ad))
1779 		return -ENOENT;
1780 	/* Check the flags and return the result. */
1781 	if (ad->flags & ATTR_DEF_RESIDENT)
1782 		return -EPERM;
1783 	return 0;
1784 }
1785 
1786 /*
1787  * ntfs_attr_can_be_resident - check if an attribute can be resident
1788  * @vol:	ntfs volume to which the attribute belongs
1789  * @type:	attribute type which to check
1790  *
1791  * Check whether the attribute of @type on the ntfs volume @vol is allowed to
1792  * be resident.  This information is derived from our ntfs knowledge and may
1793  * not be completely accurate, especially when user defined attributes are
1794  * present.  Basically we allow everything to be resident except for index
1795  * allocation and $EA attributes.
1796  *
1797  * Return 0 if the attribute is allowed to be non-resident and -EPERM if not.
1798  *
1799  * Warning: In the system file $MFT the attribute $Bitmap must be non-resident
1800  *	    otherwise windows will not boot (blue screen of death)!  We cannot
1801  *	    check for this here as we do not know which inode's $Bitmap is
1802  *	    being asked about so the caller needs to special case this.
1803  */
1804 int ntfs_attr_can_be_resident(const struct ntfs_volume *vol, const __le32 type)
1805 {
1806 	if (type == AT_INDEX_ALLOCATION)
1807 		return -EPERM;
1808 	return 0;
1809 }
1810 
1811 /*
1812  * ntfs_attr_record_resize - resize an attribute record
1813  * @m:		mft record containing attribute record
1814  * @a:		attribute record to resize
1815  * @new_size:	new size in bytes to which to resize the attribute record @a
1816  *
1817  * Resize the attribute record @a, i.e. the resident part of the attribute, in
1818  * the mft record @m to @new_size bytes.
1819  */
1820 int ntfs_attr_record_resize(struct mft_record *m, struct attr_record *a, u32 new_size)
1821 {
1822 	u32 old_size, alloc_size, attr_size;
1823 
1824 	old_size   = le32_to_cpu(m->bytes_in_use);
1825 	alloc_size = le32_to_cpu(m->bytes_allocated);
1826 	attr_size  = le32_to_cpu(a->length);
1827 
1828 	ntfs_debug("Sizes: old=%u alloc=%u attr=%u new=%u\n",
1829 			(unsigned int)old_size, (unsigned int)alloc_size,
1830 			(unsigned int)attr_size, (unsigned int)new_size);
1831 
1832 	/* Align to 8 bytes if it is not already done. */
1833 	if (new_size & 7)
1834 		new_size = (new_size + 7) & ~7;
1835 	/* If the actual attribute length has changed, move things around. */
1836 	if (new_size != attr_size) {
1837 		u32 new_muse = le32_to_cpu(m->bytes_in_use) -
1838 				attr_size + new_size;
1839 		/* Not enough space in this mft record. */
1840 		if (new_muse > le32_to_cpu(m->bytes_allocated))
1841 			return -ENOSPC;
1842 
1843 		if (a->type == AT_INDEX_ROOT && new_size > attr_size &&
1844 			new_muse + 120 > alloc_size && old_size + 120 <= alloc_size) {
1845 			ntfs_debug("Too big struct index_root (%u > %u)\n",
1846 					new_muse, alloc_size);
1847 			return -ENOSPC;
1848 		}
1849 
1850 		/* Move attributes following @a to their new location. */
1851 		memmove((u8 *)a + new_size, (u8 *)a + le32_to_cpu(a->length),
1852 				le32_to_cpu(m->bytes_in_use) - ((u8 *)a -
1853 				(u8 *)m) - attr_size);
1854 		/* Adjust @m to reflect the change in used space. */
1855 		m->bytes_in_use = cpu_to_le32(new_muse);
1856 		/* Adjust @a to reflect the new size. */
1857 		if (new_size >= offsetof(struct attr_record, length) + sizeof(a->length))
1858 			a->length = cpu_to_le32(new_size);
1859 	}
1860 	return 0;
1861 }
1862 
1863 /*
1864  * ntfs_resident_attr_value_resize - resize the value of a resident attribute
1865  * @m:		mft record containing attribute record
1866  * @a:		attribute record whose value to resize
1867  * @new_size:	new size in bytes to which to resize the attribute value of @a
1868  *
1869  * Resize the value of the attribute @a in the mft record @m to @new_size bytes.
1870  * If the value is made bigger, the newly allocated space is cleared.
1871  */
1872 int ntfs_resident_attr_value_resize(struct mft_record *m, struct attr_record *a,
1873 		const u32 new_size)
1874 {
1875 	u32 old_size;
1876 
1877 	/* Resize the resident part of the attribute record. */
1878 	if (ntfs_attr_record_resize(m, a,
1879 			le16_to_cpu(a->data.resident.value_offset) + new_size))
1880 		return -ENOSPC;
1881 	/*
1882 	 * The resize succeeded!  If we made the attribute value bigger, clear
1883 	 * the area between the old size and @new_size.
1884 	 */
1885 	old_size = le32_to_cpu(a->data.resident.value_length);
1886 	if (new_size > old_size)
1887 		memset((u8 *)a + le16_to_cpu(a->data.resident.value_offset) +
1888 				old_size, 0, new_size - old_size);
1889 	/* Finally update the length of the attribute value. */
1890 	a->data.resident.value_length = cpu_to_le32(new_size);
1891 	return 0;
1892 }
1893 
1894 /*
1895  * ntfs_attr_make_non_resident - convert a resident to a non-resident attribute
1896  * @ni:		ntfs inode describing the attribute to convert
1897  * @data_size:	size of the resident data to copy to the non-resident attribute
1898  *
1899  * Convert the resident ntfs attribute described by the ntfs inode @ni to a
1900  * non-resident one.
1901  *
1902  * @data_size must be equal to the attribute value size.  This is needed since
1903  * we need to know the size before we can map the mft record and our callers
1904  * always know it.  The reason we cannot simply read the size from the vfs
1905  * inode i_size is that this is not necessarily uptodate.  This happens when
1906  * ntfs_attr_make_non_resident() is called in the ->truncate call path(s).
1907  */
1908 int ntfs_attr_make_non_resident(struct ntfs_inode *ni, const u32 data_size)
1909 {
1910 	s64 new_size;
1911 	struct inode *vi = VFS_I(ni);
1912 	struct ntfs_volume *vol = ni->vol;
1913 	struct ntfs_inode *base_ni;
1914 	struct mft_record *m;
1915 	struct attr_record *a;
1916 	struct ntfs_attr_search_ctx *ctx;
1917 	struct folio *folio;
1918 	struct runlist_element *rl;
1919 	unsigned long flags;
1920 	int mp_size, mp_ofs, name_ofs, arec_size, err, err2;
1921 	u32 attr_size;
1922 	u8 old_res_attr_flags;
1923 
1924 	if (NInoNonResident(ni)) {
1925 		ntfs_warning(vol->sb,
1926 			"Trying to make non-resident attribute non-resident.  Aborting...\n");
1927 		return -EINVAL;
1928 	}
1929 
1930 	/* Check that the attribute is allowed to be non-resident. */
1931 	err = ntfs_attr_can_be_non_resident(vol, ni->type);
1932 	if (unlikely(err)) {
1933 		if (err == -EPERM)
1934 			ntfs_debug("Attribute is not allowed to be non-resident.");
1935 		else
1936 			ntfs_debug("Attribute not defined on the NTFS volume!");
1937 		return err;
1938 	}
1939 
1940 	if (NInoEncrypted(ni))
1941 		return -EIO;
1942 
1943 	if (!NInoAttr(ni))
1944 		base_ni = ni;
1945 	else
1946 		base_ni = ni->ext.base_ntfs_ino;
1947 	m = map_mft_record(base_ni);
1948 	if (IS_ERR(m)) {
1949 		err = PTR_ERR(m);
1950 		m = NULL;
1951 		ctx = NULL;
1952 		goto err_out;
1953 	}
1954 	ctx = ntfs_attr_get_search_ctx(base_ni, m);
1955 	if (unlikely(!ctx)) {
1956 		err = -ENOMEM;
1957 		goto err_out;
1958 	}
1959 	err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
1960 			CASE_SENSITIVE, 0, NULL, 0, ctx);
1961 	if (unlikely(err)) {
1962 		if (err == -ENOENT)
1963 			err = -EIO;
1964 		goto err_out;
1965 	}
1966 	m = ctx->mrec;
1967 	a = ctx->attr;
1968 
1969 	/*
1970 	 * The size needs to be aligned to a cluster boundary for allocation
1971 	 * purposes.
1972 	 */
1973 	new_size = (data_size + vol->cluster_size - 1) &
1974 			~(vol->cluster_size - 1);
1975 	if (new_size > 0) {
1976 		if ((a->flags & ATTR_COMPRESSION_MASK) == ATTR_IS_COMPRESSED) {
1977 			/* must allocate full compression blocks */
1978 			new_size =
1979 				((new_size - 1) |
1980 				 ((1L << (STANDARD_COMPRESSION_UNIT +
1981 					  vol->cluster_size_bits)) - 1)) + 1;
1982 		}
1983 
1984 		/*
1985 		 * Will need folio later and since folio lock nests
1986 		 * outside all ntfs locks, we need to get the folio now.
1987 		 */
1988 		folio = __filemap_get_folio(vi->i_mapping, 0,
1989 					    FGP_CREAT | FGP_LOCK,
1990 					    mapping_gfp_mask(vi->i_mapping));
1991 		if (IS_ERR(folio)) {
1992 			err = -ENOMEM;
1993 			goto err_out;
1994 		}
1995 
1996 		/* Start by allocating clusters to hold the attribute value. */
1997 		rl = ntfs_cluster_alloc(vol, 0,
1998 				ntfs_bytes_to_cluster(vol, new_size),
1999 				-1, DATA_ZONE, true, false, false);
2000 		if (IS_ERR(rl)) {
2001 			err = PTR_ERR(rl);
2002 			ntfs_debug("Failed to allocate cluster%s, error code %i.",
2003 					str_plural(ntfs_bytes_to_cluster(vol, new_size)),
2004 					err);
2005 			goto folio_err_out;
2006 		}
2007 	} else {
2008 		rl = NULL;
2009 		folio = NULL;
2010 	}
2011 
2012 	down_write(&ni->runlist.lock);
2013 	/* Determine the size of the mapping pairs array. */
2014 	mp_size = ntfs_get_size_for_mapping_pairs(vol, rl, 0, -1, -1);
2015 	if (unlikely(mp_size < 0)) {
2016 		err = mp_size;
2017 		ntfs_debug("Failed to get size for mapping pairs array, error code %i.\n", err);
2018 		goto rl_err_out;
2019 	}
2020 
2021 	if (NInoNonResident(ni) || a->non_resident) {
2022 		err = -EIO;
2023 		goto rl_err_out;
2024 	}
2025 
2026 	/*
2027 	 * Calculate new offsets for the name and the mapping pairs array.
2028 	 */
2029 	if (NInoSparse(ni) || NInoCompressed(ni))
2030 		name_ofs = (offsetof(struct attr_record,
2031 				data.non_resident.compressed_size) +
2032 				sizeof(a->data.non_resident.compressed_size) +
2033 				7) & ~7;
2034 	else
2035 		name_ofs = (offsetof(struct attr_record,
2036 				data.non_resident.compressed_size) + 7) & ~7;
2037 	mp_ofs = (name_ofs + a->name_length * sizeof(__le16) + 7) & ~7;
2038 	/*
2039 	 * Determine the size of the resident part of the now non-resident
2040 	 * attribute record.
2041 	 */
2042 	arec_size = (mp_ofs + mp_size + 7) & ~7;
2043 	/*
2044 	 * If the folio is not uptodate bring it uptodate by copying from the
2045 	 * attribute value.
2046 	 */
2047 	attr_size = le32_to_cpu(a->data.resident.value_length);
2048 	WARN_ON(attr_size != data_size);
2049 	if (folio && !folio_test_uptodate(folio)) {
2050 		folio_fill_tail(folio, 0, (u8 *)a +
2051 				le16_to_cpu(a->data.resident.value_offset),
2052 				attr_size);
2053 		folio_mark_uptodate(folio);
2054 	}
2055 
2056 	/* Backup the attribute flag. */
2057 	old_res_attr_flags = a->data.resident.flags;
2058 	/* Resize the resident part of the attribute record. */
2059 	err = ntfs_attr_record_resize(m, a, arec_size);
2060 	if (unlikely(err))
2061 		goto rl_err_out;
2062 
2063 	/*
2064 	 * Convert the resident part of the attribute record to describe a
2065 	 * non-resident attribute.
2066 	 */
2067 	a->non_resident = 1;
2068 	/* Move the attribute name if it exists and update the offset. */
2069 	if (a->name_length)
2070 		memmove((u8 *)a + name_ofs, (u8 *)a + le16_to_cpu(a->name_offset),
2071 				a->name_length * sizeof(__le16));
2072 	a->name_offset = cpu_to_le16(name_ofs);
2073 	/* Setup the fields specific to non-resident attributes. */
2074 	a->data.non_resident.lowest_vcn = 0;
2075 	a->data.non_resident.highest_vcn =
2076 		cpu_to_le64(ntfs_bytes_to_cluster(vol, new_size - 1));
2077 	a->data.non_resident.mapping_pairs_offset = cpu_to_le16(mp_ofs);
2078 	memset(&a->data.non_resident.reserved, 0,
2079 			sizeof(a->data.non_resident.reserved));
2080 	a->data.non_resident.allocated_size = cpu_to_le64(new_size);
2081 	a->data.non_resident.data_size =
2082 			a->data.non_resident.initialized_size =
2083 			cpu_to_le64(attr_size);
2084 	if (NInoSparse(ni) || NInoCompressed(ni)) {
2085 		a->data.non_resident.compression_unit = 0;
2086 		if (NInoCompressed(ni) || vol->major_ver < 3)
2087 			a->data.non_resident.compression_unit = 4;
2088 		a->data.non_resident.compressed_size =
2089 				a->data.non_resident.allocated_size;
2090 	} else
2091 		a->data.non_resident.compression_unit = 0;
2092 	/* Generate the mapping pairs array into the attribute record. */
2093 	err = ntfs_mapping_pairs_build(vol, (u8 *)a + mp_ofs,
2094 			arec_size - mp_ofs, rl, 0, -1, NULL, NULL, NULL);
2095 	if (unlikely(err)) {
2096 		ntfs_error(vol->sb, "Failed to build mapping pairs, error code %i.",
2097 				err);
2098 		goto undo_err_out;
2099 	}
2100 
2101 	/* Setup the in-memory attribute structure to be non-resident. */
2102 	ni->runlist.rl = rl;
2103 	if (rl) {
2104 		for (ni->runlist.count = 1; rl->length != 0; rl++)
2105 			ni->runlist.count++;
2106 	} else
2107 		ni->runlist.count = 0;
2108 	write_lock_irqsave(&ni->size_lock, flags);
2109 	ni->allocated_size = new_size;
2110 	if (NInoSparse(ni) || NInoCompressed(ni)) {
2111 		ni->itype.compressed.size = ni->allocated_size;
2112 		if (a->data.non_resident.compression_unit) {
2113 			ni->itype.compressed.block_size = 1U <<
2114 				(a->data.non_resident.compression_unit +
2115 				 vol->cluster_size_bits);
2116 			ni->itype.compressed.block_size_bits =
2117 					ffs(ni->itype.compressed.block_size) -
2118 					1;
2119 			ni->itype.compressed.block_clusters = 1U <<
2120 					a->data.non_resident.compression_unit;
2121 		} else {
2122 			ni->itype.compressed.block_size = 0;
2123 			ni->itype.compressed.block_size_bits = 0;
2124 			ni->itype.compressed.block_clusters = 0;
2125 		}
2126 		vi->i_blocks = ni->itype.compressed.size >> 9;
2127 	} else
2128 		vi->i_blocks = ni->allocated_size >> 9;
2129 	write_unlock_irqrestore(&ni->size_lock, flags);
2130 	/*
2131 	 * This needs to be last since the address space operations ->read_folio
2132 	 * and ->writepage can run concurrently with us as they are not
2133 	 * serialized on i_mutex.  Note, we are not allowed to fail once we flip
2134 	 * this switch, which is another reason to do this last.
2135 	 */
2136 	NInoSetNonResident(ni);
2137 	NInoSetFullyMapped(ni);
2138 	/* Mark the mft record dirty, so it gets written back. */
2139 	mark_mft_record_dirty(ctx->ntfs_ino);
2140 	ntfs_attr_put_search_ctx(ctx);
2141 	unmap_mft_record(base_ni);
2142 	up_write(&ni->runlist.lock);
2143 	if (folio) {
2144 		iomap_dirty_folio(vi->i_mapping, folio);
2145 		folio_unlock(folio);
2146 		folio_put(folio);
2147 	}
2148 	ntfs_debug("Done.");
2149 	return 0;
2150 undo_err_out:
2151 	/* Convert the attribute back into a resident attribute. */
2152 	a->non_resident = 0;
2153 	/* Move the attribute name if it exists and update the offset. */
2154 	name_ofs = (offsetof(struct attr_record, data.resident.reserved) +
2155 			sizeof(a->data.resident.reserved) + 7) & ~7;
2156 	if (a->name_length)
2157 		memmove((u8 *)a + name_ofs, (u8 *)a + le16_to_cpu(a->name_offset),
2158 				a->name_length * sizeof(__le16));
2159 	mp_ofs = (name_ofs + a->name_length * sizeof(__le16) + 7) & ~7;
2160 	a->name_offset = cpu_to_le16(name_ofs);
2161 	arec_size = (mp_ofs + attr_size + 7) & ~7;
2162 	/* Resize the resident part of the attribute record. */
2163 	err2 = ntfs_attr_record_resize(m, a, arec_size);
2164 	if (unlikely(err2)) {
2165 		/*
2166 		 * This cannot happen (well if memory corruption is at work it
2167 		 * could happen in theory), but deal with it as well as we can.
2168 		 * If the old size is too small, truncate the attribute,
2169 		 * otherwise simply give it a larger allocated size.
2170 		 */
2171 		arec_size = le32_to_cpu(a->length);
2172 		if ((mp_ofs + attr_size) > arec_size) {
2173 			err2 = attr_size;
2174 			attr_size = arec_size - mp_ofs;
2175 			ntfs_error(vol->sb,
2176 				"Failed to undo partial resident to non-resident attribute conversion.  Truncating inode 0x%llx, attribute type 0x%x from %i bytes to %i bytes to maintain metadata consistency.  THIS MEANS YOU ARE LOSING %i BYTES DATA FROM THIS %s.",
2177 					ni->mft_no,
2178 					(unsigned int)le32_to_cpu(ni->type),
2179 					err2, attr_size, err2 - attr_size,
2180 					((ni->type == AT_DATA) &&
2181 					!ni->name_len) ? "FILE" : "ATTRIBUTE");
2182 			write_lock_irqsave(&ni->size_lock, flags);
2183 			ni->initialized_size = attr_size;
2184 			i_size_write(vi, attr_size);
2185 			write_unlock_irqrestore(&ni->size_lock, flags);
2186 		}
2187 	}
2188 	/* Setup the fields specific to resident attributes. */
2189 	a->data.resident.value_length = cpu_to_le32(attr_size);
2190 	a->data.resident.value_offset = cpu_to_le16(mp_ofs);
2191 	a->data.resident.flags = old_res_attr_flags;
2192 	memset(&a->data.resident.reserved, 0,
2193 			sizeof(a->data.resident.reserved));
2194 	/* Copy the data from folio back to the attribute value. */
2195 	if (folio)
2196 		memcpy_from_folio((u8 *)a + mp_ofs, folio, 0, attr_size);
2197 	/* Setup the allocated size in the ntfs inode in case it changed. */
2198 	write_lock_irqsave(&ni->size_lock, flags);
2199 	ni->allocated_size = arec_size - mp_ofs;
2200 	write_unlock_irqrestore(&ni->size_lock, flags);
2201 	/* Mark the mft record dirty, so it gets written back. */
2202 	mark_mft_record_dirty(ctx->ntfs_ino);
2203 rl_err_out:
2204 	up_write(&ni->runlist.lock);
2205 	if (rl) {
2206 		if (ntfs_cluster_free_from_rl(vol, rl) < 0) {
2207 			ntfs_error(vol->sb,
2208 				"Failed to release allocated cluster(s) in error code path.  Run chkdsk to recover the lost cluster(s).");
2209 			NVolSetErrors(vol);
2210 		}
2211 		kvfree(rl);
2212 folio_err_out:
2213 		folio_unlock(folio);
2214 		folio_put(folio);
2215 	}
2216 err_out:
2217 	if (ctx)
2218 		ntfs_attr_put_search_ctx(ctx);
2219 	if (m)
2220 		unmap_mft_record(base_ni);
2221 	ni->runlist.rl = NULL;
2222 
2223 	if (err == -EINVAL)
2224 		err = -EIO;
2225 	return err;
2226 }
2227 
2228 /*
2229  * ntfs_attr_set - fill (a part of) an attribute with a byte
2230  * @ni:		ntfs inode describing the attribute to fill
2231  * @ofs:	offset inside the attribute at which to start to fill
2232  * @cnt:	number of bytes to fill
2233  * @val:	the unsigned 8-bit value with which to fill the attribute
2234  *
2235  * Fill @cnt bytes of the attribute described by the ntfs inode @ni starting at
2236  * byte offset @ofs inside the attribute with the constant byte @val.
2237  *
2238  * This function is effectively like memset() applied to an ntfs attribute.
2239  * Note thie function actually only operates on the page cache pages belonging
2240  * to the ntfs attribute and it marks them dirty after doing the memset().
2241  * Thus it relies on the vm dirty page write code paths to cause the modified
2242  * pages to be written to the mft record/disk.
2243  */
2244 int ntfs_attr_set(struct ntfs_inode *ni, s64 ofs, s64 cnt, const u8 val)
2245 {
2246 	struct address_space *mapping = VFS_I(ni)->i_mapping;
2247 	struct folio *folio;
2248 	pgoff_t index;
2249 	u8 *addr;
2250 	unsigned long offset;
2251 	size_t attr_len;
2252 	int ret = 0;
2253 
2254 	index = ofs >> PAGE_SHIFT;
2255 	while (cnt) {
2256 		folio = read_mapping_folio(mapping, index, NULL);
2257 		if (IS_ERR(folio)) {
2258 			ret = PTR_ERR(folio);
2259 			ntfs_error(VFS_I(ni)->i_sb, "Failed to read a page %lu for attr %#x: %ld",
2260 				   index, ni->type, PTR_ERR(folio));
2261 			break;
2262 		}
2263 
2264 		offset = offset_in_folio(folio, ofs);
2265 		attr_len = min_t(size_t, (size_t)cnt, folio_size(folio) - offset);
2266 
2267 		folio_lock(folio);
2268 		addr = kmap_local_folio(folio, offset);
2269 		memset(addr, val, attr_len);
2270 		kunmap_local(addr);
2271 
2272 		folio_mark_dirty(folio);
2273 		folio_unlock(folio);
2274 		folio_put(folio);
2275 
2276 		ofs += attr_len;
2277 		cnt -= attr_len;
2278 		index++;
2279 		cond_resched();
2280 	}
2281 
2282 	return ret;
2283 }
2284 
2285 int ntfs_attr_set_initialized_size(struct ntfs_inode *ni, loff_t new_size)
2286 {
2287 	struct ntfs_attr_search_ctx *ctx;
2288 	int err = 0;
2289 
2290 	if (!NInoNonResident(ni))
2291 		return -EINVAL;
2292 
2293 	ctx = ntfs_attr_get_search_ctx(ni, NULL);
2294 	if (!ctx)
2295 		return -ENOMEM;
2296 
2297 	err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
2298 			       CASE_SENSITIVE, 0, NULL, 0, ctx);
2299 	if (err)
2300 		goto out_ctx;
2301 
2302 	ctx->attr->data.non_resident.initialized_size = cpu_to_le64(new_size);
2303 	ni->initialized_size = new_size;
2304 	mark_mft_record_dirty(ctx->ntfs_ino);
2305 out_ctx:
2306 	ntfs_attr_put_search_ctx(ctx);
2307 	return err;
2308 }
2309 
2310 /*
2311  * ntfs_make_room_for_attr - make room for an attribute inside an mft record
2312  * @m:		mft record
2313  * @pos:	position at which to make space
2314  * @size:	byte size to make available at this position
2315  *
2316  * @pos points to the attribute in front of which we want to make space.
2317  */
2318 static int ntfs_make_room_for_attr(struct mft_record *m, u8 *pos, u32 size)
2319 {
2320 	u32 biu;
2321 
2322 	ntfs_debug("Entering for pos 0x%x, size %u.\n",
2323 			(int)(pos - (u8 *)m), (unsigned int) size);
2324 
2325 	/* Make size 8-byte alignment. */
2326 	size = (size + 7) & ~7;
2327 
2328 	/* Rigorous consistency checks. */
2329 	if (!m || !pos || pos < (u8 *)m) {
2330 		pr_err("%s: pos=%p  m=%p\n", __func__, pos, m);
2331 		return -EINVAL;
2332 	}
2333 
2334 	/* The -8 is for the attribute terminator. */
2335 	if (pos - (u8 *)m > (int)le32_to_cpu(m->bytes_in_use) - 8)
2336 		return -EINVAL;
2337 	/* Nothing to do. */
2338 	if (!size)
2339 		return 0;
2340 
2341 	biu = le32_to_cpu(m->bytes_in_use);
2342 	/* Do we have enough space? */
2343 	if (biu + size > le32_to_cpu(m->bytes_allocated) ||
2344 	    pos + size > (u8 *)m + le32_to_cpu(m->bytes_allocated)) {
2345 		ntfs_debug("No enough space in the MFT record\n");
2346 		return -ENOSPC;
2347 	}
2348 	/* Move everything after pos to pos + size. */
2349 	memmove(pos + size, pos, biu - (pos - (u8 *)m));
2350 	/* Update mft record. */
2351 	m->bytes_in_use = cpu_to_le32(biu + size);
2352 	return 0;
2353 }
2354 
2355 /*
2356  * ntfs_resident_attr_record_add - add resident attribute to inode
2357  * @ni:		opened ntfs inode to which MFT record add attribute
2358  * @type:	type of the new attribute
2359  * @name:	name of the new attribute
2360  * @name_len:	name length of the new attribute
2361  * @val:	value of the new attribute
2362  * @size:	size of new attribute (length of @val, if @val != NULL)
2363  * @flags:	flags of the new attribute
2364  */
2365 int ntfs_resident_attr_record_add(struct ntfs_inode *ni, __le32 type,
2366 		__le16 *name, u8 name_len, u8 *val, u32 size,
2367 		__le16 flags)
2368 {
2369 	struct ntfs_attr_search_ctx *ctx;
2370 	u32 length;
2371 	struct attr_record *a;
2372 	struct mft_record *m;
2373 	int err, offset;
2374 	struct ntfs_inode *base_ni;
2375 
2376 	if (!ni || (!name && name_len))
2377 		return -EINVAL;
2378 
2379 	ntfs_debug("Entering for inode 0x%llx, attr 0x%x, flags 0x%x.\n",
2380 			(long long) ni->mft_no, (unsigned int) le32_to_cpu(type),
2381 			(unsigned int) le16_to_cpu(flags));
2382 
2383 	err = ntfs_attr_can_be_resident(ni->vol, type);
2384 	if (err) {
2385 		if (err == -EPERM)
2386 			ntfs_debug("Attribute can't be resident.\n");
2387 		else
2388 			ntfs_debug("ntfs_attr_can_be_resident failed.\n");
2389 		return err;
2390 	}
2391 
2392 	/* Locate place where record should be. */
2393 	ctx = ntfs_attr_get_search_ctx(ni, NULL);
2394 	if (!ctx) {
2395 		ntfs_error(ni->vol->sb, "%s: Failed to get search context",
2396 				__func__);
2397 		return -ENOMEM;
2398 	}
2399 	/*
2400 	 * Use ntfs_attr_find instead of ntfs_attr_lookup to find place for
2401 	 * attribute in @ni->mrec, not any extent inode in case if @ni is base
2402 	 * file record.
2403 	 */
2404 	err = ntfs_attr_find(type, name, name_len, CASE_SENSITIVE, val, size, ctx);
2405 	if (!err) {
2406 		err = -EEXIST;
2407 		ntfs_debug("Attribute already present.\n");
2408 		goto put_err_out;
2409 	}
2410 	if (err != -ENOENT) {
2411 		err = -EIO;
2412 		goto put_err_out;
2413 	}
2414 	a = ctx->attr;
2415 	m = ctx->mrec;
2416 
2417 	/* Make room for attribute. */
2418 	length = offsetof(struct attr_record, data.resident.reserved) +
2419 			  sizeof(a->data.resident.reserved) +
2420 		((name_len * sizeof(__le16) + 7) & ~7) +
2421 		((size + 7) & ~7);
2422 	err = ntfs_make_room_for_attr(ctx->mrec, (u8 *) ctx->attr, length);
2423 	if (err) {
2424 		ntfs_debug("Failed to make room for attribute.\n");
2425 		goto put_err_out;
2426 	}
2427 
2428 	/* Setup record fields. */
2429 	offset = ((u8 *)a - (u8 *)m);
2430 	a->type = type;
2431 	a->length = cpu_to_le32(length);
2432 	a->non_resident = 0;
2433 	a->name_length = name_len;
2434 	a->name_offset =
2435 		name_len ? cpu_to_le16((offsetof(struct attr_record, data.resident.reserved) +
2436 				sizeof(a->data.resident.reserved))) : cpu_to_le16(0);
2437 
2438 	a->flags = flags;
2439 	a->instance = m->next_attr_instance;
2440 	a->data.resident.value_length = cpu_to_le32(size);
2441 	a->data.resident.value_offset = cpu_to_le16(length - ((size + 7) & ~7));
2442 	if (val)
2443 		memcpy((u8 *)a + le16_to_cpu(a->data.resident.value_offset), val, size);
2444 	else
2445 		memset((u8 *)a + le16_to_cpu(a->data.resident.value_offset), 0, size);
2446 	if (type == AT_FILE_NAME)
2447 		a->data.resident.flags = RESIDENT_ATTR_IS_INDEXED;
2448 	else
2449 		a->data.resident.flags = 0;
2450 	if (name_len)
2451 		memcpy((u8 *)a + le16_to_cpu(a->name_offset),
2452 				name, sizeof(__le16) * name_len);
2453 	m->next_attr_instance =
2454 		cpu_to_le16((le16_to_cpu(m->next_attr_instance) + 1) & 0xffff);
2455 	if (ni->nr_extents == -1)
2456 		base_ni = ni->ext.base_ntfs_ino;
2457 	else
2458 		base_ni = ni;
2459 	if (type != AT_ATTRIBUTE_LIST && NInoAttrList(base_ni)) {
2460 		err = ntfs_attrlist_entry_add(ni, a);
2461 		if (err) {
2462 			ntfs_attr_record_resize(m, a, 0);
2463 			mark_mft_record_dirty(ctx->ntfs_ino);
2464 			ntfs_debug("Failed add attribute entry to ATTRIBUTE_LIST.\n");
2465 			goto put_err_out;
2466 		}
2467 	}
2468 	mark_mft_record_dirty(ni);
2469 	ntfs_attr_put_search_ctx(ctx);
2470 	return offset;
2471 put_err_out:
2472 	ntfs_attr_put_search_ctx(ctx);
2473 	return -EIO;
2474 }
2475 
2476 /*
2477  * ntfs_non_resident_attr_record_add - add extent of non-resident attribute
2478  * @ni:			opened ntfs inode to which MFT record add attribute
2479  * @type:		type of the new attribute extent
2480  * @name:		name of the new attribute extent
2481  * @name_len:		name length of the new attribute extent
2482  * @lowest_vcn:		lowest vcn of the new attribute extent
2483  * @dataruns_size:	dataruns size of the new attribute extent
2484  * @flags:		flags of the new attribute extent
2485  */
2486 static int ntfs_non_resident_attr_record_add(struct ntfs_inode *ni, __le32 type,
2487 		__le16 *name, u8 name_len, s64 lowest_vcn, int dataruns_size,
2488 		__le16 flags)
2489 {
2490 	struct ntfs_attr_search_ctx *ctx;
2491 	u32 length;
2492 	struct attr_record *a;
2493 	struct mft_record *m;
2494 	struct ntfs_inode *base_ni;
2495 	int err, offset;
2496 
2497 	if (!ni || dataruns_size <= 0 || (!name && name_len))
2498 		return -EINVAL;
2499 
2500 	ntfs_debug("Entering for inode 0x%llx, attr 0x%x, lowest_vcn %lld, dataruns_size %d, flags 0x%x.\n",
2501 			(long long) ni->mft_no, (unsigned int) le32_to_cpu(type),
2502 			(long long) lowest_vcn, dataruns_size,
2503 			(unsigned int) le16_to_cpu(flags));
2504 
2505 	err = ntfs_attr_can_be_non_resident(ni->vol, type);
2506 	if (err) {
2507 		if (err == -EPERM)
2508 			pr_err("Attribute can't be non resident\n");
2509 		else
2510 			pr_err("ntfs_attr_can_be_non_resident failed\n");
2511 		return err;
2512 	}
2513 
2514 	/* Locate place where record should be. */
2515 	ctx = ntfs_attr_get_search_ctx(ni, NULL);
2516 	if (!ctx) {
2517 		pr_err("%s: Failed to get search context\n", __func__);
2518 		return -ENOMEM;
2519 	}
2520 	/*
2521 	 * Use ntfs_attr_find instead of ntfs_attr_lookup to find place for
2522 	 * attribute in @ni->mrec, not any extent inode in case if @ni is base
2523 	 * file record.
2524 	 */
2525 	err = ntfs_attr_find(type, name, name_len, CASE_SENSITIVE, NULL, 0, ctx);
2526 	if (!err) {
2527 		err = -EEXIST;
2528 		pr_err("Attribute 0x%x already present\n", type);
2529 		goto put_err_out;
2530 	}
2531 	if (err != -ENOENT) {
2532 		pr_err("ntfs_attr_find failed\n");
2533 		err = -EIO;
2534 		goto put_err_out;
2535 	}
2536 	a = ctx->attr;
2537 	m = ctx->mrec;
2538 
2539 	/* Make room for attribute. */
2540 	dataruns_size = (dataruns_size + 7) & ~7;
2541 	length = offsetof(struct attr_record, data.non_resident.compressed_size) +
2542 		((sizeof(__le16) * name_len + 7) & ~7) + dataruns_size +
2543 		((flags & (ATTR_IS_COMPRESSED | ATTR_IS_SPARSE)) ?
2544 		 sizeof(a->data.non_resident.compressed_size) : 0);
2545 	err = ntfs_make_room_for_attr(ctx->mrec, (u8 *) ctx->attr, length);
2546 	if (err) {
2547 		pr_err("Failed to make room for attribute\n");
2548 		goto put_err_out;
2549 	}
2550 
2551 	/* Setup record fields. */
2552 	a->type = type;
2553 	a->length = cpu_to_le32(length);
2554 	a->non_resident = 1;
2555 	a->name_length = name_len;
2556 	a->name_offset = cpu_to_le16(offsetof(struct attr_record,
2557 					      data.non_resident.compressed_size) +
2558 			((flags & (ATTR_IS_COMPRESSED | ATTR_IS_SPARSE)) ?
2559 			 sizeof(a->data.non_resident.compressed_size) : 0));
2560 	a->flags = flags;
2561 	a->instance = m->next_attr_instance;
2562 	a->data.non_resident.lowest_vcn = cpu_to_le64(lowest_vcn);
2563 	a->data.non_resident.mapping_pairs_offset = cpu_to_le16(length - dataruns_size);
2564 	a->data.non_resident.compression_unit =
2565 		(flags & ATTR_IS_COMPRESSED) ? STANDARD_COMPRESSION_UNIT : 0;
2566 	/* If @lowest_vcn == 0, than setup empty attribute. */
2567 	if (!lowest_vcn) {
2568 		a->data.non_resident.highest_vcn = cpu_to_le64(-1);
2569 		a->data.non_resident.allocated_size = 0;
2570 		a->data.non_resident.data_size = 0;
2571 		a->data.non_resident.initialized_size = 0;
2572 		/* Set empty mapping pairs. */
2573 		*((u8 *)a + le16_to_cpu(a->data.non_resident.mapping_pairs_offset)) = 0;
2574 	}
2575 	if (name_len)
2576 		memcpy((u8 *)a + le16_to_cpu(a->name_offset),
2577 				name, sizeof(__le16) * name_len);
2578 	m->next_attr_instance =
2579 		cpu_to_le16((le16_to_cpu(m->next_attr_instance) + 1) & 0xffff);
2580 	if (ni->nr_extents == -1)
2581 		base_ni = ni->ext.base_ntfs_ino;
2582 	else
2583 		base_ni = ni;
2584 	if (type != AT_ATTRIBUTE_LIST && NInoAttrList(base_ni)) {
2585 		err = ntfs_attrlist_entry_add(ni, a);
2586 		if (err) {
2587 			pr_err("Failed add attr entry to attrlist\n");
2588 			ntfs_attr_record_resize(m, a, 0);
2589 			goto put_err_out;
2590 		}
2591 	}
2592 	mark_mft_record_dirty(ni);
2593 	/*
2594 	 * Locate offset from start of the MFT record where new attribute is
2595 	 * placed. We need relookup it, because record maybe moved during
2596 	 * update of attribute list.
2597 	 */
2598 	ntfs_attr_reinit_search_ctx(ctx);
2599 	err = ntfs_attr_lookup(type, name, name_len, CASE_SENSITIVE,
2600 				lowest_vcn, NULL, 0, ctx);
2601 	if (err) {
2602 		pr_err("%s: attribute lookup failed\n", __func__);
2603 		ntfs_attr_put_search_ctx(ctx);
2604 		return err;
2605 
2606 	}
2607 	offset = (u8 *)ctx->attr - (u8 *)ctx->mrec;
2608 	ntfs_attr_put_search_ctx(ctx);
2609 	return offset;
2610 put_err_out:
2611 	ntfs_attr_put_search_ctx(ctx);
2612 	return -1;
2613 }
2614 
2615 /*
2616  * ntfs_attr_record_rm - remove attribute extent
2617  * @ctx:	search context describing the attribute which should be removed
2618  *
2619  * If this function succeed, user should reinit search context if he/she wants
2620  * use it anymore.
2621  */
2622 int ntfs_attr_record_rm(struct ntfs_attr_search_ctx *ctx)
2623 {
2624 	struct ntfs_inode *base_ni, *ni;
2625 	__le32 type;
2626 	int err;
2627 
2628 	if (!ctx || !ctx->ntfs_ino || !ctx->mrec || !ctx->attr)
2629 		return -EINVAL;
2630 
2631 	ntfs_debug("Entering for inode 0x%llx, attr 0x%x.\n",
2632 			(long long) ctx->ntfs_ino->mft_no,
2633 			(unsigned int) le32_to_cpu(ctx->attr->type));
2634 	type = ctx->attr->type;
2635 	ni = ctx->ntfs_ino;
2636 	if (ctx->base_ntfs_ino)
2637 		base_ni = ctx->base_ntfs_ino;
2638 	else
2639 		base_ni = ctx->ntfs_ino;
2640 
2641 	/* Remove attribute itself. */
2642 	if (ntfs_attr_record_resize(ctx->mrec, ctx->attr, 0)) {
2643 		ntfs_debug("Couldn't remove attribute record. Bug or damaged MFT record.\n");
2644 		return -EIO;
2645 	}
2646 	mark_mft_record_dirty(ni);
2647 
2648 	/*
2649 	 * Remove record from $ATTRIBUTE_LIST if present and we don't want
2650 	 * delete $ATTRIBUTE_LIST itself.
2651 	 */
2652 	if (NInoAttrList(base_ni) && type != AT_ATTRIBUTE_LIST) {
2653 		err = ntfs_attrlist_entry_rm(ctx);
2654 		if (err) {
2655 			ntfs_debug("Couldn't delete record from $ATTRIBUTE_LIST.\n");
2656 			return err;
2657 		}
2658 	}
2659 
2660 	/* Post $ATTRIBUTE_LIST delete setup. */
2661 	if (type == AT_ATTRIBUTE_LIST) {
2662 		if (NInoAttrList(base_ni) && base_ni->attr_list)
2663 			kvfree(base_ni->attr_list);
2664 		base_ni->attr_list = NULL;
2665 		NInoClearAttrList(base_ni);
2666 	}
2667 
2668 	/* Free MFT record, if it doesn't contain attributes. */
2669 	if (le32_to_cpu(ctx->mrec->bytes_in_use) -
2670 			le16_to_cpu(ctx->mrec->attrs_offset) == 8) {
2671 		if (ntfs_mft_record_free(ni->vol, ni)) {
2672 			ntfs_debug("Couldn't free MFT record.\n");
2673 			return -EIO;
2674 		}
2675 		/* Remove done if we freed base inode. */
2676 		if (ni == base_ni)
2677 			return 0;
2678 		ntfs_inode_close(ni);
2679 		ctx->ntfs_ino = ni = NULL;
2680 	}
2681 
2682 	if (type == AT_ATTRIBUTE_LIST || !NInoAttrList(base_ni))
2683 		return 0;
2684 
2685 	/* Remove attribute list if we don't need it any more. */
2686 	if (!ntfs_attrlist_need(base_ni)) {
2687 		struct ntfs_attr na;
2688 		struct inode *attr_vi;
2689 
2690 		ntfs_attr_reinit_search_ctx(ctx);
2691 		if (ntfs_attr_lookup(AT_ATTRIBUTE_LIST, NULL, 0, CASE_SENSITIVE,
2692 					0, NULL, 0, ctx)) {
2693 			ntfs_debug("Couldn't find attribute list. Succeed anyway.\n");
2694 			return 0;
2695 		}
2696 		/* Deallocate clusters. */
2697 		if (ctx->attr->non_resident) {
2698 			struct runlist_element *al_rl;
2699 			size_t new_rl_count;
2700 
2701 			al_rl = ntfs_mapping_pairs_decompress(base_ni->vol,
2702 					ctx->attr, NULL, &new_rl_count);
2703 			if (IS_ERR(al_rl)) {
2704 				ntfs_debug("Couldn't decompress attribute list runlist. Succeed anyway.\n");
2705 				return 0;
2706 			}
2707 			if (ntfs_cluster_free_from_rl(base_ni->vol, al_rl))
2708 				ntfs_debug("Leaking clusters! Run chkdsk. Couldn't free clusters from attribute list runlist.\n");
2709 			kvfree(al_rl);
2710 		}
2711 		/* Remove attribute record itself. */
2712 		if (ntfs_attr_record_rm(ctx)) {
2713 			ntfs_debug("Couldn't remove attribute list. Succeed anyway.\n");
2714 			return 0;
2715 		}
2716 
2717 		na.mft_no = VFS_I(base_ni)->i_ino;
2718 		na.type = AT_ATTRIBUTE_LIST;
2719 		na.name = NULL;
2720 		na.name_len = 0;
2721 
2722 		attr_vi = ilookup5(VFS_I(base_ni)->i_sb, VFS_I(base_ni)->i_ino,
2723 				   ntfs_test_inode, &na);
2724 		if (attr_vi) {
2725 			clear_nlink(attr_vi);
2726 			iput(attr_vi);
2727 		}
2728 
2729 	}
2730 	return 0;
2731 }
2732 
2733 /*
2734  * ntfs_attr_add - add attribute to inode
2735  * @ni:		opened ntfs inode to which add attribute
2736  * @type:	type of the new attribute
2737  * @name:	name in unicode of the new attribute
2738  * @name_len:	name length in unicode characters of the new attribute
2739  * @val:	value of new attribute
2740  * @size:	size of the new attribute / length of @val (if specified)
2741  *
2742  * @val should always be specified for always resident attributes (eg. FILE_NAME
2743  * attribute), for attributes that can become non-resident @val can be NULL
2744  * (eg. DATA attribute). @size can be specified even if @val is NULL, in this
2745  * case data size will be equal to @size and initialized size will be equal
2746  * to 0.
2747  *
2748  * If inode haven't got enough space to add attribute, add attribute to one of
2749  * it extents, if no extents present or no one of them have enough space, than
2750  * allocate new extent and add attribute to it.
2751  *
2752  * If on one of this steps attribute list is needed but not present, than it is
2753  * added transparently to caller. So, this function should not be called with
2754  * @type == AT_ATTRIBUTE_LIST, if you really need to add attribute list call
2755  * ntfs_inode_add_attrlist instead.
2756  *
2757  * On success return 0. On error return -1 with errno set to the error code.
2758  */
2759 int ntfs_attr_add(struct ntfs_inode *ni, __le32 type,
2760 		__le16 *name, u8 name_len, u8 *val, s64 size)
2761 {
2762 	struct super_block *sb;
2763 	u32 attr_rec_size;
2764 	int err, i, offset;
2765 	bool is_resident;
2766 	bool can_be_non_resident = false;
2767 	struct ntfs_inode *attr_ni;
2768 	struct inode *attr_vi;
2769 	struct mft_record *ni_mrec;
2770 
2771 	if (!ni || size < 0 || type == AT_ATTRIBUTE_LIST)
2772 		return -EINVAL;
2773 
2774 	ntfs_debug("Entering for inode 0x%llx, attr %x, size %lld.\n",
2775 			(long long) ni->mft_no, type, size);
2776 
2777 	if (ni->nr_extents == -1)
2778 		ni = ni->ext.base_ntfs_ino;
2779 
2780 	/* Check the attribute type and the size. */
2781 	err = ntfs_attr_size_bounds_check(ni->vol, type, size);
2782 	if (err) {
2783 		if (err == -ENOENT)
2784 			err = -EIO;
2785 		return err;
2786 	}
2787 
2788 	sb = ni->vol->sb;
2789 	/* Sanity checks for always resident attributes. */
2790 	err = ntfs_attr_can_be_non_resident(ni->vol, type);
2791 	if (err) {
2792 		if (err != -EPERM) {
2793 			ntfs_error(sb, "ntfs_attr_can_be_non_resident failed");
2794 			goto err_out;
2795 		}
2796 		/* @val is mandatory. */
2797 		if (!val) {
2798 			ntfs_error(sb,
2799 				"val is mandatory for always resident attributes");
2800 			return -EINVAL;
2801 		}
2802 		if (size > ni->vol->mft_record_size) {
2803 			ntfs_error(sb, "Attribute is too big");
2804 			return -ERANGE;
2805 		}
2806 	} else
2807 		can_be_non_resident = true;
2808 
2809 	/*
2810 	 * Determine resident or not will be new attribute. We add 8 to size in
2811 	 * non resident case for mapping pairs.
2812 	 */
2813 	err = ntfs_attr_can_be_resident(ni->vol, type);
2814 	if (!err) {
2815 		is_resident = true;
2816 	} else {
2817 		if (err != -EPERM) {
2818 			ntfs_error(sb, "ntfs_attr_can_be_resident failed");
2819 			goto err_out;
2820 		}
2821 		is_resident = false;
2822 	}
2823 
2824 	/* Calculate attribute record size. */
2825 	if (is_resident)
2826 		attr_rec_size = offsetof(struct attr_record, data.resident.reserved) +
2827 			1 +
2828 			((name_len * sizeof(__le16) + 7) & ~7) +
2829 			((size + 7) & ~7);
2830 	else
2831 		attr_rec_size = offsetof(struct attr_record, data.non_resident.compressed_size) +
2832 			((name_len * sizeof(__le16) + 7) & ~7) + 8;
2833 
2834 	/*
2835 	 * If we have enough free space for the new attribute in the base MFT
2836 	 * record, then add attribute to it.
2837 	 */
2838 retry:
2839 	ni_mrec = map_mft_record(ni);
2840 	if (IS_ERR(ni_mrec)) {
2841 		err = -EIO;
2842 		goto err_out;
2843 	}
2844 
2845 	if (le32_to_cpu(ni_mrec->bytes_allocated) -
2846 			le32_to_cpu(ni_mrec->bytes_in_use) >= attr_rec_size) {
2847 		attr_ni = ni;
2848 		unmap_mft_record(ni);
2849 		goto add_attr_record;
2850 	}
2851 	unmap_mft_record(ni);
2852 
2853 	/* Try to add to extent inodes. */
2854 	err = ntfs_inode_attach_all_extents(ni);
2855 	if (err) {
2856 		ntfs_error(sb, "Failed to attach all extents to inode");
2857 		goto err_out;
2858 	}
2859 
2860 	for (i = 0; i < ni->nr_extents; i++) {
2861 		attr_ni = ni->ext.extent_ntfs_inos[i];
2862 		ni_mrec = map_mft_record(attr_ni);
2863 		if (IS_ERR(ni_mrec)) {
2864 			err = -EIO;
2865 			goto err_out;
2866 		}
2867 
2868 		if (le32_to_cpu(ni_mrec->bytes_allocated) -
2869 				le32_to_cpu(ni_mrec->bytes_in_use) >=
2870 				attr_rec_size) {
2871 			unmap_mft_record(attr_ni);
2872 			goto add_attr_record;
2873 		}
2874 		unmap_mft_record(attr_ni);
2875 	}
2876 
2877 	/* There is no extent that contain enough space for new attribute. */
2878 	if (!NInoAttrList(ni)) {
2879 		/* Add attribute list not present, add it and retry. */
2880 		err = ntfs_inode_add_attrlist(ni);
2881 		if (err) {
2882 			ntfs_error(sb, "Failed to add attribute list");
2883 			goto err_out;
2884 		}
2885 		goto retry;
2886 	}
2887 
2888 	attr_ni = NULL;
2889 	/* Allocate new extent. */
2890 	err = ntfs_mft_record_alloc(ni->vol, 0, &attr_ni, ni, NULL);
2891 	if (err) {
2892 		ntfs_error(sb, "Failed to allocate extent record");
2893 		goto err_out;
2894 	}
2895 	unmap_mft_record(attr_ni);
2896 
2897 add_attr_record:
2898 	if (is_resident) {
2899 		/* Add resident attribute. */
2900 		offset = ntfs_resident_attr_record_add(attr_ni, type, name,
2901 				name_len, val, size, 0);
2902 		if (offset < 0) {
2903 			if (offset == -ENOSPC && can_be_non_resident)
2904 				goto add_non_resident;
2905 			err = offset;
2906 			ntfs_error(sb, "Failed to add resident attribute");
2907 			goto free_err_out;
2908 		}
2909 		return 0;
2910 	}
2911 
2912 add_non_resident:
2913 	/* Add non resident attribute. */
2914 	offset = ntfs_non_resident_attr_record_add(attr_ni, type, name,
2915 			name_len, 0, 8, 0);
2916 	if (offset < 0) {
2917 		err = offset;
2918 		ntfs_error(sb, "Failed to add non resident attribute");
2919 		goto free_err_out;
2920 	}
2921 
2922 	/* If @size == 0, we are done. */
2923 	if (!size)
2924 		return 0;
2925 
2926 	/* Open new attribute and resize it. */
2927 	attr_vi = ntfs_attr_iget(VFS_I(ni), type, name, name_len);
2928 	if (IS_ERR(attr_vi)) {
2929 		err = PTR_ERR(attr_vi);
2930 		ntfs_error(sb, "Failed to open just added attribute");
2931 		goto rm_attr_err_out;
2932 	}
2933 	attr_ni = NTFS_I(attr_vi);
2934 
2935 	/* Resize and set attribute value. */
2936 	if (ntfs_attr_truncate(attr_ni, size) ||
2937 		(val && (ntfs_inode_attr_pwrite(attr_vi, 0, size, val, false) != size))) {
2938 		err = -EIO;
2939 		ntfs_error(sb, "Failed to initialize just added attribute");
2940 		if (ntfs_attr_rm(attr_ni))
2941 			ntfs_error(sb, "Failed to remove just added attribute");
2942 		iput(attr_vi);
2943 		goto err_out;
2944 	}
2945 	iput(attr_vi);
2946 	return 0;
2947 
2948 rm_attr_err_out:
2949 	/* Remove just added attribute. */
2950 	ni_mrec = map_mft_record(attr_ni);
2951 	if (!IS_ERR(ni_mrec)) {
2952 		if (ntfs_attr_record_resize(ni_mrec,
2953 					(struct attr_record *)((u8 *)ni_mrec + offset), 0))
2954 			ntfs_error(sb, "Failed to remove just added attribute #2");
2955 		unmap_mft_record(attr_ni);
2956 	} else
2957 		pr_err("EIO when try to remove new added attr\n");
2958 
2959 free_err_out:
2960 	/* Free MFT record, if it doesn't contain attributes. */
2961 	ni_mrec = map_mft_record(attr_ni);
2962 	if (!IS_ERR(ni_mrec)) {
2963 		int attr_size;
2964 
2965 		attr_size = le32_to_cpu(ni_mrec->bytes_in_use) -
2966 			le16_to_cpu(ni_mrec->attrs_offset);
2967 		unmap_mft_record(attr_ni);
2968 		if (attr_size == 8) {
2969 			if (ntfs_mft_record_free(attr_ni->vol, attr_ni))
2970 				ntfs_error(sb, "Failed to free MFT record");
2971 			if (attr_ni->nr_extents < 0)
2972 				ntfs_inode_close(attr_ni);
2973 		}
2974 	} else
2975 		pr_err("EIO when testing mft record is free-able\n");
2976 
2977 err_out:
2978 	return err;
2979 }
2980 
2981 /*
2982  * __ntfs_attr_init - primary initialization of an ntfs attribute structure
2983  * @ni:		ntfs attribute inode to initialize
2984  * @ni:		ntfs inode with which to initialize the ntfs attribute
2985  * @type:	attribute type
2986  * @name:	attribute name in little endian Unicode or NULL
2987  * @name_len:	length of attribute @name in Unicode characters (if @name given)
2988  *
2989  * Initialize the ntfs attribute @na with @ni, @type, @name, and @name_len.
2990  */
2991 static void __ntfs_attr_init(struct ntfs_inode *ni,
2992 		const __le32 type, __le16 *name, const u32 name_len)
2993 {
2994 	ni->runlist.rl = NULL;
2995 	ni->type = type;
2996 	ni->name = name;
2997 	if (name)
2998 		ni->name_len = name_len;
2999 	else
3000 		ni->name_len = 0;
3001 }
3002 
3003 /*
3004  * ntfs_attr_init - initialize an ntfs_attr with data sizes and status
3005  * @ni: ntfs inode to initialize
3006  * @non_resident: true if attribute is non-resident
3007  * @compressed: true if attribute is compressed
3008  * @encrypted: true if attribute is encrypted
3009  * @sparse: true if attribute is sparse
3010  * @allocated_size: allocated size of the attribute
3011  * @data_size: actual data size of the attribute
3012  * @initialized_size: initialized size of the attribute
3013  * @compressed_size: compressed size (if compressed or sparse)
3014  * @compression_unit: compression unit size (log2 of clusters)
3015  *
3016  * Final initialization for an ntfs attribute.
3017  */
3018 static void ntfs_attr_init(struct ntfs_inode *ni, const bool non_resident,
3019 		const bool compressed, const bool encrypted, const bool sparse,
3020 		const s64 allocated_size, const s64 data_size,
3021 		const s64 initialized_size, const s64 compressed_size,
3022 		const u8 compression_unit)
3023 {
3024 	if (non_resident)
3025 		NInoSetNonResident(ni);
3026 	if (compressed) {
3027 		NInoSetCompressed(ni);
3028 		ni->flags |= FILE_ATTR_COMPRESSED;
3029 	}
3030 	if (encrypted) {
3031 		NInoSetEncrypted(ni);
3032 		ni->flags |= FILE_ATTR_ENCRYPTED;
3033 	}
3034 	if (sparse) {
3035 		NInoSetSparse(ni);
3036 		ni->flags |= FILE_ATTR_SPARSE_FILE;
3037 	}
3038 	ni->allocated_size = allocated_size;
3039 	ni->data_size = data_size;
3040 	ni->initialized_size = initialized_size;
3041 	if (compressed || sparse) {
3042 		struct ntfs_volume *vol = ni->vol;
3043 
3044 		ni->itype.compressed.size = compressed_size;
3045 		ni->itype.compressed.block_clusters = 1 << compression_unit;
3046 		ni->itype.compressed.block_size = 1 << (compression_unit +
3047 				vol->cluster_size_bits);
3048 		ni->itype.compressed.block_size_bits = ffs(
3049 				ni->itype.compressed.block_size) - 1;
3050 	}
3051 }
3052 
3053 /*
3054  * ntfs_attr_open - open an ntfs attribute for access
3055  * @ni:		open ntfs inode in which the ntfs attribute resides
3056  * @type:	attribute type
3057  * @name:	attribute name in little endian Unicode or AT_UNNAMED or NULL
3058  * @name_len:	length of attribute @name in Unicode characters (if @name given)
3059  */
3060 int ntfs_attr_open(struct ntfs_inode *ni, const __le32 type,
3061 		__le16 *name, u32 name_len)
3062 {
3063 	struct ntfs_attr_search_ctx *ctx;
3064 	__le16 *newname = NULL;
3065 	struct attr_record *a;
3066 	bool cs;
3067 	struct ntfs_inode *base_ni;
3068 	int err;
3069 
3070 	if (!ni || !ni->vol)
3071 		return -EINVAL;
3072 
3073 	ntfs_debug("Entering for inode %lld, attr 0x%x.\n",
3074 			ni->mft_no, type);
3075 
3076 	if (NInoAttr(ni))
3077 		base_ni = ni->ext.base_ntfs_ino;
3078 	else
3079 		base_ni = ni;
3080 
3081 	if (name && name != AT_UNNAMED && name != I30) {
3082 		name = ntfs_ucsndup(name, name_len);
3083 		if (!name) {
3084 			err = -ENOMEM;
3085 			goto err_out;
3086 		}
3087 		newname = name;
3088 	}
3089 
3090 	ctx = ntfs_attr_get_search_ctx(base_ni, NULL);
3091 	if (!ctx) {
3092 		err = -ENOMEM;
3093 		pr_err("%s: Failed to get search context\n", __func__);
3094 		goto err_out;
3095 	}
3096 
3097 	err = ntfs_attr_lookup(type, name, name_len, 0, 0, NULL, 0, ctx);
3098 	if (err)
3099 		goto put_err_out;
3100 
3101 	a = ctx->attr;
3102 
3103 	if (!name) {
3104 		if (a->name_length) {
3105 			name = ntfs_ucsndup((__le16 *)((u8 *)a + le16_to_cpu(a->name_offset)),
3106 					    a->name_length);
3107 			if (!name)
3108 				goto put_err_out;
3109 			newname = name;
3110 			name_len = a->name_length;
3111 		} else {
3112 			name = AT_UNNAMED;
3113 			name_len = 0;
3114 		}
3115 	}
3116 
3117 	__ntfs_attr_init(ni, type, name, name_len);
3118 
3119 	/*
3120 	 * Wipe the flags in case they are not zero for an attribute list
3121 	 * attribute.  Windows does not complain about invalid flags and chkdsk
3122 	 * does not detect or fix them so we need to cope with it, too.
3123 	 */
3124 	if (type == AT_ATTRIBUTE_LIST)
3125 		a->flags = 0;
3126 
3127 	if ((type == AT_DATA) &&
3128 	    (a->non_resident ? !a->data.non_resident.initialized_size :
3129 	     !a->data.resident.value_length)) {
3130 		/*
3131 		 * Define/redefine the compression state if stream is
3132 		 * empty, based on the compression mark on parent
3133 		 * directory (for unnamed data streams) or on current
3134 		 * inode (for named data streams). The compression mark
3135 		 * may change any time, the compression state can only
3136 		 * change when stream is wiped out.
3137 		 *
3138 		 * Also prevent compression on NTFS version < 3.0
3139 		 * or cluster size > 4K or compression is disabled
3140 		 */
3141 		a->flags &= ~ATTR_COMPRESSION_MASK;
3142 		if (NInoCompressed(ni)
3143 				&& (ni->vol->major_ver >= 3)
3144 				&& NVolCompression(ni->vol)
3145 				&& (ni->vol->cluster_size <= MAX_COMPRESSION_CLUSTER_SIZE))
3146 			a->flags |= ATTR_IS_COMPRESSED;
3147 	}
3148 
3149 	cs = a->flags & (ATTR_IS_COMPRESSED | ATTR_IS_SPARSE);
3150 
3151 	if (ni->type == AT_DATA && ni->name == AT_UNNAMED &&
3152 	    ((!(a->flags & ATTR_IS_COMPRESSED) != !NInoCompressed(ni)) ||
3153 	     (!(a->flags & ATTR_IS_SPARSE)     != !NInoSparse(ni)) ||
3154 	     (!(a->flags & ATTR_IS_ENCRYPTED)  != !NInoEncrypted(ni)))) {
3155 		err = -EIO;
3156 		pr_err("Inode %lld has corrupt attribute flags (0x%x <> 0x%x)\n",
3157 				(unsigned long long)ni->mft_no,
3158 				a->flags, ni->flags);
3159 		goto put_err_out;
3160 	}
3161 
3162 	if (a->non_resident) {
3163 		if (((a->flags & ATTR_COMPRESSION_MASK) || a->data.non_resident.compression_unit) &&
3164 				(ni->vol->major_ver < 3)) {
3165 			err = -EIO;
3166 			pr_err("Compressed inode %lld not allowed  on NTFS %d.%d\n",
3167 					(unsigned long long)ni->mft_no,
3168 					ni->vol->major_ver,
3169 					ni->vol->major_ver);
3170 			goto put_err_out;
3171 		}
3172 
3173 		if ((a->flags & ATTR_IS_COMPRESSED) && !a->data.non_resident.compression_unit) {
3174 			err = -EIO;
3175 			pr_err("Compressed inode %lld attr 0x%x has no compression unit\n",
3176 					(unsigned long long)ni->mft_no, type);
3177 			goto put_err_out;
3178 		}
3179 		if ((a->flags & ATTR_COMPRESSION_MASK) &&
3180 		    (a->data.non_resident.compression_unit != STANDARD_COMPRESSION_UNIT)) {
3181 			err = -EIO;
3182 			pr_err("Compressed inode %lld attr 0x%lx has an unsupported compression unit %d\n",
3183 					(unsigned long long)ni->mft_no,
3184 					(long)le32_to_cpu(type),
3185 					(int)a->data.non_resident.compression_unit);
3186 			goto put_err_out;
3187 		}
3188 		ntfs_attr_init(ni, true, a->flags & ATTR_IS_COMPRESSED,
3189 				a->flags & ATTR_IS_ENCRYPTED,
3190 				a->flags & ATTR_IS_SPARSE,
3191 				le64_to_cpu(a->data.non_resident.allocated_size),
3192 				le64_to_cpu(a->data.non_resident.data_size),
3193 				le64_to_cpu(a->data.non_resident.initialized_size),
3194 				cs ? le64_to_cpu(a->data.non_resident.compressed_size) : 0,
3195 				cs ? a->data.non_resident.compression_unit : 0);
3196 	} else {
3197 		s64 l = le32_to_cpu(a->data.resident.value_length);
3198 
3199 		ntfs_attr_init(ni, false, a->flags & ATTR_IS_COMPRESSED,
3200 				a->flags & ATTR_IS_ENCRYPTED,
3201 				a->flags & ATTR_IS_SPARSE, (l + 7) & ~7, l, l,
3202 				cs ? (l + 7) & ~7 : 0, 0);
3203 	}
3204 	ntfs_attr_put_search_ctx(ctx);
3205 out:
3206 	ntfs_debug("\n");
3207 	return err;
3208 
3209 put_err_out:
3210 	ntfs_attr_put_search_ctx(ctx);
3211 err_out:
3212 	kfree(newname);
3213 	goto out;
3214 }
3215 
3216 /*
3217  * ntfs_attr_close - free an ntfs attribute structure
3218  * @ni:		ntfs inode to free
3219  *
3220  * Release all memory associated with the ntfs attribute @na and then release
3221  * @na itself.
3222  */
3223 void ntfs_attr_close(struct ntfs_inode *ni)
3224 {
3225 	if (NInoNonResident(ni) && ni->runlist.rl)
3226 		kvfree(ni->runlist.rl);
3227 	/* Don't release if using an internal constant. */
3228 	if (ni->name != AT_UNNAMED && ni->name != I30)
3229 		kfree(ni->name);
3230 }
3231 
3232 /*
3233  * ntfs_attr_map_whole_runlist - map the whole runlist of an ntfs attribute
3234  * @ni:		ntfs inode for which to map the runlist
3235  *
3236  * Map the whole runlist of the ntfs attribute @na.  For an attribute made up
3237  * of only one attribute extent this is the same as calling
3238  * ntfs_map_runlist(ni, 0) but for an attribute with multiple extents this
3239  * will map the runlist fragments from each of the extents thus giving access
3240  * to the entirety of the disk allocation of an attribute.
3241  */
3242 int ntfs_attr_map_whole_runlist(struct ntfs_inode *ni)
3243 {
3244 	s64 next_vcn, last_vcn, highest_vcn;
3245 	struct ntfs_attr_search_ctx *ctx;
3246 	struct ntfs_volume *vol = ni->vol;
3247 	struct super_block *sb = vol->sb;
3248 	struct attr_record *a;
3249 	int err;
3250 	struct ntfs_inode *base_ni;
3251 	int not_mapped;
3252 	size_t new_rl_count;
3253 
3254 	ntfs_debug("Entering for inode 0x%llx, attr 0x%x.\n",
3255 			(unsigned long long)ni->mft_no, ni->type);
3256 
3257 	if (NInoFullyMapped(ni) && ni->runlist.rl)
3258 		return 0;
3259 
3260 	if (NInoAttr(ni))
3261 		base_ni = ni->ext.base_ntfs_ino;
3262 	else
3263 		base_ni = ni;
3264 
3265 	ctx = ntfs_attr_get_search_ctx(base_ni, NULL);
3266 	if (!ctx) {
3267 		ntfs_error(sb, "%s: Failed to get search context", __func__);
3268 		return -ENOMEM;
3269 	}
3270 
3271 	/* Map all attribute extents one by one. */
3272 	next_vcn = last_vcn = highest_vcn = 0;
3273 	a = NULL;
3274 	while (1) {
3275 		struct runlist_element *rl;
3276 
3277 		not_mapped = 0;
3278 		if (ntfs_rl_vcn_to_lcn(ni->runlist.rl, next_vcn) == LCN_RL_NOT_MAPPED)
3279 			not_mapped = 1;
3280 
3281 		err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
3282 					CASE_SENSITIVE, next_vcn, NULL, 0, ctx);
3283 		if (err)
3284 			break;
3285 
3286 		a = ctx->attr;
3287 
3288 		if (not_mapped) {
3289 			/* Decode the runlist. */
3290 			rl = ntfs_mapping_pairs_decompress(ni->vol, a, &ni->runlist,
3291 							   &new_rl_count);
3292 			if (IS_ERR(rl)) {
3293 				err = PTR_ERR(rl);
3294 				goto err_out;
3295 			}
3296 			ni->runlist.rl = rl;
3297 			ni->runlist.count = new_rl_count;
3298 		}
3299 
3300 		/* Are we in the first extent? */
3301 		if (!next_vcn) {
3302 			if (a->data.non_resident.lowest_vcn) {
3303 				err = -EIO;
3304 				ntfs_error(sb,
3305 					"First extent of inode %llu attribute has non-zero lowest_vcn",
3306 					(unsigned long long)ni->mft_no);
3307 				goto err_out;
3308 			}
3309 			/* Get the last vcn in the attribute. */
3310 			last_vcn = ntfs_bytes_to_cluster(vol,
3311 					le64_to_cpu(a->data.non_resident.allocated_size));
3312 		}
3313 
3314 		/* Get the lowest vcn for the next extent. */
3315 		highest_vcn = le64_to_cpu(a->data.non_resident.highest_vcn);
3316 		next_vcn = highest_vcn + 1;
3317 
3318 		/* Only one extent or error, which we catch below. */
3319 		if (next_vcn <= 0) {
3320 			err = -ENOENT;
3321 			break;
3322 		}
3323 
3324 		/* Avoid endless loops due to corruption. */
3325 		if (next_vcn < le64_to_cpu(a->data.non_resident.lowest_vcn)) {
3326 			err = -EIO;
3327 			ntfs_error(sb, "Inode %llu has corrupt attribute list",
3328 					(unsigned long long)ni->mft_no);
3329 			goto err_out;
3330 		}
3331 	}
3332 	if (!a) {
3333 		ntfs_error(sb, "Couldn't find attribute for runlist mapping");
3334 		goto err_out;
3335 	}
3336 	if (not_mapped && highest_vcn && highest_vcn != last_vcn - 1) {
3337 		err = -EIO;
3338 		ntfs_error(sb,
3339 			"Failed to load full runlist: inode: %llu highest_vcn: 0x%llx last_vcn: 0x%llx",
3340 			(unsigned long long)ni->mft_no,
3341 			(long long)highest_vcn, (long long)last_vcn);
3342 		goto err_out;
3343 	}
3344 	ntfs_attr_put_search_ctx(ctx);
3345 	if (err == -ENOENT) {
3346 		NInoSetFullyMapped(ni);
3347 		return 0;
3348 	}
3349 
3350 	return err;
3351 
3352 err_out:
3353 	ntfs_attr_put_search_ctx(ctx);
3354 	return err;
3355 }
3356 
3357 /*
3358  * ntfs_attr_record_move_to - move attribute record to target inode
3359  * @ctx:	attribute search context describing the attribute record
3360  * @ni:		opened ntfs inode to which move attribute record
3361  */
3362 int ntfs_attr_record_move_to(struct ntfs_attr_search_ctx *ctx, struct ntfs_inode *ni)
3363 {
3364 	struct ntfs_attr_search_ctx *nctx;
3365 	struct attr_record *a;
3366 	int err;
3367 	struct mft_record *ni_mrec;
3368 	struct super_block *sb;
3369 
3370 	if (!ctx || !ctx->attr || !ctx->ntfs_ino || !ni) {
3371 		ntfs_debug("Invalid arguments passed.\n");
3372 		return -EINVAL;
3373 	}
3374 
3375 	sb = ni->vol->sb;
3376 	ntfs_debug("Entering for ctx->attr->type 0x%x, ctx->ntfs_ino->mft_no 0x%llx, ni->mft_no 0x%llx.\n",
3377 			(unsigned int) le32_to_cpu(ctx->attr->type),
3378 			(long long) ctx->ntfs_ino->mft_no,
3379 			(long long) ni->mft_no);
3380 
3381 	if (ctx->ntfs_ino == ni)
3382 		return 0;
3383 
3384 	if (!ctx->al_entry) {
3385 		ntfs_debug("Inode should contain attribute list to use this function.\n");
3386 		return -EINVAL;
3387 	}
3388 
3389 	/* Find place in MFT record where attribute will be moved. */
3390 	a = ctx->attr;
3391 	nctx = ntfs_attr_get_search_ctx(ni, NULL);
3392 	if (!nctx) {
3393 		ntfs_error(sb, "%s: Failed to get search context", __func__);
3394 		return -ENOMEM;
3395 	}
3396 
3397 	/*
3398 	 * Use ntfs_attr_find instead of ntfs_attr_lookup to find place for
3399 	 * attribute in @ni->mrec, not any extent inode in case if @ni is base
3400 	 * file record.
3401 	 */
3402 	err = ntfs_attr_find(a->type, (__le16 *)((u8 *)a + le16_to_cpu(a->name_offset)),
3403 				a->name_length, CASE_SENSITIVE, NULL,
3404 				0, nctx);
3405 	if (!err) {
3406 		ntfs_debug("Attribute of such type, with same name already present in this MFT record.\n");
3407 		err = -EEXIST;
3408 		goto put_err_out;
3409 	}
3410 	if (err != -ENOENT) {
3411 		ntfs_debug("Attribute lookup failed.\n");
3412 		goto put_err_out;
3413 	}
3414 
3415 	/* Make space and move attribute. */
3416 	ni_mrec = map_mft_record(ni);
3417 	if (IS_ERR(ni_mrec)) {
3418 		err = -EIO;
3419 		goto put_err_out;
3420 	}
3421 
3422 	err = ntfs_make_room_for_attr(ni_mrec, (u8 *) nctx->attr,
3423 				le32_to_cpu(a->length));
3424 	if (err) {
3425 		ntfs_debug("Couldn't make space for attribute.\n");
3426 		unmap_mft_record(ni);
3427 		goto put_err_out;
3428 	}
3429 	memcpy(nctx->attr, a, le32_to_cpu(a->length));
3430 	nctx->attr->instance = nctx->mrec->next_attr_instance;
3431 	nctx->mrec->next_attr_instance =
3432 		cpu_to_le16((le16_to_cpu(nctx->mrec->next_attr_instance) + 1) & 0xffff);
3433 	ntfs_attr_record_resize(ctx->mrec, a, 0);
3434 	mark_mft_record_dirty(ctx->ntfs_ino);
3435 	mark_mft_record_dirty(ni);
3436 
3437 	/* Update attribute list. */
3438 	ctx->al_entry->mft_reference =
3439 		MK_LE_MREF(ni->mft_no, le16_to_cpu(ni_mrec->sequence_number));
3440 	ctx->al_entry->instance = nctx->attr->instance;
3441 	unmap_mft_record(ni);
3442 put_err_out:
3443 	ntfs_attr_put_search_ctx(nctx);
3444 	return err;
3445 }
3446 
3447 /*
3448  * ntfs_attr_record_move_away - move away attribute record from it's mft record
3449  * @ctx:	attribute search context describing the attribute record
3450  * @extra:	minimum amount of free space in the new holder of record
3451  */
3452 int ntfs_attr_record_move_away(struct ntfs_attr_search_ctx *ctx, int extra)
3453 {
3454 	struct ntfs_inode *base_ni, *ni = NULL;
3455 	struct mft_record *m;
3456 	int i, err;
3457 	struct super_block *sb;
3458 
3459 	if (!ctx || !ctx->attr || !ctx->ntfs_ino || extra < 0)
3460 		return -EINVAL;
3461 
3462 	ntfs_debug("Entering for attr 0x%x, inode %llu\n",
3463 			(unsigned int) le32_to_cpu(ctx->attr->type),
3464 			(unsigned long long)ctx->ntfs_ino->mft_no);
3465 
3466 	if (ctx->ntfs_ino->nr_extents == -1)
3467 		base_ni = ctx->base_ntfs_ino;
3468 	else
3469 		base_ni = ctx->ntfs_ino;
3470 
3471 	sb = ctx->ntfs_ino->vol->sb;
3472 	if (!NInoAttrList(base_ni)) {
3473 		ntfs_error(sb, "Inode %llu has no attrlist",
3474 				(unsigned long long)base_ni->mft_no);
3475 		return -EINVAL;
3476 	}
3477 
3478 	err = ntfs_inode_attach_all_extents(ctx->ntfs_ino);
3479 	if (err) {
3480 		ntfs_error(sb, "Couldn't attach extents, inode=%llu",
3481 			(unsigned long long)base_ni->mft_no);
3482 		return err;
3483 	}
3484 
3485 	mutex_lock(&base_ni->extent_lock);
3486 	/* Walk through all extents and try to move attribute to them. */
3487 	for (i = 0; i < base_ni->nr_extents; i++) {
3488 		ni = base_ni->ext.extent_ntfs_inos[i];
3489 
3490 		if (ctx->ntfs_ino->mft_no == ni->mft_no)
3491 			continue;
3492 		m = map_mft_record(ni);
3493 		if (IS_ERR(m)) {
3494 			ntfs_error(sb, "Can not map mft record for mft_no %lld",
3495 					(unsigned long long)ni->mft_no);
3496 			mutex_unlock(&base_ni->extent_lock);
3497 			return -EIO;
3498 		}
3499 		if (le32_to_cpu(m->bytes_allocated) -
3500 		    le32_to_cpu(m->bytes_in_use) < le32_to_cpu(ctx->attr->length) + extra) {
3501 			unmap_mft_record(ni);
3502 			continue;
3503 		}
3504 		unmap_mft_record(ni);
3505 
3506 		/*
3507 		 * ntfs_attr_record_move_to can fail if extent with other lowest
3508 		 * s64 already present in inode we trying move record to. So,
3509 		 * do not return error.
3510 		 */
3511 		if (!ntfs_attr_record_move_to(ctx, ni)) {
3512 			mutex_unlock(&base_ni->extent_lock);
3513 			return 0;
3514 		}
3515 	}
3516 	mutex_unlock(&base_ni->extent_lock);
3517 
3518 	/*
3519 	 * Failed to move attribute to one of the current extents, so allocate
3520 	 * new extent and move attribute to it.
3521 	 */
3522 	ni = NULL;
3523 	err = ntfs_mft_record_alloc(base_ni->vol, 0, &ni, base_ni, NULL);
3524 	if (err) {
3525 		ntfs_error(sb, "Couldn't allocate MFT record, err : %d", err);
3526 		return err;
3527 	}
3528 	unmap_mft_record(ni);
3529 
3530 	err = ntfs_attr_record_move_to(ctx, ni);
3531 	if (err)
3532 		ntfs_error(sb, "Couldn't move attribute to MFT record");
3533 
3534 	return err;
3535 }
3536 
3537 /*
3538  * If we are in the first extent, then set/clean sparse bit,
3539  * update allocated and compressed size.
3540  */
3541 static int ntfs_attr_update_meta(struct attr_record *a, struct ntfs_inode *ni,
3542 		struct mft_record *m, struct ntfs_attr_search_ctx *ctx)
3543 {
3544 	int sparse, err = 0;
3545 	struct ntfs_inode *base_ni;
3546 	struct super_block *sb = ni->vol->sb;
3547 
3548 	ntfs_debug("Entering for inode 0x%llx, attr 0x%x\n",
3549 			(unsigned long long)ni->mft_no, ni->type);
3550 
3551 	if (NInoAttr(ni))
3552 		base_ni = ni->ext.base_ntfs_ino;
3553 	else
3554 		base_ni = ni;
3555 
3556 	if (a->data.non_resident.lowest_vcn)
3557 		goto out;
3558 
3559 	a->data.non_resident.allocated_size = cpu_to_le64(ni->allocated_size);
3560 
3561 	sparse = ntfs_rl_sparse(ni->runlist.rl);
3562 	if (sparse < 0) {
3563 		err = -EIO;
3564 		goto out;
3565 	}
3566 
3567 	/* Attribute become sparse. */
3568 	if (sparse && !(a->flags & (ATTR_IS_SPARSE | ATTR_IS_COMPRESSED))) {
3569 		/*
3570 		 * Move attribute to another mft record, if attribute is too
3571 		 * small to add compressed_size field to it and we have no
3572 		 * free space in the current mft record.
3573 		 */
3574 		if ((le32_to_cpu(a->length) -
3575 		     le16_to_cpu(a->data.non_resident.mapping_pairs_offset) == 8) &&
3576 		    !(le32_to_cpu(m->bytes_allocated) - le32_to_cpu(m->bytes_in_use))) {
3577 
3578 			if (!NInoAttrList(base_ni)) {
3579 				err = ntfs_inode_add_attrlist(base_ni);
3580 				if (err)
3581 					goto out;
3582 				err = -EAGAIN;
3583 				goto out;
3584 			}
3585 			err = ntfs_attr_record_move_away(ctx, 8);
3586 			if (err) {
3587 				ntfs_error(sb, "Failed to move attribute");
3588 				goto out;
3589 			}
3590 
3591 			err = ntfs_attrlist_update(base_ni);
3592 			if (err)
3593 				goto out;
3594 			err = -EAGAIN;
3595 			goto out;
3596 		}
3597 		if (!(le32_to_cpu(a->length) -
3598 		    le16_to_cpu(a->data.non_resident.mapping_pairs_offset))) {
3599 			err = -EIO;
3600 			ntfs_error(sb, "Mapping pairs space is 0");
3601 			goto out;
3602 		}
3603 
3604 		NInoSetSparse(ni);
3605 		ni->flags |= FILE_ATTR_SPARSE_FILE;
3606 		a->flags |= ATTR_IS_SPARSE;
3607 		a->data.non_resident.compression_unit = 0;
3608 
3609 		memmove((u8 *)a + le16_to_cpu(a->name_offset) + 8,
3610 				(u8 *)a + le16_to_cpu(a->name_offset),
3611 				a->name_length * sizeof(__le16));
3612 
3613 		a->name_offset = cpu_to_le16(le16_to_cpu(a->name_offset) + 8);
3614 
3615 		a->data.non_resident.mapping_pairs_offset =
3616 			cpu_to_le16(le16_to_cpu(a->data.non_resident.mapping_pairs_offset) + 8);
3617 	}
3618 
3619 	/* Attribute no longer sparse. */
3620 	if (!sparse && (a->flags & ATTR_IS_SPARSE) &&
3621 	    !(a->flags & ATTR_IS_COMPRESSED)) {
3622 		NInoClearSparse(ni);
3623 		ni->flags &= ~FILE_ATTR_SPARSE_FILE;
3624 		a->flags &= ~ATTR_IS_SPARSE;
3625 		a->data.non_resident.compression_unit = 0;
3626 
3627 		memmove((u8 *)a + le16_to_cpu(a->name_offset) - 8,
3628 				(u8 *)a + le16_to_cpu(a->name_offset),
3629 				a->name_length * sizeof(__le16));
3630 
3631 		if (le16_to_cpu(a->name_offset) >= 8)
3632 			a->name_offset = cpu_to_le16(le16_to_cpu(a->name_offset) - 8);
3633 
3634 		a->data.non_resident.mapping_pairs_offset =
3635 			cpu_to_le16(le16_to_cpu(a->data.non_resident.mapping_pairs_offset) - 8);
3636 	}
3637 
3638 	/* Update compressed size if required. */
3639 	if (NInoFullyMapped(ni) && (sparse || NInoCompressed(ni))) {
3640 		s64 new_compr_size;
3641 
3642 		new_compr_size = ntfs_rl_get_compressed_size(ni->vol, ni->runlist.rl);
3643 		if (new_compr_size < 0) {
3644 			err = new_compr_size;
3645 			goto out;
3646 		}
3647 
3648 		ni->itype.compressed.size = new_compr_size;
3649 		a->data.non_resident.compressed_size = cpu_to_le64(new_compr_size);
3650 	}
3651 
3652 	if (NInoSparse(ni) || NInoCompressed(ni))
3653 		VFS_I(base_ni)->i_blocks = ni->itype.compressed.size >> 9;
3654 	else
3655 		VFS_I(base_ni)->i_blocks = ni->allocated_size >> 9;
3656 	/*
3657 	 * Set FILE_NAME dirty flag, to update sparse bit and
3658 	 * allocated size in the index.
3659 	 */
3660 	if (ni->type == AT_DATA && ni->name == AT_UNNAMED)
3661 		NInoSetFileNameDirty(ni);
3662 out:
3663 	return err;
3664 }
3665 
3666 #define NTFS_VCN_DELETE_MARK -2
3667 /*
3668  * ntfs_attr_update_mapping_pairs - update mapping pairs for ntfs attribute
3669  * @ni:		non-resident ntfs inode for which we need update
3670  * @from_vcn:	update runlist starting this VCN
3671  *
3672  * Build mapping pairs from @na->rl and write them to the disk. Also, this
3673  * function updates sparse bit, allocated and compressed size (allocates/frees
3674  * space for this field if required).
3675  *
3676  * @na->allocated_size should be set to correct value for the new runlist before
3677  * call to this function. Vice-versa @na->compressed_size will be calculated and
3678  * set to correct value during this function.
3679  */
3680 int ntfs_attr_update_mapping_pairs(struct ntfs_inode *ni, s64 from_vcn)
3681 {
3682 	struct ntfs_attr_search_ctx *ctx;
3683 	struct ntfs_inode *base_ni;
3684 	struct mft_record *m;
3685 	struct attr_record *a;
3686 	s64 stop_vcn;
3687 	int err = 0, mp_size, cur_max_mp_size, exp_max_mp_size;
3688 	bool finished_build;
3689 	bool first_updated = false;
3690 	struct super_block *sb;
3691 	struct runlist_element *start_rl;
3692 	unsigned int de_cluster_count = 0;
3693 
3694 retry:
3695 	if (!ni || !ni->runlist.rl)
3696 		return -EINVAL;
3697 
3698 	ntfs_debug("Entering for inode %llu, attr 0x%x\n",
3699 			(unsigned long long)ni->mft_no, ni->type);
3700 
3701 	sb = ni->vol->sb;
3702 	if (!NInoNonResident(ni)) {
3703 		ntfs_error(sb, "%s: resident attribute", __func__);
3704 		return -EINVAL;
3705 	}
3706 
3707 	if (ni->nr_extents == -1)
3708 		base_ni = ni->ext.base_ntfs_ino;
3709 	else
3710 		base_ni = ni;
3711 
3712 	ctx = ntfs_attr_get_search_ctx(base_ni, NULL);
3713 	if (!ctx) {
3714 		ntfs_error(sb, "%s: Failed to get search context", __func__);
3715 		return -ENOMEM;
3716 	}
3717 
3718 	/* Fill attribute records with new mapping pairs. */
3719 	stop_vcn = 0;
3720 	finished_build = false;
3721 	start_rl = ni->runlist.rl;
3722 	while (!(err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
3723 				CASE_SENSITIVE, from_vcn, NULL, 0, ctx))) {
3724 		unsigned int de_cnt = 0;
3725 
3726 		a = ctx->attr;
3727 		m = ctx->mrec;
3728 		if (!a->data.non_resident.lowest_vcn)
3729 			first_updated = true;
3730 
3731 		/*
3732 		 * If runlist is updating not from the beginning, then set
3733 		 * @stop_vcn properly, i.e. to the lowest vcn of record that
3734 		 * contain @from_vcn. Also we do not need @from_vcn anymore,
3735 		 * set it to 0 to make ntfs_attr_lookup enumerate attributes.
3736 		 */
3737 		if (from_vcn) {
3738 			s64 first_lcn;
3739 
3740 			stop_vcn = le64_to_cpu(a->data.non_resident.lowest_vcn);
3741 			from_vcn = 0;
3742 			/*
3743 			 * Check whether the first run we need to update is
3744 			 * the last run in runlist, if so, then deallocate
3745 			 * all attrubute extents starting this one.
3746 			 */
3747 			first_lcn = ntfs_rl_vcn_to_lcn(ni->runlist.rl, stop_vcn);
3748 			if (first_lcn == LCN_EINVAL) {
3749 				err = -EIO;
3750 				ntfs_error(sb, "Bad runlist");
3751 				goto put_err_out;
3752 			}
3753 			if (first_lcn == LCN_ENOENT ||
3754 			    first_lcn == LCN_RL_NOT_MAPPED)
3755 				finished_build = true;
3756 		}
3757 
3758 		/*
3759 		 * Check whether we finished mapping pairs build, if so mark
3760 		 * extent as need to delete (by setting highest vcn to
3761 		 * NTFS_VCN_DELETE_MARK (-2), we shall check it later and
3762 		 * delete extent) and continue search.
3763 		 */
3764 		if (finished_build) {
3765 			ntfs_debug("Mark attr 0x%x for delete in inode 0x%llx.\n",
3766 				(unsigned int)le32_to_cpu(a->type), ctx->ntfs_ino->mft_no);
3767 			a->data.non_resident.highest_vcn = cpu_to_le64(NTFS_VCN_DELETE_MARK);
3768 			mark_mft_record_dirty(ctx->ntfs_ino);
3769 			continue;
3770 		}
3771 
3772 		err = ntfs_attr_update_meta(a, ni, m, ctx);
3773 		if (err < 0) {
3774 			if (err == -EAGAIN) {
3775 				ntfs_attr_put_search_ctx(ctx);
3776 				goto retry;
3777 			}
3778 			goto put_err_out;
3779 		}
3780 
3781 		/*
3782 		 * Determine maximum possible length of mapping pairs,
3783 		 * if we shall *not* expand space for mapping pairs.
3784 		 */
3785 		cur_max_mp_size = le32_to_cpu(a->length) -
3786 			le16_to_cpu(a->data.non_resident.mapping_pairs_offset);
3787 		/*
3788 		 * Determine maximum possible length of mapping pairs in the
3789 		 * current mft record, if we shall expand space for mapping
3790 		 * pairs.
3791 		 */
3792 		exp_max_mp_size = le32_to_cpu(m->bytes_allocated) -
3793 			le32_to_cpu(m->bytes_in_use) + cur_max_mp_size;
3794 
3795 		/* Get the size for the rest of mapping pairs array. */
3796 		mp_size = ntfs_get_size_for_mapping_pairs(ni->vol, start_rl,
3797 				stop_vcn, -1, exp_max_mp_size);
3798 		if (mp_size <= 0) {
3799 			err = mp_size;
3800 			ntfs_error(sb, "%s: get MP size failed", __func__);
3801 			goto put_err_out;
3802 		}
3803 		/* Test mapping pairs for fitting in the current mft record. */
3804 		if (mp_size > exp_max_mp_size) {
3805 			/*
3806 			 * Mapping pairs of $ATTRIBUTE_LIST attribute must fit
3807 			 * in the base mft record. Try to move out other
3808 			 * attributes and try again.
3809 			 */
3810 			if (ni->type == AT_ATTRIBUTE_LIST) {
3811 				ntfs_attr_put_search_ctx(ctx);
3812 				if (ntfs_inode_free_space(base_ni, mp_size -
3813 							cur_max_mp_size)) {
3814 					ntfs_debug("Attribute list is too big. Defragment the volume\n");
3815 					return -ENOSPC;
3816 				}
3817 				if (ntfs_attrlist_update(base_ni))
3818 					return -EIO;
3819 				goto retry;
3820 			}
3821 
3822 			/* Add attribute list if it isn't present, and retry. */
3823 			if (!NInoAttrList(base_ni)) {
3824 				ntfs_attr_put_search_ctx(ctx);
3825 				if (ntfs_inode_add_attrlist(base_ni)) {
3826 					ntfs_error(sb, "Can not add attrlist");
3827 					return -EIO;
3828 				}
3829 				goto retry;
3830 			}
3831 
3832 			/*
3833 			 * Set mapping pairs size to maximum possible for this
3834 			 * mft record. We shall write the rest of mapping pairs
3835 			 * to another MFT records.
3836 			 */
3837 			mp_size = exp_max_mp_size;
3838 		}
3839 
3840 		/* Change space for mapping pairs if we need it. */
3841 		if (((mp_size + 7) & ~7) != cur_max_mp_size) {
3842 			if (ntfs_attr_record_resize(m, a,
3843 					le16_to_cpu(a->data.non_resident.mapping_pairs_offset) +
3844 						mp_size)) {
3845 				err = -EIO;
3846 				ntfs_error(sb, "Failed to resize attribute");
3847 				goto put_err_out;
3848 			}
3849 		}
3850 
3851 		/* Update lowest vcn. */
3852 		a->data.non_resident.lowest_vcn = cpu_to_le64(stop_vcn);
3853 		mark_mft_record_dirty(ctx->ntfs_ino);
3854 		if ((ctx->ntfs_ino->nr_extents == -1 || NInoAttrList(ctx->ntfs_ino)) &&
3855 		    ctx->attr->type != AT_ATTRIBUTE_LIST) {
3856 			ctx->al_entry->lowest_vcn = cpu_to_le64(stop_vcn);
3857 			err = ntfs_attrlist_update(base_ni);
3858 			if (err)
3859 				goto put_err_out;
3860 		}
3861 
3862 		/*
3863 		 * Generate the new mapping pairs array directly into the
3864 		 * correct destination, i.e. the attribute record itself.
3865 		 */
3866 		err = ntfs_mapping_pairs_build(ni->vol,
3867 				(u8 *)a + le16_to_cpu(a->data.non_resident.mapping_pairs_offset),
3868 				mp_size, start_rl, stop_vcn, -1, &stop_vcn, &start_rl, &de_cnt);
3869 		if (!err)
3870 			finished_build = true;
3871 		if (!finished_build && err != -ENOSPC) {
3872 			ntfs_error(sb, "Failed to build mapping pairs");
3873 			goto put_err_out;
3874 		}
3875 		a->data.non_resident.highest_vcn = cpu_to_le64(stop_vcn - 1);
3876 		mark_mft_record_dirty(ctx->ntfs_ino);
3877 		de_cluster_count += de_cnt;
3878 	}
3879 
3880 	/* Check whether error occurred. */
3881 	if (err && err != -ENOENT) {
3882 		ntfs_error(sb, "%s: Attribute lookup failed", __func__);
3883 		goto put_err_out;
3884 	}
3885 
3886 	/*
3887 	 * If the base extent was skipped in the above process,
3888 	 * we still may have to update the sizes.
3889 	 */
3890 	if (!first_updated) {
3891 		ntfs_attr_reinit_search_ctx(ctx);
3892 		err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
3893 				CASE_SENSITIVE, 0, NULL, 0, ctx);
3894 		if (!err) {
3895 			a = ctx->attr;
3896 			a->data.non_resident.allocated_size = cpu_to_le64(ni->allocated_size);
3897 			if (NInoCompressed(ni) || NInoSparse(ni))
3898 				a->data.non_resident.compressed_size =
3899 					cpu_to_le64(ni->itype.compressed.size);
3900 			/* Updating sizes taints the extent holding the attr */
3901 			if (ni->type == AT_DATA && ni->name == AT_UNNAMED)
3902 				NInoSetFileNameDirty(ni);
3903 			mark_mft_record_dirty(ctx->ntfs_ino);
3904 		} else {
3905 			ntfs_error(sb, "Failed to update sizes in base extent\n");
3906 			goto put_err_out;
3907 		}
3908 	}
3909 
3910 	/* Deallocate not used attribute extents and return with success. */
3911 	if (finished_build) {
3912 		ntfs_attr_reinit_search_ctx(ctx);
3913 		ntfs_debug("Deallocate marked extents.\n");
3914 		while (!(err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
3915 				CASE_SENSITIVE, 0, NULL, 0, ctx))) {
3916 			if (le64_to_cpu(ctx->attr->data.non_resident.highest_vcn) !=
3917 					NTFS_VCN_DELETE_MARK)
3918 				continue;
3919 			/* Remove unused attribute record. */
3920 			err = ntfs_attr_record_rm(ctx);
3921 			if (err) {
3922 				ntfs_error(sb, "Could not remove unused attr");
3923 				goto put_err_out;
3924 			}
3925 			ntfs_attr_reinit_search_ctx(ctx);
3926 		}
3927 		if (err && err != -ENOENT) {
3928 			ntfs_error(sb, "%s: Attr lookup failed", __func__);
3929 			goto put_err_out;
3930 		}
3931 		ntfs_debug("Deallocate done.\n");
3932 		ntfs_attr_put_search_ctx(ctx);
3933 		goto out;
3934 	}
3935 	ntfs_attr_put_search_ctx(ctx);
3936 	ctx = NULL;
3937 
3938 	/* Allocate new MFT records for the rest of mapping pairs. */
3939 	while (1) {
3940 		struct ntfs_inode *ext_ni = NULL;
3941 		unsigned int de_cnt = 0;
3942 
3943 		/* Allocate new mft record. */
3944 		err = ntfs_mft_record_alloc(ni->vol, 0, &ext_ni, base_ni, NULL);
3945 		if (err) {
3946 			ntfs_error(sb, "Failed to allocate extent record");
3947 			goto put_err_out;
3948 		}
3949 		unmap_mft_record(ext_ni);
3950 
3951 		m = map_mft_record(ext_ni);
3952 		if (IS_ERR(m)) {
3953 			ntfs_error(sb, "Could not map new MFT record");
3954 			if (ntfs_mft_record_free(ni->vol, ext_ni))
3955 				ntfs_error(sb, "Could not free MFT record");
3956 			ntfs_inode_close(ext_ni);
3957 			err = -ENOMEM;
3958 			ext_ni = NULL;
3959 			goto put_err_out;
3960 		}
3961 		/*
3962 		 * If mapping size exceed available space, set them to
3963 		 * possible maximum.
3964 		 */
3965 		cur_max_mp_size = le32_to_cpu(m->bytes_allocated) -
3966 			le32_to_cpu(m->bytes_in_use) -
3967 			(sizeof(struct attr_record) +
3968 			 ((NInoCompressed(ni) || NInoSparse(ni)) ?
3969 			  sizeof(a->data.non_resident.compressed_size) : 0)) -
3970 			((sizeof(__le16) * ni->name_len + 7) & ~7);
3971 
3972 		/* Calculate size of rest mapping pairs. */
3973 		mp_size = ntfs_get_size_for_mapping_pairs(ni->vol,
3974 				start_rl, stop_vcn, -1, cur_max_mp_size);
3975 		if (mp_size <= 0) {
3976 			unmap_mft_record(ext_ni);
3977 			ntfs_inode_close(ext_ni);
3978 			err = mp_size;
3979 			ntfs_error(sb, "%s: get mp size failed", __func__);
3980 			goto put_err_out;
3981 		}
3982 
3983 		if (mp_size > cur_max_mp_size)
3984 			mp_size = cur_max_mp_size;
3985 		/* Add attribute extent to new record. */
3986 		err = ntfs_non_resident_attr_record_add(ext_ni, ni->type,
3987 				ni->name, ni->name_len, stop_vcn, mp_size, 0);
3988 		if (err < 0) {
3989 			ntfs_error(sb, "Could not add attribute extent");
3990 			unmap_mft_record(ext_ni);
3991 			if (ntfs_mft_record_free(ni->vol, ext_ni))
3992 				ntfs_error(sb, "Could not free MFT record");
3993 			ntfs_inode_close(ext_ni);
3994 			goto put_err_out;
3995 		}
3996 		a = (struct attr_record *)((u8 *)m + err);
3997 
3998 		err = ntfs_mapping_pairs_build(ni->vol, (u8 *)a +
3999 				le16_to_cpu(a->data.non_resident.mapping_pairs_offset),
4000 				mp_size, start_rl, stop_vcn, -1, &stop_vcn, &start_rl,
4001 				&de_cnt);
4002 		if (err < 0 && err != -ENOSPC) {
4003 			ntfs_error(sb, "Failed to build MP");
4004 			unmap_mft_record(ext_ni);
4005 			if (ntfs_mft_record_free(ni->vol, ext_ni))
4006 				ntfs_error(sb, "Couldn't free MFT record");
4007 			goto put_err_out;
4008 		}
4009 		a->data.non_resident.highest_vcn = cpu_to_le64(stop_vcn - 1);
4010 		mark_mft_record_dirty(ext_ni);
4011 		unmap_mft_record(ext_ni);
4012 
4013 		de_cluster_count += de_cnt;
4014 		/* All mapping pairs has been written. */
4015 		if (!err)
4016 			break;
4017 	}
4018 out:
4019 	if (from_vcn == 0)
4020 		ni->i_dealloc_clusters = de_cluster_count;
4021 	return 0;
4022 
4023 put_err_out:
4024 	if (ctx)
4025 		ntfs_attr_put_search_ctx(ctx);
4026 	return err;
4027 }
4028 
4029 /*
4030  * ntfs_attr_make_resident - convert a non-resident to a resident attribute
4031  * @ni:		open ntfs attribute to make resident
4032  * @ctx:	ntfs search context describing the attribute
4033  *
4034  * Convert a non-resident ntfs attribute to a resident one.
4035  */
4036 static int ntfs_attr_make_resident(struct ntfs_inode *ni, struct ntfs_attr_search_ctx *ctx)
4037 {
4038 	struct ntfs_volume *vol = ni->vol;
4039 	struct super_block *sb = vol->sb;
4040 	struct attr_record *a = ctx->attr;
4041 	int name_ofs, val_ofs, err;
4042 	s64 arec_size;
4043 
4044 	ntfs_debug("Entering for inode 0x%llx, attr 0x%x.\n",
4045 			(unsigned long long)ni->mft_no, ni->type);
4046 
4047 	/* Should be called for the first extent of the attribute. */
4048 	if (le64_to_cpu(a->data.non_resident.lowest_vcn)) {
4049 		ntfs_debug("Eeek!  Should be called for the first extent of the attribute.  Aborting...\n");
4050 		return -EINVAL;
4051 	}
4052 
4053 	/* Some preliminary sanity checking. */
4054 	if (!NInoNonResident(ni)) {
4055 		ntfs_debug("Eeek!  Trying to make resident attribute resident. Aborting...\n");
4056 		return -EINVAL;
4057 	}
4058 
4059 	/* Make sure this is not $MFT/$BITMAP or Windows will not boot! */
4060 	if (ni->type == AT_BITMAP && ni->mft_no == FILE_MFT)
4061 		return -EPERM;
4062 
4063 	/* Check that the attribute is allowed to be resident. */
4064 	err = ntfs_attr_can_be_resident(vol, ni->type);
4065 	if (err)
4066 		return err;
4067 
4068 	if (NInoCompressed(ni) || NInoEncrypted(ni)) {
4069 		ntfs_debug("Making compressed or encrypted files resident is not implemented yet.\n");
4070 		return -EOPNOTSUPP;
4071 	}
4072 
4073 	/* Work out offsets into and size of the resident attribute. */
4074 	name_ofs = 24; /* = sizeof(resident_struct attr_record); */
4075 	val_ofs = (name_ofs + a->name_length * sizeof(__le16) + 7) & ~7;
4076 	arec_size = (val_ofs + ni->data_size + 7) & ~7;
4077 
4078 	/* Sanity check the size before we start modifying the attribute. */
4079 	if (le32_to_cpu(ctx->mrec->bytes_in_use) - le32_to_cpu(a->length) +
4080 	    arec_size > le32_to_cpu(ctx->mrec->bytes_allocated)) {
4081 		ntfs_debug("Not enough space to make attribute resident\n");
4082 		return -ENOSPC;
4083 	}
4084 
4085 	/* Read and cache the whole runlist if not already done. */
4086 	err = ntfs_attr_map_whole_runlist(ni);
4087 	if (err)
4088 		return err;
4089 
4090 	/* Move the attribute name if it exists and update the offset. */
4091 	if (a->name_length) {
4092 		memmove((u8 *)a + name_ofs, (u8 *)a + le16_to_cpu(a->name_offset),
4093 				a->name_length * sizeof(__le16));
4094 	}
4095 	a->name_offset = cpu_to_le16(name_ofs);
4096 
4097 	/* Resize the resident part of the attribute record. */
4098 	if (ntfs_attr_record_resize(ctx->mrec, a, arec_size) < 0) {
4099 		/*
4100 		 * Bug, because ntfs_attr_record_resize should not fail (we
4101 		 * already checked that attribute fits MFT record).
4102 		 */
4103 		ntfs_error(ctx->ntfs_ino->vol->sb, "BUG! Failed to resize attribute record. ");
4104 		return -EIO;
4105 	}
4106 
4107 	/* Convert the attribute record to describe a resident attribute. */
4108 	a->non_resident = 0;
4109 	a->flags = 0;
4110 	a->data.resident.value_length = cpu_to_le32(ni->data_size);
4111 	a->data.resident.value_offset = cpu_to_le16(val_ofs);
4112 	/*
4113 	 * File names cannot be non-resident so we would never see this here
4114 	 * but at least it serves as a reminder that there may be attributes
4115 	 * for which we do need to set this flag. (AIA)
4116 	 */
4117 	if (a->type == AT_FILE_NAME)
4118 		a->data.resident.flags = RESIDENT_ATTR_IS_INDEXED;
4119 	else
4120 		a->data.resident.flags = 0;
4121 	a->data.resident.reserved = 0;
4122 
4123 	/*
4124 	 * Deallocate clusters from the runlist.
4125 	 *
4126 	 * NOTE: We can use ntfs_cluster_free() because we have already mapped
4127 	 * the whole run list and thus it doesn't matter that the attribute
4128 	 * record is in a transiently corrupted state at this moment in time.
4129 	 */
4130 	err = ntfs_cluster_free(ni, 0, -1, ctx);
4131 	if (err) {
4132 		ntfs_error(sb, "Eeek! Failed to release allocated clusters");
4133 		ntfs_debug("Ignoring error and leaving behind wasted clusters.\n");
4134 	}
4135 
4136 	/* Throw away the now unused runlist. */
4137 	kvfree(ni->runlist.rl);
4138 	ni->runlist.rl = NULL;
4139 	ni->runlist.count = 0;
4140 	/* Update in-memory struct ntfs_attr. */
4141 	NInoClearNonResident(ni);
4142 	NInoClearCompressed(ni);
4143 	ni->flags &= ~FILE_ATTR_COMPRESSED;
4144 	NInoClearSparse(ni);
4145 	ni->flags &= ~FILE_ATTR_SPARSE_FILE;
4146 	NInoClearEncrypted(ni);
4147 	ni->flags &= ~FILE_ATTR_ENCRYPTED;
4148 	ni->initialized_size = ni->data_size;
4149 	ni->allocated_size = ni->itype.compressed.size = (ni->data_size + 7) & ~7;
4150 	ni->itype.compressed.block_size = 0;
4151 	ni->itype.compressed.block_size_bits = ni->itype.compressed.block_clusters = 0;
4152 	return 0;
4153 }
4154 
4155 /*
4156  * ntfs_non_resident_attr_shrink - shrink a non-resident, open ntfs attribute
4157  * @ni:		non-resident ntfs attribute to shrink
4158  * @newsize:	new size (in bytes) to which to shrink the attribute
4159  *
4160  * Reduce the size of a non-resident, open ntfs attribute @na to @newsize bytes.
4161  */
4162 static int ntfs_non_resident_attr_shrink(struct ntfs_inode *ni, const s64 newsize)
4163 {
4164 	struct ntfs_volume *vol;
4165 	struct ntfs_attr_search_ctx *ctx;
4166 	s64 first_free_vcn;
4167 	s64 nr_freed_clusters;
4168 	int err;
4169 	struct ntfs_inode *base_ni;
4170 
4171 	ntfs_debug("Inode 0x%llx attr 0x%x new size %lld\n",
4172 		(unsigned long long)ni->mft_no, ni->type, (long long)newsize);
4173 
4174 	vol = ni->vol;
4175 
4176 	if (NInoAttr(ni))
4177 		base_ni = ni->ext.base_ntfs_ino;
4178 	else
4179 		base_ni = ni;
4180 
4181 	/*
4182 	 * Check the attribute type and the corresponding minimum size
4183 	 * against @newsize and fail if @newsize is too small.
4184 	 */
4185 	err = ntfs_attr_size_bounds_check(vol, ni->type, newsize);
4186 	if (err) {
4187 		if (err == -ERANGE)
4188 			ntfs_debug("Eeek! Size bounds check failed. Aborting...\n");
4189 		else if (err == -ENOENT)
4190 			err = -EIO;
4191 		return err;
4192 	}
4193 
4194 	/* The first cluster outside the new allocation. */
4195 	if (NInoCompressed(ni))
4196 		/*
4197 		 * For compressed files we must keep full compressions blocks,
4198 		 * but currently we do not decompress/recompress the last
4199 		 * block to truncate the data, so we may leave more allocated
4200 		 * clusters than really needed.
4201 		 */
4202 		first_free_vcn = ntfs_bytes_to_cluster(vol,
4203 				((newsize - 1) | (ni->itype.compressed.block_size - 1)) + 1);
4204 	else
4205 		first_free_vcn =
4206 			ntfs_bytes_to_cluster(vol, newsize + vol->cluster_size - 1);
4207 
4208 	if (first_free_vcn < 0)
4209 		return -EINVAL;
4210 	/*
4211 	 * Compare the new allocation with the old one and only deallocate
4212 	 * clusters if there is a change.
4213 	 */
4214 	if (ntfs_bytes_to_cluster(vol, ni->allocated_size) != first_free_vcn) {
4215 		struct ntfs_attr_search_ctx *ctx;
4216 
4217 		err = ntfs_attr_map_whole_runlist(ni);
4218 		if (err) {
4219 			ntfs_debug("Eeek! ntfs_attr_map_whole_runlist failed.\n");
4220 			return err;
4221 		}
4222 
4223 		ctx = ntfs_attr_get_search_ctx(ni, NULL);
4224 		if (!ctx) {
4225 			ntfs_error(vol->sb, "%s: Failed to get search context", __func__);
4226 			return -ENOMEM;
4227 		}
4228 
4229 		/* Deallocate all clusters starting with the first free one. */
4230 		nr_freed_clusters = ntfs_cluster_free(ni, first_free_vcn, -1, ctx);
4231 		if (nr_freed_clusters < 0) {
4232 			ntfs_debug("Eeek! Freeing of clusters failed. Aborting...\n");
4233 			ntfs_attr_put_search_ctx(ctx);
4234 			return (int)nr_freed_clusters;
4235 		}
4236 		ntfs_attr_put_search_ctx(ctx);
4237 
4238 		/* Truncate the runlist itself. */
4239 		if (ntfs_rl_truncate_nolock(vol, &ni->runlist, first_free_vcn)) {
4240 			/*
4241 			 * Failed to truncate the runlist, so just throw it
4242 			 * away, it will be mapped afresh on next use.
4243 			 */
4244 			kvfree(ni->runlist.rl);
4245 			ni->runlist.rl = NULL;
4246 			ntfs_error(vol->sb, "Eeek! Run list truncation failed.\n");
4247 			return -EIO;
4248 		}
4249 
4250 		/* Prepare to mapping pairs update. */
4251 		ni->allocated_size = ntfs_cluster_to_bytes(vol, first_free_vcn);
4252 
4253 		if (NInoSparse(ni) || NInoCompressed(ni)) {
4254 			if (nr_freed_clusters) {
4255 				ni->itype.compressed.size -=
4256 					ntfs_cluster_to_bytes(vol, nr_freed_clusters);
4257 				VFS_I(base_ni)->i_blocks = ni->itype.compressed.size >> 9;
4258 			}
4259 		} else
4260 			VFS_I(base_ni)->i_blocks = ni->allocated_size >> 9;
4261 
4262 		/* Write mapping pairs for new runlist. */
4263 		err = ntfs_attr_update_mapping_pairs(ni, 0 /*first_free_vcn*/);
4264 		if (err) {
4265 			ntfs_debug("Eeek! Mapping pairs update failed. Leaving inconstant metadata. Run chkdsk.\n");
4266 			return err;
4267 		}
4268 	}
4269 
4270 	/* Get the first attribute record. */
4271 	ctx = ntfs_attr_get_search_ctx(base_ni, NULL);
4272 	if (!ctx) {
4273 		ntfs_error(vol->sb, "%s: Failed to get search context", __func__);
4274 		return -ENOMEM;
4275 	}
4276 
4277 	err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len, CASE_SENSITIVE,
4278 				0, NULL, 0, ctx);
4279 	if (err) {
4280 		if (err == -ENOENT)
4281 			err = -EIO;
4282 		ntfs_debug("Eeek! Lookup of first attribute extent failed. Leaving inconstant metadata.\n");
4283 		goto put_err_out;
4284 	}
4285 
4286 	/* Update data and initialized size. */
4287 	ni->data_size = newsize;
4288 	ctx->attr->data.non_resident.data_size = cpu_to_le64(newsize);
4289 	if (newsize < ni->initialized_size) {
4290 		ni->initialized_size = newsize;
4291 		ctx->attr->data.non_resident.initialized_size = cpu_to_le64(newsize);
4292 	}
4293 	/* Update data size in the index. */
4294 	if (ni->type == AT_DATA && ni->name == AT_UNNAMED)
4295 		NInoSetFileNameDirty(ni);
4296 
4297 	/* If the attribute now has zero size, make it resident. */
4298 	if (!newsize && !NInoEncrypted(ni) && !NInoCompressed(ni)) {
4299 		err = ntfs_attr_make_resident(ni, ctx);
4300 		if (err) {
4301 			/* If couldn't make resident, just continue. */
4302 			if (err != -EPERM)
4303 				ntfs_error(ni->vol->sb,
4304 					"Failed to make attribute resident. Leaving as is...\n");
4305 		}
4306 	}
4307 
4308 	/* Set the inode dirty so it is written out later. */
4309 	mark_mft_record_dirty(ctx->ntfs_ino);
4310 	/* Done! */
4311 	ntfs_attr_put_search_ctx(ctx);
4312 	return 0;
4313 put_err_out:
4314 	ntfs_attr_put_search_ctx(ctx);
4315 	return err;
4316 }
4317 
4318 /*
4319  * ntfs_non_resident_attr_expand - expand a non-resident, open ntfs attribute
4320  * @ni:			non-resident ntfs attribute to expand
4321  * @prealloc_size:	preallocation size (in bytes) to which to expand the attribute
4322  * @newsize:		new size (in bytes) to which to expand the attribute
4323  * @holes:		how to create a hole if expanding
4324  * @need_lock:		whether mrec lock is needed or not
4325  *
4326  * Expand the size of a non-resident, open ntfs attribute @na to @newsize bytes,
4327  * by allocating new clusters.
4328  */
4329 static int ntfs_non_resident_attr_expand(struct ntfs_inode *ni, const s64 newsize,
4330 		const s64 prealloc_size, unsigned int holes, bool need_lock)
4331 {
4332 	s64 lcn_seek_from;
4333 	s64 first_free_vcn;
4334 	struct ntfs_volume *vol;
4335 	struct ntfs_attr_search_ctx *ctx = NULL;
4336 	struct runlist_element *rl, *rln;
4337 	s64 org_alloc_size, org_compressed_size;
4338 	int err, err2;
4339 	struct ntfs_inode *base_ni;
4340 	struct super_block *sb = ni->vol->sb;
4341 	size_t new_rl_count;
4342 
4343 	ntfs_debug("Inode 0x%llx, attr 0x%x, new size %lld old size %lld\n",
4344 			(unsigned long long)ni->mft_no, ni->type,
4345 			(long long)newsize, (long long)ni->data_size);
4346 
4347 	vol = ni->vol;
4348 
4349 	if (NInoAttr(ni))
4350 		base_ni = ni->ext.base_ntfs_ino;
4351 	else
4352 		base_ni = ni;
4353 
4354 	/*
4355 	 * Check the attribute type and the corresponding maximum size
4356 	 * against @newsize and fail if @newsize is too big.
4357 	 */
4358 	err = ntfs_attr_size_bounds_check(vol, ni->type, newsize);
4359 	if (err	< 0) {
4360 		ntfs_error(sb, "%s: bounds check failed", __func__);
4361 		return err;
4362 	}
4363 
4364 	/* Save for future use. */
4365 	org_alloc_size = ni->allocated_size;
4366 	org_compressed_size = ni->itype.compressed.size;
4367 
4368 	/* The first cluster outside the new allocation. */
4369 	if (prealloc_size)
4370 		first_free_vcn =
4371 			ntfs_bytes_to_cluster(vol, prealloc_size + vol->cluster_size - 1);
4372 	else
4373 		first_free_vcn =
4374 			ntfs_bytes_to_cluster(vol, newsize + vol->cluster_size - 1);
4375 	if (first_free_vcn < 0)
4376 		return -EFBIG;
4377 
4378 	/*
4379 	 * Compare the new allocation with the old one and only allocate
4380 	 * clusters if there is a change.
4381 	 */
4382 	if (ntfs_bytes_to_cluster(vol, ni->allocated_size) < first_free_vcn) {
4383 		err = ntfs_attr_map_whole_runlist(ni);
4384 		if (err) {
4385 			ntfs_error(sb, "ntfs_attr_map_whole_runlist failed");
4386 			return err;
4387 		}
4388 
4389 		/*
4390 		 * If we extend $DATA attribute on NTFS 3+ volume, we can add
4391 		 * sparse runs instead of real allocation of clusters.
4392 		 */
4393 		if ((ni->type == AT_DATA && (vol->major_ver >= 3 || !NInoSparseDisabled(ni))) &&
4394 		    (holes != HOLES_NO)) {
4395 			if (NInoCompressed(ni)) {
4396 				int last = 0, i = 0;
4397 				s64 alloc_size;
4398 				u64 more_entries = round_up(first_free_vcn -
4399 						 ntfs_bytes_to_cluster(vol, ni->allocated_size),
4400 						 ni->itype.compressed.block_clusters);
4401 
4402 				do_div(more_entries, ni->itype.compressed.block_clusters);
4403 
4404 				while (ni->runlist.rl[last].length)
4405 					last++;
4406 
4407 				rl = ntfs_rl_realloc(ni->runlist.rl, last + 1,
4408 						last + more_entries + 1);
4409 				if (IS_ERR(rl)) {
4410 					err = -ENOMEM;
4411 					goto put_err_out;
4412 				}
4413 
4414 				alloc_size = ni->allocated_size;
4415 				while (i++ < more_entries) {
4416 					rl[last].vcn = ntfs_bytes_to_cluster(vol,
4417 							round_up(alloc_size, vol->cluster_size));
4418 					rl[last].length = ni->itype.compressed.block_clusters -
4419 						(rl[last].vcn &
4420 						 (ni->itype.compressed.block_clusters - 1));
4421 					rl[last].lcn = LCN_HOLE;
4422 					last++;
4423 					alloc_size += ni->itype.compressed.block_size;
4424 				}
4425 
4426 				rl[last].vcn = first_free_vcn;
4427 				rl[last].lcn = LCN_ENOENT;
4428 				rl[last].length = 0;
4429 
4430 				ni->runlist.rl = rl;
4431 				ni->runlist.count += more_entries;
4432 			} else {
4433 				rl = kmalloc(sizeof(struct runlist_element) * 2, GFP_NOFS);
4434 				if (!rl) {
4435 					err = -ENOMEM;
4436 					goto put_err_out;
4437 				}
4438 
4439 				rl[0].vcn = ntfs_bytes_to_cluster(vol, ni->allocated_size);
4440 				rl[0].lcn = LCN_HOLE;
4441 				rl[0].length = first_free_vcn -
4442 					ntfs_bytes_to_cluster(vol, ni->allocated_size);
4443 				rl[1].vcn = first_free_vcn;
4444 				rl[1].lcn = LCN_ENOENT;
4445 				rl[1].length = 0;
4446 			}
4447 		} else {
4448 			/*
4449 			 * Determine first after last LCN of attribute.
4450 			 * We will start seek clusters from this LCN to avoid
4451 			 * fragmentation.  If there are no valid LCNs in the
4452 			 * attribute let the cluster allocator choose the
4453 			 * starting LCN.
4454 			 */
4455 			lcn_seek_from = -1;
4456 			if (ni->runlist.rl->length) {
4457 				/* Seek to the last run list element. */
4458 				for (rl = ni->runlist.rl; (rl + 1)->length; rl++)
4459 					;
4460 				/*
4461 				 * If the last LCN is a hole or similar seek
4462 				 * back to last valid LCN.
4463 				 */
4464 				while (rl->lcn < 0 && rl != ni->runlist.rl)
4465 					rl--;
4466 				/*
4467 				 * Only set lcn_seek_from it the LCN is valid.
4468 				 */
4469 				if (rl->lcn >= 0)
4470 					lcn_seek_from = rl->lcn + rl->length;
4471 			}
4472 
4473 			rl = ntfs_cluster_alloc(vol,
4474 					ntfs_bytes_to_cluster(vol, ni->allocated_size),
4475 					first_free_vcn -
4476 					ntfs_bytes_to_cluster(vol, ni->allocated_size),
4477 					lcn_seek_from, DATA_ZONE, false, false, false);
4478 			if (IS_ERR(rl)) {
4479 				ntfs_debug("Cluster allocation failed (%lld)",
4480 						(long long)first_free_vcn -
4481 						ntfs_bytes_to_cluster(vol, ni->allocated_size));
4482 				return PTR_ERR(rl);
4483 			}
4484 		}
4485 
4486 		if (!NInoCompressed(ni)) {
4487 			/* Append new clusters to attribute runlist. */
4488 			rln = ntfs_runlists_merge(&ni->runlist, rl, 0, &new_rl_count);
4489 			if (IS_ERR(rln)) {
4490 				/* Failed, free just allocated clusters. */
4491 				ntfs_error(sb, "Run list merge failed");
4492 				ntfs_cluster_free_from_rl(vol, rl);
4493 				kvfree(rl);
4494 				return -EIO;
4495 			}
4496 			ni->runlist.rl = rln;
4497 			ni->runlist.count = new_rl_count;
4498 		}
4499 
4500 		/* Prepare to mapping pairs update. */
4501 		ni->allocated_size = ntfs_cluster_to_bytes(vol, first_free_vcn);
4502 		err = ntfs_attr_update_mapping_pairs(ni, 0);
4503 		if (err) {
4504 			ntfs_debug("Mapping pairs update failed");
4505 			goto rollback;
4506 		}
4507 	}
4508 
4509 	ctx = ntfs_attr_get_search_ctx(base_ni, NULL);
4510 	if (!ctx) {
4511 		err = -ENOMEM;
4512 		if (ni->allocated_size == org_alloc_size)
4513 			return err;
4514 		goto rollback;
4515 	}
4516 
4517 	err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len, CASE_SENSITIVE,
4518 			       0, NULL, 0, ctx);
4519 	if (err) {
4520 		if (err == -ENOENT)
4521 			err = -EIO;
4522 		if (ni->allocated_size != org_alloc_size)
4523 			goto rollback;
4524 		goto put_err_out;
4525 	}
4526 
4527 	/* Update data size. */
4528 	ni->data_size = newsize;
4529 	ctx->attr->data.non_resident.data_size = cpu_to_le64(newsize);
4530 	/* Update data size in the index. */
4531 	if (ni->type == AT_DATA && ni->name == AT_UNNAMED)
4532 		NInoSetFileNameDirty(ni);
4533 	/* Set the inode dirty so it is written out later. */
4534 	mark_mft_record_dirty(ctx->ntfs_ino);
4535 	/* Done! */
4536 	ntfs_attr_put_search_ctx(ctx);
4537 	return 0;
4538 rollback:
4539 	/* Free allocated clusters. */
4540 	err2 = ntfs_cluster_free(ni, ntfs_bytes_to_cluster(vol, org_alloc_size),
4541 				-1, ctx);
4542 	if (err2)
4543 		ntfs_debug("Leaking clusters");
4544 
4545 	/* Now, truncate the runlist itself. */
4546 	if (need_lock)
4547 		down_write(&ni->runlist.lock);
4548 	err2 = ntfs_rl_truncate_nolock(vol, &ni->runlist,
4549 			ntfs_bytes_to_cluster(vol, org_alloc_size));
4550 	if (need_lock)
4551 		up_write(&ni->runlist.lock);
4552 	if (err2) {
4553 		/*
4554 		 * Failed to truncate the runlist, so just throw it away, it
4555 		 * will be mapped afresh on next use.
4556 		 */
4557 		kvfree(ni->runlist.rl);
4558 		ni->runlist.rl = NULL;
4559 		ntfs_error(sb, "Couldn't truncate runlist. Rollback failed");
4560 	} else {
4561 		/* Prepare to mapping pairs update. */
4562 		ni->allocated_size = org_alloc_size;
4563 		/* Restore mapping pairs. */
4564 		if (need_lock)
4565 			down_read(&ni->runlist.lock);
4566 		if (ntfs_attr_update_mapping_pairs(ni, 0))
4567 			ntfs_error(sb, "Failed to restore old mapping pairs");
4568 		if (need_lock)
4569 			up_read(&ni->runlist.lock);
4570 
4571 		if (NInoSparse(ni) || NInoCompressed(ni)) {
4572 			ni->itype.compressed.size =  org_compressed_size;
4573 			VFS_I(base_ni)->i_blocks = ni->itype.compressed.size >> 9;
4574 		} else
4575 			VFS_I(base_ni)->i_blocks = ni->allocated_size >> 9;
4576 	}
4577 	if (ctx)
4578 		ntfs_attr_put_search_ctx(ctx);
4579 	return err;
4580 put_err_out:
4581 	if (ctx)
4582 		ntfs_attr_put_search_ctx(ctx);
4583 	return err;
4584 }
4585 
4586 /*
4587  * ntfs_resident_attr_resize - resize a resident, open ntfs attribute
4588  * @attr_ni:		resident ntfs inode to resize
4589  * @newsize:		new size (in bytes) to which to resize the attribute
4590  * @prealloc_size:	preallocation size (in bytes) to which to resize the attribute
4591  * @holes:		flags indicating how to handle holes
4592  *
4593  * Change the size of a resident, open ntfs attribute @na to @newsize bytes.
4594  */
4595 static int ntfs_resident_attr_resize(struct ntfs_inode *attr_ni, const s64 newsize,
4596 		const s64 prealloc_size, unsigned int holes)
4597 {
4598 	struct ntfs_attr_search_ctx *ctx;
4599 	struct ntfs_volume *vol = attr_ni->vol;
4600 	struct super_block *sb = vol->sb;
4601 	int err = -EIO;
4602 	struct ntfs_inode *base_ni, *ext_ni = NULL;
4603 
4604 attr_resize_again:
4605 	ntfs_debug("Inode 0x%llx attr 0x%x new size %lld\n",
4606 			(unsigned long long)attr_ni->mft_no, attr_ni->type,
4607 			(long long)newsize);
4608 
4609 	if (NInoAttr(attr_ni))
4610 		base_ni = attr_ni->ext.base_ntfs_ino;
4611 	else
4612 		base_ni = attr_ni;
4613 
4614 	/* Get the attribute record that needs modification. */
4615 	ctx = ntfs_attr_get_search_ctx(base_ni, NULL);
4616 	if (!ctx) {
4617 		ntfs_error(sb, "%s: Failed to get search context", __func__);
4618 		return -ENOMEM;
4619 	}
4620 
4621 	err = ntfs_attr_lookup(attr_ni->type, attr_ni->name, attr_ni->name_len,
4622 			0, 0, NULL, 0, ctx);
4623 	if (err) {
4624 		ntfs_error(sb, "ntfs_attr_lookup failed");
4625 		goto put_err_out;
4626 	}
4627 
4628 	/*
4629 	 * Check the attribute type and the corresponding minimum and maximum
4630 	 * sizes against @newsize and fail if @newsize is out of bounds.
4631 	 */
4632 	err = ntfs_attr_size_bounds_check(vol, attr_ni->type, newsize);
4633 	if (err) {
4634 		if (err == -ENOENT)
4635 			err = -EIO;
4636 		ntfs_debug("%s: bounds check failed", __func__);
4637 		goto put_err_out;
4638 	}
4639 	/*
4640 	 * If @newsize is bigger than the mft record we need to make the
4641 	 * attribute non-resident if the attribute type supports it. If it is
4642 	 * smaller we can go ahead and attempt the resize.
4643 	 */
4644 	if (newsize < vol->mft_record_size) {
4645 		/* Perform the resize of the attribute record. */
4646 		err = ntfs_resident_attr_value_resize(ctx->mrec, ctx->attr,
4647 					newsize);
4648 		if (!err) {
4649 			/* Update attribute size everywhere. */
4650 			attr_ni->data_size = attr_ni->initialized_size = newsize;
4651 			attr_ni->allocated_size = (newsize + 7) & ~7;
4652 			if (NInoCompressed(attr_ni) || NInoSparse(attr_ni))
4653 				attr_ni->itype.compressed.size = attr_ni->allocated_size;
4654 			if (attr_ni->type == AT_DATA && attr_ni->name == AT_UNNAMED)
4655 				NInoSetFileNameDirty(attr_ni);
4656 			goto resize_done;
4657 		}
4658 
4659 		/* Prefer AT_INDEX_ALLOCATION instead of AT_ATTRIBUTE_LIST */
4660 		if (err == -ENOSPC && ctx->attr->type == AT_INDEX_ROOT)
4661 			goto put_err_out;
4662 
4663 	}
4664 	/* There is not enough space in the mft record to perform the resize. */
4665 
4666 	/* Make the attribute non-resident if possible. */
4667 	err = ntfs_attr_make_non_resident(attr_ni,
4668 			le32_to_cpu(ctx->attr->data.resident.value_length));
4669 	if (!err) {
4670 		mark_mft_record_dirty(ctx->ntfs_ino);
4671 		ntfs_attr_put_search_ctx(ctx);
4672 		/* Resize non-resident attribute */
4673 		return ntfs_non_resident_attr_expand(attr_ni, newsize, prealloc_size, holes, true);
4674 	} else if (err != -ENOSPC && err != -EPERM) {
4675 		ntfs_error(sb, "Failed to make attribute non-resident");
4676 		goto put_err_out;
4677 	}
4678 
4679 	/* Try to make other attributes non-resident and retry each time. */
4680 	ntfs_attr_reinit_search_ctx(ctx);
4681 	while (!(err = ntfs_attr_lookup(AT_UNUSED, NULL, 0, 0, 0, NULL, 0, ctx))) {
4682 		struct inode *tvi;
4683 		struct attr_record *a;
4684 		u32 value_len;
4685 
4686 		a = ctx->attr;
4687 		if (a->non_resident || a->type == AT_ATTRIBUTE_LIST)
4688 			continue;
4689 		value_len = le32_to_cpu(a->data.resident.value_length);
4690 
4691 		if (ntfs_attr_can_be_non_resident(vol, a->type))
4692 			continue;
4693 
4694 		/*
4695 		 * Check out whether convert is reasonable. Assume that mapping
4696 		 * pairs will take 8 bytes.
4697 		 */
4698 		if (le32_to_cpu(a->length) <= (sizeof(struct attr_record) - sizeof(s64)) +
4699 				((a->name_length * sizeof(__le16) + 7) & ~7) + 8)
4700 			continue;
4701 		if (a->type == AT_DATA && !value_len)
4702 			continue;
4703 
4704 		if (a->type == AT_DATA)
4705 			tvi = ntfs_iget(sb, base_ni->mft_no);
4706 		else
4707 			tvi = ntfs_attr_iget(VFS_I(base_ni), a->type,
4708 				(__le16 *)((u8 *)a + le16_to_cpu(a->name_offset)),
4709 				a->name_length);
4710 		if (IS_ERR(tvi)) {
4711 			ntfs_error(sb, "Couldn't open attribute");
4712 			continue;
4713 		}
4714 
4715 		if (ntfs_attr_make_non_resident(NTFS_I(tvi), value_len)) {
4716 			iput(tvi);
4717 			continue;
4718 		}
4719 
4720 		mark_mft_record_dirty(ctx->ntfs_ino);
4721 		iput(tvi);
4722 		ntfs_attr_put_search_ctx(ctx);
4723 		goto attr_resize_again;
4724 	}
4725 
4726 	/* Check whether error occurred. */
4727 	if (err != -ENOENT) {
4728 		ntfs_error(sb, "%s: Attribute lookup failed 1", __func__);
4729 		goto put_err_out;
4730 	}
4731 
4732 	/*
4733 	 * The standard information and attribute list attributes can't be
4734 	 * moved out from the base MFT record, so try to move out others.
4735 	 */
4736 	if (attr_ni->type == AT_STANDARD_INFORMATION ||
4737 	    attr_ni->type == AT_ATTRIBUTE_LIST) {
4738 		ntfs_attr_put_search_ctx(ctx);
4739 
4740 		if (!NInoAttrList(base_ni)) {
4741 			err = ntfs_inode_add_attrlist(base_ni);
4742 			if (err)
4743 				return err;
4744 		}
4745 
4746 		err = ntfs_inode_free_space(base_ni, sizeof(struct attr_record));
4747 		if (err) {
4748 			err = -ENOSPC;
4749 			ntfs_error(sb,
4750 				"Couldn't free space in the MFT record to make attribute list non resident");
4751 			return err;
4752 		}
4753 		err = ntfs_attrlist_update(base_ni);
4754 		if (err)
4755 			return err;
4756 		goto attr_resize_again;
4757 	}
4758 
4759 	/*
4760 	 * Move the attribute to a new mft record, creating an attribute list
4761 	 * attribute or modifying it if it is already present.
4762 	 */
4763 
4764 	/* Point search context back to attribute which we need resize. */
4765 	ntfs_attr_reinit_search_ctx(ctx);
4766 	err = ntfs_attr_lookup(attr_ni->type, attr_ni->name, attr_ni->name_len,
4767 			CASE_SENSITIVE, 0, NULL, 0, ctx);
4768 	if (err) {
4769 		ntfs_error(sb, "%s: Attribute lookup failed 2", __func__);
4770 		goto put_err_out;
4771 	}
4772 
4773 	/*
4774 	 * Check whether attribute is already single in this MFT record.
4775 	 * 8 added for the attribute terminator.
4776 	 */
4777 	if (le32_to_cpu(ctx->mrec->bytes_in_use) ==
4778 	    le16_to_cpu(ctx->mrec->attrs_offset) + le32_to_cpu(ctx->attr->length) + 8) {
4779 		err = -ENOSPC;
4780 		ntfs_debug("MFT record is filled with one attribute\n");
4781 		goto put_err_out;
4782 	}
4783 
4784 	/* Add attribute list if not present. */
4785 	if (!NInoAttrList(base_ni)) {
4786 		ntfs_attr_put_search_ctx(ctx);
4787 		err = ntfs_inode_add_attrlist(base_ni);
4788 		if (err)
4789 			return err;
4790 		goto attr_resize_again;
4791 	}
4792 
4793 	/* Allocate new mft record. */
4794 	err = ntfs_mft_record_alloc(base_ni->vol, 0, &ext_ni, base_ni, NULL);
4795 	if (err) {
4796 		ntfs_error(sb, "Couldn't allocate MFT record");
4797 		goto put_err_out;
4798 	}
4799 	unmap_mft_record(ext_ni);
4800 
4801 	/* Move attribute to it. */
4802 	err = ntfs_attr_record_move_to(ctx, ext_ni);
4803 	if (err) {
4804 		ntfs_error(sb, "Couldn't move attribute to new MFT record");
4805 		err = -ENOMEM;
4806 		goto put_err_out;
4807 	}
4808 
4809 	err = ntfs_attrlist_update(base_ni);
4810 	if (err < 0)
4811 		goto put_err_out;
4812 
4813 	ntfs_attr_put_search_ctx(ctx);
4814 	/* Try to perform resize once again. */
4815 	goto attr_resize_again;
4816 
4817 resize_done:
4818 	/*
4819 	 * Set the inode (and its base inode if it exists) dirty so it is
4820 	 * written out later.
4821 	 */
4822 	mark_mft_record_dirty(ctx->ntfs_ino);
4823 	ntfs_attr_put_search_ctx(ctx);
4824 	return 0;
4825 
4826 put_err_out:
4827 	ntfs_attr_put_search_ctx(ctx);
4828 	return err;
4829 }
4830 
4831 int __ntfs_attr_truncate_vfs(struct ntfs_inode *ni, const s64 newsize,
4832 		const s64 i_size)
4833 {
4834 	int err = 0;
4835 
4836 	if (newsize < 0 ||
4837 	    (ni->mft_no == FILE_MFT && ni->type == AT_DATA)) {
4838 		ntfs_debug("Invalid arguments passed.\n");
4839 		return -EINVAL;
4840 	}
4841 
4842 	ntfs_debug("Entering for inode 0x%llx, attr 0x%x, size %lld\n",
4843 			(unsigned long long)ni->mft_no, ni->type, newsize);
4844 
4845 	if (NInoNonResident(ni)) {
4846 		if (newsize > i_size) {
4847 			down_write(&ni->runlist.lock);
4848 			err = ntfs_non_resident_attr_expand(ni, newsize, 0,
4849 							    NVolDisableSparse(ni->vol) ?
4850 							    HOLES_NO : HOLES_OK,
4851 							    false);
4852 			up_write(&ni->runlist.lock);
4853 		} else
4854 			err = ntfs_non_resident_attr_shrink(ni, newsize);
4855 	} else
4856 		err = ntfs_resident_attr_resize(ni, newsize, 0,
4857 						NVolDisableSparse(ni->vol) ?
4858 						HOLES_NO : HOLES_OK);
4859 	ntfs_debug("Return status %d\n", err);
4860 	return err;
4861 }
4862 
4863 int ntfs_attr_expand(struct ntfs_inode *ni, const s64 newsize, const s64 prealloc_size)
4864 {
4865 	int err = 0;
4866 
4867 	if (newsize < 0 ||
4868 	    (ni->mft_no == FILE_MFT && ni->type == AT_DATA)) {
4869 		ntfs_debug("Invalid arguments passed.\n");
4870 		return -EINVAL;
4871 	}
4872 
4873 	ntfs_debug("Entering for inode 0x%llx, attr 0x%x, size %lld\n",
4874 			(unsigned long long)ni->mft_no, ni->type, newsize);
4875 
4876 	if (ni->data_size == newsize) {
4877 		ntfs_debug("Size is already ok\n");
4878 		return 0;
4879 	}
4880 
4881 	/*
4882 	 * Encrypted attributes are not supported. We return access denied,
4883 	 * which is what Windows NT4 does, too.
4884 	 */
4885 	if (NInoEncrypted(ni)) {
4886 		pr_err("Failed to truncate encrypted attribute\n");
4887 		return -EACCES;
4888 	}
4889 
4890 	if (NInoNonResident(ni)) {
4891 		if (newsize > ni->data_size)
4892 			err = ntfs_non_resident_attr_expand(ni, newsize, prealloc_size,
4893 							    NVolDisableSparse(ni->vol) ?
4894 							    HOLES_NO : HOLES_OK, true);
4895 	} else
4896 		err = ntfs_resident_attr_resize(ni, newsize, prealloc_size,
4897 						NVolDisableSparse(ni->vol) ?
4898 						HOLES_NO : HOLES_OK);
4899 	if (!err)
4900 		i_size_write(VFS_I(ni), newsize);
4901 	ntfs_debug("Return status %d\n", err);
4902 	return err;
4903 }
4904 
4905 /*
4906  * ntfs_attr_truncate_i - resize an ntfs attribute
4907  * @ni:		open ntfs inode to resize
4908  * @newsize:	new size (in bytes) to which to resize the attribute
4909  * @holes:	how to create a hole if expanding
4910  *
4911  * Change the size of an open ntfs attribute @na to @newsize bytes. If the
4912  * attribute is made bigger and the attribute is resident the newly
4913  * "allocated" space is cleared and if the attribute is non-resident the
4914  * newly allocated space is marked as not initialised and no real allocation
4915  * on disk is performed.
4916  */
4917 int ntfs_attr_truncate_i(struct ntfs_inode *ni, const s64 newsize, unsigned int holes)
4918 {
4919 	int err;
4920 
4921 	if (newsize < 0 ||
4922 	    (ni->mft_no == FILE_MFT && ni->type == AT_DATA)) {
4923 		ntfs_debug("Invalid arguments passed.\n");
4924 		return -EINVAL;
4925 	}
4926 
4927 	ntfs_debug("Entering for inode 0x%llx, attr 0x%x, size %lld\n",
4928 			(unsigned long long)ni->mft_no, ni->type, newsize);
4929 
4930 	if (ni->data_size == newsize) {
4931 		ntfs_debug("Size is already ok\n");
4932 		return 0;
4933 	}
4934 
4935 	/*
4936 	 * Encrypted attributes are not supported. We return access denied,
4937 	 * which is what Windows NT4 does, too.
4938 	 */
4939 	if (NInoEncrypted(ni)) {
4940 		pr_err("Failed to truncate encrypted attribute\n");
4941 		return -EACCES;
4942 	}
4943 
4944 	if (NInoCompressed(ni)) {
4945 		pr_err("Failed to truncate compressed attribute\n");
4946 		return -EOPNOTSUPP;
4947 	}
4948 
4949 	if (NInoNonResident(ni)) {
4950 		if (newsize > ni->data_size)
4951 			err = ntfs_non_resident_attr_expand(ni, newsize, 0, holes, true);
4952 		else
4953 			err = ntfs_non_resident_attr_shrink(ni, newsize);
4954 	} else
4955 		err = ntfs_resident_attr_resize(ni, newsize, 0, holes);
4956 	ntfs_debug("Return status %d\n", err);
4957 	return err;
4958 }
4959 
4960 /*
4961  * Resize an attribute, creating a hole if relevant
4962  */
4963 int ntfs_attr_truncate(struct ntfs_inode *ni, const s64 newsize)
4964 {
4965 	return ntfs_attr_truncate_i(ni, newsize,
4966 				    NVolDisableSparse(ni->vol) ?
4967 				    HOLES_NO : HOLES_OK);
4968 }
4969 
4970 int ntfs_attr_map_cluster(struct ntfs_inode *ni, s64 vcn_start, s64 *lcn_start,
4971 		s64 *lcn_count, s64 max_clu_count, bool *balloc, bool update_mp,
4972 		bool skip_holes)
4973 {
4974 	struct ntfs_volume *vol = ni->vol;
4975 	struct ntfs_attr_search_ctx *ctx;
4976 	struct runlist_element *rl, *rlc;
4977 	s64 vcn = vcn_start, lcn, clu_count;
4978 	s64 lcn_seek_from = -1;
4979 	int err = 0;
4980 	size_t new_rl_count;
4981 
4982 	err = ntfs_attr_map_whole_runlist(ni);
4983 	if (err)
4984 		return err;
4985 
4986 	if (NInoAttr(ni))
4987 		ctx = ntfs_attr_get_search_ctx(ni->ext.base_ntfs_ino, NULL);
4988 	else
4989 		ctx = ntfs_attr_get_search_ctx(ni, NULL);
4990 	if (!ctx) {
4991 		ntfs_error(vol->sb, "%s: Failed to get search context", __func__);
4992 		return -ENOMEM;
4993 	}
4994 
4995 	err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
4996 			CASE_SENSITIVE, vcn, NULL, 0, ctx);
4997 	if (err) {
4998 		ntfs_error(vol->sb,
4999 			   "ntfs_attr_lookup failed, ntfs inode(mft_no : %llu) type : 0x%x, err : %d",
5000 			   ni->mft_no, ni->type, err);
5001 		goto out;
5002 	}
5003 
5004 	rl = ntfs_attr_find_vcn_nolock(ni, vcn, ctx);
5005 	if (IS_ERR(rl)) {
5006 		ntfs_error(vol->sb, "Failed to find run after mapping runlist.");
5007 		err = PTR_ERR(rl);
5008 		goto out;
5009 	}
5010 
5011 	lcn = ntfs_rl_vcn_to_lcn(rl, vcn);
5012 	clu_count = min(max_clu_count, rl->length - (vcn - rl->vcn));
5013 	if (lcn >= LCN_HOLE) {
5014 		if (lcn > LCN_DELALLOC ||
5015 		    (lcn == LCN_HOLE && skip_holes)) {
5016 			*lcn_start = lcn;
5017 			*lcn_count = clu_count;
5018 			*balloc = false;
5019 			goto out;
5020 		}
5021 	} else {
5022 		WARN_ON(lcn == LCN_RL_NOT_MAPPED);
5023 		if (lcn == LCN_ENOENT)
5024 			err = -ENOENT;
5025 		else
5026 			err = -EIO;
5027 		goto out;
5028 	}
5029 
5030 	/* Search backwards to find the best lcn to start seek from. */
5031 	rlc = rl;
5032 	while (rlc->vcn) {
5033 		rlc--;
5034 		if (rlc->lcn >= 0) {
5035 			/*
5036 			 * avoid fragmenting a compressed file
5037 			 * Windows does not do that, and that may
5038 			 * not be desirable for files which can
5039 			 * be updated
5040 			 */
5041 			if (NInoCompressed(ni))
5042 				lcn_seek_from = rlc->lcn + rlc->length;
5043 			else
5044 				lcn_seek_from = rlc->lcn + (vcn - rlc->vcn);
5045 			break;
5046 		}
5047 	}
5048 
5049 	if (lcn_seek_from == -1) {
5050 		/* Backwards search failed, search forwards. */
5051 		rlc = rl;
5052 		while (rlc->length) {
5053 			rlc++;
5054 			if (rlc->lcn >= 0) {
5055 				lcn_seek_from = rlc->lcn - (rlc->vcn - vcn);
5056 				if (lcn_seek_from < -1)
5057 					lcn_seek_from = -1;
5058 				break;
5059 			}
5060 		}
5061 	}
5062 
5063 	rlc = ntfs_cluster_alloc(vol, vcn, clu_count, lcn_seek_from, DATA_ZONE,
5064 			false, true, true);
5065 	if (IS_ERR(rlc)) {
5066 		err = PTR_ERR(rlc);
5067 		goto out;
5068 	}
5069 
5070 	WARN_ON(rlc->vcn != vcn);
5071 	lcn = rlc->lcn;
5072 	clu_count = rlc->length;
5073 
5074 	rl = ntfs_runlists_merge(&ni->runlist, rlc, 0, &new_rl_count);
5075 	if (IS_ERR(rl)) {
5076 		ntfs_error(vol->sb, "Failed to merge runlists");
5077 		err = PTR_ERR(rl);
5078 		if (ntfs_cluster_free_from_rl(vol, rlc))
5079 			ntfs_error(vol->sb, "Failed to free hot clusters.");
5080 		kvfree(rlc);
5081 		goto out;
5082 	}
5083 	ni->runlist.rl = rl;
5084 	ni->runlist.count = new_rl_count;
5085 
5086 	if (!update_mp) {
5087 		u64 free = atomic64_read(&vol->free_clusters) * 100;
5088 
5089 		do_div(free, vol->nr_clusters);
5090 		if (free <= 5)
5091 			update_mp = true;
5092 	}
5093 
5094 	if (update_mp) {
5095 		ntfs_attr_reinit_search_ctx(ctx);
5096 		err = ntfs_attr_update_mapping_pairs(ni, 0);
5097 		if (err) {
5098 			int err2;
5099 
5100 			err2 = ntfs_cluster_free(ni, vcn, clu_count, ctx);
5101 			if (err2 < 0)
5102 				ntfs_error(vol->sb,
5103 					   "Failed to free cluster allocation. Leaving inconstant metadata.\n");
5104 			goto out;
5105 		}
5106 	} else {
5107 		VFS_I(ni)->i_blocks += clu_count << (vol->cluster_size_bits - 9);
5108 		NInoSetRunlistDirty(ni);
5109 		mark_mft_record_dirty(ni);
5110 	}
5111 
5112 	*lcn_start = lcn;
5113 	*lcn_count = clu_count;
5114 	*balloc = true;
5115 out:
5116 	ntfs_attr_put_search_ctx(ctx);
5117 	return err;
5118 }
5119 
5120 /*
5121  * ntfs_attr_rm - remove attribute from ntfs inode
5122  * @ni:		opened ntfs attribute to delete
5123  *
5124  * Remove attribute and all it's extents from ntfs inode. If attribute was non
5125  * resident also free all clusters allocated by attribute.
5126  */
5127 int ntfs_attr_rm(struct ntfs_inode *ni)
5128 {
5129 	struct ntfs_attr_search_ctx *ctx;
5130 	int err = 0, ret = 0;
5131 	struct ntfs_inode *base_ni;
5132 	struct super_block *sb = ni->vol->sb;
5133 
5134 	if (NInoAttr(ni))
5135 		base_ni = ni->ext.base_ntfs_ino;
5136 	else
5137 		base_ni = ni;
5138 
5139 	ntfs_debug("Entering for inode 0x%llx, attr 0x%x.\n",
5140 			(long long) ni->mft_no, ni->type);
5141 
5142 	/* Free cluster allocation. */
5143 	if (NInoNonResident(ni)) {
5144 		struct ntfs_attr_search_ctx *ctx;
5145 
5146 		err = ntfs_attr_map_whole_runlist(ni);
5147 		if (err)
5148 			return err;
5149 		ctx = ntfs_attr_get_search_ctx(ni, NULL);
5150 		if (!ctx) {
5151 			ntfs_error(sb, "%s: Failed to get search context", __func__);
5152 			return -ENOMEM;
5153 		}
5154 
5155 		ret = ntfs_cluster_free(ni, 0, -1, ctx);
5156 		if (ret < 0)
5157 			ntfs_error(sb,
5158 				"Failed to free cluster allocation. Leaving inconstant metadata.\n");
5159 		ntfs_attr_put_search_ctx(ctx);
5160 	}
5161 
5162 	/* Search for attribute extents and remove them all. */
5163 	ctx = ntfs_attr_get_search_ctx(base_ni, NULL);
5164 	if (!ctx) {
5165 		ntfs_error(sb, "%s: Failed to get search context", __func__);
5166 		return -ENOMEM;
5167 	}
5168 	while (!(err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
5169 				CASE_SENSITIVE, 0, NULL, 0, ctx))) {
5170 		err = ntfs_attr_record_rm(ctx);
5171 		if (err) {
5172 			ntfs_error(sb,
5173 				"Failed to remove attribute extent. Leaving inconstant metadata.\n");
5174 			ret = err;
5175 		}
5176 		ntfs_attr_reinit_search_ctx(ctx);
5177 	}
5178 	ntfs_attr_put_search_ctx(ctx);
5179 	if (err != -ENOENT) {
5180 		ntfs_error(sb, "Attribute lookup failed. Probably leaving inconstant metadata.\n");
5181 		ret = err;
5182 	}
5183 
5184 	return ret;
5185 }
5186 
5187 int ntfs_attr_exist(struct ntfs_inode *ni, const __le32 type, __le16 *name,
5188 		u32 name_len)
5189 {
5190 	struct ntfs_attr_search_ctx *ctx;
5191 	int ret;
5192 
5193 	ntfs_debug("Entering\n");
5194 
5195 	ctx = ntfs_attr_get_search_ctx(ni, NULL);
5196 	if (!ctx) {
5197 		ntfs_error(ni->vol->sb, "%s: Failed to get search context",
5198 				__func__);
5199 		return 0;
5200 	}
5201 
5202 	ret = ntfs_attr_lookup(type, name, name_len, CASE_SENSITIVE,
5203 			0, NULL, 0, ctx);
5204 	ntfs_attr_put_search_ctx(ctx);
5205 
5206 	return !ret;
5207 }
5208 
5209 int ntfs_attr_remove(struct ntfs_inode *ni, const __le32 type, __le16 *name,
5210 		u32 name_len)
5211 {
5212 	int err;
5213 	struct inode *attr_vi;
5214 	struct ntfs_inode *attr_ni;
5215 
5216 	ntfs_debug("Entering\n");
5217 
5218 	if (!ni)
5219 		return -EINVAL;
5220 
5221 	attr_vi = ntfs_attr_iget(VFS_I(ni), type, name, name_len);
5222 	if (IS_ERR(attr_vi)) {
5223 		err = PTR_ERR(attr_vi);
5224 		ntfs_error(ni->vol->sb, "Failed to open attribute 0x%02x of inode 0x%llx",
5225 				type, (unsigned long long)ni->mft_no);
5226 		return err;
5227 	}
5228 	attr_ni = NTFS_I(attr_vi);
5229 
5230 	err = ntfs_attr_rm(attr_ni);
5231 	if (err)
5232 		ntfs_error(ni->vol->sb, "Failed to remove attribute 0x%02x of inode 0x%llx",
5233 				type, (unsigned long long)ni->mft_no);
5234 	iput(attr_vi);
5235 	return err;
5236 }
5237 
5238 /*
5239  * ntfs_attr_readall - read the entire data from an ntfs attribute
5240  * @ni:		open ntfs inode in which the ntfs attribute resides
5241  * @type:	attribute type
5242  * @name:	attribute name in little endian Unicode or AT_UNNAMED or NULL
5243  * @name_len:	length of attribute @name in Unicode characters (if @name given)
5244  * @data_size:	if non-NULL then store here the data size
5245  *
5246  * This function will read the entire content of an ntfs attribute.
5247  * If @name is AT_UNNAMED then look specifically for an unnamed attribute.
5248  * If @name is NULL then the attribute could be either named or not.
5249  * In both those cases @name_len is not used at all.
5250  *
5251  * On success a buffer is allocated with the content of the attribute
5252  * and which needs to be freed when it's not needed anymore. If the
5253  * @data_size parameter is non-NULL then the data size is set there.
5254  */
5255 void *ntfs_attr_readall(struct ntfs_inode *ni, const __le32 type,
5256 		__le16 *name, u32 name_len, s64 *data_size)
5257 {
5258 	struct ntfs_inode *bmp_ni;
5259 	struct inode *bmp_vi;
5260 	void *data, *ret = NULL;
5261 	s64 size;
5262 	struct super_block *sb = ni->vol->sb;
5263 
5264 	ntfs_debug("Entering\n");
5265 
5266 	bmp_vi = ntfs_attr_iget(VFS_I(ni), type, name, name_len);
5267 	if (IS_ERR(bmp_vi)) {
5268 		ntfs_debug("ntfs_attr_iget failed");
5269 		goto err_exit;
5270 	}
5271 	bmp_ni = NTFS_I(bmp_vi);
5272 
5273 	if (bmp_ni->data_size > NTFS_ATTR_READALL_MAX_SIZE &&
5274 		(bmp_ni->type != AT_BITMAP ||
5275 		bmp_ni->data_size > ((ni->vol->nr_clusters + 7) >> 3))) {
5276 		ntfs_error(sb, "Invalid attribute data size");
5277 		goto out;
5278 	}
5279 
5280 	data = kvmalloc(bmp_ni->data_size, GFP_NOFS);
5281 	if (!data)
5282 		goto out;
5283 
5284 	size = ntfs_inode_attr_pread(VFS_I(bmp_ni), 0, bmp_ni->data_size,
5285 			(u8 *)data);
5286 	if (size != bmp_ni->data_size) {
5287 		ntfs_error(sb, "ntfs_attr_pread failed");
5288 		kvfree(data);
5289 		goto out;
5290 	}
5291 	ret = data;
5292 	if (data_size)
5293 		*data_size = size;
5294 out:
5295 	iput(bmp_vi);
5296 err_exit:
5297 	ntfs_debug("\n");
5298 	return ret;
5299 }
5300 
5301 int ntfs_non_resident_attr_insert_range(struct ntfs_inode *ni, s64 start_vcn, s64 len)
5302 {
5303 	struct ntfs_volume *vol = ni->vol;
5304 	struct runlist_element *hole_rl, *rl;
5305 	struct ntfs_attr_search_ctx *ctx;
5306 	int ret;
5307 	size_t new_rl_count;
5308 
5309 	if (NInoAttr(ni) || ni->type != AT_DATA)
5310 		return -EOPNOTSUPP;
5311 	if (start_vcn > ntfs_bytes_to_cluster(vol, ni->allocated_size))
5312 		return -EINVAL;
5313 
5314 	hole_rl = kmalloc(sizeof(*hole_rl) * 2, GFP_NOFS);
5315 	if (!hole_rl)
5316 		return -ENOMEM;
5317 	hole_rl[0].vcn = start_vcn;
5318 	hole_rl[0].lcn = LCN_HOLE;
5319 	hole_rl[0].length = len;
5320 	hole_rl[1].vcn = start_vcn + len;
5321 	hole_rl[1].lcn = LCN_ENOENT;
5322 	hole_rl[1].length = 0;
5323 
5324 	down_write(&ni->runlist.lock);
5325 	ret = ntfs_attr_map_whole_runlist(ni);
5326 	if (ret) {
5327 		up_write(&ni->runlist.lock);
5328 		return ret;
5329 	}
5330 
5331 	rl = ntfs_rl_find_vcn_nolock(ni->runlist.rl, start_vcn);
5332 	if (!rl) {
5333 		up_write(&ni->runlist.lock);
5334 		kfree(hole_rl);
5335 		return -EIO;
5336 	}
5337 
5338 	rl = ntfs_rl_insert_range(ni->runlist.rl, (int)ni->runlist.count,
5339 				  hole_rl, 1, &new_rl_count);
5340 	if (IS_ERR(rl)) {
5341 		up_write(&ni->runlist.lock);
5342 		kfree(hole_rl);
5343 		return PTR_ERR(rl);
5344 	}
5345 	ni->runlist.rl =  rl;
5346 	ni->runlist.count = new_rl_count;
5347 
5348 	ni->allocated_size += ntfs_cluster_to_bytes(vol, len);
5349 	ni->data_size += ntfs_cluster_to_bytes(vol, len);
5350 	if (ntfs_cluster_to_bytes(vol, start_vcn) < ni->initialized_size)
5351 		ni->initialized_size += ntfs_cluster_to_bytes(vol, len);
5352 	ret = ntfs_attr_update_mapping_pairs(ni, 0);
5353 	up_write(&ni->runlist.lock);
5354 	if (ret)
5355 		return ret;
5356 
5357 	ctx = ntfs_attr_get_search_ctx(ni, NULL);
5358 	if (!ctx) {
5359 		ret = -ENOMEM;
5360 		return ret;
5361 	}
5362 
5363 	ret = ntfs_attr_lookup(ni->type, ni->name, ni->name_len, CASE_SENSITIVE,
5364 			       0, NULL, 0, ctx);
5365 	if (ret) {
5366 		ntfs_attr_put_search_ctx(ctx);
5367 		return ret;
5368 	}
5369 
5370 	ctx->attr->data.non_resident.data_size = cpu_to_le64(ni->data_size);
5371 	ctx->attr->data.non_resident.initialized_size = cpu_to_le64(ni->initialized_size);
5372 	if (ni->type == AT_DATA && ni->name == AT_UNNAMED)
5373 		NInoSetFileNameDirty(ni);
5374 	mark_mft_record_dirty(ctx->ntfs_ino);
5375 	ntfs_attr_put_search_ctx(ctx);
5376 	return ret;
5377 }
5378 
5379 int ntfs_non_resident_attr_collapse_range(struct ntfs_inode *ni, s64 start_vcn, s64 len)
5380 {
5381 	struct ntfs_volume *vol = ni->vol;
5382 	struct runlist_element *punch_rl, *rl;
5383 	struct ntfs_attr_search_ctx *ctx = NULL;
5384 	s64 end_vcn;
5385 	int dst_cnt;
5386 	int ret;
5387 	size_t new_rl_cnt;
5388 
5389 	if (NInoAttr(ni) || ni->type != AT_DATA)
5390 		return -EOPNOTSUPP;
5391 
5392 	end_vcn = ntfs_bytes_to_cluster(vol, ni->allocated_size);
5393 	if (start_vcn >= end_vcn)
5394 		return -EINVAL;
5395 
5396 	down_write(&ni->runlist.lock);
5397 	ret = ntfs_attr_map_whole_runlist(ni);
5398 	if (ret) {
5399 		up_write(&ni->runlist.lock);
5400 		return ret;
5401 	}
5402 
5403 	len = min(len, end_vcn - start_vcn);
5404 	for (rl = ni->runlist.rl, dst_cnt = 0; rl && rl->length; rl++)
5405 		dst_cnt++;
5406 	rl = ntfs_rl_find_vcn_nolock(ni->runlist.rl, start_vcn);
5407 	if (!rl) {
5408 		up_write(&ni->runlist.lock);
5409 		return -EIO;
5410 	}
5411 
5412 	rl = ntfs_rl_collapse_range(ni->runlist.rl, dst_cnt + 1,
5413 				    start_vcn, len, &punch_rl, &new_rl_cnt);
5414 	if (IS_ERR(rl)) {
5415 		up_write(&ni->runlist.lock);
5416 		return PTR_ERR(rl);
5417 	}
5418 	ni->runlist.rl = rl;
5419 	ni->runlist.count = new_rl_cnt;
5420 
5421 	ni->allocated_size -= ntfs_cluster_to_bytes(vol, len);
5422 	if (ni->data_size > ntfs_cluster_to_bytes(vol, start_vcn)) {
5423 		if (ni->data_size > ntfs_cluster_to_bytes(vol, (start_vcn + len)))
5424 			ni->data_size -= ntfs_cluster_to_bytes(vol, len);
5425 		else
5426 			ni->data_size = ntfs_cluster_to_bytes(vol, start_vcn);
5427 	}
5428 	if (ni->initialized_size > ntfs_cluster_to_bytes(vol, start_vcn)) {
5429 		if (ni->initialized_size >
5430 		    ntfs_cluster_to_bytes(vol, start_vcn + len))
5431 			ni->initialized_size -= ntfs_cluster_to_bytes(vol, len);
5432 		else
5433 			ni->initialized_size = ntfs_cluster_to_bytes(vol, start_vcn);
5434 	}
5435 
5436 	if (ni->allocated_size > 0) {
5437 		ret = ntfs_attr_update_mapping_pairs(ni, 0);
5438 		if (ret) {
5439 			up_write(&ni->runlist.lock);
5440 			goto out_rl;
5441 		}
5442 	}
5443 	up_write(&ni->runlist.lock);
5444 
5445 	ctx = ntfs_attr_get_search_ctx(ni, NULL);
5446 	if (!ctx) {
5447 		ret = -ENOMEM;
5448 		goto out_rl;
5449 	}
5450 
5451 	ret = ntfs_attr_lookup(ni->type, ni->name, ni->name_len, CASE_SENSITIVE,
5452 			       0, NULL, 0, ctx);
5453 	if (ret)
5454 		goto out_ctx;
5455 
5456 	ctx->attr->data.non_resident.data_size = cpu_to_le64(ni->data_size);
5457 	ctx->attr->data.non_resident.initialized_size = cpu_to_le64(ni->initialized_size);
5458 	if (ni->allocated_size == 0)
5459 		ntfs_attr_make_resident(ni, ctx);
5460 	mark_mft_record_dirty(ctx->ntfs_ino);
5461 
5462 	ret = ntfs_cluster_free_from_rl(vol, punch_rl);
5463 	if (ret)
5464 		ntfs_error(vol->sb, "Freeing of clusters failed");
5465 out_ctx:
5466 	if (ctx)
5467 		ntfs_attr_put_search_ctx(ctx);
5468 out_rl:
5469 	kvfree(punch_rl);
5470 	mark_mft_record_dirty(ni);
5471 	return ret;
5472 }
5473 
5474 int ntfs_non_resident_attr_punch_hole(struct ntfs_inode *ni, s64 start_vcn, s64 len)
5475 {
5476 	struct ntfs_volume *vol = ni->vol;
5477 	struct runlist_element *punch_rl, *rl;
5478 	s64 end_vcn;
5479 	int dst_cnt;
5480 	int ret;
5481 	size_t new_rl_count;
5482 
5483 	if (NInoAttr(ni) || ni->type != AT_DATA)
5484 		return -EOPNOTSUPP;
5485 
5486 	end_vcn = ntfs_bytes_to_cluster(vol, ni->allocated_size);
5487 	if (start_vcn >= end_vcn)
5488 		return -EINVAL;
5489 
5490 	down_write(&ni->runlist.lock);
5491 	ret = ntfs_attr_map_whole_runlist(ni);
5492 	if (ret) {
5493 		up_write(&ni->runlist.lock);
5494 		return ret;
5495 	}
5496 
5497 	len = min(len, end_vcn - start_vcn + 1);
5498 	for (rl = ni->runlist.rl, dst_cnt = 0; rl && rl->length; rl++)
5499 		dst_cnt++;
5500 	rl = ntfs_rl_find_vcn_nolock(ni->runlist.rl, start_vcn);
5501 	if (!rl) {
5502 		up_write(&ni->runlist.lock);
5503 		return -EIO;
5504 	}
5505 
5506 	rl = ntfs_rl_punch_hole(ni->runlist.rl, dst_cnt + 1,
5507 				start_vcn, len, &punch_rl, &new_rl_count);
5508 	if (IS_ERR(rl)) {
5509 		up_write(&ni->runlist.lock);
5510 		return PTR_ERR(rl);
5511 	}
5512 	ni->runlist.rl = rl;
5513 	ni->runlist.count = new_rl_count;
5514 
5515 	ret = ntfs_attr_update_mapping_pairs(ni, 0);
5516 	up_write(&ni->runlist.lock);
5517 	if (ret) {
5518 		kvfree(punch_rl);
5519 		return ret;
5520 	}
5521 
5522 	ret = ntfs_cluster_free_from_rl(vol, punch_rl);
5523 	if (ret)
5524 		ntfs_error(vol->sb, "Freeing of clusters failed");
5525 
5526 	kvfree(punch_rl);
5527 	mark_mft_record_dirty(ni);
5528 	return ret;
5529 }
5530 
5531 int ntfs_attr_fallocate(struct ntfs_inode *ni, loff_t start, loff_t byte_len, bool keep_size)
5532 {
5533 	struct ntfs_volume *vol = ni->vol;
5534 	struct mft_record *mrec;
5535 	struct ntfs_attr_search_ctx *ctx;
5536 	s64 old_data_size;
5537 	s64 vcn_start, vcn_end, vcn_uninit, vcn, try_alloc_cnt;
5538 	s64 lcn, alloc_cnt;
5539 	int err = 0;
5540 	struct runlist_element *rl;
5541 	bool balloc;
5542 
5543 	if (NInoAttr(ni) || ni->type != AT_DATA)
5544 		return -EINVAL;
5545 
5546 	if (NInoNonResident(ni) && !NInoFullyMapped(ni)) {
5547 		down_write(&ni->runlist.lock);
5548 		err = ntfs_attr_map_whole_runlist(ni);
5549 		up_write(&ni->runlist.lock);
5550 		if (err)
5551 			return err;
5552 	}
5553 
5554 	mutex_lock_nested(&ni->mrec_lock, NTFS_INODE_MUTEX_NORMAL);
5555 	mrec = map_mft_record(ni);
5556 	if (IS_ERR(mrec)) {
5557 		mutex_unlock(&ni->mrec_lock);
5558 		return PTR_ERR(mrec);
5559 	}
5560 
5561 	ctx = ntfs_attr_get_search_ctx(ni, mrec);
5562 	if (!ctx) {
5563 		err = -ENOMEM;
5564 		goto out_unmap;
5565 	}
5566 
5567 	err = ntfs_attr_lookup(AT_DATA, AT_UNNAMED, 0, 0, 0, NULL, 0, ctx);
5568 	if (err) {
5569 		err = -EIO;
5570 		goto out_unmap;
5571 	}
5572 
5573 	old_data_size = ni->data_size;
5574 	if (start + byte_len > ni->data_size) {
5575 		err = ntfs_attr_truncate(ni, start + byte_len);
5576 		if (err)
5577 			goto out_unmap;
5578 		if (keep_size) {
5579 			ntfs_attr_reinit_search_ctx(ctx);
5580 			err = ntfs_attr_lookup(AT_DATA, AT_UNNAMED, 0, 0, 0, NULL, 0, ctx);
5581 			if (err) {
5582 				err = -EIO;
5583 				goto out_unmap;
5584 			}
5585 			ni->data_size = old_data_size;
5586 			if (NInoNonResident(ni))
5587 				ctx->attr->data.non_resident.data_size =
5588 					cpu_to_le64(old_data_size);
5589 			else
5590 				ctx->attr->data.resident.value_length =
5591 					cpu_to_le32((u32)old_data_size);
5592 			mark_mft_record_dirty(ni);
5593 		}
5594 	}
5595 
5596 	ntfs_attr_put_search_ctx(ctx);
5597 	unmap_mft_record(ni);
5598 	mutex_unlock(&ni->mrec_lock);
5599 
5600 	if (!NInoNonResident(ni))
5601 		goto out;
5602 
5603 	vcn_start = (s64)ntfs_bytes_to_cluster(vol, start);
5604 	vcn_end = (s64)ntfs_bytes_to_cluster(vol,
5605 			round_up(start + byte_len, vol->cluster_size));
5606 	vcn_uninit = (s64)ntfs_bytes_to_cluster(vol,
5607 			round_up(ni->initialized_size, vol->cluster_size));
5608 	vcn_uninit = min_t(s64, vcn_uninit, vcn_end);
5609 
5610 	/*
5611 	 * we have to allocate clusters for holes and delayed within initialized_size,
5612 	 * and zero out the clusters only for the holes.
5613 	 */
5614 	vcn = vcn_start;
5615 	while (vcn < vcn_uninit) {
5616 		down_read(&ni->runlist.lock);
5617 		rl = ntfs_attr_find_vcn_nolock(ni, vcn, NULL);
5618 		up_read(&ni->runlist.lock);
5619 		if (IS_ERR(rl)) {
5620 			err = PTR_ERR(rl);
5621 			goto out;
5622 		}
5623 
5624 		if (rl->lcn > 0) {
5625 			vcn += rl->length - (vcn - rl->vcn);
5626 		} else if (rl->lcn == LCN_DELALLOC || rl->lcn == LCN_HOLE) {
5627 			try_alloc_cnt = min(rl->length - (vcn - rl->vcn),
5628 					    vcn_uninit - vcn);
5629 
5630 			if (rl->lcn == LCN_DELALLOC) {
5631 				vcn += try_alloc_cnt;
5632 				continue;
5633 			}
5634 
5635 			while (try_alloc_cnt > 0) {
5636 				mutex_lock_nested(&ni->mrec_lock, NTFS_INODE_MUTEX_NORMAL);
5637 				down_write(&ni->runlist.lock);
5638 				err = ntfs_attr_map_cluster(ni, vcn, &lcn, &alloc_cnt,
5639 							    try_alloc_cnt, &balloc, false, false);
5640 				up_write(&ni->runlist.lock);
5641 				mutex_unlock(&ni->mrec_lock);
5642 				if (err)
5643 					goto out;
5644 
5645 				err = ntfs_dio_zero_range(VFS_I(ni),
5646 							  lcn << vol->cluster_size_bits,
5647 							  alloc_cnt << vol->cluster_size_bits);
5648 				if (err > 0)
5649 					goto out;
5650 
5651 				if (signal_pending(current))
5652 					goto out;
5653 
5654 				vcn += alloc_cnt;
5655 				try_alloc_cnt -= alloc_cnt;
5656 			}
5657 		} else {
5658 			err = -EIO;
5659 			goto out;
5660 		}
5661 	}
5662 
5663 	/* allocate clusters outside of initialized_size */
5664 	try_alloc_cnt = vcn_end - vcn;
5665 	while (try_alloc_cnt > 0) {
5666 		mutex_lock_nested(&ni->mrec_lock, NTFS_INODE_MUTEX_NORMAL);
5667 		down_write(&ni->runlist.lock);
5668 		err = ntfs_attr_map_cluster(ni, vcn, &lcn, &alloc_cnt,
5669 					    try_alloc_cnt, &balloc, false, false);
5670 		up_write(&ni->runlist.lock);
5671 		mutex_unlock(&ni->mrec_lock);
5672 		if (err || signal_pending(current))
5673 			goto out;
5674 
5675 		vcn += alloc_cnt;
5676 		try_alloc_cnt -= alloc_cnt;
5677 		cond_resched();
5678 	}
5679 
5680 	if (NInoRunlistDirty(ni)) {
5681 		mutex_lock_nested(&ni->mrec_lock, NTFS_INODE_MUTEX_NORMAL);
5682 		down_write(&ni->runlist.lock);
5683 		err = ntfs_attr_update_mapping_pairs(ni, 0);
5684 		if (err)
5685 			ntfs_error(ni->vol->sb, "Updating mapping pairs failed");
5686 		else
5687 			NInoClearRunlistDirty(ni);
5688 		up_write(&ni->runlist.lock);
5689 		mutex_unlock(&ni->mrec_lock);
5690 	}
5691 	return err;
5692 out_unmap:
5693 	if (ctx)
5694 		ntfs_attr_put_search_ctx(ctx);
5695 	unmap_mft_record(ni);
5696 	mutex_unlock(&ni->mrec_lock);
5697 out:
5698 	return err >= 0 ? 0 : err;
5699 }
5700