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