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