xref: /linux/fs/ntfs/index.c (revision e782ca90ceb798bb1811b214bf814216f11aae6a)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * NTFS kernel index handling.
4  *
5  * Copyright (c) 2004-2005 Anton Altaparmakov
6  * Copyright (c) 2025 LG Electronics Co., Ltd.
7  *
8  * Part of this file is based on code from the NTFS-3G.
9  * and is copyrighted by the respective authors below:
10  * Copyright (c) 2004-2005 Anton Altaparmakov
11  * Copyright (c) 2004-2005 Richard Russon
12  * Copyright (c) 2005-2006 Yura Pakhuchiy
13  * Copyright (c) 2005-2008 Szabolcs Szakacsits
14  * Copyright (c) 2007-2021 Jean-Pierre Andre
15  */
16 
17 #include "collate.h"
18 #include "index.h"
19 #include "ntfs.h"
20 #include "attrlist.h"
21 
22 /*
23  * ntfs_index_entry_inconsistent - Check the consistency of an index entry
24  *
25  * Make sure data and key do not overflow from entry.
26  * As a side effect, an entry with zero length is rejected.
27  * This entry must be a full one (no INDEX_ENTRY_END flag), and its
28  * length must have been checked beforehand to not overflow from the
29  * index record.
30  */
31 static int ntfs_index_entry_inconsistent(const struct ntfs_volume *vol,
32 					 const struct index_entry *ie,
33 					 __le32 collation_rule, u64 inum)
34 {
35 	if (ie->key_length &&
36 	    ((le16_to_cpu(ie->key_length) + offsetof(struct index_entry, key)) >
37 	     le16_to_cpu(ie->length))) {
38 		ntfs_error(vol->sb, "Overflow from index entry in inode %lld\n",
39 				(long long)inum);
40 		return -EIO;
41 
42 	} else {
43 		if (collation_rule == COLLATION_FILE_NAME) {
44 			if ((offsetof(struct index_entry, key.file_name.file_name) +
45 			     ie->key.file_name.file_name_length	* sizeof(__le16)) >
46 					le16_to_cpu(ie->length)) {
47 				ntfs_error(vol->sb,
48 					"File name overflow from index entry in inode %lld\n",
49 					(long long)inum);
50 				return -EIO;
51 			}
52 		} else {
53 			if (ie->data.vi.data_length &&
54 			    ((le16_to_cpu(ie->data.vi.data_offset) +
55 			      le16_to_cpu(ie->data.vi.data_length)) >
56 			     le16_to_cpu(ie->length))) {
57 				ntfs_error(vol->sb,
58 					"Data overflow from index entry in inode %lld\n",
59 					(long long)inum);
60 				return -EIO;
61 			}
62 		}
63 	}
64 
65 	return 0;
66 }
67 
68 /*
69  * ntfs_index_entry_mark_dirty - mark an index entry dirty
70  * @ictx:	ntfs index context describing the index entry
71  *
72  * Mark the index entry described by the index entry context @ictx dirty.
73  *
74  * If the index entry is in the index root attribute, simply mark the inode
75  * containing the index root attribute dirty.  This ensures the mftrecord, and
76  * hence the index root attribute, will be written out to disk later.
77  *
78  * If the index entry is in an index block belonging to the index allocation
79  * attribute, set ib_dirty to true, thus index block will be updated during
80  * ntfs_index_ctx_put.
81  */
82 void ntfs_index_entry_mark_dirty(struct ntfs_index_context *ictx)
83 {
84 	if (ictx->is_in_root)
85 		mark_mft_record_dirty(ictx->actx->ntfs_ino);
86 	else if (ictx->ib)
87 		ictx->ib_dirty = true;
88 }
89 
90 static s64 ntfs_ib_vcn_to_pos(struct ntfs_index_context *icx, s64 vcn)
91 {
92 	return vcn << icx->vcn_size_bits;
93 }
94 
95 static s64 ntfs_ib_pos_to_vcn(struct ntfs_index_context *icx, s64 pos)
96 {
97 	return pos >> icx->vcn_size_bits;
98 }
99 
100 static int ntfs_ib_write(struct ntfs_index_context *icx, struct index_block *ib)
101 {
102 	s64 ret, vcn = le64_to_cpu(ib->index_block_vcn);
103 
104 	ntfs_debug("vcn: %lld\n", vcn);
105 
106 	ret = pre_write_mst_fixup((struct ntfs_record *)ib, icx->block_size);
107 	if (ret)
108 		return -EIO;
109 
110 	ret = ntfs_inode_attr_pwrite(VFS_I(icx->ia_ni),
111 			ntfs_ib_vcn_to_pos(icx, vcn), icx->block_size,
112 			(u8 *)ib, icx->sync_write);
113 	if (ret != icx->block_size) {
114 		ntfs_debug("Failed to write index block %lld, inode %llu",
115 				vcn, (unsigned long long)icx->idx_ni->mft_no);
116 		return ret;
117 	}
118 
119 	return 0;
120 }
121 
122 static int ntfs_icx_ib_write(struct ntfs_index_context *icx)
123 {
124 	int err;
125 
126 	err = ntfs_ib_write(icx, icx->ib);
127 	if (err)
128 		return err;
129 
130 	icx->ib_dirty = false;
131 
132 	return 0;
133 }
134 
135 int ntfs_icx_ib_sync_write(struct ntfs_index_context *icx)
136 {
137 	int ret;
138 
139 	if (icx->ib_dirty == false)
140 		return 0;
141 
142 	icx->sync_write = true;
143 
144 	ret = ntfs_ib_write(icx, icx->ib);
145 	if (!ret) {
146 		kvfree(icx->ib);
147 		icx->ib = NULL;
148 		icx->ib_dirty = false;
149 	} else {
150 		post_write_mst_fixup((struct ntfs_record *)icx->ib);
151 		icx->sync_write = false;
152 	}
153 
154 	return ret;
155 }
156 
157 /*
158  * ntfs_index_ctx_get - allocate and initialize a new index context
159  * @ni:		ntfs inode with which to initialize the context
160  * @name:	name of the which context describes
161  * @name_len:	length of the index name
162  *
163  * Allocate a new index context, initialize it with @ni and return it.
164  * Return NULL if allocation failed.
165  */
166 struct ntfs_index_context *ntfs_index_ctx_get(struct ntfs_inode *ni,
167 		__le16 *name, u32 name_len)
168 {
169 	struct ntfs_index_context *icx;
170 
171 	ntfs_debug("Entering\n");
172 
173 	if (!ni)
174 		return NULL;
175 
176 	if (ni->nr_extents == -1)
177 		ni = ni->ext.base_ntfs_ino;
178 
179 	icx = kmem_cache_alloc(ntfs_index_ctx_cache, GFP_NOFS);
180 	if (icx)
181 		*icx = (struct ntfs_index_context) {
182 			.idx_ni = ni,
183 			.name = name,
184 			.name_len = name_len,
185 		};
186 	return icx;
187 }
188 
189 static void ntfs_index_ctx_free(struct ntfs_index_context *icx)
190 {
191 	ntfs_debug("Entering\n");
192 
193 	if (icx->actx) {
194 		ntfs_attr_put_search_ctx(icx->actx);
195 		icx->actx = NULL;
196 	}
197 
198 	if (!icx->is_in_root) {
199 		if (icx->ib_dirty)
200 			ntfs_ib_write(icx, icx->ib);
201 		kvfree(icx->ib);
202 		icx->ib = NULL;
203 	}
204 
205 	if (icx->ia_ni) {
206 		iput(VFS_I(icx->ia_ni));
207 		icx->ia_ni = NULL;
208 	}
209 }
210 
211 /*
212  * ntfs_index_ctx_put - release an index context
213  * @icx:	index context to free
214  *
215  * Release the index context @icx, releasing all associated resources.
216  */
217 void ntfs_index_ctx_put(struct ntfs_index_context *icx)
218 {
219 	ntfs_index_ctx_free(icx);
220 	kmem_cache_free(ntfs_index_ctx_cache, icx);
221 }
222 
223 /*
224  * ntfs_index_ctx_reinit - reinitialize an index context
225  * @icx:	index context to reinitialize
226  *
227  * Reinitialize the index context @icx so it can be used for ntfs_index_lookup.
228  */
229 void ntfs_index_ctx_reinit(struct ntfs_index_context *icx)
230 {
231 	ntfs_debug("Entering\n");
232 
233 	ntfs_index_ctx_free(icx);
234 
235 	*icx = (struct ntfs_index_context) {
236 		.idx_ni = icx->idx_ni,
237 		.name = icx->name,
238 		.name_len = icx->name_len,
239 	};
240 }
241 
242 static __le64 *ntfs_ie_get_vcn_addr(struct index_entry *ie)
243 {
244 	return (__le64 *)((u8 *)ie + le16_to_cpu(ie->length) - sizeof(s64));
245 }
246 
247 /*
248  *  Get the subnode vcn to which the index entry refers.
249  */
250 static s64 ntfs_ie_get_vcn(struct index_entry *ie)
251 {
252 	return le64_to_cpup(ntfs_ie_get_vcn_addr(ie));
253 }
254 
255 static struct index_entry *ntfs_ie_get_first(struct index_header *ih)
256 {
257 	return (struct index_entry *)((u8 *)ih + le32_to_cpu(ih->entries_offset));
258 }
259 
260 static struct index_entry *ntfs_ie_get_next(struct index_entry *ie)
261 {
262 	return (struct index_entry *)((char *)ie + le16_to_cpu(ie->length));
263 }
264 
265 static u8 *ntfs_ie_get_end(struct index_header *ih)
266 {
267 	return (u8 *)ih + le32_to_cpu(ih->index_length);
268 }
269 
270 static int ntfs_ie_end(struct index_entry *ie)
271 {
272 	return ie->flags & INDEX_ENTRY_END || !ie->length;
273 }
274 
275 static int ntfs_index_header_inconsistent(struct ntfs_volume *vol,
276 					  const struct index_header *ih,
277 					  u32 bytes_available, u64 inum)
278 {
279 	u32 entries_offset, index_length, allocated_size;
280 
281 	if (bytes_available < sizeof(struct index_header)) {
282 		ntfs_error(vol->sb,
283 			   "index block in inode %llu is smaller than an index header.",
284 			   (unsigned long long)inum);
285 		return -EIO;
286 	}
287 
288 	entries_offset = le32_to_cpu(ih->entries_offset);
289 	index_length = le32_to_cpu(ih->index_length);
290 	allocated_size = le32_to_cpu(ih->allocated_size);
291 
292 	if (entries_offset < sizeof(struct index_header) ||
293 	    entries_offset > bytes_available) {
294 		ntfs_error(vol->sb,
295 			   "Invalid index entry offset in inode %llu.",
296 			   (unsigned long long)inum);
297 		return -EIO;
298 	}
299 
300 	if (index_length <= entries_offset) {
301 		ntfs_error(vol->sb,
302 			   "No space for index entries in inode %llu.",
303 			   (unsigned long long)inum);
304 		return -EIO;
305 	}
306 
307 	if (allocated_size < index_length) {
308 		ntfs_error(vol->sb,
309 			   "Index entries overflow in inode %llu.",
310 			   (unsigned long long)inum);
311 		return -EIO;
312 	}
313 
314 	if (allocated_size > bytes_available || index_length > bytes_available) {
315 		ntfs_error(vol->sb,
316 			   "Index entries in inode %llu exceed the available buffer.",
317 			   (unsigned long long)inum);
318 		return -EIO;
319 	}
320 
321 	return 0;
322 }
323 
324 int ntfs_index_entries_inconsistent(const struct ntfs_volume *vol,
325 				    const struct index_header *ih,
326 				    __le32 collation_rule, u64 inum)
327 {
328 	struct index_entry *ie;
329 	u8 *index_end = (u8 *)ih + le32_to_cpu(ih->index_length);
330 
331 	for (ie = ntfs_ie_get_first((struct index_header *)ih);
332 	      ; ie = ntfs_ie_get_next(ie)) {
333 		if ((u8 *)ie + sizeof(struct index_entry_header) > index_end ||
334 		    (u8 *)ie + le16_to_cpu(ie->length) > index_end) {
335 			ntfs_error(vol->sb,
336 				   "Index entry out of bounds in inode %llu.",
337 				   (unsigned long long)inum);
338 			return -EIO;
339 		}
340 
341 		if (le16_to_cpu(ie->length) < sizeof(struct index_entry_header)) {
342 			ntfs_error(vol->sb,
343 				   "Index entry too small in inode %llu.",
344 				   inum);
345 			return -EIO;
346 		}
347 
348 		if (ntfs_ie_end(ie))
349 			break;
350 
351 		if (!ie->key_length)
352 			return -EIO;
353 
354 		if (ntfs_index_entry_inconsistent(vol, ie,
355 						  collation_rule, inum))
356 			return -EIO;
357 	}
358 
359 	return 0;
360 }
361 
362 /*
363  *  Find the last entry in the index block
364  */
365 static struct index_entry *ntfs_ie_get_last(struct index_entry *ie, char *ies_end)
366 {
367 	ntfs_debug("Entering\n");
368 
369 	while ((char *)ie < ies_end && !ntfs_ie_end(ie))
370 		ie = ntfs_ie_get_next(ie);
371 
372 	return ie;
373 }
374 
375 static struct index_entry *ntfs_ie_get_by_pos(struct index_header *ih, int pos)
376 {
377 	struct index_entry *ie;
378 
379 	ntfs_debug("pos: %d\n", pos);
380 
381 	ie = ntfs_ie_get_first(ih);
382 
383 	while (pos-- > 0)
384 		ie = ntfs_ie_get_next(ie);
385 
386 	return ie;
387 }
388 
389 static struct index_entry *ntfs_ie_prev(struct index_header *ih, struct index_entry *ie)
390 {
391 	struct index_entry *ie_prev = NULL;
392 	struct index_entry *tmp;
393 
394 	ntfs_debug("Entering\n");
395 
396 	tmp = ntfs_ie_get_first(ih);
397 
398 	while (tmp != ie) {
399 		ie_prev = tmp;
400 		tmp = ntfs_ie_get_next(tmp);
401 	}
402 
403 	return ie_prev;
404 }
405 
406 static int ntfs_ih_numof_entries(struct index_header *ih)
407 {
408 	int n;
409 	struct index_entry *ie;
410 	u8 *end;
411 
412 	ntfs_debug("Entering\n");
413 
414 	end = ntfs_ie_get_end(ih);
415 	ie = ntfs_ie_get_first(ih);
416 	for (n = 0; !ntfs_ie_end(ie) && (u8 *)ie < end; n++)
417 		ie = ntfs_ie_get_next(ie);
418 	return n;
419 }
420 
421 static int ntfs_ih_one_entry(struct index_header *ih)
422 {
423 	return (ntfs_ih_numof_entries(ih) == 1);
424 }
425 
426 static int ntfs_ih_zero_entry(struct index_header *ih)
427 {
428 	return (ntfs_ih_numof_entries(ih) == 0);
429 }
430 
431 static void ntfs_ie_delete(struct index_header *ih, struct index_entry *ie)
432 {
433 	u32 new_size;
434 
435 	ntfs_debug("Entering\n");
436 
437 	new_size = le32_to_cpu(ih->index_length) - le16_to_cpu(ie->length);
438 	ih->index_length = cpu_to_le32(new_size);
439 	memmove(ie, (u8 *)ie + le16_to_cpu(ie->length),
440 			new_size - ((u8 *)ie - (u8 *)ih));
441 }
442 
443 static void ntfs_ie_set_vcn(struct index_entry *ie, s64 vcn)
444 {
445 	*ntfs_ie_get_vcn_addr(ie) = cpu_to_le64(vcn);
446 }
447 
448 /*
449  *  Insert @ie index entry at @pos entry. Used @ih values should be ok already.
450  */
451 static void ntfs_ie_insert(struct index_header *ih, struct index_entry *ie,
452 		struct index_entry *pos)
453 {
454 	int ie_size = le16_to_cpu(ie->length);
455 
456 	ntfs_debug("Entering\n");
457 
458 	ih->index_length = cpu_to_le32(le32_to_cpu(ih->index_length) + ie_size);
459 	memmove((u8 *)pos + ie_size, pos,
460 			le32_to_cpu(ih->index_length) - ((u8 *)pos - (u8 *)ih) - ie_size);
461 	memcpy(pos, ie, ie_size);
462 }
463 
464 static struct index_entry *ntfs_ie_dup(struct index_entry *ie)
465 {
466 	ntfs_debug("Entering\n");
467 
468 	return kmemdup(ie, le16_to_cpu(ie->length), GFP_NOFS);
469 }
470 
471 static struct index_entry *ntfs_ie_dup_novcn(struct index_entry *ie)
472 {
473 	struct index_entry *dup;
474 	int size = le16_to_cpu(ie->length);
475 
476 	ntfs_debug("Entering\n");
477 
478 	if (ie->flags & INDEX_ENTRY_NODE)
479 		size -= sizeof(s64);
480 
481 	dup = kmemdup(ie, size, GFP_NOFS);
482 	if (dup) {
483 		dup->flags &= ~INDEX_ENTRY_NODE;
484 		dup->length = cpu_to_le16(size);
485 	}
486 	return dup;
487 }
488 
489 /*
490  * Check the consistency of an index block
491  *
492  * Make sure the index block does not overflow from the index record.
493  * The size of block is assumed to have been checked to be what is
494  * defined in the index root.
495  *
496  * Returns 0 if no error was found, -EIO otherwise
497  *
498  * |<--->|  offsetof(struct index_block, index)
499  * |     |<--->|  sizeof(struct index_header)
500  * |     |     |
501  * |     |     | seq          index entries         unused
502  * |=====|=====|=====|===========================|==============|
503  * |     |           |                           |              |
504  * |     |<--------->| entries_offset            |              |
505  * |     |<---------------- index_length ------->|              |
506  * |     |<--------------------- allocated_size --------------->|
507  * |<--------------------------- block_size ------------------->|
508  *
509  * size(struct index_header) <= ent_offset < ind_length <= alloc_size < bk_size
510  */
511 int ntfs_index_block_inconsistent(struct ntfs_volume *vol,
512 				  const struct index_block *ib,
513 				  u32 block_size, s64 vcn, __le32 cr,
514 				  u64 inum)
515 {
516 	u32 ib_size = (unsigned int)le32_to_cpu(ib->index.allocated_size) +
517 		offsetof(struct index_block, index);
518 	struct super_block *sb = vol->sb;
519 
520 	ntfs_debug("Entering\n");
521 
522 	if (!ntfs_is_indx_record(ib->magic)) {
523 		ntfs_error(sb, "Corrupt index block signature: vcn %lld inode %llu\n",
524 			   vcn, (unsigned long long)inum);
525 		return -EIO;
526 	}
527 
528 	if (le64_to_cpu(ib->index_block_vcn) != vcn) {
529 		ntfs_error(sb,
530 			"Corrupt index block: s64 (%lld) is different from expected s64 (%lld) in inode %llu\n",
531 			(long long)le64_to_cpu(ib->index_block_vcn),
532 			vcn, inum);
533 		return -EIO;
534 	}
535 
536 	if (ib_size != block_size) {
537 		ntfs_error(sb,
538 			   "Corrupt index block : s64 (%lld) of inode %llu has a size (%u) differing from the index specified size (%u)\n",
539 			   vcn, inum, ib_size, block_size);
540 		return -EIO;
541 	}
542 
543 	if (ntfs_index_header_inconsistent(vol, &ib->index,
544 					   block_size -
545 					   offsetof(struct index_block, index),
546 					   inum))
547 		return -EIO;
548 	if (ntfs_index_entries_inconsistent(vol, &ib->index, cr, inum))
549 		return -EIO;
550 	return 0;
551 }
552 
553 int ntfs_index_root_inconsistent(struct ntfs_volume *vol,
554 				 const struct attr_record *a,
555 				 const struct index_root *ir, u64 inum)
556 {
557 	u32 value_length = le32_to_cpu(a->data.resident.value_length);
558 
559 	if (value_length < offsetof(struct index_root, index)) {
560 		ntfs_error(vol->sb, "$INDEX_ROOT in inode %llu is too small.",
561 			   (unsigned long long)inum);
562 		return -EIO;
563 	}
564 
565 	return ntfs_index_header_inconsistent(vol, &ir->index,
566 					      value_length -
567 					      offsetof(struct index_root, index),
568 					      inum);
569 }
570 
571 static struct index_root *ntfs_ir_lookup(struct ntfs_inode *ni, __le16 *name,
572 		u32 name_len, struct ntfs_attr_search_ctx **ctx)
573 {
574 	struct attr_record *a;
575 	struct index_root *ir = NULL;
576 
577 	ntfs_debug("Entering\n");
578 	*ctx = ntfs_attr_get_search_ctx(ni, NULL);
579 	if (!*ctx) {
580 		ntfs_error(ni->vol->sb, "%s, Failed to get search context", __func__);
581 		return NULL;
582 	}
583 
584 	if (ntfs_attr_lookup(AT_INDEX_ROOT, name, name_len, CASE_SENSITIVE,
585 				0, NULL, 0, *ctx)) {
586 		ntfs_error(ni->vol->sb, "Failed to lookup $INDEX_ROOT");
587 		goto err_out;
588 	}
589 
590 	a = (*ctx)->attr;
591 	if (a->non_resident) {
592 		ntfs_error(ni->vol->sb, "Non-resident $INDEX_ROOT detected");
593 		goto err_out;
594 	}
595 
596 	ir = (struct index_root *)((char *)a + le16_to_cpu(a->data.resident.value_offset));
597 err_out:
598 	if (!ir) {
599 		ntfs_attr_put_search_ctx(*ctx);
600 		*ctx = NULL;
601 	}
602 	return ir;
603 }
604 
605 static struct index_root *ntfs_ir_lookup2(struct ntfs_inode *ni, __le16 *name, u32 len)
606 {
607 	struct ntfs_attr_search_ctx *ctx;
608 	struct index_root *ir;
609 
610 	ir = ntfs_ir_lookup(ni, name, len, &ctx);
611 	if (ir)
612 		ntfs_attr_put_search_ctx(ctx);
613 	return ir;
614 }
615 
616 /*
617  * Find a key in the index block.
618  */
619 static int ntfs_ie_lookup(const void *key, const u32 key_len,
620 		struct ntfs_index_context *icx, struct index_header *ih,
621 		s64 *vcn, struct index_entry **ie_out)
622 {
623 	struct index_entry *ie;
624 	u8 *index_end;
625 	int rc, item = 0;
626 
627 	ntfs_debug("Entering\n");
628 
629 	index_end = ntfs_ie_get_end(ih);
630 
631 	/*
632 	 * Loop until we exceed valid memory (corruption case) or until we
633 	 * reach the last entry.
634 	 */
635 	for (ie = ntfs_ie_get_first(ih); ; ie = ntfs_ie_get_next(ie)) {
636 		/* Bounds checks. */
637 		if ((u8 *)ie + sizeof(struct index_entry_header) > index_end ||
638 				(u8 *)ie + le16_to_cpu(ie->length) > index_end) {
639 			ntfs_error(icx->idx_ni->vol->sb,
640 					"Index entry out of bounds in inode %llu.\n",
641 					(unsigned long long)icx->idx_ni->mft_no);
642 			return -ERANGE;
643 		}
644 
645 		/*
646 		 * The last entry cannot contain a key.  It can however contain
647 		 * a pointer to a child node in the B+tree so we just break out.
648 		 */
649 		if (ntfs_ie_end(ie))
650 			break;
651 
652 		/*
653 		 * Not a perfect match, need to do full blown collation so we
654 		 * know which way in the B+tree we have to go.
655 		 */
656 		rc = ntfs_collate(icx->idx_ni->vol, icx->cr, key, key_len, &ie->key,
657 				le16_to_cpu(ie->key_length));
658 		if (rc == -EINVAL) {
659 			ntfs_error(icx->idx_ni->vol->sb,
660 				"Collation error. Perhaps a filename contains invalid characters?\n");
661 			return -ERANGE;
662 		}
663 		/*
664 		 * If @key collates before the key of the current entry, there
665 		 * is definitely no such key in this index but we might need to
666 		 * descend into the B+tree so we just break out of the loop.
667 		 */
668 		if (rc == -1)
669 			break;
670 
671 		if (!rc) {
672 			*ie_out = ie;
673 			icx->parent_pos[icx->pindex] = item;
674 			return 0;
675 		}
676 
677 		item++;
678 	}
679 	/*
680 	 * We have finished with this index block without success. Check for the
681 	 * presence of a child node and if not present return with errno ENOENT,
682 	 * otherwise we will keep searching in another index block.
683 	 */
684 	if (!(ie->flags & INDEX_ENTRY_NODE)) {
685 		ntfs_debug("Index entry wasn't found.\n");
686 		*ie_out = ie;
687 		return -ENOENT;
688 	}
689 
690 	/* Get the starting vcn of the index_block holding the child node. */
691 	*vcn = ntfs_ie_get_vcn(ie);
692 	if (*vcn < 0) {
693 		ntfs_error(icx->idx_ni->vol->sb, "Negative vcn in inode %llu\n",
694 				(unsigned long long)icx->idx_ni->mft_no);
695 		return -EINVAL;
696 	}
697 
698 	ntfs_debug("Parent entry number %d\n", item);
699 	icx->parent_pos[icx->pindex] = item;
700 
701 	return -EAGAIN;
702 }
703 
704 struct ntfs_inode *ntfs_ia_open(struct ntfs_index_context *icx, struct ntfs_inode *ni)
705 {
706 	struct inode *ia_vi;
707 
708 	ia_vi = ntfs_index_iget(VFS_I(ni), icx->name, icx->name_len);
709 	if (IS_ERR(ia_vi)) {
710 		ntfs_error(icx->idx_ni->vol->sb,
711 				"Failed to open index allocation of inode %llu",
712 				(unsigned long long)ni->mft_no);
713 		return NULL;
714 	}
715 
716 	return NTFS_I(ia_vi);
717 }
718 
719 static int ntfs_ib_read(struct ntfs_index_context *icx, s64 vcn, struct index_block *dst)
720 {
721 	s64 pos, ret;
722 
723 	ntfs_debug("vcn: %lld\n", vcn);
724 
725 	pos = ntfs_ib_vcn_to_pos(icx, vcn);
726 
727 	ret = ntfs_inode_attr_pread(VFS_I(icx->ia_ni), pos, icx->block_size, (u8 *)dst);
728 	if (ret != icx->block_size) {
729 		if (ret == -1)
730 			ntfs_error(icx->idx_ni->vol->sb, "Failed to read index block");
731 		else
732 			ntfs_error(icx->idx_ni->vol->sb,
733 				"Failed to read full index block at %lld\n", pos);
734 		return -EIO;
735 	}
736 
737 	post_read_mst_fixup((struct ntfs_record *)((u8 *)dst), icx->block_size);
738 	if (ntfs_index_block_inconsistent(icx->idx_ni->vol, dst,
739 					  icx->block_size, vcn, icx->cr,
740 					  icx->idx_ni->mft_no))
741 		return -EIO;
742 	return 0;
743 }
744 
745 static int ntfs_icx_parent_inc(struct ntfs_index_context *icx)
746 {
747 	if (icx->pindex >= MAX_PARENT_VCN - 1) {
748 		ntfs_error(icx->idx_ni->vol->sb, "Index is over %d level deep", MAX_PARENT_VCN);
749 		return -EOPNOTSUPP;
750 	}
751 	icx->pindex++;
752 	return 0;
753 }
754 
755 static int ntfs_icx_parent_dec(struct ntfs_index_context *icx)
756 {
757 	icx->pindex--;
758 	if (icx->pindex < 0) {
759 		ntfs_error(icx->idx_ni->vol->sb, "Corrupt index pointer (%d)", icx->pindex);
760 		return -EINVAL;
761 	}
762 	return 0;
763 }
764 
765 /*
766  * ntfs_index_lookup - find a key in an index and return its index entry
767  * @key:	key for which to search in the index
768  * @key_len:	length of @key in bytes
769  * @icx:	context describing the index and the returned entry
770  *
771  * Before calling ntfs_index_lookup(), @icx must have been obtained from a
772  * call to ntfs_index_ctx_get().
773  *
774  * Look for the @key in the index specified by the index lookup context @icx.
775  * ntfs_index_lookup() walks the contents of the index looking for the @key.
776  *
777  * If the @key is found in the index, 0 is returned and @icx is setup to
778  * describe the index entry containing the matching @key.  @icx->entry is the
779  * index entry and @icx->data and @icx->data_len are the index entry data and
780  * its length in bytes, respectively.
781  *
782  * If the @key is not found in the index, -ENOENT is returned and
783  * @icx is setup to describe the index entry whose key collates immediately
784  * after the search @key, i.e. this is the position in the index at which
785  * an index entry with a key of @key would need to be inserted.
786  *
787  * When finished with the entry and its data, call ntfs_index_ctx_put() to free
788  * the context and other associated resources.
789  *
790  * If the index entry was modified, call ntfs_index_entry_mark_dirty() before
791  * the call to ntfs_index_ctx_put() to ensure that the changes are written
792  * to disk.
793  */
794 int ntfs_index_lookup(const void *key, const u32 key_len, struct ntfs_index_context *icx)
795 {
796 	s64 old_vcn, vcn;
797 	struct ntfs_inode *ni = icx->idx_ni;
798 	struct super_block *sb = ni->vol->sb;
799 	struct index_root *ir;
800 	struct index_entry *ie;
801 	struct index_block *ib = NULL;
802 	int err = 0;
803 
804 	ntfs_debug("Entering\n");
805 
806 	if (!key) {
807 		ntfs_error(sb, "key: %p  key_len: %d", key, key_len);
808 		return -EINVAL;
809 	}
810 
811 	ir = ntfs_ir_lookup(ni, icx->name, icx->name_len, &icx->actx);
812 	if (!ir)
813 		return -EIO;
814 
815 	icx->block_size = le32_to_cpu(ir->index_block_size);
816 	if (icx->block_size < NTFS_BLOCK_SIZE) {
817 		err = -EINVAL;
818 		ntfs_error(sb,
819 			"Index block size (%d) is smaller than the sector size (%d)",
820 			icx->block_size, NTFS_BLOCK_SIZE);
821 		goto err_out;
822 	}
823 
824 	if (ni->vol->cluster_size <= icx->block_size)
825 		icx->vcn_size_bits = ni->vol->cluster_size_bits;
826 	else
827 		icx->vcn_size_bits = ni->vol->sector_size_bits;
828 
829 	icx->cr = ir->collation_rule;
830 	if (!ntfs_is_collation_rule_supported(icx->cr)) {
831 		err = -EOPNOTSUPP;
832 		ntfs_error(sb, "Unknown collation rule 0x%x",
833 				(unsigned int)le32_to_cpu(icx->cr));
834 		goto err_out;
835 	}
836 
837 	old_vcn = VCN_INDEX_ROOT_PARENT;
838 	err = ntfs_ie_lookup(key, key_len, icx, &ir->index, &vcn, &ie);
839 	if (err == -ERANGE || err == -EINVAL)
840 		goto err_out;
841 
842 	icx->ir = ir;
843 	if (err != -EAGAIN) {
844 		icx->is_in_root = true;
845 		icx->parent_vcn[icx->pindex] = old_vcn;
846 		goto done;
847 	}
848 
849 	/* Child node present, descend into it. */
850 	icx->ia_ni = ntfs_ia_open(icx, ni);
851 	if (!icx->ia_ni) {
852 		err = -ENOENT;
853 		goto err_out;
854 	}
855 
856 	ib = kvzalloc(icx->block_size, GFP_NOFS);
857 	if (!ib) {
858 		err = -ENOMEM;
859 		goto err_out;
860 	}
861 
862 descend_into_child_node:
863 	icx->parent_vcn[icx->pindex] = old_vcn;
864 	if (ntfs_icx_parent_inc(icx)) {
865 		err = -EIO;
866 		goto err_out;
867 	}
868 	old_vcn = vcn;
869 
870 	ntfs_debug("Descend into node with s64 %lld.\n", vcn);
871 
872 	if (ntfs_ib_read(icx, vcn, ib)) {
873 		err = -EIO;
874 		goto err_out;
875 	}
876 	err = ntfs_ie_lookup(key, key_len, icx, &ib->index, &vcn, &ie);
877 	if (err != -EAGAIN) {
878 		if (err == -EINVAL || err == -ERANGE)
879 			goto err_out;
880 
881 		icx->is_in_root = false;
882 		icx->ib = ib;
883 		icx->parent_vcn[icx->pindex] = vcn;
884 		goto done;
885 	}
886 
887 	if ((ib->index.flags & NODE_MASK) == LEAF_NODE) {
888 		ntfs_error(icx->idx_ni->vol->sb,
889 			"Index entry with child node found in a leaf node in inode 0x%llx.\n",
890 			(unsigned long long)ni->mft_no);
891 		goto err_out;
892 	}
893 
894 	goto descend_into_child_node;
895 err_out:
896 	if (icx->actx) {
897 		ntfs_attr_put_search_ctx(icx->actx);
898 		icx->actx = NULL;
899 	}
900 	kvfree(ib);
901 	if (!err)
902 		err = -EIO;
903 	return err;
904 done:
905 	icx->entry = ie;
906 	icx->data = (u8 *)ie + offsetof(struct index_entry, key);
907 	icx->data_len = le16_to_cpu(ie->key_length);
908 	ntfs_debug("Done.\n");
909 	return err;
910 
911 }
912 
913 static struct index_block *ntfs_ib_alloc(s64 ib_vcn, u32 ib_size,
914 		u8 node_type)
915 {
916 	struct index_block *ib;
917 	int ih_size = sizeof(struct index_header);
918 
919 	ntfs_debug("Entering ib_vcn = %lld ib_size = %u\n", ib_vcn, ib_size);
920 
921 	ib = kvzalloc(ib_size, GFP_NOFS);
922 	if (!ib)
923 		return NULL;
924 
925 	ib->magic = magic_INDX;
926 	ib->usa_ofs = cpu_to_le16(sizeof(struct index_block));
927 	ib->usa_count = cpu_to_le16(ib_size / NTFS_BLOCK_SIZE + 1);
928 	/* Set USN to 1 */
929 	*(__le16 *)((char *)ib + le16_to_cpu(ib->usa_ofs)) = cpu_to_le16(1);
930 	ib->lsn = 0;
931 	ib->index_block_vcn = cpu_to_le64(ib_vcn);
932 	ib->index.entries_offset = cpu_to_le32((ih_size +
933 				le16_to_cpu(ib->usa_count) * 2 + 7) & ~7);
934 	ib->index.index_length = 0;
935 	ib->index.allocated_size = cpu_to_le32(ib_size -
936 			(sizeof(struct index_block) - ih_size));
937 	ib->index.flags = node_type;
938 
939 	return ib;
940 }
941 
942 /*
943  *  Find the median by going through all the entries
944  */
945 static struct index_entry *ntfs_ie_get_median(struct index_header *ih)
946 {
947 	struct index_entry *ie, *ie_start;
948 	u8 *ie_end;
949 	int i = 0, median;
950 
951 	ntfs_debug("Entering\n");
952 
953 	ie = ie_start = ntfs_ie_get_first(ih);
954 	ie_end = (u8 *)ntfs_ie_get_end(ih);
955 
956 	while ((u8 *)ie < ie_end && !ntfs_ie_end(ie)) {
957 		ie = ntfs_ie_get_next(ie);
958 		i++;
959 	}
960 	/*
961 	 * NOTE: this could be also the entry at the half of the index block.
962 	 */
963 	median = i / 2 - 1;
964 
965 	ntfs_debug("Entries: %d  median: %d\n", i, median);
966 
967 	for (i = 0, ie = ie_start; i <= median; i++)
968 		ie = ntfs_ie_get_next(ie);
969 
970 	return ie;
971 }
972 
973 static u64 ntfs_ibm_vcn_to_pos(struct ntfs_index_context *icx, s64 vcn)
974 {
975 	u64 pos = ntfs_ib_vcn_to_pos(icx, vcn);
976 
977 	do_div(pos, icx->block_size);
978 	return pos;
979 }
980 
981 static s64 ntfs_ibm_pos_to_vcn(struct ntfs_index_context *icx, s64 pos)
982 {
983 	return ntfs_ib_pos_to_vcn(icx, pos * icx->block_size);
984 }
985 
986 static int ntfs_ibm_add(struct ntfs_index_context *icx)
987 {
988 	u8 bmp[8];
989 
990 	ntfs_debug("Entering\n");
991 
992 	if (ntfs_attr_exist(icx->idx_ni, AT_BITMAP, icx->name, icx->name_len))
993 		return 0;
994 	/*
995 	 * AT_BITMAP must be at least 8 bytes.
996 	 */
997 	memset(bmp, 0, sizeof(bmp));
998 	if (ntfs_attr_add(icx->idx_ni, AT_BITMAP, icx->name, icx->name_len,
999 				bmp, sizeof(bmp))) {
1000 		ntfs_error(icx->idx_ni->vol->sb, "Failed to add AT_BITMAP");
1001 		return -EINVAL;
1002 	}
1003 
1004 	return 0;
1005 }
1006 
1007 static int ntfs_ibm_modify(struct ntfs_index_context *icx, s64 vcn, int set)
1008 {
1009 	u8 byte;
1010 	u64 pos = ntfs_ibm_vcn_to_pos(icx, vcn);
1011 	u32 bpos = pos / 8;
1012 	u32 bit = 1 << (pos % 8);
1013 	struct ntfs_inode *bmp_ni;
1014 	struct inode *bmp_vi;
1015 	int ret = 0;
1016 
1017 	ntfs_debug("%s vcn: %lld\n", set ? "set" : "clear", vcn);
1018 
1019 	bmp_vi = ntfs_attr_iget(VFS_I(icx->idx_ni), AT_BITMAP, icx->name, icx->name_len);
1020 	if (IS_ERR(bmp_vi)) {
1021 		ntfs_error(icx->idx_ni->vol->sb, "Failed to open $BITMAP attribute");
1022 		return PTR_ERR(bmp_vi);
1023 	}
1024 
1025 	bmp_ni = NTFS_I(bmp_vi);
1026 
1027 	if (set) {
1028 		if (bmp_ni->data_size < bpos + 1) {
1029 			ret = ntfs_attr_truncate(bmp_ni, (bmp_ni->data_size + 8) & ~7);
1030 			if (ret) {
1031 				ntfs_error(icx->idx_ni->vol->sb, "Failed to truncate AT_BITMAP");
1032 				goto err;
1033 			}
1034 			i_size_write(bmp_vi, (loff_t)bmp_ni->data_size);
1035 		}
1036 	}
1037 
1038 	if (ntfs_inode_attr_pread(bmp_vi, bpos, 1, &byte) != 1) {
1039 		ret = -EIO;
1040 		ntfs_error(icx->idx_ni->vol->sb, "Failed to read $BITMAP");
1041 		goto err;
1042 	}
1043 
1044 	if (set)
1045 		byte |= bit;
1046 	else
1047 		byte &= ~bit;
1048 
1049 	if (ntfs_inode_attr_pwrite(bmp_vi, bpos, 1, &byte, false) != 1) {
1050 		ret = -EIO;
1051 		ntfs_error(icx->idx_ni->vol->sb, "Failed to write $Bitmap");
1052 		goto err;
1053 	}
1054 
1055 err:
1056 	iput(bmp_vi);
1057 	return ret;
1058 }
1059 
1060 static int ntfs_ibm_set(struct ntfs_index_context *icx, s64 vcn)
1061 {
1062 	return ntfs_ibm_modify(icx, vcn, 1);
1063 }
1064 
1065 static int ntfs_ibm_clear(struct ntfs_index_context *icx, s64 vcn)
1066 {
1067 	return ntfs_ibm_modify(icx, vcn, 0);
1068 }
1069 
1070 static s64 ntfs_ibm_get_free(struct ntfs_index_context *icx)
1071 {
1072 	u8 *bm;
1073 	int bit;
1074 	s64 vcn, byte, size;
1075 
1076 	ntfs_debug("Entering\n");
1077 
1078 	bm = ntfs_attr_readall(icx->idx_ni, AT_BITMAP,  icx->name, icx->name_len,
1079 			&size);
1080 	if (!bm)
1081 		return (s64)-1;
1082 
1083 	for (byte = 0; byte < size; byte++) {
1084 		if (bm[byte] == 255)
1085 			continue;
1086 
1087 		for (bit = 0; bit < 8; bit++) {
1088 			if (!(bm[byte] & (1 << bit))) {
1089 				vcn = ntfs_ibm_pos_to_vcn(icx, byte * 8 + bit);
1090 				goto out;
1091 			}
1092 		}
1093 	}
1094 
1095 	vcn = ntfs_ibm_pos_to_vcn(icx, size * 8);
1096 out:
1097 	ntfs_debug("allocated vcn: %lld\n", vcn);
1098 
1099 	if (ntfs_ibm_set(icx, vcn))
1100 		vcn = (s64)-1;
1101 
1102 	kvfree(bm);
1103 	return vcn;
1104 }
1105 
1106 static struct index_block *ntfs_ir_to_ib(struct index_root *ir, s64 ib_vcn)
1107 {
1108 	struct index_block *ib;
1109 	struct index_entry *ie_last;
1110 	char *ies_start, *ies_end;
1111 	int i;
1112 
1113 	ntfs_debug("Entering\n");
1114 
1115 	ib = ntfs_ib_alloc(ib_vcn, le32_to_cpu(ir->index_block_size), LEAF_NODE);
1116 	if (!ib)
1117 		return NULL;
1118 
1119 	ies_start = (char *)ntfs_ie_get_first(&ir->index);
1120 	ies_end   = (char *)ntfs_ie_get_end(&ir->index);
1121 	ie_last   = ntfs_ie_get_last((struct index_entry *)ies_start, ies_end);
1122 	/*
1123 	 * Copy all entries, including the termination entry
1124 	 * as well, which can never have any data.
1125 	 */
1126 	i = (char *)ie_last - ies_start + le16_to_cpu(ie_last->length);
1127 	memcpy(ntfs_ie_get_first(&ib->index), ies_start, i);
1128 
1129 	ib->index.flags = ir->index.flags;
1130 	ib->index.index_length = cpu_to_le32(i +
1131 			le32_to_cpu(ib->index.entries_offset));
1132 	return ib;
1133 }
1134 
1135 static void ntfs_ir_nill(struct index_root *ir)
1136 {
1137 	struct index_entry *ie_last;
1138 	char *ies_start, *ies_end;
1139 
1140 	ntfs_debug("Entering\n");
1141 
1142 	ies_start = (char *)ntfs_ie_get_first(&ir->index);
1143 	ies_end   = (char *)ntfs_ie_get_end(&ir->index);
1144 	ie_last   = ntfs_ie_get_last((struct index_entry *)ies_start, ies_end);
1145 	/*
1146 	 * Move the index root termination entry forward
1147 	 */
1148 	if ((char *)ie_last > ies_start) {
1149 		memmove((char *)ntfs_ie_get_first(&ir->index),
1150 			(char *)ie_last, le16_to_cpu(ie_last->length));
1151 		ie_last = (struct index_entry *)ies_start;
1152 	}
1153 }
1154 
1155 static int ntfs_ib_copy_tail(struct ntfs_index_context *icx, struct index_block *src,
1156 		struct index_entry *median, s64 new_vcn)
1157 {
1158 	u8 *ies_end;
1159 	struct index_entry *ie_head;		/* first entry after the median */
1160 	int tail_size, ret;
1161 	struct index_block *dst;
1162 
1163 	ntfs_debug("Entering\n");
1164 
1165 	dst = ntfs_ib_alloc(new_vcn, icx->block_size,
1166 			src->index.flags & NODE_MASK);
1167 	if (!dst)
1168 		return -ENOMEM;
1169 
1170 	ie_head = ntfs_ie_get_next(median);
1171 
1172 	ies_end = (u8 *)ntfs_ie_get_end(&src->index);
1173 	tail_size = ies_end - (u8 *)ie_head;
1174 	memcpy(ntfs_ie_get_first(&dst->index), ie_head, tail_size);
1175 
1176 	dst->index.index_length = cpu_to_le32(tail_size +
1177 			le32_to_cpu(dst->index.entries_offset));
1178 	ret = ntfs_ib_write(icx, dst);
1179 
1180 	kvfree(dst);
1181 	return ret;
1182 }
1183 
1184 static int ntfs_ib_cut_tail(struct ntfs_index_context *icx, struct index_block *ib,
1185 		struct index_entry *ie)
1186 {
1187 	char *ies_start, *ies_end;
1188 	struct index_entry *ie_last;
1189 	int ret;
1190 
1191 	ntfs_debug("Entering\n");
1192 
1193 	ies_start = (char *)ntfs_ie_get_first(&ib->index);
1194 	ies_end   = (char *)ntfs_ie_get_end(&ib->index);
1195 
1196 	ie_last   = ntfs_ie_get_last((struct index_entry *)ies_start, ies_end);
1197 	if (ie_last->flags & INDEX_ENTRY_NODE)
1198 		ntfs_ie_set_vcn(ie_last, ntfs_ie_get_vcn(ie));
1199 
1200 	unsafe_memcpy(ie, ie_last, le16_to_cpu(ie_last->length),
1201 			/* alloc is larger than ie_last->length, see ntfs_ie_get_last() */);
1202 
1203 	ib->index.index_length = cpu_to_le32(((char *)ie - ies_start) +
1204 			le16_to_cpu(ie->length) + le32_to_cpu(ib->index.entries_offset));
1205 
1206 	ret = ntfs_ib_write(icx, ib);
1207 	return ret;
1208 }
1209 
1210 static int ntfs_ia_add(struct ntfs_index_context *icx)
1211 {
1212 	int ret;
1213 
1214 	ntfs_debug("Entering\n");
1215 
1216 	ret = ntfs_ibm_add(icx);
1217 	if (ret)
1218 		return ret;
1219 
1220 	if (!ntfs_attr_exist(icx->idx_ni, AT_INDEX_ALLOCATION, icx->name, icx->name_len)) {
1221 		ret = ntfs_attr_add(icx->idx_ni, AT_INDEX_ALLOCATION, icx->name,
1222 					icx->name_len, NULL, 0);
1223 		if (ret) {
1224 			ntfs_error(icx->idx_ni->vol->sb, "Failed to add AT_INDEX_ALLOCATION");
1225 			return ret;
1226 		}
1227 	}
1228 
1229 	icx->ia_ni = ntfs_ia_open(icx, icx->idx_ni);
1230 	if (!icx->ia_ni)
1231 		return -ENOENT;
1232 
1233 	return 0;
1234 }
1235 
1236 static int ntfs_ir_reparent(struct ntfs_index_context *icx)
1237 {
1238 	struct ntfs_attr_search_ctx *ctx = NULL;
1239 	struct index_root *ir;
1240 	struct index_entry *ie;
1241 	struct index_block *ib = NULL;
1242 	s64 new_ib_vcn;
1243 	u32 index_length;
1244 	u32 old_value_length;
1245 	int ix_root_size;
1246 	int ret = 0;
1247 
1248 	ntfs_debug("Entering\n");
1249 
1250 	ir = ntfs_ir_lookup2(icx->idx_ni, icx->name, icx->name_len);
1251 	if (!ir) {
1252 		ret = -ENOENT;
1253 		goto out;
1254 	}
1255 
1256 	if ((ir->index.flags & NODE_MASK) == SMALL_INDEX) {
1257 		ret = ntfs_ia_add(icx);
1258 		if (ret)
1259 			goto out;
1260 	}
1261 
1262 	new_ib_vcn = ntfs_ibm_get_free(icx);
1263 	if (new_ib_vcn < 0) {
1264 		ret = -EINVAL;
1265 		goto out;
1266 	}
1267 
1268 	ir = ntfs_ir_lookup2(icx->idx_ni, icx->name, icx->name_len);
1269 	if (!ir) {
1270 		ret = -ENOENT;
1271 		goto clear_bmp;
1272 	}
1273 
1274 	ib = ntfs_ir_to_ib(ir, new_ib_vcn);
1275 	if (ib == NULL) {
1276 		ret = -EIO;
1277 		ntfs_error(icx->idx_ni->vol->sb, "Failed to move index root to index block");
1278 		goto clear_bmp;
1279 	}
1280 
1281 	ret = ntfs_ib_write(icx, ib);
1282 	if (ret)
1283 		goto clear_bmp;
1284 
1285 retry:
1286 	ir = ntfs_ir_lookup(icx->idx_ni, icx->name, icx->name_len, &ctx);
1287 	if (!ir) {
1288 		ret = -ENOENT;
1289 		goto clear_bmp;
1290 	}
1291 
1292 	old_value_length = le32_to_cpu(ctx->attr->data.resident.value_length);
1293 	index_length = le32_to_cpu(ir->index.entries_offset) +
1294 		sizeof(struct index_entry_header) + sizeof(s64);
1295 	ix_root_size = offsetof(struct index_root, index) + index_length;
1296 	/* Grow the resident value before publishing the larger root header. */
1297 	if (ix_root_size > old_value_length) {
1298 		ret = ntfs_resident_attr_value_resize(ctx->mrec, ctx->attr, ix_root_size);
1299 		if (ret)
1300 			goto resize_failed;
1301 
1302 		icx->idx_ni->data_size = ix_root_size;
1303 		icx->idx_ni->initialized_size = ix_root_size;
1304 		icx->idx_ni->allocated_size = (ix_root_size + 7) & ~7;
1305 	}
1306 
1307 	ntfs_ir_nill(ir);
1308 
1309 	ie = ntfs_ie_get_first(&ir->index);
1310 	ie->flags |= INDEX_ENTRY_NODE;
1311 	ie->length = cpu_to_le16(sizeof(struct index_entry_header) + sizeof(s64));
1312 
1313 	ir->index.flags = LARGE_INDEX;
1314 	NInoSetIndexAllocPresent(icx->idx_ni);
1315 	ir->index.index_length = cpu_to_le32(index_length);
1316 	ir->index.allocated_size = ir->index.index_length;
1317 
1318 	if (ix_root_size <= old_value_length) {
1319 		ret = ntfs_resident_attr_value_resize(ctx->mrec, ctx->attr, ix_root_size);
1320 		if (ret)
1321 			goto resize_failed;
1322 
1323 		icx->idx_ni->data_size = ix_root_size;
1324 		icx->idx_ni->initialized_size = ix_root_size;
1325 		icx->idx_ni->allocated_size = (ix_root_size + 7) & ~7;
1326 	}
1327 	ntfs_ie_set_vcn(ie, new_ib_vcn);
1328 	goto err_out;
1329 
1330 resize_failed:
1331 	/*
1332 	 * When there is no space to build a non-resident
1333 	 * index, we may have to move the root to an extent
1334 	 */
1335 	if ((ret == -ENOSPC) && (ctx->al_entry || !ntfs_inode_add_attrlist(icx->idx_ni))) {
1336 		ntfs_attr_put_search_ctx(ctx);
1337 		ctx = NULL;
1338 		ir = ntfs_ir_lookup(icx->idx_ni, icx->name, icx->name_len, &ctx);
1339 		if (ir && !ntfs_attr_record_move_away(ctx, ix_root_size -
1340 				le32_to_cpu(ctx->attr->data.resident.value_length))) {
1341 			if (ntfs_attrlist_update(ctx->base_ntfs_ino ?
1342 						 ctx->base_ntfs_ino : ctx->ntfs_ino))
1343 				goto clear_bmp;
1344 			ntfs_attr_put_search_ctx(ctx);
1345 			ctx = NULL;
1346 			goto retry;
1347 		}
1348 	}
1349 clear_bmp:
1350 	ntfs_ibm_clear(icx, new_ib_vcn);
1351 	goto err_out;
1352 err_out:
1353 	kvfree(ib);
1354 	if (ctx)
1355 		ntfs_attr_put_search_ctx(ctx);
1356 out:
1357 	return ret;
1358 }
1359 
1360 /*
1361  * ntfs_ir_truncate - Truncate index root attribute
1362  * @icx: index context
1363  * @data_size: new data size for the index root
1364  */
1365 static int ntfs_ir_truncate(struct ntfs_index_context *icx, int data_size)
1366 {
1367 	int ret;
1368 	u32 old_allocated_size;
1369 	bool shrink;
1370 
1371 	ntfs_debug("Entering\n");
1372 
1373 	old_allocated_size = le32_to_cpu(icx->ir->index.allocated_size);
1374 	shrink = data_size < old_allocated_size;
1375 	if (shrink)
1376 		icx->ir->index.allocated_size = cpu_to_le32(data_size);
1377 
1378 	/*
1379 	 *  INDEX_ROOT must be resident and its entries can be moved to
1380 	 *  struct index_block, so ENOSPC isn't a real error.
1381 	 */
1382 	ret = ntfs_attr_truncate(icx->idx_ni, data_size + offsetof(struct index_root, index));
1383 	if (!ret) {
1384 		i_size_write(VFS_I(icx->idx_ni), icx->idx_ni->initialized_size);
1385 		icx->ir = ntfs_ir_lookup2(icx->idx_ni, icx->name, icx->name_len);
1386 		if (!icx->ir)
1387 			return -ENOENT;
1388 
1389 		if (!shrink)
1390 			icx->ir->index.allocated_size = cpu_to_le32(data_size);
1391 	} else {
1392 		if (shrink)
1393 			icx->ir->index.allocated_size = cpu_to_le32(old_allocated_size);
1394 		if (ret != -ENOSPC)
1395 			ntfs_error(icx->idx_ni->vol->sb, "Failed to truncate INDEX_ROOT");
1396 	}
1397 
1398 	return ret;
1399 }
1400 
1401 /*
1402  * ntfs_ir_make_space - Make more space for the index root attribute
1403  * @icx: index context
1404  * @data_size: required data size for the index root
1405  */
1406 static int ntfs_ir_make_space(struct ntfs_index_context *icx, int data_size)
1407 {
1408 	int ret;
1409 
1410 	ntfs_debug("Entering\n");
1411 
1412 	ret = ntfs_ir_truncate(icx, data_size);
1413 	if (ret == -ENOSPC) {
1414 		ret = ntfs_ir_reparent(icx);
1415 		if (!ret)
1416 			ret = -EAGAIN;
1417 		else
1418 			ntfs_error(icx->idx_ni->vol->sb, "Failed to modify INDEX_ROOT");
1419 	}
1420 
1421 	return ret;
1422 }
1423 
1424 /*
1425  * NOTE: 'ie' must be a copy of a real index entry.
1426  */
1427 static int ntfs_ie_add_vcn(struct index_entry **ie)
1428 {
1429 	struct index_entry *p, *old = *ie;
1430 
1431 	old->length = cpu_to_le16(le16_to_cpu(old->length) + sizeof(s64));
1432 	p = krealloc(old, le16_to_cpu(old->length), GFP_NOFS);
1433 	if (!p)
1434 		return -ENOMEM;
1435 
1436 	p->flags |= INDEX_ENTRY_NODE;
1437 	*ie = p;
1438 	return 0;
1439 }
1440 
1441 static int ntfs_ih_insert(struct index_header *ih, struct index_entry *orig_ie, s64 new_vcn,
1442 		int pos)
1443 {
1444 	struct index_entry *ie_node, *ie;
1445 	int ret = 0;
1446 	s64 old_vcn;
1447 
1448 	ntfs_debug("Entering\n");
1449 	ie = ntfs_ie_dup(orig_ie);
1450 	if (!ie)
1451 		return -ENOMEM;
1452 
1453 	if (!(ie->flags & INDEX_ENTRY_NODE)) {
1454 		ret = ntfs_ie_add_vcn(&ie);
1455 		if (ret)
1456 			goto out;
1457 	}
1458 
1459 	ie_node = ntfs_ie_get_by_pos(ih, pos);
1460 	old_vcn = ntfs_ie_get_vcn(ie_node);
1461 	ntfs_ie_set_vcn(ie_node, new_vcn);
1462 
1463 	ntfs_ie_insert(ih, ie, ie_node);
1464 	ntfs_ie_set_vcn(ie_node, old_vcn);
1465 out:
1466 	kfree(ie);
1467 	return ret;
1468 }
1469 
1470 static s64 ntfs_icx_parent_vcn(struct ntfs_index_context *icx)
1471 {
1472 	return icx->parent_vcn[icx->pindex];
1473 }
1474 
1475 static s64 ntfs_icx_parent_pos(struct ntfs_index_context *icx)
1476 {
1477 	return icx->parent_pos[icx->pindex];
1478 }
1479 
1480 static int ntfs_ir_insert_median(struct ntfs_index_context *icx, struct index_entry *median,
1481 		s64 new_vcn)
1482 {
1483 	u32 new_size;
1484 	int ret;
1485 
1486 	ntfs_debug("Entering\n");
1487 
1488 	icx->ir = ntfs_ir_lookup2(icx->idx_ni, icx->name, icx->name_len);
1489 	if (!icx->ir)
1490 		return -ENOENT;
1491 
1492 	new_size = le32_to_cpu(icx->ir->index.index_length) +
1493 		le16_to_cpu(median->length);
1494 	if (!(median->flags & INDEX_ENTRY_NODE))
1495 		new_size += sizeof(s64);
1496 
1497 	ret = ntfs_ir_make_space(icx, new_size);
1498 	if (ret)
1499 		return ret;
1500 
1501 	icx->ir = ntfs_ir_lookup2(icx->idx_ni, icx->name, icx->name_len);
1502 	if (!icx->ir)
1503 		return -ENOENT;
1504 
1505 	return ntfs_ih_insert(&icx->ir->index, median, new_vcn,
1506 			ntfs_icx_parent_pos(icx));
1507 }
1508 
1509 static int ntfs_ib_split(struct ntfs_index_context *icx, struct index_block *ib);
1510 
1511 struct split_info {
1512 	struct list_head entry;
1513 	s64 new_vcn;
1514 	struct index_block *ib;
1515 };
1516 
1517 static int ntfs_ib_insert(struct ntfs_index_context *icx, struct index_entry *ie, s64 new_vcn,
1518 		struct split_info *si)
1519 {
1520 	struct index_block *ib;
1521 	u32 idx_size, allocated_size;
1522 	int err;
1523 	s64 old_vcn;
1524 
1525 	ntfs_debug("Entering\n");
1526 
1527 	ib = kvzalloc(icx->block_size, GFP_NOFS);
1528 	if (!ib)
1529 		return -ENOMEM;
1530 
1531 	old_vcn = ntfs_icx_parent_vcn(icx);
1532 
1533 	err = ntfs_ib_read(icx, old_vcn, ib);
1534 	if (err)
1535 		goto err_out;
1536 
1537 	idx_size = le32_to_cpu(ib->index.index_length);
1538 	allocated_size = le32_to_cpu(ib->index.allocated_size);
1539 	if (idx_size + le16_to_cpu(ie->length) + sizeof(s64) > allocated_size) {
1540 		si->ib = ib;
1541 		si->new_vcn = new_vcn;
1542 		return -EAGAIN;
1543 	}
1544 
1545 	err = ntfs_ih_insert(&ib->index, ie, new_vcn, ntfs_icx_parent_pos(icx));
1546 	if (err)
1547 		goto err_out;
1548 
1549 	err = ntfs_ib_write(icx, ib);
1550 
1551 err_out:
1552 	kvfree(ib);
1553 	return err;
1554 }
1555 
1556 /*
1557  * ntfs_ib_split - Split an index block
1558  * @icx: index context
1559  * @ib: index block to split
1560  */
1561 static int ntfs_ib_split(struct ntfs_index_context *icx, struct index_block *ib)
1562 {
1563 	struct index_entry *median;
1564 	s64 new_vcn;
1565 	int ret;
1566 	struct split_info *si;
1567 	LIST_HEAD(ntfs_cut_tail_list);
1568 
1569 	ntfs_debug("Entering\n");
1570 
1571 resplit:
1572 	ret = ntfs_icx_parent_dec(icx);
1573 	if (ret)
1574 		goto out;
1575 
1576 	median  = ntfs_ie_get_median(&ib->index);
1577 	new_vcn = ntfs_ibm_get_free(icx);
1578 	if (new_vcn < 0) {
1579 		ret = -EINVAL;
1580 		goto out;
1581 	}
1582 
1583 	ret = ntfs_ib_copy_tail(icx, ib, median, new_vcn);
1584 	if (ret) {
1585 		ntfs_ibm_clear(icx, new_vcn);
1586 		goto out;
1587 	}
1588 
1589 	if (ntfs_icx_parent_vcn(icx) == VCN_INDEX_ROOT_PARENT) {
1590 		ret = ntfs_ir_insert_median(icx, median, new_vcn);
1591 		if (ret) {
1592 			ntfs_ibm_clear(icx, new_vcn);
1593 			goto out;
1594 		}
1595 	} else {
1596 		si = kzalloc(sizeof(struct split_info), GFP_NOFS);
1597 		if (!si) {
1598 			ntfs_ibm_clear(icx, new_vcn);
1599 			ret = -ENOMEM;
1600 			goto out;
1601 		}
1602 
1603 		ret = ntfs_ib_insert(icx, median, new_vcn, si);
1604 		if (ret == -EAGAIN) {
1605 			list_add_tail(&si->entry, &ntfs_cut_tail_list);
1606 			ib = si->ib;
1607 			goto resplit;
1608 		} else if (ret) {
1609 			kvfree(si->ib);
1610 			kfree(si);
1611 			ntfs_ibm_clear(icx, new_vcn);
1612 			goto out;
1613 		}
1614 		kfree(si);
1615 	}
1616 
1617 	ret = ntfs_ib_cut_tail(icx, ib, median);
1618 
1619 out:
1620 	while (!list_empty(&ntfs_cut_tail_list)) {
1621 		si = list_last_entry(&ntfs_cut_tail_list, struct split_info, entry);
1622 		ntfs_ibm_clear(icx, si->new_vcn);
1623 		kvfree(si->ib);
1624 		list_del(&si->entry);
1625 		kfree(si);
1626 		if (!ret)
1627 			ret = -EAGAIN;
1628 	}
1629 
1630 	return ret;
1631 }
1632 
1633 int ntfs_ie_add(struct ntfs_index_context *icx, struct index_entry *ie)
1634 {
1635 	struct index_header *ih;
1636 	int allocated_size, new_size;
1637 	int ret;
1638 
1639 	while (1) {
1640 		ret = ntfs_index_lookup(&ie->key, le16_to_cpu(ie->key_length), icx);
1641 		if (!ret) {
1642 			ret = -EEXIST;
1643 			ntfs_error(icx->idx_ni->vol->sb, "Index already have such entry");
1644 			goto err_out;
1645 		}
1646 		if (ret != -ENOENT) {
1647 			ntfs_error(icx->idx_ni->vol->sb, "Failed to find place for new entry");
1648 			goto err_out;
1649 		}
1650 		ret = 0;
1651 
1652 		if (icx->is_in_root)
1653 			ih = &icx->ir->index;
1654 		else
1655 			ih = &icx->ib->index;
1656 
1657 		allocated_size = le32_to_cpu(ih->allocated_size);
1658 		new_size = le32_to_cpu(ih->index_length) + le16_to_cpu(ie->length);
1659 
1660 		if (new_size <= allocated_size)
1661 			break;
1662 
1663 		ntfs_debug("index block sizes: allocated: %d  needed: %d\n",
1664 				allocated_size, new_size);
1665 
1666 		if (icx->is_in_root)
1667 			ret = ntfs_ir_make_space(icx, new_size);
1668 		else
1669 			ret = ntfs_ib_split(icx, icx->ib);
1670 		if (ret && ret != -EAGAIN)
1671 			goto err_out;
1672 
1673 		mark_mft_record_dirty(icx->actx->ntfs_ino);
1674 		ntfs_index_ctx_reinit(icx);
1675 	}
1676 
1677 	ntfs_ie_insert(ih, ie, icx->entry);
1678 	ntfs_index_entry_mark_dirty(icx);
1679 
1680 err_out:
1681 	ntfs_debug("%s\n", ret ? "Failed" : "Done");
1682 	return ret;
1683 }
1684 
1685 /*
1686  * ntfs_index_add_filename - add filename to directory index
1687  * @ni:		ntfs inode describing directory to which index add filename
1688  * @fn:		FILE_NAME attribute to add
1689  * @mref:	reference of the inode which @fn describes
1690  */
1691 int ntfs_index_add_filename(struct ntfs_inode *ni, struct file_name_attr *fn, u64 mref)
1692 {
1693 	struct index_entry *ie;
1694 	struct ntfs_index_context *icx;
1695 	int fn_size, ie_size, err;
1696 
1697 	ntfs_debug("Entering\n");
1698 
1699 	if (!ni || !fn)
1700 		return -EINVAL;
1701 
1702 	fn_size = (fn->file_name_length * sizeof(__le16)) +
1703 		sizeof(struct file_name_attr);
1704 	ie_size = (sizeof(struct index_entry_header) + fn_size + 7) & ~7;
1705 
1706 	ie = kzalloc(ie_size, GFP_NOFS);
1707 	if (!ie)
1708 		return -ENOMEM;
1709 
1710 	ie->data.dir.indexed_file = cpu_to_le64(mref);
1711 	ie->length	 = cpu_to_le16(ie_size);
1712 	ie->key_length	 = cpu_to_le16(fn_size);
1713 
1714 	unsafe_memcpy(&ie->key, fn, fn_size,
1715 		      /* "fn_size" was correctly calculated above */);
1716 
1717 	icx = ntfs_index_ctx_get(ni, I30, 4);
1718 	if (!icx) {
1719 		err = -ENOMEM;
1720 		goto out;
1721 	}
1722 
1723 	err = ntfs_ie_add(icx, ie);
1724 	ntfs_index_ctx_put(icx);
1725 out:
1726 	kfree(ie);
1727 	return err;
1728 }
1729 
1730 static int ntfs_ih_takeout(struct ntfs_index_context *icx, struct index_header *ih,
1731 		struct index_entry *ie, struct index_block *ib)
1732 {
1733 	struct index_entry *ie_roam;
1734 	int freed_space;
1735 	bool full;
1736 	int ret = 0;
1737 
1738 	ntfs_debug("Entering\n");
1739 
1740 	full = ih->index_length == ih->allocated_size;
1741 	ie_roam = ntfs_ie_dup_novcn(ie);
1742 	if (!ie_roam)
1743 		return -ENOMEM;
1744 
1745 	ntfs_ie_delete(ih, ie);
1746 
1747 	if (ntfs_icx_parent_vcn(icx) == VCN_INDEX_ROOT_PARENT) {
1748 		/*
1749 		 * Recover the space which may have been freed
1750 		 * while deleting an entry from root index
1751 		 */
1752 		freed_space = le32_to_cpu(ih->allocated_size) -
1753 			le32_to_cpu(ih->index_length);
1754 		if (full && (freed_space > 0) && !(freed_space & 7)) {
1755 			ntfs_ir_truncate(icx, le32_to_cpu(ih->index_length));
1756 			/* do nothing if truncation fails */
1757 		}
1758 
1759 		mark_mft_record_dirty(icx->actx->ntfs_ino);
1760 	} else {
1761 		ret = ntfs_ib_write(icx, ib);
1762 		if (ret)
1763 			goto out;
1764 	}
1765 
1766 	ntfs_index_ctx_reinit(icx);
1767 
1768 	ret = ntfs_ie_add(icx, ie_roam);
1769 out:
1770 	kfree(ie_roam);
1771 	return ret;
1772 }
1773 
1774 /*
1775  *  Used if an empty index block to be deleted has END entry as the parent
1776  *  in the INDEX_ROOT which is the only one there.
1777  */
1778 static void ntfs_ir_leafify(struct ntfs_index_context *icx, struct index_header *ih)
1779 {
1780 	struct index_entry *ie;
1781 
1782 	ntfs_debug("Entering\n");
1783 
1784 	ie = ntfs_ie_get_first(ih);
1785 	ie->flags &= ~INDEX_ENTRY_NODE;
1786 	ie->length = cpu_to_le16(le16_to_cpu(ie->length) - sizeof(s64));
1787 
1788 	ih->index_length = cpu_to_le32(le32_to_cpu(ih->index_length) - sizeof(s64));
1789 	ih->flags &= ~LARGE_INDEX;
1790 	NInoClearIndexAllocPresent(icx->idx_ni);
1791 
1792 	/* Not fatal error */
1793 	ntfs_ir_truncate(icx, le32_to_cpu(ih->index_length));
1794 }
1795 
1796 /*
1797  *  Used if an empty index block to be deleted has END entry as the parent
1798  *  in the INDEX_ROOT which is not the only one there.
1799  */
1800 static int ntfs_ih_reparent_end(struct ntfs_index_context *icx, struct index_header *ih,
1801 		struct index_block *ib)
1802 {
1803 	struct index_entry *ie, *ie_prev;
1804 
1805 	ntfs_debug("Entering\n");
1806 
1807 	ie = ntfs_ie_get_by_pos(ih, ntfs_icx_parent_pos(icx));
1808 	ie_prev = ntfs_ie_prev(ih, ie);
1809 	if (!ie_prev)
1810 		return -EIO;
1811 	ntfs_ie_set_vcn(ie, ntfs_ie_get_vcn(ie_prev));
1812 
1813 	return ntfs_ih_takeout(icx, ih, ie_prev, ib);
1814 }
1815 
1816 static int ntfs_index_rm_leaf(struct ntfs_index_context *icx)
1817 {
1818 	struct index_block *ib = NULL;
1819 	struct index_header *parent_ih;
1820 	struct index_entry *ie;
1821 	int ret;
1822 
1823 	ntfs_debug("pindex: %d\n", icx->pindex);
1824 
1825 	ret = ntfs_icx_parent_dec(icx);
1826 	if (ret)
1827 		return ret;
1828 
1829 	ret = ntfs_ibm_clear(icx, icx->parent_vcn[icx->pindex + 1]);
1830 	if (ret)
1831 		return ret;
1832 
1833 	if (ntfs_icx_parent_vcn(icx) == VCN_INDEX_ROOT_PARENT)
1834 		parent_ih = &icx->ir->index;
1835 	else {
1836 		ib = kvzalloc(icx->block_size, GFP_NOFS);
1837 		if (!ib)
1838 			return -ENOMEM;
1839 
1840 		ret = ntfs_ib_read(icx, ntfs_icx_parent_vcn(icx), ib);
1841 		if (ret)
1842 			goto out;
1843 
1844 		parent_ih = &ib->index;
1845 	}
1846 
1847 	ie = ntfs_ie_get_by_pos(parent_ih, ntfs_icx_parent_pos(icx));
1848 	if (!ntfs_ie_end(ie)) {
1849 		ret = ntfs_ih_takeout(icx, parent_ih, ie, ib);
1850 		goto out;
1851 	}
1852 
1853 	if (ntfs_ih_zero_entry(parent_ih)) {
1854 		if (ntfs_icx_parent_vcn(icx) == VCN_INDEX_ROOT_PARENT) {
1855 			ntfs_ir_leafify(icx, parent_ih);
1856 			goto out;
1857 		}
1858 
1859 		ret = ntfs_index_rm_leaf(icx);
1860 		goto out;
1861 	}
1862 
1863 	ret = ntfs_ih_reparent_end(icx, parent_ih, ib);
1864 out:
1865 	kvfree(ib);
1866 	return ret;
1867 }
1868 
1869 static int ntfs_index_rm_node(struct ntfs_index_context *icx)
1870 {
1871 	int entry_pos, pindex;
1872 	s64 vcn;
1873 	struct index_block *ib = NULL;
1874 	struct index_entry *ie_succ, *ie, *entry = icx->entry;
1875 	struct index_header *ih;
1876 	u32 new_size;
1877 	int delta, ret;
1878 
1879 	ntfs_debug("Entering\n");
1880 
1881 	if (!icx->ia_ni) {
1882 		icx->ia_ni = ntfs_ia_open(icx, icx->idx_ni);
1883 		if (!icx->ia_ni)
1884 			return -EINVAL;
1885 	}
1886 
1887 	ib = kvzalloc(icx->block_size, GFP_NOFS);
1888 	if (!ib)
1889 		return -ENOMEM;
1890 
1891 	ie_succ = ntfs_ie_get_next(icx->entry);
1892 	entry_pos = icx->parent_pos[icx->pindex]++;
1893 	pindex = icx->pindex;
1894 descend:
1895 	vcn = ntfs_ie_get_vcn(ie_succ);
1896 	ret = ntfs_ib_read(icx, vcn, ib);
1897 	if (ret)
1898 		goto out;
1899 
1900 	ie_succ = ntfs_ie_get_first(&ib->index);
1901 
1902 	ret = ntfs_icx_parent_inc(icx);
1903 	if (ret)
1904 		goto out;
1905 
1906 	icx->parent_vcn[icx->pindex] = vcn;
1907 	icx->parent_pos[icx->pindex] = 0;
1908 
1909 	if ((ib->index.flags & NODE_MASK) == INDEX_NODE)
1910 		goto descend;
1911 
1912 	if (ntfs_ih_zero_entry(&ib->index)) {
1913 		ret = -EIO;
1914 		ntfs_error(icx->idx_ni->vol->sb, "Empty index block");
1915 		goto out;
1916 	}
1917 
1918 	ie = ntfs_ie_dup(ie_succ);
1919 	if (!ie) {
1920 		ret = -ENOMEM;
1921 		goto out;
1922 	}
1923 
1924 	ret = ntfs_ie_add_vcn(&ie);
1925 	if (ret)
1926 		goto out2;
1927 
1928 	ntfs_ie_set_vcn(ie, ntfs_ie_get_vcn(icx->entry));
1929 
1930 	if (icx->is_in_root)
1931 		ih = &icx->ir->index;
1932 	else
1933 		ih = &icx->ib->index;
1934 
1935 	delta = le16_to_cpu(ie->length) - le16_to_cpu(icx->entry->length);
1936 	new_size = le32_to_cpu(ih->index_length) + delta;
1937 	if (delta > 0) {
1938 		if (icx->is_in_root) {
1939 			ret = ntfs_ir_make_space(icx, new_size);
1940 			if (ret != 0)
1941 				goto out2;
1942 
1943 			ih = &icx->ir->index;
1944 			entry = ntfs_ie_get_by_pos(ih, entry_pos);
1945 
1946 		} else if (new_size > le32_to_cpu(ih->allocated_size)) {
1947 			icx->pindex = pindex;
1948 			ret = ntfs_ib_split(icx, icx->ib);
1949 			if (!ret)
1950 				ret = -EAGAIN;
1951 			goto out2;
1952 		}
1953 	}
1954 
1955 	ntfs_ie_delete(ih, entry);
1956 	ntfs_ie_insert(ih, ie, entry);
1957 
1958 	if (icx->is_in_root)
1959 		ret = ntfs_ir_truncate(icx, new_size);
1960 	else
1961 		ret = ntfs_icx_ib_write(icx);
1962 	if (ret)
1963 		goto out2;
1964 
1965 	ntfs_ie_delete(&ib->index, ie_succ);
1966 
1967 	if (ntfs_ih_zero_entry(&ib->index))
1968 		ret = ntfs_index_rm_leaf(icx);
1969 	else
1970 		ret = ntfs_ib_write(icx, ib);
1971 
1972 out2:
1973 	kfree(ie);
1974 out:
1975 	kvfree(ib);
1976 	return ret;
1977 }
1978 
1979 /*
1980  * ntfs_index_rm - remove entry from the index
1981  * @icx:	index context describing entry to delete
1982  *
1983  * Delete entry described by @icx from the index. Index context is always
1984  * reinitialized after use of this function, so it can be used for index
1985  * lookup once again.
1986  */
1987 int ntfs_index_rm(struct ntfs_index_context *icx)
1988 {
1989 	struct index_header *ih;
1990 	int ret = 0;
1991 
1992 	ntfs_debug("Entering\n");
1993 
1994 	if (!icx || (!icx->ib && !icx->ir) || ntfs_ie_end(icx->entry)) {
1995 		ret = -EINVAL;
1996 		goto err_out;
1997 	}
1998 	if (icx->is_in_root)
1999 		ih = &icx->ir->index;
2000 	else
2001 		ih = &icx->ib->index;
2002 
2003 	if (icx->entry->flags & INDEX_ENTRY_NODE) {
2004 		ret = ntfs_index_rm_node(icx);
2005 		if (ret)
2006 			goto err_out;
2007 	} else if (icx->is_in_root || !ntfs_ih_one_entry(ih)) {
2008 		ntfs_ie_delete(ih, icx->entry);
2009 
2010 		if (icx->is_in_root)
2011 			ret = ntfs_ir_truncate(icx, le32_to_cpu(ih->index_length));
2012 		else
2013 			ret = ntfs_icx_ib_write(icx);
2014 		if (ret)
2015 			goto err_out;
2016 	} else {
2017 		ret = ntfs_index_rm_leaf(icx);
2018 		if (ret)
2019 			goto err_out;
2020 	}
2021 
2022 	return 0;
2023 err_out:
2024 	return ret;
2025 }
2026 
2027 int ntfs_index_remove(struct ntfs_inode *dir_ni, const void *key, const u32 keylen)
2028 {
2029 	int ret = 0;
2030 	struct ntfs_index_context *icx;
2031 
2032 	icx = ntfs_index_ctx_get(dir_ni, I30, 4);
2033 	if (!icx)
2034 		return -EINVAL;
2035 
2036 	while (1) {
2037 		ret = ntfs_index_lookup(key, keylen, icx);
2038 		if (ret)
2039 			goto err_out;
2040 
2041 		ret = ntfs_index_rm(icx);
2042 		if (ret && ret != -EAGAIN)
2043 			goto err_out;
2044 		else if (!ret)
2045 			break;
2046 
2047 		mark_mft_record_dirty(icx->actx->ntfs_ino);
2048 		ntfs_index_ctx_reinit(icx);
2049 	}
2050 
2051 	mark_mft_record_dirty(icx->actx->ntfs_ino);
2052 
2053 	ntfs_index_ctx_put(icx);
2054 	return 0;
2055 err_out:
2056 	ntfs_index_ctx_put(icx);
2057 	ntfs_error(dir_ni->vol->sb, "Delete failed");
2058 	return ret;
2059 }
2060 
2061 /*
2062  * ntfs_index_walk_down - walk down the index tree (leaf bound)
2063  * until there are no subnode in the first index entry returns
2064  * the entry at the bottom left in subnode
2065  */
2066 struct index_entry *ntfs_index_walk_down(struct index_entry *ie, struct ntfs_index_context *ictx)
2067 {
2068 	struct index_entry *entry;
2069 	struct index_block *ib;
2070 	int err;
2071 	s64 vcn;
2072 
2073 	entry = ie;
2074 	do {
2075 		vcn = ntfs_ie_get_vcn(entry);
2076 		if (ictx->is_in_root) {
2077 			ib = kvzalloc(ictx->block_size, GFP_NOFS);
2078 			if (!ib)
2079 				return ERR_PTR(-ENOMEM);
2080 			/*
2081 			 * Descending from root index (level 0) to the first
2082 			 * child level. is_in_root == true implies pindex == 0,
2083 			 * so advance to level 1.
2084 			 */
2085 			ictx->pindex = 1;
2086 			ictx->ir = NULL;
2087 			ictx->ib = ib;
2088 			ictx->is_in_root = false;
2089 		} else {
2090 			/* down from non-zero level */
2091 			err = ntfs_icx_parent_inc(ictx);
2092 			if (err)
2093 				return ERR_PTR(err);
2094 		}
2095 
2096 		ictx->parent_pos[ictx->pindex] = 0;
2097 		ictx->parent_vcn[ictx->pindex] = vcn;
2098 		if (!ntfs_ib_read(ictx, vcn, ictx->ib)) {
2099 			ictx->entry = ntfs_ie_get_first(&ictx->ib->index);
2100 			entry = ictx->entry;
2101 		} else
2102 			entry = ERR_PTR(-EIO);
2103 	} while (!IS_ERR(entry) && (entry->flags & INDEX_ENTRY_NODE));
2104 
2105 	return entry;
2106 }
2107 
2108 /*
2109  * ntfs_index_walk_up - walk up the index tree (root bound) until
2110  * there is a valid data entry in parent returns the parent entry
2111  * or NULL if no more parent.
2112  * @ie: current index entry
2113  * @ictx: index context
2114  */
2115 static struct index_entry *ntfs_index_walk_up(struct index_entry *ie,
2116 		struct ntfs_index_context *ictx)
2117 {
2118 	struct index_entry *entry = ie;
2119 	s64 vcn;
2120 
2121 	if (ictx->pindex <= 0)
2122 		return NULL;
2123 
2124 	do {
2125 		ictx->pindex--;
2126 		if (!ictx->pindex) {
2127 			/* we have reached the root */
2128 			kfree(ictx->ib);
2129 			ictx->ib = NULL;
2130 			ictx->is_in_root = true;
2131 			/* a new search context is to be allocated */
2132 			if (ictx->actx)
2133 				ntfs_attr_put_search_ctx(ictx->actx);
2134 			ictx->ir = ntfs_ir_lookup(ictx->idx_ni, ictx->name,
2135 						  ictx->name_len, &ictx->actx);
2136 			if (ictx->ir)
2137 				entry = ntfs_ie_get_by_pos(
2138 					&ictx->ir->index,
2139 					ictx->parent_pos[ictx->pindex]);
2140 			else
2141 				entry = NULL;
2142 		} else {
2143 			/* up into non-root node */
2144 			vcn = ictx->parent_vcn[ictx->pindex];
2145 			if (!ntfs_ib_read(ictx, vcn, ictx->ib)) {
2146 				entry = ntfs_ie_get_by_pos(
2147 					&ictx->ib->index,
2148 					ictx->parent_pos[ictx->pindex]);
2149 			} else
2150 				entry = NULL;
2151 		}
2152 		ictx->entry = entry;
2153 	} while (entry && (ictx->pindex > 0) &&
2154 		 (entry->flags & INDEX_ENTRY_END));
2155 	return entry;
2156 }
2157 
2158 /*
2159  * ntfs_index_next - get next entry in an index according to collating sequence.
2160  * Returns next entry or NULL if none.
2161  *
2162  * Sample layout :
2163  *
2164  *                 +---+---+---+---+---+---+---+---+    n ptrs to subnodes
2165  *                 |   |   | 10| 25| 33|   |   |   |    n-1 keys in between
2166  *                 +---+---+---+---+---+---+---+---+    no key in last entry
2167  *                              | A | A
2168  *                              | | | +-------------------------------+
2169  *   +--------------------------+ | +-----+                           |
2170  *   |                            +--+    |                           |
2171  *   V                               |    V                           |
2172  * +---+---+---+---+---+---+---+---+ |  +---+---+---+---+---+---+---+---+
2173  * | 11| 12| 13| 14| 15| 16| 17|   | |  | 26| 27| 28| 29| 30| 31| 32|   |
2174  * +---+---+---+---+---+---+---+---+ |  +---+---+---+---+---+---+---+---+
2175  *                               |   |
2176  *       +-----------------------+   |
2177  *       |                           |
2178  *     +---+---+---+---+---+---+---+---+
2179  *     | 18| 19| 20| 21| 22| 23| 24|   |
2180  *     +---+---+---+---+---+---+---+---+
2181  *
2182  * @ie: current index entry
2183  * @ictx: index context
2184  */
2185 struct index_entry *ntfs_index_next(struct index_entry *ie, struct ntfs_index_context *ictx)
2186 {
2187 	struct index_entry *next;
2188 	__le16 flags;
2189 
2190 	/*
2191 	 * lookup() may have returned an invalid node
2192 	 * when searching for a partial key
2193 	 * if this happens, walk up
2194 	 */
2195 	if (ie->flags & INDEX_ENTRY_END)
2196 		next = ntfs_index_walk_up(ie, ictx);
2197 	else {
2198 		/*
2199 		 * get next entry in same node
2200 		 * there is always one after any entry with data
2201 		 */
2202 		next = (struct index_entry *)((char *)ie + le16_to_cpu(ie->length));
2203 		++ictx->parent_pos[ictx->pindex];
2204 		flags = next->flags;
2205 
2206 		/* walk down if it has a subnode */
2207 		if (flags & INDEX_ENTRY_NODE) {
2208 			if (!ictx->ia_ni) {
2209 				ictx->ia_ni = ntfs_ia_open(ictx, ictx->idx_ni);
2210 				if (!ictx->ia_ni)
2211 					return ERR_PTR(-EIO);
2212 			}
2213 
2214 			next = ntfs_index_walk_down(next, ictx);
2215 			if (IS_ERR(next))
2216 				return next;
2217 		} else {
2218 
2219 			/* walk up it has no subnode, nor data */
2220 			if (flags & INDEX_ENTRY_END)
2221 				next = ntfs_index_walk_up(next, ictx);
2222 		}
2223 	}
2224 
2225 	/* return NULL if stuck at end of a block */
2226 	if (next && (next->flags & INDEX_ENTRY_END))
2227 		next = NULL;
2228 
2229 	return next;
2230 }
2231