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