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