1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  *
4  * Copyright (C) 2019-2021 Paragon Software GmbH, All rights reserved.
5  *
6  */
7 
8 #include <linux/fiemap.h>
9 #include <linux/fs.h>
10 #include <linux/minmax.h>
11 #include <linux/vmalloc.h>
12 
13 #include "debug.h"
14 #include "ntfs.h"
15 #include "ntfs_fs.h"
16 #ifdef CONFIG_NTFS3_LZX_XPRESS
17 #include "lib/lib.h"
18 #endif
19 
ni_ins_mi(struct ntfs_inode * ni,struct rb_root * tree,CLST ino,struct rb_node * ins)20 static struct mft_inode *ni_ins_mi(struct ntfs_inode *ni, struct rb_root *tree,
21 				   CLST ino, struct rb_node *ins)
22 {
23 	struct rb_node **p = &tree->rb_node;
24 	struct rb_node *pr = NULL;
25 
26 	while (*p) {
27 		struct mft_inode *mi;
28 
29 		pr = *p;
30 		mi = rb_entry(pr, struct mft_inode, node);
31 		if (mi->rno > ino)
32 			p = &pr->rb_left;
33 		else if (mi->rno < ino)
34 			p = &pr->rb_right;
35 		else
36 			return mi;
37 	}
38 
39 	if (!ins)
40 		return NULL;
41 
42 	rb_link_node(ins, pr, p);
43 	rb_insert_color(ins, tree);
44 	return rb_entry(ins, struct mft_inode, node);
45 }
46 
47 /*
48  * ni_find_mi - Find mft_inode by record number.
49  */
ni_find_mi(struct ntfs_inode * ni,CLST rno)50 static struct mft_inode *ni_find_mi(struct ntfs_inode *ni, CLST rno)
51 {
52 	return ni_ins_mi(ni, &ni->mi_tree, rno, NULL);
53 }
54 
55 /*
56  * ni_add_mi - Add new mft_inode into ntfs_inode.
57  */
ni_add_mi(struct ntfs_inode * ni,struct mft_inode * mi)58 static void ni_add_mi(struct ntfs_inode *ni, struct mft_inode *mi)
59 {
60 	ni_ins_mi(ni, &ni->mi_tree, mi->rno, &mi->node);
61 }
62 
63 /*
64  * ni_remove_mi - Remove mft_inode from ntfs_inode.
65  */
ni_remove_mi(struct ntfs_inode * ni,struct mft_inode * mi)66 void ni_remove_mi(struct ntfs_inode *ni, struct mft_inode *mi)
67 {
68 	rb_erase(&mi->node, &ni->mi_tree);
69 }
70 
71 /*
72  * ni_std - Return: Pointer into std_info from primary record.
73  */
ni_std(struct ntfs_inode * ni)74 struct ATTR_STD_INFO *ni_std(struct ntfs_inode *ni)
75 {
76 	const struct ATTRIB *attr;
77 
78 	attr = mi_find_attr(&ni->mi, NULL, ATTR_STD, NULL, 0, NULL);
79 	return attr ? resident_data_ex(attr, sizeof(struct ATTR_STD_INFO)) :
80 		      NULL;
81 }
82 
83 /*
84  * ni_std5
85  *
86  * Return: Pointer into std_info from primary record.
87  */
ni_std5(struct ntfs_inode * ni)88 struct ATTR_STD_INFO5 *ni_std5(struct ntfs_inode *ni)
89 {
90 	const struct ATTRIB *attr;
91 
92 	attr = mi_find_attr(&ni->mi, NULL, ATTR_STD, NULL, 0, NULL);
93 
94 	return attr ? resident_data_ex(attr, sizeof(struct ATTR_STD_INFO5)) :
95 		      NULL;
96 }
97 
98 /*
99  * ni_clear - Clear resources allocated by ntfs_inode.
100  */
ni_clear(struct ntfs_inode * ni)101 void ni_clear(struct ntfs_inode *ni)
102 {
103 	struct rb_node *node;
104 
105 	if (!ni->vfs_inode.i_nlink && ni->mi.mrec &&
106 	    is_rec_inuse(ni->mi.mrec) &&
107 	    !(ni->mi.sbi->flags & NTFS_FLAGS_LOG_REPLAYING))
108 		ni_delete_all(ni);
109 
110 	al_destroy(ni);
111 
112 	for (node = rb_first(&ni->mi_tree); node;) {
113 		struct rb_node *next = rb_next(node);
114 		struct mft_inode *mi = rb_entry(node, struct mft_inode, node);
115 
116 		rb_erase(node, &ni->mi_tree);
117 		mi_put(mi);
118 		node = next;
119 	}
120 
121 	/* Bad inode always has mode == S_IFREG. */
122 	if (ni->ni_flags & NI_FLAG_DIR)
123 		indx_clear(&ni->dir);
124 	else {
125 		run_close(&ni->file.run);
126 #ifdef CONFIG_NTFS3_LZX_XPRESS
127 		if (ni->file.offs_folio) {
128 			/* On-demand allocated page for offsets. */
129 			folio_put(ni->file.offs_folio);
130 			ni->file.offs_folio = NULL;
131 		}
132 #endif
133 	}
134 
135 	mi_clear(&ni->mi);
136 }
137 
138 /*
139  * ni_load_mi_ex - Find mft_inode by record number.
140  */
ni_load_mi_ex(struct ntfs_inode * ni,CLST rno,struct mft_inode ** mi)141 int ni_load_mi_ex(struct ntfs_inode *ni, CLST rno, struct mft_inode **mi)
142 {
143 	int err;
144 	struct mft_inode *r;
145 
146 	r = ni_find_mi(ni, rno);
147 	if (r)
148 		goto out;
149 
150 	err = mi_get(ni->mi.sbi, rno, &r);
151 	if (err) {
152 		_ntfs_bad_inode(&ni->vfs_inode);
153 		return err;
154 	}
155 
156 	ni_add_mi(ni, r);
157 
158 out:
159 	if (mi)
160 		*mi = r;
161 	return 0;
162 }
163 
164 /*
165  * ni_load_mi - Load mft_inode corresponded list_entry.
166  */
ni_load_mi(struct ntfs_inode * ni,const struct ATTR_LIST_ENTRY * le,struct mft_inode ** mi)167 int ni_load_mi(struct ntfs_inode *ni, const struct ATTR_LIST_ENTRY *le,
168 	       struct mft_inode **mi)
169 {
170 	CLST rno;
171 
172 	if (!le) {
173 		*mi = &ni->mi;
174 		return 0;
175 	}
176 
177 	rno = ino_get(&le->ref);
178 	if (rno == ni->mi.rno) {
179 		*mi = &ni->mi;
180 		return 0;
181 	}
182 	return ni_load_mi_ex(ni, rno, mi);
183 }
184 
185 /*
186  * ni_find_attr
187  *
188  * Return: Attribute and record this attribute belongs to.
189  */
ni_find_attr(struct ntfs_inode * ni,struct ATTRIB * attr,struct ATTR_LIST_ENTRY ** le_o,enum ATTR_TYPE type,const __le16 * name,u8 name_len,const CLST * vcn,struct mft_inode ** mi)190 struct ATTRIB *ni_find_attr(struct ntfs_inode *ni, struct ATTRIB *attr,
191 			    struct ATTR_LIST_ENTRY **le_o, enum ATTR_TYPE type,
192 			    const __le16 *name, u8 name_len, const CLST *vcn,
193 			    struct mft_inode **mi)
194 {
195 	struct ATTR_LIST_ENTRY *le;
196 	struct mft_inode *m;
197 
198 	if (!ni->attr_list.size ||
199 	    (!name_len && (type == ATTR_LIST || type == ATTR_STD))) {
200 		if (le_o)
201 			*le_o = NULL;
202 		if (mi)
203 			*mi = &ni->mi;
204 
205 		/* Look for required attribute in primary record. */
206 		return mi_find_attr(&ni->mi, attr, type, name, name_len, NULL);
207 	}
208 
209 	/* First look for list entry of required type. */
210 	le = al_find_ex(ni, le_o ? *le_o : NULL, type, name, name_len, vcn);
211 	if (!le)
212 		return NULL;
213 
214 	if (le_o)
215 		*le_o = le;
216 
217 	/* Load record that contains this attribute. */
218 	if (ni_load_mi(ni, le, &m))
219 		return NULL;
220 
221 	/* Look for required attribute. */
222 	attr = mi_find_attr(m, NULL, type, name, name_len, &le->id);
223 
224 	if (!attr)
225 		goto out;
226 
227 	if (!attr->non_res) {
228 		if (vcn && *vcn)
229 			goto out;
230 	} else if (!vcn) {
231 		if (attr->nres.svcn)
232 			goto out;
233 	} else if (le64_to_cpu(attr->nres.svcn) > *vcn ||
234 		   *vcn > le64_to_cpu(attr->nres.evcn)) {
235 		goto out;
236 	}
237 
238 	if (mi)
239 		*mi = m;
240 	return attr;
241 
242 out:
243 	_ntfs_bad_inode(&ni->vfs_inode);
244 	return NULL;
245 }
246 
247 /*
248  * ni_enum_attr_ex - Enumerates attributes in ntfs_inode.
249  */
ni_enum_attr_ex(struct ntfs_inode * ni,struct ATTRIB * attr,struct ATTR_LIST_ENTRY ** le,struct mft_inode ** mi)250 struct ATTRIB *ni_enum_attr_ex(struct ntfs_inode *ni, struct ATTRIB *attr,
251 			       struct ATTR_LIST_ENTRY **le,
252 			       struct mft_inode **mi)
253 {
254 	struct mft_inode *mi2;
255 	struct ATTR_LIST_ENTRY *le2;
256 
257 	/* Do we have an attribute list? */
258 	if (!ni->attr_list.size) {
259 		*le = NULL;
260 		if (mi)
261 			*mi = &ni->mi;
262 		/* Enum attributes in primary record. */
263 		return mi_enum_attr(&ni->mi, attr);
264 	}
265 
266 	/* Get next list entry. */
267 	le2 = *le = al_enumerate(ni, attr ? *le : NULL);
268 	if (!le2)
269 		return NULL;
270 
271 	/* Load record that contains the required attribute. */
272 	if (ni_load_mi(ni, le2, &mi2))
273 		return NULL;
274 
275 	if (mi)
276 		*mi = mi2;
277 
278 	/* Find attribute in loaded record. */
279 	return rec_find_attr_le(mi2, le2);
280 }
281 
282 /*
283  * ni_load_attr - Load attribute that contains given VCN.
284  */
ni_load_attr(struct ntfs_inode * ni,enum ATTR_TYPE type,const __le16 * name,u8 name_len,CLST vcn,struct mft_inode ** pmi)285 struct ATTRIB *ni_load_attr(struct ntfs_inode *ni, enum ATTR_TYPE type,
286 			    const __le16 *name, u8 name_len, CLST vcn,
287 			    struct mft_inode **pmi)
288 {
289 	struct ATTR_LIST_ENTRY *le;
290 	struct ATTRIB *attr;
291 	struct mft_inode *mi;
292 	struct ATTR_LIST_ENTRY *next;
293 
294 	if (!ni->attr_list.size) {
295 		if (pmi)
296 			*pmi = &ni->mi;
297 		return mi_find_attr(&ni->mi, NULL, type, name, name_len, NULL);
298 	}
299 
300 	le = al_find_ex(ni, NULL, type, name, name_len, NULL);
301 	if (!le)
302 		return NULL;
303 
304 	/*
305 	 * Unfortunately ATTR_LIST_ENTRY contains only start VCN.
306 	 * So to find the ATTRIB segment that contains 'vcn' we should
307 	 * enumerate some entries.
308 	 */
309 	if (vcn) {
310 		for (;; le = next) {
311 			next = al_find_ex(ni, le, type, name, name_len, NULL);
312 			if (!next || le64_to_cpu(next->vcn) > vcn)
313 				break;
314 		}
315 	}
316 
317 	if (ni_load_mi(ni, le, &mi))
318 		return NULL;
319 
320 	if (pmi)
321 		*pmi = mi;
322 
323 	attr = mi_find_attr(mi, NULL, type, name, name_len, &le->id);
324 	if (!attr)
325 		return NULL;
326 
327 	if (!attr->non_res)
328 		return attr;
329 
330 	if (le64_to_cpu(attr->nres.svcn) <= vcn &&
331 	    vcn <= le64_to_cpu(attr->nres.evcn))
332 		return attr;
333 
334 	_ntfs_bad_inode(&ni->vfs_inode);
335 	return NULL;
336 }
337 
338 /*
339  * ni_load_all_mi - Load all subrecords.
340  */
ni_load_all_mi(struct ntfs_inode * ni)341 int ni_load_all_mi(struct ntfs_inode *ni)
342 {
343 	int err;
344 	struct ATTR_LIST_ENTRY *le;
345 
346 	if (!ni->attr_list.size)
347 		return 0;
348 
349 	le = NULL;
350 
351 	while ((le = al_enumerate(ni, le))) {
352 		CLST rno = ino_get(&le->ref);
353 
354 		if (rno == ni->mi.rno)
355 			continue;
356 
357 		err = ni_load_mi_ex(ni, rno, NULL);
358 		if (err)
359 			return err;
360 	}
361 
362 	return 0;
363 }
364 
365 /*
366  * ni_add_subrecord - Allocate + format + attach a new subrecord.
367  */
ni_add_subrecord(struct ntfs_inode * ni,CLST rno,struct mft_inode ** mi)368 bool ni_add_subrecord(struct ntfs_inode *ni, CLST rno, struct mft_inode **mi)
369 {
370 	struct mft_inode *m;
371 
372 	m = kzalloc(sizeof(struct mft_inode), GFP_NOFS);
373 	if (!m)
374 		return false;
375 
376 	if (mi_format_new(m, ni->mi.sbi, rno, 0, ni->mi.rno == MFT_REC_MFT)) {
377 		mi_put(m);
378 		return false;
379 	}
380 
381 	mi_get_ref(&ni->mi, &m->mrec->parent_ref);
382 
383 	ni_add_mi(ni, m);
384 	*mi = m;
385 	return true;
386 }
387 
388 /*
389  * ni_remove_attr - Remove all attributes for the given type/name/id.
390  */
ni_remove_attr(struct ntfs_inode * ni,enum ATTR_TYPE type,const __le16 * name,u8 name_len,bool base_only,const __le16 * id)391 int ni_remove_attr(struct ntfs_inode *ni, enum ATTR_TYPE type,
392 		   const __le16 *name, u8 name_len, bool base_only,
393 		   const __le16 *id)
394 {
395 	int err;
396 	struct ATTRIB *attr;
397 	struct ATTR_LIST_ENTRY *le;
398 	struct mft_inode *mi;
399 	u32 type_in;
400 	int diff;
401 
402 	if (base_only || type == ATTR_LIST || !ni->attr_list.size) {
403 		attr = mi_find_attr(&ni->mi, NULL, type, name, name_len, id);
404 		if (!attr)
405 			return -ENOENT;
406 
407 		mi_remove_attr(ni, &ni->mi, attr);
408 		return 0;
409 	}
410 
411 	type_in = le32_to_cpu(type);
412 	le = NULL;
413 
414 	for (;;) {
415 		le = al_enumerate(ni, le);
416 		if (!le)
417 			return 0;
418 
419 next_le2:
420 		diff = le32_to_cpu(le->type) - type_in;
421 		if (diff < 0)
422 			continue;
423 
424 		if (diff > 0)
425 			return 0;
426 
427 		if (le->name_len != name_len)
428 			continue;
429 
430 		if (name_len &&
431 		    memcmp(le_name(le), name, name_len * sizeof(short)))
432 			continue;
433 
434 		if (id && le->id != *id)
435 			continue;
436 		err = ni_load_mi(ni, le, &mi);
437 		if (err)
438 			return err;
439 
440 		al_remove_le(ni, le);
441 
442 		attr = mi_find_attr(mi, NULL, type, name, name_len, id);
443 		if (!attr)
444 			return -ENOENT;
445 
446 		mi_remove_attr(ni, mi, attr);
447 
448 		if (PtrOffset(ni->attr_list.le, le) >= ni->attr_list.size)
449 			return 0;
450 		goto next_le2;
451 	}
452 }
453 
454 /*
455  * ni_ins_new_attr - Insert the attribute into record.
456  *
457  * Return: Not full constructed attribute or NULL if not possible to create.
458  */
459 static struct ATTRIB *
ni_ins_new_attr(struct ntfs_inode * ni,struct mft_inode * mi,struct ATTR_LIST_ENTRY * le,enum ATTR_TYPE type,const __le16 * name,u8 name_len,u32 asize,u16 name_off,CLST svcn,struct ATTR_LIST_ENTRY ** ins_le)460 ni_ins_new_attr(struct ntfs_inode *ni, struct mft_inode *mi,
461 		struct ATTR_LIST_ENTRY *le, enum ATTR_TYPE type,
462 		const __le16 *name, u8 name_len, u32 asize, u16 name_off,
463 		CLST svcn, struct ATTR_LIST_ENTRY **ins_le)
464 {
465 	int err;
466 	struct ATTRIB *attr;
467 	bool le_added = false;
468 	struct MFT_REF ref;
469 
470 	mi_get_ref(mi, &ref);
471 
472 	if (type != ATTR_LIST && !le && ni->attr_list.size) {
473 		err = al_add_le(ni, type, name, name_len, svcn, cpu_to_le16(-1),
474 				&ref, &le);
475 		if (err) {
476 			/* No memory or no space. */
477 			return ERR_PTR(err);
478 		}
479 		le_added = true;
480 
481 		/*
482 		 * al_add_le -> attr_set_size (list) -> ni_expand_list
483 		 * which moves some attributes out of primary record
484 		 * this means that name may point into moved memory
485 		 * reinit 'name' from le.
486 		 */
487 		name = le->name;
488 	}
489 
490 	attr = mi_insert_attr(mi, type, name, name_len, asize, name_off);
491 	if (!attr) {
492 		if (le_added)
493 			al_remove_le(ni, le);
494 		return NULL;
495 	}
496 
497 	if (type == ATTR_LIST) {
498 		/* Attr list is not in list entry array. */
499 		goto out;
500 	}
501 
502 	if (!le)
503 		goto out;
504 
505 	/* Update ATTRIB Id and record reference. */
506 	le->id = attr->id;
507 	ni->attr_list.dirty = true;
508 	le->ref = ref;
509 
510 out:
511 	if (ins_le)
512 		*ins_le = le;
513 	return attr;
514 }
515 
516 /*
517  * ni_repack
518  *
519  * Random write access to sparsed or compressed file may result to
520  * not optimized packed runs.
521  * Here is the place to optimize it.
522  */
ni_repack(struct ntfs_inode * ni)523 static int ni_repack(struct ntfs_inode *ni)
524 {
525 #if 1
526 	return 0;
527 #else
528 	int err = 0;
529 	struct ntfs_sb_info *sbi = ni->mi.sbi;
530 	struct mft_inode *mi, *mi_p = NULL;
531 	struct ATTRIB *attr = NULL, *attr_p;
532 	struct ATTR_LIST_ENTRY *le = NULL, *le_p;
533 	CLST alloc = 0;
534 	u8 cluster_bits = sbi->cluster_bits;
535 	CLST svcn, evcn = 0, svcn_p, evcn_p, next_svcn;
536 	u32 roff, rs = sbi->record_size;
537 	struct runs_tree run;
538 
539 	run_init(&run);
540 
541 	while ((attr = ni_enum_attr_ex(ni, attr, &le, &mi))) {
542 		if (!attr->non_res)
543 			continue;
544 
545 		svcn = le64_to_cpu(attr->nres.svcn);
546 		if (svcn != le64_to_cpu(le->vcn)) {
547 			err = -EINVAL;
548 			break;
549 		}
550 
551 		if (!svcn) {
552 			alloc = le64_to_cpu(attr->nres.alloc_size) >>
553 				cluster_bits;
554 			mi_p = NULL;
555 		} else if (svcn != evcn + 1) {
556 			err = -EINVAL;
557 			break;
558 		}
559 
560 		evcn = le64_to_cpu(attr->nres.evcn);
561 
562 		if (svcn > evcn + 1) {
563 			err = -EINVAL;
564 			break;
565 		}
566 
567 		if (!mi_p) {
568 			/* Do not try if not enough free space. */
569 			if (le32_to_cpu(mi->mrec->used) + 8 >= rs)
570 				continue;
571 
572 			/* Do not try if last attribute segment. */
573 			if (evcn + 1 == alloc)
574 				continue;
575 			run_close(&run);
576 		}
577 
578 		roff = le16_to_cpu(attr->nres.run_off);
579 
580 		if (roff > le32_to_cpu(attr->size)) {
581 			err = -EINVAL;
582 			break;
583 		}
584 
585 		err = run_unpack(&run, sbi, ni->mi.rno, svcn, evcn, svcn,
586 				 Add2Ptr(attr, roff),
587 				 le32_to_cpu(attr->size) - roff);
588 		if (err < 0)
589 			break;
590 
591 		if (!mi_p) {
592 			mi_p = mi;
593 			attr_p = attr;
594 			svcn_p = svcn;
595 			evcn_p = evcn;
596 			le_p = le;
597 			err = 0;
598 			continue;
599 		}
600 
601 		/*
602 		 * Run contains data from two records: mi_p and mi
603 		 * Try to pack in one.
604 		 */
605 		err = mi_pack_runs(mi_p, attr_p, &run, evcn + 1 - svcn_p);
606 		if (err)
607 			break;
608 
609 		next_svcn = le64_to_cpu(attr_p->nres.evcn) + 1;
610 
611 		if (next_svcn >= evcn + 1) {
612 			/* We can remove this attribute segment. */
613 			al_remove_le(ni, le);
614 			mi_remove_attr(NULL, mi, attr);
615 			le = le_p;
616 			continue;
617 		}
618 
619 		attr->nres.svcn = le->vcn = cpu_to_le64(next_svcn);
620 		mi->dirty = true;
621 		ni->attr_list.dirty = true;
622 
623 		if (evcn + 1 == alloc) {
624 			err = mi_pack_runs(mi, attr, &run,
625 					   evcn + 1 - next_svcn);
626 			if (err)
627 				break;
628 			mi_p = NULL;
629 		} else {
630 			mi_p = mi;
631 			attr_p = attr;
632 			svcn_p = next_svcn;
633 			evcn_p = evcn;
634 			le_p = le;
635 			run_truncate_head(&run, next_svcn);
636 		}
637 	}
638 
639 	if (err) {
640 		ntfs_inode_warn(&ni->vfs_inode, "repack problem");
641 		ntfs_set_state(sbi, NTFS_DIRTY_ERROR);
642 
643 		/* Pack loaded but not packed runs. */
644 		if (mi_p)
645 			mi_pack_runs(mi_p, attr_p, &run, evcn_p + 1 - svcn_p);
646 	}
647 
648 	run_close(&run);
649 	return err;
650 #endif
651 }
652 
653 /*
654  * ni_try_remove_attr_list
655  *
656  * Can we remove attribute list?
657  * Check the case when primary record contains enough space for all attributes.
658  */
ni_try_remove_attr_list(struct ntfs_inode * ni)659 static int ni_try_remove_attr_list(struct ntfs_inode *ni)
660 {
661 	int err = 0;
662 	struct ntfs_sb_info *sbi = ni->mi.sbi;
663 	struct ATTRIB *attr, *attr_list, *attr_ins;
664 	struct ATTR_LIST_ENTRY *le;
665 	struct mft_inode *mi;
666 	u32 asize, free;
667 	struct MFT_REF ref;
668 	struct MFT_REC *mrec;
669 	__le16 id;
670 
671 	if (!ni->attr_list.dirty)
672 		return 0;
673 
674 	err = ni_repack(ni);
675 	if (err)
676 		return err;
677 
678 	attr_list = mi_find_attr(&ni->mi, NULL, ATTR_LIST, NULL, 0, NULL);
679 	if (!attr_list)
680 		return 0;
681 
682 	asize = le32_to_cpu(attr_list->size);
683 
684 	/* Free space in primary record without attribute list. */
685 	free = sbi->record_size - le32_to_cpu(ni->mi.mrec->used) + asize;
686 	mi_get_ref(&ni->mi, &ref);
687 
688 	le = NULL;
689 	while ((le = al_enumerate(ni, le))) {
690 		if (!memcmp(&le->ref, &ref, sizeof(ref)))
691 			continue;
692 
693 		if (le->vcn)
694 			return 0;
695 
696 		mi = ni_find_mi(ni, ino_get(&le->ref));
697 		if (!mi)
698 			return 0;
699 
700 		attr = mi_find_attr(mi, NULL, le->type, le_name(le),
701 				    le->name_len, &le->id);
702 		if (!attr)
703 			return 0;
704 
705 		asize = le32_to_cpu(attr->size);
706 		if (asize > free)
707 			return 0;
708 
709 		free -= asize;
710 	}
711 
712 	/* Make a copy of primary record to restore if error. */
713 	mrec = kmemdup(ni->mi.mrec, sbi->record_size, GFP_NOFS);
714 	if (!mrec)
715 		return 0; /* Not critical. */
716 
717 	/* It seems that attribute list can be removed from primary record. */
718 	mi_remove_attr(NULL, &ni->mi, attr_list);
719 
720 	/*
721 	 * Repeat the cycle above and copy all attributes to primary record.
722 	 * Do not remove original attributes from subrecords!
723 	 * It should be success!
724 	 */
725 	le = NULL;
726 	while ((le = al_enumerate(ni, le))) {
727 		if (!memcmp(&le->ref, &ref, sizeof(ref)))
728 			continue;
729 
730 		mi = ni_find_mi(ni, ino_get(&le->ref));
731 		if (!mi) {
732 			/* Should never happened, 'cause already checked. */
733 			goto out;
734 		}
735 
736 		attr = mi_find_attr(mi, NULL, le->type, le_name(le),
737 				    le->name_len, &le->id);
738 		if (!attr) {
739 			/* Should never happened, 'cause already checked. */
740 			goto out;
741 		}
742 		asize = le32_to_cpu(attr->size);
743 
744 		/* Insert into primary record. */
745 		attr_ins = mi_insert_attr(&ni->mi, le->type, le_name(le),
746 					  le->name_len, asize,
747 					  le16_to_cpu(attr->name_off));
748 		if (!attr_ins) {
749 			/*
750 			 * No space in primary record (already checked).
751 			 */
752 			goto out;
753 		}
754 
755 		/* Copy all except id. */
756 		id = attr_ins->id;
757 		memcpy(attr_ins, attr, asize);
758 		attr_ins->id = id;
759 	}
760 
761 	/*
762 	 * Repeat the cycle above and remove all attributes from subrecords.
763 	 */
764 	le = NULL;
765 	while ((le = al_enumerate(ni, le))) {
766 		if (!memcmp(&le->ref, &ref, sizeof(ref)))
767 			continue;
768 
769 		mi = ni_find_mi(ni, ino_get(&le->ref));
770 		if (!mi)
771 			continue;
772 
773 		attr = mi_find_attr(mi, NULL, le->type, le_name(le),
774 				    le->name_len, &le->id);
775 		if (!attr)
776 			continue;
777 
778 		/* Remove from original record. */
779 		mi_remove_attr(NULL, mi, attr);
780 	}
781 
782 	run_deallocate(sbi, &ni->attr_list.run, true);
783 	run_close(&ni->attr_list.run);
784 	ni->attr_list.size = 0;
785 	kvfree(ni->attr_list.le);
786 	ni->attr_list.le = NULL;
787 	ni->attr_list.dirty = false;
788 
789 	kfree(mrec);
790 	return 0;
791 out:
792 	/* Restore primary record. */
793 	swap(mrec, ni->mi.mrec);
794 	kfree(mrec);
795 	return 0;
796 }
797 
798 /*
799  * ni_create_attr_list - Generates an attribute list for this primary record.
800  */
ni_create_attr_list(struct ntfs_inode * ni)801 int ni_create_attr_list(struct ntfs_inode *ni)
802 {
803 	struct ntfs_sb_info *sbi = ni->mi.sbi;
804 	int err;
805 	u32 lsize;
806 	struct ATTRIB *attr;
807 	struct ATTRIB *arr_move[7];
808 	struct ATTR_LIST_ENTRY *le, *le_b[7];
809 	struct MFT_REC *rec;
810 	bool is_mft;
811 	CLST rno = 0;
812 	struct mft_inode *mi;
813 	u32 free_b, nb, to_free, rs;
814 	u16 sz;
815 
816 	is_mft = ni->mi.rno == MFT_REC_MFT;
817 	rec = ni->mi.mrec;
818 	rs = sbi->record_size;
819 
820 	/*
821 	 * Skip estimating exact memory requirement.
822 	 * Looks like one record_size is always enough.
823 	 */
824 	le = kmalloc(al_aligned(rs), GFP_NOFS);
825 	if (!le)
826 		return -ENOMEM;
827 
828 	mi_get_ref(&ni->mi, &le->ref);
829 	ni->attr_list.le = le;
830 
831 	attr = NULL;
832 	nb = 0;
833 	free_b = 0;
834 	attr = NULL;
835 
836 	for (; (attr = mi_enum_attr(&ni->mi, attr)); le = Add2Ptr(le, sz)) {
837 		sz = le_size(attr->name_len);
838 		le->type = attr->type;
839 		le->size = cpu_to_le16(sz);
840 		le->name_len = attr->name_len;
841 		le->name_off = offsetof(struct ATTR_LIST_ENTRY, name);
842 		le->vcn = 0;
843 		if (le != ni->attr_list.le)
844 			le->ref = ni->attr_list.le->ref;
845 		le->id = attr->id;
846 
847 		if (attr->name_len)
848 			memcpy(le->name, attr_name(attr),
849 			       sizeof(short) * attr->name_len);
850 		else if (attr->type == ATTR_STD)
851 			continue;
852 		else if (attr->type == ATTR_LIST)
853 			continue;
854 		else if (is_mft && attr->type == ATTR_DATA)
855 			continue;
856 
857 		if (!nb || nb < ARRAY_SIZE(arr_move)) {
858 			le_b[nb] = le;
859 			arr_move[nb++] = attr;
860 			free_b += le32_to_cpu(attr->size);
861 		}
862 	}
863 
864 	lsize = PtrOffset(ni->attr_list.le, le);
865 	ni->attr_list.size = lsize;
866 
867 	to_free = le32_to_cpu(rec->used) + lsize + SIZEOF_RESIDENT;
868 	if (to_free <= rs) {
869 		to_free = 0;
870 	} else {
871 		to_free -= rs;
872 
873 		if (to_free > free_b) {
874 			err = -EINVAL;
875 			goto out;
876 		}
877 	}
878 
879 	/* Allocate child MFT. */
880 	err = ntfs_look_free_mft(sbi, &rno, is_mft, ni, &mi);
881 	if (err)
882 		goto out;
883 
884 	err = -EINVAL;
885 	/* Call mi_remove_attr() in reverse order to keep pointers 'arr_move' valid. */
886 	while (to_free > 0) {
887 		struct ATTRIB *b = arr_move[--nb];
888 		u32 asize = le32_to_cpu(b->size);
889 		u16 name_off = le16_to_cpu(b->name_off);
890 
891 		attr = mi_insert_attr(mi, b->type, Add2Ptr(b, name_off),
892 				      b->name_len, asize, name_off);
893 		if (!attr)
894 			goto out;
895 
896 		mi_get_ref(mi, &le_b[nb]->ref);
897 		le_b[nb]->id = attr->id;
898 
899 		/* Copy all except id. */
900 		memcpy(attr, b, asize);
901 		attr->id = le_b[nb]->id;
902 
903 		/* Remove from primary record. */
904 		if (!mi_remove_attr(NULL, &ni->mi, b))
905 			goto out;
906 
907 		if (to_free <= asize)
908 			break;
909 		to_free -= asize;
910 		if (!nb)
911 			goto out;
912 	}
913 
914 	attr = mi_insert_attr(&ni->mi, ATTR_LIST, NULL, 0,
915 			      lsize + SIZEOF_RESIDENT, SIZEOF_RESIDENT);
916 	if (!attr)
917 		goto out;
918 
919 	attr->non_res = 0;
920 	attr->flags = 0;
921 	attr->res.data_size = cpu_to_le32(lsize);
922 	attr->res.data_off = SIZEOF_RESIDENT_LE;
923 	attr->res.flags = 0;
924 	attr->res.res = 0;
925 
926 	memcpy(resident_data_ex(attr, lsize), ni->attr_list.le, lsize);
927 
928 	ni->attr_list.dirty = false;
929 
930 	mark_inode_dirty(&ni->vfs_inode);
931 	return 0;
932 
933 out:
934 	kvfree(ni->attr_list.le);
935 	ni->attr_list.le = NULL;
936 	ni->attr_list.size = 0;
937 	return err;
938 }
939 
940 /*
941  * ni_ins_attr_ext - Add an external attribute to the ntfs_inode.
942  */
ni_ins_attr_ext(struct ntfs_inode * ni,struct ATTR_LIST_ENTRY * le,enum ATTR_TYPE type,const __le16 * name,u8 name_len,u32 asize,CLST svcn,u16 name_off,bool force_ext,struct ATTRIB ** ins_attr,struct mft_inode ** ins_mi,struct ATTR_LIST_ENTRY ** ins_le)943 static int ni_ins_attr_ext(struct ntfs_inode *ni, struct ATTR_LIST_ENTRY *le,
944 			   enum ATTR_TYPE type, const __le16 *name, u8 name_len,
945 			   u32 asize, CLST svcn, u16 name_off, bool force_ext,
946 			   struct ATTRIB **ins_attr, struct mft_inode **ins_mi,
947 			   struct ATTR_LIST_ENTRY **ins_le)
948 {
949 	struct ATTRIB *attr;
950 	struct mft_inode *mi;
951 	CLST rno;
952 	u64 vbo;
953 	struct rb_node *node;
954 	int err;
955 	bool is_mft, is_mft_data;
956 	struct ntfs_sb_info *sbi = ni->mi.sbi;
957 
958 	is_mft = ni->mi.rno == MFT_REC_MFT;
959 	is_mft_data = is_mft && type == ATTR_DATA && !name_len;
960 
961 	if (asize > sbi->max_bytes_per_attr) {
962 		err = -EINVAL;
963 		goto out;
964 	}
965 
966 	/*
967 	 * Standard information and attr_list cannot be made external.
968 	 * The Log File cannot have any external attributes.
969 	 */
970 	if (type == ATTR_STD || type == ATTR_LIST ||
971 	    ni->mi.rno == MFT_REC_LOG) {
972 		err = -EINVAL;
973 		goto out;
974 	}
975 
976 	/* Create attribute list if it is not already existed. */
977 	if (!ni->attr_list.size) {
978 		err = ni_create_attr_list(ni);
979 		if (err)
980 			goto out;
981 	}
982 
983 	vbo = is_mft_data ? ((u64)svcn << sbi->cluster_bits) : 0;
984 
985 	if (force_ext)
986 		goto insert_ext;
987 
988 	/* Load all subrecords into memory. */
989 	err = ni_load_all_mi(ni);
990 	if (err)
991 		goto out;
992 
993 	/* Check each of loaded subrecord. */
994 	for (node = rb_first(&ni->mi_tree); node; node = rb_next(node)) {
995 		mi = rb_entry(node, struct mft_inode, node);
996 
997 		if (is_mft_data &&
998 		    (mi_enum_attr(mi, NULL) ||
999 		     vbo <= ((u64)mi->rno << sbi->record_bits))) {
1000 			/* We can't accept this record 'cause MFT's bootstrapping. */
1001 			continue;
1002 		}
1003 		if (is_mft &&
1004 		    mi_find_attr(mi, NULL, ATTR_DATA, NULL, 0, NULL)) {
1005 			/*
1006 			 * This child record already has a ATTR_DATA.
1007 			 * So it can't accept any other records.
1008 			 */
1009 			continue;
1010 		}
1011 
1012 		if ((type != ATTR_NAME || name_len) &&
1013 		    mi_find_attr(mi, NULL, type, name, name_len, NULL)) {
1014 			/* Only indexed attributes can share same record. */
1015 			continue;
1016 		}
1017 
1018 		/*
1019 		 * Do not try to insert this attribute
1020 		 * if there is no room in record.
1021 		 */
1022 		if (le32_to_cpu(mi->mrec->used) + asize > sbi->record_size)
1023 			continue;
1024 
1025 		/* Try to insert attribute into this subrecord. */
1026 		attr = ni_ins_new_attr(ni, mi, le, type, name, name_len, asize,
1027 				       name_off, svcn, ins_le);
1028 		if (!attr)
1029 			continue;
1030 		if (IS_ERR(attr))
1031 			return PTR_ERR(attr);
1032 
1033 		if (ins_attr)
1034 			*ins_attr = attr;
1035 		if (ins_mi)
1036 			*ins_mi = mi;
1037 		return 0;
1038 	}
1039 
1040 insert_ext:
1041 	/* We have to allocate a new child subrecord. */
1042 	err = ntfs_look_free_mft(sbi, &rno, is_mft_data, ni, &mi);
1043 	if (err)
1044 		goto out;
1045 
1046 	if (is_mft_data && vbo <= ((u64)rno << sbi->record_bits)) {
1047 		err = -EINVAL;
1048 		goto out1;
1049 	}
1050 
1051 	attr = ni_ins_new_attr(ni, mi, le, type, name, name_len, asize,
1052 			       name_off, svcn, ins_le);
1053 	if (!attr) {
1054 		err = -EINVAL;
1055 		goto out2;
1056 	}
1057 
1058 	if (IS_ERR(attr)) {
1059 		err = PTR_ERR(attr);
1060 		goto out2;
1061 	}
1062 
1063 	if (ins_attr)
1064 		*ins_attr = attr;
1065 	if (ins_mi)
1066 		*ins_mi = mi;
1067 
1068 	return 0;
1069 
1070 out2:
1071 	ni_remove_mi(ni, mi);
1072 	mi_put(mi);
1073 
1074 out1:
1075 	ntfs_mark_rec_free(sbi, rno, is_mft);
1076 
1077 out:
1078 	return err;
1079 }
1080 
1081 /*
1082  * ni_insert_attr - Insert an attribute into the file.
1083  *
1084  * If the primary record has room, it will just insert the attribute.
1085  * If not, it may make the attribute external.
1086  * For $MFT::Data it may make room for the attribute by
1087  * making other attributes external.
1088  *
1089  * NOTE:
1090  * The ATTR_LIST and ATTR_STD cannot be made external.
1091  * This function does not fill new attribute full.
1092  * It only fills 'size'/'type'/'id'/'name_len' fields.
1093  */
ni_insert_attr(struct ntfs_inode * ni,enum ATTR_TYPE type,const __le16 * name,u8 name_len,u32 asize,u16 name_off,CLST svcn,struct ATTRIB ** ins_attr,struct mft_inode ** ins_mi,struct ATTR_LIST_ENTRY ** ins_le)1094 static int ni_insert_attr(struct ntfs_inode *ni, enum ATTR_TYPE type,
1095 			  const __le16 *name, u8 name_len, u32 asize,
1096 			  u16 name_off, CLST svcn, struct ATTRIB **ins_attr,
1097 			  struct mft_inode **ins_mi,
1098 			  struct ATTR_LIST_ENTRY **ins_le)
1099 {
1100 	struct ntfs_sb_info *sbi = ni->mi.sbi;
1101 	int err;
1102 	struct ATTRIB *attr, *eattr;
1103 	struct MFT_REC *rec;
1104 	bool is_mft;
1105 	struct ATTR_LIST_ENTRY *le;
1106 	u32 list_reserve, max_free, free, used, t32;
1107 	__le16 id;
1108 	u16 t16;
1109 
1110 	is_mft = ni->mi.rno == MFT_REC_MFT;
1111 	rec = ni->mi.mrec;
1112 
1113 	list_reserve = SIZEOF_NONRESIDENT + 3 * (1 + 2 * sizeof(u32));
1114 	used = le32_to_cpu(rec->used);
1115 	free = sbi->record_size - used;
1116 
1117 	if (is_mft && type != ATTR_LIST) {
1118 		/* Reserve space for the ATTRIB list. */
1119 		if (free < list_reserve)
1120 			free = 0;
1121 		else
1122 			free -= list_reserve;
1123 	}
1124 
1125 	if (asize <= free) {
1126 		attr = ni_ins_new_attr(ni, &ni->mi, NULL, type, name, name_len,
1127 				       asize, name_off, svcn, ins_le);
1128 		if (IS_ERR(attr)) {
1129 			err = PTR_ERR(attr);
1130 			goto out;
1131 		}
1132 
1133 		if (attr) {
1134 			if (ins_attr)
1135 				*ins_attr = attr;
1136 			if (ins_mi)
1137 				*ins_mi = &ni->mi;
1138 			err = 0;
1139 			goto out;
1140 		}
1141 	}
1142 
1143 	if (!is_mft || type != ATTR_DATA || svcn) {
1144 		/* This ATTRIB will be external. */
1145 		err = ni_ins_attr_ext(ni, NULL, type, name, name_len, asize,
1146 				      svcn, name_off, false, ins_attr, ins_mi,
1147 				      ins_le);
1148 		goto out;
1149 	}
1150 
1151 	/*
1152 	 * Here we have: "is_mft && type == ATTR_DATA && !svcn"
1153 	 *
1154 	 * The first chunk of the $MFT::Data ATTRIB must be the base record.
1155 	 * Evict as many other attributes as possible.
1156 	 */
1157 	max_free = free;
1158 
1159 	/* Estimate the result of moving all possible attributes away. */
1160 	attr = NULL;
1161 
1162 	while ((attr = mi_enum_attr(&ni->mi, attr))) {
1163 		if (attr->type == ATTR_STD)
1164 			continue;
1165 		if (attr->type == ATTR_LIST)
1166 			continue;
1167 		max_free += le32_to_cpu(attr->size);
1168 	}
1169 
1170 	if (max_free < asize + list_reserve) {
1171 		/* Impossible to insert this attribute into primary record. */
1172 		err = -EINVAL;
1173 		goto out;
1174 	}
1175 
1176 	/* Start real attribute moving. */
1177 	attr = NULL;
1178 
1179 	for (;;) {
1180 		attr = mi_enum_attr(&ni->mi, attr);
1181 		if (!attr) {
1182 			/* We should never be here 'cause we have already check this case. */
1183 			err = -EINVAL;
1184 			goto out;
1185 		}
1186 
1187 		/* Skip attributes that MUST be primary record. */
1188 		if (attr->type == ATTR_STD || attr->type == ATTR_LIST)
1189 			continue;
1190 
1191 		le = NULL;
1192 		if (ni->attr_list.size) {
1193 			le = al_find_le(ni, NULL, attr);
1194 			if (!le) {
1195 				/* Really this is a serious bug. */
1196 				err = -EINVAL;
1197 				goto out;
1198 			}
1199 		}
1200 
1201 		t32 = le32_to_cpu(attr->size);
1202 		t16 = le16_to_cpu(attr->name_off);
1203 		err = ni_ins_attr_ext(ni, le, attr->type, Add2Ptr(attr, t16),
1204 				      attr->name_len, t32, attr_svcn(attr), t16,
1205 				      false, &eattr, NULL, NULL);
1206 		if (err)
1207 			return err;
1208 
1209 		id = eattr->id;
1210 		memcpy(eattr, attr, t32);
1211 		eattr->id = id;
1212 
1213 		/* Remove from primary record. */
1214 		mi_remove_attr(NULL, &ni->mi, attr);
1215 
1216 		/* attr now points to next attribute. */
1217 		if (attr->type == ATTR_END)
1218 			goto out;
1219 	}
1220 	while (asize + list_reserve > sbi->record_size - le32_to_cpu(rec->used))
1221 		;
1222 
1223 	attr = ni_ins_new_attr(ni, &ni->mi, NULL, type, name, name_len, asize,
1224 			       name_off, svcn, ins_le);
1225 	if (!attr) {
1226 		err = -EINVAL;
1227 		goto out;
1228 	}
1229 
1230 	if (IS_ERR(attr)) {
1231 		err = PTR_ERR(attr);
1232 		goto out;
1233 	}
1234 
1235 	if (ins_attr)
1236 		*ins_attr = attr;
1237 	if (ins_mi)
1238 		*ins_mi = &ni->mi;
1239 
1240 out:
1241 	return err;
1242 }
1243 
1244 /* ni_expand_mft_list - Split ATTR_DATA of $MFT. */
ni_expand_mft_list(struct ntfs_inode * ni)1245 static int ni_expand_mft_list(struct ntfs_inode *ni)
1246 {
1247 	int err = 0;
1248 	struct runs_tree *run = &ni->file.run;
1249 	u32 asize, run_size, done = 0;
1250 	struct ATTRIB *attr;
1251 	struct rb_node *node;
1252 	CLST mft_min, mft_new, svcn, evcn, plen;
1253 	struct mft_inode *mi, *mi_min, *mi_new;
1254 	struct ntfs_sb_info *sbi = ni->mi.sbi;
1255 
1256 	/* Find the nearest MFT. */
1257 	mft_min = 0;
1258 	mft_new = 0;
1259 	mi_min = NULL;
1260 
1261 	for (node = rb_first(&ni->mi_tree); node; node = rb_next(node)) {
1262 		mi = rb_entry(node, struct mft_inode, node);
1263 
1264 		attr = mi_enum_attr(mi, NULL);
1265 
1266 		if (!attr) {
1267 			mft_min = mi->rno;
1268 			mi_min = mi;
1269 			break;
1270 		}
1271 	}
1272 
1273 	if (ntfs_look_free_mft(sbi, &mft_new, true, ni, &mi_new)) {
1274 		mft_new = 0;
1275 		/* Really this is not critical. */
1276 	} else if (mft_min > mft_new) {
1277 		mft_min = mft_new;
1278 		mi_min = mi_new;
1279 	} else {
1280 		ntfs_mark_rec_free(sbi, mft_new, true);
1281 		mft_new = 0;
1282 		ni_remove_mi(ni, mi_new);
1283 	}
1284 
1285 	attr = mi_find_attr(&ni->mi, NULL, ATTR_DATA, NULL, 0, NULL);
1286 	if (!attr) {
1287 		err = -EINVAL;
1288 		goto out;
1289 	}
1290 
1291 	asize = le32_to_cpu(attr->size);
1292 
1293 	evcn = le64_to_cpu(attr->nres.evcn);
1294 	svcn = bytes_to_cluster(sbi, (u64)(mft_min + 1) << sbi->record_bits);
1295 	if (evcn + 1 >= svcn) {
1296 		err = -EINVAL;
1297 		goto out;
1298 	}
1299 
1300 	/*
1301 	 * Split primary attribute [0 evcn] in two parts [0 svcn) + [svcn evcn].
1302 	 *
1303 	 * Update first part of ATTR_DATA in 'primary MFT.
1304 	 */
1305 	err = run_pack(run, 0, svcn, Add2Ptr(attr, SIZEOF_NONRESIDENT),
1306 		       asize - SIZEOF_NONRESIDENT, &plen);
1307 	if (err < 0)
1308 		goto out;
1309 
1310 	run_size = ALIGN(err, 8);
1311 	err = 0;
1312 
1313 	if (plen < svcn) {
1314 		err = -EINVAL;
1315 		goto out;
1316 	}
1317 
1318 	attr->nres.evcn = cpu_to_le64(svcn - 1);
1319 	attr->size = cpu_to_le32(run_size + SIZEOF_NONRESIDENT);
1320 	/* 'done' - How many bytes of primary MFT becomes free. */
1321 	done = asize - run_size - SIZEOF_NONRESIDENT;
1322 	le32_sub_cpu(&ni->mi.mrec->used, done);
1323 
1324 	/* Estimate packed size (run_buf=NULL). */
1325 	err = run_pack(run, svcn, evcn + 1 - svcn, NULL, sbi->record_size,
1326 		       &plen);
1327 	if (err < 0)
1328 		goto out;
1329 
1330 	run_size = ALIGN(err, 8);
1331 	err = 0;
1332 
1333 	if (plen < evcn + 1 - svcn) {
1334 		err = -EINVAL;
1335 		goto out;
1336 	}
1337 
1338 	/*
1339 	 * This function may implicitly call expand attr_list.
1340 	 * Insert second part of ATTR_DATA in 'mi_min'.
1341 	 */
1342 	attr = ni_ins_new_attr(ni, mi_min, NULL, ATTR_DATA, NULL, 0,
1343 			       SIZEOF_NONRESIDENT + run_size,
1344 			       SIZEOF_NONRESIDENT, svcn, NULL);
1345 	if (!attr) {
1346 		err = -EINVAL;
1347 		goto out;
1348 	}
1349 
1350 	if (IS_ERR(attr)) {
1351 		err = PTR_ERR(attr);
1352 		goto out;
1353 	}
1354 
1355 	attr->non_res = 1;
1356 	attr->name_off = SIZEOF_NONRESIDENT_LE;
1357 	attr->flags = 0;
1358 
1359 	/* This function can't fail - cause already checked above. */
1360 	run_pack(run, svcn, evcn + 1 - svcn, Add2Ptr(attr, SIZEOF_NONRESIDENT),
1361 		 run_size, &plen);
1362 
1363 	attr->nres.svcn = cpu_to_le64(svcn);
1364 	attr->nres.evcn = cpu_to_le64(evcn);
1365 	attr->nres.run_off = cpu_to_le16(SIZEOF_NONRESIDENT);
1366 
1367 out:
1368 	if (mft_new) {
1369 		ntfs_mark_rec_free(sbi, mft_new, true);
1370 		ni_remove_mi(ni, mi_new);
1371 	}
1372 
1373 	return !err && !done ? -EOPNOTSUPP : err;
1374 }
1375 
1376 /*
1377  * ni_expand_list - Move all possible attributes out of primary record.
1378  */
ni_expand_list(struct ntfs_inode * ni)1379 int ni_expand_list(struct ntfs_inode *ni)
1380 {
1381 	int err = 0;
1382 	u32 asize, done = 0;
1383 	struct ATTRIB *attr, *ins_attr;
1384 	struct ATTR_LIST_ENTRY *le;
1385 	bool is_mft = ni->mi.rno == MFT_REC_MFT;
1386 	struct MFT_REF ref;
1387 
1388 	mi_get_ref(&ni->mi, &ref);
1389 	le = NULL;
1390 
1391 	while ((le = al_enumerate(ni, le))) {
1392 		if (le->type == ATTR_STD)
1393 			continue;
1394 
1395 		if (memcmp(&ref, &le->ref, sizeof(struct MFT_REF)))
1396 			continue;
1397 
1398 		if (is_mft && le->type == ATTR_DATA)
1399 			continue;
1400 
1401 		/* Find attribute in primary record. */
1402 		attr = rec_find_attr_le(&ni->mi, le);
1403 		if (!attr) {
1404 			err = -EINVAL;
1405 			goto out;
1406 		}
1407 
1408 		asize = le32_to_cpu(attr->size);
1409 
1410 		/* Always insert into new record to avoid collisions (deep recursive). */
1411 		err = ni_ins_attr_ext(ni, le, attr->type, attr_name(attr),
1412 				      attr->name_len, asize, attr_svcn(attr),
1413 				      le16_to_cpu(attr->name_off), true,
1414 				      &ins_attr, NULL, NULL);
1415 
1416 		if (err)
1417 			goto out;
1418 
1419 		memcpy(ins_attr, attr, asize);
1420 		ins_attr->id = le->id;
1421 		/* Remove from primary record. */
1422 		mi_remove_attr(NULL, &ni->mi, attr);
1423 
1424 		done += asize;
1425 		goto out;
1426 	}
1427 
1428 	if (!is_mft) {
1429 		err = -EFBIG; /* Attr list is too big(?) */
1430 		goto out;
1431 	}
1432 
1433 	/* Split MFT data as much as possible. */
1434 	err = ni_expand_mft_list(ni);
1435 
1436 out:
1437 	return !err && !done ? -EOPNOTSUPP : err;
1438 }
1439 
1440 /*
1441  * ni_insert_nonresident - Insert new nonresident attribute.
1442  */
ni_insert_nonresident(struct ntfs_inode * ni,enum ATTR_TYPE type,const __le16 * name,u8 name_len,const struct runs_tree * run,CLST svcn,CLST len,__le16 flags,struct ATTRIB ** new_attr,struct mft_inode ** mi,struct ATTR_LIST_ENTRY ** le)1443 int ni_insert_nonresident(struct ntfs_inode *ni, enum ATTR_TYPE type,
1444 			  const __le16 *name, u8 name_len,
1445 			  const struct runs_tree *run, CLST svcn, CLST len,
1446 			  __le16 flags, struct ATTRIB **new_attr,
1447 			  struct mft_inode **mi, struct ATTR_LIST_ENTRY **le)
1448 {
1449 	int err;
1450 	CLST plen;
1451 	struct ATTRIB *attr;
1452 	bool is_ext = (flags & (ATTR_FLAG_SPARSED | ATTR_FLAG_COMPRESSED)) &&
1453 		      !svcn;
1454 	u32 name_size = ALIGN(name_len * sizeof(short), 8);
1455 	u32 name_off = is_ext ? SIZEOF_NONRESIDENT_EX : SIZEOF_NONRESIDENT;
1456 	u32 run_off = name_off + name_size;
1457 	u32 run_size, asize;
1458 	struct ntfs_sb_info *sbi = ni->mi.sbi;
1459 
1460 	/* Estimate packed size (run_buf=NULL). */
1461 	err = run_pack(run, svcn, len, NULL, sbi->max_bytes_per_attr - run_off,
1462 		       &plen);
1463 	if (err < 0)
1464 		goto out;
1465 
1466 	run_size = ALIGN(err, 8);
1467 
1468 	if (plen < len) {
1469 		err = -EINVAL;
1470 		goto out;
1471 	}
1472 
1473 	asize = run_off + run_size;
1474 
1475 	if (asize > sbi->max_bytes_per_attr) {
1476 		err = -EINVAL;
1477 		goto out;
1478 	}
1479 
1480 	err = ni_insert_attr(ni, type, name, name_len, asize, name_off, svcn,
1481 			     &attr, mi, le);
1482 
1483 	if (err)
1484 		goto out;
1485 
1486 	attr->non_res = 1;
1487 	attr->name_off = cpu_to_le16(name_off);
1488 	attr->flags = flags;
1489 
1490 	/* This function can't fail - cause already checked above. */
1491 	run_pack(run, svcn, len, Add2Ptr(attr, run_off), run_size, &plen);
1492 
1493 	attr->nres.svcn = cpu_to_le64(svcn);
1494 	attr->nres.evcn = cpu_to_le64((u64)svcn + len - 1);
1495 
1496 	if (new_attr)
1497 		*new_attr = attr;
1498 
1499 	*(__le64 *)&attr->nres.run_off = cpu_to_le64(run_off);
1500 
1501 	attr->nres.alloc_size =
1502 		svcn ? 0 : cpu_to_le64((u64)len << ni->mi.sbi->cluster_bits);
1503 	attr->nres.data_size = attr->nres.alloc_size;
1504 	attr->nres.valid_size = attr->nres.alloc_size;
1505 
1506 	if (is_ext) {
1507 		if (flags & ATTR_FLAG_COMPRESSED)
1508 			attr->nres.c_unit = NTFS_LZNT_CUNIT;
1509 		attr->nres.total_size = attr->nres.alloc_size;
1510 	}
1511 
1512 out:
1513 	return err;
1514 }
1515 
1516 /*
1517  * ni_insert_resident - Inserts new resident attribute.
1518  */
ni_insert_resident(struct ntfs_inode * ni,u32 data_size,enum ATTR_TYPE type,const __le16 * name,u8 name_len,struct ATTRIB ** new_attr,struct mft_inode ** mi,struct ATTR_LIST_ENTRY ** le)1519 int ni_insert_resident(struct ntfs_inode *ni, u32 data_size,
1520 		       enum ATTR_TYPE type, const __le16 *name, u8 name_len,
1521 		       struct ATTRIB **new_attr, struct mft_inode **mi,
1522 		       struct ATTR_LIST_ENTRY **le)
1523 {
1524 	int err;
1525 	u32 name_size = ALIGN(name_len * sizeof(short), 8);
1526 	u32 asize = SIZEOF_RESIDENT + name_size + ALIGN(data_size, 8);
1527 	struct ATTRIB *attr;
1528 
1529 	err = ni_insert_attr(ni, type, name, name_len, asize, SIZEOF_RESIDENT,
1530 			     0, &attr, mi, le);
1531 	if (err)
1532 		return err;
1533 
1534 	attr->non_res = 0;
1535 	attr->flags = 0;
1536 
1537 	attr->res.data_size = cpu_to_le32(data_size);
1538 	attr->res.data_off = cpu_to_le16(SIZEOF_RESIDENT + name_size);
1539 	if (type == ATTR_NAME) {
1540 		attr->res.flags = RESIDENT_FLAG_INDEXED;
1541 
1542 		/* is_attr_indexed(attr)) == true */
1543 		le16_add_cpu(&ni->mi.mrec->hard_links, 1);
1544 		ni->mi.dirty = true;
1545 	}
1546 	attr->res.res = 0;
1547 
1548 	if (new_attr)
1549 		*new_attr = attr;
1550 
1551 	return 0;
1552 }
1553 
1554 /*
1555  * ni_remove_attr_le - Remove attribute from record.
1556  */
ni_remove_attr_le(struct ntfs_inode * ni,struct ATTRIB * attr,struct mft_inode * mi,struct ATTR_LIST_ENTRY * le)1557 void ni_remove_attr_le(struct ntfs_inode *ni, struct ATTRIB *attr,
1558 		       struct mft_inode *mi, struct ATTR_LIST_ENTRY *le)
1559 {
1560 	mi_remove_attr(ni, mi, attr);
1561 
1562 	if (le)
1563 		al_remove_le(ni, le);
1564 }
1565 
1566 /*
1567  * ni_delete_all - Remove all attributes and frees allocates space.
1568  *
1569  * ntfs_evict_inode->ntfs_clear_inode->ni_delete_all (if no links).
1570  */
ni_delete_all(struct ntfs_inode * ni)1571 int ni_delete_all(struct ntfs_inode *ni)
1572 {
1573 	int err;
1574 	struct ATTR_LIST_ENTRY *le = NULL;
1575 	struct ATTRIB *attr = NULL;
1576 	struct rb_node *node;
1577 	u16 roff;
1578 	u32 asize;
1579 	CLST svcn, evcn;
1580 	struct ntfs_sb_info *sbi = ni->mi.sbi;
1581 	bool nt3 = is_ntfs3(sbi);
1582 	struct MFT_REF ref;
1583 
1584 	while ((attr = ni_enum_attr_ex(ni, attr, &le, NULL))) {
1585 		if (!nt3 || attr->name_len) {
1586 			;
1587 		} else if (attr->type == ATTR_REPARSE) {
1588 			mi_get_ref(&ni->mi, &ref);
1589 			ntfs_remove_reparse(sbi, 0, &ref);
1590 		} else if (attr->type == ATTR_ID && !attr->non_res &&
1591 			   le32_to_cpu(attr->res.data_size) >=
1592 				   sizeof(struct GUID)) {
1593 			ntfs_objid_remove(sbi, resident_data(attr));
1594 		}
1595 
1596 		if (!attr->non_res)
1597 			continue;
1598 
1599 		svcn = le64_to_cpu(attr->nres.svcn);
1600 		evcn = le64_to_cpu(attr->nres.evcn);
1601 
1602 		if (evcn + 1 <= svcn)
1603 			continue;
1604 
1605 		asize = le32_to_cpu(attr->size);
1606 		roff = le16_to_cpu(attr->nres.run_off);
1607 
1608 		if (roff > asize) {
1609 			/* ni_enum_attr_ex checks this case. */
1610 			continue;
1611 		}
1612 
1613 		/* run==1 means unpack and deallocate. */
1614 		run_unpack_ex(RUN_DEALLOCATE, sbi, ni->mi.rno, svcn, evcn, svcn,
1615 			      Add2Ptr(attr, roff), asize - roff);
1616 	}
1617 
1618 	if (ni->attr_list.size) {
1619 		run_deallocate(ni->mi.sbi, &ni->attr_list.run, true);
1620 		al_destroy(ni);
1621 	}
1622 
1623 	/* Free all subrecords. */
1624 	for (node = rb_first(&ni->mi_tree); node;) {
1625 		struct rb_node *next = rb_next(node);
1626 		struct mft_inode *mi = rb_entry(node, struct mft_inode, node);
1627 
1628 		clear_rec_inuse(mi->mrec);
1629 		mi->dirty = true;
1630 		mi_write(mi, 0);
1631 
1632 		ntfs_mark_rec_free(sbi, mi->rno, false);
1633 		ni_remove_mi(ni, mi);
1634 		mi_put(mi);
1635 		node = next;
1636 	}
1637 
1638 	/* Free base record. */
1639 	clear_rec_inuse(ni->mi.mrec);
1640 	ni->mi.dirty = true;
1641 	err = mi_write(&ni->mi, 0);
1642 
1643 	ntfs_mark_rec_free(sbi, ni->mi.rno, false);
1644 
1645 	return err;
1646 }
1647 
1648 /* ni_fname_name
1649  *
1650  * Return: File name attribute by its value.
1651  */
ni_fname_name(struct ntfs_inode * ni,const struct le_str * uni,const struct MFT_REF * home_dir,struct mft_inode ** mi,struct ATTR_LIST_ENTRY ** le)1652 struct ATTR_FILE_NAME *ni_fname_name(struct ntfs_inode *ni,
1653 				     const struct le_str *uni,
1654 				     const struct MFT_REF *home_dir,
1655 				     struct mft_inode **mi,
1656 				     struct ATTR_LIST_ENTRY **le)
1657 {
1658 	struct ATTRIB *attr = NULL;
1659 	struct ATTR_FILE_NAME *fname;
1660 
1661 	if (le)
1662 		*le = NULL;
1663 
1664 	/* Enumerate all names. */
1665 next:
1666 	attr = ni_find_attr(ni, attr, le, ATTR_NAME, NULL, 0, NULL, mi);
1667 	if (!attr)
1668 		return NULL;
1669 
1670 	fname = resident_data_ex(attr, SIZEOF_ATTRIBUTE_FILENAME);
1671 	if (!fname)
1672 		goto next;
1673 
1674 	if (home_dir && memcmp(home_dir, &fname->home, sizeof(*home_dir)))
1675 		goto next;
1676 
1677 	if (!uni)
1678 		return fname;
1679 
1680 	if (uni->len != fname->name_len)
1681 		goto next;
1682 
1683 	if (ntfs_cmp_names(uni->name, uni->len, fname->name, uni->len, NULL,
1684 			   false))
1685 		goto next;
1686 	return fname;
1687 }
1688 
1689 /*
1690  * ni_fname_type
1691  *
1692  * Return: File name attribute with given type.
1693  */
ni_fname_type(struct ntfs_inode * ni,u8 name_type,struct mft_inode ** mi,struct ATTR_LIST_ENTRY ** le)1694 struct ATTR_FILE_NAME *ni_fname_type(struct ntfs_inode *ni, u8 name_type,
1695 				     struct mft_inode **mi,
1696 				     struct ATTR_LIST_ENTRY **le)
1697 {
1698 	struct ATTRIB *attr = NULL;
1699 	struct ATTR_FILE_NAME *fname;
1700 
1701 	*le = NULL;
1702 
1703 	if (name_type == FILE_NAME_POSIX)
1704 		return NULL;
1705 
1706 	/* Enumerate all names. */
1707 	for (;;) {
1708 		attr = ni_find_attr(ni, attr, le, ATTR_NAME, NULL, 0, NULL, mi);
1709 		if (!attr)
1710 			return NULL;
1711 
1712 		fname = resident_data_ex(attr, SIZEOF_ATTRIBUTE_FILENAME);
1713 		if (fname && name_type == fname->type)
1714 			return fname;
1715 	}
1716 }
1717 
1718 /*
1719  * ni_new_attr_flags
1720  *
1721  * Process compressed/sparsed in special way.
1722  * NOTE: You need to set ni->std_fa = new_fa
1723  * after this function to keep internal structures in consistency.
1724  */
ni_new_attr_flags(struct ntfs_inode * ni,enum FILE_ATTRIBUTE new_fa)1725 int ni_new_attr_flags(struct ntfs_inode *ni, enum FILE_ATTRIBUTE new_fa)
1726 {
1727 	struct ATTRIB *attr;
1728 	struct mft_inode *mi;
1729 	__le16 new_aflags;
1730 	u32 new_asize;
1731 
1732 	attr = ni_find_attr(ni, NULL, NULL, ATTR_DATA, NULL, 0, NULL, &mi);
1733 	if (!attr)
1734 		return -EINVAL;
1735 
1736 	new_aflags = attr->flags;
1737 
1738 	if (new_fa & FILE_ATTRIBUTE_SPARSE_FILE)
1739 		new_aflags |= ATTR_FLAG_SPARSED;
1740 	else
1741 		new_aflags &= ~ATTR_FLAG_SPARSED;
1742 
1743 	if (new_fa & FILE_ATTRIBUTE_COMPRESSED)
1744 		new_aflags |= ATTR_FLAG_COMPRESSED;
1745 	else
1746 		new_aflags &= ~ATTR_FLAG_COMPRESSED;
1747 
1748 	if (new_aflags == attr->flags)
1749 		return 0;
1750 
1751 	if ((new_aflags & (ATTR_FLAG_COMPRESSED | ATTR_FLAG_SPARSED)) ==
1752 	    (ATTR_FLAG_COMPRESSED | ATTR_FLAG_SPARSED)) {
1753 		ntfs_inode_warn(&ni->vfs_inode,
1754 				"file can't be sparsed and compressed");
1755 		return -EOPNOTSUPP;
1756 	}
1757 
1758 	if (!attr->non_res)
1759 		goto out;
1760 
1761 	if (attr->nres.data_size) {
1762 		ntfs_inode_warn(
1763 			&ni->vfs_inode,
1764 			"one can change sparsed/compressed only for empty files");
1765 		return -EOPNOTSUPP;
1766 	}
1767 
1768 	/* Resize nonresident empty attribute in-place only. */
1769 	new_asize = (new_aflags & (ATTR_FLAG_COMPRESSED | ATTR_FLAG_SPARSED)) ?
1770 			    (SIZEOF_NONRESIDENT_EX + 8) :
1771 			    (SIZEOF_NONRESIDENT + 8);
1772 
1773 	if (!mi_resize_attr(mi, attr, new_asize - le32_to_cpu(attr->size)))
1774 		return -EOPNOTSUPP;
1775 
1776 	if (new_aflags & ATTR_FLAG_SPARSED) {
1777 		attr->name_off = SIZEOF_NONRESIDENT_EX_LE;
1778 		/* Windows uses 16 clusters per frame but supports one cluster per frame too. */
1779 		attr->nres.c_unit = 0;
1780 		ni->vfs_inode.i_mapping->a_ops = &ntfs_aops;
1781 	} else if (new_aflags & ATTR_FLAG_COMPRESSED) {
1782 		attr->name_off = SIZEOF_NONRESIDENT_EX_LE;
1783 		/* The only allowed: 16 clusters per frame. */
1784 		attr->nres.c_unit = NTFS_LZNT_CUNIT;
1785 		ni->vfs_inode.i_mapping->a_ops = &ntfs_aops_cmpr;
1786 	} else {
1787 		attr->name_off = SIZEOF_NONRESIDENT_LE;
1788 		/* Normal files. */
1789 		attr->nres.c_unit = 0;
1790 		ni->vfs_inode.i_mapping->a_ops = &ntfs_aops;
1791 	}
1792 	attr->nres.run_off = attr->name_off;
1793 out:
1794 	attr->flags = new_aflags;
1795 	mi->dirty = true;
1796 
1797 	return 0;
1798 }
1799 
1800 /*
1801  * ni_parse_reparse
1802  *
1803  * buffer - memory for reparse buffer header
1804  */
ni_parse_reparse(struct ntfs_inode * ni,struct ATTRIB * attr,struct REPARSE_DATA_BUFFER * buffer)1805 enum REPARSE_SIGN ni_parse_reparse(struct ntfs_inode *ni, struct ATTRIB *attr,
1806 				   struct REPARSE_DATA_BUFFER *buffer)
1807 {
1808 	const struct REPARSE_DATA_BUFFER *rp = NULL;
1809 	u8 bits;
1810 	u16 len;
1811 	typeof(rp->CompressReparseBuffer) *cmpr;
1812 
1813 	/* Try to estimate reparse point. */
1814 	if (!attr->non_res) {
1815 		rp = resident_data_ex(attr, sizeof(struct REPARSE_DATA_BUFFER));
1816 	} else if (le64_to_cpu(attr->nres.data_size) >=
1817 		   sizeof(struct REPARSE_DATA_BUFFER)) {
1818 		struct runs_tree run;
1819 
1820 		run_init(&run);
1821 
1822 		if (!attr_load_runs_vcn(ni, ATTR_REPARSE, NULL, 0, &run, 0) &&
1823 		    !ntfs_read_run_nb(ni->mi.sbi, &run, 0, buffer,
1824 				      sizeof(struct REPARSE_DATA_BUFFER),
1825 				      NULL)) {
1826 			rp = buffer;
1827 		}
1828 
1829 		run_close(&run);
1830 	}
1831 
1832 	if (!rp)
1833 		return REPARSE_NONE;
1834 
1835 	len = le16_to_cpu(rp->ReparseDataLength);
1836 	switch (rp->ReparseTag) {
1837 	case (IO_REPARSE_TAG_MICROSOFT | IO_REPARSE_TAG_SYMBOLIC_LINK):
1838 		break; /* Symbolic link. */
1839 	case IO_REPARSE_TAG_MOUNT_POINT:
1840 		break; /* Mount points and junctions. */
1841 	case IO_REPARSE_TAG_SYMLINK:
1842 		break;
1843 	case IO_REPARSE_TAG_COMPRESS:
1844 		/*
1845 		 * WOF - Windows Overlay Filter - Used to compress files with
1846 		 * LZX/Xpress.
1847 		 *
1848 		 * Unlike native NTFS file compression, the Windows
1849 		 * Overlay Filter supports only read operations. This means
1850 		 * that it doesn't need to sector-align each compressed chunk,
1851 		 * so the compressed data can be packed more tightly together.
1852 		 * If you open the file for writing, the WOF just decompresses
1853 		 * the entire file, turning it back into a plain file.
1854 		 *
1855 		 * Ntfs3 driver decompresses the entire file only on write or
1856 		 * change size requests.
1857 		 */
1858 
1859 		cmpr = &rp->CompressReparseBuffer;
1860 		if (len < sizeof(*cmpr) ||
1861 		    cmpr->WofVersion != WOF_CURRENT_VERSION ||
1862 		    cmpr->WofProvider != WOF_PROVIDER_SYSTEM ||
1863 		    cmpr->ProviderVer != WOF_PROVIDER_CURRENT_VERSION) {
1864 			return REPARSE_NONE;
1865 		}
1866 
1867 		switch (cmpr->CompressionFormat) {
1868 		case WOF_COMPRESSION_XPRESS4K:
1869 			bits = 0xc; // 4k
1870 			break;
1871 		case WOF_COMPRESSION_XPRESS8K:
1872 			bits = 0xd; // 8k
1873 			break;
1874 		case WOF_COMPRESSION_XPRESS16K:
1875 			bits = 0xe; // 16k
1876 			break;
1877 		case WOF_COMPRESSION_LZX32K:
1878 			bits = 0xf; // 32k
1879 			break;
1880 		default:
1881 			bits = 0x10; // 64k
1882 			break;
1883 		}
1884 		ni_set_ext_compress_bits(ni, bits);
1885 		return REPARSE_COMPRESSED;
1886 
1887 	case IO_REPARSE_TAG_DEDUP:
1888 		ni->ni_flags |= NI_FLAG_DEDUPLICATED;
1889 		return REPARSE_DEDUPLICATED;
1890 
1891 	default:
1892 		if (rp->ReparseTag & IO_REPARSE_TAG_NAME_SURROGATE)
1893 			break;
1894 
1895 		return REPARSE_NONE;
1896 	}
1897 
1898 	if (buffer != rp)
1899 		memcpy(buffer, rp, sizeof(struct REPARSE_DATA_BUFFER));
1900 
1901 	/* Looks like normal symlink. */
1902 	return REPARSE_LINK;
1903 }
1904 
1905 /*
1906  * ni_fiemap - Helper for file_fiemap().
1907  *
1908  * Assumed ni_lock.
1909  * TODO: Less aggressive locks.
1910  */
ni_fiemap(struct ntfs_inode * ni,struct fiemap_extent_info * fieinfo,__u64 vbo,__u64 len)1911 int ni_fiemap(struct ntfs_inode *ni, struct fiemap_extent_info *fieinfo,
1912 	      __u64 vbo, __u64 len)
1913 {
1914 	int err = 0;
1915 	struct ntfs_sb_info *sbi = ni->mi.sbi;
1916 	u8 cluster_bits = sbi->cluster_bits;
1917 	struct runs_tree run;
1918 	struct ATTRIB *attr;
1919 	CLST vcn = vbo >> cluster_bits;
1920 	CLST lcn, clen;
1921 	u64 valid = ni->i_valid;
1922 	u64 lbo, bytes;
1923 	u64 end, alloc_size;
1924 	size_t idx = -1;
1925 	u32 flags;
1926 	bool ok;
1927 
1928 	run_init(&run);
1929 	if (S_ISDIR(ni->vfs_inode.i_mode)) {
1930 		attr = ni_find_attr(ni, NULL, NULL, ATTR_ALLOC, I30_NAME,
1931 				    ARRAY_SIZE(I30_NAME), NULL, NULL);
1932 	} else {
1933 		attr = ni_find_attr(ni, NULL, NULL, ATTR_DATA, NULL, 0, NULL,
1934 				    NULL);
1935 		if (!attr) {
1936 			err = -EINVAL;
1937 			goto out;
1938 		}
1939 		if (is_attr_compressed(attr)) {
1940 			/* Unfortunately cp -r incorrectly treats compressed clusters. */
1941 			err = -EOPNOTSUPP;
1942 			ntfs_inode_warn(
1943 				&ni->vfs_inode,
1944 				"fiemap is not supported for compressed file (cp -r)");
1945 			goto out;
1946 		}
1947 	}
1948 
1949 	if (!attr || !attr->non_res) {
1950 		err = fiemap_fill_next_extent(
1951 			fieinfo, 0, 0,
1952 			attr ? le32_to_cpu(attr->res.data_size) : 0,
1953 			FIEMAP_EXTENT_DATA_INLINE | FIEMAP_EXTENT_LAST |
1954 				FIEMAP_EXTENT_MERGED);
1955 		goto out;
1956 	}
1957 
1958 	end = vbo + len;
1959 	alloc_size = le64_to_cpu(attr->nres.alloc_size);
1960 	if (end > alloc_size)
1961 		end = alloc_size;
1962 
1963 
1964 	while (vbo < end) {
1965 		if (idx == -1) {
1966 			ok = run_lookup_entry(&run, vcn, &lcn, &clen, &idx);
1967 		} else {
1968 			CLST vcn_next = vcn;
1969 
1970 			ok = run_get_entry(&run, ++idx, &vcn, &lcn, &clen) &&
1971 			     vcn == vcn_next;
1972 			if (!ok)
1973 				vcn = vcn_next;
1974 		}
1975 
1976 		if (!ok) {
1977 			err = attr_load_runs_vcn(ni, attr->type,
1978 						 attr_name(attr),
1979 						 attr->name_len, &run, vcn);
1980 
1981 			if (err)
1982 				break;
1983 
1984 			ok = run_lookup_entry(&run, vcn, &lcn, &clen, &idx);
1985 
1986 			if (!ok) {
1987 				err = -EINVAL;
1988 				break;
1989 			}
1990 		}
1991 
1992 		if (!clen) {
1993 			err = -EINVAL; // ?
1994 			break;
1995 		}
1996 
1997 		if (lcn == SPARSE_LCN) {
1998 			vcn += clen;
1999 			vbo = (u64)vcn << cluster_bits;
2000 			continue;
2001 		}
2002 
2003 		flags = FIEMAP_EXTENT_MERGED;
2004 		if (S_ISDIR(ni->vfs_inode.i_mode)) {
2005 			;
2006 		} else if (is_attr_compressed(attr)) {
2007 			CLST clst_data;
2008 
2009 			err = attr_is_frame_compressed(ni, attr,
2010 						       vcn >> attr->nres.c_unit,
2011 						       &clst_data, &run);
2012 			if (err)
2013 				break;
2014 			if (clst_data < NTFS_LZNT_CLUSTERS)
2015 				flags |= FIEMAP_EXTENT_ENCODED;
2016 		} else if (is_attr_encrypted(attr)) {
2017 			flags |= FIEMAP_EXTENT_DATA_ENCRYPTED;
2018 		}
2019 
2020 		vbo = (u64)vcn << cluster_bits;
2021 		bytes = (u64)clen << cluster_bits;
2022 		lbo = (u64)lcn << cluster_bits;
2023 
2024 		vcn += clen;
2025 
2026 		if (vbo + bytes >= end)
2027 			bytes = end - vbo;
2028 
2029 		if (vbo + bytes <= valid) {
2030 			;
2031 		} else if (vbo >= valid) {
2032 			flags |= FIEMAP_EXTENT_UNWRITTEN;
2033 		} else {
2034 			/* vbo < valid && valid < vbo + bytes */
2035 			u64 dlen = valid - vbo;
2036 
2037 			if (vbo + dlen >= end)
2038 				flags |= FIEMAP_EXTENT_LAST;
2039 
2040 			err = fiemap_fill_next_extent(fieinfo, vbo, lbo, dlen,
2041 						      flags);
2042 
2043 			if (err < 0)
2044 				break;
2045 			if (err == 1) {
2046 				err = 0;
2047 				break;
2048 			}
2049 
2050 			vbo = valid;
2051 			bytes -= dlen;
2052 			if (!bytes)
2053 				continue;
2054 
2055 			lbo += dlen;
2056 			flags |= FIEMAP_EXTENT_UNWRITTEN;
2057 		}
2058 
2059 		if (vbo + bytes >= end)
2060 			flags |= FIEMAP_EXTENT_LAST;
2061 
2062 		err = fiemap_fill_next_extent(fieinfo, vbo, lbo, bytes, flags);
2063 		if (err < 0)
2064 			break;
2065 		if (err == 1) {
2066 			err = 0;
2067 			break;
2068 		}
2069 
2070 		vbo += bytes;
2071 	}
2072 
2073 out:
2074 	run_close(&run);
2075 	return err;
2076 }
2077 
2078 /*
2079  * ni_readpage_cmpr
2080  *
2081  * When decompressing, we typically obtain more than one page per reference.
2082  * We inject the additional pages into the page cache.
2083  */
ni_readpage_cmpr(struct ntfs_inode * ni,struct folio * folio)2084 int ni_readpage_cmpr(struct ntfs_inode *ni, struct folio *folio)
2085 {
2086 	int err;
2087 	struct ntfs_sb_info *sbi = ni->mi.sbi;
2088 	struct address_space *mapping = folio->mapping;
2089 	pgoff_t index = folio->index;
2090 	u64 frame_vbo, vbo = (u64)index << PAGE_SHIFT;
2091 	struct page **pages = NULL; /* Array of at most 16 pages. stack? */
2092 	u8 frame_bits;
2093 	CLST frame;
2094 	u32 i, idx, frame_size, pages_per_frame;
2095 	gfp_t gfp_mask;
2096 	struct page *pg;
2097 
2098 	if (vbo >= i_size_read(&ni->vfs_inode)) {
2099 		folio_zero_range(folio, 0, folio_size(folio));
2100 		folio_mark_uptodate(folio);
2101 		err = 0;
2102 		goto out;
2103 	}
2104 
2105 	if (ni->ni_flags & NI_FLAG_COMPRESSED_MASK) {
2106 		/* Xpress or LZX. */
2107 		frame_bits = ni_ext_compress_bits(ni);
2108 	} else {
2109 		/* LZNT compression. */
2110 		frame_bits = NTFS_LZNT_CUNIT + sbi->cluster_bits;
2111 	}
2112 	frame_size = 1u << frame_bits;
2113 	frame = vbo >> frame_bits;
2114 	frame_vbo = (u64)frame << frame_bits;
2115 	idx = (vbo - frame_vbo) >> PAGE_SHIFT;
2116 
2117 	pages_per_frame = frame_size >> PAGE_SHIFT;
2118 	pages = kcalloc(pages_per_frame, sizeof(struct page *), GFP_NOFS);
2119 	if (!pages) {
2120 		err = -ENOMEM;
2121 		goto out;
2122 	}
2123 
2124 	pages[idx] = &folio->page;
2125 	index = frame_vbo >> PAGE_SHIFT;
2126 	gfp_mask = mapping_gfp_mask(mapping);
2127 
2128 	for (i = 0; i < pages_per_frame; i++, index++) {
2129 		if (i == idx)
2130 			continue;
2131 
2132 		pg = find_or_create_page(mapping, index, gfp_mask);
2133 		if (!pg) {
2134 			err = -ENOMEM;
2135 			goto out1;
2136 		}
2137 		pages[i] = pg;
2138 	}
2139 
2140 	err = ni_read_frame(ni, frame_vbo, pages, pages_per_frame);
2141 
2142 out1:
2143 	for (i = 0; i < pages_per_frame; i++) {
2144 		pg = pages[i];
2145 		if (i == idx || !pg)
2146 			continue;
2147 		unlock_page(pg);
2148 		put_page(pg);
2149 	}
2150 
2151 out:
2152 	/* At this point, err contains 0 or -EIO depending on the "critical" page. */
2153 	kfree(pages);
2154 	folio_unlock(folio);
2155 
2156 	return err;
2157 }
2158 
2159 #ifdef CONFIG_NTFS3_LZX_XPRESS
2160 /*
2161  * ni_decompress_file - Decompress LZX/Xpress compressed file.
2162  *
2163  * Remove ATTR_DATA::WofCompressedData.
2164  * Remove ATTR_REPARSE.
2165  */
ni_decompress_file(struct ntfs_inode * ni)2166 int ni_decompress_file(struct ntfs_inode *ni)
2167 {
2168 	struct ntfs_sb_info *sbi = ni->mi.sbi;
2169 	struct inode *inode = &ni->vfs_inode;
2170 	loff_t i_size = i_size_read(inode);
2171 	struct address_space *mapping = inode->i_mapping;
2172 	gfp_t gfp_mask = mapping_gfp_mask(mapping);
2173 	struct page **pages = NULL;
2174 	struct ATTR_LIST_ENTRY *le;
2175 	struct ATTRIB *attr;
2176 	CLST vcn, cend, lcn, clen, end;
2177 	pgoff_t index;
2178 	u64 vbo;
2179 	u8 frame_bits;
2180 	u32 i, frame_size, pages_per_frame, bytes;
2181 	struct mft_inode *mi;
2182 	int err;
2183 
2184 	/* Clusters for decompressed data. */
2185 	cend = bytes_to_cluster(sbi, i_size);
2186 
2187 	if (!i_size)
2188 		goto remove_wof;
2189 
2190 	/* Check in advance. */
2191 	if (cend > wnd_zeroes(&sbi->used.bitmap)) {
2192 		err = -ENOSPC;
2193 		goto out;
2194 	}
2195 
2196 	frame_bits = ni_ext_compress_bits(ni);
2197 	frame_size = 1u << frame_bits;
2198 	pages_per_frame = frame_size >> PAGE_SHIFT;
2199 	pages = kcalloc(pages_per_frame, sizeof(struct page *), GFP_NOFS);
2200 	if (!pages) {
2201 		err = -ENOMEM;
2202 		goto out;
2203 	}
2204 
2205 	/*
2206 	 * Step 1: Decompress data and copy to new allocated clusters.
2207 	 */
2208 	index = 0;
2209 	for (vbo = 0; vbo < i_size; vbo += bytes) {
2210 		u32 nr_pages;
2211 		bool new;
2212 
2213 		if (vbo + frame_size > i_size) {
2214 			bytes = i_size - vbo;
2215 			nr_pages = (bytes + PAGE_SIZE - 1) >> PAGE_SHIFT;
2216 		} else {
2217 			nr_pages = pages_per_frame;
2218 			bytes = frame_size;
2219 		}
2220 
2221 		end = bytes_to_cluster(sbi, vbo + bytes);
2222 
2223 		for (vcn = vbo >> sbi->cluster_bits; vcn < end; vcn += clen) {
2224 			err = attr_data_get_block(ni, vcn, cend - vcn, &lcn,
2225 						  &clen, &new, false);
2226 			if (err)
2227 				goto out;
2228 		}
2229 
2230 		for (i = 0; i < pages_per_frame; i++, index++) {
2231 			struct page *pg;
2232 
2233 			pg = find_or_create_page(mapping, index, gfp_mask);
2234 			if (!pg) {
2235 				while (i--) {
2236 					unlock_page(pages[i]);
2237 					put_page(pages[i]);
2238 				}
2239 				err = -ENOMEM;
2240 				goto out;
2241 			}
2242 			pages[i] = pg;
2243 		}
2244 
2245 		err = ni_read_frame(ni, vbo, pages, pages_per_frame);
2246 
2247 		if (!err) {
2248 			down_read(&ni->file.run_lock);
2249 			err = ntfs_bio_pages(sbi, &ni->file.run, pages,
2250 					     nr_pages, vbo, bytes,
2251 					     REQ_OP_WRITE);
2252 			up_read(&ni->file.run_lock);
2253 		}
2254 
2255 		for (i = 0; i < pages_per_frame; i++) {
2256 			unlock_page(pages[i]);
2257 			put_page(pages[i]);
2258 		}
2259 
2260 		if (err)
2261 			goto out;
2262 
2263 		cond_resched();
2264 	}
2265 
2266 remove_wof:
2267 	/*
2268 	 * Step 2: Deallocate attributes ATTR_DATA::WofCompressedData
2269 	 * and ATTR_REPARSE.
2270 	 */
2271 	attr = NULL;
2272 	le = NULL;
2273 	while ((attr = ni_enum_attr_ex(ni, attr, &le, NULL))) {
2274 		CLST svcn, evcn;
2275 		u32 asize, roff;
2276 
2277 		if (attr->type == ATTR_REPARSE) {
2278 			struct MFT_REF ref;
2279 
2280 			mi_get_ref(&ni->mi, &ref);
2281 			ntfs_remove_reparse(sbi, 0, &ref);
2282 		}
2283 
2284 		if (!attr->non_res)
2285 			continue;
2286 
2287 		if (attr->type != ATTR_REPARSE &&
2288 		    (attr->type != ATTR_DATA ||
2289 		     attr->name_len != ARRAY_SIZE(WOF_NAME) ||
2290 		     memcmp(attr_name(attr), WOF_NAME, sizeof(WOF_NAME))))
2291 			continue;
2292 
2293 		svcn = le64_to_cpu(attr->nres.svcn);
2294 		evcn = le64_to_cpu(attr->nres.evcn);
2295 
2296 		if (evcn + 1 <= svcn)
2297 			continue;
2298 
2299 		asize = le32_to_cpu(attr->size);
2300 		roff = le16_to_cpu(attr->nres.run_off);
2301 
2302 		if (roff > asize) {
2303 			err = -EINVAL;
2304 			goto out;
2305 		}
2306 
2307 		/*run==1  Means unpack and deallocate. */
2308 		run_unpack_ex(RUN_DEALLOCATE, sbi, ni->mi.rno, svcn, evcn, svcn,
2309 			      Add2Ptr(attr, roff), asize - roff);
2310 	}
2311 
2312 	/*
2313 	 * Step 3: Remove attribute ATTR_DATA::WofCompressedData.
2314 	 */
2315 	err = ni_remove_attr(ni, ATTR_DATA, WOF_NAME, ARRAY_SIZE(WOF_NAME),
2316 			     false, NULL);
2317 	if (err)
2318 		goto out;
2319 
2320 	/*
2321 	 * Step 4: Remove ATTR_REPARSE.
2322 	 */
2323 	err = ni_remove_attr(ni, ATTR_REPARSE, NULL, 0, false, NULL);
2324 	if (err)
2325 		goto out;
2326 
2327 	/*
2328 	 * Step 5: Remove sparse flag from data attribute.
2329 	 */
2330 	attr = ni_find_attr(ni, NULL, NULL, ATTR_DATA, NULL, 0, NULL, &mi);
2331 	if (!attr) {
2332 		err = -EINVAL;
2333 		goto out;
2334 	}
2335 
2336 	if (attr->non_res && is_attr_sparsed(attr)) {
2337 		/* Sparsed attribute header is 8 bytes bigger than normal. */
2338 		struct MFT_REC *rec = mi->mrec;
2339 		u32 used = le32_to_cpu(rec->used);
2340 		u32 asize = le32_to_cpu(attr->size);
2341 		u16 roff = le16_to_cpu(attr->nres.run_off);
2342 		char *rbuf = Add2Ptr(attr, roff);
2343 
2344 		memmove(rbuf - 8, rbuf, used - PtrOffset(rec, rbuf));
2345 		attr->size = cpu_to_le32(asize - 8);
2346 		attr->flags &= ~ATTR_FLAG_SPARSED;
2347 		attr->nres.run_off = cpu_to_le16(roff - 8);
2348 		attr->nres.c_unit = 0;
2349 		rec->used = cpu_to_le32(used - 8);
2350 		mi->dirty = true;
2351 		ni->std_fa &= ~(FILE_ATTRIBUTE_SPARSE_FILE |
2352 				FILE_ATTRIBUTE_REPARSE_POINT);
2353 
2354 		mark_inode_dirty(inode);
2355 	}
2356 
2357 	/* Clear cached flag. */
2358 	ni->ni_flags &= ~NI_FLAG_COMPRESSED_MASK;
2359 	if (ni->file.offs_folio) {
2360 		folio_put(ni->file.offs_folio);
2361 		ni->file.offs_folio = NULL;
2362 	}
2363 	mapping->a_ops = &ntfs_aops;
2364 
2365 out:
2366 	kfree(pages);
2367 	if (err)
2368 		_ntfs_bad_inode(inode);
2369 
2370 	return err;
2371 }
2372 
2373 /*
2374  * decompress_lzx_xpress - External compression LZX/Xpress.
2375  */
decompress_lzx_xpress(struct ntfs_sb_info * sbi,const char * cmpr,size_t cmpr_size,void * unc,size_t unc_size,u32 frame_size)2376 static int decompress_lzx_xpress(struct ntfs_sb_info *sbi, const char *cmpr,
2377 				 size_t cmpr_size, void *unc, size_t unc_size,
2378 				 u32 frame_size)
2379 {
2380 	int err;
2381 	void *ctx;
2382 
2383 	if (cmpr_size == unc_size) {
2384 		/* Frame not compressed. */
2385 		memcpy(unc, cmpr, unc_size);
2386 		return 0;
2387 	}
2388 
2389 	err = 0;
2390 	if (frame_size == 0x8000) {
2391 		mutex_lock(&sbi->compress.mtx_lzx);
2392 		/* LZX: Frame compressed. */
2393 		ctx = sbi->compress.lzx;
2394 		if (!ctx) {
2395 			/* Lazy initialize LZX decompress context. */
2396 			ctx = lzx_allocate_decompressor();
2397 			if (!ctx) {
2398 				err = -ENOMEM;
2399 				goto out1;
2400 			}
2401 
2402 			sbi->compress.lzx = ctx;
2403 		}
2404 
2405 		if (lzx_decompress(ctx, cmpr, cmpr_size, unc, unc_size)) {
2406 			/* Treat all errors as "invalid argument". */
2407 			err = -EINVAL;
2408 		}
2409 out1:
2410 		mutex_unlock(&sbi->compress.mtx_lzx);
2411 	} else {
2412 		/* XPRESS: Frame compressed. */
2413 		mutex_lock(&sbi->compress.mtx_xpress);
2414 		ctx = sbi->compress.xpress;
2415 		if (!ctx) {
2416 			/* Lazy initialize Xpress decompress context. */
2417 			ctx = xpress_allocate_decompressor();
2418 			if (!ctx) {
2419 				err = -ENOMEM;
2420 				goto out2;
2421 			}
2422 
2423 			sbi->compress.xpress = ctx;
2424 		}
2425 
2426 		if (xpress_decompress(ctx, cmpr, cmpr_size, unc, unc_size)) {
2427 			/* Treat all errors as "invalid argument". */
2428 			err = -EINVAL;
2429 		}
2430 out2:
2431 		mutex_unlock(&sbi->compress.mtx_xpress);
2432 	}
2433 	return err;
2434 }
2435 #endif
2436 
2437 /*
2438  * ni_read_frame
2439  *
2440  * Pages - Array of locked pages.
2441  */
ni_read_frame(struct ntfs_inode * ni,u64 frame_vbo,struct page ** pages,u32 pages_per_frame)2442 int ni_read_frame(struct ntfs_inode *ni, u64 frame_vbo, struct page **pages,
2443 		  u32 pages_per_frame)
2444 {
2445 	int err;
2446 	struct ntfs_sb_info *sbi = ni->mi.sbi;
2447 	u8 cluster_bits = sbi->cluster_bits;
2448 	char *frame_ondisk = NULL;
2449 	char *frame_mem = NULL;
2450 	struct page **pages_disk = NULL;
2451 	struct ATTR_LIST_ENTRY *le = NULL;
2452 	struct runs_tree *run = &ni->file.run;
2453 	u64 valid_size = ni->i_valid;
2454 	u64 vbo_disk;
2455 	size_t unc_size;
2456 	u32 frame_size, i, npages_disk, ondisk_size;
2457 	struct page *pg;
2458 	struct ATTRIB *attr;
2459 	CLST frame, clst_data;
2460 
2461 	/*
2462 	 * To simplify decompress algorithm do vmap for source
2463 	 * and target pages.
2464 	 */
2465 	for (i = 0; i < pages_per_frame; i++)
2466 		kmap(pages[i]);
2467 
2468 	frame_size = pages_per_frame << PAGE_SHIFT;
2469 	frame_mem = vmap(pages, pages_per_frame, VM_MAP, PAGE_KERNEL);
2470 	if (!frame_mem) {
2471 		err = -ENOMEM;
2472 		goto out;
2473 	}
2474 
2475 	attr = ni_find_attr(ni, NULL, &le, ATTR_DATA, NULL, 0, NULL, NULL);
2476 	if (!attr) {
2477 		err = -ENOENT;
2478 		goto out1;
2479 	}
2480 
2481 	if (!attr->non_res) {
2482 		u32 data_size = le32_to_cpu(attr->res.data_size);
2483 
2484 		memset(frame_mem, 0, frame_size);
2485 		if (frame_vbo < data_size) {
2486 			ondisk_size = data_size - frame_vbo;
2487 			memcpy(frame_mem, resident_data(attr) + frame_vbo,
2488 			       min(ondisk_size, frame_size));
2489 		}
2490 		err = 0;
2491 		goto out1;
2492 	}
2493 
2494 	if (frame_vbo >= valid_size) {
2495 		memset(frame_mem, 0, frame_size);
2496 		err = 0;
2497 		goto out1;
2498 	}
2499 
2500 	if (ni->ni_flags & NI_FLAG_COMPRESSED_MASK) {
2501 #ifndef CONFIG_NTFS3_LZX_XPRESS
2502 		err = -EOPNOTSUPP;
2503 		goto out1;
2504 #else
2505 		loff_t i_size = i_size_read(&ni->vfs_inode);
2506 		u32 frame_bits = ni_ext_compress_bits(ni);
2507 		u64 frame64 = frame_vbo >> frame_bits;
2508 		u64 frames, vbo_data;
2509 
2510 		if (frame_size != (1u << frame_bits)) {
2511 			err = -EINVAL;
2512 			goto out1;
2513 		}
2514 		switch (frame_size) {
2515 		case 0x1000:
2516 		case 0x2000:
2517 		case 0x4000:
2518 		case 0x8000:
2519 			break;
2520 		default:
2521 			/* Unknown compression. */
2522 			err = -EOPNOTSUPP;
2523 			goto out1;
2524 		}
2525 
2526 		attr = ni_find_attr(ni, attr, &le, ATTR_DATA, WOF_NAME,
2527 				    ARRAY_SIZE(WOF_NAME), NULL, NULL);
2528 		if (!attr) {
2529 			ntfs_inode_err(
2530 				&ni->vfs_inode,
2531 				"external compressed file should contains data attribute \"WofCompressedData\"");
2532 			err = -EINVAL;
2533 			goto out1;
2534 		}
2535 
2536 		if (!attr->non_res) {
2537 			run = NULL;
2538 		} else {
2539 			run = run_alloc();
2540 			if (!run) {
2541 				err = -ENOMEM;
2542 				goto out1;
2543 			}
2544 		}
2545 
2546 		frames = (i_size - 1) >> frame_bits;
2547 
2548 		err = attr_wof_frame_info(ni, attr, run, frame64, frames,
2549 					  frame_bits, &ondisk_size, &vbo_data);
2550 		if (err)
2551 			goto out2;
2552 
2553 		if (frame64 == frames) {
2554 			unc_size = 1 + ((i_size - 1) & (frame_size - 1));
2555 			ondisk_size = attr_size(attr) - vbo_data;
2556 		} else {
2557 			unc_size = frame_size;
2558 		}
2559 
2560 		if (ondisk_size > frame_size) {
2561 			err = -EINVAL;
2562 			goto out2;
2563 		}
2564 
2565 		if (!attr->non_res) {
2566 			if (vbo_data + ondisk_size >
2567 			    le32_to_cpu(attr->res.data_size)) {
2568 				err = -EINVAL;
2569 				goto out1;
2570 			}
2571 
2572 			err = decompress_lzx_xpress(
2573 				sbi, Add2Ptr(resident_data(attr), vbo_data),
2574 				ondisk_size, frame_mem, unc_size, frame_size);
2575 			goto out1;
2576 		}
2577 		vbo_disk = vbo_data;
2578 		/* Load all runs to read [vbo_disk-vbo_to). */
2579 		err = attr_load_runs_range(ni, ATTR_DATA, WOF_NAME,
2580 					   ARRAY_SIZE(WOF_NAME), run, vbo_disk,
2581 					   vbo_data + ondisk_size);
2582 		if (err)
2583 			goto out2;
2584 		npages_disk = (ondisk_size + (vbo_disk & (PAGE_SIZE - 1)) +
2585 			       PAGE_SIZE - 1) >>
2586 			      PAGE_SHIFT;
2587 #endif
2588 	} else if (is_attr_compressed(attr)) {
2589 		/* LZNT compression. */
2590 		if (sbi->cluster_size > NTFS_LZNT_MAX_CLUSTER) {
2591 			err = -EOPNOTSUPP;
2592 			goto out1;
2593 		}
2594 
2595 		if (attr->nres.c_unit != NTFS_LZNT_CUNIT) {
2596 			err = -EOPNOTSUPP;
2597 			goto out1;
2598 		}
2599 
2600 		down_write(&ni->file.run_lock);
2601 		run_truncate_around(run, le64_to_cpu(attr->nres.svcn));
2602 		frame = frame_vbo >> (cluster_bits + NTFS_LZNT_CUNIT);
2603 		err = attr_is_frame_compressed(ni, attr, frame, &clst_data,
2604 					       run);
2605 		up_write(&ni->file.run_lock);
2606 		if (err)
2607 			goto out1;
2608 
2609 		if (!clst_data) {
2610 			memset(frame_mem, 0, frame_size);
2611 			goto out1;
2612 		}
2613 
2614 		frame_size = sbi->cluster_size << NTFS_LZNT_CUNIT;
2615 		ondisk_size = clst_data << cluster_bits;
2616 
2617 		if (clst_data >= NTFS_LZNT_CLUSTERS) {
2618 			/* Frame is not compressed. */
2619 			down_read(&ni->file.run_lock);
2620 			err = ntfs_bio_pages(sbi, run, pages, pages_per_frame,
2621 					     frame_vbo, ondisk_size,
2622 					     REQ_OP_READ);
2623 			up_read(&ni->file.run_lock);
2624 			goto out1;
2625 		}
2626 		vbo_disk = frame_vbo;
2627 		npages_disk = (ondisk_size + PAGE_SIZE - 1) >> PAGE_SHIFT;
2628 	} else {
2629 		__builtin_unreachable();
2630 		err = -EINVAL;
2631 		goto out1;
2632 	}
2633 
2634 	pages_disk = kcalloc(npages_disk, sizeof(*pages_disk), GFP_NOFS);
2635 	if (!pages_disk) {
2636 		err = -ENOMEM;
2637 		goto out2;
2638 	}
2639 
2640 	for (i = 0; i < npages_disk; i++) {
2641 		pg = alloc_page(GFP_KERNEL);
2642 		if (!pg) {
2643 			err = -ENOMEM;
2644 			goto out3;
2645 		}
2646 		pages_disk[i] = pg;
2647 		lock_page(pg);
2648 		kmap(pg);
2649 	}
2650 
2651 	/* Read 'ondisk_size' bytes from disk. */
2652 	down_read(&ni->file.run_lock);
2653 	err = ntfs_bio_pages(sbi, run, pages_disk, npages_disk, vbo_disk,
2654 			     ondisk_size, REQ_OP_READ);
2655 	up_read(&ni->file.run_lock);
2656 	if (err)
2657 		goto out3;
2658 
2659 	/*
2660 	 * To simplify decompress algorithm do vmap for source and target pages.
2661 	 */
2662 	frame_ondisk = vmap(pages_disk, npages_disk, VM_MAP, PAGE_KERNEL_RO);
2663 	if (!frame_ondisk) {
2664 		err = -ENOMEM;
2665 		goto out3;
2666 	}
2667 
2668 	/* Decompress: Frame_ondisk -> frame_mem. */
2669 #ifdef CONFIG_NTFS3_LZX_XPRESS
2670 	if (run != &ni->file.run) {
2671 		/* LZX or XPRESS */
2672 		err = decompress_lzx_xpress(
2673 			sbi, frame_ondisk + (vbo_disk & (PAGE_SIZE - 1)),
2674 			ondisk_size, frame_mem, unc_size, frame_size);
2675 	} else
2676 #endif
2677 	{
2678 		/* LZNT - Native NTFS compression. */
2679 		unc_size = decompress_lznt(frame_ondisk, ondisk_size, frame_mem,
2680 					   frame_size);
2681 		if ((ssize_t)unc_size < 0)
2682 			err = unc_size;
2683 		else if (!unc_size || unc_size > frame_size)
2684 			err = -EINVAL;
2685 	}
2686 	if (!err && valid_size < frame_vbo + frame_size) {
2687 		size_t ok = valid_size - frame_vbo;
2688 
2689 		memset(frame_mem + ok, 0, frame_size - ok);
2690 	}
2691 
2692 	vunmap(frame_ondisk);
2693 
2694 out3:
2695 	for (i = 0; i < npages_disk; i++) {
2696 		pg = pages_disk[i];
2697 		if (pg) {
2698 			kunmap(pg);
2699 			unlock_page(pg);
2700 			put_page(pg);
2701 		}
2702 	}
2703 	kfree(pages_disk);
2704 
2705 out2:
2706 #ifdef CONFIG_NTFS3_LZX_XPRESS
2707 	if (run != &ni->file.run)
2708 		run_free(run);
2709 #endif
2710 out1:
2711 	vunmap(frame_mem);
2712 out:
2713 	for (i = 0; i < pages_per_frame; i++) {
2714 		pg = pages[i];
2715 		kunmap(pg);
2716 		SetPageUptodate(pg);
2717 	}
2718 
2719 	return err;
2720 }
2721 
2722 /*
2723  * ni_write_frame
2724  *
2725  * Pages - Array of locked pages.
2726  */
ni_write_frame(struct ntfs_inode * ni,struct page ** pages,u32 pages_per_frame)2727 int ni_write_frame(struct ntfs_inode *ni, struct page **pages,
2728 		   u32 pages_per_frame)
2729 {
2730 	int err;
2731 	struct ntfs_sb_info *sbi = ni->mi.sbi;
2732 	u8 frame_bits = NTFS_LZNT_CUNIT + sbi->cluster_bits;
2733 	u32 frame_size = sbi->cluster_size << NTFS_LZNT_CUNIT;
2734 	u64 frame_vbo = (u64)pages[0]->index << PAGE_SHIFT;
2735 	CLST frame = frame_vbo >> frame_bits;
2736 	char *frame_ondisk = NULL;
2737 	struct page **pages_disk = NULL;
2738 	struct ATTR_LIST_ENTRY *le = NULL;
2739 	char *frame_mem;
2740 	struct ATTRIB *attr;
2741 	struct mft_inode *mi;
2742 	u32 i;
2743 	struct page *pg;
2744 	size_t compr_size, ondisk_size;
2745 	struct lznt *lznt;
2746 
2747 	attr = ni_find_attr(ni, NULL, &le, ATTR_DATA, NULL, 0, NULL, &mi);
2748 	if (!attr) {
2749 		err = -ENOENT;
2750 		goto out;
2751 	}
2752 
2753 	if (WARN_ON(!is_attr_compressed(attr))) {
2754 		err = -EINVAL;
2755 		goto out;
2756 	}
2757 
2758 	if (sbi->cluster_size > NTFS_LZNT_MAX_CLUSTER) {
2759 		err = -EOPNOTSUPP;
2760 		goto out;
2761 	}
2762 
2763 	if (!attr->non_res) {
2764 		down_write(&ni->file.run_lock);
2765 		err = attr_make_nonresident(ni, attr, le, mi,
2766 					    le32_to_cpu(attr->res.data_size),
2767 					    &ni->file.run, &attr, pages[0]);
2768 		up_write(&ni->file.run_lock);
2769 		if (err)
2770 			goto out;
2771 	}
2772 
2773 	if (attr->nres.c_unit != NTFS_LZNT_CUNIT) {
2774 		err = -EOPNOTSUPP;
2775 		goto out;
2776 	}
2777 
2778 	pages_disk = kcalloc(pages_per_frame, sizeof(struct page *), GFP_NOFS);
2779 	if (!pages_disk) {
2780 		err = -ENOMEM;
2781 		goto out;
2782 	}
2783 
2784 	for (i = 0; i < pages_per_frame; i++) {
2785 		pg = alloc_page(GFP_KERNEL);
2786 		if (!pg) {
2787 			err = -ENOMEM;
2788 			goto out1;
2789 		}
2790 		pages_disk[i] = pg;
2791 		lock_page(pg);
2792 		kmap(pg);
2793 	}
2794 
2795 	/* To simplify compress algorithm do vmap for source and target pages. */
2796 	frame_ondisk = vmap(pages_disk, pages_per_frame, VM_MAP, PAGE_KERNEL);
2797 	if (!frame_ondisk) {
2798 		err = -ENOMEM;
2799 		goto out1;
2800 	}
2801 
2802 	for (i = 0; i < pages_per_frame; i++)
2803 		kmap(pages[i]);
2804 
2805 	/* Map in-memory frame for read-only. */
2806 	frame_mem = vmap(pages, pages_per_frame, VM_MAP, PAGE_KERNEL_RO);
2807 	if (!frame_mem) {
2808 		err = -ENOMEM;
2809 		goto out2;
2810 	}
2811 
2812 	mutex_lock(&sbi->compress.mtx_lznt);
2813 	lznt = NULL;
2814 	if (!sbi->compress.lznt) {
2815 		/*
2816 		 * LZNT implements two levels of compression:
2817 		 * 0 - Standard compression
2818 		 * 1 - Best compression, requires a lot of cpu
2819 		 * use mount option?
2820 		 */
2821 		lznt = get_lznt_ctx(0);
2822 		if (!lznt) {
2823 			mutex_unlock(&sbi->compress.mtx_lznt);
2824 			err = -ENOMEM;
2825 			goto out3;
2826 		}
2827 
2828 		sbi->compress.lznt = lznt;
2829 		lznt = NULL;
2830 	}
2831 
2832 	/* Compress: frame_mem -> frame_ondisk */
2833 	compr_size = compress_lznt(frame_mem, frame_size, frame_ondisk,
2834 				   frame_size, sbi->compress.lznt);
2835 	mutex_unlock(&sbi->compress.mtx_lznt);
2836 	kfree(lznt);
2837 
2838 	if (compr_size + sbi->cluster_size > frame_size) {
2839 		/* Frame is not compressed. */
2840 		compr_size = frame_size;
2841 		ondisk_size = frame_size;
2842 	} else if (compr_size) {
2843 		/* Frame is compressed. */
2844 		ondisk_size = ntfs_up_cluster(sbi, compr_size);
2845 		memset(frame_ondisk + compr_size, 0, ondisk_size - compr_size);
2846 	} else {
2847 		/* Frame is sparsed. */
2848 		ondisk_size = 0;
2849 	}
2850 
2851 	down_write(&ni->file.run_lock);
2852 	run_truncate_around(&ni->file.run, le64_to_cpu(attr->nres.svcn));
2853 	err = attr_allocate_frame(ni, frame, compr_size, ni->i_valid);
2854 	up_write(&ni->file.run_lock);
2855 	if (err)
2856 		goto out2;
2857 
2858 	if (!ondisk_size)
2859 		goto out2;
2860 
2861 	down_read(&ni->file.run_lock);
2862 	err = ntfs_bio_pages(sbi, &ni->file.run,
2863 			     ondisk_size < frame_size ? pages_disk : pages,
2864 			     pages_per_frame, frame_vbo, ondisk_size,
2865 			     REQ_OP_WRITE);
2866 	up_read(&ni->file.run_lock);
2867 
2868 out3:
2869 	vunmap(frame_mem);
2870 
2871 out2:
2872 	for (i = 0; i < pages_per_frame; i++)
2873 		kunmap(pages[i]);
2874 
2875 	vunmap(frame_ondisk);
2876 out1:
2877 	for (i = 0; i < pages_per_frame; i++) {
2878 		pg = pages_disk[i];
2879 		if (pg) {
2880 			kunmap(pg);
2881 			unlock_page(pg);
2882 			put_page(pg);
2883 		}
2884 	}
2885 	kfree(pages_disk);
2886 out:
2887 	return err;
2888 }
2889 
2890 /*
2891  * ni_remove_name - Removes name 'de' from MFT and from directory.
2892  * 'de2' and 'undo_step' are used to restore MFT/dir, if error occurs.
2893  */
ni_remove_name(struct ntfs_inode * dir_ni,struct ntfs_inode * ni,struct NTFS_DE * de,struct NTFS_DE ** de2,int * undo_step)2894 int ni_remove_name(struct ntfs_inode *dir_ni, struct ntfs_inode *ni,
2895 		   struct NTFS_DE *de, struct NTFS_DE **de2, int *undo_step)
2896 {
2897 	int err;
2898 	struct ntfs_sb_info *sbi = ni->mi.sbi;
2899 	struct ATTR_FILE_NAME *de_name = (struct ATTR_FILE_NAME *)(de + 1);
2900 	struct ATTR_FILE_NAME *fname;
2901 	struct ATTR_LIST_ENTRY *le;
2902 	struct mft_inode *mi;
2903 	u16 de_key_size = le16_to_cpu(de->key_size);
2904 	u8 name_type;
2905 
2906 	*undo_step = 0;
2907 
2908 	/* Find name in record. */
2909 	mi_get_ref(&dir_ni->mi, &de_name->home);
2910 
2911 	fname = ni_fname_name(ni, (struct le_str *)&de_name->name_len,
2912 			      &de_name->home, &mi, &le);
2913 	if (!fname)
2914 		return -ENOENT;
2915 
2916 	memcpy(&de_name->dup, &fname->dup, sizeof(struct NTFS_DUP_INFO));
2917 	name_type = paired_name(fname->type);
2918 
2919 	/* Mark ntfs as dirty. It will be cleared at umount. */
2920 	ntfs_set_state(sbi, NTFS_DIRTY_DIRTY);
2921 
2922 	/* Step 1: Remove name from directory. */
2923 	err = indx_delete_entry(&dir_ni->dir, dir_ni, fname, de_key_size, sbi);
2924 	if (err)
2925 		return err;
2926 
2927 	/* Step 2: Remove name from MFT. */
2928 	ni_remove_attr_le(ni, attr_from_name(fname), mi, le);
2929 
2930 	*undo_step = 2;
2931 
2932 	/* Get paired name. */
2933 	fname = ni_fname_type(ni, name_type, &mi, &le);
2934 	if (fname) {
2935 		u16 de2_key_size = fname_full_size(fname);
2936 
2937 		*de2 = Add2Ptr(de, 1024);
2938 		(*de2)->key_size = cpu_to_le16(de2_key_size);
2939 
2940 		memcpy(*de2 + 1, fname, de2_key_size);
2941 
2942 		/* Step 3: Remove paired name from directory. */
2943 		err = indx_delete_entry(&dir_ni->dir, dir_ni, fname,
2944 					de2_key_size, sbi);
2945 		if (err)
2946 			return err;
2947 
2948 		/* Step 4: Remove paired name from MFT. */
2949 		ni_remove_attr_le(ni, attr_from_name(fname), mi, le);
2950 
2951 		*undo_step = 4;
2952 	}
2953 	return 0;
2954 }
2955 
2956 /*
2957  * ni_remove_name_undo - Paired function for ni_remove_name.
2958  *
2959  * Return: True if ok
2960  */
ni_remove_name_undo(struct ntfs_inode * dir_ni,struct ntfs_inode * ni,struct NTFS_DE * de,struct NTFS_DE * de2,int undo_step)2961 bool ni_remove_name_undo(struct ntfs_inode *dir_ni, struct ntfs_inode *ni,
2962 			 struct NTFS_DE *de, struct NTFS_DE *de2, int undo_step)
2963 {
2964 	struct ntfs_sb_info *sbi = ni->mi.sbi;
2965 	struct ATTRIB *attr;
2966 	u16 de_key_size;
2967 
2968 	switch (undo_step) {
2969 	case 4:
2970 		de_key_size = le16_to_cpu(de2->key_size);
2971 		if (ni_insert_resident(ni, de_key_size, ATTR_NAME, NULL, 0,
2972 				       &attr, NULL, NULL))
2973 			return false;
2974 		memcpy(Add2Ptr(attr, SIZEOF_RESIDENT), de2 + 1, de_key_size);
2975 
2976 		mi_get_ref(&ni->mi, &de2->ref);
2977 		de2->size = cpu_to_le16(ALIGN(de_key_size, 8) +
2978 					sizeof(struct NTFS_DE));
2979 		de2->flags = 0;
2980 		de2->res = 0;
2981 
2982 		if (indx_insert_entry(&dir_ni->dir, dir_ni, de2, sbi, NULL, 1))
2983 			return false;
2984 		fallthrough;
2985 
2986 	case 2:
2987 		de_key_size = le16_to_cpu(de->key_size);
2988 
2989 		if (ni_insert_resident(ni, de_key_size, ATTR_NAME, NULL, 0,
2990 				       &attr, NULL, NULL))
2991 			return false;
2992 
2993 		memcpy(Add2Ptr(attr, SIZEOF_RESIDENT), de + 1, de_key_size);
2994 		mi_get_ref(&ni->mi, &de->ref);
2995 
2996 		if (indx_insert_entry(&dir_ni->dir, dir_ni, de, sbi, NULL, 1))
2997 			return false;
2998 	}
2999 
3000 	return true;
3001 }
3002 
3003 /*
3004  * ni_add_name - Add new name into MFT and into directory.
3005  */
ni_add_name(struct ntfs_inode * dir_ni,struct ntfs_inode * ni,struct NTFS_DE * de)3006 int ni_add_name(struct ntfs_inode *dir_ni, struct ntfs_inode *ni,
3007 		struct NTFS_DE *de)
3008 {
3009 	int err;
3010 	struct ntfs_sb_info *sbi = ni->mi.sbi;
3011 	struct ATTRIB *attr;
3012 	struct ATTR_LIST_ENTRY *le;
3013 	struct mft_inode *mi;
3014 	struct ATTR_FILE_NAME *fname;
3015 	struct ATTR_FILE_NAME *de_name = (struct ATTR_FILE_NAME *)(de + 1);
3016 	u16 de_key_size = le16_to_cpu(de->key_size);
3017 
3018 	if (sbi->options->windows_names &&
3019 	    !valid_windows_name(sbi, (struct le_str *)&de_name->name_len))
3020 		return -EINVAL;
3021 
3022 	/* If option "hide_dot_files" then set hidden attribute for dot files. */
3023 	if (ni->mi.sbi->options->hide_dot_files) {
3024 		if (de_name->name_len > 0 &&
3025 		    le16_to_cpu(de_name->name[0]) == '.')
3026 			ni->std_fa |= FILE_ATTRIBUTE_HIDDEN;
3027 		else
3028 			ni->std_fa &= ~FILE_ATTRIBUTE_HIDDEN;
3029 	}
3030 
3031 	mi_get_ref(&ni->mi, &de->ref);
3032 	mi_get_ref(&dir_ni->mi, &de_name->home);
3033 
3034 	/* Fill duplicate from any ATTR_NAME. */
3035 	fname = ni_fname_name(ni, NULL, NULL, NULL, NULL);
3036 	if (fname)
3037 		memcpy(&de_name->dup, &fname->dup, sizeof(fname->dup));
3038 	de_name->dup.fa = ni->std_fa;
3039 
3040 	/* Insert new name into MFT. */
3041 	err = ni_insert_resident(ni, de_key_size, ATTR_NAME, NULL, 0, &attr,
3042 				 &mi, &le);
3043 	if (err)
3044 		return err;
3045 
3046 	memcpy(Add2Ptr(attr, SIZEOF_RESIDENT), de_name, de_key_size);
3047 
3048 	/* Insert new name into directory. */
3049 	err = indx_insert_entry(&dir_ni->dir, dir_ni, de, sbi, NULL, 0);
3050 	if (err)
3051 		ni_remove_attr_le(ni, attr, mi, le);
3052 
3053 	return err;
3054 }
3055 
3056 /*
3057  * ni_rename - Remove one name and insert new name.
3058  */
ni_rename(struct ntfs_inode * dir_ni,struct ntfs_inode * new_dir_ni,struct ntfs_inode * ni,struct NTFS_DE * de,struct NTFS_DE * new_de)3059 int ni_rename(struct ntfs_inode *dir_ni, struct ntfs_inode *new_dir_ni,
3060 	      struct ntfs_inode *ni, struct NTFS_DE *de, struct NTFS_DE *new_de)
3061 {
3062 	int err;
3063 	struct NTFS_DE *de2 = NULL;
3064 	int undo = 0;
3065 
3066 	/*
3067 	 * There are two possible ways to rename:
3068 	 * 1) Add new name and remove old name.
3069 	 * 2) Remove old name and add new name.
3070 	 *
3071 	 * In most cases (not all!) adding new name into MFT and into directory can
3072 	 * allocate additional cluster(s).
3073 	 * Second way may result to bad inode if we can't add new name
3074 	 * and then can't restore (add) old name.
3075 	 */
3076 
3077 	/*
3078 	 * Way 1 - Add new + remove old.
3079 	 */
3080 	err = ni_add_name(new_dir_ni, ni, new_de);
3081 	if (!err) {
3082 		err = ni_remove_name(dir_ni, ni, de, &de2, &undo);
3083 		WARN_ON(err && ni_remove_name(new_dir_ni, ni, new_de, &de2,
3084 			&undo));
3085 	}
3086 
3087 	/*
3088 	 * Way 2 - Remove old + add new.
3089 	 */
3090 	/*
3091 	 *	err = ni_remove_name(dir_ni, ni, de, &de2, &undo);
3092 	 *	if (!err) {
3093 	 *		err = ni_add_name(new_dir_ni, ni, new_de);
3094 	 *		if (err && !ni_remove_name_undo(dir_ni, ni, de, de2, undo))
3095 	 *			*is_bad = true;
3096 	 *	}
3097 	 */
3098 
3099 	return err;
3100 }
3101 
3102 /*
3103  * ni_is_dirty - Return: True if 'ni' requires ni_write_inode.
3104  */
ni_is_dirty(struct inode * inode)3105 bool ni_is_dirty(struct inode *inode)
3106 {
3107 	struct ntfs_inode *ni = ntfs_i(inode);
3108 	struct rb_node *node;
3109 
3110 	if (ni->mi.dirty || ni->attr_list.dirty ||
3111 	    (ni->ni_flags & NI_FLAG_UPDATE_PARENT))
3112 		return true;
3113 
3114 	for (node = rb_first(&ni->mi_tree); node; node = rb_next(node)) {
3115 		if (rb_entry(node, struct mft_inode, node)->dirty)
3116 			return true;
3117 	}
3118 
3119 	return false;
3120 }
3121 
3122 /*
3123  * ni_update_parent
3124  *
3125  * Update duplicate info of ATTR_FILE_NAME in MFT and in parent directories.
3126  */
ni_update_parent(struct ntfs_inode * ni,struct NTFS_DUP_INFO * dup,int sync)3127 static bool ni_update_parent(struct ntfs_inode *ni, struct NTFS_DUP_INFO *dup,
3128 			     int sync)
3129 {
3130 	struct ATTRIB *attr;
3131 	struct mft_inode *mi;
3132 	struct ATTR_LIST_ENTRY *le = NULL;
3133 	struct ntfs_sb_info *sbi = ni->mi.sbi;
3134 	struct super_block *sb = sbi->sb;
3135 	bool re_dirty = false;
3136 
3137 	if (ni->mi.mrec->flags & RECORD_FLAG_DIR) {
3138 		dup->fa |= FILE_ATTRIBUTE_DIRECTORY;
3139 		attr = NULL;
3140 		dup->alloc_size = 0;
3141 		dup->data_size = 0;
3142 	} else {
3143 		dup->fa &= ~FILE_ATTRIBUTE_DIRECTORY;
3144 
3145 		attr = ni_find_attr(ni, NULL, &le, ATTR_DATA, NULL, 0, NULL,
3146 				    &mi);
3147 		if (!attr) {
3148 			dup->alloc_size = dup->data_size = 0;
3149 		} else if (!attr->non_res) {
3150 			u32 data_size = le32_to_cpu(attr->res.data_size);
3151 
3152 			dup->alloc_size = cpu_to_le64(ALIGN(data_size, 8));
3153 			dup->data_size = cpu_to_le64(data_size);
3154 		} else {
3155 			u64 new_valid = ni->i_valid;
3156 			u64 data_size = le64_to_cpu(attr->nres.data_size);
3157 			__le64 valid_le;
3158 
3159 			dup->alloc_size = is_attr_ext(attr) ?
3160 						  attr->nres.total_size :
3161 						  attr->nres.alloc_size;
3162 			dup->data_size = attr->nres.data_size;
3163 
3164 			if (new_valid > data_size)
3165 				new_valid = data_size;
3166 
3167 			valid_le = cpu_to_le64(new_valid);
3168 			if (valid_le != attr->nres.valid_size) {
3169 				attr->nres.valid_size = valid_le;
3170 				mi->dirty = true;
3171 			}
3172 		}
3173 	}
3174 
3175 	/* TODO: Fill reparse info. */
3176 	dup->reparse = 0;
3177 	dup->ea_size = 0;
3178 
3179 	if (ni->ni_flags & NI_FLAG_EA) {
3180 		attr = ni_find_attr(ni, attr, &le, ATTR_EA_INFO, NULL, 0, NULL,
3181 				    NULL);
3182 		if (attr) {
3183 			const struct EA_INFO *info;
3184 
3185 			info = resident_data_ex(attr, sizeof(struct EA_INFO));
3186 			/* If ATTR_EA_INFO exists 'info' can't be NULL. */
3187 			if (info)
3188 				dup->ea_size = info->size_pack;
3189 		}
3190 	}
3191 
3192 	attr = NULL;
3193 	le = NULL;
3194 
3195 	while ((attr = ni_find_attr(ni, attr, &le, ATTR_NAME, NULL, 0, NULL,
3196 				    &mi))) {
3197 		struct inode *dir;
3198 		struct ATTR_FILE_NAME *fname;
3199 
3200 		fname = resident_data_ex(attr, SIZEOF_ATTRIBUTE_FILENAME);
3201 		if (!fname || !memcmp(&fname->dup, dup, sizeof(fname->dup)))
3202 			continue;
3203 
3204 		/* Check simple case when parent inode equals current inode. */
3205 		if (ino_get(&fname->home) == ni->vfs_inode.i_ino) {
3206 			ntfs_set_state(sbi, NTFS_DIRTY_ERROR);
3207 			continue;
3208 		}
3209 
3210 		/* ntfs_iget5 may sleep. */
3211 		dir = ntfs_iget5(sb, &fname->home, NULL);
3212 		if (IS_ERR(dir)) {
3213 			ntfs_inode_warn(
3214 				&ni->vfs_inode,
3215 				"failed to open parent directory r=%lx to update",
3216 				(long)ino_get(&fname->home));
3217 			continue;
3218 		}
3219 
3220 		if (!is_bad_inode(dir)) {
3221 			struct ntfs_inode *dir_ni = ntfs_i(dir);
3222 
3223 			if (!ni_trylock(dir_ni)) {
3224 				re_dirty = true;
3225 			} else {
3226 				indx_update_dup(dir_ni, sbi, fname, dup, sync);
3227 				ni_unlock(dir_ni);
3228 				memcpy(&fname->dup, dup, sizeof(fname->dup));
3229 				mi->dirty = true;
3230 			}
3231 		}
3232 		iput(dir);
3233 	}
3234 
3235 	return re_dirty;
3236 }
3237 
3238 /*
3239  * ni_write_inode - Write MFT base record and all subrecords to disk.
3240  */
ni_write_inode(struct inode * inode,int sync,const char * hint)3241 int ni_write_inode(struct inode *inode, int sync, const char *hint)
3242 {
3243 	int err = 0, err2;
3244 	struct ntfs_inode *ni = ntfs_i(inode);
3245 	struct super_block *sb = inode->i_sb;
3246 	struct ntfs_sb_info *sbi = sb->s_fs_info;
3247 	bool re_dirty = false;
3248 	struct ATTR_STD_INFO *std;
3249 	struct rb_node *node, *next;
3250 	struct NTFS_DUP_INFO dup;
3251 
3252 	if (is_bad_inode(inode) || sb_rdonly(sb))
3253 		return 0;
3254 
3255 	if (unlikely(ntfs3_forced_shutdown(sb)))
3256 		return -EIO;
3257 
3258 	if (!ni_trylock(ni)) {
3259 		/* 'ni' is under modification, skip for now. */
3260 		mark_inode_dirty_sync(inode);
3261 		return 0;
3262 	}
3263 
3264 	if (!ni->mi.mrec)
3265 		goto out;
3266 
3267 	if (is_rec_inuse(ni->mi.mrec) &&
3268 	    !(sbi->flags & NTFS_FLAGS_LOG_REPLAYING) && inode->i_nlink) {
3269 		bool modified = false;
3270 		struct timespec64 ts;
3271 
3272 		/* Update times in standard attribute. */
3273 		std = ni_std(ni);
3274 		if (!std) {
3275 			err = -EINVAL;
3276 			goto out;
3277 		}
3278 
3279 		/* Update the access times if they have changed. */
3280 		ts = inode_get_mtime(inode);
3281 		dup.m_time = kernel2nt(&ts);
3282 		if (std->m_time != dup.m_time) {
3283 			std->m_time = dup.m_time;
3284 			modified = true;
3285 		}
3286 
3287 		ts = inode_get_ctime(inode);
3288 		dup.c_time = kernel2nt(&ts);
3289 		if (std->c_time != dup.c_time) {
3290 			std->c_time = dup.c_time;
3291 			modified = true;
3292 		}
3293 
3294 		ts = inode_get_atime(inode);
3295 		dup.a_time = kernel2nt(&ts);
3296 		if (std->a_time != dup.a_time) {
3297 			std->a_time = dup.a_time;
3298 			modified = true;
3299 		}
3300 
3301 		dup.fa = ni->std_fa;
3302 		if (std->fa != dup.fa) {
3303 			std->fa = dup.fa;
3304 			modified = true;
3305 		}
3306 
3307 		/* std attribute is always in primary MFT record. */
3308 		if (modified)
3309 			ni->mi.dirty = true;
3310 
3311 		if (!ntfs_is_meta_file(sbi, inode->i_ino) &&
3312 		    (modified || (ni->ni_flags & NI_FLAG_UPDATE_PARENT))
3313 		    /* Avoid __wait_on_freeing_inode(inode). */
3314 		    && (sb->s_flags & SB_ACTIVE)) {
3315 			dup.cr_time = std->cr_time;
3316 			/* Not critical if this function fail. */
3317 			re_dirty = ni_update_parent(ni, &dup, sync);
3318 
3319 			if (re_dirty)
3320 				ni->ni_flags |= NI_FLAG_UPDATE_PARENT;
3321 			else
3322 				ni->ni_flags &= ~NI_FLAG_UPDATE_PARENT;
3323 		}
3324 
3325 		/* Update attribute list. */
3326 		if (ni->attr_list.size && ni->attr_list.dirty) {
3327 			if (inode->i_ino != MFT_REC_MFT || sync) {
3328 				err = ni_try_remove_attr_list(ni);
3329 				if (err)
3330 					goto out;
3331 			}
3332 
3333 			err = al_update(ni, sync);
3334 			if (err)
3335 				goto out;
3336 		}
3337 	}
3338 
3339 	for (node = rb_first(&ni->mi_tree); node; node = next) {
3340 		struct mft_inode *mi = rb_entry(node, struct mft_inode, node);
3341 		bool is_empty;
3342 
3343 		next = rb_next(node);
3344 
3345 		if (!mi->dirty)
3346 			continue;
3347 
3348 		is_empty = !mi_enum_attr(mi, NULL);
3349 
3350 		if (is_empty)
3351 			clear_rec_inuse(mi->mrec);
3352 
3353 		err2 = mi_write(mi, sync);
3354 		if (!err && err2)
3355 			err = err2;
3356 
3357 		if (is_empty) {
3358 			ntfs_mark_rec_free(sbi, mi->rno, false);
3359 			rb_erase(node, &ni->mi_tree);
3360 			mi_put(mi);
3361 		}
3362 	}
3363 
3364 	if (ni->mi.dirty) {
3365 		err2 = mi_write(&ni->mi, sync);
3366 		if (!err && err2)
3367 			err = err2;
3368 	}
3369 out:
3370 	ni_unlock(ni);
3371 
3372 	if (err) {
3373 		ntfs_inode_err(inode, "%s failed, %d.", hint, err);
3374 		ntfs_set_state(sbi, NTFS_DIRTY_ERROR);
3375 		return err;
3376 	}
3377 
3378 	if (re_dirty)
3379 		mark_inode_dirty_sync(inode);
3380 
3381 	return 0;
3382 }
3383 
3384 /*
3385  * ni_set_compress
3386  *
3387  * Helper for 'ntfs_fileattr_set'.
3388  * Changes compression for empty files and directories only.
3389  */
ni_set_compress(struct inode * inode,bool compr)3390 int ni_set_compress(struct inode *inode, bool compr)
3391 {
3392 	int err;
3393 	struct ntfs_inode *ni = ntfs_i(inode);
3394 	struct ATTR_STD_INFO *std;
3395 	const char *bad_inode;
3396 
3397 	if (is_compressed(ni) == !!compr)
3398 		return 0;
3399 
3400 	if (is_sparsed(ni)) {
3401 		/* sparse and compress not compatible. */
3402 		return -EOPNOTSUPP;
3403 	}
3404 
3405 	if (!S_ISREG(inode->i_mode) && !S_ISDIR(inode->i_mode)) {
3406 		/*Skip other inodes. (symlink,fifo,...) */
3407 		return -EOPNOTSUPP;
3408 	}
3409 
3410 	bad_inode = NULL;
3411 
3412 	ni_lock(ni);
3413 
3414 	std = ni_std(ni);
3415 	if (!std) {
3416 		bad_inode = "no std";
3417 		goto out;
3418 	}
3419 
3420 	if (S_ISREG(inode->i_mode)) {
3421 		err = attr_set_compress(ni, compr);
3422 		if (err) {
3423 			if (err == -ENOENT) {
3424 				/* Fix on the fly? */
3425 				/* Each file must contain data attribute. */
3426 				bad_inode = "no data attribute";
3427 			}
3428 			goto out;
3429 		}
3430 	}
3431 
3432 	ni->std_fa = std->fa;
3433 	if (compr) {
3434 		std->fa &= ~FILE_ATTRIBUTE_SPARSE_FILE;
3435 		std->fa |= FILE_ATTRIBUTE_COMPRESSED;
3436 	} else {
3437 		std->fa &= ~FILE_ATTRIBUTE_COMPRESSED;
3438 	}
3439 
3440 	if (ni->std_fa != std->fa) {
3441 		ni->std_fa = std->fa;
3442 		ni->mi.dirty = true;
3443 	}
3444 	/* update duplicate information and directory entries in ni_write_inode.*/
3445 	ni->ni_flags |= NI_FLAG_UPDATE_PARENT;
3446 	err = 0;
3447 
3448 out:
3449 	ni_unlock(ni);
3450 	if (bad_inode) {
3451 		ntfs_bad_inode(inode, bad_inode);
3452 		err = -EINVAL;
3453 	}
3454 
3455 	return err;
3456 }
3457