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