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