GNU Linux-libre 5.15.137-gnu
[releases.git] / fs / ntfs3 / index.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  *
4  * Copyright (C) 2019-2021 Paragon Software GmbH, All rights reserved.
5  *
6  */
7
8 #include <linux/blkdev.h>
9 #include <linux/buffer_head.h>
10 #include <linux/fs.h>
11 #include <linux/kernel.h>
12
13 #include "debug.h"
14 #include "ntfs.h"
15 #include "ntfs_fs.h"
16
17 static const struct INDEX_NAMES {
18         const __le16 *name;
19         u8 name_len;
20 } s_index_names[INDEX_MUTEX_TOTAL] = {
21         { I30_NAME, ARRAY_SIZE(I30_NAME) }, { SII_NAME, ARRAY_SIZE(SII_NAME) },
22         { SDH_NAME, ARRAY_SIZE(SDH_NAME) }, { SO_NAME, ARRAY_SIZE(SO_NAME) },
23         { SQ_NAME, ARRAY_SIZE(SQ_NAME) },   { SR_NAME, ARRAY_SIZE(SR_NAME) },
24 };
25
26 /*
27  * cmp_fnames - Compare two names in index.
28  *
29  * if l1 != 0
30  *   Both names are little endian on-disk ATTR_FILE_NAME structs.
31  * else
32  *   key1 - cpu_str, key2 - ATTR_FILE_NAME
33  */
34 static int cmp_fnames(const void *key1, size_t l1, const void *key2, size_t l2,
35                       const void *data)
36 {
37         const struct ATTR_FILE_NAME *f2 = key2;
38         const struct ntfs_sb_info *sbi = data;
39         const struct ATTR_FILE_NAME *f1;
40         u16 fsize2;
41         bool both_case;
42
43         if (l2 <= offsetof(struct ATTR_FILE_NAME, name))
44                 return -1;
45
46         fsize2 = fname_full_size(f2);
47         if (l2 < fsize2)
48                 return -1;
49
50         both_case = f2->type != FILE_NAME_DOS /*&& !sbi->options.nocase*/;
51         if (!l1) {
52                 const struct le_str *s2 = (struct le_str *)&f2->name_len;
53
54                 /*
55                  * If names are equal (case insensitive)
56                  * try to compare it case sensitive.
57                  */
58                 return ntfs_cmp_names_cpu(key1, s2, sbi->upcase, both_case);
59         }
60
61         f1 = key1;
62         return ntfs_cmp_names(f1->name, f1->name_len, f2->name, f2->name_len,
63                               sbi->upcase, both_case);
64 }
65
66 /*
67  * cmp_uint - $SII of $Secure and $Q of Quota
68  */
69 static int cmp_uint(const void *key1, size_t l1, const void *key2, size_t l2,
70                     const void *data)
71 {
72         const u32 *k1 = key1;
73         const u32 *k2 = key2;
74
75         if (l2 < sizeof(u32))
76                 return -1;
77
78         if (*k1 < *k2)
79                 return -1;
80         if (*k1 > *k2)
81                 return 1;
82         return 0;
83 }
84
85 /*
86  * cmp_sdh - $SDH of $Secure
87  */
88 static int cmp_sdh(const void *key1, size_t l1, const void *key2, size_t l2,
89                    const void *data)
90 {
91         const struct SECURITY_KEY *k1 = key1;
92         const struct SECURITY_KEY *k2 = key2;
93         u32 t1, t2;
94
95         if (l2 < sizeof(struct SECURITY_KEY))
96                 return -1;
97
98         t1 = le32_to_cpu(k1->hash);
99         t2 = le32_to_cpu(k2->hash);
100
101         /* First value is a hash value itself. */
102         if (t1 < t2)
103                 return -1;
104         if (t1 > t2)
105                 return 1;
106
107         /* Second value is security Id. */
108         if (data) {
109                 t1 = le32_to_cpu(k1->sec_id);
110                 t2 = le32_to_cpu(k2->sec_id);
111                 if (t1 < t2)
112                         return -1;
113                 if (t1 > t2)
114                         return 1;
115         }
116
117         return 0;
118 }
119
120 /*
121  * cmp_uints - $O of ObjId and "$R" for Reparse.
122  */
123 static int cmp_uints(const void *key1, size_t l1, const void *key2, size_t l2,
124                      const void *data)
125 {
126         const __le32 *k1 = key1;
127         const __le32 *k2 = key2;
128         size_t count;
129
130         if ((size_t)data == 1) {
131                 /*
132                  * ni_delete_all -> ntfs_remove_reparse ->
133                  * delete all with this reference.
134                  * k1, k2 - pointers to REPARSE_KEY
135                  */
136
137                 k1 += 1; // Skip REPARSE_KEY.ReparseTag
138                 k2 += 1; // Skip REPARSE_KEY.ReparseTag
139                 if (l2 <= sizeof(int))
140                         return -1;
141                 l2 -= sizeof(int);
142                 if (l1 <= sizeof(int))
143                         return 1;
144                 l1 -= sizeof(int);
145         }
146
147         if (l2 < sizeof(int))
148                 return -1;
149
150         for (count = min(l1, l2) >> 2; count > 0; --count, ++k1, ++k2) {
151                 u32 t1 = le32_to_cpu(*k1);
152                 u32 t2 = le32_to_cpu(*k2);
153
154                 if (t1 > t2)
155                         return 1;
156                 if (t1 < t2)
157                         return -1;
158         }
159
160         if (l1 > l2)
161                 return 1;
162         if (l1 < l2)
163                 return -1;
164
165         return 0;
166 }
167
168 static inline NTFS_CMP_FUNC get_cmp_func(const struct INDEX_ROOT *root)
169 {
170         switch (root->type) {
171         case ATTR_NAME:
172                 if (root->rule == NTFS_COLLATION_TYPE_FILENAME)
173                         return &cmp_fnames;
174                 break;
175         case ATTR_ZERO:
176                 switch (root->rule) {
177                 case NTFS_COLLATION_TYPE_UINT:
178                         return &cmp_uint;
179                 case NTFS_COLLATION_TYPE_SECURITY_HASH:
180                         return &cmp_sdh;
181                 case NTFS_COLLATION_TYPE_UINTS:
182                         return &cmp_uints;
183                 default:
184                         break;
185                 }
186                 break;
187         default:
188                 break;
189         }
190
191         return NULL;
192 }
193
194 struct bmp_buf {
195         struct ATTRIB *b;
196         struct mft_inode *mi;
197         struct buffer_head *bh;
198         ulong *buf;
199         size_t bit;
200         u32 nbits;
201         u64 new_valid;
202 };
203
204 static int bmp_buf_get(struct ntfs_index *indx, struct ntfs_inode *ni,
205                        size_t bit, struct bmp_buf *bbuf)
206 {
207         struct ATTRIB *b;
208         size_t data_size, valid_size, vbo, off = bit >> 3;
209         struct ntfs_sb_info *sbi = ni->mi.sbi;
210         CLST vcn = off >> sbi->cluster_bits;
211         struct ATTR_LIST_ENTRY *le = NULL;
212         struct buffer_head *bh;
213         struct super_block *sb;
214         u32 blocksize;
215         const struct INDEX_NAMES *in = &s_index_names[indx->type];
216
217         bbuf->bh = NULL;
218
219         b = ni_find_attr(ni, NULL, &le, ATTR_BITMAP, in->name, in->name_len,
220                          &vcn, &bbuf->mi);
221         bbuf->b = b;
222         if (!b)
223                 return -EINVAL;
224
225         if (!b->non_res) {
226                 data_size = le32_to_cpu(b->res.data_size);
227
228                 if (off >= data_size)
229                         return -EINVAL;
230
231                 bbuf->buf = (ulong *)resident_data(b);
232                 bbuf->bit = 0;
233                 bbuf->nbits = data_size * 8;
234
235                 return 0;
236         }
237
238         data_size = le64_to_cpu(b->nres.data_size);
239         if (WARN_ON(off >= data_size)) {
240                 /* Looks like filesystem error. */
241                 return -EINVAL;
242         }
243
244         valid_size = le64_to_cpu(b->nres.valid_size);
245
246         bh = ntfs_bread_run(sbi, &indx->bitmap_run, off);
247         if (!bh)
248                 return -EIO;
249
250         if (IS_ERR(bh))
251                 return PTR_ERR(bh);
252
253         bbuf->bh = bh;
254
255         if (buffer_locked(bh))
256                 __wait_on_buffer(bh);
257
258         lock_buffer(bh);
259
260         sb = sbi->sb;
261         blocksize = sb->s_blocksize;
262
263         vbo = off & ~(size_t)sbi->block_mask;
264
265         bbuf->new_valid = vbo + blocksize;
266         if (bbuf->new_valid <= valid_size)
267                 bbuf->new_valid = 0;
268         else if (bbuf->new_valid > data_size)
269                 bbuf->new_valid = data_size;
270
271         if (vbo >= valid_size) {
272                 memset(bh->b_data, 0, blocksize);
273         } else if (vbo + blocksize > valid_size) {
274                 u32 voff = valid_size & sbi->block_mask;
275
276                 memset(bh->b_data + voff, 0, blocksize - voff);
277         }
278
279         bbuf->buf = (ulong *)bh->b_data;
280         bbuf->bit = 8 * (off & ~(size_t)sbi->block_mask);
281         bbuf->nbits = 8 * blocksize;
282
283         return 0;
284 }
285
286 static void bmp_buf_put(struct bmp_buf *bbuf, bool dirty)
287 {
288         struct buffer_head *bh = bbuf->bh;
289         struct ATTRIB *b = bbuf->b;
290
291         if (!bh) {
292                 if (b && !b->non_res && dirty)
293                         bbuf->mi->dirty = true;
294                 return;
295         }
296
297         if (!dirty)
298                 goto out;
299
300         if (bbuf->new_valid) {
301                 b->nres.valid_size = cpu_to_le64(bbuf->new_valid);
302                 bbuf->mi->dirty = true;
303         }
304
305         set_buffer_uptodate(bh);
306         mark_buffer_dirty(bh);
307
308 out:
309         unlock_buffer(bh);
310         put_bh(bh);
311 }
312
313 /*
314  * indx_mark_used - Mark the bit @bit as used.
315  */
316 static int indx_mark_used(struct ntfs_index *indx, struct ntfs_inode *ni,
317                           size_t bit)
318 {
319         int err;
320         struct bmp_buf bbuf;
321
322         err = bmp_buf_get(indx, ni, bit, &bbuf);
323         if (err)
324                 return err;
325
326         __set_bit(bit - bbuf.bit, bbuf.buf);
327
328         bmp_buf_put(&bbuf, true);
329
330         return 0;
331 }
332
333 /*
334  * indx_mark_free - Mark the bit @bit as free.
335  */
336 static int indx_mark_free(struct ntfs_index *indx, struct ntfs_inode *ni,
337                           size_t bit)
338 {
339         int err;
340         struct bmp_buf bbuf;
341
342         err = bmp_buf_get(indx, ni, bit, &bbuf);
343         if (err)
344                 return err;
345
346         __clear_bit(bit - bbuf.bit, bbuf.buf);
347
348         bmp_buf_put(&bbuf, true);
349
350         return 0;
351 }
352
353 /*
354  * scan_nres_bitmap
355  *
356  * If ntfs_readdir calls this function (indx_used_bit -> scan_nres_bitmap),
357  * inode is shared locked and no ni_lock.
358  * Use rw_semaphore for read/write access to bitmap_run.
359  */
360 static int scan_nres_bitmap(struct ntfs_inode *ni, struct ATTRIB *bitmap,
361                             struct ntfs_index *indx, size_t from,
362                             bool (*fn)(const ulong *buf, u32 bit, u32 bits,
363                                        size_t *ret),
364                             size_t *ret)
365 {
366         struct ntfs_sb_info *sbi = ni->mi.sbi;
367         struct super_block *sb = sbi->sb;
368         struct runs_tree *run = &indx->bitmap_run;
369         struct rw_semaphore *lock = &indx->run_lock;
370         u32 nbits = sb->s_blocksize * 8;
371         u32 blocksize = sb->s_blocksize;
372         u64 valid_size = le64_to_cpu(bitmap->nres.valid_size);
373         u64 data_size = le64_to_cpu(bitmap->nres.data_size);
374         sector_t eblock = bytes_to_block(sb, data_size);
375         size_t vbo = from >> 3;
376         sector_t blk = (vbo & sbi->cluster_mask) >> sb->s_blocksize_bits;
377         sector_t vblock = vbo >> sb->s_blocksize_bits;
378         sector_t blen, block;
379         CLST lcn, clen, vcn, vcn_next;
380         size_t idx;
381         struct buffer_head *bh;
382         bool ok;
383
384         *ret = MINUS_ONE_T;
385
386         if (vblock >= eblock)
387                 return 0;
388
389         from &= nbits - 1;
390         vcn = vbo >> sbi->cluster_bits;
391
392         down_read(lock);
393         ok = run_lookup_entry(run, vcn, &lcn, &clen, &idx);
394         up_read(lock);
395
396 next_run:
397         if (!ok) {
398                 int err;
399                 const struct INDEX_NAMES *name = &s_index_names[indx->type];
400
401                 down_write(lock);
402                 err = attr_load_runs_vcn(ni, ATTR_BITMAP, name->name,
403                                          name->name_len, run, vcn);
404                 up_write(lock);
405                 if (err)
406                         return err;
407                 down_read(lock);
408                 ok = run_lookup_entry(run, vcn, &lcn, &clen, &idx);
409                 up_read(lock);
410                 if (!ok)
411                         return -EINVAL;
412         }
413
414         blen = (sector_t)clen * sbi->blocks_per_cluster;
415         block = (sector_t)lcn * sbi->blocks_per_cluster;
416
417         for (; blk < blen; blk++, from = 0) {
418                 bh = ntfs_bread(sb, block + blk);
419                 if (!bh)
420                         return -EIO;
421
422                 vbo = (u64)vblock << sb->s_blocksize_bits;
423                 if (vbo >= valid_size) {
424                         memset(bh->b_data, 0, blocksize);
425                 } else if (vbo + blocksize > valid_size) {
426                         u32 voff = valid_size & sbi->block_mask;
427
428                         memset(bh->b_data + voff, 0, blocksize - voff);
429                 }
430
431                 if (vbo + blocksize > data_size)
432                         nbits = 8 * (data_size - vbo);
433
434                 ok = nbits > from ? (*fn)((ulong *)bh->b_data, from, nbits, ret)
435                                   : false;
436                 put_bh(bh);
437
438                 if (ok) {
439                         *ret += 8 * vbo;
440                         return 0;
441                 }
442
443                 if (++vblock >= eblock) {
444                         *ret = MINUS_ONE_T;
445                         return 0;
446                 }
447         }
448         blk = 0;
449         vcn_next = vcn + clen;
450         down_read(lock);
451         ok = run_get_entry(run, ++idx, &vcn, &lcn, &clen) && vcn == vcn_next;
452         if (!ok)
453                 vcn = vcn_next;
454         up_read(lock);
455         goto next_run;
456 }
457
458 static bool scan_for_free(const ulong *buf, u32 bit, u32 bits, size_t *ret)
459 {
460         size_t pos = find_next_zero_bit(buf, bits, bit);
461
462         if (pos >= bits)
463                 return false;
464         *ret = pos;
465         return true;
466 }
467
468 /*
469  * indx_find_free - Look for free bit.
470  *
471  * Return: -1 if no free bits.
472  */
473 static int indx_find_free(struct ntfs_index *indx, struct ntfs_inode *ni,
474                           size_t *bit, struct ATTRIB **bitmap)
475 {
476         struct ATTRIB *b;
477         struct ATTR_LIST_ENTRY *le = NULL;
478         const struct INDEX_NAMES *in = &s_index_names[indx->type];
479         int err;
480
481         b = ni_find_attr(ni, NULL, &le, ATTR_BITMAP, in->name, in->name_len,
482                          NULL, NULL);
483
484         if (!b)
485                 return -ENOENT;
486
487         *bitmap = b;
488         *bit = MINUS_ONE_T;
489
490         if (!b->non_res) {
491                 u32 nbits = 8 * le32_to_cpu(b->res.data_size);
492                 size_t pos = find_next_zero_bit(resident_data(b), nbits, 0);
493
494                 if (pos < nbits)
495                         *bit = pos;
496         } else {
497                 err = scan_nres_bitmap(ni, b, indx, 0, &scan_for_free, bit);
498
499                 if (err)
500                         return err;
501         }
502
503         return 0;
504 }
505
506 static bool scan_for_used(const ulong *buf, u32 bit, u32 bits, size_t *ret)
507 {
508         size_t pos = find_next_bit(buf, bits, bit);
509
510         if (pos >= bits)
511                 return false;
512         *ret = pos;
513         return true;
514 }
515
516 /*
517  * indx_used_bit - Look for used bit.
518  *
519  * Return: MINUS_ONE_T if no used bits.
520  */
521 int indx_used_bit(struct ntfs_index *indx, struct ntfs_inode *ni, size_t *bit)
522 {
523         struct ATTRIB *b;
524         struct ATTR_LIST_ENTRY *le = NULL;
525         size_t from = *bit;
526         const struct INDEX_NAMES *in = &s_index_names[indx->type];
527         int err;
528
529         b = ni_find_attr(ni, NULL, &le, ATTR_BITMAP, in->name, in->name_len,
530                          NULL, NULL);
531
532         if (!b)
533                 return -ENOENT;
534
535         *bit = MINUS_ONE_T;
536
537         if (!b->non_res) {
538                 u32 nbits = le32_to_cpu(b->res.data_size) * 8;
539                 size_t pos = find_next_bit(resident_data(b), nbits, from);
540
541                 if (pos < nbits)
542                         *bit = pos;
543         } else {
544                 err = scan_nres_bitmap(ni, b, indx, from, &scan_for_used, bit);
545                 if (err)
546                         return err;
547         }
548
549         return 0;
550 }
551
552 /*
553  * hdr_find_split
554  *
555  * Find a point at which the index allocation buffer would like to be split.
556  * NOTE: This function should never return 'END' entry NULL returns on error.
557  */
558 static const struct NTFS_DE *hdr_find_split(const struct INDEX_HDR *hdr)
559 {
560         size_t o;
561         const struct NTFS_DE *e = hdr_first_de(hdr);
562         u32 used_2 = le32_to_cpu(hdr->used) >> 1;
563         u16 esize;
564
565         if (!e || de_is_last(e))
566                 return NULL;
567
568         esize = le16_to_cpu(e->size);
569         for (o = le32_to_cpu(hdr->de_off) + esize; o < used_2; o += esize) {
570                 const struct NTFS_DE *p = e;
571
572                 e = Add2Ptr(hdr, o);
573
574                 /* We must not return END entry. */
575                 if (de_is_last(e))
576                         return p;
577
578                 esize = le16_to_cpu(e->size);
579         }
580
581         return e;
582 }
583
584 /*
585  * hdr_insert_head - Insert some entries at the beginning of the buffer.
586  *
587  * It is used to insert entries into a newly-created buffer.
588  */
589 static const struct NTFS_DE *hdr_insert_head(struct INDEX_HDR *hdr,
590                                              const void *ins, u32 ins_bytes)
591 {
592         u32 to_move;
593         struct NTFS_DE *e = hdr_first_de(hdr);
594         u32 used = le32_to_cpu(hdr->used);
595
596         if (!e)
597                 return NULL;
598
599         /* Now we just make room for the inserted entries and jam it in. */
600         to_move = used - le32_to_cpu(hdr->de_off);
601         memmove(Add2Ptr(e, ins_bytes), e, to_move);
602         memcpy(e, ins, ins_bytes);
603         hdr->used = cpu_to_le32(used + ins_bytes);
604
605         return e;
606 }
607
608 /*
609  * index_hdr_check
610  *
611  * return true if INDEX_HDR is valid
612  */
613 static bool index_hdr_check(const struct INDEX_HDR *hdr, u32 bytes)
614 {
615         u32 end = le32_to_cpu(hdr->used);
616         u32 tot = le32_to_cpu(hdr->total);
617         u32 off = le32_to_cpu(hdr->de_off);
618
619         if (!IS_ALIGNED(off, 8) || tot > bytes || end > tot ||
620             off + sizeof(struct NTFS_DE) > end) {
621                 /* incorrect index buffer. */
622                 return false;
623         }
624
625         return true;
626 }
627
628 /*
629  * index_buf_check
630  *
631  * return true if INDEX_BUFFER seems is valid
632  */
633 static bool index_buf_check(const struct INDEX_BUFFER *ib, u32 bytes,
634                             const CLST *vbn)
635 {
636         const struct NTFS_RECORD_HEADER *rhdr = &ib->rhdr;
637         u16 fo = le16_to_cpu(rhdr->fix_off);
638         u16 fn = le16_to_cpu(rhdr->fix_num);
639
640         if (bytes <= offsetof(struct INDEX_BUFFER, ihdr) ||
641             rhdr->sign != NTFS_INDX_SIGNATURE ||
642             fo < sizeof(struct INDEX_BUFFER)
643             /* Check index buffer vbn. */
644             || (vbn && *vbn != le64_to_cpu(ib->vbn)) || (fo % sizeof(short)) ||
645             fo + fn * sizeof(short) >= bytes ||
646             fn != ((bytes >> SECTOR_SHIFT) + 1)) {
647                 /* incorrect index buffer. */
648                 return false;
649         }
650
651         return index_hdr_check(&ib->ihdr,
652                                bytes - offsetof(struct INDEX_BUFFER, ihdr));
653 }
654
655 void fnd_clear(struct ntfs_fnd *fnd)
656 {
657         int i;
658
659         for (i = fnd->level - 1; i >= 0; i--) {
660                 struct indx_node *n = fnd->nodes[i];
661
662                 if (!n)
663                         continue;
664
665                 put_indx_node(n);
666                 fnd->nodes[i] = NULL;
667         }
668         fnd->level = 0;
669         fnd->root_de = NULL;
670 }
671
672 static int fnd_push(struct ntfs_fnd *fnd, struct indx_node *n,
673                     struct NTFS_DE *e)
674 {
675         int i;
676
677         i = fnd->level;
678         if (i < 0 || i >= ARRAY_SIZE(fnd->nodes))
679                 return -EINVAL;
680         fnd->nodes[i] = n;
681         fnd->de[i] = e;
682         fnd->level += 1;
683         return 0;
684 }
685
686 static struct indx_node *fnd_pop(struct ntfs_fnd *fnd)
687 {
688         struct indx_node *n;
689         int i = fnd->level;
690
691         i -= 1;
692         n = fnd->nodes[i];
693         fnd->nodes[i] = NULL;
694         fnd->level = i;
695
696         return n;
697 }
698
699 static bool fnd_is_empty(struct ntfs_fnd *fnd)
700 {
701         if (!fnd->level)
702                 return !fnd->root_de;
703
704         return !fnd->de[fnd->level - 1];
705 }
706
707 /*
708  * hdr_find_e - Locate an entry the index buffer.
709  *
710  * If no matching entry is found, it returns the first entry which is greater
711  * than the desired entry If the search key is greater than all the entries the
712  * buffer, it returns the 'end' entry. This function does a binary search of the
713  * current index buffer, for the first entry that is <= to the search value.
714  *
715  * Return: NULL if error.
716  */
717 static struct NTFS_DE *hdr_find_e(const struct ntfs_index *indx,
718                                   const struct INDEX_HDR *hdr, const void *key,
719                                   size_t key_len, const void *ctx, int *diff)
720 {
721         struct NTFS_DE *e, *found = NULL;
722         NTFS_CMP_FUNC cmp = indx->cmp;
723         int min_idx = 0, mid_idx, max_idx = 0;
724         int diff2;
725         int table_size = 8;
726         u32 e_size, e_key_len;
727         u32 end = le32_to_cpu(hdr->used);
728         u32 off = le32_to_cpu(hdr->de_off);
729         u32 total = le32_to_cpu(hdr->total);
730         u16 offs[128];
731
732         if (unlikely(!cmp))
733                 return NULL;
734
735 fill_table:
736         if (end > total)
737                 return NULL;
738
739         if (off + sizeof(struct NTFS_DE) > end)
740                 return NULL;
741
742         e = Add2Ptr(hdr, off);
743         e_size = le16_to_cpu(e->size);
744
745         if (e_size < sizeof(struct NTFS_DE) || off + e_size > end)
746                 return NULL;
747
748         if (!de_is_last(e)) {
749                 offs[max_idx] = off;
750                 off += e_size;
751
752                 max_idx++;
753                 if (max_idx < table_size)
754                         goto fill_table;
755
756                 max_idx--;
757         }
758
759 binary_search:
760         e_key_len = le16_to_cpu(e->key_size);
761
762         diff2 = (*cmp)(key, key_len, e + 1, e_key_len, ctx);
763         if (diff2 > 0) {
764                 if (found) {
765                         min_idx = mid_idx + 1;
766                 } else {
767                         if (de_is_last(e))
768                                 return NULL;
769
770                         max_idx = 0;
771                         table_size = min(table_size * 2,
772                                          (int)ARRAY_SIZE(offs));
773                         goto fill_table;
774                 }
775         } else if (diff2 < 0) {
776                 if (found)
777                         max_idx = mid_idx - 1;
778                 else
779                         max_idx--;
780
781                 found = e;
782         } else {
783                 *diff = 0;
784                 return e;
785         }
786
787         if (min_idx > max_idx) {
788                 *diff = -1;
789                 return found;
790         }
791
792         mid_idx = (min_idx + max_idx) >> 1;
793         e = Add2Ptr(hdr, offs[mid_idx]);
794
795         goto binary_search;
796 }
797
798 /*
799  * hdr_insert_de - Insert an index entry into the buffer.
800  *
801  * 'before' should be a pointer previously returned from hdr_find_e.
802  */
803 static struct NTFS_DE *hdr_insert_de(const struct ntfs_index *indx,
804                                      struct INDEX_HDR *hdr,
805                                      const struct NTFS_DE *de,
806                                      struct NTFS_DE *before, const void *ctx)
807 {
808         int diff;
809         size_t off = PtrOffset(hdr, before);
810         u32 used = le32_to_cpu(hdr->used);
811         u32 total = le32_to_cpu(hdr->total);
812         u16 de_size = le16_to_cpu(de->size);
813
814         /* First, check to see if there's enough room. */
815         if (used + de_size > total)
816                 return NULL;
817
818         /* We know there's enough space, so we know we'll succeed. */
819         if (before) {
820                 /* Check that before is inside Index. */
821                 if (off >= used || off < le32_to_cpu(hdr->de_off) ||
822                     off + le16_to_cpu(before->size) > total) {
823                         return NULL;
824                 }
825                 goto ok;
826         }
827         /* No insert point is applied. Get it manually. */
828         before = hdr_find_e(indx, hdr, de + 1, le16_to_cpu(de->key_size), ctx,
829                             &diff);
830         if (!before)
831                 return NULL;
832         off = PtrOffset(hdr, before);
833
834 ok:
835         /* Now we just make room for the entry and jam it in. */
836         memmove(Add2Ptr(before, de_size), before, used - off);
837
838         hdr->used = cpu_to_le32(used + de_size);
839         memcpy(before, de, de_size);
840
841         return before;
842 }
843
844 /*
845  * hdr_delete_de - Remove an entry from the index buffer.
846  */
847 static inline struct NTFS_DE *hdr_delete_de(struct INDEX_HDR *hdr,
848                                             struct NTFS_DE *re)
849 {
850         u32 used = le32_to_cpu(hdr->used);
851         u16 esize = le16_to_cpu(re->size);
852         u32 off = PtrOffset(hdr, re);
853         int bytes = used - (off + esize);
854
855         /* check INDEX_HDR valid before using INDEX_HDR */
856         if (!check_index_header(hdr, le32_to_cpu(hdr->total)))
857                 return NULL;
858
859         if (off >= used || esize < sizeof(struct NTFS_DE) ||
860             bytes < sizeof(struct NTFS_DE))
861                 return NULL;
862
863         hdr->used = cpu_to_le32(used - esize);
864         memmove(re, Add2Ptr(re, esize), bytes);
865
866         return re;
867 }
868
869 void indx_clear(struct ntfs_index *indx)
870 {
871         run_close(&indx->alloc_run);
872         run_close(&indx->bitmap_run);
873 }
874
875 int indx_init(struct ntfs_index *indx, struct ntfs_sb_info *sbi,
876               const struct ATTRIB *attr, enum index_mutex_classed type)
877 {
878         u32 t32;
879         const struct INDEX_ROOT *root = resident_data(attr);
880
881         t32 = le32_to_cpu(attr->res.data_size);
882         if (t32 <= offsetof(struct INDEX_ROOT, ihdr) ||
883             !index_hdr_check(&root->ihdr,
884                              t32 - offsetof(struct INDEX_ROOT, ihdr))) {
885                 goto out;
886         }
887
888         /* Check root fields. */
889         if (!root->index_block_clst)
890                 goto out;
891
892         indx->type = type;
893         indx->idx2vbn_bits = __ffs(root->index_block_clst);
894
895         t32 = le32_to_cpu(root->index_block_size);
896         indx->index_bits = blksize_bits(t32);
897
898         /* Check index record size. */
899         if (t32 < sbi->cluster_size) {
900                 /* Index record is smaller than a cluster, use 512 blocks. */
901                 if (t32 != root->index_block_clst * SECTOR_SIZE)
902                         goto out;
903
904                 /* Check alignment to a cluster. */
905                 if ((sbi->cluster_size >> SECTOR_SHIFT) &
906                     (root->index_block_clst - 1)) {
907                         goto out;
908                 }
909
910                 indx->vbn2vbo_bits = SECTOR_SHIFT;
911         } else {
912                 /* Index record must be a multiple of cluster size. */
913                 if (t32 != root->index_block_clst << sbi->cluster_bits)
914                         goto out;
915
916                 indx->vbn2vbo_bits = sbi->cluster_bits;
917         }
918
919         init_rwsem(&indx->run_lock);
920
921         indx->cmp = get_cmp_func(root);
922         if (!indx->cmp)
923                 goto out;
924
925         return 0;
926
927 out:
928         ntfs_set_state(sbi, NTFS_DIRTY_DIRTY);
929         return -EINVAL;
930 }
931
932 static struct indx_node *indx_new(struct ntfs_index *indx,
933                                   struct ntfs_inode *ni, CLST vbn,
934                                   const __le64 *sub_vbn)
935 {
936         int err;
937         struct NTFS_DE *e;
938         struct indx_node *r;
939         struct INDEX_HDR *hdr;
940         struct INDEX_BUFFER *index;
941         u64 vbo = (u64)vbn << indx->vbn2vbo_bits;
942         u32 bytes = 1u << indx->index_bits;
943         u16 fn;
944         u32 eo;
945
946         r = kzalloc(sizeof(struct indx_node), GFP_NOFS);
947         if (!r)
948                 return ERR_PTR(-ENOMEM);
949
950         index = kzalloc(bytes, GFP_NOFS);
951         if (!index) {
952                 kfree(r);
953                 return ERR_PTR(-ENOMEM);
954         }
955
956         err = ntfs_get_bh(ni->mi.sbi, &indx->alloc_run, vbo, bytes, &r->nb);
957
958         if (err) {
959                 kfree(index);
960                 kfree(r);
961                 return ERR_PTR(err);
962         }
963
964         /* Create header. */
965         index->rhdr.sign = NTFS_INDX_SIGNATURE;
966         index->rhdr.fix_off = cpu_to_le16(sizeof(struct INDEX_BUFFER)); // 0x28
967         fn = (bytes >> SECTOR_SHIFT) + 1; // 9
968         index->rhdr.fix_num = cpu_to_le16(fn);
969         index->vbn = cpu_to_le64(vbn);
970         hdr = &index->ihdr;
971         eo = ALIGN(sizeof(struct INDEX_BUFFER) + fn * sizeof(short), 8);
972         hdr->de_off = cpu_to_le32(eo);
973
974         e = Add2Ptr(hdr, eo);
975
976         if (sub_vbn) {
977                 e->flags = NTFS_IE_LAST | NTFS_IE_HAS_SUBNODES;
978                 e->size = cpu_to_le16(sizeof(struct NTFS_DE) + sizeof(u64));
979                 hdr->used =
980                         cpu_to_le32(eo + sizeof(struct NTFS_DE) + sizeof(u64));
981                 de_set_vbn_le(e, *sub_vbn);
982                 hdr->flags = 1;
983         } else {
984                 e->size = cpu_to_le16(sizeof(struct NTFS_DE));
985                 hdr->used = cpu_to_le32(eo + sizeof(struct NTFS_DE));
986                 e->flags = NTFS_IE_LAST;
987         }
988
989         hdr->total = cpu_to_le32(bytes - offsetof(struct INDEX_BUFFER, ihdr));
990
991         r->index = index;
992         return r;
993 }
994
995 struct INDEX_ROOT *indx_get_root(struct ntfs_index *indx, struct ntfs_inode *ni,
996                                  struct ATTRIB **attr, struct mft_inode **mi)
997 {
998         struct ATTR_LIST_ENTRY *le = NULL;
999         struct ATTRIB *a;
1000         const struct INDEX_NAMES *in = &s_index_names[indx->type];
1001         struct INDEX_ROOT *root = NULL;
1002
1003         a = ni_find_attr(ni, NULL, &le, ATTR_ROOT, in->name, in->name_len, NULL,
1004                          mi);
1005         if (!a)
1006                 return NULL;
1007
1008         if (attr)
1009                 *attr = a;
1010
1011         root = resident_data_ex(a, sizeof(struct INDEX_ROOT));
1012
1013         /* length check */
1014         if (root && offsetof(struct INDEX_ROOT, ihdr) + le32_to_cpu(root->ihdr.used) >
1015                         le32_to_cpu(a->res.data_size)) {
1016                 return NULL;
1017         }
1018
1019         return root;
1020 }
1021
1022 static int indx_write(struct ntfs_index *indx, struct ntfs_inode *ni,
1023                       struct indx_node *node, int sync)
1024 {
1025         struct INDEX_BUFFER *ib = node->index;
1026
1027         return ntfs_write_bh(ni->mi.sbi, &ib->rhdr, &node->nb, sync);
1028 }
1029
1030 /*
1031  * indx_read
1032  *
1033  * If ntfs_readdir calls this function
1034  * inode is shared locked and no ni_lock.
1035  * Use rw_semaphore for read/write access to alloc_run.
1036  */
1037 int indx_read(struct ntfs_index *indx, struct ntfs_inode *ni, CLST vbn,
1038               struct indx_node **node)
1039 {
1040         int err;
1041         struct INDEX_BUFFER *ib;
1042         struct runs_tree *run = &indx->alloc_run;
1043         struct rw_semaphore *lock = &indx->run_lock;
1044         u64 vbo = (u64)vbn << indx->vbn2vbo_bits;
1045         u32 bytes = 1u << indx->index_bits;
1046         struct indx_node *in = *node;
1047         const struct INDEX_NAMES *name;
1048
1049         if (!in) {
1050                 in = kzalloc(sizeof(struct indx_node), GFP_NOFS);
1051                 if (!in)
1052                         return -ENOMEM;
1053         } else {
1054                 nb_put(&in->nb);
1055         }
1056
1057         ib = in->index;
1058         if (!ib) {
1059                 ib = kmalloc(bytes, GFP_NOFS);
1060                 if (!ib) {
1061                         err = -ENOMEM;
1062                         goto out;
1063                 }
1064         }
1065
1066         down_read(lock);
1067         err = ntfs_read_bh(ni->mi.sbi, run, vbo, &ib->rhdr, bytes, &in->nb);
1068         up_read(lock);
1069         if (!err)
1070                 goto ok;
1071
1072         if (err == -E_NTFS_FIXUP)
1073                 goto ok;
1074
1075         if (err != -ENOENT)
1076                 goto out;
1077
1078         name = &s_index_names[indx->type];
1079         down_write(lock);
1080         err = attr_load_runs_range(ni, ATTR_ALLOC, name->name, name->name_len,
1081                                    run, vbo, vbo + bytes);
1082         up_write(lock);
1083         if (err)
1084                 goto out;
1085
1086         down_read(lock);
1087         err = ntfs_read_bh(ni->mi.sbi, run, vbo, &ib->rhdr, bytes, &in->nb);
1088         up_read(lock);
1089         if (err == -E_NTFS_FIXUP)
1090                 goto ok;
1091
1092         if (err)
1093                 goto out;
1094
1095 ok:
1096         if (!index_buf_check(ib, bytes, &vbn)) {
1097                 ntfs_inode_err(&ni->vfs_inode, "directory corrupted");
1098                 ntfs_set_state(ni->mi.sbi, NTFS_DIRTY_ERROR);
1099                 err = -EINVAL;
1100                 goto out;
1101         }
1102
1103         if (err == -E_NTFS_FIXUP) {
1104                 ntfs_write_bh(ni->mi.sbi, &ib->rhdr, &in->nb, 0);
1105                 err = 0;
1106         }
1107
1108         /* check for index header length */
1109         if (offsetof(struct INDEX_BUFFER, ihdr) + ib->ihdr.used > bytes) {
1110                 err = -EINVAL;
1111                 goto out;
1112         }
1113
1114         in->index = ib;
1115         *node = in;
1116
1117 out:
1118         if (err == -E_NTFS_CORRUPT) {
1119                 ntfs_inode_err(&ni->vfs_inode, "directory corrupted");
1120                 ntfs_set_state(ni->mi.sbi, NTFS_DIRTY_ERROR);
1121                 err = -EINVAL;
1122         }
1123
1124         if (ib != in->index)
1125                 kfree(ib);
1126
1127         if (*node != in) {
1128                 nb_put(&in->nb);
1129                 kfree(in);
1130         }
1131
1132         return err;
1133 }
1134
1135 /*
1136  * indx_find - Scan NTFS directory for given entry.
1137  */
1138 int indx_find(struct ntfs_index *indx, struct ntfs_inode *ni,
1139               const struct INDEX_ROOT *root, const void *key, size_t key_len,
1140               const void *ctx, int *diff, struct NTFS_DE **entry,
1141               struct ntfs_fnd *fnd)
1142 {
1143         int err;
1144         struct NTFS_DE *e;
1145         const struct INDEX_HDR *hdr;
1146         struct indx_node *node;
1147
1148         if (!root)
1149                 root = indx_get_root(&ni->dir, ni, NULL, NULL);
1150
1151         if (!root) {
1152                 err = -EINVAL;
1153                 goto out;
1154         }
1155
1156         hdr = &root->ihdr;
1157
1158         /* Check cache. */
1159         e = fnd->level ? fnd->de[fnd->level - 1] : fnd->root_de;
1160         if (e && !de_is_last(e) &&
1161             !(*indx->cmp)(key, key_len, e + 1, le16_to_cpu(e->key_size), ctx)) {
1162                 *entry = e;
1163                 *diff = 0;
1164                 return 0;
1165         }
1166
1167         /* Soft finder reset. */
1168         fnd_clear(fnd);
1169
1170         /* Lookup entry that is <= to the search value. */
1171         e = hdr_find_e(indx, hdr, key, key_len, ctx, diff);
1172         if (!e)
1173                 return -EINVAL;
1174
1175         fnd->root_de = e;
1176         err = 0;
1177
1178         for (;;) {
1179                 node = NULL;
1180                 if (*diff >= 0 || !de_has_vcn_ex(e)) {
1181                         *entry = e;
1182                         goto out;
1183                 }
1184
1185                 /* Read next level. */
1186                 err = indx_read(indx, ni, de_get_vbn(e), &node);
1187                 if (err)
1188                         goto out;
1189
1190                 /* Lookup entry that is <= to the search value. */
1191                 e = hdr_find_e(indx, &node->index->ihdr, key, key_len, ctx,
1192                                diff);
1193                 if (!e) {
1194                         err = -EINVAL;
1195                         put_indx_node(node);
1196                         goto out;
1197                 }
1198
1199                 fnd_push(fnd, node, e);
1200         }
1201
1202 out:
1203         return err;
1204 }
1205
1206 int indx_find_sort(struct ntfs_index *indx, struct ntfs_inode *ni,
1207                    const struct INDEX_ROOT *root, struct NTFS_DE **entry,
1208                    struct ntfs_fnd *fnd)
1209 {
1210         int err;
1211         struct indx_node *n = NULL;
1212         struct NTFS_DE *e;
1213         size_t iter = 0;
1214         int level = fnd->level;
1215
1216         if (!*entry) {
1217                 /* Start find. */
1218                 e = hdr_first_de(&root->ihdr);
1219                 if (!e)
1220                         return 0;
1221                 fnd_clear(fnd);
1222                 fnd->root_de = e;
1223         } else if (!level) {
1224                 if (de_is_last(fnd->root_de)) {
1225                         *entry = NULL;
1226                         return 0;
1227                 }
1228
1229                 e = hdr_next_de(&root->ihdr, fnd->root_de);
1230                 if (!e)
1231                         return -EINVAL;
1232                 fnd->root_de = e;
1233         } else {
1234                 n = fnd->nodes[level - 1];
1235                 e = fnd->de[level - 1];
1236
1237                 if (de_is_last(e))
1238                         goto pop_level;
1239
1240                 e = hdr_next_de(&n->index->ihdr, e);
1241                 if (!e)
1242                         return -EINVAL;
1243
1244                 fnd->de[level - 1] = e;
1245         }
1246
1247         /* Just to avoid tree cycle. */
1248 next_iter:
1249         if (iter++ >= 1000)
1250                 return -EINVAL;
1251
1252         while (de_has_vcn_ex(e)) {
1253                 if (le16_to_cpu(e->size) <
1254                     sizeof(struct NTFS_DE) + sizeof(u64)) {
1255                         if (n) {
1256                                 fnd_pop(fnd);
1257                                 kfree(n);
1258                         }
1259                         return -EINVAL;
1260                 }
1261
1262                 /* Read next level. */
1263                 err = indx_read(indx, ni, de_get_vbn(e), &n);
1264                 if (err)
1265                         return err;
1266
1267                 /* Try next level. */
1268                 e = hdr_first_de(&n->index->ihdr);
1269                 if (!e) {
1270                         kfree(n);
1271                         return -EINVAL;
1272                 }
1273
1274                 fnd_push(fnd, n, e);
1275         }
1276
1277         if (le16_to_cpu(e->size) > sizeof(struct NTFS_DE)) {
1278                 *entry = e;
1279                 return 0;
1280         }
1281
1282 pop_level:
1283         for (;;) {
1284                 if (!de_is_last(e))
1285                         goto next_iter;
1286
1287                 /* Pop one level. */
1288                 if (n) {
1289                         fnd_pop(fnd);
1290                         kfree(n);
1291                 }
1292
1293                 level = fnd->level;
1294
1295                 if (level) {
1296                         n = fnd->nodes[level - 1];
1297                         e = fnd->de[level - 1];
1298                 } else if (fnd->root_de) {
1299                         n = NULL;
1300                         e = fnd->root_de;
1301                         fnd->root_de = NULL;
1302                 } else {
1303                         *entry = NULL;
1304                         return 0;
1305                 }
1306
1307                 if (le16_to_cpu(e->size) > sizeof(struct NTFS_DE)) {
1308                         *entry = e;
1309                         if (!fnd->root_de)
1310                                 fnd->root_de = e;
1311                         return 0;
1312                 }
1313         }
1314 }
1315
1316 int indx_find_raw(struct ntfs_index *indx, struct ntfs_inode *ni,
1317                   const struct INDEX_ROOT *root, struct NTFS_DE **entry,
1318                   size_t *off, struct ntfs_fnd *fnd)
1319 {
1320         int err;
1321         struct indx_node *n = NULL;
1322         struct NTFS_DE *e = NULL;
1323         struct NTFS_DE *e2;
1324         size_t bit;
1325         CLST next_used_vbn;
1326         CLST next_vbn;
1327         u32 record_size = ni->mi.sbi->record_size;
1328
1329         /* Use non sorted algorithm. */
1330         if (!*entry) {
1331                 /* This is the first call. */
1332                 e = hdr_first_de(&root->ihdr);
1333                 if (!e)
1334                         return 0;
1335                 fnd_clear(fnd);
1336                 fnd->root_de = e;
1337
1338                 /* The first call with setup of initial element. */
1339                 if (*off >= record_size) {
1340                         next_vbn = (((*off - record_size) >> indx->index_bits))
1341                                    << indx->idx2vbn_bits;
1342                         /* Jump inside cycle 'for'. */
1343                         goto next;
1344                 }
1345
1346                 /* Start enumeration from root. */
1347                 *off = 0;
1348         } else if (!fnd->root_de)
1349                 return -EINVAL;
1350
1351         for (;;) {
1352                 /* Check if current entry can be used. */
1353                 if (e && le16_to_cpu(e->size) > sizeof(struct NTFS_DE))
1354                         goto ok;
1355
1356                 if (!fnd->level) {
1357                         /* Continue to enumerate root. */
1358                         if (!de_is_last(fnd->root_de)) {
1359                                 e = hdr_next_de(&root->ihdr, fnd->root_de);
1360                                 if (!e)
1361                                         return -EINVAL;
1362                                 fnd->root_de = e;
1363                                 continue;
1364                         }
1365
1366                         /* Start to enumerate indexes from 0. */
1367                         next_vbn = 0;
1368                 } else {
1369                         /* Continue to enumerate indexes. */
1370                         e2 = fnd->de[fnd->level - 1];
1371
1372                         n = fnd->nodes[fnd->level - 1];
1373
1374                         if (!de_is_last(e2)) {
1375                                 e = hdr_next_de(&n->index->ihdr, e2);
1376                                 if (!e)
1377                                         return -EINVAL;
1378                                 fnd->de[fnd->level - 1] = e;
1379                                 continue;
1380                         }
1381
1382                         /* Continue with next index. */
1383                         next_vbn = le64_to_cpu(n->index->vbn) +
1384                                    root->index_block_clst;
1385                 }
1386
1387 next:
1388                 /* Release current index. */
1389                 if (n) {
1390                         fnd_pop(fnd);
1391                         put_indx_node(n);
1392                         n = NULL;
1393                 }
1394
1395                 /* Skip all free indexes. */
1396                 bit = next_vbn >> indx->idx2vbn_bits;
1397                 err = indx_used_bit(indx, ni, &bit);
1398                 if (err == -ENOENT || bit == MINUS_ONE_T) {
1399                         /* No used indexes. */
1400                         *entry = NULL;
1401                         return 0;
1402                 }
1403
1404                 next_used_vbn = bit << indx->idx2vbn_bits;
1405
1406                 /* Read buffer into memory. */
1407                 err = indx_read(indx, ni, next_used_vbn, &n);
1408                 if (err)
1409                         return err;
1410
1411                 e = hdr_first_de(&n->index->ihdr);
1412                 fnd_push(fnd, n, e);
1413                 if (!e)
1414                         return -EINVAL;
1415         }
1416
1417 ok:
1418         /* Return offset to restore enumerator if necessary. */
1419         if (!n) {
1420                 /* 'e' points in root, */
1421                 *off = PtrOffset(&root->ihdr, e);
1422         } else {
1423                 /* 'e' points in index, */
1424                 *off = (le64_to_cpu(n->index->vbn) << indx->vbn2vbo_bits) +
1425                        record_size + PtrOffset(&n->index->ihdr, e);
1426         }
1427
1428         *entry = e;
1429         return 0;
1430 }
1431
1432 /*
1433  * indx_create_allocate - Create "Allocation + Bitmap" attributes.
1434  */
1435 static int indx_create_allocate(struct ntfs_index *indx, struct ntfs_inode *ni,
1436                                 CLST *vbn)
1437 {
1438         int err;
1439         struct ntfs_sb_info *sbi = ni->mi.sbi;
1440         struct ATTRIB *bitmap;
1441         struct ATTRIB *alloc;
1442         u32 data_size = 1u << indx->index_bits;
1443         u32 alloc_size = ntfs_up_cluster(sbi, data_size);
1444         CLST len = alloc_size >> sbi->cluster_bits;
1445         const struct INDEX_NAMES *in = &s_index_names[indx->type];
1446         CLST alen;
1447         struct runs_tree run;
1448
1449         run_init(&run);
1450
1451         err = attr_allocate_clusters(sbi, &run, 0, 0, len, NULL, 0, &alen, 0,
1452                                      NULL);
1453         if (err)
1454                 goto out;
1455
1456         err = ni_insert_nonresident(ni, ATTR_ALLOC, in->name, in->name_len,
1457                                     &run, 0, len, 0, &alloc, NULL);
1458         if (err)
1459                 goto out1;
1460
1461         alloc->nres.valid_size = alloc->nres.data_size = cpu_to_le64(data_size);
1462
1463         err = ni_insert_resident(ni, bitmap_size(1), ATTR_BITMAP, in->name,
1464                                  in->name_len, &bitmap, NULL, NULL);
1465         if (err)
1466                 goto out2;
1467
1468         if (in->name == I30_NAME) {
1469                 ni->vfs_inode.i_size = data_size;
1470                 inode_set_bytes(&ni->vfs_inode, alloc_size);
1471         }
1472
1473         memcpy(&indx->alloc_run, &run, sizeof(run));
1474
1475         *vbn = 0;
1476
1477         return 0;
1478
1479 out2:
1480         mi_remove_attr(NULL, &ni->mi, alloc);
1481
1482 out1:
1483         run_deallocate(sbi, &run, false);
1484
1485 out:
1486         return err;
1487 }
1488
1489 /*
1490  * indx_add_allocate - Add clusters to index.
1491  */
1492 static int indx_add_allocate(struct ntfs_index *indx, struct ntfs_inode *ni,
1493                              CLST *vbn)
1494 {
1495         int err;
1496         size_t bit;
1497         u64 data_size;
1498         u64 bmp_size, bmp_size_v;
1499         struct ATTRIB *bmp, *alloc;
1500         struct mft_inode *mi;
1501         const struct INDEX_NAMES *in = &s_index_names[indx->type];
1502
1503         err = indx_find_free(indx, ni, &bit, &bmp);
1504         if (err)
1505                 goto out1;
1506
1507         if (bit != MINUS_ONE_T) {
1508                 bmp = NULL;
1509         } else {
1510                 if (bmp->non_res) {
1511                         bmp_size = le64_to_cpu(bmp->nres.data_size);
1512                         bmp_size_v = le64_to_cpu(bmp->nres.valid_size);
1513                 } else {
1514                         bmp_size = bmp_size_v = le32_to_cpu(bmp->res.data_size);
1515                 }
1516
1517                 bit = bmp_size << 3;
1518         }
1519
1520         data_size = (u64)(bit + 1) << indx->index_bits;
1521
1522         if (bmp) {
1523                 /* Increase bitmap. */
1524                 err = attr_set_size(ni, ATTR_BITMAP, in->name, in->name_len,
1525                                     &indx->bitmap_run, bitmap_size(bit + 1),
1526                                     NULL, true, NULL);
1527                 if (err)
1528                         goto out1;
1529         }
1530
1531         alloc = ni_find_attr(ni, NULL, NULL, ATTR_ALLOC, in->name, in->name_len,
1532                              NULL, &mi);
1533         if (!alloc) {
1534                 err = -EINVAL;
1535                 if (bmp)
1536                         goto out2;
1537                 goto out1;
1538         }
1539
1540         /* Increase allocation. */
1541         err = attr_set_size(ni, ATTR_ALLOC, in->name, in->name_len,
1542                             &indx->alloc_run, data_size, &data_size, true,
1543                             NULL);
1544         if (err) {
1545                 if (bmp)
1546                         goto out2;
1547                 goto out1;
1548         }
1549
1550         *vbn = bit << indx->idx2vbn_bits;
1551
1552         return 0;
1553
1554 out2:
1555         /* Ops. No space? */
1556         attr_set_size(ni, ATTR_BITMAP, in->name, in->name_len,
1557                       &indx->bitmap_run, bmp_size, &bmp_size_v, false, NULL);
1558
1559 out1:
1560         return err;
1561 }
1562
1563 /*
1564  * indx_insert_into_root - Attempt to insert an entry into the index root.
1565  *
1566  * @undo - True if we undoing previous remove.
1567  * If necessary, it will twiddle the index b-tree.
1568  */
1569 static int indx_insert_into_root(struct ntfs_index *indx, struct ntfs_inode *ni,
1570                                  const struct NTFS_DE *new_de,
1571                                  struct NTFS_DE *root_de, const void *ctx,
1572                                  struct ntfs_fnd *fnd, bool undo)
1573 {
1574         int err = 0;
1575         struct NTFS_DE *e, *e0, *re;
1576         struct mft_inode *mi;
1577         struct ATTRIB *attr;
1578         struct INDEX_HDR *hdr;
1579         struct indx_node *n;
1580         CLST new_vbn;
1581         __le64 *sub_vbn, t_vbn;
1582         u16 new_de_size;
1583         u32 hdr_used, hdr_total, asize, to_move;
1584         u32 root_size, new_root_size;
1585         struct ntfs_sb_info *sbi;
1586         int ds_root;
1587         struct INDEX_ROOT *root, *a_root;
1588
1589         /* Get the record this root placed in. */
1590         root = indx_get_root(indx, ni, &attr, &mi);
1591         if (!root)
1592                 return -EINVAL;
1593
1594         /*
1595          * Try easy case:
1596          * hdr_insert_de will succeed if there's
1597          * room the root for the new entry.
1598          */
1599         hdr = &root->ihdr;
1600         sbi = ni->mi.sbi;
1601         new_de_size = le16_to_cpu(new_de->size);
1602         hdr_used = le32_to_cpu(hdr->used);
1603         hdr_total = le32_to_cpu(hdr->total);
1604         asize = le32_to_cpu(attr->size);
1605         root_size = le32_to_cpu(attr->res.data_size);
1606
1607         ds_root = new_de_size + hdr_used - hdr_total;
1608
1609         /* If 'undo' is set then reduce requirements. */
1610         if ((undo || asize + ds_root < sbi->max_bytes_per_attr) &&
1611             mi_resize_attr(mi, attr, ds_root)) {
1612                 hdr->total = cpu_to_le32(hdr_total + ds_root);
1613                 e = hdr_insert_de(indx, hdr, new_de, root_de, ctx);
1614                 WARN_ON(!e);
1615                 fnd_clear(fnd);
1616                 fnd->root_de = e;
1617
1618                 return 0;
1619         }
1620
1621         /* Make a copy of root attribute to restore if error. */
1622         a_root = kmemdup(attr, asize, GFP_NOFS);
1623         if (!a_root)
1624                 return -ENOMEM;
1625
1626         /*
1627          * Copy all the non-end entries from
1628          * the index root to the new buffer.
1629          */
1630         to_move = 0;
1631         e0 = hdr_first_de(hdr);
1632
1633         /* Calculate the size to copy. */
1634         for (e = e0;; e = hdr_next_de(hdr, e)) {
1635                 if (!e) {
1636                         err = -EINVAL;
1637                         goto out_free_root;
1638                 }
1639
1640                 if (de_is_last(e))
1641                         break;
1642                 to_move += le16_to_cpu(e->size);
1643         }
1644
1645         if (!to_move) {
1646                 re = NULL;
1647         } else {
1648                 re = kmemdup(e0, to_move, GFP_NOFS);
1649                 if (!re) {
1650                         err = -ENOMEM;
1651                         goto out_free_root;
1652                 }
1653         }
1654
1655         sub_vbn = NULL;
1656         if (de_has_vcn(e)) {
1657                 t_vbn = de_get_vbn_le(e);
1658                 sub_vbn = &t_vbn;
1659         }
1660
1661         new_root_size = sizeof(struct INDEX_ROOT) + sizeof(struct NTFS_DE) +
1662                         sizeof(u64);
1663         ds_root = new_root_size - root_size;
1664
1665         if (ds_root > 0 && asize + ds_root > sbi->max_bytes_per_attr) {
1666                 /* Make root external. */
1667                 err = -EOPNOTSUPP;
1668                 goto out_free_re;
1669         }
1670
1671         if (ds_root)
1672                 mi_resize_attr(mi, attr, ds_root);
1673
1674         /* Fill first entry (vcn will be set later). */
1675         e = (struct NTFS_DE *)(root + 1);
1676         memset(e, 0, sizeof(struct NTFS_DE));
1677         e->size = cpu_to_le16(sizeof(struct NTFS_DE) + sizeof(u64));
1678         e->flags = NTFS_IE_HAS_SUBNODES | NTFS_IE_LAST;
1679
1680         hdr->flags = 1;
1681         hdr->used = hdr->total =
1682                 cpu_to_le32(new_root_size - offsetof(struct INDEX_ROOT, ihdr));
1683
1684         fnd->root_de = hdr_first_de(hdr);
1685         mi->dirty = true;
1686
1687         /* Create alloc and bitmap attributes (if not). */
1688         err = run_is_empty(&indx->alloc_run)
1689                       ? indx_create_allocate(indx, ni, &new_vbn)
1690                       : indx_add_allocate(indx, ni, &new_vbn);
1691
1692         /* Layout of record may be changed, so rescan root. */
1693         root = indx_get_root(indx, ni, &attr, &mi);
1694         if (!root) {
1695                 /* Bug? */
1696                 ntfs_set_state(sbi, NTFS_DIRTY_ERROR);
1697                 err = -EINVAL;
1698                 goto out_free_re;
1699         }
1700
1701         if (err) {
1702                 /* Restore root. */
1703                 if (mi_resize_attr(mi, attr, -ds_root)) {
1704                         memcpy(attr, a_root, asize);
1705                 } else {
1706                         /* Bug? */
1707                         ntfs_set_state(sbi, NTFS_DIRTY_ERROR);
1708                 }
1709                 goto out_free_re;
1710         }
1711
1712         e = (struct NTFS_DE *)(root + 1);
1713         *(__le64 *)(e + 1) = cpu_to_le64(new_vbn);
1714         mi->dirty = true;
1715
1716         /* Now we can create/format the new buffer and copy the entries into. */
1717         n = indx_new(indx, ni, new_vbn, sub_vbn);
1718         if (IS_ERR(n)) {
1719                 err = PTR_ERR(n);
1720                 goto out_free_re;
1721         }
1722
1723         hdr = &n->index->ihdr;
1724         hdr_used = le32_to_cpu(hdr->used);
1725         hdr_total = le32_to_cpu(hdr->total);
1726
1727         /* Copy root entries into new buffer. */
1728         hdr_insert_head(hdr, re, to_move);
1729
1730         /* Update bitmap attribute. */
1731         indx_mark_used(indx, ni, new_vbn >> indx->idx2vbn_bits);
1732
1733         /* Check if we can insert new entry new index buffer. */
1734         if (hdr_used + new_de_size > hdr_total) {
1735                 /*
1736                  * This occurs if MFT record is the same or bigger than index
1737                  * buffer. Move all root new index and have no space to add
1738                  * new entry classic case when MFT record is 1K and index
1739                  * buffer 4K the problem should not occurs.
1740                  */
1741                 kfree(re);
1742                 indx_write(indx, ni, n, 0);
1743
1744                 put_indx_node(n);
1745                 fnd_clear(fnd);
1746                 err = indx_insert_entry(indx, ni, new_de, ctx, fnd, undo);
1747                 goto out_free_root;
1748         }
1749
1750         /*
1751          * Now root is a parent for new index buffer.
1752          * Insert NewEntry a new buffer.
1753          */
1754         e = hdr_insert_de(indx, hdr, new_de, NULL, ctx);
1755         if (!e) {
1756                 err = -EINVAL;
1757                 goto out_put_n;
1758         }
1759         fnd_push(fnd, n, e);
1760
1761         /* Just write updates index into disk. */
1762         indx_write(indx, ni, n, 0);
1763
1764         n = NULL;
1765
1766 out_put_n:
1767         put_indx_node(n);
1768 out_free_re:
1769         kfree(re);
1770 out_free_root:
1771         kfree(a_root);
1772         return err;
1773 }
1774
1775 /*
1776  * indx_insert_into_buffer
1777  *
1778  * Attempt to insert an entry into an Index Allocation Buffer.
1779  * If necessary, it will split the buffer.
1780  */
1781 static int
1782 indx_insert_into_buffer(struct ntfs_index *indx, struct ntfs_inode *ni,
1783                         struct INDEX_ROOT *root, const struct NTFS_DE *new_de,
1784                         const void *ctx, int level, struct ntfs_fnd *fnd)
1785 {
1786         int err;
1787         const struct NTFS_DE *sp;
1788         struct NTFS_DE *e, *de_t, *up_e = NULL;
1789         struct indx_node *n2 = NULL;
1790         struct indx_node *n1 = fnd->nodes[level];
1791         struct INDEX_HDR *hdr1 = &n1->index->ihdr;
1792         struct INDEX_HDR *hdr2;
1793         u32 to_copy, used;
1794         CLST new_vbn;
1795         __le64 t_vbn, *sub_vbn;
1796         u16 sp_size;
1797
1798         /* Try the most easy case. */
1799         e = fnd->level - 1 == level ? fnd->de[level] : NULL;
1800         e = hdr_insert_de(indx, hdr1, new_de, e, ctx);
1801         fnd->de[level] = e;
1802         if (e) {
1803                 /* Just write updated index into disk. */
1804                 indx_write(indx, ni, n1, 0);
1805                 return 0;
1806         }
1807
1808         /*
1809          * No space to insert into buffer. Split it.
1810          * To split we:
1811          *  - Save split point ('cause index buffers will be changed)
1812          * - Allocate NewBuffer and copy all entries <= sp into new buffer
1813          * - Remove all entries (sp including) from TargetBuffer
1814          * - Insert NewEntry into left or right buffer (depending on sp <=>
1815          *     NewEntry)
1816          * - Insert sp into parent buffer (or root)
1817          * - Make sp a parent for new buffer
1818          */
1819         sp = hdr_find_split(hdr1);
1820         if (!sp)
1821                 return -EINVAL;
1822
1823         sp_size = le16_to_cpu(sp->size);
1824         up_e = kmalloc(sp_size + sizeof(u64), GFP_NOFS);
1825         if (!up_e)
1826                 return -ENOMEM;
1827         memcpy(up_e, sp, sp_size);
1828
1829         if (!hdr1->flags) {
1830                 up_e->flags |= NTFS_IE_HAS_SUBNODES;
1831                 up_e->size = cpu_to_le16(sp_size + sizeof(u64));
1832                 sub_vbn = NULL;
1833         } else {
1834                 t_vbn = de_get_vbn_le(up_e);
1835                 sub_vbn = &t_vbn;
1836         }
1837
1838         /* Allocate on disk a new index allocation buffer. */
1839         err = indx_add_allocate(indx, ni, &new_vbn);
1840         if (err)
1841                 goto out;
1842
1843         /* Allocate and format memory a new index buffer. */
1844         n2 = indx_new(indx, ni, new_vbn, sub_vbn);
1845         if (IS_ERR(n2)) {
1846                 err = PTR_ERR(n2);
1847                 goto out;
1848         }
1849
1850         hdr2 = &n2->index->ihdr;
1851
1852         /* Make sp a parent for new buffer. */
1853         de_set_vbn(up_e, new_vbn);
1854
1855         /* Copy all the entries <= sp into the new buffer. */
1856         de_t = hdr_first_de(hdr1);
1857         to_copy = PtrOffset(de_t, sp);
1858         hdr_insert_head(hdr2, de_t, to_copy);
1859
1860         /* Remove all entries (sp including) from hdr1. */
1861         used = le32_to_cpu(hdr1->used) - to_copy - sp_size;
1862         memmove(de_t, Add2Ptr(sp, sp_size), used - le32_to_cpu(hdr1->de_off));
1863         hdr1->used = cpu_to_le32(used);
1864
1865         /*
1866          * Insert new entry into left or right buffer
1867          * (depending on sp <=> new_de).
1868          */
1869         hdr_insert_de(indx,
1870                       (*indx->cmp)(new_de + 1, le16_to_cpu(new_de->key_size),
1871                                    up_e + 1, le16_to_cpu(up_e->key_size),
1872                                    ctx) < 0
1873                               ? hdr2
1874                               : hdr1,
1875                       new_de, NULL, ctx);
1876
1877         indx_mark_used(indx, ni, new_vbn >> indx->idx2vbn_bits);
1878
1879         indx_write(indx, ni, n1, 0);
1880         indx_write(indx, ni, n2, 0);
1881
1882         put_indx_node(n2);
1883
1884         /*
1885          * We've finished splitting everybody, so we are ready to
1886          * insert the promoted entry into the parent.
1887          */
1888         if (!level) {
1889                 /* Insert in root. */
1890                 err = indx_insert_into_root(indx, ni, up_e, NULL, ctx, fnd, 0);
1891                 if (err)
1892                         goto out;
1893         } else {
1894                 /*
1895                  * The target buffer's parent is another index buffer.
1896                  * TODO: Remove recursion.
1897                  */
1898                 err = indx_insert_into_buffer(indx, ni, root, up_e, ctx,
1899                                               level - 1, fnd);
1900                 if (err)
1901                         goto out;
1902         }
1903
1904 out:
1905         kfree(up_e);
1906
1907         return err;
1908 }
1909
1910 /*
1911  * indx_insert_entry - Insert new entry into index.
1912  *
1913  * @undo - True if we undoing previous remove.
1914  */
1915 int indx_insert_entry(struct ntfs_index *indx, struct ntfs_inode *ni,
1916                       const struct NTFS_DE *new_de, const void *ctx,
1917                       struct ntfs_fnd *fnd, bool undo)
1918 {
1919         int err;
1920         int diff;
1921         struct NTFS_DE *e;
1922         struct ntfs_fnd *fnd_a = NULL;
1923         struct INDEX_ROOT *root;
1924
1925         if (!fnd) {
1926                 fnd_a = fnd_get();
1927                 if (!fnd_a) {
1928                         err = -ENOMEM;
1929                         goto out1;
1930                 }
1931                 fnd = fnd_a;
1932         }
1933
1934         root = indx_get_root(indx, ni, NULL, NULL);
1935         if (!root) {
1936                 err = -EINVAL;
1937                 goto out;
1938         }
1939
1940         if (fnd_is_empty(fnd)) {
1941                 /*
1942                  * Find the spot the tree where we want to
1943                  * insert the new entry.
1944                  */
1945                 err = indx_find(indx, ni, root, new_de + 1,
1946                                 le16_to_cpu(new_de->key_size), ctx, &diff, &e,
1947                                 fnd);
1948                 if (err)
1949                         goto out;
1950
1951                 if (!diff) {
1952                         err = -EEXIST;
1953                         goto out;
1954                 }
1955         }
1956
1957         if (!fnd->level) {
1958                 /*
1959                  * The root is also a leaf, so we'll insert the
1960                  * new entry into it.
1961                  */
1962                 err = indx_insert_into_root(indx, ni, new_de, fnd->root_de, ctx,
1963                                             fnd, undo);
1964                 if (err)
1965                         goto out;
1966         } else {
1967                 /*
1968                  * Found a leaf buffer, so we'll insert the new entry into it.
1969                  */
1970                 err = indx_insert_into_buffer(indx, ni, root, new_de, ctx,
1971                                               fnd->level - 1, fnd);
1972                 if (err)
1973                         goto out;
1974         }
1975
1976 out:
1977         fnd_put(fnd_a);
1978 out1:
1979         return err;
1980 }
1981
1982 /*
1983  * indx_find_buffer - Locate a buffer from the tree.
1984  */
1985 static struct indx_node *indx_find_buffer(struct ntfs_index *indx,
1986                                           struct ntfs_inode *ni,
1987                                           const struct INDEX_ROOT *root,
1988                                           __le64 vbn, struct indx_node *n)
1989 {
1990         int err;
1991         const struct NTFS_DE *e;
1992         struct indx_node *r;
1993         const struct INDEX_HDR *hdr = n ? &n->index->ihdr : &root->ihdr;
1994
1995         /* Step 1: Scan one level. */
1996         for (e = hdr_first_de(hdr);; e = hdr_next_de(hdr, e)) {
1997                 if (!e)
1998                         return ERR_PTR(-EINVAL);
1999
2000                 if (de_has_vcn(e) && vbn == de_get_vbn_le(e))
2001                         return n;
2002
2003                 if (de_is_last(e))
2004                         break;
2005         }
2006
2007         /* Step2: Do recursion. */
2008         e = Add2Ptr(hdr, le32_to_cpu(hdr->de_off));
2009         for (;;) {
2010                 if (de_has_vcn_ex(e)) {
2011                         err = indx_read(indx, ni, de_get_vbn(e), &n);
2012                         if (err)
2013                                 return ERR_PTR(err);
2014
2015                         r = indx_find_buffer(indx, ni, root, vbn, n);
2016                         if (r)
2017                                 return r;
2018                 }
2019
2020                 if (de_is_last(e))
2021                         break;
2022
2023                 e = Add2Ptr(e, le16_to_cpu(e->size));
2024         }
2025
2026         return NULL;
2027 }
2028
2029 /*
2030  * indx_shrink - Deallocate unused tail indexes.
2031  */
2032 static int indx_shrink(struct ntfs_index *indx, struct ntfs_inode *ni,
2033                        size_t bit)
2034 {
2035         int err = 0;
2036         u64 bpb, new_data;
2037         size_t nbits;
2038         struct ATTRIB *b;
2039         struct ATTR_LIST_ENTRY *le = NULL;
2040         const struct INDEX_NAMES *in = &s_index_names[indx->type];
2041
2042         b = ni_find_attr(ni, NULL, &le, ATTR_BITMAP, in->name, in->name_len,
2043                          NULL, NULL);
2044
2045         if (!b)
2046                 return -ENOENT;
2047
2048         if (!b->non_res) {
2049                 unsigned long pos;
2050                 const unsigned long *bm = resident_data(b);
2051
2052                 nbits = (size_t)le32_to_cpu(b->res.data_size) * 8;
2053
2054                 if (bit >= nbits)
2055                         return 0;
2056
2057                 pos = find_next_bit(bm, nbits, bit);
2058                 if (pos < nbits)
2059                         return 0;
2060         } else {
2061                 size_t used = MINUS_ONE_T;
2062
2063                 nbits = le64_to_cpu(b->nres.data_size) * 8;
2064
2065                 if (bit >= nbits)
2066                         return 0;
2067
2068                 err = scan_nres_bitmap(ni, b, indx, bit, &scan_for_used, &used);
2069                 if (err)
2070                         return err;
2071
2072                 if (used != MINUS_ONE_T)
2073                         return 0;
2074         }
2075
2076         new_data = (u64)bit << indx->index_bits;
2077
2078         err = attr_set_size(ni, ATTR_ALLOC, in->name, in->name_len,
2079                             &indx->alloc_run, new_data, &new_data, false, NULL);
2080         if (err)
2081                 return err;
2082
2083         bpb = bitmap_size(bit);
2084         if (bpb * 8 == nbits)
2085                 return 0;
2086
2087         err = attr_set_size(ni, ATTR_BITMAP, in->name, in->name_len,
2088                             &indx->bitmap_run, bpb, &bpb, false, NULL);
2089
2090         return err;
2091 }
2092
2093 static int indx_free_children(struct ntfs_index *indx, struct ntfs_inode *ni,
2094                               const struct NTFS_DE *e, bool trim)
2095 {
2096         int err;
2097         struct indx_node *n = NULL;
2098         struct INDEX_HDR *hdr;
2099         CLST vbn = de_get_vbn(e);
2100         size_t i;
2101
2102         err = indx_read(indx, ni, vbn, &n);
2103         if (err)
2104                 return err;
2105
2106         hdr = &n->index->ihdr;
2107         /* First, recurse into the children, if any. */
2108         if (hdr_has_subnode(hdr)) {
2109                 for (e = hdr_first_de(hdr); e; e = hdr_next_de(hdr, e)) {
2110                         indx_free_children(indx, ni, e, false);
2111                         if (de_is_last(e))
2112                                 break;
2113                 }
2114         }
2115
2116         put_indx_node(n);
2117
2118         i = vbn >> indx->idx2vbn_bits;
2119         /*
2120          * We've gotten rid of the children; add this buffer to the free list.
2121          */
2122         indx_mark_free(indx, ni, i);
2123
2124         if (!trim)
2125                 return 0;
2126
2127         /*
2128          * If there are no used indexes after current free index
2129          * then we can truncate allocation and bitmap.
2130          * Use bitmap to estimate the case.
2131          */
2132         indx_shrink(indx, ni, i + 1);
2133         return 0;
2134 }
2135
2136 /*
2137  * indx_get_entry_to_replace
2138  *
2139  * Find a replacement entry for a deleted entry.
2140  * Always returns a node entry:
2141  * NTFS_IE_HAS_SUBNODES is set the flags and the size includes the sub_vcn.
2142  */
2143 static int indx_get_entry_to_replace(struct ntfs_index *indx,
2144                                      struct ntfs_inode *ni,
2145                                      const struct NTFS_DE *de_next,
2146                                      struct NTFS_DE **de_to_replace,
2147                                      struct ntfs_fnd *fnd)
2148 {
2149         int err;
2150         int level = -1;
2151         CLST vbn;
2152         struct NTFS_DE *e, *te, *re;
2153         struct indx_node *n;
2154         struct INDEX_BUFFER *ib;
2155
2156         *de_to_replace = NULL;
2157
2158         /* Find first leaf entry down from de_next. */
2159         vbn = de_get_vbn(de_next);
2160         for (;;) {
2161                 n = NULL;
2162                 err = indx_read(indx, ni, vbn, &n);
2163                 if (err)
2164                         goto out;
2165
2166                 e = hdr_first_de(&n->index->ihdr);
2167                 fnd_push(fnd, n, e);
2168
2169                 if (!de_is_last(e)) {
2170                         /*
2171                          * This buffer is non-empty, so its first entry
2172                          * could be used as the replacement entry.
2173                          */
2174                         level = fnd->level - 1;
2175                 }
2176
2177                 if (!de_has_vcn(e))
2178                         break;
2179
2180                 /* This buffer is a node. Continue to go down. */
2181                 vbn = de_get_vbn(e);
2182         }
2183
2184         if (level == -1)
2185                 goto out;
2186
2187         n = fnd->nodes[level];
2188         te = hdr_first_de(&n->index->ihdr);
2189         /* Copy the candidate entry into the replacement entry buffer. */
2190         re = kmalloc(le16_to_cpu(te->size) + sizeof(u64), GFP_NOFS);
2191         if (!re) {
2192                 err = -ENOMEM;
2193                 goto out;
2194         }
2195
2196         *de_to_replace = re;
2197         memcpy(re, te, le16_to_cpu(te->size));
2198
2199         if (!de_has_vcn(re)) {
2200                 /*
2201                  * The replacement entry we found doesn't have a sub_vcn.
2202                  * increase its size to hold one.
2203                  */
2204                 le16_add_cpu(&re->size, sizeof(u64));
2205                 re->flags |= NTFS_IE_HAS_SUBNODES;
2206         } else {
2207                 /*
2208                  * The replacement entry we found was a node entry, which
2209                  * means that all its child buffers are empty. Return them
2210                  * to the free pool.
2211                  */
2212                 indx_free_children(indx, ni, te, true);
2213         }
2214
2215         /*
2216          * Expunge the replacement entry from its former location,
2217          * and then write that buffer.
2218          */
2219         ib = n->index;
2220         e = hdr_delete_de(&ib->ihdr, te);
2221
2222         fnd->de[level] = e;
2223         indx_write(indx, ni, n, 0);
2224
2225         /* Check to see if this action created an empty leaf. */
2226         if (ib_is_leaf(ib) && ib_is_empty(ib))
2227                 return 0;
2228
2229 out:
2230         fnd_clear(fnd);
2231         return err;
2232 }
2233
2234 /*
2235  * indx_delete_entry - Delete an entry from the index.
2236  */
2237 int indx_delete_entry(struct ntfs_index *indx, struct ntfs_inode *ni,
2238                       const void *key, u32 key_len, const void *ctx)
2239 {
2240         int err, diff;
2241         struct INDEX_ROOT *root;
2242         struct INDEX_HDR *hdr;
2243         struct ntfs_fnd *fnd, *fnd2;
2244         struct INDEX_BUFFER *ib;
2245         struct NTFS_DE *e, *re, *next, *prev, *me;
2246         struct indx_node *n, *n2d = NULL;
2247         __le64 sub_vbn;
2248         int level, level2;
2249         struct ATTRIB *attr;
2250         struct mft_inode *mi;
2251         u32 e_size, root_size, new_root_size;
2252         size_t trim_bit;
2253         const struct INDEX_NAMES *in;
2254
2255         fnd = fnd_get();
2256         if (!fnd) {
2257                 err = -ENOMEM;
2258                 goto out2;
2259         }
2260
2261         fnd2 = fnd_get();
2262         if (!fnd2) {
2263                 err = -ENOMEM;
2264                 goto out1;
2265         }
2266
2267         root = indx_get_root(indx, ni, &attr, &mi);
2268         if (!root) {
2269                 err = -EINVAL;
2270                 goto out;
2271         }
2272
2273         /* Locate the entry to remove. */
2274         err = indx_find(indx, ni, root, key, key_len, ctx, &diff, &e, fnd);
2275         if (err)
2276                 goto out;
2277
2278         if (!e || diff) {
2279                 err = -ENOENT;
2280                 goto out;
2281         }
2282
2283         level = fnd->level;
2284
2285         if (level) {
2286                 n = fnd->nodes[level - 1];
2287                 e = fnd->de[level - 1];
2288                 ib = n->index;
2289                 hdr = &ib->ihdr;
2290         } else {
2291                 hdr = &root->ihdr;
2292                 e = fnd->root_de;
2293                 n = NULL;
2294         }
2295
2296         e_size = le16_to_cpu(e->size);
2297
2298         if (!de_has_vcn_ex(e)) {
2299                 /* The entry to delete is a leaf, so we can just rip it out. */
2300                 hdr_delete_de(hdr, e);
2301
2302                 if (!level) {
2303                         hdr->total = hdr->used;
2304
2305                         /* Shrink resident root attribute. */
2306                         mi_resize_attr(mi, attr, 0 - e_size);
2307                         goto out;
2308                 }
2309
2310                 indx_write(indx, ni, n, 0);
2311
2312                 /*
2313                  * Check to see if removing that entry made
2314                  * the leaf empty.
2315                  */
2316                 if (ib_is_leaf(ib) && ib_is_empty(ib)) {
2317                         fnd_pop(fnd);
2318                         fnd_push(fnd2, n, e);
2319                 }
2320         } else {
2321                 /*
2322                  * The entry we wish to delete is a node buffer, so we
2323                  * have to find a replacement for it.
2324                  */
2325                 next = de_get_next(e);
2326
2327                 err = indx_get_entry_to_replace(indx, ni, next, &re, fnd2);
2328                 if (err)
2329                         goto out;
2330
2331                 if (re) {
2332                         de_set_vbn_le(re, de_get_vbn_le(e));
2333                         hdr_delete_de(hdr, e);
2334
2335                         err = level ? indx_insert_into_buffer(indx, ni, root,
2336                                                               re, ctx,
2337                                                               fnd->level - 1,
2338                                                               fnd)
2339                                     : indx_insert_into_root(indx, ni, re, e,
2340                                                             ctx, fnd, 0);
2341                         kfree(re);
2342
2343                         if (err)
2344                                 goto out;
2345                 } else {
2346                         /*
2347                          * There is no replacement for the current entry.
2348                          * This means that the subtree rooted at its node
2349                          * is empty, and can be deleted, which turn means
2350                          * that the node can just inherit the deleted
2351                          * entry sub_vcn.
2352                          */
2353                         indx_free_children(indx, ni, next, true);
2354
2355                         de_set_vbn_le(next, de_get_vbn_le(e));
2356                         hdr_delete_de(hdr, e);
2357                         if (level) {
2358                                 indx_write(indx, ni, n, 0);
2359                         } else {
2360                                 hdr->total = hdr->used;
2361
2362                                 /* Shrink resident root attribute. */
2363                                 mi_resize_attr(mi, attr, 0 - e_size);
2364                         }
2365                 }
2366         }
2367
2368         /* Delete a branch of tree. */
2369         if (!fnd2 || !fnd2->level)
2370                 goto out;
2371
2372         /* Reinit root 'cause it can be changed. */
2373         root = indx_get_root(indx, ni, &attr, &mi);
2374         if (!root) {
2375                 err = -EINVAL;
2376                 goto out;
2377         }
2378
2379         n2d = NULL;
2380         sub_vbn = fnd2->nodes[0]->index->vbn;
2381         level2 = 0;
2382         level = fnd->level;
2383
2384         hdr = level ? &fnd->nodes[level - 1]->index->ihdr : &root->ihdr;
2385
2386         /* Scan current level. */
2387         for (e = hdr_first_de(hdr);; e = hdr_next_de(hdr, e)) {
2388                 if (!e) {
2389                         err = -EINVAL;
2390                         goto out;
2391                 }
2392
2393                 if (de_has_vcn(e) && sub_vbn == de_get_vbn_le(e))
2394                         break;
2395
2396                 if (de_is_last(e)) {
2397                         e = NULL;
2398                         break;
2399                 }
2400         }
2401
2402         if (!e) {
2403                 /* Do slow search from root. */
2404                 struct indx_node *in;
2405
2406                 fnd_clear(fnd);
2407
2408                 in = indx_find_buffer(indx, ni, root, sub_vbn, NULL);
2409                 if (IS_ERR(in)) {
2410                         err = PTR_ERR(in);
2411                         goto out;
2412                 }
2413
2414                 if (in)
2415                         fnd_push(fnd, in, NULL);
2416         }
2417
2418         /* Merge fnd2 -> fnd. */
2419         for (level = 0; level < fnd2->level; level++) {
2420                 fnd_push(fnd, fnd2->nodes[level], fnd2->de[level]);
2421                 fnd2->nodes[level] = NULL;
2422         }
2423         fnd2->level = 0;
2424
2425         hdr = NULL;
2426         for (level = fnd->level; level; level--) {
2427                 struct indx_node *in = fnd->nodes[level - 1];
2428
2429                 ib = in->index;
2430                 if (ib_is_empty(ib)) {
2431                         sub_vbn = ib->vbn;
2432                 } else {
2433                         hdr = &ib->ihdr;
2434                         n2d = in;
2435                         level2 = level;
2436                         break;
2437                 }
2438         }
2439
2440         if (!hdr)
2441                 hdr = &root->ihdr;
2442
2443         e = hdr_first_de(hdr);
2444         if (!e) {
2445                 err = -EINVAL;
2446                 goto out;
2447         }
2448
2449         if (hdr != &root->ihdr || !de_is_last(e)) {
2450                 prev = NULL;
2451                 while (!de_is_last(e)) {
2452                         if (de_has_vcn(e) && sub_vbn == de_get_vbn_le(e))
2453                                 break;
2454                         prev = e;
2455                         e = hdr_next_de(hdr, e);
2456                         if (!e) {
2457                                 err = -EINVAL;
2458                                 goto out;
2459                         }
2460                 }
2461
2462                 if (sub_vbn != de_get_vbn_le(e)) {
2463                         /*
2464                          * Didn't find the parent entry, although this buffer
2465                          * is the parent trail. Something is corrupt.
2466                          */
2467                         err = -EINVAL;
2468                         goto out;
2469                 }
2470
2471                 if (de_is_last(e)) {
2472                         /*
2473                          * Since we can't remove the end entry, we'll remove
2474                          * its predecessor instead. This means we have to
2475                          * transfer the predecessor's sub_vcn to the end entry.
2476                          * Note: This index block is not empty, so the
2477                          * predecessor must exist.
2478                          */
2479                         if (!prev) {
2480                                 err = -EINVAL;
2481                                 goto out;
2482                         }
2483
2484                         if (de_has_vcn(prev)) {
2485                                 de_set_vbn_le(e, de_get_vbn_le(prev));
2486                         } else if (de_has_vcn(e)) {
2487                                 le16_sub_cpu(&e->size, sizeof(u64));
2488                                 e->flags &= ~NTFS_IE_HAS_SUBNODES;
2489                                 le32_sub_cpu(&hdr->used, sizeof(u64));
2490                         }
2491                         e = prev;
2492                 }
2493
2494                 /*
2495                  * Copy the current entry into a temporary buffer (stripping
2496                  * off its down-pointer, if any) and delete it from the current
2497                  * buffer or root, as appropriate.
2498                  */
2499                 e_size = le16_to_cpu(e->size);
2500                 me = kmemdup(e, e_size, GFP_NOFS);
2501                 if (!me) {
2502                         err = -ENOMEM;
2503                         goto out;
2504                 }
2505
2506                 if (de_has_vcn(me)) {
2507                         me->flags &= ~NTFS_IE_HAS_SUBNODES;
2508                         le16_sub_cpu(&me->size, sizeof(u64));
2509                 }
2510
2511                 hdr_delete_de(hdr, e);
2512
2513                 if (hdr == &root->ihdr) {
2514                         level = 0;
2515                         hdr->total = hdr->used;
2516
2517                         /* Shrink resident root attribute. */
2518                         mi_resize_attr(mi, attr, 0 - e_size);
2519                 } else {
2520                         indx_write(indx, ni, n2d, 0);
2521                         level = level2;
2522                 }
2523
2524                 /* Mark unused buffers as free. */
2525                 trim_bit = -1;
2526                 for (; level < fnd->level; level++) {
2527                         ib = fnd->nodes[level]->index;
2528                         if (ib_is_empty(ib)) {
2529                                 size_t k = le64_to_cpu(ib->vbn) >>
2530                                            indx->idx2vbn_bits;
2531
2532                                 indx_mark_free(indx, ni, k);
2533                                 if (k < trim_bit)
2534                                         trim_bit = k;
2535                         }
2536                 }
2537
2538                 fnd_clear(fnd);
2539                 /*fnd->root_de = NULL;*/
2540
2541                 /*
2542                  * Re-insert the entry into the tree.
2543                  * Find the spot the tree where we want to insert the new entry.
2544                  */
2545                 err = indx_insert_entry(indx, ni, me, ctx, fnd, 0);
2546                 kfree(me);
2547                 if (err)
2548                         goto out;
2549
2550                 if (trim_bit != -1)
2551                         indx_shrink(indx, ni, trim_bit);
2552         } else {
2553                 /*
2554                  * This tree needs to be collapsed down to an empty root.
2555                  * Recreate the index root as an empty leaf and free all
2556                  * the bits the index allocation bitmap.
2557                  */
2558                 fnd_clear(fnd);
2559                 fnd_clear(fnd2);
2560
2561                 in = &s_index_names[indx->type];
2562
2563                 err = attr_set_size(ni, ATTR_ALLOC, in->name, in->name_len,
2564                                     &indx->alloc_run, 0, NULL, false, NULL);
2565                 err = ni_remove_attr(ni, ATTR_ALLOC, in->name, in->name_len,
2566                                      false, NULL);
2567                 run_close(&indx->alloc_run);
2568
2569                 err = attr_set_size(ni, ATTR_BITMAP, in->name, in->name_len,
2570                                     &indx->bitmap_run, 0, NULL, false, NULL);
2571                 err = ni_remove_attr(ni, ATTR_BITMAP, in->name, in->name_len,
2572                                      false, NULL);
2573                 run_close(&indx->bitmap_run);
2574
2575                 root = indx_get_root(indx, ni, &attr, &mi);
2576                 if (!root) {
2577                         err = -EINVAL;
2578                         goto out;
2579                 }
2580
2581                 root_size = le32_to_cpu(attr->res.data_size);
2582                 new_root_size =
2583                         sizeof(struct INDEX_ROOT) + sizeof(struct NTFS_DE);
2584
2585                 if (new_root_size != root_size &&
2586                     !mi_resize_attr(mi, attr, new_root_size - root_size)) {
2587                         err = -EINVAL;
2588                         goto out;
2589                 }
2590
2591                 /* Fill first entry. */
2592                 e = (struct NTFS_DE *)(root + 1);
2593                 e->ref.low = 0;
2594                 e->ref.high = 0;
2595                 e->ref.seq = 0;
2596                 e->size = cpu_to_le16(sizeof(struct NTFS_DE));
2597                 e->flags = NTFS_IE_LAST; // 0x02
2598                 e->key_size = 0;
2599                 e->res = 0;
2600
2601                 hdr = &root->ihdr;
2602                 hdr->flags = 0;
2603                 hdr->used = hdr->total = cpu_to_le32(
2604                         new_root_size - offsetof(struct INDEX_ROOT, ihdr));
2605                 mi->dirty = true;
2606         }
2607
2608 out:
2609         fnd_put(fnd2);
2610 out1:
2611         fnd_put(fnd);
2612 out2:
2613         return err;
2614 }
2615
2616 /*
2617  * Update duplicated information in directory entry
2618  * 'dup' - info from MFT record
2619  */
2620 int indx_update_dup(struct ntfs_inode *ni, struct ntfs_sb_info *sbi,
2621                     const struct ATTR_FILE_NAME *fname,
2622                     const struct NTFS_DUP_INFO *dup, int sync)
2623 {
2624         int err, diff;
2625         struct NTFS_DE *e = NULL;
2626         struct ATTR_FILE_NAME *e_fname;
2627         struct ntfs_fnd *fnd;
2628         struct INDEX_ROOT *root;
2629         struct mft_inode *mi;
2630         struct ntfs_index *indx = &ni->dir;
2631
2632         fnd = fnd_get();
2633         if (!fnd)
2634                 return -ENOMEM;
2635
2636         root = indx_get_root(indx, ni, NULL, &mi);
2637         if (!root) {
2638                 err = -EINVAL;
2639                 goto out;
2640         }
2641
2642         /* Find entry in directory. */
2643         err = indx_find(indx, ni, root, fname, fname_full_size(fname), sbi,
2644                         &diff, &e, fnd);
2645         if (err)
2646                 goto out;
2647
2648         if (!e) {
2649                 err = -EINVAL;
2650                 goto out;
2651         }
2652
2653         if (diff) {
2654                 err = -EINVAL;
2655                 goto out;
2656         }
2657
2658         e_fname = (struct ATTR_FILE_NAME *)(e + 1);
2659
2660         if (!memcmp(&e_fname->dup, dup, sizeof(*dup))) {
2661                 /*
2662                  * Nothing to update in index! Try to avoid this call.
2663                  */
2664                 goto out;
2665         }
2666
2667         memcpy(&e_fname->dup, dup, sizeof(*dup));
2668
2669         if (fnd->level) {
2670                 /* Directory entry in index. */
2671                 err = indx_write(indx, ni, fnd->nodes[fnd->level - 1], sync);
2672         } else {
2673                 /* Directory entry in directory MFT record. */
2674                 mi->dirty = true;
2675                 if (sync)
2676                         err = mi_write(mi, 1);
2677                 else
2678                         mark_inode_dirty(&ni->vfs_inode);
2679         }
2680
2681 out:
2682         fnd_put(fnd);
2683         return err;
2684 }