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