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