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