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