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