fs/ntfs3: Do not use driver own alloc wrappers
[linux-block.git] / fs / ntfs3 / fsntfs.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/blkdev.h>
9 #include <linux/buffer_head.h>
10 #include <linux/fs.h>
11 #include <linux/nls.h>
12
13 #include "debug.h"
14 #include "ntfs.h"
15 #include "ntfs_fs.h"
16
17 // clang-format off
18 const struct cpu_str NAME_MFT = {
19         4, 0, { '$', 'M', 'F', 'T' },
20 };
21 const struct cpu_str NAME_MIRROR = {
22         8, 0, { '$', 'M', 'F', 'T', 'M', 'i', 'r', 'r' },
23 };
24 const struct cpu_str NAME_LOGFILE = {
25         8, 0, { '$', 'L', 'o', 'g', 'F', 'i', 'l', 'e' },
26 };
27 const struct cpu_str NAME_VOLUME = {
28         7, 0, { '$', 'V', 'o', 'l', 'u', 'm', 'e' },
29 };
30 const struct cpu_str NAME_ATTRDEF = {
31         8, 0, { '$', 'A', 't', 't', 'r', 'D', 'e', 'f' },
32 };
33 const struct cpu_str NAME_ROOT = {
34         1, 0, { '.' },
35 };
36 const struct cpu_str NAME_BITMAP = {
37         7, 0, { '$', 'B', 'i', 't', 'm', 'a', 'p' },
38 };
39 const struct cpu_str NAME_BOOT = {
40         5, 0, { '$', 'B', 'o', 'o', 't' },
41 };
42 const struct cpu_str NAME_BADCLUS = {
43         8, 0, { '$', 'B', 'a', 'd', 'C', 'l', 'u', 's' },
44 };
45 const struct cpu_str NAME_QUOTA = {
46         6, 0, { '$', 'Q', 'u', 'o', 't', 'a' },
47 };
48 const struct cpu_str NAME_SECURE = {
49         7, 0, { '$', 'S', 'e', 'c', 'u', 'r', 'e' },
50 };
51 const struct cpu_str NAME_UPCASE = {
52         7, 0, { '$', 'U', 'p', 'C', 'a', 's', 'e' },
53 };
54 const struct cpu_str NAME_EXTEND = {
55         7, 0, { '$', 'E', 'x', 't', 'e', 'n', 'd' },
56 };
57 const struct cpu_str NAME_OBJID = {
58         6, 0, { '$', 'O', 'b', 'j', 'I', 'd' },
59 };
60 const struct cpu_str NAME_REPARSE = {
61         8, 0, { '$', 'R', 'e', 'p', 'a', 'r', 's', 'e' },
62 };
63 const struct cpu_str NAME_USNJRNL = {
64         8, 0, { '$', 'U', 's', 'n', 'J', 'r', 'n', 'l' },
65 };
66 const __le16 BAD_NAME[4] = {
67         cpu_to_le16('$'), cpu_to_le16('B'), cpu_to_le16('a'), cpu_to_le16('d'),
68 };
69 const __le16 I30_NAME[4] = {
70         cpu_to_le16('$'), cpu_to_le16('I'), cpu_to_le16('3'), cpu_to_le16('0'),
71 };
72 const __le16 SII_NAME[4] = {
73         cpu_to_le16('$'), cpu_to_le16('S'), cpu_to_le16('I'), cpu_to_le16('I'),
74 };
75 const __le16 SDH_NAME[4] = {
76         cpu_to_le16('$'), cpu_to_le16('S'), cpu_to_le16('D'), cpu_to_le16('H'),
77 };
78 const __le16 SDS_NAME[4] = {
79         cpu_to_le16('$'), cpu_to_le16('S'), cpu_to_le16('D'), cpu_to_le16('S'),
80 };
81 const __le16 SO_NAME[2] = {
82         cpu_to_le16('$'), cpu_to_le16('O'),
83 };
84 const __le16 SQ_NAME[2] = {
85         cpu_to_le16('$'), cpu_to_le16('Q'),
86 };
87 const __le16 SR_NAME[2] = {
88         cpu_to_le16('$'), cpu_to_le16('R'),
89 };
90
91 #ifdef CONFIG_NTFS3_LZX_XPRESS
92 const __le16 WOF_NAME[17] = {
93         cpu_to_le16('W'), cpu_to_le16('o'), cpu_to_le16('f'), cpu_to_le16('C'),
94         cpu_to_le16('o'), cpu_to_le16('m'), cpu_to_le16('p'), cpu_to_le16('r'),
95         cpu_to_le16('e'), cpu_to_le16('s'), cpu_to_le16('s'), cpu_to_le16('e'),
96         cpu_to_le16('d'), cpu_to_le16('D'), cpu_to_le16('a'), cpu_to_le16('t'),
97         cpu_to_le16('a'),
98 };
99 #endif
100
101 // clang-format on
102
103 /*
104  * ntfs_fix_pre_write
105  *
106  * inserts fixups into 'rhdr' before writing to disk
107  */
108 bool ntfs_fix_pre_write(struct NTFS_RECORD_HEADER *rhdr, size_t bytes)
109 {
110         u16 *fixup, *ptr;
111         u16 sample;
112         u16 fo = le16_to_cpu(rhdr->fix_off);
113         u16 fn = le16_to_cpu(rhdr->fix_num);
114
115         if ((fo & 1) || fo + fn * sizeof(short) > SECTOR_SIZE || !fn-- ||
116             fn * SECTOR_SIZE > bytes) {
117                 return false;
118         }
119
120         /* Get fixup pointer */
121         fixup = Add2Ptr(rhdr, fo);
122
123         if (*fixup >= 0x7FFF)
124                 *fixup = 1;
125         else
126                 *fixup += 1;
127
128         sample = *fixup;
129
130         ptr = Add2Ptr(rhdr, SECTOR_SIZE - sizeof(short));
131
132         while (fn--) {
133                 *++fixup = *ptr;
134                 *ptr = sample;
135                 ptr += SECTOR_SIZE / sizeof(short);
136         }
137         return true;
138 }
139
140 /*
141  * ntfs_fix_post_read
142  *
143  * remove fixups after reading from disk
144  * Returns < 0 if error, 0 if ok, 1 if need to update fixups
145  */
146 int ntfs_fix_post_read(struct NTFS_RECORD_HEADER *rhdr, size_t bytes,
147                        bool simple)
148 {
149         int ret;
150         u16 *fixup, *ptr;
151         u16 sample, fo, fn;
152
153         fo = le16_to_cpu(rhdr->fix_off);
154         fn = simple ? ((bytes >> SECTOR_SHIFT) + 1)
155                     : le16_to_cpu(rhdr->fix_num);
156
157         /* Check errors */
158         if ((fo & 1) || fo + fn * sizeof(short) > SECTOR_SIZE || !fn-- ||
159             fn * SECTOR_SIZE > bytes) {
160                 return -EINVAL; /* native chkntfs returns ok! */
161         }
162
163         /* Get fixup pointer */
164         fixup = Add2Ptr(rhdr, fo);
165         sample = *fixup;
166         ptr = Add2Ptr(rhdr, SECTOR_SIZE - sizeof(short));
167         ret = 0;
168
169         while (fn--) {
170                 /* Test current word */
171                 if (*ptr != sample) {
172                         /* Fixup does not match! Is it serious error? */
173                         ret = -E_NTFS_FIXUP;
174                 }
175
176                 /* Replace fixup */
177                 *ptr = *++fixup;
178                 ptr += SECTOR_SIZE / sizeof(short);
179         }
180
181         return ret;
182 }
183
184 /*
185  * ntfs_extend_init
186  *
187  * loads $Extend file
188  */
189 int ntfs_extend_init(struct ntfs_sb_info *sbi)
190 {
191         int err;
192         struct super_block *sb = sbi->sb;
193         struct inode *inode, *inode2;
194         struct MFT_REF ref;
195
196         if (sbi->volume.major_ver < 3) {
197                 ntfs_notice(sb, "Skip $Extend 'cause NTFS version");
198                 return 0;
199         }
200
201         ref.low = cpu_to_le32(MFT_REC_EXTEND);
202         ref.high = 0;
203         ref.seq = cpu_to_le16(MFT_REC_EXTEND);
204         inode = ntfs_iget5(sb, &ref, &NAME_EXTEND);
205         if (IS_ERR(inode)) {
206                 err = PTR_ERR(inode);
207                 ntfs_err(sb, "Failed to load $Extend.");
208                 inode = NULL;
209                 goto out;
210         }
211
212         /* if ntfs_iget5 reads from disk it never returns bad inode */
213         if (!S_ISDIR(inode->i_mode)) {
214                 err = -EINVAL;
215                 goto out;
216         }
217
218         /* Try to find $ObjId */
219         inode2 = dir_search_u(inode, &NAME_OBJID, NULL);
220         if (inode2 && !IS_ERR(inode2)) {
221                 if (is_bad_inode(inode2)) {
222                         iput(inode2);
223                 } else {
224                         sbi->objid.ni = ntfs_i(inode2);
225                         sbi->objid_no = inode2->i_ino;
226                 }
227         }
228
229         /* Try to find $Quota */
230         inode2 = dir_search_u(inode, &NAME_QUOTA, NULL);
231         if (inode2 && !IS_ERR(inode2)) {
232                 sbi->quota_no = inode2->i_ino;
233                 iput(inode2);
234         }
235
236         /* Try to find $Reparse */
237         inode2 = dir_search_u(inode, &NAME_REPARSE, NULL);
238         if (inode2 && !IS_ERR(inode2)) {
239                 sbi->reparse.ni = ntfs_i(inode2);
240                 sbi->reparse_no = inode2->i_ino;
241         }
242
243         /* Try to find $UsnJrnl */
244         inode2 = dir_search_u(inode, &NAME_USNJRNL, NULL);
245         if (inode2 && !IS_ERR(inode2)) {
246                 sbi->usn_jrnl_no = inode2->i_ino;
247                 iput(inode2);
248         }
249
250         err = 0;
251 out:
252         iput(inode);
253         return err;
254 }
255
256 int ntfs_loadlog_and_replay(struct ntfs_inode *ni, struct ntfs_sb_info *sbi)
257 {
258         int err = 0;
259         struct super_block *sb = sbi->sb;
260         bool initialized = false;
261         struct MFT_REF ref;
262         struct inode *inode;
263
264         /* Check for 4GB */
265         if (ni->vfs_inode.i_size >= 0x100000000ull) {
266                 ntfs_err(sb, "\x24LogFile is too big");
267                 err = -EINVAL;
268                 goto out;
269         }
270
271         sbi->flags |= NTFS_FLAGS_LOG_REPLAYING;
272
273         ref.low = cpu_to_le32(MFT_REC_MFT);
274         ref.high = 0;
275         ref.seq = cpu_to_le16(1);
276
277         inode = ntfs_iget5(sb, &ref, NULL);
278
279         if (IS_ERR(inode))
280                 inode = NULL;
281
282         if (!inode) {
283                 /* Try to use mft copy */
284                 u64 t64 = sbi->mft.lbo;
285
286                 sbi->mft.lbo = sbi->mft.lbo2;
287                 inode = ntfs_iget5(sb, &ref, NULL);
288                 sbi->mft.lbo = t64;
289                 if (IS_ERR(inode))
290                         inode = NULL;
291         }
292
293         if (!inode) {
294                 err = -EINVAL;
295                 ntfs_err(sb, "Failed to load $MFT.");
296                 goto out;
297         }
298
299         sbi->mft.ni = ntfs_i(inode);
300
301         /* LogFile should not contains attribute list */
302         err = ni_load_all_mi(sbi->mft.ni);
303         if (!err)
304                 err = log_replay(ni, &initialized);
305
306         iput(inode);
307         sbi->mft.ni = NULL;
308
309         sync_blockdev(sb->s_bdev);
310         invalidate_bdev(sb->s_bdev);
311
312         if (sbi->flags & NTFS_FLAGS_NEED_REPLAY) {
313                 err = 0;
314                 goto out;
315         }
316
317         if (sb_rdonly(sb) || !initialized)
318                 goto out;
319
320         /* fill LogFile by '-1' if it is initialized */
321         err = ntfs_bio_fill_1(sbi, &ni->file.run);
322
323 out:
324         sbi->flags &= ~NTFS_FLAGS_LOG_REPLAYING;
325
326         return err;
327 }
328
329 /*
330  * ntfs_query_def
331  *
332  * returns current ATTR_DEF_ENTRY for given attribute type
333  */
334 const struct ATTR_DEF_ENTRY *ntfs_query_def(struct ntfs_sb_info *sbi,
335                                             enum ATTR_TYPE type)
336 {
337         int type_in = le32_to_cpu(type);
338         size_t min_idx = 0;
339         size_t max_idx = sbi->def_entries - 1;
340
341         while (min_idx <= max_idx) {
342                 size_t i = min_idx + ((max_idx - min_idx) >> 1);
343                 const struct ATTR_DEF_ENTRY *entry = sbi->def_table + i;
344                 int diff = le32_to_cpu(entry->type) - type_in;
345
346                 if (!diff)
347                         return entry;
348                 if (diff < 0)
349                         min_idx = i + 1;
350                 else if (i)
351                         max_idx = i - 1;
352                 else
353                         return NULL;
354         }
355         return NULL;
356 }
357
358 /*
359  * ntfs_look_for_free_space
360  *
361  * looks for a free space in bitmap
362  */
363 int ntfs_look_for_free_space(struct ntfs_sb_info *sbi, CLST lcn, CLST len,
364                              CLST *new_lcn, CLST *new_len,
365                              enum ALLOCATE_OPT opt)
366 {
367         int err;
368         struct super_block *sb = sbi->sb;
369         size_t a_lcn, zlen, zeroes, zlcn, zlen2, ztrim, new_zlen;
370         struct wnd_bitmap *wnd = &sbi->used.bitmap;
371
372         down_write_nested(&wnd->rw_lock, BITMAP_MUTEX_CLUSTERS);
373         if (opt & ALLOCATE_MFT) {
374                 CLST alen;
375
376                 zlen = wnd_zone_len(wnd);
377
378                 if (!zlen) {
379                         err = ntfs_refresh_zone(sbi);
380                         if (err)
381                                 goto out;
382
383                         zlen = wnd_zone_len(wnd);
384
385                         if (!zlen) {
386                                 ntfs_err(sbi->sb,
387                                          "no free space to extend mft");
388                                 err = -ENOSPC;
389                                 goto out;
390                         }
391                 }
392
393                 lcn = wnd_zone_bit(wnd);
394                 alen = zlen > len ? len : zlen;
395
396                 wnd_zone_set(wnd, lcn + alen, zlen - alen);
397
398                 err = wnd_set_used(wnd, lcn, alen);
399                 if (err)
400                         goto out;
401
402                 *new_lcn = lcn;
403                 *new_len = alen;
404                 goto ok;
405         }
406
407         /*
408          * 'Cause cluster 0 is always used this value means that we should use
409          * cached value of 'next_free_lcn' to improve performance
410          */
411         if (!lcn)
412                 lcn = sbi->used.next_free_lcn;
413
414         if (lcn >= wnd->nbits)
415                 lcn = 0;
416
417         *new_len = wnd_find(wnd, len, lcn, BITMAP_FIND_MARK_AS_USED, &a_lcn);
418         if (*new_len) {
419                 *new_lcn = a_lcn;
420                 goto ok;
421         }
422
423         /* Try to use clusters from MftZone */
424         zlen = wnd_zone_len(wnd);
425         zeroes = wnd_zeroes(wnd);
426
427         /* Check too big request */
428         if (len > zeroes + zlen)
429                 goto no_space;
430
431         if (zlen <= NTFS_MIN_MFT_ZONE)
432                 goto no_space;
433
434         /* How many clusters to cat from zone */
435         zlcn = wnd_zone_bit(wnd);
436         zlen2 = zlen >> 1;
437         ztrim = len > zlen ? zlen : (len > zlen2 ? len : zlen2);
438         new_zlen = zlen - ztrim;
439
440         if (new_zlen < NTFS_MIN_MFT_ZONE) {
441                 new_zlen = NTFS_MIN_MFT_ZONE;
442                 if (new_zlen > zlen)
443                         new_zlen = zlen;
444         }
445
446         wnd_zone_set(wnd, zlcn, new_zlen);
447
448         /* allocate continues clusters */
449         *new_len =
450                 wnd_find(wnd, len, 0,
451                          BITMAP_FIND_MARK_AS_USED | BITMAP_FIND_FULL, &a_lcn);
452         if (*new_len) {
453                 *new_lcn = a_lcn;
454                 goto ok;
455         }
456
457 no_space:
458         up_write(&wnd->rw_lock);
459
460         return -ENOSPC;
461
462 ok:
463         err = 0;
464
465         ntfs_unmap_meta(sb, *new_lcn, *new_len);
466
467         if (opt & ALLOCATE_MFT)
468                 goto out;
469
470         /* Set hint for next requests */
471         sbi->used.next_free_lcn = *new_lcn + *new_len;
472
473 out:
474         up_write(&wnd->rw_lock);
475         return err;
476 }
477
478 /*
479  * ntfs_extend_mft
480  *
481  * allocates additional MFT records
482  * sbi->mft.bitmap is locked for write
483  *
484  * NOTE: recursive:
485  *      ntfs_look_free_mft ->
486  *      ntfs_extend_mft ->
487  *      attr_set_size ->
488  *      ni_insert_nonresident ->
489  *      ni_insert_attr ->
490  *      ni_ins_attr_ext ->
491  *      ntfs_look_free_mft ->
492  *      ntfs_extend_mft
493  * To avoid recursive always allocate space for two new mft records
494  * see attrib.c: "at least two mft to avoid recursive loop"
495  */
496 static int ntfs_extend_mft(struct ntfs_sb_info *sbi)
497 {
498         int err;
499         struct ntfs_inode *ni = sbi->mft.ni;
500         size_t new_mft_total;
501         u64 new_mft_bytes, new_bitmap_bytes;
502         struct ATTRIB *attr;
503         struct wnd_bitmap *wnd = &sbi->mft.bitmap;
504
505         new_mft_total = (wnd->nbits + MFT_INCREASE_CHUNK + 127) & (CLST)~127;
506         new_mft_bytes = (u64)new_mft_total << sbi->record_bits;
507
508         /* Step 1: Resize $MFT::DATA */
509         down_write(&ni->file.run_lock);
510         err = attr_set_size(ni, ATTR_DATA, NULL, 0, &ni->file.run,
511                             new_mft_bytes, NULL, false, &attr);
512
513         if (err) {
514                 up_write(&ni->file.run_lock);
515                 goto out;
516         }
517
518         attr->nres.valid_size = attr->nres.data_size;
519         new_mft_total = le64_to_cpu(attr->nres.alloc_size) >> sbi->record_bits;
520         ni->mi.dirty = true;
521
522         /* Step 2: Resize $MFT::BITMAP */
523         new_bitmap_bytes = bitmap_size(new_mft_total);
524
525         err = attr_set_size(ni, ATTR_BITMAP, NULL, 0, &sbi->mft.bitmap.run,
526                             new_bitmap_bytes, &new_bitmap_bytes, true, NULL);
527
528         /* Refresh Mft Zone if necessary */
529         down_write_nested(&sbi->used.bitmap.rw_lock, BITMAP_MUTEX_CLUSTERS);
530
531         ntfs_refresh_zone(sbi);
532
533         up_write(&sbi->used.bitmap.rw_lock);
534         up_write(&ni->file.run_lock);
535
536         if (err)
537                 goto out;
538
539         err = wnd_extend(wnd, new_mft_total);
540
541         if (err)
542                 goto out;
543
544         ntfs_clear_mft_tail(sbi, sbi->mft.used, new_mft_total);
545
546         err = _ni_write_inode(&ni->vfs_inode, 0);
547 out:
548         return err;
549 }
550
551 /*
552  * ntfs_look_free_mft
553  *
554  * looks for a free MFT record
555  */
556 int ntfs_look_free_mft(struct ntfs_sb_info *sbi, CLST *rno, bool mft,
557                        struct ntfs_inode *ni, struct mft_inode **mi)
558 {
559         int err = 0;
560         size_t zbit, zlen, from, to, fr;
561         size_t mft_total;
562         struct MFT_REF ref;
563         struct super_block *sb = sbi->sb;
564         struct wnd_bitmap *wnd = &sbi->mft.bitmap;
565         u32 ir;
566
567         static_assert(sizeof(sbi->mft.reserved_bitmap) * 8 >=
568                       MFT_REC_FREE - MFT_REC_RESERVED);
569
570         if (!mft)
571                 down_write_nested(&wnd->rw_lock, BITMAP_MUTEX_MFT);
572
573         zlen = wnd_zone_len(wnd);
574
575         /* Always reserve space for MFT */
576         if (zlen) {
577                 if (mft) {
578                         zbit = wnd_zone_bit(wnd);
579                         *rno = zbit;
580                         wnd_zone_set(wnd, zbit + 1, zlen - 1);
581                 }
582                 goto found;
583         }
584
585         /* No MFT zone. find the nearest to '0' free MFT */
586         if (!wnd_find(wnd, 1, MFT_REC_FREE, 0, &zbit)) {
587                 /* Resize MFT */
588                 mft_total = wnd->nbits;
589
590                 err = ntfs_extend_mft(sbi);
591                 if (!err) {
592                         zbit = mft_total;
593                         goto reserve_mft;
594                 }
595
596                 if (!mft || MFT_REC_FREE == sbi->mft.next_reserved)
597                         goto out;
598
599                 err = 0;
600
601                 /*
602                  * Look for free record reserved area [11-16) ==
603                  * [MFT_REC_RESERVED, MFT_REC_FREE ) MFT bitmap always
604                  * marks it as used
605                  */
606                 if (!sbi->mft.reserved_bitmap) {
607                         /* Once per session create internal bitmap for 5 bits */
608                         sbi->mft.reserved_bitmap = 0xFF;
609
610                         ref.high = 0;
611                         for (ir = MFT_REC_RESERVED; ir < MFT_REC_FREE; ir++) {
612                                 struct inode *i;
613                                 struct ntfs_inode *ni;
614                                 struct MFT_REC *mrec;
615
616                                 ref.low = cpu_to_le32(ir);
617                                 ref.seq = cpu_to_le16(ir);
618
619                                 i = ntfs_iget5(sb, &ref, NULL);
620                                 if (IS_ERR(i)) {
621 next:
622                                         ntfs_notice(
623                                                 sb,
624                                                 "Invalid reserved record %x",
625                                                 ref.low);
626                                         continue;
627                                 }
628                                 if (is_bad_inode(i)) {
629                                         iput(i);
630                                         goto next;
631                                 }
632
633                                 ni = ntfs_i(i);
634
635                                 mrec = ni->mi.mrec;
636
637                                 if (!is_rec_base(mrec))
638                                         goto next;
639
640                                 if (mrec->hard_links)
641                                         goto next;
642
643                                 if (!ni_std(ni))
644                                         goto next;
645
646                                 if (ni_find_attr(ni, NULL, NULL, ATTR_NAME,
647                                                  NULL, 0, NULL, NULL))
648                                         goto next;
649
650                                 __clear_bit(ir - MFT_REC_RESERVED,
651                                             &sbi->mft.reserved_bitmap);
652                         }
653                 }
654
655                 /* Scan 5 bits for zero. Bit 0 == MFT_REC_RESERVED */
656                 zbit = find_next_zero_bit(&sbi->mft.reserved_bitmap,
657                                           MFT_REC_FREE, MFT_REC_RESERVED);
658                 if (zbit >= MFT_REC_FREE) {
659                         sbi->mft.next_reserved = MFT_REC_FREE;
660                         goto out;
661                 }
662
663                 zlen = 1;
664                 sbi->mft.next_reserved = zbit;
665         } else {
666 reserve_mft:
667                 zlen = zbit == MFT_REC_FREE ? (MFT_REC_USER - MFT_REC_FREE) : 4;
668                 if (zbit + zlen > wnd->nbits)
669                         zlen = wnd->nbits - zbit;
670
671                 while (zlen > 1 && !wnd_is_free(wnd, zbit, zlen))
672                         zlen -= 1;
673
674                 /* [zbit, zbit + zlen) will be used for Mft itself */
675                 from = sbi->mft.used;
676                 if (from < zbit)
677                         from = zbit;
678                 to = zbit + zlen;
679                 if (from < to) {
680                         ntfs_clear_mft_tail(sbi, from, to);
681                         sbi->mft.used = to;
682                 }
683         }
684
685         if (mft) {
686                 *rno = zbit;
687                 zbit += 1;
688                 zlen -= 1;
689         }
690
691         wnd_zone_set(wnd, zbit, zlen);
692
693 found:
694         if (!mft) {
695                 /* The request to get record for general purpose */
696                 if (sbi->mft.next_free < MFT_REC_USER)
697                         sbi->mft.next_free = MFT_REC_USER;
698
699                 for (;;) {
700                         if (sbi->mft.next_free >= sbi->mft.bitmap.nbits) {
701                         } else if (!wnd_find(wnd, 1, MFT_REC_USER, 0, &fr)) {
702                                 sbi->mft.next_free = sbi->mft.bitmap.nbits;
703                         } else {
704                                 *rno = fr;
705                                 sbi->mft.next_free = *rno + 1;
706                                 break;
707                         }
708
709                         err = ntfs_extend_mft(sbi);
710                         if (err)
711                                 goto out;
712                 }
713         }
714
715         if (ni && !ni_add_subrecord(ni, *rno, mi)) {
716                 err = -ENOMEM;
717                 goto out;
718         }
719
720         /* We have found a record that are not reserved for next MFT */
721         if (*rno >= MFT_REC_FREE)
722                 wnd_set_used(wnd, *rno, 1);
723         else if (*rno >= MFT_REC_RESERVED && sbi->mft.reserved_bitmap_inited)
724                 __set_bit(*rno - MFT_REC_RESERVED, &sbi->mft.reserved_bitmap);
725
726 out:
727         if (!mft)
728                 up_write(&wnd->rw_lock);
729
730         return err;
731 }
732
733 /*
734  * ntfs_mark_rec_free
735  *
736  * marks record as free
737  */
738 void ntfs_mark_rec_free(struct ntfs_sb_info *sbi, CLST rno)
739 {
740         struct wnd_bitmap *wnd = &sbi->mft.bitmap;
741
742         down_write_nested(&wnd->rw_lock, BITMAP_MUTEX_MFT);
743         if (rno >= wnd->nbits)
744                 goto out;
745
746         if (rno >= MFT_REC_FREE) {
747                 if (!wnd_is_used(wnd, rno, 1))
748                         ntfs_set_state(sbi, NTFS_DIRTY_ERROR);
749                 else
750                         wnd_set_free(wnd, rno, 1);
751         } else if (rno >= MFT_REC_RESERVED && sbi->mft.reserved_bitmap_inited) {
752                 __clear_bit(rno - MFT_REC_RESERVED, &sbi->mft.reserved_bitmap);
753         }
754
755         if (rno < wnd_zone_bit(wnd))
756                 wnd_zone_set(wnd, rno, 1);
757         else if (rno < sbi->mft.next_free && rno >= MFT_REC_USER)
758                 sbi->mft.next_free = rno;
759
760 out:
761         up_write(&wnd->rw_lock);
762 }
763
764 /*
765  * ntfs_clear_mft_tail
766  *
767  * formats empty records [from, to)
768  * sbi->mft.bitmap is locked for write
769  */
770 int ntfs_clear_mft_tail(struct ntfs_sb_info *sbi, size_t from, size_t to)
771 {
772         int err;
773         u32 rs;
774         u64 vbo;
775         struct runs_tree *run;
776         struct ntfs_inode *ni;
777
778         if (from >= to)
779                 return 0;
780
781         rs = sbi->record_size;
782         ni = sbi->mft.ni;
783         run = &ni->file.run;
784
785         down_read(&ni->file.run_lock);
786         vbo = (u64)from * rs;
787         for (; from < to; from++, vbo += rs) {
788                 struct ntfs_buffers nb;
789
790                 err = ntfs_get_bh(sbi, run, vbo, rs, &nb);
791                 if (err)
792                         goto out;
793
794                 err = ntfs_write_bh(sbi, &sbi->new_rec->rhdr, &nb, 0);
795                 nb_put(&nb);
796                 if (err)
797                         goto out;
798         }
799
800 out:
801         sbi->mft.used = from;
802         up_read(&ni->file.run_lock);
803         return err;
804 }
805
806 /*
807  * ntfs_refresh_zone
808  *
809  * refreshes Mft zone
810  * sbi->used.bitmap is locked for rw
811  * sbi->mft.bitmap is locked for write
812  * sbi->mft.ni->file.run_lock for write
813  */
814 int ntfs_refresh_zone(struct ntfs_sb_info *sbi)
815 {
816         CLST zone_limit, zone_max, lcn, vcn, len;
817         size_t lcn_s, zlen;
818         struct wnd_bitmap *wnd = &sbi->used.bitmap;
819         struct ntfs_inode *ni = sbi->mft.ni;
820
821         /* Do not change anything unless we have non empty Mft zone */
822         if (wnd_zone_len(wnd))
823                 return 0;
824
825         /*
826          * Compute the mft zone at two steps
827          * It would be nice if we are able to allocate
828          * 1/8 of total clusters for MFT but not more then 512 MB
829          */
830         zone_limit = (512 * 1024 * 1024) >> sbi->cluster_bits;
831         zone_max = wnd->nbits >> 3;
832         if (zone_max > zone_limit)
833                 zone_max = zone_limit;
834
835         vcn = bytes_to_cluster(sbi,
836                                (u64)sbi->mft.bitmap.nbits << sbi->record_bits);
837
838         if (!run_lookup_entry(&ni->file.run, vcn - 1, &lcn, &len, NULL))
839                 lcn = SPARSE_LCN;
840
841         /* We should always find Last Lcn for MFT */
842         if (lcn == SPARSE_LCN)
843                 return -EINVAL;
844
845         lcn_s = lcn + 1;
846
847         /* Try to allocate clusters after last MFT run */
848         zlen = wnd_find(wnd, zone_max, lcn_s, 0, &lcn_s);
849         if (!zlen) {
850                 ntfs_notice(sbi->sb, "MftZone: unavailable");
851                 return 0;
852         }
853
854         /* Truncate too large zone */
855         wnd_zone_set(wnd, lcn_s, zlen);
856
857         return 0;
858 }
859
860 /*
861  * ntfs_update_mftmirr
862  *
863  * updates $MFTMirr data
864  */
865 int ntfs_update_mftmirr(struct ntfs_sb_info *sbi, int wait)
866 {
867         int err;
868         struct super_block *sb = sbi->sb;
869         u32 blocksize = sb->s_blocksize;
870         sector_t block1, block2;
871         u32 bytes;
872
873         if (!(sbi->flags & NTFS_FLAGS_MFTMIRR))
874                 return 0;
875
876         err = 0;
877         bytes = sbi->mft.recs_mirr << sbi->record_bits;
878         block1 = sbi->mft.lbo >> sb->s_blocksize_bits;
879         block2 = sbi->mft.lbo2 >> sb->s_blocksize_bits;
880
881         for (; bytes >= blocksize; bytes -= blocksize) {
882                 struct buffer_head *bh1, *bh2;
883
884                 bh1 = sb_bread(sb, block1++);
885                 if (!bh1) {
886                         err = -EIO;
887                         goto out;
888                 }
889
890                 bh2 = sb_getblk(sb, block2++);
891                 if (!bh2) {
892                         put_bh(bh1);
893                         err = -EIO;
894                         goto out;
895                 }
896
897                 if (buffer_locked(bh2))
898                         __wait_on_buffer(bh2);
899
900                 lock_buffer(bh2);
901                 memcpy(bh2->b_data, bh1->b_data, blocksize);
902                 set_buffer_uptodate(bh2);
903                 mark_buffer_dirty(bh2);
904                 unlock_buffer(bh2);
905
906                 put_bh(bh1);
907                 bh1 = NULL;
908
909                 if (wait)
910                         err = sync_dirty_buffer(bh2);
911
912                 put_bh(bh2);
913                 if (err)
914                         goto out;
915         }
916
917         sbi->flags &= ~NTFS_FLAGS_MFTMIRR;
918
919 out:
920         return err;
921 }
922
923 /*
924  * ntfs_set_state
925  *
926  * mount: ntfs_set_state(NTFS_DIRTY_DIRTY)
927  * umount: ntfs_set_state(NTFS_DIRTY_CLEAR)
928  * ntfs error: ntfs_set_state(NTFS_DIRTY_ERROR)
929  */
930 int ntfs_set_state(struct ntfs_sb_info *sbi, enum NTFS_DIRTY_FLAGS dirty)
931 {
932         int err;
933         struct ATTRIB *attr;
934         struct VOLUME_INFO *info;
935         struct mft_inode *mi;
936         struct ntfs_inode *ni;
937
938         /*
939          * do not change state if fs was real_dirty
940          * do not change state if fs already dirty(clear)
941          * do not change any thing if mounted read only
942          */
943         if (sbi->volume.real_dirty || sb_rdonly(sbi->sb))
944                 return 0;
945
946         /* Check cached value */
947         if ((dirty == NTFS_DIRTY_CLEAR ? 0 : VOLUME_FLAG_DIRTY) ==
948             (sbi->volume.flags & VOLUME_FLAG_DIRTY))
949                 return 0;
950
951         ni = sbi->volume.ni;
952         if (!ni)
953                 return -EINVAL;
954
955         mutex_lock_nested(&ni->ni_lock, NTFS_INODE_MUTEX_DIRTY);
956
957         attr = ni_find_attr(ni, NULL, NULL, ATTR_VOL_INFO, NULL, 0, NULL, &mi);
958         if (!attr) {
959                 err = -EINVAL;
960                 goto out;
961         }
962
963         info = resident_data_ex(attr, SIZEOF_ATTRIBUTE_VOLUME_INFO);
964         if (!info) {
965                 err = -EINVAL;
966                 goto out;
967         }
968
969         switch (dirty) {
970         case NTFS_DIRTY_ERROR:
971                 ntfs_notice(sbi->sb, "Mark volume as dirty due to NTFS errors");
972                 sbi->volume.real_dirty = true;
973                 fallthrough;
974         case NTFS_DIRTY_DIRTY:
975                 info->flags |= VOLUME_FLAG_DIRTY;
976                 break;
977         case NTFS_DIRTY_CLEAR:
978                 info->flags &= ~VOLUME_FLAG_DIRTY;
979                 break;
980         }
981         /* cache current volume flags*/
982         sbi->volume.flags = info->flags;
983         mi->dirty = true;
984         err = 0;
985
986 out:
987         ni_unlock(ni);
988         if (err)
989                 return err;
990
991         mark_inode_dirty(&ni->vfs_inode);
992         /*verify(!ntfs_update_mftmirr()); */
993
994         /*
995          * if we used wait=1, sync_inode_metadata waits for the io for the
996          * inode to finish. It hangs when media is removed.
997          * So wait=0 is sent down to sync_inode_metadata
998          * and filemap_fdatawrite is used for the data blocks
999          */
1000         err = sync_inode_metadata(&ni->vfs_inode, 0);
1001         if (!err)
1002                 err = filemap_fdatawrite(ni->vfs_inode.i_mapping);
1003
1004         return err;
1005 }
1006
1007 /*
1008  * security_hash
1009  *
1010  * calculates a hash of security descriptor
1011  */
1012 static inline __le32 security_hash(const void *sd, size_t bytes)
1013 {
1014         u32 hash = 0;
1015         const __le32 *ptr = sd;
1016
1017         bytes >>= 2;
1018         while (bytes--)
1019                 hash = ((hash >> 0x1D) | (hash << 3)) + le32_to_cpu(*ptr++);
1020         return cpu_to_le32(hash);
1021 }
1022
1023 int ntfs_sb_read(struct super_block *sb, u64 lbo, size_t bytes, void *buffer)
1024 {
1025         struct block_device *bdev = sb->s_bdev;
1026         u32 blocksize = sb->s_blocksize;
1027         u64 block = lbo >> sb->s_blocksize_bits;
1028         u32 off = lbo & (blocksize - 1);
1029         u32 op = blocksize - off;
1030
1031         for (; bytes; block += 1, off = 0, op = blocksize) {
1032                 struct buffer_head *bh = __bread(bdev, block, blocksize);
1033
1034                 if (!bh)
1035                         return -EIO;
1036
1037                 if (op > bytes)
1038                         op = bytes;
1039
1040                 memcpy(buffer, bh->b_data + off, op);
1041
1042                 put_bh(bh);
1043
1044                 bytes -= op;
1045                 buffer = Add2Ptr(buffer, op);
1046         }
1047
1048         return 0;
1049 }
1050
1051 int ntfs_sb_write(struct super_block *sb, u64 lbo, size_t bytes,
1052                   const void *buf, int wait)
1053 {
1054         u32 blocksize = sb->s_blocksize;
1055         struct block_device *bdev = sb->s_bdev;
1056         sector_t block = lbo >> sb->s_blocksize_bits;
1057         u32 off = lbo & (blocksize - 1);
1058         u32 op = blocksize - off;
1059         struct buffer_head *bh;
1060
1061         if (!wait && (sb->s_flags & SB_SYNCHRONOUS))
1062                 wait = 1;
1063
1064         for (; bytes; block += 1, off = 0, op = blocksize) {
1065                 if (op > bytes)
1066                         op = bytes;
1067
1068                 if (op < blocksize) {
1069                         bh = __bread(bdev, block, blocksize);
1070                         if (!bh) {
1071                                 ntfs_err(sb, "failed to read block %llx",
1072                                          (u64)block);
1073                                 return -EIO;
1074                         }
1075                 } else {
1076                         bh = __getblk(bdev, block, blocksize);
1077                         if (!bh)
1078                                 return -ENOMEM;
1079                 }
1080
1081                 if (buffer_locked(bh))
1082                         __wait_on_buffer(bh);
1083
1084                 lock_buffer(bh);
1085                 if (buf) {
1086                         memcpy(bh->b_data + off, buf, op);
1087                         buf = Add2Ptr(buf, op);
1088                 } else {
1089                         memset(bh->b_data + off, -1, op);
1090                 }
1091
1092                 set_buffer_uptodate(bh);
1093                 mark_buffer_dirty(bh);
1094                 unlock_buffer(bh);
1095
1096                 if (wait) {
1097                         int err = sync_dirty_buffer(bh);
1098
1099                         if (err) {
1100                                 ntfs_err(
1101                                         sb,
1102                                         "failed to sync buffer at block %llx, error %d",
1103                                         (u64)block, err);
1104                                 put_bh(bh);
1105                                 return err;
1106                         }
1107                 }
1108
1109                 put_bh(bh);
1110
1111                 bytes -= op;
1112         }
1113         return 0;
1114 }
1115
1116 int ntfs_sb_write_run(struct ntfs_sb_info *sbi, const struct runs_tree *run,
1117                       u64 vbo, const void *buf, size_t bytes)
1118 {
1119         struct super_block *sb = sbi->sb;
1120         u8 cluster_bits = sbi->cluster_bits;
1121         u32 off = vbo & sbi->cluster_mask;
1122         CLST lcn, clen, vcn = vbo >> cluster_bits, vcn_next;
1123         u64 lbo, len;
1124         size_t idx;
1125
1126         if (!run_lookup_entry(run, vcn, &lcn, &clen, &idx))
1127                 return -ENOENT;
1128
1129         if (lcn == SPARSE_LCN)
1130                 return -EINVAL;
1131
1132         lbo = ((u64)lcn << cluster_bits) + off;
1133         len = ((u64)clen << cluster_bits) - off;
1134
1135         for (;;) {
1136                 u32 op = len < bytes ? len : bytes;
1137                 int err = ntfs_sb_write(sb, lbo, op, buf, 0);
1138
1139                 if (err)
1140                         return err;
1141
1142                 bytes -= op;
1143                 if (!bytes)
1144                         break;
1145
1146                 vcn_next = vcn + clen;
1147                 if (!run_get_entry(run, ++idx, &vcn, &lcn, &clen) ||
1148                     vcn != vcn_next)
1149                         return -ENOENT;
1150
1151                 if (lcn == SPARSE_LCN)
1152                         return -EINVAL;
1153
1154                 if (buf)
1155                         buf = Add2Ptr(buf, op);
1156
1157                 lbo = ((u64)lcn << cluster_bits);
1158                 len = ((u64)clen << cluster_bits);
1159         }
1160
1161         return 0;
1162 }
1163
1164 struct buffer_head *ntfs_bread_run(struct ntfs_sb_info *sbi,
1165                                    const struct runs_tree *run, u64 vbo)
1166 {
1167         struct super_block *sb = sbi->sb;
1168         u8 cluster_bits = sbi->cluster_bits;
1169         CLST lcn;
1170         u64 lbo;
1171
1172         if (!run_lookup_entry(run, vbo >> cluster_bits, &lcn, NULL, NULL))
1173                 return ERR_PTR(-ENOENT);
1174
1175         lbo = ((u64)lcn << cluster_bits) + (vbo & sbi->cluster_mask);
1176
1177         return ntfs_bread(sb, lbo >> sb->s_blocksize_bits);
1178 }
1179
1180 int ntfs_read_run_nb(struct ntfs_sb_info *sbi, const struct runs_tree *run,
1181                      u64 vbo, void *buf, u32 bytes, struct ntfs_buffers *nb)
1182 {
1183         int err;
1184         struct super_block *sb = sbi->sb;
1185         u32 blocksize = sb->s_blocksize;
1186         u8 cluster_bits = sbi->cluster_bits;
1187         u32 off = vbo & sbi->cluster_mask;
1188         u32 nbh = 0;
1189         CLST vcn_next, vcn = vbo >> cluster_bits;
1190         CLST lcn, clen;
1191         u64 lbo, len;
1192         size_t idx;
1193         struct buffer_head *bh;
1194
1195         if (!run) {
1196                 /* first reading of $Volume + $MFTMirr + LogFile goes here*/
1197                 if (vbo > MFT_REC_VOL * sbi->record_size) {
1198                         err = -ENOENT;
1199                         goto out;
1200                 }
1201
1202                 /* use absolute boot's 'MFTCluster' to read record */
1203                 lbo = vbo + sbi->mft.lbo;
1204                 len = sbi->record_size;
1205         } else if (!run_lookup_entry(run, vcn, &lcn, &clen, &idx)) {
1206                 err = -ENOENT;
1207                 goto out;
1208         } else {
1209                 if (lcn == SPARSE_LCN) {
1210                         err = -EINVAL;
1211                         goto out;
1212                 }
1213
1214                 lbo = ((u64)lcn << cluster_bits) + off;
1215                 len = ((u64)clen << cluster_bits) - off;
1216         }
1217
1218         off = lbo & (blocksize - 1);
1219         if (nb) {
1220                 nb->off = off;
1221                 nb->bytes = bytes;
1222         }
1223
1224         for (;;) {
1225                 u32 len32 = len >= bytes ? bytes : len;
1226                 sector_t block = lbo >> sb->s_blocksize_bits;
1227
1228                 do {
1229                         u32 op = blocksize - off;
1230
1231                         if (op > len32)
1232                                 op = len32;
1233
1234                         bh = ntfs_bread(sb, block);
1235                         if (!bh) {
1236                                 err = -EIO;
1237                                 goto out;
1238                         }
1239
1240                         if (buf) {
1241                                 memcpy(buf, bh->b_data + off, op);
1242                                 buf = Add2Ptr(buf, op);
1243                         }
1244
1245                         if (!nb) {
1246                                 put_bh(bh);
1247                         } else if (nbh >= ARRAY_SIZE(nb->bh)) {
1248                                 err = -EINVAL;
1249                                 goto out;
1250                         } else {
1251                                 nb->bh[nbh++] = bh;
1252                                 nb->nbufs = nbh;
1253                         }
1254
1255                         bytes -= op;
1256                         if (!bytes)
1257                                 return 0;
1258                         len32 -= op;
1259                         block += 1;
1260                         off = 0;
1261
1262                 } while (len32);
1263
1264                 vcn_next = vcn + clen;
1265                 if (!run_get_entry(run, ++idx, &vcn, &lcn, &clen) ||
1266                     vcn != vcn_next) {
1267                         err = -ENOENT;
1268                         goto out;
1269                 }
1270
1271                 if (lcn == SPARSE_LCN) {
1272                         err = -EINVAL;
1273                         goto out;
1274                 }
1275
1276                 lbo = ((u64)lcn << cluster_bits);
1277                 len = ((u64)clen << cluster_bits);
1278         }
1279
1280 out:
1281         if (!nbh)
1282                 return err;
1283
1284         while (nbh) {
1285                 put_bh(nb->bh[--nbh]);
1286                 nb->bh[nbh] = NULL;
1287         }
1288
1289         nb->nbufs = 0;
1290         return err;
1291 }
1292
1293 /* Returns < 0 if error, 0 if ok, '-E_NTFS_FIXUP' if need to update fixups */
1294 int ntfs_read_bh(struct ntfs_sb_info *sbi, const struct runs_tree *run, u64 vbo,
1295                  struct NTFS_RECORD_HEADER *rhdr, u32 bytes,
1296                  struct ntfs_buffers *nb)
1297 {
1298         int err = ntfs_read_run_nb(sbi, run, vbo, rhdr, bytes, nb);
1299
1300         if (err)
1301                 return err;
1302         return ntfs_fix_post_read(rhdr, nb->bytes, true);
1303 }
1304
1305 int ntfs_get_bh(struct ntfs_sb_info *sbi, const struct runs_tree *run, u64 vbo,
1306                 u32 bytes, struct ntfs_buffers *nb)
1307 {
1308         int err = 0;
1309         struct super_block *sb = sbi->sb;
1310         u32 blocksize = sb->s_blocksize;
1311         u8 cluster_bits = sbi->cluster_bits;
1312         CLST vcn_next, vcn = vbo >> cluster_bits;
1313         u32 off;
1314         u32 nbh = 0;
1315         CLST lcn, clen;
1316         u64 lbo, len;
1317         size_t idx;
1318
1319         nb->bytes = bytes;
1320
1321         if (!run_lookup_entry(run, vcn, &lcn, &clen, &idx)) {
1322                 err = -ENOENT;
1323                 goto out;
1324         }
1325
1326         off = vbo & sbi->cluster_mask;
1327         lbo = ((u64)lcn << cluster_bits) + off;
1328         len = ((u64)clen << cluster_bits) - off;
1329
1330         nb->off = off = lbo & (blocksize - 1);
1331
1332         for (;;) {
1333                 u32 len32 = len < bytes ? len : bytes;
1334                 sector_t block = lbo >> sb->s_blocksize_bits;
1335
1336                 do {
1337                         u32 op;
1338                         struct buffer_head *bh;
1339
1340                         if (nbh >= ARRAY_SIZE(nb->bh)) {
1341                                 err = -EINVAL;
1342                                 goto out;
1343                         }
1344
1345                         op = blocksize - off;
1346                         if (op > len32)
1347                                 op = len32;
1348
1349                         if (op == blocksize) {
1350                                 bh = sb_getblk(sb, block);
1351                                 if (!bh) {
1352                                         err = -ENOMEM;
1353                                         goto out;
1354                                 }
1355                                 if (buffer_locked(bh))
1356                                         __wait_on_buffer(bh);
1357                                 set_buffer_uptodate(bh);
1358                         } else {
1359                                 bh = ntfs_bread(sb, block);
1360                                 if (!bh) {
1361                                         err = -EIO;
1362                                         goto out;
1363                                 }
1364                         }
1365
1366                         nb->bh[nbh++] = bh;
1367                         bytes -= op;
1368                         if (!bytes) {
1369                                 nb->nbufs = nbh;
1370                                 return 0;
1371                         }
1372
1373                         block += 1;
1374                         len32 -= op;
1375                         off = 0;
1376                 } while (len32);
1377
1378                 vcn_next = vcn + clen;
1379                 if (!run_get_entry(run, ++idx, &vcn, &lcn, &clen) ||
1380                     vcn != vcn_next) {
1381                         err = -ENOENT;
1382                         goto out;
1383                 }
1384
1385                 lbo = ((u64)lcn << cluster_bits);
1386                 len = ((u64)clen << cluster_bits);
1387         }
1388
1389 out:
1390         while (nbh) {
1391                 put_bh(nb->bh[--nbh]);
1392                 nb->bh[nbh] = NULL;
1393         }
1394
1395         nb->nbufs = 0;
1396
1397         return err;
1398 }
1399
1400 int ntfs_write_bh(struct ntfs_sb_info *sbi, struct NTFS_RECORD_HEADER *rhdr,
1401                   struct ntfs_buffers *nb, int sync)
1402 {
1403         int err = 0;
1404         struct super_block *sb = sbi->sb;
1405         u32 block_size = sb->s_blocksize;
1406         u32 bytes = nb->bytes;
1407         u32 off = nb->off;
1408         u16 fo = le16_to_cpu(rhdr->fix_off);
1409         u16 fn = le16_to_cpu(rhdr->fix_num);
1410         u32 idx;
1411         __le16 *fixup;
1412         __le16 sample;
1413
1414         if ((fo & 1) || fo + fn * sizeof(short) > SECTOR_SIZE || !fn-- ||
1415             fn * SECTOR_SIZE > bytes) {
1416                 return -EINVAL;
1417         }
1418
1419         for (idx = 0; bytes && idx < nb->nbufs; idx += 1, off = 0) {
1420                 u32 op = block_size - off;
1421                 char *bh_data;
1422                 struct buffer_head *bh = nb->bh[idx];
1423                 __le16 *ptr, *end_data;
1424
1425                 if (op > bytes)
1426                         op = bytes;
1427
1428                 if (buffer_locked(bh))
1429                         __wait_on_buffer(bh);
1430
1431                 lock_buffer(nb->bh[idx]);
1432
1433                 bh_data = bh->b_data + off;
1434                 end_data = Add2Ptr(bh_data, op);
1435                 memcpy(bh_data, rhdr, op);
1436
1437                 if (!idx) {
1438                         u16 t16;
1439
1440                         fixup = Add2Ptr(bh_data, fo);
1441                         sample = *fixup;
1442                         t16 = le16_to_cpu(sample);
1443                         if (t16 >= 0x7FFF) {
1444                                 sample = *fixup = cpu_to_le16(1);
1445                         } else {
1446                                 sample = cpu_to_le16(t16 + 1);
1447                                 *fixup = sample;
1448                         }
1449
1450                         *(__le16 *)Add2Ptr(rhdr, fo) = sample;
1451                 }
1452
1453                 ptr = Add2Ptr(bh_data, SECTOR_SIZE - sizeof(short));
1454
1455                 do {
1456                         *++fixup = *ptr;
1457                         *ptr = sample;
1458                         ptr += SECTOR_SIZE / sizeof(short);
1459                 } while (ptr < end_data);
1460
1461                 set_buffer_uptodate(bh);
1462                 mark_buffer_dirty(bh);
1463                 unlock_buffer(bh);
1464
1465                 if (sync) {
1466                         int err2 = sync_dirty_buffer(bh);
1467
1468                         if (!err && err2)
1469                                 err = err2;
1470                 }
1471
1472                 bytes -= op;
1473                 rhdr = Add2Ptr(rhdr, op);
1474         }
1475
1476         return err;
1477 }
1478
1479 static inline struct bio *ntfs_alloc_bio(u32 nr_vecs)
1480 {
1481         struct bio *bio = bio_alloc(GFP_NOFS | __GFP_HIGH, nr_vecs);
1482
1483         if (!bio && (current->flags & PF_MEMALLOC)) {
1484                 while (!bio && (nr_vecs /= 2))
1485                         bio = bio_alloc(GFP_NOFS | __GFP_HIGH, nr_vecs);
1486         }
1487         return bio;
1488 }
1489
1490 /* read/write pages from/to disk*/
1491 int ntfs_bio_pages(struct ntfs_sb_info *sbi, const struct runs_tree *run,
1492                    struct page **pages, u32 nr_pages, u64 vbo, u32 bytes,
1493                    u32 op)
1494 {
1495         int err = 0;
1496         struct bio *new, *bio = NULL;
1497         struct super_block *sb = sbi->sb;
1498         struct block_device *bdev = sb->s_bdev;
1499         struct page *page;
1500         u8 cluster_bits = sbi->cluster_bits;
1501         CLST lcn, clen, vcn, vcn_next;
1502         u32 add, off, page_idx;
1503         u64 lbo, len;
1504         size_t run_idx;
1505         struct blk_plug plug;
1506
1507         if (!bytes)
1508                 return 0;
1509
1510         blk_start_plug(&plug);
1511
1512         /* align vbo and bytes to be 512 bytes aligned */
1513         lbo = (vbo + bytes + 511) & ~511ull;
1514         vbo = vbo & ~511ull;
1515         bytes = lbo - vbo;
1516
1517         vcn = vbo >> cluster_bits;
1518         if (!run_lookup_entry(run, vcn, &lcn, &clen, &run_idx)) {
1519                 err = -ENOENT;
1520                 goto out;
1521         }
1522         off = vbo & sbi->cluster_mask;
1523         page_idx = 0;
1524         page = pages[0];
1525
1526         for (;;) {
1527                 lbo = ((u64)lcn << cluster_bits) + off;
1528                 len = ((u64)clen << cluster_bits) - off;
1529 new_bio:
1530                 new = ntfs_alloc_bio(nr_pages - page_idx);
1531                 if (!new) {
1532                         err = -ENOMEM;
1533                         goto out;
1534                 }
1535                 if (bio) {
1536                         bio_chain(bio, new);
1537                         submit_bio(bio);
1538                 }
1539                 bio = new;
1540                 bio_set_dev(bio, bdev);
1541                 bio->bi_iter.bi_sector = lbo >> 9;
1542                 bio->bi_opf = op;
1543
1544                 while (len) {
1545                         off = vbo & (PAGE_SIZE - 1);
1546                         add = off + len > PAGE_SIZE ? (PAGE_SIZE - off) : len;
1547
1548                         if (bio_add_page(bio, page, add, off) < add)
1549                                 goto new_bio;
1550
1551                         if (bytes <= add)
1552                                 goto out;
1553                         bytes -= add;
1554                         vbo += add;
1555
1556                         if (add + off == PAGE_SIZE) {
1557                                 page_idx += 1;
1558                                 if (WARN_ON(page_idx >= nr_pages)) {
1559                                         err = -EINVAL;
1560                                         goto out;
1561                                 }
1562                                 page = pages[page_idx];
1563                         }
1564
1565                         if (len <= add)
1566                                 break;
1567                         len -= add;
1568                         lbo += add;
1569                 }
1570
1571                 vcn_next = vcn + clen;
1572                 if (!run_get_entry(run, ++run_idx, &vcn, &lcn, &clen) ||
1573                     vcn != vcn_next) {
1574                         err = -ENOENT;
1575                         goto out;
1576                 }
1577                 off = 0;
1578         }
1579 out:
1580         if (bio) {
1581                 if (!err)
1582                         err = submit_bio_wait(bio);
1583                 bio_put(bio);
1584         }
1585         blk_finish_plug(&plug);
1586
1587         return err;
1588 }
1589
1590 /*
1591  * Helper for ntfs_loadlog_and_replay
1592  * fill on-disk logfile range by (-1)
1593  * this means empty logfile
1594  */
1595 int ntfs_bio_fill_1(struct ntfs_sb_info *sbi, const struct runs_tree *run)
1596 {
1597         int err = 0;
1598         struct super_block *sb = sbi->sb;
1599         struct block_device *bdev = sb->s_bdev;
1600         u8 cluster_bits = sbi->cluster_bits;
1601         struct bio *new, *bio = NULL;
1602         CLST lcn, clen;
1603         u64 lbo, len;
1604         size_t run_idx;
1605         struct page *fill;
1606         void *kaddr;
1607         struct blk_plug plug;
1608
1609         fill = alloc_page(GFP_KERNEL);
1610         if (!fill)
1611                 return -ENOMEM;
1612
1613         kaddr = kmap_atomic(fill);
1614         memset(kaddr, -1, PAGE_SIZE);
1615         kunmap_atomic(kaddr);
1616         flush_dcache_page(fill);
1617         lock_page(fill);
1618
1619         if (!run_lookup_entry(run, 0, &lcn, &clen, &run_idx)) {
1620                 err = -ENOENT;
1621                 goto out;
1622         }
1623
1624         /*
1625          * TODO: try blkdev_issue_write_same
1626          */
1627         blk_start_plug(&plug);
1628         do {
1629                 lbo = (u64)lcn << cluster_bits;
1630                 len = (u64)clen << cluster_bits;
1631 new_bio:
1632                 new = ntfs_alloc_bio(BIO_MAX_VECS);
1633                 if (!new) {
1634                         err = -ENOMEM;
1635                         break;
1636                 }
1637                 if (bio) {
1638                         bio_chain(bio, new);
1639                         submit_bio(bio);
1640                 }
1641                 bio = new;
1642                 bio_set_dev(bio, bdev);
1643                 bio->bi_opf = REQ_OP_WRITE;
1644                 bio->bi_iter.bi_sector = lbo >> 9;
1645
1646                 for (;;) {
1647                         u32 add = len > PAGE_SIZE ? PAGE_SIZE : len;
1648
1649                         if (bio_add_page(bio, fill, add, 0) < add)
1650                                 goto new_bio;
1651
1652                         lbo += add;
1653                         if (len <= add)
1654                                 break;
1655                         len -= add;
1656                 }
1657         } while (run_get_entry(run, ++run_idx, NULL, &lcn, &clen));
1658
1659         if (bio) {
1660                 if (!err)
1661                         err = submit_bio_wait(bio);
1662                 bio_put(bio);
1663         }
1664         blk_finish_plug(&plug);
1665 out:
1666         unlock_page(fill);
1667         put_page(fill);
1668
1669         return err;
1670 }
1671
1672 int ntfs_vbo_to_lbo(struct ntfs_sb_info *sbi, const struct runs_tree *run,
1673                     u64 vbo, u64 *lbo, u64 *bytes)
1674 {
1675         u32 off;
1676         CLST lcn, len;
1677         u8 cluster_bits = sbi->cluster_bits;
1678
1679         if (!run_lookup_entry(run, vbo >> cluster_bits, &lcn, &len, NULL))
1680                 return -ENOENT;
1681
1682         off = vbo & sbi->cluster_mask;
1683         *lbo = lcn == SPARSE_LCN ? -1 : (((u64)lcn << cluster_bits) + off);
1684         *bytes = ((u64)len << cluster_bits) - off;
1685
1686         return 0;
1687 }
1688
1689 struct ntfs_inode *ntfs_new_inode(struct ntfs_sb_info *sbi, CLST rno, bool dir)
1690 {
1691         int err = 0;
1692         struct super_block *sb = sbi->sb;
1693         struct inode *inode = new_inode(sb);
1694         struct ntfs_inode *ni;
1695
1696         if (!inode)
1697                 return ERR_PTR(-ENOMEM);
1698
1699         ni = ntfs_i(inode);
1700
1701         err = mi_format_new(&ni->mi, sbi, rno, dir ? RECORD_FLAG_DIR : 0,
1702                             false);
1703         if (err)
1704                 goto out;
1705
1706         inode->i_ino = rno;
1707         if (insert_inode_locked(inode) < 0) {
1708                 err = -EIO;
1709                 goto out;
1710         }
1711
1712 out:
1713         if (err) {
1714                 iput(inode);
1715                 ni = ERR_PTR(err);
1716         }
1717         return ni;
1718 }
1719
1720 /*
1721  * O:BAG:BAD:(A;OICI;FA;;;WD)
1722  * owner S-1-5-32-544 (Administrators)
1723  * group S-1-5-32-544 (Administrators)
1724  * ACE: allow S-1-1-0 (Everyone) with FILE_ALL_ACCESS
1725  */
1726 const u8 s_default_security[] __aligned(8) = {
1727         0x01, 0x00, 0x04, 0x80, 0x30, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00,
1728         0x00, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x02, 0x00, 0x1C, 0x00,
1729         0x01, 0x00, 0x00, 0x00, 0x00, 0x03, 0x14, 0x00, 0xFF, 0x01, 0x1F, 0x00,
1730         0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00,
1731         0x01, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x20, 0x00, 0x00, 0x00,
1732         0x20, 0x02, 0x00, 0x00, 0x01, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05,
1733         0x20, 0x00, 0x00, 0x00, 0x20, 0x02, 0x00, 0x00,
1734 };
1735
1736 static_assert(sizeof(s_default_security) == 0x50);
1737
1738 static inline u32 sid_length(const struct SID *sid)
1739 {
1740         return struct_size(sid, SubAuthority, sid->SubAuthorityCount);
1741 }
1742
1743 /*
1744  * Thanks Mark Harmstone for idea
1745  */
1746 static bool is_acl_valid(const struct ACL *acl, u32 len)
1747 {
1748         const struct ACE_HEADER *ace;
1749         u32 i;
1750         u16 ace_count, ace_size;
1751
1752         if (acl->AclRevision != ACL_REVISION &&
1753             acl->AclRevision != ACL_REVISION_DS) {
1754                 /*
1755                  * This value should be ACL_REVISION, unless the ACL contains an
1756                  * object-specific ACE, in which case this value must be ACL_REVISION_DS.
1757                  * All ACEs in an ACL must be at the same revision level.
1758                  */
1759                 return false;
1760         }
1761
1762         if (acl->Sbz1)
1763                 return false;
1764
1765         if (le16_to_cpu(acl->AclSize) > len)
1766                 return false;
1767
1768         if (acl->Sbz2)
1769                 return false;
1770
1771         len -= sizeof(struct ACL);
1772         ace = (struct ACE_HEADER *)&acl[1];
1773         ace_count = le16_to_cpu(acl->AceCount);
1774
1775         for (i = 0; i < ace_count; i++) {
1776                 if (len < sizeof(struct ACE_HEADER))
1777                         return false;
1778
1779                 ace_size = le16_to_cpu(ace->AceSize);
1780                 if (len < ace_size)
1781                         return false;
1782
1783                 len -= ace_size;
1784                 ace = Add2Ptr(ace, ace_size);
1785         }
1786
1787         return true;
1788 }
1789
1790 bool is_sd_valid(const struct SECURITY_DESCRIPTOR_RELATIVE *sd, u32 len)
1791 {
1792         u32 sd_owner, sd_group, sd_sacl, sd_dacl;
1793
1794         if (len < sizeof(struct SECURITY_DESCRIPTOR_RELATIVE))
1795                 return false;
1796
1797         if (sd->Revision != 1)
1798                 return false;
1799
1800         if (sd->Sbz1)
1801                 return false;
1802
1803         if (!(sd->Control & SE_SELF_RELATIVE))
1804                 return false;
1805
1806         sd_owner = le32_to_cpu(sd->Owner);
1807         if (sd_owner) {
1808                 const struct SID *owner = Add2Ptr(sd, sd_owner);
1809
1810                 if (sd_owner + offsetof(struct SID, SubAuthority) > len)
1811                         return false;
1812
1813                 if (owner->Revision != 1)
1814                         return false;
1815
1816                 if (sd_owner + sid_length(owner) > len)
1817                         return false;
1818         }
1819
1820         sd_group = le32_to_cpu(sd->Group);
1821         if (sd_group) {
1822                 const struct SID *group = Add2Ptr(sd, sd_group);
1823
1824                 if (sd_group + offsetof(struct SID, SubAuthority) > len)
1825                         return false;
1826
1827                 if (group->Revision != 1)
1828                         return false;
1829
1830                 if (sd_group + sid_length(group) > len)
1831                         return false;
1832         }
1833
1834         sd_sacl = le32_to_cpu(sd->Sacl);
1835         if (sd_sacl) {
1836                 const struct ACL *sacl = Add2Ptr(sd, sd_sacl);
1837
1838                 if (sd_sacl + sizeof(struct ACL) > len)
1839                         return false;
1840
1841                 if (!is_acl_valid(sacl, len - sd_sacl))
1842                         return false;
1843         }
1844
1845         sd_dacl = le32_to_cpu(sd->Dacl);
1846         if (sd_dacl) {
1847                 const struct ACL *dacl = Add2Ptr(sd, sd_dacl);
1848
1849                 if (sd_dacl + sizeof(struct ACL) > len)
1850                         return false;
1851
1852                 if (!is_acl_valid(dacl, len - sd_dacl))
1853                         return false;
1854         }
1855
1856         return true;
1857 }
1858
1859 /*
1860  * ntfs_security_init
1861  *
1862  * loads and parse $Secure
1863  */
1864 int ntfs_security_init(struct ntfs_sb_info *sbi)
1865 {
1866         int err;
1867         struct super_block *sb = sbi->sb;
1868         struct inode *inode;
1869         struct ntfs_inode *ni;
1870         struct MFT_REF ref;
1871         struct ATTRIB *attr;
1872         struct ATTR_LIST_ENTRY *le;
1873         u64 sds_size;
1874         size_t off;
1875         struct NTFS_DE *ne;
1876         struct NTFS_DE_SII *sii_e;
1877         struct ntfs_fnd *fnd_sii = NULL;
1878         const struct INDEX_ROOT *root_sii;
1879         const struct INDEX_ROOT *root_sdh;
1880         struct ntfs_index *indx_sdh = &sbi->security.index_sdh;
1881         struct ntfs_index *indx_sii = &sbi->security.index_sii;
1882
1883         ref.low = cpu_to_le32(MFT_REC_SECURE);
1884         ref.high = 0;
1885         ref.seq = cpu_to_le16(MFT_REC_SECURE);
1886
1887         inode = ntfs_iget5(sb, &ref, &NAME_SECURE);
1888         if (IS_ERR(inode)) {
1889                 err = PTR_ERR(inode);
1890                 ntfs_err(sb, "Failed to load $Secure.");
1891                 inode = NULL;
1892                 goto out;
1893         }
1894
1895         ni = ntfs_i(inode);
1896
1897         le = NULL;
1898
1899         attr = ni_find_attr(ni, NULL, &le, ATTR_ROOT, SDH_NAME,
1900                             ARRAY_SIZE(SDH_NAME), NULL, NULL);
1901         if (!attr) {
1902                 err = -EINVAL;
1903                 goto out;
1904         }
1905
1906         root_sdh = resident_data(attr);
1907         if (root_sdh->type != ATTR_ZERO ||
1908             root_sdh->rule != NTFS_COLLATION_TYPE_SECURITY_HASH) {
1909                 err = -EINVAL;
1910                 goto out;
1911         }
1912
1913         err = indx_init(indx_sdh, sbi, attr, INDEX_MUTEX_SDH);
1914         if (err)
1915                 goto out;
1916
1917         attr = ni_find_attr(ni, attr, &le, ATTR_ROOT, SII_NAME,
1918                             ARRAY_SIZE(SII_NAME), NULL, NULL);
1919         if (!attr) {
1920                 err = -EINVAL;
1921                 goto out;
1922         }
1923
1924         root_sii = resident_data(attr);
1925         if (root_sii->type != ATTR_ZERO ||
1926             root_sii->rule != NTFS_COLLATION_TYPE_UINT) {
1927                 err = -EINVAL;
1928                 goto out;
1929         }
1930
1931         err = indx_init(indx_sii, sbi, attr, INDEX_MUTEX_SII);
1932         if (err)
1933                 goto out;
1934
1935         fnd_sii = fnd_get();
1936         if (!fnd_sii) {
1937                 err = -ENOMEM;
1938                 goto out;
1939         }
1940
1941         sds_size = inode->i_size;
1942
1943         /* Find the last valid Id */
1944         sbi->security.next_id = SECURITY_ID_FIRST;
1945         /* Always write new security at the end of bucket */
1946         sbi->security.next_off =
1947                         ALIGN(sds_size - SecurityDescriptorsBlockSize, 16);
1948
1949         off = 0;
1950         ne = NULL;
1951
1952         for (;;) {
1953                 u32 next_id;
1954
1955                 err = indx_find_raw(indx_sii, ni, root_sii, &ne, &off, fnd_sii);
1956                 if (err || !ne)
1957                         break;
1958
1959                 sii_e = (struct NTFS_DE_SII *)ne;
1960                 if (le16_to_cpu(ne->view.data_size) < SIZEOF_SECURITY_HDR)
1961                         continue;
1962
1963                 next_id = le32_to_cpu(sii_e->sec_id) + 1;
1964                 if (next_id >= sbi->security.next_id)
1965                         sbi->security.next_id = next_id;
1966         }
1967
1968         sbi->security.ni = ni;
1969         inode = NULL;
1970 out:
1971         iput(inode);
1972         fnd_put(fnd_sii);
1973
1974         return err;
1975 }
1976
1977 /*
1978  * ntfs_get_security_by_id
1979  *
1980  * reads security descriptor by id
1981  */
1982 int ntfs_get_security_by_id(struct ntfs_sb_info *sbi, __le32 security_id,
1983                             struct SECURITY_DESCRIPTOR_RELATIVE **sd,
1984                             size_t *size)
1985 {
1986         int err;
1987         int diff;
1988         struct ntfs_inode *ni = sbi->security.ni;
1989         struct ntfs_index *indx = &sbi->security.index_sii;
1990         void *p = NULL;
1991         struct NTFS_DE_SII *sii_e;
1992         struct ntfs_fnd *fnd_sii;
1993         struct SECURITY_HDR d_security;
1994         const struct INDEX_ROOT *root_sii;
1995         u32 t32;
1996
1997         *sd = NULL;
1998
1999         mutex_lock_nested(&ni->ni_lock, NTFS_INODE_MUTEX_SECURITY);
2000
2001         fnd_sii = fnd_get();
2002         if (!fnd_sii) {
2003                 err = -ENOMEM;
2004                 goto out;
2005         }
2006
2007         root_sii = indx_get_root(indx, ni, NULL, NULL);
2008         if (!root_sii) {
2009                 err = -EINVAL;
2010                 goto out;
2011         }
2012
2013         /* Try to find this SECURITY descriptor in SII indexes */
2014         err = indx_find(indx, ni, root_sii, &security_id, sizeof(security_id),
2015                         NULL, &diff, (struct NTFS_DE **)&sii_e, fnd_sii);
2016         if (err)
2017                 goto out;
2018
2019         if (diff)
2020                 goto out;
2021
2022         t32 = le32_to_cpu(sii_e->sec_hdr.size);
2023         if (t32 < SIZEOF_SECURITY_HDR) {
2024                 err = -EINVAL;
2025                 goto out;
2026         }
2027
2028         if (t32 > SIZEOF_SECURITY_HDR + 0x10000) {
2029                 /*
2030                  * looks like too big security. 0x10000 - is arbitrary big number
2031                  */
2032                 err = -EFBIG;
2033                 goto out;
2034         }
2035
2036         *size = t32 - SIZEOF_SECURITY_HDR;
2037
2038         p = kmalloc(*size, GFP_NOFS);
2039         if (!p) {
2040                 err = -ENOMEM;
2041                 goto out;
2042         }
2043
2044         err = ntfs_read_run_nb(sbi, &ni->file.run,
2045                                le64_to_cpu(sii_e->sec_hdr.off), &d_security,
2046                                sizeof(d_security), NULL);
2047         if (err)
2048                 goto out;
2049
2050         if (memcmp(&d_security, &sii_e->sec_hdr, SIZEOF_SECURITY_HDR)) {
2051                 err = -EINVAL;
2052                 goto out;
2053         }
2054
2055         err = ntfs_read_run_nb(sbi, &ni->file.run,
2056                                le64_to_cpu(sii_e->sec_hdr.off) +
2057                                        SIZEOF_SECURITY_HDR,
2058                                p, *size, NULL);
2059         if (err)
2060                 goto out;
2061
2062         *sd = p;
2063         p = NULL;
2064
2065 out:
2066         kfree(p);
2067         fnd_put(fnd_sii);
2068         ni_unlock(ni);
2069
2070         return err;
2071 }
2072
2073 /*
2074  * ntfs_insert_security
2075  *
2076  * inserts security descriptor into $Secure::SDS
2077  *
2078  * SECURITY Descriptor Stream data is organized into chunks of 256K bytes
2079  * and it contains a mirror copy of each security descriptor.  When writing
2080  * to a security descriptor at location X, another copy will be written at
2081  * location (X+256K).
2082  * When writing a security descriptor that will cross the 256K boundary,
2083  * the pointer will be advanced by 256K to skip
2084  * over the mirror portion.
2085  */
2086 int ntfs_insert_security(struct ntfs_sb_info *sbi,
2087                          const struct SECURITY_DESCRIPTOR_RELATIVE *sd,
2088                          u32 size_sd, __le32 *security_id, bool *inserted)
2089 {
2090         int err, diff;
2091         struct ntfs_inode *ni = sbi->security.ni;
2092         struct ntfs_index *indx_sdh = &sbi->security.index_sdh;
2093         struct ntfs_index *indx_sii = &sbi->security.index_sii;
2094         struct NTFS_DE_SDH *e;
2095         struct NTFS_DE_SDH sdh_e;
2096         struct NTFS_DE_SII sii_e;
2097         struct SECURITY_HDR *d_security;
2098         u32 new_sec_size = size_sd + SIZEOF_SECURITY_HDR;
2099         u32 aligned_sec_size = ALIGN(new_sec_size, 16);
2100         struct SECURITY_KEY hash_key;
2101         struct ntfs_fnd *fnd_sdh = NULL;
2102         const struct INDEX_ROOT *root_sdh;
2103         const struct INDEX_ROOT *root_sii;
2104         u64 mirr_off, new_sds_size;
2105         u32 next, left;
2106
2107         static_assert((1 << Log2OfSecurityDescriptorsBlockSize) ==
2108                       SecurityDescriptorsBlockSize);
2109
2110         hash_key.hash = security_hash(sd, size_sd);
2111         hash_key.sec_id = SECURITY_ID_INVALID;
2112
2113         if (inserted)
2114                 *inserted = false;
2115         *security_id = SECURITY_ID_INVALID;
2116
2117         /* Allocate a temporal buffer*/
2118         d_security = kzalloc(aligned_sec_size, GFP_NOFS);
2119         if (!d_security)
2120                 return -ENOMEM;
2121
2122         mutex_lock_nested(&ni->ni_lock, NTFS_INODE_MUTEX_SECURITY);
2123
2124         fnd_sdh = fnd_get();
2125         if (!fnd_sdh) {
2126                 err = -ENOMEM;
2127                 goto out;
2128         }
2129
2130         root_sdh = indx_get_root(indx_sdh, ni, NULL, NULL);
2131         if (!root_sdh) {
2132                 err = -EINVAL;
2133                 goto out;
2134         }
2135
2136         root_sii = indx_get_root(indx_sii, ni, NULL, NULL);
2137         if (!root_sii) {
2138                 err = -EINVAL;
2139                 goto out;
2140         }
2141
2142         /*
2143          * Check if such security already exists
2144          * use "SDH" and hash -> to get the offset in "SDS"
2145          */
2146         err = indx_find(indx_sdh, ni, root_sdh, &hash_key, sizeof(hash_key),
2147                         &d_security->key.sec_id, &diff, (struct NTFS_DE **)&e,
2148                         fnd_sdh);
2149         if (err)
2150                 goto out;
2151
2152         while (e) {
2153                 if (le32_to_cpu(e->sec_hdr.size) == new_sec_size) {
2154                         err = ntfs_read_run_nb(sbi, &ni->file.run,
2155                                                le64_to_cpu(e->sec_hdr.off),
2156                                                d_security, new_sec_size, NULL);
2157                         if (err)
2158                                 goto out;
2159
2160                         if (le32_to_cpu(d_security->size) == new_sec_size &&
2161                             d_security->key.hash == hash_key.hash &&
2162                             !memcmp(d_security + 1, sd, size_sd)) {
2163                                 *security_id = d_security->key.sec_id;
2164                                 /*such security already exists*/
2165                                 err = 0;
2166                                 goto out;
2167                         }
2168                 }
2169
2170                 err = indx_find_sort(indx_sdh, ni, root_sdh,
2171                                      (struct NTFS_DE **)&e, fnd_sdh);
2172                 if (err)
2173                         goto out;
2174
2175                 if (!e || e->key.hash != hash_key.hash)
2176                         break;
2177         }
2178
2179         /* Zero unused space */
2180         next = sbi->security.next_off & (SecurityDescriptorsBlockSize - 1);
2181         left = SecurityDescriptorsBlockSize - next;
2182
2183         /* Zero gap until SecurityDescriptorsBlockSize */
2184         if (left < new_sec_size) {
2185                 /* zero "left" bytes from sbi->security.next_off */
2186                 sbi->security.next_off += SecurityDescriptorsBlockSize + left;
2187         }
2188
2189         /* Zero tail of previous security */
2190         //used = ni->vfs_inode.i_size & (SecurityDescriptorsBlockSize - 1);
2191
2192         /*
2193          * Example:
2194          * 0x40438 == ni->vfs_inode.i_size
2195          * 0x00440 == sbi->security.next_off
2196          * need to zero [0x438-0x440)
2197          * if (next > used) {
2198          *  u32 tozero = next - used;
2199          *  zero "tozero" bytes from sbi->security.next_off - tozero
2200          */
2201
2202         /* format new security descriptor */
2203         d_security->key.hash = hash_key.hash;
2204         d_security->key.sec_id = cpu_to_le32(sbi->security.next_id);
2205         d_security->off = cpu_to_le64(sbi->security.next_off);
2206         d_security->size = cpu_to_le32(new_sec_size);
2207         memcpy(d_security + 1, sd, size_sd);
2208
2209         /* Write main SDS bucket */
2210         err = ntfs_sb_write_run(sbi, &ni->file.run, sbi->security.next_off,
2211                                 d_security, aligned_sec_size);
2212
2213         if (err)
2214                 goto out;
2215
2216         mirr_off = sbi->security.next_off + SecurityDescriptorsBlockSize;
2217         new_sds_size = mirr_off + aligned_sec_size;
2218
2219         if (new_sds_size > ni->vfs_inode.i_size) {
2220                 err = attr_set_size(ni, ATTR_DATA, SDS_NAME,
2221                                     ARRAY_SIZE(SDS_NAME), &ni->file.run,
2222                                     new_sds_size, &new_sds_size, false, NULL);
2223                 if (err)
2224                         goto out;
2225         }
2226
2227         /* Write copy SDS bucket */
2228         err = ntfs_sb_write_run(sbi, &ni->file.run, mirr_off, d_security,
2229                                 aligned_sec_size);
2230         if (err)
2231                 goto out;
2232
2233         /* Fill SII entry */
2234         sii_e.de.view.data_off =
2235                 cpu_to_le16(offsetof(struct NTFS_DE_SII, sec_hdr));
2236         sii_e.de.view.data_size = cpu_to_le16(SIZEOF_SECURITY_HDR);
2237         sii_e.de.view.res = 0;
2238         sii_e.de.size = cpu_to_le16(SIZEOF_SII_DIRENTRY);
2239         sii_e.de.key_size = cpu_to_le16(sizeof(d_security->key.sec_id));
2240         sii_e.de.flags = 0;
2241         sii_e.de.res = 0;
2242         sii_e.sec_id = d_security->key.sec_id;
2243         memcpy(&sii_e.sec_hdr, d_security, SIZEOF_SECURITY_HDR);
2244
2245         err = indx_insert_entry(indx_sii, ni, &sii_e.de, NULL, NULL);
2246         if (err)
2247                 goto out;
2248
2249         /* Fill SDH entry */
2250         sdh_e.de.view.data_off =
2251                 cpu_to_le16(offsetof(struct NTFS_DE_SDH, sec_hdr));
2252         sdh_e.de.view.data_size = cpu_to_le16(SIZEOF_SECURITY_HDR);
2253         sdh_e.de.view.res = 0;
2254         sdh_e.de.size = cpu_to_le16(SIZEOF_SDH_DIRENTRY);
2255         sdh_e.de.key_size = cpu_to_le16(sizeof(sdh_e.key));
2256         sdh_e.de.flags = 0;
2257         sdh_e.de.res = 0;
2258         sdh_e.key.hash = d_security->key.hash;
2259         sdh_e.key.sec_id = d_security->key.sec_id;
2260         memcpy(&sdh_e.sec_hdr, d_security, SIZEOF_SECURITY_HDR);
2261         sdh_e.magic[0] = cpu_to_le16('I');
2262         sdh_e.magic[1] = cpu_to_le16('I');
2263
2264         fnd_clear(fnd_sdh);
2265         err = indx_insert_entry(indx_sdh, ni, &sdh_e.de, (void *)(size_t)1,
2266                                 fnd_sdh);
2267         if (err)
2268                 goto out;
2269
2270         *security_id = d_security->key.sec_id;
2271         if (inserted)
2272                 *inserted = true;
2273
2274         /* Update Id and offset for next descriptor */
2275         sbi->security.next_id += 1;
2276         sbi->security.next_off += aligned_sec_size;
2277
2278 out:
2279         fnd_put(fnd_sdh);
2280         mark_inode_dirty(&ni->vfs_inode);
2281         ni_unlock(ni);
2282         kfree(d_security);
2283
2284         return err;
2285 }
2286
2287 /*
2288  * ntfs_reparse_init
2289  *
2290  * loads and parse $Extend/$Reparse
2291  */
2292 int ntfs_reparse_init(struct ntfs_sb_info *sbi)
2293 {
2294         int err;
2295         struct ntfs_inode *ni = sbi->reparse.ni;
2296         struct ntfs_index *indx = &sbi->reparse.index_r;
2297         struct ATTRIB *attr;
2298         struct ATTR_LIST_ENTRY *le;
2299         const struct INDEX_ROOT *root_r;
2300
2301         if (!ni)
2302                 return 0;
2303
2304         le = NULL;
2305         attr = ni_find_attr(ni, NULL, &le, ATTR_ROOT, SR_NAME,
2306                             ARRAY_SIZE(SR_NAME), NULL, NULL);
2307         if (!attr) {
2308                 err = -EINVAL;
2309                 goto out;
2310         }
2311
2312         root_r = resident_data(attr);
2313         if (root_r->type != ATTR_ZERO ||
2314             root_r->rule != NTFS_COLLATION_TYPE_UINTS) {
2315                 err = -EINVAL;
2316                 goto out;
2317         }
2318
2319         err = indx_init(indx, sbi, attr, INDEX_MUTEX_SR);
2320         if (err)
2321                 goto out;
2322
2323 out:
2324         return err;
2325 }
2326
2327 /*
2328  * ntfs_objid_init
2329  *
2330  * loads and parse $Extend/$ObjId
2331  */
2332 int ntfs_objid_init(struct ntfs_sb_info *sbi)
2333 {
2334         int err;
2335         struct ntfs_inode *ni = sbi->objid.ni;
2336         struct ntfs_index *indx = &sbi->objid.index_o;
2337         struct ATTRIB *attr;
2338         struct ATTR_LIST_ENTRY *le;
2339         const struct INDEX_ROOT *root;
2340
2341         if (!ni)
2342                 return 0;
2343
2344         le = NULL;
2345         attr = ni_find_attr(ni, NULL, &le, ATTR_ROOT, SO_NAME,
2346                             ARRAY_SIZE(SO_NAME), NULL, NULL);
2347         if (!attr) {
2348                 err = -EINVAL;
2349                 goto out;
2350         }
2351
2352         root = resident_data(attr);
2353         if (root->type != ATTR_ZERO ||
2354             root->rule != NTFS_COLLATION_TYPE_UINTS) {
2355                 err = -EINVAL;
2356                 goto out;
2357         }
2358
2359         err = indx_init(indx, sbi, attr, INDEX_MUTEX_SO);
2360         if (err)
2361                 goto out;
2362
2363 out:
2364         return err;
2365 }
2366
2367 int ntfs_objid_remove(struct ntfs_sb_info *sbi, struct GUID *guid)
2368 {
2369         int err;
2370         struct ntfs_inode *ni = sbi->objid.ni;
2371         struct ntfs_index *indx = &sbi->objid.index_o;
2372
2373         if (!ni)
2374                 return -EINVAL;
2375
2376         mutex_lock_nested(&ni->ni_lock, NTFS_INODE_MUTEX_OBJID);
2377
2378         err = indx_delete_entry(indx, ni, guid, sizeof(*guid), NULL);
2379
2380         mark_inode_dirty(&ni->vfs_inode);
2381         ni_unlock(ni);
2382
2383         return err;
2384 }
2385
2386 int ntfs_insert_reparse(struct ntfs_sb_info *sbi, __le32 rtag,
2387                         const struct MFT_REF *ref)
2388 {
2389         int err;
2390         struct ntfs_inode *ni = sbi->reparse.ni;
2391         struct ntfs_index *indx = &sbi->reparse.index_r;
2392         struct NTFS_DE_R re;
2393
2394         if (!ni)
2395                 return -EINVAL;
2396
2397         memset(&re, 0, sizeof(re));
2398
2399         re.de.view.data_off = cpu_to_le16(offsetof(struct NTFS_DE_R, zero));
2400         re.de.size = cpu_to_le16(sizeof(struct NTFS_DE_R));
2401         re.de.key_size = cpu_to_le16(sizeof(re.key));
2402
2403         re.key.ReparseTag = rtag;
2404         memcpy(&re.key.ref, ref, sizeof(*ref));
2405
2406         mutex_lock_nested(&ni->ni_lock, NTFS_INODE_MUTEX_REPARSE);
2407
2408         err = indx_insert_entry(indx, ni, &re.de, NULL, NULL);
2409
2410         mark_inode_dirty(&ni->vfs_inode);
2411         ni_unlock(ni);
2412
2413         return err;
2414 }
2415
2416 int ntfs_remove_reparse(struct ntfs_sb_info *sbi, __le32 rtag,
2417                         const struct MFT_REF *ref)
2418 {
2419         int err, diff;
2420         struct ntfs_inode *ni = sbi->reparse.ni;
2421         struct ntfs_index *indx = &sbi->reparse.index_r;
2422         struct ntfs_fnd *fnd = NULL;
2423         struct REPARSE_KEY rkey;
2424         struct NTFS_DE_R *re;
2425         struct INDEX_ROOT *root_r;
2426
2427         if (!ni)
2428                 return -EINVAL;
2429
2430         rkey.ReparseTag = rtag;
2431         rkey.ref = *ref;
2432
2433         mutex_lock_nested(&ni->ni_lock, NTFS_INODE_MUTEX_REPARSE);
2434
2435         if (rtag) {
2436                 err = indx_delete_entry(indx, ni, &rkey, sizeof(rkey), NULL);
2437                 goto out1;
2438         }
2439
2440         fnd = fnd_get();
2441         if (!fnd) {
2442                 err = -ENOMEM;
2443                 goto out1;
2444         }
2445
2446         root_r = indx_get_root(indx, ni, NULL, NULL);
2447         if (!root_r) {
2448                 err = -EINVAL;
2449                 goto out;
2450         }
2451
2452         /* 1 - forces to ignore rkey.ReparseTag when comparing keys */
2453         err = indx_find(indx, ni, root_r, &rkey, sizeof(rkey), (void *)1, &diff,
2454                         (struct NTFS_DE **)&re, fnd);
2455         if (err)
2456                 goto out;
2457
2458         if (memcmp(&re->key.ref, ref, sizeof(*ref))) {
2459                 /* Impossible. Looks like volume corrupt?*/
2460                 goto out;
2461         }
2462
2463         memcpy(&rkey, &re->key, sizeof(rkey));
2464
2465         fnd_put(fnd);
2466         fnd = NULL;
2467
2468         err = indx_delete_entry(indx, ni, &rkey, sizeof(rkey), NULL);
2469         if (err)
2470                 goto out;
2471
2472 out:
2473         fnd_put(fnd);
2474
2475 out1:
2476         mark_inode_dirty(&ni->vfs_inode);
2477         ni_unlock(ni);
2478
2479         return err;
2480 }
2481
2482 static inline void ntfs_unmap_and_discard(struct ntfs_sb_info *sbi, CLST lcn,
2483                                           CLST len)
2484 {
2485         ntfs_unmap_meta(sbi->sb, lcn, len);
2486         ntfs_discard(sbi, lcn, len);
2487 }
2488
2489 void mark_as_free_ex(struct ntfs_sb_info *sbi, CLST lcn, CLST len, bool trim)
2490 {
2491         CLST end, i;
2492         struct wnd_bitmap *wnd = &sbi->used.bitmap;
2493
2494         down_write_nested(&wnd->rw_lock, BITMAP_MUTEX_CLUSTERS);
2495         if (!wnd_is_used(wnd, lcn, len)) {
2496                 ntfs_set_state(sbi, NTFS_DIRTY_ERROR);
2497
2498                 end = lcn + len;
2499                 len = 0;
2500                 for (i = lcn; i < end; i++) {
2501                         if (wnd_is_used(wnd, i, 1)) {
2502                                 if (!len)
2503                                         lcn = i;
2504                                 len += 1;
2505                                 continue;
2506                         }
2507
2508                         if (!len)
2509                                 continue;
2510
2511                         if (trim)
2512                                 ntfs_unmap_and_discard(sbi, lcn, len);
2513
2514                         wnd_set_free(wnd, lcn, len);
2515                         len = 0;
2516                 }
2517
2518                 if (!len)
2519                         goto out;
2520         }
2521
2522         if (trim)
2523                 ntfs_unmap_and_discard(sbi, lcn, len);
2524         wnd_set_free(wnd, lcn, len);
2525
2526 out:
2527         up_write(&wnd->rw_lock);
2528 }
2529
2530 /*
2531  * run_deallocate
2532  *
2533  * deallocate clusters
2534  */
2535 int run_deallocate(struct ntfs_sb_info *sbi, struct runs_tree *run, bool trim)
2536 {
2537         CLST lcn, len;
2538         size_t idx = 0;
2539
2540         while (run_get_entry(run, idx++, NULL, &lcn, &len)) {
2541                 if (lcn == SPARSE_LCN)
2542                         continue;
2543
2544                 mark_as_free_ex(sbi, lcn, len, trim);
2545         }
2546
2547         return 0;
2548 }