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