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