xref: /linux/fs/ntfs/attrib.c (revision f16d85cd3de9d0c761b74155b4cbe2f20d3dcf80)
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 int ntfs_attr_make_non_resident(struct ntfs_inode *ni, const u32 data_size)
1979 {
1980 	s64 new_size;
1981 	struct inode *vi = VFS_I(ni);
1982 	struct ntfs_volume *vol = ni->vol;
1983 	struct ntfs_inode *base_ni;
1984 	struct mft_record *m;
1985 	struct attr_record *a;
1986 	struct ntfs_attr_search_ctx *ctx;
1987 	struct folio *folio;
1988 	struct runlist_element *rl;
1989 	unsigned long flags;
1990 	int mp_size, mp_ofs, name_ofs, arec_size, err, err2;
1991 	u32 attr_size;
1992 	u8 old_res_attr_flags;
1993 
1994 	if (NInoNonResident(ni)) {
1995 		ntfs_warning(vol->sb,
1996 			"Trying to make non-resident attribute non-resident.  Aborting...\n");
1997 		return -EINVAL;
1998 	}
1999 
2000 	/* Check that the attribute is allowed to be non-resident. */
2001 	err = ntfs_attr_can_be_non_resident(vol, ni->type);
2002 	if (unlikely(err)) {
2003 		if (err == -EPERM)
2004 			ntfs_debug("Attribute is not allowed to be non-resident.");
2005 		else
2006 			ntfs_debug("Attribute not defined on the NTFS volume!");
2007 		return err;
2008 	}
2009 
2010 	if (NInoEncrypted(ni))
2011 		return -EIO;
2012 
2013 	if (!NInoAttr(ni))
2014 		base_ni = ni;
2015 	else
2016 		base_ni = ni->ext.base_ntfs_ino;
2017 	m = map_mft_record(base_ni);
2018 	if (IS_ERR(m)) {
2019 		err = PTR_ERR(m);
2020 		m = NULL;
2021 		ctx = NULL;
2022 		goto err_out;
2023 	}
2024 	ctx = ntfs_attr_get_search_ctx(base_ni, m);
2025 	if (unlikely(!ctx)) {
2026 		err = -ENOMEM;
2027 		goto err_out;
2028 	}
2029 	err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
2030 			CASE_SENSITIVE, 0, NULL, 0, ctx);
2031 	if (unlikely(err)) {
2032 		if (err == -ENOENT)
2033 			err = -EIO;
2034 		goto err_out;
2035 	}
2036 	m = ctx->mrec;
2037 	a = ctx->attr;
2038 
2039 	/*
2040 	 * The size needs to be aligned to a cluster boundary for allocation
2041 	 * purposes.
2042 	 */
2043 	new_size = (data_size + vol->cluster_size - 1) &
2044 			~(vol->cluster_size - 1);
2045 	if (new_size > 0) {
2046 		if ((a->flags & ATTR_COMPRESSION_MASK) == ATTR_IS_COMPRESSED) {
2047 			/* must allocate full compression blocks */
2048 			new_size =
2049 				((new_size - 1) |
2050 				 ((1L << (STANDARD_COMPRESSION_UNIT +
2051 					  vol->cluster_size_bits)) - 1)) + 1;
2052 		}
2053 
2054 		/*
2055 		 * Will need folio later and since folio lock nests
2056 		 * outside all ntfs locks, we need to get the folio now.
2057 		 */
2058 		folio = __filemap_get_folio(vi->i_mapping, 0,
2059 					    FGP_CREAT | FGP_LOCK,
2060 					    mapping_gfp_mask(vi->i_mapping));
2061 		if (IS_ERR(folio)) {
2062 			err = -ENOMEM;
2063 			goto err_out;
2064 		}
2065 
2066 		/* Start by allocating clusters to hold the attribute value. */
2067 		rl = ntfs_cluster_alloc(vol, 0,
2068 				ntfs_bytes_to_cluster(vol, new_size),
2069 				-1, DATA_ZONE, true, false, false);
2070 		if (IS_ERR(rl)) {
2071 			err = PTR_ERR(rl);
2072 			ntfs_debug("Failed to allocate cluster%s, error code %i.",
2073 					str_plural(ntfs_bytes_to_cluster(vol, new_size)),
2074 					err);
2075 			goto folio_err_out;
2076 		}
2077 	} else {
2078 		rl = NULL;
2079 		folio = NULL;
2080 	}
2081 
2082 	down_write(&ni->runlist.lock);
2083 	/* Determine the size of the mapping pairs array. */
2084 	mp_size = ntfs_get_size_for_mapping_pairs(vol, rl, 0, -1, -1);
2085 	if (unlikely(mp_size < 0)) {
2086 		err = mp_size;
2087 		ntfs_debug("Failed to get size for mapping pairs array, error code %i.\n", err);
2088 		goto rl_err_out;
2089 	}
2090 
2091 	if (NInoNonResident(ni) || a->non_resident) {
2092 		err = -EIO;
2093 		goto rl_err_out;
2094 	}
2095 
2096 	/*
2097 	 * Calculate new offsets for the name and the mapping pairs array.
2098 	 */
2099 	if (NInoSparse(ni) || NInoCompressed(ni))
2100 		name_ofs = (offsetof(struct attr_record,
2101 				data.non_resident.compressed_size) +
2102 				sizeof(a->data.non_resident.compressed_size) +
2103 				7) & ~7;
2104 	else
2105 		name_ofs = (offsetof(struct attr_record,
2106 				data.non_resident.compressed_size) + 7) & ~7;
2107 	mp_ofs = (name_ofs + a->name_length * sizeof(__le16) + 7) & ~7;
2108 	/*
2109 	 * Determine the size of the resident part of the now non-resident
2110 	 * attribute record.
2111 	 */
2112 	arec_size = (mp_ofs + mp_size + 7) & ~7;
2113 	/*
2114 	 * If the folio is not uptodate bring it uptodate by copying from the
2115 	 * attribute value.
2116 	 */
2117 	attr_size = le32_to_cpu(a->data.resident.value_length);
2118 	WARN_ON(attr_size != data_size);
2119 	if (folio && !folio_test_uptodate(folio)) {
2120 		folio_fill_tail(folio, 0, (u8 *)a +
2121 				le16_to_cpu(a->data.resident.value_offset),
2122 				attr_size);
2123 		folio_mark_uptodate(folio);
2124 	}
2125 
2126 	/* Backup the attribute flag. */
2127 	old_res_attr_flags = a->data.resident.flags;
2128 	/* Resize the resident part of the attribute record. */
2129 	err = ntfs_attr_record_resize(m, a, arec_size);
2130 	if (unlikely(err))
2131 		goto rl_err_out;
2132 
2133 	/*
2134 	 * Convert the resident part of the attribute record to describe a
2135 	 * non-resident attribute.
2136 	 */
2137 	a->non_resident = 1;
2138 	/* Move the attribute name if it exists and update the offset. */
2139 	if (a->name_length)
2140 		memmove((u8 *)a + name_ofs, (u8 *)a + le16_to_cpu(a->name_offset),
2141 				a->name_length * sizeof(__le16));
2142 	a->name_offset = cpu_to_le16(name_ofs);
2143 	/* Setup the fields specific to non-resident attributes. */
2144 	a->data.non_resident.lowest_vcn = 0;
2145 	a->data.non_resident.highest_vcn =
2146 		cpu_to_le64(ntfs_bytes_to_cluster(vol, new_size - 1));
2147 	a->data.non_resident.mapping_pairs_offset = cpu_to_le16(mp_ofs);
2148 	memset(&a->data.non_resident.reserved, 0,
2149 			sizeof(a->data.non_resident.reserved));
2150 	a->data.non_resident.allocated_size = cpu_to_le64(new_size);
2151 	a->data.non_resident.data_size =
2152 			a->data.non_resident.initialized_size =
2153 			cpu_to_le64(attr_size);
2154 	if (NInoSparse(ni) || NInoCompressed(ni)) {
2155 		a->data.non_resident.compression_unit = 0;
2156 		if (NInoCompressed(ni) || vol->major_ver < 3)
2157 			a->data.non_resident.compression_unit = 4;
2158 		a->data.non_resident.compressed_size =
2159 				a->data.non_resident.allocated_size;
2160 	} else
2161 		a->data.non_resident.compression_unit = 0;
2162 	/* Generate the mapping pairs array into the attribute record. */
2163 	err = ntfs_mapping_pairs_build(vol, (u8 *)a + mp_ofs,
2164 			arec_size - mp_ofs, rl, 0, -1, NULL, NULL, NULL);
2165 	if (unlikely(err)) {
2166 		ntfs_error(vol->sb, "Failed to build mapping pairs, error code %i.",
2167 				err);
2168 		goto undo_err_out;
2169 	}
2170 
2171 	/* Setup the in-memory attribute structure to be non-resident. */
2172 	ni->runlist.rl = rl;
2173 	if (rl) {
2174 		for (ni->runlist.count = 1; rl->length != 0; rl++)
2175 			ni->runlist.count++;
2176 	} else
2177 		ni->runlist.count = 0;
2178 	write_lock_irqsave(&ni->size_lock, flags);
2179 	ni->allocated_size = new_size;
2180 	if ((NInoSparse(ni) && !NInoWofCompressed(ni)) || NInoCompressed(ni)) {
2181 		ni->itype.compressed.size = ni->allocated_size;
2182 		if (a->data.non_resident.compression_unit) {
2183 			ni->itype.compressed.block_size = 1U <<
2184 				(a->data.non_resident.compression_unit +
2185 				 vol->cluster_size_bits);
2186 			ni->itype.compressed.block_size_bits =
2187 					ffs(ni->itype.compressed.block_size) -
2188 					1;
2189 			ni->itype.compressed.block_clusters = 1U <<
2190 					a->data.non_resident.compression_unit;
2191 		} else {
2192 			ni->itype.compressed.block_size = 0;
2193 			ni->itype.compressed.block_size_bits = 0;
2194 			ni->itype.compressed.block_clusters = 0;
2195 		}
2196 		vi->i_blocks = ni->itype.compressed.size >> 9;
2197 	} else
2198 		vi->i_blocks = ni->allocated_size >> 9;
2199 	write_unlock_irqrestore(&ni->size_lock, flags);
2200 	/*
2201 	 * This needs to be last since the address space operations ->read_folio
2202 	 * and ->writepage can run concurrently with us as they are not
2203 	 * serialized on i_mutex.  Note, we are not allowed to fail once we flip
2204 	 * this switch, which is another reason to do this last.
2205 	 */
2206 	NInoSetNonResident(ni);
2207 	NInoSetFullyMapped(ni);
2208 	/* Mark the mft record dirty, so it gets written back. */
2209 	mark_mft_record_dirty(ctx->ntfs_ino);
2210 	ntfs_attr_put_search_ctx(ctx);
2211 	unmap_mft_record(base_ni);
2212 	up_write(&ni->runlist.lock);
2213 	if (folio) {
2214 		iomap_dirty_folio(vi->i_mapping, folio);
2215 		folio_unlock(folio);
2216 		folio_put(folio);
2217 	}
2218 	ntfs_debug("Done.");
2219 	return 0;
2220 undo_err_out:
2221 	/* Convert the attribute back into a resident attribute. */
2222 	a->non_resident = 0;
2223 	/* Move the attribute name if it exists and update the offset. */
2224 	name_ofs = (offsetof(struct attr_record, data.resident.reserved) +
2225 			sizeof(a->data.resident.reserved) + 7) & ~7;
2226 	if (a->name_length)
2227 		memmove((u8 *)a + name_ofs, (u8 *)a + le16_to_cpu(a->name_offset),
2228 				a->name_length * sizeof(__le16));
2229 	mp_ofs = (name_ofs + a->name_length * sizeof(__le16) + 7) & ~7;
2230 	a->name_offset = cpu_to_le16(name_ofs);
2231 	arec_size = (mp_ofs + attr_size + 7) & ~7;
2232 	/* Resize the resident part of the attribute record. */
2233 	err2 = ntfs_attr_record_resize(m, a, arec_size);
2234 	if (unlikely(err2)) {
2235 		/*
2236 		 * This cannot happen (well if memory corruption is at work it
2237 		 * could happen in theory), but deal with it as well as we can.
2238 		 * If the old size is too small, truncate the attribute,
2239 		 * otherwise simply give it a larger allocated size.
2240 		 */
2241 		arec_size = le32_to_cpu(a->length);
2242 		if ((mp_ofs + attr_size) > arec_size) {
2243 			err2 = attr_size;
2244 			attr_size = arec_size - mp_ofs;
2245 			ntfs_error(vol->sb,
2246 				"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.",
2247 					ni->mft_no,
2248 					(unsigned int)le32_to_cpu(ni->type),
2249 					err2, attr_size, err2 - attr_size,
2250 					((ni->type == AT_DATA) &&
2251 					!ni->name_len) ? "FILE" : "ATTRIBUTE");
2252 			write_lock_irqsave(&ni->size_lock, flags);
2253 			ni->initialized_size = attr_size;
2254 			i_size_write(vi, attr_size);
2255 			write_unlock_irqrestore(&ni->size_lock, flags);
2256 		}
2257 	}
2258 	/* Setup the fields specific to resident attributes. */
2259 	a->data.resident.value_length = cpu_to_le32(attr_size);
2260 	a->data.resident.value_offset = cpu_to_le16(mp_ofs);
2261 	a->data.resident.flags = old_res_attr_flags;
2262 	memset(&a->data.resident.reserved, 0,
2263 			sizeof(a->data.resident.reserved));
2264 	/* Copy the data from folio back to the attribute value. */
2265 	if (folio)
2266 		memcpy_from_folio((u8 *)a + mp_ofs, folio, 0, attr_size);
2267 	/* Setup the allocated size in the ntfs inode in case it changed. */
2268 	write_lock_irqsave(&ni->size_lock, flags);
2269 	ni->allocated_size = arec_size - mp_ofs;
2270 	write_unlock_irqrestore(&ni->size_lock, flags);
2271 	/* Mark the mft record dirty, so it gets written back. */
2272 	mark_mft_record_dirty(ctx->ntfs_ino);
2273 rl_err_out:
2274 	up_write(&ni->runlist.lock);
2275 	if (rl) {
2276 		if (ntfs_cluster_free_from_rl(vol, rl) < 0) {
2277 			ntfs_error(vol->sb,
2278 				"Failed to release allocated cluster(s) in error code path.  Run chkdsk to recover the lost cluster(s).");
2279 			NVolSetErrors(vol);
2280 		}
2281 		kvfree(rl);
2282 folio_err_out:
2283 		folio_unlock(folio);
2284 		folio_put(folio);
2285 	}
2286 err_out:
2287 	if (ctx)
2288 		ntfs_attr_put_search_ctx(ctx);
2289 	if (m)
2290 		unmap_mft_record(base_ni);
2291 	ni->runlist.rl = NULL;
2292 
2293 	if (err == -EINVAL)
2294 		err = -EIO;
2295 	return err;
2296 }
2297 
2298 /*
2299  * ntfs_attr_set - fill (a part of) an attribute with a byte
2300  * @ni:		ntfs inode describing the attribute to fill
2301  * @ofs:	offset inside the attribute at which to start to fill
2302  * @cnt:	number of bytes to fill
2303  * @val:	the unsigned 8-bit value with which to fill the attribute
2304  *
2305  * Fill @cnt bytes of the attribute described by the ntfs inode @ni starting at
2306  * byte offset @ofs inside the attribute with the constant byte @val.
2307  *
2308  * This function is effectively like memset() applied to an ntfs attribute.
2309  * Note thie function actually only operates on the page cache pages belonging
2310  * to the ntfs attribute and it marks them dirty after doing the memset().
2311  * Thus it relies on the vm dirty page write code paths to cause the modified
2312  * pages to be written to the mft record/disk.
2313  */
2314 int ntfs_attr_set(struct ntfs_inode *ni, s64 ofs, s64 cnt, const u8 val)
2315 {
2316 	struct address_space *mapping = VFS_I(ni)->i_mapping;
2317 	struct folio *folio;
2318 	pgoff_t index;
2319 	u8 *addr;
2320 	unsigned long offset;
2321 	size_t attr_len;
2322 	int ret = 0;
2323 
2324 	index = ofs >> PAGE_SHIFT;
2325 	while (cnt) {
2326 		folio = read_mapping_folio(mapping, index, NULL);
2327 		if (IS_ERR(folio)) {
2328 			ret = PTR_ERR(folio);
2329 			ntfs_error(VFS_I(ni)->i_sb, "Failed to read a page %lu for attr %#x: %ld",
2330 				   index, ni->type, PTR_ERR(folio));
2331 			break;
2332 		}
2333 
2334 		offset = offset_in_folio(folio, ofs);
2335 		attr_len = min_t(size_t, (size_t)cnt, folio_size(folio) - offset);
2336 
2337 		folio_lock(folio);
2338 		addr = kmap_local_folio(folio, offset);
2339 		memset(addr, val, attr_len);
2340 		kunmap_local(addr);
2341 
2342 		folio_mark_dirty(folio);
2343 		folio_unlock(folio);
2344 		folio_put(folio);
2345 
2346 		ofs += attr_len;
2347 		cnt -= attr_len;
2348 		index++;
2349 		cond_resched();
2350 	}
2351 
2352 	return ret;
2353 }
2354 
2355 int ntfs_attr_set_initialized_size(struct ntfs_inode *ni, loff_t new_size)
2356 {
2357 	struct ntfs_attr_search_ctx *ctx;
2358 	struct ntfs_inode *base_ni = ntfs_base_inode(ni);
2359 	int err = 0;
2360 
2361 	if (!NInoNonResident(ni))
2362 		return -EINVAL;
2363 
2364 	ctx = ntfs_attr_get_search_ctx(base_ni, NULL);
2365 	if (!ctx)
2366 		return -ENOMEM;
2367 
2368 	err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
2369 			       CASE_SENSITIVE, 0, NULL, 0, ctx);
2370 	if (err)
2371 		goto out_ctx;
2372 
2373 	ctx->attr->data.non_resident.initialized_size = cpu_to_le64(new_size);
2374 	ni->initialized_size = new_size;
2375 	mark_mft_record_dirty(ctx->ntfs_ino);
2376 out_ctx:
2377 	ntfs_attr_put_search_ctx(ctx);
2378 	return err;
2379 }
2380 
2381 /*
2382  * ntfs_make_room_for_attr - make room for an attribute inside an mft record
2383  * @m:		mft record
2384  * @pos:	position at which to make space
2385  * @size:	byte size to make available at this position
2386  *
2387  * @pos points to the attribute in front of which we want to make space.
2388  */
2389 static int ntfs_make_room_for_attr(struct mft_record *m, u8 *pos, u32 size)
2390 {
2391 	u32 biu;
2392 
2393 	ntfs_debug("Entering for pos 0x%x, size %u.\n",
2394 			(int)(pos - (u8 *)m), (unsigned int) size);
2395 
2396 	/* Make size 8-byte alignment. */
2397 	size = (size + 7) & ~7;
2398 
2399 	/* Rigorous consistency checks. */
2400 	if (!m || !pos || pos < (u8 *)m) {
2401 		pr_err("%s: pos=%p  m=%p\n", __func__, pos, m);
2402 		return -EINVAL;
2403 	}
2404 
2405 	/* The -8 is for the attribute terminator. */
2406 	if (pos - (u8 *)m > (int)le32_to_cpu(m->bytes_in_use) - 8)
2407 		return -EINVAL;
2408 	/* Nothing to do. */
2409 	if (!size)
2410 		return 0;
2411 
2412 	biu = le32_to_cpu(m->bytes_in_use);
2413 	/* Do we have enough space? */
2414 	if (biu + size > le32_to_cpu(m->bytes_allocated) ||
2415 	    pos + size > (u8 *)m + le32_to_cpu(m->bytes_allocated)) {
2416 		ntfs_debug("No enough space in the MFT record\n");
2417 		return -ENOSPC;
2418 	}
2419 	/* Move everything after pos to pos + size. */
2420 	memmove(pos + size, pos, biu - (pos - (u8 *)m));
2421 	/* Update mft record. */
2422 	m->bytes_in_use = cpu_to_le32(biu + size);
2423 	return 0;
2424 }
2425 
2426 /*
2427  * ntfs_resident_attr_record_add - add resident attribute to inode
2428  * @ni:		opened ntfs inode to which MFT record add attribute
2429  * @type:	type of the new attribute
2430  * @name:	name of the new attribute
2431  * @name_len:	name length of the new attribute
2432  * @val:	value of the new attribute
2433  * @size:	size of new attribute (length of @val, if @val != NULL)
2434  * @flags:	flags of the new attribute
2435  */
2436 int ntfs_resident_attr_record_add(struct ntfs_inode *ni, __le32 type,
2437 		__le16 *name, u8 name_len, u8 *val, u32 size,
2438 		__le16 flags)
2439 {
2440 	struct ntfs_attr_search_ctx *ctx;
2441 	u32 length;
2442 	struct attr_record *a;
2443 	struct mft_record *m;
2444 	int err, offset;
2445 	struct ntfs_inode *base_ni;
2446 	u32 ic;
2447 
2448 	if (!ni || (!name && name_len))
2449 		return -EINVAL;
2450 
2451 	ntfs_debug("Entering for inode 0x%llx, attr 0x%x, flags 0x%x.\n",
2452 			(long long) ni->mft_no, (unsigned int) le32_to_cpu(type),
2453 			(unsigned int) le16_to_cpu(flags));
2454 
2455 	err = ntfs_attr_can_be_resident(ni->vol, type);
2456 	if (err) {
2457 		if (err == -EPERM)
2458 			ntfs_debug("Attribute can't be resident.\n");
2459 		else
2460 			ntfs_debug("ntfs_attr_can_be_resident failed.\n");
2461 		return err;
2462 	}
2463 
2464 	/* Locate place where record should be. */
2465 	ctx = ntfs_attr_get_search_ctx(ni, NULL);
2466 	if (!ctx) {
2467 		ntfs_error(ni->vol->sb, "%s: Failed to get search context",
2468 				__func__);
2469 		return -ENOMEM;
2470 	}
2471 	/*
2472 	 * Use ntfs_attr_find instead of ntfs_attr_lookup to find place for
2473 	 * attribute in @ni->mrec, not any extent inode in case if @ni is base
2474 	 * file record.
2475 	 */
2476 	ic = type == AT_DATA && name_len ? IGNORE_CASE : CASE_SENSITIVE;
2477 	err = ntfs_attr_find(type, name, name_len, ic, val, size, ctx);
2478 	if (!err) {
2479 		err = -EEXIST;
2480 		ntfs_debug("Attribute already present.\n");
2481 		goto put_err_out;
2482 	}
2483 	if (err != -ENOENT) {
2484 		err = -EIO;
2485 		goto put_err_out;
2486 	}
2487 	a = ctx->attr;
2488 	m = ctx->mrec;
2489 
2490 	/* Make room for attribute. */
2491 	length = offsetof(struct attr_record, data.resident.reserved) +
2492 			  sizeof(a->data.resident.reserved) +
2493 		((name_len * sizeof(__le16) + 7) & ~7) +
2494 		((size + 7) & ~7);
2495 	err = ntfs_make_room_for_attr(ctx->mrec, (u8 *) ctx->attr, length);
2496 	if (err) {
2497 		ntfs_debug("Failed to make room for attribute.\n");
2498 		goto put_err_out;
2499 	}
2500 
2501 	/* Setup record fields. */
2502 	offset = ((u8 *)a - (u8 *)m);
2503 	a->type = type;
2504 	a->length = cpu_to_le32(length);
2505 	a->non_resident = 0;
2506 	a->name_length = name_len;
2507 	a->name_offset =
2508 		name_len ? cpu_to_le16((offsetof(struct attr_record, data.resident.reserved) +
2509 				sizeof(a->data.resident.reserved))) : cpu_to_le16(0);
2510 
2511 	a->flags = flags;
2512 	a->instance = m->next_attr_instance;
2513 	a->data.resident.value_length = cpu_to_le32(size);
2514 	a->data.resident.value_offset = cpu_to_le16(length - ((size + 7) & ~7));
2515 	if (val)
2516 		memcpy((u8 *)a + le16_to_cpu(a->data.resident.value_offset), val, size);
2517 	else
2518 		memset((u8 *)a + le16_to_cpu(a->data.resident.value_offset), 0, size);
2519 	if (type == AT_FILE_NAME)
2520 		a->data.resident.flags = RESIDENT_ATTR_IS_INDEXED;
2521 	else
2522 		a->data.resident.flags = 0;
2523 	if (name_len)
2524 		memcpy((u8 *)a + le16_to_cpu(a->name_offset),
2525 				name, sizeof(__le16) * name_len);
2526 	m->next_attr_instance =
2527 		cpu_to_le16((le16_to_cpu(m->next_attr_instance) + 1) & 0xffff);
2528 	if (ni->nr_extents == -1)
2529 		base_ni = ni->ext.base_ntfs_ino;
2530 	else
2531 		base_ni = ni;
2532 	if (type != AT_ATTRIBUTE_LIST && NInoAttrList(base_ni)) {
2533 		err = ntfs_attrlist_entry_add(ni, a);
2534 		if (err) {
2535 			ntfs_attr_record_resize(m, a, 0);
2536 			mark_mft_record_dirty(ctx->ntfs_ino);
2537 			ntfs_debug("Failed add attribute entry to ATTRIBUTE_LIST.\n");
2538 			goto put_err_out;
2539 		}
2540 	}
2541 	mark_mft_record_dirty(ni);
2542 	ntfs_attr_put_search_ctx(ctx);
2543 	return offset;
2544 put_err_out:
2545 	ntfs_attr_put_search_ctx(ctx);
2546 	return err;
2547 }
2548 
2549 /*
2550  * ntfs_non_resident_attr_record_add - add extent of non-resident attribute
2551  * @ni:			opened ntfs inode to which MFT record add attribute
2552  * @type:		type of the new attribute extent
2553  * @name:		name of the new attribute extent
2554  * @name_len:		name length of the new attribute extent
2555  * @lowest_vcn:		lowest vcn of the new attribute extent
2556  * @dataruns_size:	dataruns size of the new attribute extent
2557  * @flags:		flags of the new attribute extent
2558  */
2559 static int ntfs_non_resident_attr_record_add(struct ntfs_inode *ni, __le32 type,
2560 		__le16 *name, u8 name_len, s64 lowest_vcn, int dataruns_size,
2561 		__le16 flags)
2562 {
2563 	struct ntfs_attr_search_ctx *ctx;
2564 	u32 length;
2565 	struct attr_record *a;
2566 	struct mft_record *m;
2567 	struct ntfs_inode *base_ni;
2568 	int err, offset;
2569 	u32 ic;
2570 
2571 	if (!ni || dataruns_size <= 0 || (!name && name_len))
2572 		return -EINVAL;
2573 
2574 	ntfs_debug("Entering for inode 0x%llx, attr 0x%x, lowest_vcn %lld, dataruns_size %d, flags 0x%x.\n",
2575 			(long long) ni->mft_no, (unsigned int) le32_to_cpu(type),
2576 			(long long) lowest_vcn, dataruns_size,
2577 			(unsigned int) le16_to_cpu(flags));
2578 
2579 	err = ntfs_attr_can_be_non_resident(ni->vol, type);
2580 	if (err) {
2581 		if (err == -EPERM)
2582 			pr_err("Attribute can't be non resident\n");
2583 		else
2584 			pr_err("ntfs_attr_can_be_non_resident failed\n");
2585 		return err;
2586 	}
2587 
2588 	/* Locate place where record should be. */
2589 	ctx = ntfs_attr_get_search_ctx(ni, NULL);
2590 	if (!ctx) {
2591 		pr_err("%s: Failed to get search context\n", __func__);
2592 		return -ENOMEM;
2593 	}
2594 	/*
2595 	 * Use ntfs_attr_find instead of ntfs_attr_lookup to find place for
2596 	 * attribute in @ni->mrec, not any extent inode in case if @ni is base
2597 	 * file record.
2598 	 */
2599 	ic = type == AT_DATA && name_len ? IGNORE_CASE : CASE_SENSITIVE;
2600 	err = ntfs_attr_find(type, name, name_len, ic, NULL, 0, ctx);
2601 	if (!err) {
2602 		err = -EEXIST;
2603 		pr_err("Attribute 0x%x already present\n", type);
2604 		goto put_err_out;
2605 	}
2606 	if (err != -ENOENT) {
2607 		pr_err("ntfs_attr_find failed\n");
2608 		err = -EIO;
2609 		goto put_err_out;
2610 	}
2611 	a = ctx->attr;
2612 	m = ctx->mrec;
2613 
2614 	/* Make room for attribute. */
2615 	dataruns_size = (dataruns_size + 7) & ~7;
2616 	length = offsetof(struct attr_record, data.non_resident.compressed_size) +
2617 		((sizeof(__le16) * name_len + 7) & ~7) + dataruns_size +
2618 		((flags & (ATTR_IS_COMPRESSED | ATTR_IS_SPARSE)) ?
2619 		 sizeof(a->data.non_resident.compressed_size) : 0);
2620 	err = ntfs_make_room_for_attr(ctx->mrec, (u8 *) ctx->attr, length);
2621 	if (err) {
2622 		pr_err("Failed to make room for attribute\n");
2623 		goto put_err_out;
2624 	}
2625 
2626 	/* Setup record fields. */
2627 	a->type = type;
2628 	a->length = cpu_to_le32(length);
2629 	a->non_resident = 1;
2630 	a->name_length = name_len;
2631 	a->name_offset = cpu_to_le16(offsetof(struct attr_record,
2632 					      data.non_resident.compressed_size) +
2633 			((flags & (ATTR_IS_COMPRESSED | ATTR_IS_SPARSE)) ?
2634 			 sizeof(a->data.non_resident.compressed_size) : 0));
2635 	a->flags = flags;
2636 	a->instance = m->next_attr_instance;
2637 	a->data.non_resident.lowest_vcn = cpu_to_le64(lowest_vcn);
2638 	a->data.non_resident.mapping_pairs_offset = cpu_to_le16(length - dataruns_size);
2639 	a->data.non_resident.compression_unit =
2640 		(flags & ATTR_IS_COMPRESSED) ? STANDARD_COMPRESSION_UNIT : 0;
2641 	/* If @lowest_vcn == 0, than setup empty attribute. */
2642 	if (!lowest_vcn) {
2643 		a->data.non_resident.highest_vcn = cpu_to_le64(-1);
2644 		a->data.non_resident.allocated_size = 0;
2645 		a->data.non_resident.data_size = 0;
2646 		a->data.non_resident.initialized_size = 0;
2647 		/* Set empty mapping pairs. */
2648 		*((u8 *)a + le16_to_cpu(a->data.non_resident.mapping_pairs_offset)) = 0;
2649 	}
2650 	if (name_len)
2651 		memcpy((u8 *)a + le16_to_cpu(a->name_offset),
2652 				name, sizeof(__le16) * name_len);
2653 	m->next_attr_instance =
2654 		cpu_to_le16((le16_to_cpu(m->next_attr_instance) + 1) & 0xffff);
2655 	if (ni->nr_extents == -1)
2656 		base_ni = ni->ext.base_ntfs_ino;
2657 	else
2658 		base_ni = ni;
2659 	if (type != AT_ATTRIBUTE_LIST && NInoAttrList(base_ni)) {
2660 		err = ntfs_attrlist_entry_add(ni, a);
2661 		if (err) {
2662 			pr_err("Failed add attr entry to attrlist\n");
2663 			ntfs_attr_record_resize(m, a, 0);
2664 			goto put_err_out;
2665 		}
2666 	}
2667 	mark_mft_record_dirty(ni);
2668 	/*
2669 	 * Locate offset from start of the MFT record where new attribute is
2670 	 * placed. We need relookup it, because record maybe moved during
2671 	 * update of attribute list.
2672 	 */
2673 	ntfs_attr_reinit_search_ctx(ctx);
2674 	err = ntfs_attr_lookup(type, name, name_len, ic,
2675 				lowest_vcn, NULL, 0, ctx);
2676 	if (err) {
2677 		pr_err("%s: attribute lookup failed\n", __func__);
2678 		ntfs_attr_put_search_ctx(ctx);
2679 		return err;
2680 
2681 	}
2682 	offset = (u8 *)ctx->attr - (u8 *)ctx->mrec;
2683 	ntfs_attr_put_search_ctx(ctx);
2684 	return offset;
2685 put_err_out:
2686 	ntfs_attr_put_search_ctx(ctx);
2687 	return err;
2688 }
2689 
2690 /*
2691  * ntfs_attr_record_rm - remove attribute extent
2692  * @ctx:	search context describing the attribute which should be removed
2693  *
2694  * If this function succeed, user should reinit search context if he/she wants
2695  * use it anymore.
2696  */
2697 int ntfs_attr_record_rm(struct ntfs_attr_search_ctx *ctx)
2698 {
2699 	struct ntfs_inode *base_ni, *ni;
2700 	__le32 type;
2701 	int err;
2702 
2703 	if (!ctx || !ctx->ntfs_ino || !ctx->mrec || !ctx->attr)
2704 		return -EINVAL;
2705 
2706 	ntfs_debug("Entering for inode 0x%llx, attr 0x%x.\n",
2707 			(long long) ctx->ntfs_ino->mft_no,
2708 			(unsigned int) le32_to_cpu(ctx->attr->type));
2709 	type = ctx->attr->type;
2710 	ni = ctx->ntfs_ino;
2711 	if (ctx->base_ntfs_ino)
2712 		base_ni = ctx->base_ntfs_ino;
2713 	else
2714 		base_ni = ctx->ntfs_ino;
2715 
2716 	/* Remove attribute itself. */
2717 	if (ntfs_attr_record_resize(ctx->mrec, ctx->attr, 0)) {
2718 		ntfs_debug("Couldn't remove attribute record. Bug or damaged MFT record.\n");
2719 		return -EIO;
2720 	}
2721 	mark_mft_record_dirty(ni);
2722 
2723 	/*
2724 	 * Remove record from $ATTRIBUTE_LIST if present and we don't want
2725 	 * delete $ATTRIBUTE_LIST itself.
2726 	 */
2727 	if (NInoAttrList(base_ni) && type != AT_ATTRIBUTE_LIST) {
2728 		err = ntfs_attrlist_entry_rm(ctx);
2729 		if (err) {
2730 			ntfs_debug("Couldn't delete record from $ATTRIBUTE_LIST.\n");
2731 			return err;
2732 		}
2733 	}
2734 
2735 	/* Post $ATTRIBUTE_LIST delete setup. */
2736 	if (type == AT_ATTRIBUTE_LIST) {
2737 		if (NInoAttrList(base_ni) && base_ni->attr_list)
2738 			kvfree(base_ni->attr_list);
2739 		base_ni->attr_list = NULL;
2740 		NInoClearAttrList(base_ni);
2741 	}
2742 
2743 	/* Free MFT record, if it doesn't contain attributes. */
2744 	if (le32_to_cpu(ctx->mrec->bytes_in_use) -
2745 			le16_to_cpu(ctx->mrec->attrs_offset) == 8) {
2746 		if (ntfs_mft_record_free(ni->vol, ni)) {
2747 			ntfs_debug("Couldn't free MFT record.\n");
2748 			return -EIO;
2749 		}
2750 		/* Remove done if we freed base inode. */
2751 		if (ni == base_ni)
2752 			return 0;
2753 		ntfs_inode_close(ni);
2754 		ctx->ntfs_ino = ni = NULL;
2755 	}
2756 
2757 	if (type == AT_ATTRIBUTE_LIST || !NInoAttrList(base_ni))
2758 		return 0;
2759 
2760 	/* Remove attribute list if we don't need it any more. */
2761 	if (!ntfs_attrlist_need(base_ni)) {
2762 		struct ntfs_attr na;
2763 		struct inode *attr_vi;
2764 
2765 		ntfs_attr_reinit_search_ctx(ctx);
2766 		if (ntfs_attr_lookup(AT_ATTRIBUTE_LIST, NULL, 0, CASE_SENSITIVE,
2767 					0, NULL, 0, ctx)) {
2768 			ntfs_debug("Couldn't find attribute list. Succeed anyway.\n");
2769 			return 0;
2770 		}
2771 		/* Deallocate clusters. */
2772 		if (ctx->attr->non_resident) {
2773 			struct runlist_element *al_rl;
2774 			size_t new_rl_count;
2775 
2776 			al_rl = ntfs_mapping_pairs_decompress(base_ni->vol,
2777 					ctx->attr, NULL, &new_rl_count);
2778 			if (IS_ERR(al_rl)) {
2779 				ntfs_debug("Couldn't decompress attribute list runlist. Succeed anyway.\n");
2780 				return 0;
2781 			}
2782 			if (ntfs_cluster_free_from_rl(base_ni->vol, al_rl))
2783 				ntfs_debug("Leaking clusters! Run chkdsk. Couldn't free clusters from attribute list runlist.\n");
2784 			kvfree(al_rl);
2785 		}
2786 		/* Remove attribute record itself. */
2787 		if (ntfs_attr_record_rm(ctx)) {
2788 			ntfs_debug("Couldn't remove attribute list. Succeed anyway.\n");
2789 			return 0;
2790 		}
2791 
2792 		na.mft_no = VFS_I(base_ni)->i_ino;
2793 		na.type = AT_ATTRIBUTE_LIST;
2794 		na.name = NULL;
2795 		na.name_len = 0;
2796 
2797 		attr_vi = ilookup5(VFS_I(base_ni)->i_sb, VFS_I(base_ni)->i_ino,
2798 				   ntfs_test_inode, &na);
2799 		if (attr_vi) {
2800 			clear_nlink(attr_vi);
2801 			iput(attr_vi);
2802 		}
2803 
2804 	}
2805 	return 0;
2806 }
2807 
2808 /*
2809  * ntfs_attr_add - add attribute to inode
2810  * @ni:		opened ntfs inode to which add attribute
2811  * @type:	type of the new attribute
2812  * @name:	name in unicode of the new attribute
2813  * @name_len:	name length in unicode characters of the new attribute
2814  * @val:	value of new attribute
2815  * @size:	size of the new attribute / length of @val (if specified)
2816  *
2817  * @val should always be specified for always resident attributes (eg. FILE_NAME
2818  * attribute), for attributes that can become non-resident @val can be NULL
2819  * (eg. DATA attribute). @size can be specified even if @val is NULL, in this
2820  * case data size will be equal to @size and initialized size will be equal
2821  * to 0.
2822  *
2823  * If inode haven't got enough space to add attribute, add attribute to one of
2824  * it extents, if no extents present or no one of them have enough space, than
2825  * allocate new extent and add attribute to it.
2826  *
2827  * If on one of this steps attribute list is needed but not present, than it is
2828  * added transparently to caller. So, this function should not be called with
2829  * @type == AT_ATTRIBUTE_LIST, if you really need to add attribute list call
2830  * ntfs_inode_add_attrlist instead.
2831  *
2832  * On success return 0. On error return -1 with errno set to the error code.
2833  */
2834 int ntfs_attr_add(struct ntfs_inode *ni, __le32 type,
2835 		__le16 *name, u8 name_len, u8 *val, s64 size)
2836 {
2837 	struct super_block *sb;
2838 	u32 attr_rec_size;
2839 	int err, i, offset;
2840 	bool is_resident;
2841 	bool can_be_non_resident = false;
2842 	struct ntfs_inode *attr_ni;
2843 	struct inode *attr_vi;
2844 	struct mft_record *ni_mrec;
2845 
2846 	if (!ni || size < 0 || type == AT_ATTRIBUTE_LIST)
2847 		return -EINVAL;
2848 
2849 	ntfs_debug("Entering for inode 0x%llx, attr %x, size %lld.\n",
2850 			(long long) ni->mft_no, type, size);
2851 
2852 	if (ni->nr_extents == -1)
2853 		ni = ni->ext.base_ntfs_ino;
2854 
2855 	/* Check the attribute type and the size. */
2856 	err = ntfs_attr_size_bounds_check(ni->vol, type, size);
2857 	if (err) {
2858 		if (err == -ENOENT)
2859 			err = -EIO;
2860 		return err;
2861 	}
2862 
2863 	sb = ni->vol->sb;
2864 	/* Sanity checks for always resident attributes. */
2865 	err = ntfs_attr_can_be_non_resident(ni->vol, type);
2866 	if (err) {
2867 		if (err != -EPERM) {
2868 			ntfs_error(sb, "ntfs_attr_can_be_non_resident failed");
2869 			goto err_out;
2870 		}
2871 		/* @val is mandatory. */
2872 		if (!val) {
2873 			ntfs_error(sb,
2874 				"val is mandatory for always resident attributes");
2875 			return -EINVAL;
2876 		}
2877 		if (size > ni->vol->mft_record_size) {
2878 			ntfs_error(sb, "Attribute is too big");
2879 			return -ERANGE;
2880 		}
2881 	} else
2882 		can_be_non_resident = true;
2883 
2884 	/*
2885 	 * Determine resident or not will be new attribute. We add 8 to size in
2886 	 * non resident case for mapping pairs.
2887 	 */
2888 	err = ntfs_attr_can_be_resident(ni->vol, type);
2889 	if (!err) {
2890 		is_resident = true;
2891 	} else {
2892 		if (err != -EPERM) {
2893 			ntfs_error(sb, "ntfs_attr_can_be_resident failed");
2894 			goto err_out;
2895 		}
2896 		is_resident = false;
2897 	}
2898 
2899 	/* Calculate attribute record size. */
2900 	if (is_resident)
2901 		attr_rec_size = offsetof(struct attr_record, data.resident.reserved) +
2902 			1 +
2903 			((name_len * sizeof(__le16) + 7) & ~7) +
2904 			((size + 7) & ~7);
2905 	else
2906 		attr_rec_size = offsetof(struct attr_record, data.non_resident.compressed_size) +
2907 			((name_len * sizeof(__le16) + 7) & ~7) + 8;
2908 
2909 	/*
2910 	 * If we have enough free space for the new attribute in the base MFT
2911 	 * record, then add attribute to it.
2912 	 */
2913 retry:
2914 	ni_mrec = map_mft_record(ni);
2915 	if (IS_ERR(ni_mrec)) {
2916 		err = -EIO;
2917 		goto err_out;
2918 	}
2919 
2920 	if (le32_to_cpu(ni_mrec->bytes_allocated) -
2921 			le32_to_cpu(ni_mrec->bytes_in_use) >= attr_rec_size) {
2922 		attr_ni = ni;
2923 		unmap_mft_record(ni);
2924 		goto add_attr_record;
2925 	}
2926 	unmap_mft_record(ni);
2927 
2928 	/* Try to add to extent inodes. */
2929 	err = ntfs_inode_attach_all_extents(ni);
2930 	if (err) {
2931 		ntfs_error(sb, "Failed to attach all extents to inode");
2932 		goto err_out;
2933 	}
2934 
2935 	for (i = 0; i < ni->nr_extents; i++) {
2936 		attr_ni = ni->ext.extent_ntfs_inos[i];
2937 		ni_mrec = map_mft_record(attr_ni);
2938 		if (IS_ERR(ni_mrec)) {
2939 			err = -EIO;
2940 			goto err_out;
2941 		}
2942 
2943 		if (le32_to_cpu(ni_mrec->bytes_allocated) -
2944 				le32_to_cpu(ni_mrec->bytes_in_use) >=
2945 				attr_rec_size) {
2946 			unmap_mft_record(attr_ni);
2947 			goto add_attr_record;
2948 		}
2949 		unmap_mft_record(attr_ni);
2950 	}
2951 
2952 	/* There is no extent that contain enough space for new attribute. */
2953 	if (!NInoAttrList(ni)) {
2954 		/* Add attribute list not present, add it and retry. */
2955 		err = ntfs_inode_add_attrlist(ni);
2956 		if (err) {
2957 			ntfs_error(sb, "Failed to add attribute list");
2958 			goto err_out;
2959 		}
2960 		goto retry;
2961 	}
2962 
2963 	attr_ni = NULL;
2964 	/* Allocate new extent. */
2965 	err = ntfs_mft_record_alloc(ni->vol, 0, &attr_ni, ni, NULL, -1);
2966 	if (err) {
2967 		ntfs_error(sb, "Failed to allocate extent record");
2968 		goto err_out;
2969 	}
2970 	unmap_mft_record(attr_ni);
2971 
2972 add_attr_record:
2973 	if (is_resident) {
2974 		/* Add resident attribute. */
2975 		offset = ntfs_resident_attr_record_add(attr_ni, type, name,
2976 				name_len, val, size, 0);
2977 		if (offset < 0) {
2978 			if (offset == -ENOSPC && can_be_non_resident)
2979 				goto add_non_resident;
2980 			err = offset;
2981 			ntfs_error(sb, "Failed to add resident attribute");
2982 			goto free_err_out;
2983 		}
2984 		return 0;
2985 	}
2986 
2987 add_non_resident:
2988 	/* Add non resident attribute. */
2989 	offset = ntfs_non_resident_attr_record_add(attr_ni, type, name,
2990 			name_len, 0, 8, 0);
2991 	if (offset < 0) {
2992 		err = offset;
2993 		ntfs_error(sb, "Failed to add non resident attribute");
2994 		goto free_err_out;
2995 	}
2996 
2997 	/* If @size == 0, we are done. */
2998 	if (!size)
2999 		return 0;
3000 
3001 	/* Open new attribute and resize it. */
3002 	attr_vi = ntfs_attr_iget(VFS_I(ni), type, name, name_len);
3003 	if (IS_ERR(attr_vi)) {
3004 		err = PTR_ERR(attr_vi);
3005 		ntfs_error(sb, "Failed to open just added attribute");
3006 		goto rm_attr_err_out;
3007 	}
3008 	attr_ni = NTFS_I(attr_vi);
3009 
3010 	/* Resize and set attribute value. */
3011 	if (ntfs_attr_truncate(attr_ni, size) ||
3012 		(val && (ntfs_inode_attr_pwrite(attr_vi, 0, size, val, false) != size))) {
3013 		err = -EIO;
3014 		ntfs_error(sb, "Failed to initialize just added attribute");
3015 		if (ntfs_attr_rm(attr_ni))
3016 			ntfs_error(sb, "Failed to remove just added attribute");
3017 		iput(attr_vi);
3018 		goto err_out;
3019 	}
3020 	iput(attr_vi);
3021 	return 0;
3022 
3023 rm_attr_err_out:
3024 	/* Remove just added attribute. */
3025 	ni_mrec = map_mft_record(attr_ni);
3026 	if (!IS_ERR(ni_mrec)) {
3027 		if (ntfs_attr_record_resize(ni_mrec,
3028 					(struct attr_record *)((u8 *)ni_mrec + offset), 0))
3029 			ntfs_error(sb, "Failed to remove just added attribute #2");
3030 		unmap_mft_record(attr_ni);
3031 	} else
3032 		pr_err("EIO when try to remove new added attr\n");
3033 
3034 free_err_out:
3035 	/* Free MFT record, if it doesn't contain attributes. */
3036 	ni_mrec = map_mft_record(attr_ni);
3037 	if (!IS_ERR(ni_mrec)) {
3038 		int attr_size;
3039 
3040 		attr_size = le32_to_cpu(ni_mrec->bytes_in_use) -
3041 			le16_to_cpu(ni_mrec->attrs_offset);
3042 		unmap_mft_record(attr_ni);
3043 		if (attr_size == 8) {
3044 			if (ntfs_mft_record_free(attr_ni->vol, attr_ni))
3045 				ntfs_error(sb, "Failed to free MFT record");
3046 			if (attr_ni->nr_extents < 0)
3047 				ntfs_inode_close(attr_ni);
3048 		}
3049 	} else
3050 		pr_err("EIO when testing mft record is free-able\n");
3051 
3052 err_out:
3053 	return err;
3054 }
3055 
3056 /*
3057  * __ntfs_attr_init - primary initialization of an ntfs attribute structure
3058  * @ni:		ntfs attribute inode to initialize
3059  * @ni:		ntfs inode with which to initialize the ntfs attribute
3060  * @type:	attribute type
3061  * @name:	attribute name in little endian Unicode or NULL
3062  * @name_len:	length of attribute @name in Unicode characters (if @name given)
3063  *
3064  * Initialize the ntfs attribute @na with @ni, @type, @name, and @name_len.
3065  */
3066 static void __ntfs_attr_init(struct ntfs_inode *ni,
3067 		const __le32 type, __le16 *name, const u32 name_len)
3068 {
3069 	ni->runlist.rl = NULL;
3070 	ni->type = type;
3071 	ni->name = name;
3072 	if (name)
3073 		ni->name_len = name_len;
3074 	else
3075 		ni->name_len = 0;
3076 }
3077 
3078 /*
3079  * ntfs_attr_init - initialize an ntfs_attr with data sizes and status
3080  * @ni: ntfs inode to initialize
3081  * @non_resident: true if attribute is non-resident
3082  * @compressed: true if attribute is compressed
3083  * @encrypted: true if attribute is encrypted
3084  * @sparse: true if attribute is sparse
3085  * @allocated_size: allocated size of the attribute
3086  * @data_size: actual data size of the attribute
3087  * @initialized_size: initialized size of the attribute
3088  * @compressed_size: compressed size (if compressed or sparse)
3089  * @compression_unit: compression unit size (log2 of clusters)
3090  *
3091  * Final initialization for an ntfs attribute.
3092  */
3093 static void ntfs_attr_init(struct ntfs_inode *ni, const bool non_resident,
3094 		const bool compressed, const bool encrypted, const bool sparse,
3095 		const s64 allocated_size, const s64 data_size,
3096 		const s64 initialized_size, const s64 compressed_size,
3097 		const u8 compression_unit)
3098 {
3099 	if (non_resident)
3100 		NInoSetNonResident(ni);
3101 	if (compressed) {
3102 		NInoSetCompressed(ni);
3103 		ni->flags |= FILE_ATTR_COMPRESSED;
3104 	}
3105 	if (encrypted) {
3106 		NInoSetEncrypted(ni);
3107 		ni->flags |= FILE_ATTR_ENCRYPTED;
3108 	}
3109 	if (sparse) {
3110 		NInoSetSparse(ni);
3111 		ni->flags |= FILE_ATTR_SPARSE_FILE;
3112 	}
3113 	ni->allocated_size = allocated_size;
3114 	ni->data_size = data_size;
3115 	ni->initialized_size = initialized_size;
3116 	if (compressed || sparse) {
3117 		struct ntfs_volume *vol = ni->vol;
3118 
3119 		ni->itype.compressed.size = compressed_size;
3120 		ni->itype.compressed.block_clusters = 1 << compression_unit;
3121 		ni->itype.compressed.block_size = 1 << (compression_unit +
3122 				vol->cluster_size_bits);
3123 		ni->itype.compressed.block_size_bits = ffs(
3124 				ni->itype.compressed.block_size) - 1;
3125 	}
3126 }
3127 
3128 /*
3129  * ntfs_attr_open - open an ntfs attribute for access
3130  * @ni:		open ntfs inode in which the ntfs attribute resides
3131  * @type:	attribute type
3132  * @name:	attribute name in little endian Unicode or AT_UNNAMED or NULL
3133  * @name_len:	length of attribute @name in Unicode characters (if @name given)
3134  */
3135 int ntfs_attr_open(struct ntfs_inode *ni, const __le32 type,
3136 		__le16 *name, u32 name_len)
3137 {
3138 	struct ntfs_attr_search_ctx *ctx;
3139 	__le16 *newname = NULL;
3140 	struct attr_record *a;
3141 	bool cs;
3142 	struct ntfs_inode *base_ni;
3143 	u32 ic;
3144 	int err;
3145 
3146 	if (!ni || !ni->vol)
3147 		return -EINVAL;
3148 
3149 	ntfs_debug("Entering for inode %lld, attr 0x%x.\n",
3150 			ni->mft_no, type);
3151 
3152 	base_ni = ntfs_base_inode(ni);
3153 
3154 	if (name && name != AT_UNNAMED && name != I30) {
3155 		name = ntfs_ucsndup(name, name_len);
3156 		if (!name) {
3157 			err = -ENOMEM;
3158 			goto err_out;
3159 		}
3160 		newname = name;
3161 	}
3162 
3163 	ctx = ntfs_attr_get_search_ctx(base_ni, NULL);
3164 	if (!ctx) {
3165 		err = -ENOMEM;
3166 		pr_err("%s: Failed to get search context\n", __func__);
3167 		goto err_out;
3168 	}
3169 
3170 	ic = type == AT_DATA && name_len ? IGNORE_CASE : CASE_SENSITIVE;
3171 	err = ntfs_attr_lookup(type, name, name_len, ic, 0, NULL, 0, ctx);
3172 	if (err)
3173 		goto put_err_out;
3174 
3175 	a = ctx->attr;
3176 
3177 	if (!name) {
3178 		if (a->name_length) {
3179 			name = ntfs_ucsndup((__le16 *)((u8 *)a + le16_to_cpu(a->name_offset)),
3180 					    a->name_length);
3181 			if (!name)
3182 				goto put_err_out;
3183 			newname = name;
3184 			name_len = a->name_length;
3185 		} else {
3186 			name = AT_UNNAMED;
3187 			name_len = 0;
3188 		}
3189 	}
3190 
3191 	__ntfs_attr_init(ni, type, name, name_len);
3192 
3193 	/*
3194 	 * Wipe the flags in case they are not zero for an attribute list
3195 	 * attribute.  Windows does not complain about invalid flags and chkdsk
3196 	 * does not detect or fix them so we need to cope with it, too.
3197 	 */
3198 	if (type == AT_ATTRIBUTE_LIST)
3199 		a->flags = 0;
3200 
3201 	if ((type == AT_DATA) &&
3202 	    (a->non_resident ? !a->data.non_resident.initialized_size :
3203 	     !a->data.resident.value_length)) {
3204 		/*
3205 		 * Define/redefine the compression state if stream is
3206 		 * empty, based on the compression mark on parent
3207 		 * directory (for unnamed data streams) or on current
3208 		 * inode (for named data streams). The compression mark
3209 		 * may change any time, the compression state can only
3210 		 * change when stream is wiped out.
3211 		 *
3212 		 * Also prevent compression on NTFS version < 3.0
3213 		 * or cluster size > 4K or compression is disabled
3214 		 */
3215 		a->flags &= ~ATTR_COMPRESSION_MASK;
3216 		if (NInoCompressed(ni)
3217 				&& (ni->vol->major_ver >= 3)
3218 				&& NVolCompression(ni->vol)
3219 				&& (ni->vol->cluster_size <= MAX_COMPRESSION_CLUSTER_SIZE))
3220 			a->flags |= ATTR_IS_COMPRESSED;
3221 	}
3222 
3223 	cs = a->flags & (ATTR_IS_COMPRESSED | ATTR_IS_SPARSE);
3224 
3225 	if (ni->type == AT_DATA && ni->name == AT_UNNAMED &&
3226 	    ((!(a->flags & ATTR_IS_COMPRESSED) != !NInoCompressed(ni)) ||
3227 	     (!(a->flags & ATTR_IS_SPARSE)     != !NInoSparse(ni)) ||
3228 	     (!(a->flags & ATTR_IS_ENCRYPTED)  != !NInoEncrypted(ni)))) {
3229 		err = -EIO;
3230 		pr_err("Inode %lld has corrupt attribute flags (0x%x <> 0x%x)\n",
3231 				(unsigned long long)ni->mft_no,
3232 				a->flags, ni->flags);
3233 		goto put_err_out;
3234 	}
3235 
3236 	if (a->non_resident) {
3237 		if (((a->flags & ATTR_COMPRESSION_MASK) || a->data.non_resident.compression_unit) &&
3238 				(ni->vol->major_ver < 3)) {
3239 			err = -EIO;
3240 			pr_err("Compressed inode %lld not allowed  on NTFS %d.%d\n",
3241 					(unsigned long long)ni->mft_no,
3242 					ni->vol->major_ver,
3243 					ni->vol->major_ver);
3244 			goto put_err_out;
3245 		}
3246 
3247 		if ((a->flags & ATTR_IS_COMPRESSED) && !a->data.non_resident.compression_unit) {
3248 			err = -EIO;
3249 			pr_err("Compressed inode %lld attr 0x%x has no compression unit\n",
3250 					(unsigned long long)ni->mft_no, type);
3251 			goto put_err_out;
3252 		}
3253 		if ((a->flags & ATTR_COMPRESSION_MASK) &&
3254 		    (a->data.non_resident.compression_unit != STANDARD_COMPRESSION_UNIT)) {
3255 			err = -EIO;
3256 			pr_err("Compressed inode %lld attr 0x%lx has an unsupported compression unit %d\n",
3257 					(unsigned long long)ni->mft_no,
3258 					(long)le32_to_cpu(type),
3259 					(int)a->data.non_resident.compression_unit);
3260 			goto put_err_out;
3261 		}
3262 		ntfs_attr_init(ni, true, a->flags & ATTR_IS_COMPRESSED,
3263 				a->flags & ATTR_IS_ENCRYPTED,
3264 				a->flags & ATTR_IS_SPARSE,
3265 				le64_to_cpu(a->data.non_resident.allocated_size),
3266 				le64_to_cpu(a->data.non_resident.data_size),
3267 				le64_to_cpu(a->data.non_resident.initialized_size),
3268 				cs ? le64_to_cpu(a->data.non_resident.compressed_size) : 0,
3269 				cs ? a->data.non_resident.compression_unit : 0);
3270 	} else {
3271 		s64 l = le32_to_cpu(a->data.resident.value_length);
3272 
3273 		ntfs_attr_init(ni, false, a->flags & ATTR_IS_COMPRESSED,
3274 				a->flags & ATTR_IS_ENCRYPTED,
3275 				a->flags & ATTR_IS_SPARSE, (l + 7) & ~7, l, l,
3276 				cs ? (l + 7) & ~7 : 0, 0);
3277 	}
3278 	ntfs_attr_put_search_ctx(ctx);
3279 out:
3280 	ntfs_debug("\n");
3281 	return err;
3282 
3283 put_err_out:
3284 	ntfs_attr_put_search_ctx(ctx);
3285 err_out:
3286 	kfree(newname);
3287 	goto out;
3288 }
3289 
3290 /*
3291  * ntfs_attr_close - free an ntfs attribute structure
3292  * @ni:		ntfs inode to free
3293  *
3294  * Release all memory associated with the ntfs attribute @na and then release
3295  * @na itself.
3296  */
3297 void ntfs_attr_close(struct ntfs_inode *ni)
3298 {
3299 	if (NInoNonResident(ni) && ni->runlist.rl)
3300 		kvfree(ni->runlist.rl);
3301 	/* Don't release if using an internal constant. */
3302 	if (ni->name != AT_UNNAMED && ni->name != I30)
3303 		kfree(ni->name);
3304 }
3305 
3306 /*
3307  * ntfs_attr_map_whole_runlist - map the whole runlist of an ntfs attribute
3308  * @ni:		ntfs inode for which to map the runlist
3309  *
3310  * Map the whole runlist of the ntfs attribute @na.  For an attribute made up
3311  * of only one attribute extent this is the same as calling
3312  * ntfs_map_runlist(ni, 0) but for an attribute with multiple extents this
3313  * will map the runlist fragments from each of the extents thus giving access
3314  * to the entirety of the disk allocation of an attribute.
3315  */
3316 int ntfs_attr_map_whole_runlist(struct ntfs_inode *ni)
3317 {
3318 	s64 next_vcn, last_vcn, highest_vcn;
3319 	struct ntfs_attr_search_ctx *ctx;
3320 	struct ntfs_volume *vol = ni->vol;
3321 	struct super_block *sb = vol->sb;
3322 	struct attr_record *a;
3323 	int err;
3324 	struct ntfs_inode *base_ni;
3325 	int not_mapped;
3326 	size_t new_rl_count;
3327 
3328 	ntfs_debug("Entering for inode 0x%llx, attr 0x%x.\n",
3329 			(unsigned long long)ni->mft_no, ni->type);
3330 
3331 	if (NInoFullyMapped(ni) && ni->runlist.rl)
3332 		return 0;
3333 
3334 	if (NInoAttr(ni))
3335 		base_ni = ni->ext.base_ntfs_ino;
3336 	else
3337 		base_ni = ni;
3338 
3339 	ctx = ntfs_attr_get_search_ctx(base_ni, NULL);
3340 	if (!ctx) {
3341 		ntfs_error(sb, "%s: Failed to get search context", __func__);
3342 		return -ENOMEM;
3343 	}
3344 
3345 	/* Map all attribute extents one by one. */
3346 	next_vcn = last_vcn = highest_vcn = 0;
3347 	a = NULL;
3348 	while (1) {
3349 		struct runlist_element *rl;
3350 
3351 		not_mapped = 0;
3352 		if (ntfs_rl_vcn_to_lcn(ni->runlist.rl, next_vcn) == LCN_RL_NOT_MAPPED)
3353 			not_mapped = 1;
3354 
3355 		err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
3356 					CASE_SENSITIVE, next_vcn,
3357 					NULL, 0, ctx);
3358 		if (err)
3359 			break;
3360 
3361 		a = ctx->attr;
3362 
3363 		if (not_mapped) {
3364 			/* Decode the runlist. */
3365 			rl = ntfs_mapping_pairs_decompress(ni->vol, a, &ni->runlist,
3366 							   &new_rl_count);
3367 			if (IS_ERR(rl)) {
3368 				err = PTR_ERR(rl);
3369 				goto err_out;
3370 			}
3371 			ni->runlist.rl = rl;
3372 			ni->runlist.count = new_rl_count;
3373 		}
3374 
3375 		/* Are we in the first extent? */
3376 		if (!next_vcn) {
3377 			if (a->data.non_resident.lowest_vcn) {
3378 				err = -EIO;
3379 				ntfs_error(sb,
3380 					"First extent of inode %llu attribute has non-zero lowest_vcn",
3381 					(unsigned long long)ni->mft_no);
3382 				goto err_out;
3383 			}
3384 			/* Get the last vcn in the attribute. */
3385 			last_vcn = ntfs_bytes_to_cluster(vol,
3386 					le64_to_cpu(a->data.non_resident.allocated_size));
3387 		}
3388 
3389 		/* Get the lowest vcn for the next extent. */
3390 		highest_vcn = le64_to_cpu(a->data.non_resident.highest_vcn);
3391 		next_vcn = highest_vcn + 1;
3392 
3393 		/* Only one extent or error, which we catch below. */
3394 		if (next_vcn <= 0) {
3395 			err = -ENOENT;
3396 			break;
3397 		}
3398 
3399 		/* Avoid endless loops due to corruption. */
3400 		if (next_vcn < le64_to_cpu(a->data.non_resident.lowest_vcn)) {
3401 			err = -EIO;
3402 			ntfs_error(sb, "Inode %llu has corrupt attribute list",
3403 					(unsigned long long)ni->mft_no);
3404 			goto err_out;
3405 		}
3406 	}
3407 	if (!a) {
3408 		ntfs_error(sb, "Couldn't find attribute for runlist mapping");
3409 		goto err_out;
3410 	}
3411 	if (not_mapped && highest_vcn && highest_vcn != last_vcn - 1) {
3412 		err = -EIO;
3413 		ntfs_error(sb,
3414 			"Failed to load full runlist: inode: %llu highest_vcn: 0x%llx last_vcn: 0x%llx",
3415 			(unsigned long long)ni->mft_no,
3416 			(long long)highest_vcn, (long long)last_vcn);
3417 		goto err_out;
3418 	}
3419 	ntfs_attr_put_search_ctx(ctx);
3420 	if (err == -ENOENT) {
3421 		NInoSetFullyMapped(ni);
3422 		return 0;
3423 	}
3424 
3425 	return err;
3426 
3427 err_out:
3428 	ntfs_attr_put_search_ctx(ctx);
3429 	return err;
3430 }
3431 
3432 /*
3433  * ntfs_attr_record_move_to - move attribute record to target inode
3434  * @ctx:	attribute search context describing the attribute record
3435  * @ni:		opened ntfs inode to which move attribute record
3436  */
3437 int ntfs_attr_record_move_to(struct ntfs_attr_search_ctx *ctx, struct ntfs_inode *ni)
3438 {
3439 	struct ntfs_attr_search_ctx *nctx;
3440 	struct attr_record *a;
3441 	int err;
3442 	u32 ic;
3443 	struct mft_record *ni_mrec;
3444 	struct super_block *sb;
3445 
3446 	if (!ctx || !ctx->attr || !ctx->ntfs_ino || !ni) {
3447 		ntfs_debug("Invalid arguments passed.\n");
3448 		return -EINVAL;
3449 	}
3450 
3451 	sb = ni->vol->sb;
3452 	ntfs_debug("Entering for ctx->attr->type 0x%x, ctx->ntfs_ino->mft_no 0x%llx, ni->mft_no 0x%llx.\n",
3453 			(unsigned int) le32_to_cpu(ctx->attr->type),
3454 			(long long) ctx->ntfs_ino->mft_no,
3455 			(long long) ni->mft_no);
3456 
3457 	if (ctx->ntfs_ino == ni)
3458 		return 0;
3459 
3460 	if (!ctx->al_entry) {
3461 		ntfs_debug("Inode should contain attribute list to use this function.\n");
3462 		return -EINVAL;
3463 	}
3464 
3465 	/* Find place in MFT record where attribute will be moved. */
3466 	a = ctx->attr;
3467 	nctx = ntfs_attr_get_search_ctx(ni, NULL);
3468 	if (!nctx) {
3469 		ntfs_error(sb, "%s: Failed to get search context", __func__);
3470 		return -ENOMEM;
3471 	}
3472 
3473 	/*
3474 	 * Use ntfs_attr_find instead of ntfs_attr_lookup to find place for
3475 	 * attribute in @ni->mrec, not any extent inode in case if @ni is base
3476 	 * file record.
3477 	 */
3478 	ic = a->type == AT_DATA && a->name_length ?
3479 			IGNORE_CASE : CASE_SENSITIVE;
3480 	err = ntfs_attr_find(a->type,
3481 			(__le16 *)((u8 *)a + le16_to_cpu(a->name_offset)),
3482 			a->name_length, ic, NULL, 0, nctx);
3483 	if (!err) {
3484 		ntfs_debug("Attribute of such type, with same name already present in this MFT record.\n");
3485 		err = -EEXIST;
3486 		goto put_err_out;
3487 	}
3488 	if (err != -ENOENT) {
3489 		ntfs_debug("Attribute lookup failed.\n");
3490 		goto put_err_out;
3491 	}
3492 
3493 	/* Make space and move attribute. */
3494 	ni_mrec = map_mft_record(ni);
3495 	if (IS_ERR(ni_mrec)) {
3496 		err = -EIO;
3497 		goto put_err_out;
3498 	}
3499 
3500 	err = ntfs_make_room_for_attr(ni_mrec, (u8 *) nctx->attr,
3501 				le32_to_cpu(a->length));
3502 	if (err) {
3503 		ntfs_debug("Couldn't make space for attribute.\n");
3504 		unmap_mft_record(ni);
3505 		goto put_err_out;
3506 	}
3507 	memcpy(nctx->attr, a, le32_to_cpu(a->length));
3508 	nctx->attr->instance = nctx->mrec->next_attr_instance;
3509 	nctx->mrec->next_attr_instance =
3510 		cpu_to_le16((le16_to_cpu(nctx->mrec->next_attr_instance) + 1) & 0xffff);
3511 	ntfs_attr_record_resize(ctx->mrec, a, 0);
3512 	mark_mft_record_dirty(ctx->ntfs_ino);
3513 	mark_mft_record_dirty(ni);
3514 
3515 	/* Update attribute list. */
3516 	ctx->al_entry->mft_reference =
3517 		MK_LE_MREF(ni->mft_no, le16_to_cpu(ni_mrec->sequence_number));
3518 	ctx->al_entry->instance = nctx->attr->instance;
3519 	unmap_mft_record(ni);
3520 put_err_out:
3521 	ntfs_attr_put_search_ctx(nctx);
3522 	return err;
3523 }
3524 
3525 /*
3526  * ntfs_attr_record_move_away - move away attribute record from it's mft record
3527  * @ctx:	attribute search context describing the attribute record
3528  * @extra:	minimum amount of free space in the new holder of record
3529  */
3530 int ntfs_attr_record_move_away(struct ntfs_attr_search_ctx *ctx, int extra)
3531 {
3532 	struct ntfs_inode *base_ni, *ni = NULL;
3533 	struct mft_record *m;
3534 	int i, err;
3535 	struct super_block *sb;
3536 
3537 	if (!ctx || !ctx->attr || !ctx->ntfs_ino || extra < 0)
3538 		return -EINVAL;
3539 
3540 	ntfs_debug("Entering for attr 0x%x, inode %llu\n",
3541 			(unsigned int) le32_to_cpu(ctx->attr->type),
3542 			(unsigned long long)ctx->ntfs_ino->mft_no);
3543 
3544 	if (ctx->ntfs_ino->nr_extents == -1)
3545 		base_ni = ctx->base_ntfs_ino;
3546 	else
3547 		base_ni = ctx->ntfs_ino;
3548 
3549 	sb = ctx->ntfs_ino->vol->sb;
3550 	if (!NInoAttrList(base_ni)) {
3551 		ntfs_error(sb, "Inode %llu has no attrlist",
3552 				(unsigned long long)base_ni->mft_no);
3553 		return -EINVAL;
3554 	}
3555 
3556 	err = ntfs_inode_attach_all_extents(ctx->ntfs_ino);
3557 	if (err) {
3558 		ntfs_error(sb, "Couldn't attach extents, inode=%llu",
3559 			(unsigned long long)base_ni->mft_no);
3560 		return err;
3561 	}
3562 
3563 	mutex_lock(&base_ni->extent_lock);
3564 	/* Walk through all extents and try to move attribute to them. */
3565 	for (i = 0; i < base_ni->nr_extents; i++) {
3566 		ni = base_ni->ext.extent_ntfs_inos[i];
3567 
3568 		if (ctx->ntfs_ino->mft_no == ni->mft_no)
3569 			continue;
3570 		m = map_mft_record(ni);
3571 		if (IS_ERR(m)) {
3572 			ntfs_error(sb, "Can not map mft record for mft_no %lld",
3573 					(unsigned long long)ni->mft_no);
3574 			mutex_unlock(&base_ni->extent_lock);
3575 			return -EIO;
3576 		}
3577 		if (le32_to_cpu(m->bytes_allocated) -
3578 		    le32_to_cpu(m->bytes_in_use) < le32_to_cpu(ctx->attr->length) + extra) {
3579 			unmap_mft_record(ni);
3580 			continue;
3581 		}
3582 		unmap_mft_record(ni);
3583 
3584 		/*
3585 		 * ntfs_attr_record_move_to can fail if extent with other lowest
3586 		 * s64 already present in inode we trying move record to. So,
3587 		 * do not return error.
3588 		 */
3589 		if (!ntfs_attr_record_move_to(ctx, ni)) {
3590 			mutex_unlock(&base_ni->extent_lock);
3591 			return 0;
3592 		}
3593 	}
3594 	mutex_unlock(&base_ni->extent_lock);
3595 
3596 	/*
3597 	 * Failed to move attribute to one of the current extents, so allocate
3598 	 * new extent and move attribute to it.
3599 	 */
3600 	ni = NULL;
3601 	err = ntfs_mft_record_alloc(base_ni->vol, 0, &ni, base_ni, NULL, -1);
3602 	if (err) {
3603 		ntfs_error(sb, "Couldn't allocate MFT record, err : %d", err);
3604 		return err;
3605 	}
3606 	unmap_mft_record(ni);
3607 
3608 	err = ntfs_attr_record_move_to(ctx, ni);
3609 	if (err) {
3610 		ntfs_error(sb, "Couldn't move attribute to MFT record");
3611 		if (ntfs_mft_record_free(base_ni->vol, ni))
3612 			ntfs_error(sb, "Couldn't free empty MFT record");
3613 		else
3614 			ntfs_inode_close(ni);
3615 	}
3616 
3617 	return err;
3618 }
3619 
3620 /*
3621  * If we are in the first extent, then set/clean sparse bit,
3622  * update allocated and compressed size.
3623  */
3624 static int ntfs_attr_update_meta(struct attr_record *a, struct ntfs_inode *ni,
3625 		struct mft_record *m, struct ntfs_attr_search_ctx *ctx,
3626 		struct ntfs_inode *locked_ni, bool defer_attrlist)
3627 {
3628 	int sparse, err = 0;
3629 	struct ntfs_inode *base_ni;
3630 	struct super_block *sb = ni->vol->sb;
3631 
3632 	ntfs_debug("Entering for inode 0x%llx, attr 0x%x\n",
3633 			(unsigned long long)ni->mft_no, ni->type);
3634 
3635 	if (NInoAttr(ni))
3636 		base_ni = ni->ext.base_ntfs_ino;
3637 	else
3638 		base_ni = ni;
3639 
3640 	if (a->data.non_resident.lowest_vcn)
3641 		goto out;
3642 
3643 	a->data.non_resident.allocated_size = cpu_to_le64(ni->allocated_size);
3644 
3645 	sparse = ntfs_rl_sparse(ni->runlist.rl);
3646 	if (sparse < 0) {
3647 		err = -EIO;
3648 		goto out;
3649 	}
3650 
3651 	/* Attribute become sparse. */
3652 	if (sparse && !(a->flags & (ATTR_IS_SPARSE | ATTR_IS_COMPRESSED))) {
3653 		/*
3654 		 * Move attribute to another mft record, if attribute is too
3655 		 * small to add compressed_size field to it and we have no
3656 		 * free space in the current mft record.
3657 		 */
3658 		if ((le32_to_cpu(a->length) -
3659 		     le16_to_cpu(a->data.non_resident.mapping_pairs_offset) == 8) &&
3660 		    !(le32_to_cpu(m->bytes_allocated) - le32_to_cpu(m->bytes_in_use))) {
3661 
3662 			if (defer_attrlist)
3663 				return -ENOSPC;
3664 			if (!NInoAttrList(base_ni)) {
3665 				err = ntfs_inode_add_attrlist(base_ni);
3666 				if (err)
3667 					goto out;
3668 				err = -EAGAIN;
3669 				goto out;
3670 			}
3671 			err = ntfs_attr_record_move_away(ctx, 8);
3672 			if (err) {
3673 				ntfs_error(sb, "Failed to move attribute");
3674 				goto out;
3675 			}
3676 
3677 			err = ntfs_attrlist_update_locked(base_ni, locked_ni);
3678 			if (err)
3679 				goto out;
3680 			err = -EAGAIN;
3681 			goto out;
3682 		}
3683 		if (!(le32_to_cpu(a->length) -
3684 		    le16_to_cpu(a->data.non_resident.mapping_pairs_offset))) {
3685 			err = -EIO;
3686 			ntfs_error(sb, "Mapping pairs space is 0");
3687 			goto out;
3688 		}
3689 
3690 		NInoSetSparse(ni);
3691 		ni->flags |= FILE_ATTR_SPARSE_FILE;
3692 		a->flags |= ATTR_IS_SPARSE;
3693 		a->data.non_resident.compression_unit = 0;
3694 
3695 		memmove((u8 *)a + le16_to_cpu(a->name_offset) + 8,
3696 				(u8 *)a + le16_to_cpu(a->name_offset),
3697 				a->name_length * sizeof(__le16));
3698 
3699 		a->name_offset = cpu_to_le16(le16_to_cpu(a->name_offset) + 8);
3700 
3701 		a->data.non_resident.mapping_pairs_offset =
3702 			cpu_to_le16(le16_to_cpu(a->data.non_resident.mapping_pairs_offset) + 8);
3703 	}
3704 
3705 	/* Attribute no longer sparse. */
3706 	if (!sparse && (a->flags & ATTR_IS_SPARSE) &&
3707 	    !(a->flags & ATTR_IS_COMPRESSED)) {
3708 		NInoClearSparse(ni);
3709 		ni->flags &= ~FILE_ATTR_SPARSE_FILE;
3710 		a->flags &= ~ATTR_IS_SPARSE;
3711 		a->data.non_resident.compression_unit = 0;
3712 
3713 		memmove((u8 *)a + le16_to_cpu(a->name_offset) - 8,
3714 				(u8 *)a + le16_to_cpu(a->name_offset),
3715 				a->name_length * sizeof(__le16));
3716 
3717 		if (le16_to_cpu(a->name_offset) >= 8)
3718 			a->name_offset = cpu_to_le16(le16_to_cpu(a->name_offset) - 8);
3719 
3720 		a->data.non_resident.mapping_pairs_offset =
3721 			cpu_to_le16(le16_to_cpu(a->data.non_resident.mapping_pairs_offset) - 8);
3722 	}
3723 
3724 	/* Update compressed size if required. */
3725 	if (NInoFullyMapped(ni) && (sparse || NInoCompressed(ni))) {
3726 		s64 new_compr_size;
3727 
3728 		new_compr_size = ntfs_rl_get_compressed_size(ni->vol, ni->runlist.rl);
3729 		if (new_compr_size < 0) {
3730 			err = new_compr_size;
3731 			goto out;
3732 		}
3733 
3734 		ni->itype.compressed.size = new_compr_size;
3735 		a->data.non_resident.compressed_size = cpu_to_le64(new_compr_size);
3736 	}
3737 
3738 	if (NInoSparse(ni) || NInoCompressed(ni))
3739 		VFS_I(base_ni)->i_blocks = ni->itype.compressed.size >> 9;
3740 	else
3741 		VFS_I(base_ni)->i_blocks = ni->allocated_size >> 9;
3742 	/*
3743 	 * Set FILE_NAME dirty flag, to update sparse bit and
3744 	 * allocated size in the index.
3745 	 */
3746 	if (ni->type == AT_DATA && ni->name == AT_UNNAMED)
3747 		NInoSetFileNameDirty(ni);
3748 out:
3749 	return err;
3750 }
3751 
3752 #define NTFS_VCN_DELETE_MARK -2
3753 /*
3754  * ntfs_attr_update_mapping_pairs - update mapping pairs for ntfs attribute
3755  * @ni:		non-resident ntfs inode for which we need update
3756  * @from_vcn:	update runlist starting this VCN
3757  * @locked_ni:	inode whose runlist write lock is already held
3758  * @defer_attrlist: return -ENOSPC instead of updating an attribute list
3759  *
3760  * Build mapping pairs from @na->rl and write them to the disk. Also, this
3761  * function updates sparse bit, allocated and compressed size (allocates/frees
3762  * space for this field if required).
3763  *
3764  * @na->allocated_size should be set to correct value for the new runlist before
3765  * call to this function. Vice-versa @na->compressed_size will be calculated and
3766  * set to correct value during this function.
3767  */
3768 static int __ntfs_attr_update_mapping_pairs(struct ntfs_inode *ni,
3769 					    s64 from_vcn,
3770 					    struct ntfs_inode *locked_ni,
3771 					    bool defer_attrlist)
3772 {
3773 	struct ntfs_attr_search_ctx *ctx;
3774 	struct ntfs_inode *base_ni;
3775 	struct mft_record *m;
3776 	struct attr_record *a;
3777 	s64 stop_vcn;
3778 	int err = 0, mp_size, cur_max_mp_size, exp_max_mp_size;
3779 	bool finished_build;
3780 	bool first_updated = false;
3781 	struct super_block *sb;
3782 	struct runlist_element *start_rl;
3783 	unsigned int de_cluster_count = 0;
3784 
3785 retry:
3786 	if (!ni || !ni->runlist.rl)
3787 		return -EINVAL;
3788 
3789 	ntfs_debug("Entering for inode %llu, attr 0x%x\n",
3790 			(unsigned long long)ni->mft_no, ni->type);
3791 
3792 	sb = ni->vol->sb;
3793 	if (!NInoNonResident(ni)) {
3794 		ntfs_error(sb, "%s: resident attribute", __func__);
3795 		return -EINVAL;
3796 	}
3797 
3798 	if (ni->nr_extents == -1)
3799 		base_ni = ni->ext.base_ntfs_ino;
3800 	else
3801 		base_ni = ni;
3802 
3803 	ctx = ntfs_attr_get_search_ctx(base_ni, NULL);
3804 	if (!ctx) {
3805 		ntfs_error(sb, "%s: Failed to get search context", __func__);
3806 		return -ENOMEM;
3807 	}
3808 
3809 	/* Fill attribute records with new mapping pairs. */
3810 	stop_vcn = 0;
3811 	finished_build = false;
3812 	start_rl = ni->runlist.rl;
3813 	while (!(err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
3814 				CASE_SENSITIVE, from_vcn, NULL,
3815 				0, ctx))) {
3816 		unsigned int de_cnt = 0;
3817 
3818 		a = ctx->attr;
3819 		m = ctx->mrec;
3820 		if (!a->data.non_resident.lowest_vcn)
3821 			first_updated = true;
3822 
3823 		/*
3824 		 * If runlist is updating not from the beginning, then set
3825 		 * @stop_vcn properly, i.e. to the lowest vcn of record that
3826 		 * contain @from_vcn. Also we do not need @from_vcn anymore,
3827 		 * set it to 0 to make ntfs_attr_lookup enumerate attributes.
3828 		 */
3829 		if (from_vcn) {
3830 			s64 first_lcn;
3831 
3832 			stop_vcn = le64_to_cpu(a->data.non_resident.lowest_vcn);
3833 			from_vcn = 0;
3834 			/*
3835 			 * Check whether the first run we need to update is
3836 			 * the last run in runlist, if so, then deallocate
3837 			 * all attrubute extents starting this one.
3838 			 */
3839 			first_lcn = ntfs_rl_vcn_to_lcn(ni->runlist.rl, stop_vcn);
3840 			if (first_lcn == LCN_EINVAL) {
3841 				err = -EIO;
3842 				ntfs_error(sb, "Bad runlist");
3843 				goto put_err_out;
3844 			}
3845 			if (first_lcn == LCN_ENOENT ||
3846 			    first_lcn == LCN_RL_NOT_MAPPED)
3847 				finished_build = true;
3848 		}
3849 
3850 		/*
3851 		 * Check whether we finished mapping pairs build, if so mark
3852 		 * extent as need to delete (by setting highest vcn to
3853 		 * NTFS_VCN_DELETE_MARK (-2), we shall check it later and
3854 		 * delete extent) and continue search.
3855 		 */
3856 		if (finished_build) {
3857 			ntfs_debug("Mark attr 0x%x for delete in inode 0x%llx.\n",
3858 				(unsigned int)le32_to_cpu(a->type), ctx->ntfs_ino->mft_no);
3859 			a->data.non_resident.highest_vcn = cpu_to_le64(NTFS_VCN_DELETE_MARK);
3860 			mark_mft_record_dirty(ctx->ntfs_ino);
3861 			continue;
3862 		}
3863 
3864 		err = ntfs_attr_update_meta(a, ni, m, ctx, locked_ni,
3865 					    defer_attrlist);
3866 		if (err < 0) {
3867 			if (err == -EAGAIN) {
3868 				ntfs_attr_put_search_ctx(ctx);
3869 				goto retry;
3870 			}
3871 			goto put_err_out;
3872 		}
3873 
3874 		/*
3875 		 * Determine maximum possible length of mapping pairs,
3876 		 * if we shall *not* expand space for mapping pairs.
3877 		 */
3878 		cur_max_mp_size = le32_to_cpu(a->length) -
3879 			le16_to_cpu(a->data.non_resident.mapping_pairs_offset);
3880 		/*
3881 		 * Determine maximum possible length of mapping pairs in the
3882 		 * current mft record, if we shall expand space for mapping
3883 		 * pairs.
3884 		 */
3885 		exp_max_mp_size = le32_to_cpu(m->bytes_allocated) -
3886 			le32_to_cpu(m->bytes_in_use) + cur_max_mp_size;
3887 
3888 		/* Get the size for the rest of mapping pairs array. */
3889 		mp_size = ntfs_get_size_for_mapping_pairs(ni->vol, start_rl,
3890 				stop_vcn, -1, exp_max_mp_size);
3891 		if (mp_size <= 0) {
3892 			err = mp_size;
3893 			ntfs_error(sb, "%s: get MP size failed", __func__);
3894 			goto put_err_out;
3895 		}
3896 		/* Test mapping pairs for fitting in the current mft record. */
3897 		if (mp_size > exp_max_mp_size) {
3898 			/*
3899 			 * Mapping pairs of $ATTRIBUTE_LIST attribute must fit
3900 			 * in the base mft record. Try to move out other
3901 			 * attributes and try again.
3902 			 */
3903 			if (ni->type == AT_ATTRIBUTE_LIST) {
3904 				ntfs_attr_put_search_ctx(ctx);
3905 				ctx = NULL;
3906 				if (locked_ni == ni || defer_attrlist) {
3907 					err = -ENOSPC;
3908 					goto put_err_out;
3909 				}
3910 				err = ntfs_inode_free_space(base_ni, mp_size -
3911 							cur_max_mp_size);
3912 				if (err)
3913 					return err;
3914 				err = ntfs_attrlist_update_locked(
3915 					base_ni, locked_ni);
3916 				if (err)
3917 					return err;
3918 				goto retry;
3919 			}
3920 
3921 			/* Add attribute list if it isn't present, and retry. */
3922 			if (!NInoAttrList(base_ni)) {
3923 				if (defer_attrlist) {
3924 					err = -ENOSPC;
3925 					goto put_err_out;
3926 				}
3927 				ntfs_attr_put_search_ctx(ctx);
3928 				if (ntfs_inode_add_attrlist(base_ni)) {
3929 					ntfs_error(sb, "Can not add attrlist");
3930 					return -EIO;
3931 				}
3932 				goto retry;
3933 			}
3934 
3935 			/*
3936 			 * Set mapping pairs size to maximum possible for this
3937 			 * mft record. We shall write the rest of mapping pairs
3938 			 * to another MFT records.
3939 			 */
3940 			mp_size = exp_max_mp_size;
3941 		}
3942 
3943 		/* Change space for mapping pairs if we need it. */
3944 		if (((mp_size + 7) & ~7) != cur_max_mp_size) {
3945 			if (ntfs_attr_record_resize(m, a,
3946 					le16_to_cpu(a->data.non_resident.mapping_pairs_offset) +
3947 						mp_size)) {
3948 				err = -EIO;
3949 				ntfs_error(sb, "Failed to resize attribute");
3950 				goto put_err_out;
3951 			}
3952 		}
3953 
3954 		if (defer_attrlist &&
3955 		    (ctx->ntfs_ino->nr_extents == -1 ||
3956 		     NInoAttrList(ctx->ntfs_ino)) &&
3957 		    ctx->attr->type != AT_ATTRIBUTE_LIST) {
3958 			err = -ENOSPC;
3959 			goto put_err_out;
3960 		}
3961 
3962 		/* Update lowest vcn. */
3963 		a->data.non_resident.lowest_vcn = cpu_to_le64(stop_vcn);
3964 		mark_mft_record_dirty(ctx->ntfs_ino);
3965 		if ((ctx->ntfs_ino->nr_extents == -1 || NInoAttrList(ctx->ntfs_ino)) &&
3966 		    ctx->attr->type != AT_ATTRIBUTE_LIST) {
3967 			ctx->al_entry->lowest_vcn = cpu_to_le64(stop_vcn);
3968 			err = ntfs_attrlist_update_locked(base_ni, locked_ni);
3969 			if (err)
3970 				goto put_err_out;
3971 		}
3972 
3973 		/*
3974 		 * Generate the new mapping pairs array directly into the
3975 		 * correct destination, i.e. the attribute record itself.
3976 		 */
3977 		err = ntfs_mapping_pairs_build(ni->vol,
3978 				(u8 *)a + le16_to_cpu(a->data.non_resident.mapping_pairs_offset),
3979 				mp_size, start_rl, stop_vcn, -1, &stop_vcn, &start_rl, &de_cnt);
3980 		if (!err)
3981 			finished_build = true;
3982 		if (!finished_build && err != -ENOSPC) {
3983 			ntfs_error(sb, "Failed to build mapping pairs");
3984 			goto put_err_out;
3985 		}
3986 		a->data.non_resident.highest_vcn = cpu_to_le64(stop_vcn - 1);
3987 		mark_mft_record_dirty(ctx->ntfs_ino);
3988 		de_cluster_count += de_cnt;
3989 	}
3990 
3991 	/* Check whether error occurred. */
3992 	if (err && err != -ENOENT) {
3993 		ntfs_error(sb, "%s: Attribute lookup failed", __func__);
3994 		goto put_err_out;
3995 	}
3996 
3997 	/*
3998 	 * If the base extent was skipped in the above process,
3999 	 * we still may have to update the sizes.
4000 	 */
4001 	if (!first_updated) {
4002 		ntfs_attr_reinit_search_ctx(ctx);
4003 		err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
4004 				CASE_SENSITIVE, 0, NULL, 0, ctx);
4005 		if (!err) {
4006 			a = ctx->attr;
4007 			a->data.non_resident.allocated_size = cpu_to_le64(ni->allocated_size);
4008 			if (NInoCompressed(ni) || NInoSparse(ni))
4009 				a->data.non_resident.compressed_size =
4010 					cpu_to_le64(ni->itype.compressed.size);
4011 			/* Updating sizes taints the extent holding the attr */
4012 			if (ni->type == AT_DATA && ni->name == AT_UNNAMED)
4013 				NInoSetFileNameDirty(ni);
4014 			mark_mft_record_dirty(ctx->ntfs_ino);
4015 		} else {
4016 			ntfs_error(sb, "Failed to update sizes in base extent\n");
4017 			goto put_err_out;
4018 		}
4019 	}
4020 
4021 	/* Deallocate not used attribute extents and return with success. */
4022 	if (finished_build) {
4023 		ntfs_attr_reinit_search_ctx(ctx);
4024 		ntfs_debug("Deallocate marked extents.\n");
4025 		while (!(err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
4026 				CASE_SENSITIVE, 0, NULL, 0,
4027 				ctx))) {
4028 			if (le64_to_cpu(ctx->attr->data.non_resident.highest_vcn) !=
4029 					NTFS_VCN_DELETE_MARK)
4030 				continue;
4031 			/* Remove unused attribute record. */
4032 			err = ntfs_attr_record_rm(ctx);
4033 			if (err) {
4034 				ntfs_error(sb, "Could not remove unused attr");
4035 				goto put_err_out;
4036 			}
4037 			ntfs_attr_reinit_search_ctx(ctx);
4038 		}
4039 		if (err && err != -ENOENT) {
4040 			ntfs_error(sb, "%s: Attr lookup failed", __func__);
4041 			goto put_err_out;
4042 		}
4043 		ntfs_debug("Deallocate done.\n");
4044 		ntfs_attr_put_search_ctx(ctx);
4045 		goto out;
4046 	}
4047 	ntfs_attr_put_search_ctx(ctx);
4048 	ctx = NULL;
4049 
4050 	/* Allocate new MFT records for the rest of mapping pairs. */
4051 	while (1) {
4052 		struct ntfs_inode *ext_ni = NULL;
4053 		unsigned int de_cnt = 0;
4054 
4055 		/* Allocate new mft record. */
4056 		err = ntfs_mft_record_alloc(ni->vol, 0, &ext_ni, base_ni, NULL,
4057 					    base_ni->mft_no == FILE_MFT &&
4058 					    ni->type == AT_DATA &&
4059 					    ni->name == AT_UNNAMED ? stop_vcn : -1);
4060 		if (err) {
4061 			ntfs_error(sb, "Failed to allocate extent record");
4062 			goto put_err_out;
4063 		}
4064 		unmap_mft_record(ext_ni);
4065 
4066 		m = map_mft_record(ext_ni);
4067 		if (IS_ERR(m)) {
4068 			ntfs_error(sb, "Could not map new MFT record");
4069 			if (ntfs_mft_record_free(ni->vol, ext_ni))
4070 				ntfs_error(sb, "Could not free MFT record");
4071 			ntfs_inode_close(ext_ni);
4072 			err = -ENOMEM;
4073 			ext_ni = NULL;
4074 			goto put_err_out;
4075 		}
4076 		/*
4077 		 * If mapping size exceed available space, set them to
4078 		 * possible maximum.
4079 		 */
4080 		cur_max_mp_size = le32_to_cpu(m->bytes_allocated) -
4081 			le32_to_cpu(m->bytes_in_use) -
4082 			(sizeof(struct attr_record) +
4083 			 ((NInoCompressed(ni) || NInoSparse(ni)) ?
4084 			  sizeof(a->data.non_resident.compressed_size) : 0)) -
4085 			((sizeof(__le16) * ni->name_len + 7) & ~7);
4086 
4087 		/* Calculate size of rest mapping pairs. */
4088 		mp_size = ntfs_get_size_for_mapping_pairs(ni->vol,
4089 				start_rl, stop_vcn, -1, cur_max_mp_size);
4090 		if (mp_size <= 0) {
4091 			unmap_mft_record(ext_ni);
4092 			ntfs_inode_close(ext_ni);
4093 			err = mp_size;
4094 			ntfs_error(sb, "%s: get mp size failed", __func__);
4095 			goto put_err_out;
4096 		}
4097 
4098 		if (mp_size > cur_max_mp_size)
4099 			mp_size = cur_max_mp_size;
4100 		/* Add attribute extent to new record. */
4101 		err = ntfs_non_resident_attr_record_add(ext_ni, ni->type,
4102 				ni->name, ni->name_len, stop_vcn, mp_size, 0);
4103 		if (err < 0) {
4104 			ntfs_error(sb, "Could not add attribute extent");
4105 			unmap_mft_record(ext_ni);
4106 			if (ntfs_mft_record_free(ni->vol, ext_ni))
4107 				ntfs_error(sb, "Could not free MFT record");
4108 			ntfs_inode_close(ext_ni);
4109 			goto put_err_out;
4110 		}
4111 		a = (struct attr_record *)((u8 *)m + err);
4112 
4113 		err = ntfs_mapping_pairs_build(ni->vol, (u8 *)a +
4114 				le16_to_cpu(a->data.non_resident.mapping_pairs_offset),
4115 				mp_size, start_rl, stop_vcn, -1, &stop_vcn, &start_rl,
4116 				&de_cnt);
4117 		if (err < 0 && err != -ENOSPC) {
4118 			ntfs_error(sb, "Failed to build MP");
4119 			unmap_mft_record(ext_ni);
4120 			if (ntfs_mft_record_free(ni->vol, ext_ni))
4121 				ntfs_error(sb, "Couldn't free MFT record");
4122 			goto put_err_out;
4123 		}
4124 		a->data.non_resident.highest_vcn = cpu_to_le64(stop_vcn - 1);
4125 		mark_mft_record_dirty(ext_ni);
4126 		unmap_mft_record(ext_ni);
4127 
4128 		de_cluster_count += de_cnt;
4129 		/* All mapping pairs has been written. */
4130 		if (!err)
4131 			break;
4132 	}
4133 out:
4134 	if (from_vcn == 0)
4135 		ni->i_dealloc_clusters = de_cluster_count;
4136 	return 0;
4137 
4138 put_err_out:
4139 	if (ctx)
4140 		ntfs_attr_put_search_ctx(ctx);
4141 	return err;
4142 }
4143 
4144 int ntfs_attr_update_mapping_pairs_locked(struct ntfs_inode *ni,
4145 					  s64 from_vcn,
4146 					 struct ntfs_inode *locked_ni)
4147 {
4148 	return __ntfs_attr_update_mapping_pairs(ni, from_vcn, locked_ni,
4149 						false);
4150 }
4151 
4152 int ntfs_attr_update_mapping_pairs(struct ntfs_inode *ni, s64 from_vcn)
4153 {
4154 	return ntfs_attr_update_mapping_pairs_locked(ni, from_vcn, NULL);
4155 }
4156 
4157 /*
4158  * ntfs_attr_make_resident - convert a non-resident to a resident attribute
4159  * @ni:		open ntfs attribute to make resident
4160  * @ctx:	ntfs search context describing the attribute
4161  *
4162  * Convert a non-resident ntfs attribute to a resident one.
4163  */
4164 static int ntfs_attr_make_resident(struct ntfs_inode *ni, struct ntfs_attr_search_ctx *ctx)
4165 {
4166 	struct ntfs_volume *vol = ni->vol;
4167 	struct super_block *sb = vol->sb;
4168 	struct attr_record *a = ctx->attr;
4169 	int name_ofs, val_ofs, err;
4170 	s64 arec_size;
4171 
4172 	ntfs_debug("Entering for inode 0x%llx, attr 0x%x.\n",
4173 			(unsigned long long)ni->mft_no, ni->type);
4174 
4175 	/* Should be called for the first extent of the attribute. */
4176 	if (le64_to_cpu(a->data.non_resident.lowest_vcn)) {
4177 		ntfs_debug("Eeek!  Should be called for the first extent of the attribute.  Aborting...\n");
4178 		return -EINVAL;
4179 	}
4180 
4181 	/* Some preliminary sanity checking. */
4182 	if (!NInoNonResident(ni)) {
4183 		ntfs_debug("Eeek!  Trying to make resident attribute resident. Aborting...\n");
4184 		return -EINVAL;
4185 	}
4186 
4187 	/* Make sure this is not $MFT/$BITMAP or Windows will not boot! */
4188 	if (ni->type == AT_BITMAP && ni->mft_no == FILE_MFT)
4189 		return -EPERM;
4190 
4191 	/* Check that the attribute is allowed to be resident. */
4192 	err = ntfs_attr_can_be_resident(vol, ni->type);
4193 	if (err)
4194 		return err;
4195 
4196 	if (NInoCompressed(ni) || NInoEncrypted(ni)) {
4197 		ntfs_debug("Making compressed or encrypted files resident is not implemented yet.\n");
4198 		return -EOPNOTSUPP;
4199 	}
4200 
4201 	/* Work out offsets into and size of the resident attribute. */
4202 	name_ofs = 24; /* = sizeof(resident_struct attr_record); */
4203 	val_ofs = (name_ofs + a->name_length * sizeof(__le16) + 7) & ~7;
4204 	arec_size = (val_ofs + ni->data_size + 7) & ~7;
4205 
4206 	/* Sanity check the size before we start modifying the attribute. */
4207 	if (le32_to_cpu(ctx->mrec->bytes_in_use) - le32_to_cpu(a->length) +
4208 	    arec_size > le32_to_cpu(ctx->mrec->bytes_allocated)) {
4209 		ntfs_debug("Not enough space to make attribute resident\n");
4210 		return -ENOSPC;
4211 	}
4212 
4213 	/* Read and cache the whole runlist if not already done. */
4214 	err = ntfs_attr_map_whole_runlist(ni);
4215 	if (err)
4216 		return err;
4217 
4218 	/* Move the attribute name if it exists and update the offset. */
4219 	if (a->name_length) {
4220 		memmove((u8 *)a + name_ofs, (u8 *)a + le16_to_cpu(a->name_offset),
4221 				a->name_length * sizeof(__le16));
4222 	}
4223 	a->name_offset = cpu_to_le16(name_ofs);
4224 
4225 	/* Resize the resident part of the attribute record. */
4226 	if (ntfs_attr_record_resize(ctx->mrec, a, arec_size) < 0) {
4227 		/*
4228 		 * Bug, because ntfs_attr_record_resize should not fail (we
4229 		 * already checked that attribute fits MFT record).
4230 		 */
4231 		ntfs_error(ctx->ntfs_ino->vol->sb, "BUG! Failed to resize attribute record. ");
4232 		return -EIO;
4233 	}
4234 
4235 	/* Convert the attribute record to describe a resident attribute. */
4236 	a->non_resident = 0;
4237 	a->flags = 0;
4238 	a->data.resident.value_length = cpu_to_le32(ni->data_size);
4239 	a->data.resident.value_offset = cpu_to_le16(val_ofs);
4240 	/*
4241 	 * File names cannot be non-resident so we would never see this here
4242 	 * but at least it serves as a reminder that there may be attributes
4243 	 * for which we do need to set this flag. (AIA)
4244 	 */
4245 	if (a->type == AT_FILE_NAME)
4246 		a->data.resident.flags = RESIDENT_ATTR_IS_INDEXED;
4247 	else
4248 		a->data.resident.flags = 0;
4249 	a->data.resident.reserved = 0;
4250 
4251 	/*
4252 	 * Deallocate clusters from the runlist.
4253 	 *
4254 	 * NOTE: We can use ntfs_cluster_free() because we have already mapped
4255 	 * the whole run list and thus it doesn't matter that the attribute
4256 	 * record is in a transiently corrupted state at this moment in time.
4257 	 */
4258 	err = ntfs_cluster_free(ni, 0, -1, ctx);
4259 	if (err) {
4260 		ntfs_error(sb, "Eeek! Failed to release allocated clusters");
4261 		ntfs_debug("Ignoring error and leaving behind wasted clusters.\n");
4262 	}
4263 
4264 	/* Throw away the now unused runlist. */
4265 	kvfree(ni->runlist.rl);
4266 	ni->runlist.rl = NULL;
4267 	ni->runlist.count = 0;
4268 	/* Update in-memory struct ntfs_attr. */
4269 	NInoClearNonResident(ni);
4270 	NInoClearCompressed(ni);
4271 	ni->flags &= ~FILE_ATTR_COMPRESSED;
4272 	NInoClearSparse(ni);
4273 	ni->flags &= ~FILE_ATTR_SPARSE_FILE;
4274 	NInoClearEncrypted(ni);
4275 	ni->flags &= ~FILE_ATTR_ENCRYPTED;
4276 	ni->initialized_size = ni->data_size;
4277 	ni->allocated_size = ni->itype.compressed.size = (ni->data_size + 7) & ~7;
4278 	ni->itype.compressed.block_size = 0;
4279 	ni->itype.compressed.block_size_bits = ni->itype.compressed.block_clusters = 0;
4280 	return 0;
4281 }
4282 
4283 /*
4284  * ntfs_non_resident_attr_shrink - shrink a non-resident, open ntfs attribute
4285  * @ni:		non-resident ntfs attribute to shrink
4286  * @newsize:	new size (in bytes) to which to shrink the attribute
4287  * @pagecache_truncated: page cache was already truncated to @newsize
4288  *
4289  * Reduce the size of a non-resident, open ntfs attribute @na to @newsize bytes.
4290  */
4291 static int ntfs_non_resident_attr_shrink(struct ntfs_inode *ni,
4292 					 const s64 newsize,
4293 					struct ntfs_inode *locked_ni,
4294 					bool pagecache_truncated)
4295 {
4296 	struct ntfs_volume *vol;
4297 	struct ntfs_attr_search_ctx *ctx;
4298 	s64 first_free_vcn;
4299 	s64 nr_freed_clusters;
4300 	int err;
4301 	struct ntfs_inode *base_ni;
4302 	bool runlist_locked = locked_ni == ni;
4303 
4304 	ntfs_debug("Inode 0x%llx attr 0x%x new size %lld\n",
4305 		(unsigned long long)ni->mft_no, ni->type, (long long)newsize);
4306 
4307 	vol = ni->vol;
4308 
4309 	if (NInoAttr(ni))
4310 		base_ni = ni->ext.base_ntfs_ino;
4311 	else
4312 		base_ni = ni;
4313 
4314 	/*
4315 	 * Check the attribute type and the corresponding minimum size
4316 	 * against @newsize and fail if @newsize is too small.
4317 	 */
4318 	err = ntfs_attr_size_bounds_check(vol, ni->type, newsize);
4319 	if (err) {
4320 		if (err == -ERANGE)
4321 			ntfs_debug("Eeek! Size bounds check failed. Aborting...\n");
4322 		else if (err == -ENOENT)
4323 			err = -EIO;
4324 		return err;
4325 	}
4326 
4327 	/* The first cluster outside the new allocation. */
4328 	if (NInoCompressed(ni))
4329 		/*
4330 		 * For compressed files we must keep full compressions blocks,
4331 		 * but currently we do not decompress/recompress the last
4332 		 * block to truncate the data, so we may leave more allocated
4333 		 * clusters than really needed.
4334 		 */
4335 		first_free_vcn = ntfs_bytes_to_cluster(vol,
4336 				((newsize - 1) | (ni->itype.compressed.block_size - 1)) + 1);
4337 	else
4338 		first_free_vcn =
4339 			ntfs_bytes_to_cluster(vol, newsize + vol->cluster_size - 1);
4340 
4341 	if (first_free_vcn < 0)
4342 		return -EINVAL;
4343 	/*
4344 	 * Compare the new allocation with the old one and only deallocate
4345 	 * clusters if there is a change.
4346 	 */
4347 	if (ntfs_bytes_to_cluster(vol, ni->allocated_size) != first_free_vcn) {
4348 		/*
4349 		 * ntfs_cluster_free() and ntfs_rl_truncate_nolock()
4350 		 * both require this lock.
4351 		 */
4352 		if (!runlist_locked)
4353 			down_write(&ni->runlist.lock);
4354 
4355 		err = ntfs_attr_map_whole_runlist(ni);
4356 		if (err) {
4357 			ntfs_debug("Eeek! ntfs_attr_map_whole_runlist failed.\n");
4358 			goto unlock_runlist;
4359 		}
4360 
4361 		ctx = ntfs_attr_get_search_ctx(base_ni, NULL);
4362 		if (!ctx) {
4363 			ntfs_error(vol->sb, "%s: Failed to get search context", __func__);
4364 			err = -ENOMEM;
4365 			goto unlock_runlist;
4366 		}
4367 
4368 		/* Deallocate all clusters starting with the first free one. */
4369 		nr_freed_clusters = ntfs_cluster_free(ni, first_free_vcn, -1, ctx);
4370 		if (nr_freed_clusters < 0) {
4371 			ntfs_debug("Eeek! Freeing of clusters failed. Aborting...\n");
4372 			ntfs_attr_put_search_ctx(ctx);
4373 			err = (int)nr_freed_clusters;
4374 			goto unlock_runlist;
4375 		}
4376 		ntfs_attr_put_search_ctx(ctx);
4377 
4378 		/* Truncate the runlist itself. */
4379 		if (ntfs_rl_truncate_nolock(vol, &ni->runlist, first_free_vcn)) {
4380 			/*
4381 			 * Failed to truncate the runlist, so just throw it
4382 			 * away, it will be mapped afresh on next use.
4383 			 */
4384 			kvfree(ni->runlist.rl);
4385 			ni->runlist.rl = NULL;
4386 			ntfs_error(vol->sb, "Eeek! Run list truncation failed.\n");
4387 			err = -EIO;
4388 			goto unlock_runlist;
4389 		}
4390 
4391 		/* Prepare to mapping pairs update. */
4392 		ni->allocated_size = ntfs_cluster_to_bytes(vol, first_free_vcn);
4393 
4394 		if (NInoSparse(ni) || NInoCompressed(ni)) {
4395 			if (nr_freed_clusters) {
4396 				ni->itype.compressed.size -=
4397 					ntfs_cluster_to_bytes(vol, nr_freed_clusters);
4398 				VFS_I(base_ni)->i_blocks = ni->itype.compressed.size >> 9;
4399 			}
4400 		} else
4401 			VFS_I(base_ni)->i_blocks = ni->allocated_size >> 9;
4402 
4403 		/* Write mapping pairs for new runlist. */
4404 		err = ntfs_attr_update_mapping_pairs_locked(ni, 0, ni);
4405 		if (err) {
4406 			ntfs_debug("Eeek! Mapping pairs update failed. Leaving inconstant metadata. Run chkdsk.\n");
4407 			goto unlock_runlist;
4408 		}
4409 		if (!runlist_locked)
4410 			up_write(&ni->runlist.lock);
4411 	}
4412 
4413 	/* Get the first attribute record. */
4414 	ctx = ntfs_attr_get_search_ctx(base_ni, NULL);
4415 	if (!ctx) {
4416 		ntfs_error(vol->sb, "%s: Failed to get search context", __func__);
4417 		return -ENOMEM;
4418 	}
4419 
4420 	err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
4421 				CASE_SENSITIVE, 0, NULL, 0, ctx);
4422 	if (err) {
4423 		if (err == -ENOENT)
4424 			err = -EIO;
4425 		ntfs_debug("Eeek! Lookup of first attribute extent failed. Leaving inconstant metadata.\n");
4426 		goto put_err_out;
4427 	}
4428 
4429 	/* Update data and initialized size. */
4430 	ni->data_size = newsize;
4431 	ctx->attr->data.non_resident.data_size = cpu_to_le64(newsize);
4432 	if (newsize < ni->initialized_size) {
4433 		ni->initialized_size = newsize;
4434 		ctx->attr->data.non_resident.initialized_size = cpu_to_le64(newsize);
4435 	}
4436 
4437 	/*
4438 	 * Drop any page-cache folios that now lie beyond the shrunk
4439 	 * attribute. The clusters backing them have just been freed and the
4440 	 * runlist truncated, so leaving stale dirty folios around makes a
4441 	 * later writeback map a vcn past the new allocation, which fails with
4442 	 * -ENOENT and loses the write.
4443 	 */
4444 	if (!pagecache_truncated)
4445 		truncate_inode_pages(VFS_I(ni)->i_mapping, newsize);
4446 
4447 	/* Update data size in the index. */
4448 	if (ni->type == AT_DATA && ni->name == AT_UNNAMED)
4449 		NInoSetFileNameDirty(ni);
4450 
4451 	/* If the attribute now has zero size, make it resident. */
4452 	if (!newsize && !NInoEncrypted(ni) && !NInoCompressed(ni)) {
4453 		if (!runlist_locked)
4454 			down_write(&ni->runlist.lock);
4455 		err = ntfs_attr_make_resident(ni, ctx);
4456 		if (!runlist_locked)
4457 			up_write(&ni->runlist.lock);
4458 		if (err) {
4459 			/* If couldn't make resident, just continue. */
4460 			if (err != -EPERM)
4461 				ntfs_error(ni->vol->sb,
4462 					"Failed to make attribute resident. Leaving as is...\n");
4463 		}
4464 	}
4465 
4466 	/* Set the inode dirty so it is written out later. */
4467 	mark_mft_record_dirty(ctx->ntfs_ino);
4468 	/* Done! */
4469 	ntfs_attr_put_search_ctx(ctx);
4470 	return 0;
4471 put_err_out:
4472 	ntfs_attr_put_search_ctx(ctx);
4473 	return err;
4474 
4475 unlock_runlist:
4476 	if (!runlist_locked)
4477 		up_write(&ni->runlist.lock);
4478 	return err;
4479 }
4480 
4481 /*
4482  * ntfs_non_resident_attr_expand - expand a non-resident, open ntfs attribute
4483  * @ni:			non-resident ntfs attribute to expand
4484  * @prealloc_size:	preallocation size (in bytes) to which to expand the attribute
4485  * @newsize:		new size (in bytes) to which to expand the attribute
4486  * @holes:		how to create a hole if expanding
4487  * @locked_ni:		inode whose runlist lock is already held
4488  *
4489  * Expand the size of a non-resident, open ntfs attribute @na to @newsize bytes,
4490  * by allocating new clusters.
4491  */
4492 static int ntfs_non_resident_attr_expand(struct ntfs_inode *ni, const s64 newsize,
4493 		const s64 prealloc_size, unsigned int holes,
4494 		struct ntfs_inode *locked_ni)
4495 {
4496 	s64 lcn_seek_from;
4497 	s64 first_free_vcn;
4498 	struct ntfs_volume *vol;
4499 	struct ntfs_attr_search_ctx *ctx = NULL;
4500 	struct runlist_element *rl, *rln;
4501 	s64 org_alloc_size, org_compressed_size;
4502 	int err, err2;
4503 	struct ntfs_inode *base_ni;
4504 	struct super_block *sb = ni->vol->sb;
4505 	size_t new_rl_count;
4506 	unsigned long flags;
4507 	bool runlist_locked = locked_ni == ni;
4508 
4509 	ntfs_debug("Inode 0x%llx, attr 0x%x, new size %lld old size %lld\n",
4510 			(unsigned long long)ni->mft_no, ni->type,
4511 			(long long)newsize, (long long)ni->data_size);
4512 
4513 	vol = ni->vol;
4514 
4515 	if (NInoAttr(ni))
4516 		base_ni = ni->ext.base_ntfs_ino;
4517 	else
4518 		base_ni = ni;
4519 
4520 	/*
4521 	 * Check the attribute type and the corresponding maximum size
4522 	 * against @newsize and fail if @newsize is too big.
4523 	 */
4524 	err = ntfs_attr_size_bounds_check(vol, ni->type, newsize);
4525 	if (err	< 0) {
4526 		ntfs_error(sb, "%s: bounds check failed", __func__);
4527 		return err;
4528 	}
4529 
4530 	/* Save for future use. */
4531 	org_alloc_size = ni->allocated_size;
4532 	org_compressed_size = ni->itype.compressed.size;
4533 
4534 	/* The first cluster outside the new allocation. */
4535 	if (prealloc_size)
4536 		first_free_vcn =
4537 			ntfs_bytes_to_cluster(vol, prealloc_size + vol->cluster_size - 1);
4538 	else
4539 		first_free_vcn =
4540 			ntfs_bytes_to_cluster(vol, newsize + vol->cluster_size - 1);
4541 	if (first_free_vcn < 0)
4542 		return -EFBIG;
4543 
4544 	/*
4545 	 * Compare the new allocation with the old one and only allocate
4546 	 * clusters if there is a change.
4547 	 */
4548 	if (ntfs_bytes_to_cluster(vol, ni->allocated_size) < first_free_vcn) {
4549 		/*
4550 		 * The runlist array is replaced below.  Readers such as the
4551 		 * iomap read path hold only the runlist lock, not mrec_lock.
4552 		 */
4553 		if (runlist_locked)
4554 			lockdep_assert_held_write(&ni->runlist.lock);
4555 		else
4556 			down_write(&ni->runlist.lock);
4557 
4558 		err = ntfs_attr_map_whole_runlist(ni);
4559 		if (err) {
4560 			ntfs_error(sb, "ntfs_attr_map_whole_runlist failed");
4561 			goto unlock_runlist;
4562 		}
4563 
4564 		/*
4565 		 * If we extend $DATA attribute on NTFS 3+ volume, we can add
4566 		 * sparse runs instead of real allocation of clusters.
4567 		 */
4568 		if ((ni->type == AT_DATA && (vol->major_ver >= 3 || !NInoSparseDisabled(ni))) &&
4569 		    (holes != HOLES_NO)) {
4570 			if (NInoCompressed(ni)) {
4571 				int last = 0, i = 0;
4572 				s64 alloc_size;
4573 				u64 more_entries = round_up(first_free_vcn -
4574 						 ntfs_bytes_to_cluster(vol, ni->allocated_size),
4575 						 ni->itype.compressed.block_clusters);
4576 
4577 				do_div(more_entries, ni->itype.compressed.block_clusters);
4578 
4579 				while (ni->runlist.rl[last].length)
4580 					last++;
4581 
4582 				rl = ntfs_rl_realloc(ni->runlist.rl, last + 1,
4583 						last + more_entries + 1);
4584 				if (IS_ERR(rl)) {
4585 					err = -ENOMEM;
4586 					goto unlock_runlist;
4587 				}
4588 
4589 				alloc_size = ni->allocated_size;
4590 				while (i++ < more_entries) {
4591 					rl[last].vcn = ntfs_bytes_to_cluster(vol,
4592 							round_up(alloc_size, vol->cluster_size));
4593 					rl[last].length = ni->itype.compressed.block_clusters -
4594 						(rl[last].vcn &
4595 						 (ni->itype.compressed.block_clusters - 1));
4596 					rl[last].lcn = LCN_HOLE;
4597 					last++;
4598 					alloc_size += ni->itype.compressed.block_size;
4599 				}
4600 
4601 				rl[last].vcn = first_free_vcn;
4602 				rl[last].lcn = LCN_ENOENT;
4603 				rl[last].length = 0;
4604 
4605 				ni->runlist.rl = rl;
4606 				ni->runlist.count += more_entries;
4607 			} else {
4608 				rl = kmalloc(sizeof(struct runlist_element) * 2, GFP_NOFS);
4609 				if (!rl) {
4610 					err = -ENOMEM;
4611 					goto unlock_runlist;
4612 				}
4613 
4614 				rl[0].vcn = ntfs_bytes_to_cluster(vol, ni->allocated_size);
4615 				rl[0].lcn = LCN_HOLE;
4616 				rl[0].length = first_free_vcn -
4617 					ntfs_bytes_to_cluster(vol, ni->allocated_size);
4618 				rl[1].vcn = first_free_vcn;
4619 				rl[1].lcn = LCN_ENOENT;
4620 				rl[1].length = 0;
4621 			}
4622 		} else {
4623 			/*
4624 			 * Determine first after last LCN of attribute.
4625 			 * We will start seek clusters from this LCN to avoid
4626 			 * fragmentation.  If there are no valid LCNs in the
4627 			 * attribute let the cluster allocator choose the
4628 			 * starting LCN.
4629 			 */
4630 			lcn_seek_from = -1;
4631 			if (ni->runlist.rl->length) {
4632 				/* Seek to the last run list element. */
4633 				for (rl = ni->runlist.rl; (rl + 1)->length; rl++)
4634 					;
4635 				/*
4636 				 * If the last LCN is a hole or similar seek
4637 				 * back to last valid LCN.
4638 				 */
4639 				while (rl->lcn < 0 && rl != ni->runlist.rl)
4640 					rl--;
4641 				/*
4642 				 * Only set lcn_seek_from it the LCN is valid.
4643 				 */
4644 				if (rl->lcn >= 0)
4645 					lcn_seek_from = rl->lcn + rl->length;
4646 			}
4647 
4648 			rl = ntfs_cluster_alloc(vol,
4649 					ntfs_bytes_to_cluster(vol, ni->allocated_size),
4650 					first_free_vcn -
4651 					ntfs_bytes_to_cluster(vol, ni->allocated_size),
4652 					lcn_seek_from, DATA_ZONE, false,
4653 					ni->type == AT_ATTRIBUTE_LIST, false);
4654 			if (IS_ERR(rl)) {
4655 				ntfs_debug("Cluster allocation failed (%lld)",
4656 						(long long)first_free_vcn -
4657 						ntfs_bytes_to_cluster(vol, ni->allocated_size));
4658 				err = PTR_ERR(rl);
4659 				goto unlock_runlist;
4660 			}
4661 			/*
4662 			 * A contiguous ATTRIBUTE_LIST allocation keeps its mapping
4663 			 * pairs small enough to fit in the base MFT record. The
4664 			 * allocator can return a short run when contiguity was
4665 			 * requested, so discard it and retry normally if necessary.
4666 			 */
4667 			if (ni->type == AT_ATTRIBUTE_LIST &&
4668 				(rl->vcn != ntfs_bytes_to_cluster(vol,
4669 						ni->allocated_size) ||
4670 				 rl->length != first_free_vcn -
4671 					ntfs_bytes_to_cluster(vol, ni->allocated_size) ||
4672 				 rl[1].length)) {
4673 				ntfs_cluster_free_from_rl(vol, rl);
4674 				kvfree(rl);
4675 				rl = ntfs_cluster_alloc(vol,
4676 						ntfs_bytes_to_cluster(vol,
4677 								ni->allocated_size),
4678 						first_free_vcn -
4679 						ntfs_bytes_to_cluster(vol,
4680 								ni->allocated_size),
4681 						lcn_seek_from, DATA_ZONE, false,
4682 						false, false);
4683 				if (IS_ERR(rl)) {
4684 					err = PTR_ERR(rl);
4685 					goto unlock_runlist;
4686 				}
4687 			}
4688 		}
4689 
4690 		if (!NInoCompressed(ni)) {
4691 			/* Append new clusters to attribute runlist. */
4692 			rln = ntfs_runlists_merge(&ni->runlist, rl, 0, &new_rl_count);
4693 			if (IS_ERR(rln)) {
4694 				/* Failed, free just allocated clusters. */
4695 				ntfs_error(sb, "Run list merge failed");
4696 				ntfs_cluster_free_from_rl(vol, rl);
4697 				kvfree(rl);
4698 				err = -EIO;
4699 				goto unlock_runlist;
4700 			}
4701 			ni->runlist.rl = rln;
4702 			ni->runlist.count = new_rl_count;
4703 		}
4704 
4705 		/* Prepare to mapping pairs update. */
4706 		ni->allocated_size = ntfs_cluster_to_bytes(vol, first_free_vcn);
4707 		if (ni->type == AT_ATTRIBUTE_LIST && !runlist_locked) {
4708 			/*
4709 			 * Making room for the list's mapping pairs can resize
4710 			 * this attribute list again through
4711 			 * ntfs_attrlist_update_locked(), which takes its
4712 			 * runlist lock.
4713 			 */
4714 			up_write(&ni->runlist.lock);
4715 			err = ntfs_attr_update_mapping_pairs_locked(ni, 0,
4716 								    locked_ni);
4717 			if (err) {
4718 				ntfs_debug("Mapping pairs update failed");
4719 				goto rollback;
4720 			}
4721 		} else {
4722 			err = ntfs_attr_update_mapping_pairs_locked(ni, 0, ni);
4723 			if (err) {
4724 				ntfs_debug("Mapping pairs update failed");
4725 				goto rollback_locked;
4726 			}
4727 			if (!runlist_locked)
4728 				up_write(&ni->runlist.lock);
4729 		}
4730 	}
4731 
4732 	ctx = ntfs_attr_get_search_ctx(base_ni, NULL);
4733 	if (!ctx) {
4734 		err = -ENOMEM;
4735 		if (ni->allocated_size == org_alloc_size)
4736 			return err;
4737 		goto rollback;
4738 	}
4739 
4740 	err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
4741 			       CASE_SENSITIVE, 0, NULL, 0, ctx);
4742 	if (err) {
4743 		if (err == -ENOENT)
4744 			err = -EIO;
4745 		if (ni->allocated_size != org_alloc_size)
4746 			goto rollback;
4747 		goto put_err_out;
4748 	}
4749 
4750 	/* Update data size. */
4751 	ni->data_size = newsize;
4752 	ctx->attr->data.non_resident.data_size = cpu_to_le64(newsize);
4753 	/* Update data size in the index. */
4754 	if (ni->type == AT_DATA && ni->name == AT_UNNAMED)
4755 		NInoSetFileNameDirty(ni);
4756 	/* Set the inode dirty so it is written out later. */
4757 	mark_mft_record_dirty(ctx->ntfs_ino);
4758 	/* Done! */
4759 	ntfs_attr_put_search_ctx(ctx);
4760 	return 0;
4761 rollback:
4762 	if (!runlist_locked)
4763 		down_write(&ni->runlist.lock);
4764 rollback_locked:
4765 	/* Free allocated clusters. */
4766 	err2 = ntfs_cluster_free(ni, ntfs_bytes_to_cluster(vol, org_alloc_size),
4767 				-1, ctx);
4768 	if (err2)
4769 		ntfs_debug("Leaking clusters");
4770 
4771 	/*
4772 	 * Now, truncate the runlist itself.  Restore allocated_size before
4773 	 * dropping the lock: ntfs_attr_vcn_to_rl() fails a lookup below the
4774 	 * allocated size that falls past the end of the runlist.
4775 	 */
4776 	err2 = ntfs_rl_truncate_nolock(vol, &ni->runlist,
4777 			ntfs_bytes_to_cluster(vol, org_alloc_size));
4778 	if (!err2) {
4779 		write_lock_irqsave(&ni->size_lock, flags);
4780 		ni->allocated_size = org_alloc_size;
4781 		write_unlock_irqrestore(&ni->size_lock, flags);
4782 	}
4783 	if (err2) {
4784 		/*
4785 		 * Failed to truncate the runlist, so just throw it away, it
4786 		 * will be mapped afresh on next use.
4787 		 */
4788 		kvfree(ni->runlist.rl);
4789 		ni->runlist.rl = NULL;
4790 		ntfs_error(sb, "Couldn't truncate runlist. Rollback failed");
4791 	} else {
4792 		/* Restore mapping pairs. */
4793 		if (__ntfs_attr_update_mapping_pairs(ni, 0, ni, true))
4794 			ntfs_error(sb, "Failed to restore old mapping pairs");
4795 
4796 		if (NInoSparse(ni) || NInoCompressed(ni)) {
4797 			ni->itype.compressed.size =  org_compressed_size;
4798 			VFS_I(base_ni)->i_blocks = ni->itype.compressed.size >> 9;
4799 		} else
4800 			VFS_I(base_ni)->i_blocks = ni->allocated_size >> 9;
4801 	}
4802 	if (!runlist_locked)
4803 		up_write(&ni->runlist.lock);
4804 	if (ctx)
4805 		ntfs_attr_put_search_ctx(ctx);
4806 	return err;
4807 put_err_out:
4808 	if (ctx)
4809 		ntfs_attr_put_search_ctx(ctx);
4810 	return err;
4811 unlock_runlist:
4812 	if (!runlist_locked)
4813 		up_write(&ni->runlist.lock);
4814 	return err;
4815 }
4816 
4817 /*
4818  * ntfs_resident_attr_resize - resize a resident, open ntfs attribute
4819  * @attr_ni:		resident ntfs inode to resize
4820  * @newsize:		new size (in bytes) to which to resize the attribute
4821  * @prealloc_size:	preallocation size (in bytes) to which to resize the attribute
4822  * @holes:		flags indicating how to handle holes
4823  *
4824  * Change the size of a resident, open ntfs attribute @na to @newsize bytes.
4825  */
4826 static int ntfs_resident_attr_resize(struct ntfs_inode *attr_ni, const s64 newsize,
4827 		const s64 prealloc_size, unsigned int holes)
4828 {
4829 	struct ntfs_attr_search_ctx *ctx;
4830 	struct ntfs_volume *vol = attr_ni->vol;
4831 	struct super_block *sb = vol->sb;
4832 	int err = -EIO;
4833 	struct ntfs_inode *base_ni, *ext_ni = NULL;
4834 
4835 attr_resize_again:
4836 	ntfs_debug("Inode 0x%llx attr 0x%x new size %lld\n",
4837 			(unsigned long long)attr_ni->mft_no, attr_ni->type,
4838 			(long long)newsize);
4839 
4840 	if (NInoAttr(attr_ni))
4841 		base_ni = attr_ni->ext.base_ntfs_ino;
4842 	else
4843 		base_ni = attr_ni;
4844 
4845 	/* Get the attribute record that needs modification. */
4846 	ctx = ntfs_attr_get_search_ctx(base_ni, NULL);
4847 	if (!ctx) {
4848 		ntfs_error(sb, "%s: Failed to get search context", __func__);
4849 		return -ENOMEM;
4850 	}
4851 
4852 	err = ntfs_attr_lookup(attr_ni->type, attr_ni->name, attr_ni->name_len,
4853 			CASE_SENSITIVE, 0, NULL, 0, ctx);
4854 	if (err) {
4855 		ntfs_error(sb, "ntfs_attr_lookup failed");
4856 		goto put_err_out;
4857 	}
4858 
4859 	/*
4860 	 * Check the attribute type and the corresponding minimum and maximum
4861 	 * sizes against @newsize and fail if @newsize is out of bounds.
4862 	 */
4863 	err = ntfs_attr_size_bounds_check(vol, attr_ni->type, newsize);
4864 	if (err) {
4865 		if (err == -ENOENT)
4866 			err = -EIO;
4867 		ntfs_debug("%s: bounds check failed", __func__);
4868 		goto put_err_out;
4869 	}
4870 	/*
4871 	 * If @newsize is bigger than the mft record we need to make the
4872 	 * attribute non-resident if the attribute type supports it. If it is
4873 	 * smaller we can go ahead and attempt the resize.
4874 	 */
4875 	if (newsize < vol->mft_record_size) {
4876 		/* Perform the resize of the attribute record. */
4877 		err = ntfs_resident_attr_value_resize(ctx->mrec, ctx->attr,
4878 					newsize);
4879 		if (!err) {
4880 			/* Update attribute size everywhere. */
4881 			attr_ni->data_size = attr_ni->initialized_size = newsize;
4882 			attr_ni->allocated_size = (newsize + 7) & ~7;
4883 			if (NInoCompressed(attr_ni) || NInoSparse(attr_ni))
4884 				attr_ni->itype.compressed.size = attr_ni->allocated_size;
4885 			if (attr_ni->type == AT_DATA && attr_ni->name == AT_UNNAMED)
4886 				NInoSetFileNameDirty(attr_ni);
4887 			goto resize_done;
4888 		}
4889 
4890 		/* Prefer AT_INDEX_ALLOCATION instead of AT_ATTRIBUTE_LIST */
4891 		if (err == -ENOSPC && ctx->attr->type == AT_INDEX_ROOT)
4892 			goto put_err_out;
4893 
4894 	}
4895 	/* There is not enough space in the mft record to perform the resize. */
4896 
4897 	/* Make the attribute non-resident if possible. */
4898 	err = ntfs_attr_make_non_resident(attr_ni,
4899 			le32_to_cpu(ctx->attr->data.resident.value_length));
4900 	if (!err) {
4901 		mark_mft_record_dirty(ctx->ntfs_ino);
4902 		ntfs_attr_put_search_ctx(ctx);
4903 		/* Resize non-resident attribute */
4904 		return ntfs_non_resident_attr_expand(
4905 				attr_ni, newsize, prealloc_size, holes, NULL);
4906 	} else if (err != -ENOSPC && err != -EPERM) {
4907 		ntfs_error(sb, "Failed to make attribute non-resident");
4908 		goto put_err_out;
4909 	}
4910 
4911 	/* Try to make other attributes non-resident and retry each time. */
4912 	ntfs_attr_reinit_search_ctx(ctx);
4913 	while (!(err = ntfs_attr_lookup(AT_UNUSED, NULL, 0, 0, 0, NULL, 0, ctx))) {
4914 		struct inode *tvi;
4915 		struct attr_record *a;
4916 		u32 value_len;
4917 
4918 		a = ctx->attr;
4919 		if (a->non_resident || a->type == AT_ATTRIBUTE_LIST)
4920 			continue;
4921 		value_len = le32_to_cpu(a->data.resident.value_length);
4922 
4923 		if (ntfs_attr_can_be_non_resident(vol, a->type))
4924 			continue;
4925 
4926 		/*
4927 		 * Check out whether convert is reasonable. Assume that mapping
4928 		 * pairs will take 8 bytes.
4929 		 */
4930 		if (le32_to_cpu(a->length) <= (sizeof(struct attr_record) - sizeof(s64)) +
4931 				((a->name_length * sizeof(__le16) + 7) & ~7) + 8)
4932 			continue;
4933 		if (a->type == AT_DATA && !value_len)
4934 			continue;
4935 
4936 		if (a->type == AT_DATA)
4937 			tvi = ntfs_iget(sb, base_ni->mft_no);
4938 		else
4939 			tvi = ntfs_attr_iget(VFS_I(base_ni), a->type,
4940 				(__le16 *)((u8 *)a + le16_to_cpu(a->name_offset)),
4941 				a->name_length);
4942 		if (IS_ERR(tvi)) {
4943 			ntfs_error(sb, "Couldn't open attribute");
4944 			continue;
4945 		}
4946 
4947 		if (ntfs_attr_make_non_resident(NTFS_I(tvi), value_len)) {
4948 			iput(tvi);
4949 			continue;
4950 		}
4951 
4952 		mark_mft_record_dirty(ctx->ntfs_ino);
4953 		iput(tvi);
4954 		ntfs_attr_put_search_ctx(ctx);
4955 		goto attr_resize_again;
4956 	}
4957 
4958 	/* Check whether error occurred. */
4959 	if (err != -ENOENT) {
4960 		ntfs_error(sb, "%s: Attribute lookup failed 1", __func__);
4961 		goto put_err_out;
4962 	}
4963 
4964 	/*
4965 	 * The standard information and attribute list attributes can't be
4966 	 * moved out from the base MFT record, so try to move out others.
4967 	 */
4968 	if (attr_ni->type == AT_STANDARD_INFORMATION ||
4969 	    attr_ni->type == AT_ATTRIBUTE_LIST) {
4970 		ntfs_attr_put_search_ctx(ctx);
4971 
4972 		if (!NInoAttrList(base_ni)) {
4973 			err = ntfs_inode_add_attrlist(base_ni);
4974 			if (err)
4975 				return err;
4976 		}
4977 
4978 		err = ntfs_inode_free_space(base_ni, sizeof(struct attr_record));
4979 		if (err) {
4980 			err = -ENOSPC;
4981 			ntfs_error(sb,
4982 				"Couldn't free space in the MFT record to make attribute list non resident");
4983 			return err;
4984 		}
4985 		err = ntfs_attrlist_update(base_ni);
4986 		if (err)
4987 			return err;
4988 		goto attr_resize_again;
4989 	}
4990 
4991 	/*
4992 	 * Move the attribute to a new mft record, creating an attribute list
4993 	 * attribute or modifying it if it is already present.
4994 	 */
4995 
4996 	/* Point search context back to attribute which we need resize. */
4997 	ntfs_attr_reinit_search_ctx(ctx);
4998 	err = ntfs_attr_lookup(attr_ni->type, attr_ni->name, attr_ni->name_len,
4999 			CASE_SENSITIVE, 0, NULL, 0, ctx);
5000 	if (err) {
5001 		ntfs_error(sb, "%s: Attribute lookup failed 2", __func__);
5002 		goto put_err_out;
5003 	}
5004 
5005 	/*
5006 	 * Check whether attribute is already single in this MFT record.
5007 	 * 8 added for the attribute terminator.
5008 	 */
5009 	if (le32_to_cpu(ctx->mrec->bytes_in_use) ==
5010 	    le16_to_cpu(ctx->mrec->attrs_offset) + le32_to_cpu(ctx->attr->length) + 8) {
5011 		err = -ENOSPC;
5012 		ntfs_debug("MFT record is filled with one attribute\n");
5013 		goto put_err_out;
5014 	}
5015 
5016 	/* Add attribute list if not present. */
5017 	if (!NInoAttrList(base_ni)) {
5018 		ntfs_attr_put_search_ctx(ctx);
5019 		err = ntfs_inode_add_attrlist(base_ni);
5020 		if (err)
5021 			return err;
5022 		goto attr_resize_again;
5023 	}
5024 
5025 	/* Allocate new mft record. */
5026 	err = ntfs_mft_record_alloc(base_ni->vol, 0, &ext_ni, base_ni, NULL, -1);
5027 	if (err) {
5028 		ntfs_error(sb, "Couldn't allocate MFT record");
5029 		goto put_err_out;
5030 	}
5031 	unmap_mft_record(ext_ni);
5032 
5033 	/* Move attribute to it. */
5034 	err = ntfs_attr_record_move_to(ctx, ext_ni);
5035 	if (err) {
5036 		ntfs_error(sb, "Couldn't move attribute to new MFT record");
5037 		err = -ENOMEM;
5038 		goto put_err_out;
5039 	}
5040 
5041 	err = ntfs_attrlist_update(base_ni);
5042 	if (err < 0)
5043 		goto put_err_out;
5044 
5045 	ntfs_attr_put_search_ctx(ctx);
5046 	/* Try to perform resize once again. */
5047 	goto attr_resize_again;
5048 
5049 resize_done:
5050 	/*
5051 	 * Set the inode (and its base inode if it exists) dirty so it is
5052 	 * written out later.
5053 	 */
5054 	mark_mft_record_dirty(ctx->ntfs_ino);
5055 	ntfs_attr_put_search_ctx(ctx);
5056 	return 0;
5057 
5058 put_err_out:
5059 	ntfs_attr_put_search_ctx(ctx);
5060 	return err;
5061 }
5062 
5063 int __ntfs_attr_truncate_vfs(struct ntfs_inode *ni, const s64 newsize,
5064 		const s64 i_size)
5065 {
5066 	int err = 0;
5067 
5068 	if (newsize < 0 ||
5069 	    (ni->mft_no == FILE_MFT && ni->type == AT_DATA)) {
5070 		ntfs_debug("Invalid arguments passed.\n");
5071 		return -EINVAL;
5072 	}
5073 
5074 	ntfs_debug("Entering for inode 0x%llx, attr 0x%x, size %lld\n",
5075 			(unsigned long long)ni->mft_no, ni->type, newsize);
5076 
5077 	if (NInoNonResident(ni)) {
5078 		if (newsize > i_size) {
5079 			down_write(&ni->runlist.lock);
5080 			err = ntfs_non_resident_attr_expand(
5081 					ni, newsize, 0,
5082 					NVolDisableSparse(ni->vol) ?
5083 					HOLES_NO : HOLES_OK, ni);
5084 			up_write(&ni->runlist.lock);
5085 		} else
5086 			err = ntfs_non_resident_attr_shrink(
5087 					ni, newsize, NULL, true);
5088 	} else
5089 		err = ntfs_resident_attr_resize(ni, newsize, 0,
5090 						NVolDisableSparse(ni->vol) ?
5091 						HOLES_NO : HOLES_OK);
5092 	ntfs_debug("Return status %d\n", err);
5093 	return err;
5094 }
5095 
5096 int ntfs_attr_expand_locked(struct ntfs_inode *ni, const s64 newsize,
5097 			    const s64 prealloc_size,
5098 			   struct ntfs_inode *locked_ni)
5099 {
5100 	int err = 0;
5101 
5102 	if (newsize < 0 ||
5103 	    (ni->mft_no == FILE_MFT && ni->type == AT_DATA)) {
5104 		ntfs_debug("Invalid arguments passed.\n");
5105 		return -EINVAL;
5106 	}
5107 
5108 	ntfs_debug("Entering for inode 0x%llx, attr 0x%x, size %lld\n",
5109 			(unsigned long long)ni->mft_no, ni->type, newsize);
5110 
5111 	if (ni->data_size == newsize &&
5112 		(!prealloc_size || prealloc_size <= ni->allocated_size)) {
5113 		ntfs_debug("Size is already ok\n");
5114 		return 0;
5115 	}
5116 
5117 	/*
5118 	 * Encrypted attributes are not supported. We return access denied,
5119 	 * which is what Windows NT4 does, too.
5120 	 */
5121 	if (NInoEncrypted(ni)) {
5122 		pr_err("Failed to truncate encrypted attribute\n");
5123 		return -EACCES;
5124 	}
5125 
5126 	if (NInoNonResident(ni)) {
5127 		if (newsize > ni->data_size || prealloc_size > ni->allocated_size)
5128 			err = ntfs_non_resident_attr_expand(
5129 					ni, newsize, prealloc_size,
5130 					NVolDisableSparse(ni->vol) ?
5131 					HOLES_NO : HOLES_OK, locked_ni);
5132 	} else
5133 		err = ntfs_resident_attr_resize(ni, newsize, prealloc_size,
5134 						NVolDisableSparse(ni->vol) ?
5135 						HOLES_NO : HOLES_OK);
5136 	if (!err)
5137 		i_size_write(VFS_I(ni), newsize);
5138 	ntfs_debug("Return status %d\n", err);
5139 	return err;
5140 }
5141 
5142 int ntfs_attr_expand(struct ntfs_inode *ni, const s64 newsize,
5143 		     const s64 prealloc_size)
5144 {
5145 	return ntfs_attr_expand_locked(ni, newsize, prealloc_size, NULL);
5146 }
5147 
5148 /*
5149  * ntfs_attr_truncate_i - resize an ntfs attribute
5150  * @ni:		open ntfs inode to resize
5151  * @newsize:	new size (in bytes) to which to resize the attribute
5152  * @holes:	how to create a hole if expanding
5153  *
5154  * Change the size of an open ntfs attribute @na to @newsize bytes. If the
5155  * attribute is made bigger and the attribute is resident the newly
5156  * "allocated" space is cleared and if the attribute is non-resident the
5157  * newly allocated space is marked as not initialised and no real allocation
5158  * on disk is performed.
5159  */
5160 int ntfs_attr_truncate_i_locked(struct ntfs_inode *ni, const s64 newsize,
5161 				unsigned int holes,
5162 			       struct ntfs_inode *locked_ni)
5163 {
5164 	int err;
5165 
5166 	if (newsize < 0 ||
5167 	    (ni->mft_no == FILE_MFT && ni->type == AT_DATA)) {
5168 		ntfs_debug("Invalid arguments passed.\n");
5169 		return -EINVAL;
5170 	}
5171 
5172 	ntfs_debug("Entering for inode 0x%llx, attr 0x%x, size %lld\n",
5173 			(unsigned long long)ni->mft_no, ni->type, newsize);
5174 
5175 	if (ni->data_size == newsize) {
5176 		ntfs_debug("Size is already ok\n");
5177 		return 0;
5178 	}
5179 
5180 	/*
5181 	 * Encrypted attributes are not supported. We return access denied,
5182 	 * which is what Windows NT4 does, too.
5183 	 */
5184 	if (NInoEncrypted(ni)) {
5185 		pr_err("Failed to truncate encrypted attribute\n");
5186 		return -EACCES;
5187 	}
5188 
5189 	if (NInoCompressed(ni)) {
5190 		pr_err("Failed to truncate compressed attribute\n");
5191 		return -EOPNOTSUPP;
5192 	}
5193 
5194 	if (NInoNonResident(ni)) {
5195 		if (newsize > ni->data_size)
5196 			err = ntfs_non_resident_attr_expand(
5197 					ni, newsize, 0, holes, locked_ni);
5198 		else
5199 			err = ntfs_non_resident_attr_shrink(
5200 					ni, newsize, locked_ni, false);
5201 	} else
5202 		err = ntfs_resident_attr_resize(ni, newsize, 0, holes);
5203 	if (!err && NInoAttr(ni))
5204 		i_size_write(VFS_I(ni), newsize);
5205 	ntfs_debug("Return status %d\n", err);
5206 	return err;
5207 }
5208 
5209 int ntfs_attr_truncate_i(struct ntfs_inode *ni, const s64 newsize,
5210 			 unsigned int holes)
5211 {
5212 	return ntfs_attr_truncate_i_locked(ni, newsize, holes, NULL);
5213 }
5214 
5215 /*
5216  * Resize an attribute, creating a hole if relevant
5217  */
5218 int ntfs_attr_truncate(struct ntfs_inode *ni, const s64 newsize)
5219 {
5220 	return ntfs_attr_truncate_i(ni, newsize,
5221 				    NVolDisableSparse(ni->vol) ?
5222 				    HOLES_NO : HOLES_OK);
5223 }
5224 
5225 int ntfs_attr_map_cluster(struct ntfs_inode *ni, s64 vcn_start, s64 *lcn_start,
5226 		s64 *lcn_count, s64 max_clu_count, bool *balloc, bool update_mp,
5227 		bool skip_holes)
5228 {
5229 	struct ntfs_inode *base_ni = ntfs_base_inode(ni);
5230 	struct ntfs_volume *vol = ni->vol;
5231 	struct ntfs_attr_search_ctx *ctx;
5232 	struct runlist_element *rl, *rlc;
5233 	struct runlist_element *old_rl = NULL;
5234 	s64 vcn = vcn_start, lcn, clu_count;
5235 	s64 lcn_seek_from = -1;
5236 	int err = 0;
5237 	size_t new_rl_count, old_rl_count;
5238 
5239 	err = ntfs_attr_map_whole_runlist(ni);
5240 	if (err)
5241 		return err;
5242 
5243 	ctx = ntfs_attr_get_search_ctx(base_ni, NULL);
5244 	if (!ctx) {
5245 		ntfs_error(vol->sb, "%s: Failed to get search context", __func__);
5246 		return -ENOMEM;
5247 	}
5248 
5249 	err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
5250 			CASE_SENSITIVE, vcn, NULL, 0, ctx);
5251 	if (err) {
5252 		ntfs_error(vol->sb,
5253 			   "ntfs_attr_lookup failed, ntfs inode(mft_no : %llu) type : 0x%x, err : %d",
5254 			   ni->mft_no, ni->type, err);
5255 		goto out;
5256 	}
5257 
5258 	rl = ntfs_attr_find_vcn_nolock(ni, vcn, ctx);
5259 	if (IS_ERR(rl)) {
5260 		ntfs_error(vol->sb, "Failed to find run after mapping runlist.");
5261 		err = PTR_ERR(rl);
5262 		goto out;
5263 	}
5264 
5265 	lcn = ntfs_rl_vcn_to_lcn(rl, vcn);
5266 	clu_count = min(max_clu_count, rl->length - (vcn - rl->vcn));
5267 	if (lcn >= LCN_HOLE) {
5268 		if (lcn > LCN_DELALLOC ||
5269 		    (lcn == LCN_HOLE && skip_holes)) {
5270 			*lcn_start = lcn;
5271 			*lcn_count = clu_count;
5272 			*balloc = false;
5273 			goto out;
5274 		}
5275 	} else {
5276 		WARN_ON(lcn == LCN_RL_NOT_MAPPED);
5277 		if (lcn == LCN_ENOENT)
5278 			err = -ENOENT;
5279 		else
5280 			err = -EIO;
5281 		goto out;
5282 	}
5283 
5284 	/* Search backwards to find the best lcn to start seek from. */
5285 	rlc = rl;
5286 	while (rlc->vcn) {
5287 		rlc--;
5288 		if (rlc->lcn >= 0) {
5289 			/*
5290 			 * avoid fragmenting a compressed file
5291 			 * Windows does not do that, and that may
5292 			 * not be desirable for files which can
5293 			 * be updated
5294 			 */
5295 			if (NInoCompressed(ni))
5296 				lcn_seek_from = rlc->lcn + rlc->length;
5297 			else
5298 				lcn_seek_from = rlc->lcn + (vcn - rlc->vcn);
5299 			break;
5300 		}
5301 	}
5302 
5303 	if (lcn_seek_from == -1) {
5304 		/* Backwards search failed, search forwards. */
5305 		rlc = rl;
5306 		while (rlc->length) {
5307 			rlc++;
5308 			if (rlc->lcn >= 0) {
5309 				lcn_seek_from = rlc->lcn - (rlc->vcn - vcn);
5310 				if (lcn_seek_from < -1)
5311 					lcn_seek_from = -1;
5312 				break;
5313 			}
5314 		}
5315 	}
5316 
5317 	rlc = ntfs_cluster_alloc(vol, vcn, clu_count, lcn_seek_from, DATA_ZONE,
5318 			false, true, true);
5319 	if (IS_ERR(rlc)) {
5320 		err = PTR_ERR(rlc);
5321 		goto out;
5322 	}
5323 
5324 	WARN_ON(rlc->vcn != vcn);
5325 	lcn = rlc->lcn;
5326 	clu_count = rlc->length;
5327 	old_rl_count = ni->runlist.count;
5328 	old_rl = kmemdup(ni->runlist.rl,
5329 			 old_rl_count * sizeof(*old_rl), GFP_NOFS);
5330 	if (!old_rl) {
5331 		err = -ENOMEM;
5332 		if (ntfs_cluster_free_from_rl(vol, rlc)) {
5333 			ntfs_error(vol->sb,
5334 				   "Failed to free cluster allocation after runlist backup failure.");
5335 			NVolSetErrors(vol);
5336 		}
5337 		kvfree(rlc);
5338 		goto out;
5339 	}
5340 
5341 	rl = ntfs_runlists_merge(&ni->runlist, rlc, 0, &new_rl_count);
5342 	if (IS_ERR(rl)) {
5343 		ntfs_error(vol->sb, "Failed to merge runlists");
5344 		err = PTR_ERR(rl);
5345 		if (ntfs_cluster_free_from_rl(vol, rlc))
5346 			ntfs_error(vol->sb, "Failed to free hot clusters.");
5347 		kvfree(rlc);
5348 		goto out;
5349 	}
5350 	ni->runlist.rl = rl;
5351 	ni->runlist.count = new_rl_count;
5352 
5353 	if (!update_mp) {
5354 		u64 free = atomic64_read(&vol->free_clusters) * 100;
5355 
5356 		do_div(free, vol->nr_clusters);
5357 		if (free <= 5)
5358 			update_mp = true;
5359 	}
5360 
5361 	if (update_mp) {
5362 		ntfs_attr_reinit_search_ctx(ctx);
5363 		err = ntfs_attr_update_mapping_pairs_locked(ni, 0, ni);
5364 		if (err) {
5365 			int err2;
5366 
5367 			err2 = ntfs_cluster_free(ni, vcn, clu_count, ctx);
5368 			if (err2 < 0 || err2 != clu_count) {
5369 				ntfs_error(vol->sb,
5370 					   "Failed to free cluster allocation. Leaving inconsistent metadata.\n");
5371 				NVolSetErrors(vol);
5372 				goto out;
5373 			}
5374 
5375 			/*
5376 			 * Restore the runlist before repairing the on-disk
5377 			 * mapping pairs.
5378 			 */
5379 			kvfree(ni->runlist.rl);
5380 			ni->runlist.rl = old_rl;
5381 			ni->runlist.count = old_rl_count;
5382 			old_rl = NULL;
5383 			if (ntfs_attr_update_mapping_pairs_locked(
5384 					ni, 0, ni)) {
5385 				ntfs_error(vol->sb,
5386 					   "Failed to restore mapping pairs after allocation rollback.\n");
5387 				NVolSetErrors(vol);
5388 			}
5389 		}
5390 	} else {
5391 		VFS_I(ni)->i_blocks += clu_count << (vol->cluster_size_bits - 9);
5392 		NInoSetRunlistDirty(ni);
5393 		mark_mft_record_dirty(base_ni);
5394 	}
5395 
5396 	*lcn_start = lcn;
5397 	*lcn_count = clu_count;
5398 	*balloc = true;
5399 out:
5400 	kvfree(old_rl);
5401 	ntfs_attr_put_search_ctx(ctx);
5402 	return err;
5403 }
5404 
5405 /*
5406  * ntfs_attr_rm - remove attribute from ntfs inode
5407  * @ni:		opened ntfs attribute to delete
5408  *
5409  * Remove attribute and all it's extents from ntfs inode. If attribute was non
5410  * resident also free all clusters allocated by attribute.
5411  */
5412 int ntfs_attr_rm(struct ntfs_inode *ni)
5413 {
5414 	struct ntfs_attr_search_ctx *ctx;
5415 	int err = 0, ret = 0;
5416 	struct ntfs_inode *base_ni;
5417 	struct super_block *sb = ni->vol->sb;
5418 
5419 	base_ni = ntfs_base_inode(ni);
5420 
5421 	ntfs_debug("Entering for inode 0x%llx, attr 0x%x.\n",
5422 			(long long) ni->mft_no, ni->type);
5423 
5424 	/* Free cluster allocation. */
5425 	if (NInoNonResident(ni)) {
5426 		struct ntfs_attr_search_ctx *ctx;
5427 
5428 		err = ntfs_attr_map_whole_runlist(ni);
5429 		if (err)
5430 			return err;
5431 		ctx = ntfs_attr_get_search_ctx(base_ni, NULL);
5432 		if (!ctx) {
5433 			ntfs_error(sb, "%s: Failed to get search context", __func__);
5434 			return -ENOMEM;
5435 		}
5436 
5437 		ret = ntfs_cluster_free(ni, 0, -1, ctx);
5438 		if (ret < 0)
5439 			ntfs_error(sb,
5440 				"Failed to free cluster allocation. Leaving inconstant metadata.\n");
5441 		ntfs_attr_put_search_ctx(ctx);
5442 	}
5443 
5444 	/* Search for attribute extents and remove them all. */
5445 	ctx = ntfs_attr_get_search_ctx(base_ni, NULL);
5446 	if (!ctx) {
5447 		ntfs_error(sb, "%s: Failed to get search context", __func__);
5448 		return -ENOMEM;
5449 	}
5450 	while (!(err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
5451 				CASE_SENSITIVE, 0, NULL, 0, ctx))) {
5452 		err = ntfs_attr_record_rm(ctx);
5453 		if (err) {
5454 			ntfs_error(sb,
5455 				"Failed to remove attribute extent. Leaving inconstant metadata.\n");
5456 			ret = err;
5457 		}
5458 		ntfs_attr_reinit_search_ctx(ctx);
5459 	}
5460 	ntfs_attr_put_search_ctx(ctx);
5461 	if (err != -ENOENT) {
5462 		ntfs_error(sb, "Attribute lookup failed. Probably leaving inconstant metadata.\n");
5463 		ret = err;
5464 	}
5465 
5466 	return ret;
5467 }
5468 
5469 int ntfs_attr_exist(struct ntfs_inode *ni, const __le32 type, __le16 *name,
5470 		u32 name_len)
5471 {
5472 	struct ntfs_attr_search_ctx *ctx;
5473 	u32 ic;
5474 	int ret;
5475 
5476 	ntfs_debug("Entering\n");
5477 
5478 	ctx = ntfs_attr_get_search_ctx(ni, NULL);
5479 	if (!ctx) {
5480 		ntfs_error(ni->vol->sb, "%s: Failed to get search context",
5481 				__func__);
5482 		return 0;
5483 	}
5484 
5485 	ic = type == AT_DATA && name_len ? IGNORE_CASE : CASE_SENSITIVE;
5486 	ret = ntfs_attr_lookup(type, name, name_len, ic,
5487 			0, NULL, 0, ctx);
5488 	ntfs_attr_put_search_ctx(ctx);
5489 
5490 	return !ret;
5491 }
5492 
5493 /*
5494  * If @attr_vi is non-NULL, the attribute inode reference is returned to the
5495  * caller, which must release it after dropping ni->mrec_lock.
5496  */
5497 int ntfs_attr_remove(struct ntfs_inode *ni, const __le32 type, __le16 *name,
5498 		u32 name_len, struct inode **attr_vi)
5499 {
5500 	int err;
5501 	struct inode *vi;
5502 	struct ntfs_inode *attr_ni;
5503 
5504 	ntfs_debug("Entering\n");
5505 
5506 	if (attr_vi)
5507 		*attr_vi = NULL;
5508 	if (!ni)
5509 		return -EINVAL;
5510 
5511 	vi = ntfs_attr_iget(VFS_I(ni), type, name, name_len);
5512 	if (IS_ERR(vi)) {
5513 		err = PTR_ERR(vi);
5514 		ntfs_error(ni->vol->sb, "Failed to open attribute 0x%02x of inode 0x%llx",
5515 				type, (unsigned long long)ni->mft_no);
5516 		return err;
5517 	}
5518 	attr_ni = NTFS_I(vi);
5519 
5520 	err = ntfs_attr_rm(attr_ni);
5521 	if (err) {
5522 		ntfs_error(ni->vol->sb, "Failed to remove attribute 0x%02x of inode 0x%llx",
5523 				type, (unsigned long long)ni->mft_no);
5524 	} else {
5525 		NInoClearDirty(attr_ni);
5526 		clear_nlink(vi);
5527 		remove_inode_hash(vi);
5528 	}
5529 	if (attr_vi)
5530 		*attr_vi = vi;
5531 	else
5532 		iput(vi);
5533 	return err;
5534 }
5535 
5536 /*
5537  * ntfs_attr_readall - read the entire data from an ntfs attribute
5538  * @ni:		open ntfs inode in which the ntfs attribute resides
5539  * @type:	attribute type
5540  * @name:	attribute name in little endian Unicode or AT_UNNAMED or NULL
5541  * @name_len:	length of attribute @name in Unicode characters (if @name given)
5542  * @data_size:	if non-NULL then store here the data size
5543  *
5544  * This function will read the entire content of an ntfs attribute.
5545  * If @name is AT_UNNAMED then look specifically for an unnamed attribute.
5546  * If @name is NULL then the attribute could be either named or not.
5547  * In both those cases @name_len is not used at all.
5548  *
5549  * On success a buffer is allocated with the content of the attribute
5550  * and which needs to be freed when it's not needed anymore. If the
5551  * @data_size parameter is non-NULL then the data size is set there.
5552  * On error, an ERR_PTR() containing the negative error code is returned.
5553  */
5554 void *ntfs_attr_readall(struct ntfs_inode *ni, const __le32 type,
5555 		__le16 *name, u32 name_len, s64 *data_size)
5556 {
5557 	struct ntfs_inode *bmp_ni;
5558 	struct inode *bmp_vi;
5559 	void *data, *ret = NULL;
5560 	s64 size;
5561 	struct super_block *sb = ni->vol->sb;
5562 
5563 	ntfs_debug("Entering\n");
5564 
5565 	bmp_vi = ntfs_attr_iget(VFS_I(ni), type, name, name_len);
5566 	if (IS_ERR(bmp_vi)) {
5567 		ret = ERR_PTR(PTR_ERR(bmp_vi));
5568 		ntfs_debug("ntfs_attr_iget failed");
5569 		goto err_exit;
5570 	}
5571 	bmp_ni = NTFS_I(bmp_vi);
5572 
5573 	if (bmp_ni->data_size > NTFS_ATTR_READALL_MAX_SIZE &&
5574 		(bmp_ni->type != AT_BITMAP ||
5575 		bmp_ni->data_size > ((ni->vol->nr_clusters + 7) >> 3))) {
5576 		ntfs_error(sb, "Invalid attribute data size");
5577 		ret = ERR_PTR(-EIO);
5578 		goto out;
5579 	}
5580 
5581 	data = kvmalloc(bmp_ni->data_size, GFP_NOFS);
5582 	if (!data) {
5583 		ret = ERR_PTR(-ENOMEM);
5584 		goto out;
5585 	}
5586 
5587 	size = ntfs_inode_attr_pread(VFS_I(bmp_ni), 0, bmp_ni->data_size,
5588 			(u8 *)data);
5589 	if (size != bmp_ni->data_size) {
5590 		ntfs_error(sb, "ntfs_attr_pread failed");
5591 		ret = size < 0 ? ERR_PTR((int)size) : ERR_PTR(-EIO);
5592 		kvfree(data);
5593 		goto out;
5594 	}
5595 	ret = data;
5596 	if (data_size)
5597 		*data_size = size;
5598 out:
5599 	iput(bmp_vi);
5600 err_exit:
5601 	ntfs_debug("\n");
5602 	return ret;
5603 }
5604 
5605 int ntfs_non_resident_attr_insert_range(struct ntfs_inode *ni, s64 start_vcn, s64 len)
5606 {
5607 	struct ntfs_inode *base_ni = ntfs_base_inode(ni);
5608 	struct ntfs_volume *vol = ni->vol;
5609 	struct runlist_element *hole_rl, *rl;
5610 	struct ntfs_attr_search_ctx *ctx;
5611 	int ret;
5612 	size_t new_rl_count;
5613 
5614 	if (ni->type != AT_DATA)
5615 		return -EOPNOTSUPP;
5616 	if (start_vcn > ntfs_bytes_to_cluster(vol, ni->allocated_size))
5617 		return -EINVAL;
5618 
5619 	hole_rl = kmalloc(sizeof(*hole_rl) * 2, GFP_NOFS);
5620 	if (!hole_rl)
5621 		return -ENOMEM;
5622 	hole_rl[0].vcn = start_vcn;
5623 	hole_rl[0].lcn = LCN_HOLE;
5624 	hole_rl[0].length = len;
5625 	hole_rl[1].vcn = start_vcn + len;
5626 	hole_rl[1].lcn = LCN_ENOENT;
5627 	hole_rl[1].length = 0;
5628 
5629 	down_write(&ni->runlist.lock);
5630 	ret = ntfs_attr_map_whole_runlist(ni);
5631 	if (ret) {
5632 		up_write(&ni->runlist.lock);
5633 		kfree(hole_rl);
5634 		return ret;
5635 	}
5636 
5637 	rl = ntfs_rl_find_vcn_nolock(ni->runlist.rl, start_vcn);
5638 	if (!rl) {
5639 		up_write(&ni->runlist.lock);
5640 		kfree(hole_rl);
5641 		return -EIO;
5642 	}
5643 
5644 	rl = ntfs_rl_insert_range(ni->runlist.rl, (int)ni->runlist.count,
5645 				  hole_rl, 1, &new_rl_count);
5646 	if (IS_ERR(rl)) {
5647 		up_write(&ni->runlist.lock);
5648 		kfree(hole_rl);
5649 		return PTR_ERR(rl);
5650 	}
5651 	ni->runlist.rl =  rl;
5652 	ni->runlist.count = new_rl_count;
5653 
5654 	ni->allocated_size += ntfs_cluster_to_bytes(vol, len);
5655 	ni->data_size += ntfs_cluster_to_bytes(vol, len);
5656 	if (ntfs_cluster_to_bytes(vol, start_vcn) < ni->initialized_size)
5657 		ni->initialized_size += ntfs_cluster_to_bytes(vol, len);
5658 	ret = ntfs_attr_update_mapping_pairs_locked(ni, 0, ni);
5659 	up_write(&ni->runlist.lock);
5660 	if (ret)
5661 		return ret;
5662 
5663 	ctx = ntfs_attr_get_search_ctx(base_ni, NULL);
5664 	if (!ctx) {
5665 		ret = -ENOMEM;
5666 		return ret;
5667 	}
5668 
5669 	ret = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
5670 			       CASE_SENSITIVE, 0, NULL, 0, ctx);
5671 	if (ret) {
5672 		ntfs_attr_put_search_ctx(ctx);
5673 		return ret;
5674 	}
5675 
5676 	ctx->attr->data.non_resident.data_size = cpu_to_le64(ni->data_size);
5677 	ctx->attr->data.non_resident.initialized_size = cpu_to_le64(ni->initialized_size);
5678 	if (ni->type == AT_DATA && ni->name == AT_UNNAMED)
5679 		NInoSetFileNameDirty(ni);
5680 	mark_mft_record_dirty(ctx->ntfs_ino);
5681 	ntfs_attr_put_search_ctx(ctx);
5682 	return ret;
5683 }
5684 
5685 int ntfs_non_resident_attr_collapse_range(struct ntfs_inode *ni, s64 start_vcn, s64 len)
5686 {
5687 	struct ntfs_inode *base_ni = ntfs_base_inode(ni);
5688 	struct ntfs_volume *vol = ni->vol;
5689 	struct runlist_element *punch_rl, *rl;
5690 	struct ntfs_attr_search_ctx *ctx = NULL;
5691 	s64 end_vcn;
5692 	int dst_cnt;
5693 	int ret;
5694 	size_t new_rl_cnt;
5695 
5696 	if (ni->type != AT_DATA)
5697 		return -EOPNOTSUPP;
5698 
5699 	end_vcn = ntfs_bytes_to_cluster(vol, ni->allocated_size);
5700 	if (start_vcn >= end_vcn)
5701 		return -EINVAL;
5702 
5703 	down_write(&ni->runlist.lock);
5704 	ret = ntfs_attr_map_whole_runlist(ni);
5705 	if (ret) {
5706 		up_write(&ni->runlist.lock);
5707 		return ret;
5708 	}
5709 
5710 	len = min(len, end_vcn - start_vcn);
5711 	for (rl = ni->runlist.rl, dst_cnt = 0; rl && rl->length; rl++)
5712 		dst_cnt++;
5713 	rl = ntfs_rl_find_vcn_nolock(ni->runlist.rl, start_vcn);
5714 	if (!rl) {
5715 		up_write(&ni->runlist.lock);
5716 		return -EIO;
5717 	}
5718 
5719 	rl = ntfs_rl_collapse_range(ni->runlist.rl, dst_cnt + 1,
5720 				    start_vcn, len, &punch_rl, &new_rl_cnt);
5721 	if (IS_ERR(rl)) {
5722 		up_write(&ni->runlist.lock);
5723 		return PTR_ERR(rl);
5724 	}
5725 	ni->runlist.rl = rl;
5726 	ni->runlist.count = new_rl_cnt;
5727 
5728 	ni->allocated_size -= ntfs_cluster_to_bytes(vol, len);
5729 	if (ni->data_size > ntfs_cluster_to_bytes(vol, start_vcn)) {
5730 		if (ni->data_size > ntfs_cluster_to_bytes(vol, (start_vcn + len)))
5731 			ni->data_size -= ntfs_cluster_to_bytes(vol, len);
5732 		else
5733 			ni->data_size = ntfs_cluster_to_bytes(vol, start_vcn);
5734 	}
5735 	if (ni->initialized_size > ntfs_cluster_to_bytes(vol, start_vcn)) {
5736 		if (ni->initialized_size >
5737 		    ntfs_cluster_to_bytes(vol, start_vcn + len))
5738 			ni->initialized_size -= ntfs_cluster_to_bytes(vol, len);
5739 		else
5740 			ni->initialized_size = ntfs_cluster_to_bytes(vol, start_vcn);
5741 	}
5742 
5743 	if (ni->allocated_size > 0) {
5744 		ret = ntfs_attr_update_mapping_pairs_locked(ni, 0, ni);
5745 		if (ret) {
5746 			up_write(&ni->runlist.lock);
5747 			goto out_rl;
5748 		}
5749 	}
5750 	up_write(&ni->runlist.lock);
5751 
5752 	ctx = ntfs_attr_get_search_ctx(base_ni, NULL);
5753 	if (!ctx) {
5754 		ret = -ENOMEM;
5755 		goto out_rl;
5756 	}
5757 
5758 	ret = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
5759 			       CASE_SENSITIVE, 0, NULL, 0, ctx);
5760 	if (ret)
5761 		goto out_ctx;
5762 
5763 	ctx->attr->data.non_resident.data_size = cpu_to_le64(ni->data_size);
5764 	ctx->attr->data.non_resident.initialized_size = cpu_to_le64(ni->initialized_size);
5765 	if (ni->allocated_size == 0)
5766 		ntfs_attr_make_resident(ni, ctx);
5767 	mark_mft_record_dirty(ctx->ntfs_ino);
5768 
5769 	ret = ntfs_cluster_free_from_rl(vol, punch_rl);
5770 	if (ret)
5771 		ntfs_error(vol->sb, "Freeing of clusters failed");
5772 out_ctx:
5773 	if (ctx)
5774 		ntfs_attr_put_search_ctx(ctx);
5775 out_rl:
5776 	kvfree(punch_rl);
5777 	mark_mft_record_dirty(base_ni);
5778 	return ret;
5779 }
5780 
5781 int ntfs_non_resident_attr_punch_hole(struct ntfs_inode *ni, s64 start_vcn, s64 len)
5782 {
5783 	struct ntfs_inode *base_ni = ntfs_base_inode(ni);
5784 	struct ntfs_volume *vol = ni->vol;
5785 	struct runlist_element *punch_rl, *rl;
5786 	s64 end_vcn;
5787 	int dst_cnt;
5788 	int ret;
5789 	size_t new_rl_count;
5790 
5791 	if (ni->type != AT_DATA)
5792 		return -EOPNOTSUPP;
5793 
5794 	end_vcn = ntfs_bytes_to_cluster(vol, ni->allocated_size);
5795 	if (start_vcn >= end_vcn)
5796 		return -EINVAL;
5797 
5798 	down_write(&ni->runlist.lock);
5799 	ret = ntfs_attr_map_whole_runlist(ni);
5800 	if (ret) {
5801 		up_write(&ni->runlist.lock);
5802 		return ret;
5803 	}
5804 
5805 	len = min(len, end_vcn - start_vcn + 1);
5806 	for (rl = ni->runlist.rl, dst_cnt = 0; rl && rl->length; rl++)
5807 		dst_cnt++;
5808 	rl = ntfs_rl_find_vcn_nolock(ni->runlist.rl, start_vcn);
5809 	if (!rl) {
5810 		up_write(&ni->runlist.lock);
5811 		return -EIO;
5812 	}
5813 
5814 	rl = ntfs_rl_punch_hole(ni->runlist.rl, dst_cnt + 1,
5815 				start_vcn, len, &punch_rl, &new_rl_count);
5816 	if (IS_ERR(rl)) {
5817 		up_write(&ni->runlist.lock);
5818 		return PTR_ERR(rl);
5819 	}
5820 	ni->runlist.rl = rl;
5821 	ni->runlist.count = new_rl_count;
5822 
5823 	ret = ntfs_attr_update_mapping_pairs_locked(ni, 0, ni);
5824 	up_write(&ni->runlist.lock);
5825 	if (ret) {
5826 		kvfree(punch_rl);
5827 		return ret;
5828 	}
5829 
5830 	ret = ntfs_cluster_free_from_rl(vol, punch_rl);
5831 	if (ret)
5832 		ntfs_error(vol->sb, "Freeing of clusters failed");
5833 
5834 	kvfree(punch_rl);
5835 	mark_mft_record_dirty(base_ni);
5836 	return ret;
5837 }
5838 
5839 int ntfs_attr_fallocate(struct ntfs_inode *ni, loff_t start, loff_t byte_len, bool keep_size)
5840 {
5841 	struct ntfs_inode *base_ni = ntfs_base_inode(ni);
5842 	struct ntfs_volume *vol = ni->vol;
5843 	struct mft_record *mrec;
5844 	struct ntfs_attr_search_ctx *ctx;
5845 	s64 old_data_size;
5846 	s64 vcn_start, vcn_end, vcn_uninit, vcn, try_alloc_cnt;
5847 	s64 lcn, alloc_cnt;
5848 	s64 rl_lcn, rl_length, rl_vcn;
5849 	int err = 0;
5850 	struct runlist_element *rl;
5851 	bool balloc;
5852 
5853 	if (ni->type != AT_DATA)
5854 		return -EINVAL;
5855 
5856 	if (NInoNonResident(ni) && !NInoFullyMapped(ni)) {
5857 		down_write(&ni->runlist.lock);
5858 		err = ntfs_attr_map_whole_runlist(ni);
5859 		up_write(&ni->runlist.lock);
5860 		if (err)
5861 			return err;
5862 	}
5863 
5864 	mutex_lock_nested(&base_ni->mrec_lock, NTFS_INODE_MUTEX_NORMAL);
5865 	mrec = map_mft_record(base_ni);
5866 	if (IS_ERR(mrec)) {
5867 		mutex_unlock(&base_ni->mrec_lock);
5868 		return PTR_ERR(mrec);
5869 	}
5870 
5871 	ctx = ntfs_attr_get_search_ctx(base_ni, mrec);
5872 	if (!ctx) {
5873 		err = -ENOMEM;
5874 		goto out_unmap;
5875 	}
5876 
5877 	err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
5878 			CASE_SENSITIVE, 0, NULL, 0, ctx);
5879 	if (err) {
5880 		err = -EIO;
5881 		goto out_unmap;
5882 	}
5883 
5884 	old_data_size = ni->data_size;
5885 	if (start + byte_len > ni->data_size) {
5886 		err = ntfs_attr_truncate(ni, start + byte_len);
5887 		if (err)
5888 			goto out_unmap;
5889 		if (keep_size) {
5890 			ntfs_attr_reinit_search_ctx(ctx);
5891 			err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
5892 					CASE_SENSITIVE, 0, NULL, 0,
5893 					ctx);
5894 			if (err) {
5895 				err = -EIO;
5896 				goto out_unmap;
5897 			}
5898 			ni->data_size = old_data_size;
5899 			i_size_write(VFS_I(ni), old_data_size);
5900 			if (NInoNonResident(ni))
5901 				ctx->attr->data.non_resident.data_size =
5902 					cpu_to_le64(old_data_size);
5903 			else
5904 				ctx->attr->data.resident.value_length =
5905 					cpu_to_le32((u32)old_data_size);
5906 			mark_mft_record_dirty(base_ni);
5907 		}
5908 	}
5909 
5910 	ntfs_attr_put_search_ctx(ctx);
5911 	unmap_mft_record(base_ni);
5912 	mutex_unlock(&base_ni->mrec_lock);
5913 
5914 	if (!NInoNonResident(ni))
5915 		goto out;
5916 
5917 	vcn_start = (s64)ntfs_bytes_to_cluster(vol, start);
5918 	vcn_end = (s64)ntfs_bytes_to_cluster(vol,
5919 			round_up(start + byte_len, vol->cluster_size));
5920 	vcn_uninit = (s64)ntfs_bytes_to_cluster(vol,
5921 			round_up(ni->initialized_size, vol->cluster_size));
5922 	vcn_uninit = min_t(s64, vcn_uninit, vcn_end);
5923 
5924 	/*
5925 	 * we have to allocate clusters for holes and delayed within initialized_size,
5926 	 * and zero out the clusters only for the holes.
5927 	 */
5928 	vcn = vcn_start;
5929 	while (vcn < vcn_uninit) {
5930 		down_read(&ni->runlist.lock);
5931 		rl = ntfs_attr_find_vcn_nolock(ni, vcn, NULL);
5932 		if (IS_ERR(rl)) {
5933 			up_read(&ni->runlist.lock);
5934 			err = PTR_ERR(rl);
5935 			goto out;
5936 		}
5937 		rl_lcn = rl->lcn;
5938 		rl_length = rl->length;
5939 		rl_vcn = rl->vcn;
5940 		up_read(&ni->runlist.lock);
5941 
5942 		if (rl_lcn > 0) {
5943 			vcn += rl_length - (vcn - rl_vcn);
5944 		} else if (rl_lcn == LCN_DELALLOC || rl_lcn == LCN_HOLE) {
5945 			try_alloc_cnt = min(rl_length - (vcn - rl_vcn),
5946 					    vcn_uninit - vcn);
5947 
5948 			if (rl_lcn == LCN_DELALLOC) {
5949 				vcn += try_alloc_cnt;
5950 				continue;
5951 			}
5952 
5953 			while (try_alloc_cnt > 0) {
5954 				mutex_lock_nested(&base_ni->mrec_lock,
5955 						NTFS_INODE_MUTEX_NORMAL);
5956 				down_write(&ni->runlist.lock);
5957 				err = ntfs_attr_map_cluster(ni, vcn, &lcn, &alloc_cnt,
5958 							    try_alloc_cnt, &balloc, false, false);
5959 				up_write(&ni->runlist.lock);
5960 				mutex_unlock(&base_ni->mrec_lock);
5961 				if (err)
5962 					goto out;
5963 
5964 				if (balloc) {
5965 					err = ntfs_dio_zero_range(VFS_I(ni),
5966 								  lcn << vol->cluster_size_bits,
5967 								  alloc_cnt <<
5968 								  vol->cluster_size_bits);
5969 					if (err)
5970 						goto out;
5971 				}
5972 
5973 				if (fatal_signal_pending(current))
5974 					goto signal_out;
5975 
5976 				vcn += alloc_cnt;
5977 				try_alloc_cnt -= alloc_cnt;
5978 			}
5979 		} else {
5980 			err = -EIO;
5981 			goto out;
5982 		}
5983 	}
5984 
5985 	/* allocate clusters outside of initialized_size */
5986 	try_alloc_cnt = vcn_end - vcn;
5987 	while (try_alloc_cnt > 0) {
5988 		mutex_lock_nested(&base_ni->mrec_lock, NTFS_INODE_MUTEX_NORMAL);
5989 		down_write(&ni->runlist.lock);
5990 		err = ntfs_attr_map_cluster(ni, vcn, &lcn, &alloc_cnt,
5991 					    try_alloc_cnt, &balloc, false, false);
5992 		up_write(&ni->runlist.lock);
5993 		mutex_unlock(&base_ni->mrec_lock);
5994 		if (err || fatal_signal_pending(current))
5995 			goto signal_out;
5996 
5997 		vcn += alloc_cnt;
5998 		try_alloc_cnt -= alloc_cnt;
5999 		cond_resched();
6000 	}
6001 
6002 	if (NInoRunlistDirty(ni)) {
6003 		mutex_lock_nested(&base_ni->mrec_lock, NTFS_INODE_MUTEX_NORMAL);
6004 		down_write(&ni->runlist.lock);
6005 		err = ntfs_attr_update_mapping_pairs_locked(ni, 0, ni);
6006 		if (err)
6007 			ntfs_error(ni->vol->sb, "Updating mapping pairs failed");
6008 		else
6009 			NInoClearRunlistDirty(ni);
6010 		up_write(&ni->runlist.lock);
6011 		mutex_unlock(&base_ni->mrec_lock);
6012 	}
6013 	return err;
6014 out_unmap:
6015 	if (ctx)
6016 		ntfs_attr_put_search_ctx(ctx);
6017 	unmap_mft_record(base_ni);
6018 	mutex_unlock(&base_ni->mrec_lock);
6019 out:
6020 	return err >= 0 ? 0 : err;
6021 signal_out:
6022 	if (!err)
6023 		err = -EINTR;
6024 	goto out;
6025 }
6026