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