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