xref: /linux/fs/ntfs/index.c (revision fab183d632628381b466a41479489541ac0e29a0)
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 
619 /*
620  * Find a key in the index block.
621  */
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)622 static int ntfs_ie_lookup(const void *key, const u32 key_len,
623 		struct ntfs_index_context *icx, struct index_header *ih,
624 		s64 *vcn, struct index_entry **ie_out)
625 {
626 	struct index_entry *ie;
627 	u8 *index_end;
628 	int rc, item = 0;
629 
630 	ntfs_debug("Entering\n");
631 
632 	index_end = ntfs_ie_get_end(ih);
633 
634 	/*
635 	 * Loop until we exceed valid memory (corruption case) or until we
636 	 * reach the last entry.
637 	 */
638 	for (ie = ntfs_ie_get_first(ih); ; ie = ntfs_ie_get_next(ie)) {
639 		/* Bounds checks. */
640 		if ((u8 *)ie + sizeof(struct index_entry_header) > index_end ||
641 				(u8 *)ie + le16_to_cpu(ie->length) > index_end) {
642 			ntfs_error(icx->idx_ni->vol->sb,
643 					"Index entry out of bounds in inode %llu.\n",
644 					(unsigned long long)icx->idx_ni->mft_no);
645 			return -ERANGE;
646 		}
647 
648 		/*
649 		 * The last entry cannot contain a key.  It can however contain
650 		 * a pointer to a child node in the B+tree so we just break out.
651 		 */
652 		if (ntfs_ie_end(ie))
653 			break;
654 
655 		/*
656 		 * Not a perfect match, need to do full blown collation so we
657 		 * know which way in the B+tree we have to go.
658 		 */
659 		rc = ntfs_collate(icx->idx_ni->vol, icx->cr, key, key_len, &ie->key,
660 				le16_to_cpu(ie->key_length));
661 		if (rc == -EINVAL) {
662 			ntfs_error(icx->idx_ni->vol->sb,
663 				"Collation error. Perhaps a filename contains invalid characters?\n");
664 			return -ERANGE;
665 		}
666 		/*
667 		 * If @key collates before the key of the current entry, there
668 		 * is definitely no such key in this index but we might need to
669 		 * descend into the B+tree so we just break out of the loop.
670 		 */
671 		if (rc == -1)
672 			break;
673 
674 		if (!rc) {
675 			*ie_out = ie;
676 			icx->parent_pos[icx->pindex] = item;
677 			return 0;
678 		}
679 
680 		item++;
681 	}
682 	/*
683 	 * We have finished with this index block without success. Check for the
684 	 * presence of a child node and if not present return with errno ENOENT,
685 	 * otherwise we will keep searching in another index block.
686 	 */
687 	if (!(ie->flags & INDEX_ENTRY_NODE)) {
688 		ntfs_debug("Index entry wasn't found.\n");
689 		*ie_out = ie;
690 		return -ENOENT;
691 	}
692 
693 	/* Get the starting vcn of the index_block holding the child node. */
694 	*vcn = ntfs_ie_get_vcn(ie);
695 	if (*vcn < 0) {
696 		ntfs_error(icx->idx_ni->vol->sb, "Negative vcn in inode %llu\n",
697 				(unsigned long long)icx->idx_ni->mft_no);
698 		return -EINVAL;
699 	}
700 
701 	ntfs_debug("Parent entry number %d\n", item);
702 	icx->parent_pos[icx->pindex] = item;
703 
704 	return -EAGAIN;
705 }
706 
ntfs_ia_open(struct ntfs_index_context * icx,struct ntfs_inode * ni)707 struct ntfs_inode *ntfs_ia_open(struct ntfs_index_context *icx, struct ntfs_inode *ni)
708 {
709 	struct inode *ia_vi;
710 
711 	ia_vi = ntfs_index_iget(VFS_I(ni), icx->name, icx->name_len);
712 	if (IS_ERR(ia_vi)) {
713 		ntfs_error(icx->idx_ni->vol->sb,
714 				"Failed to open index allocation of inode %llu",
715 				(unsigned long long)ni->mft_no);
716 		return NULL;
717 	}
718 
719 	return NTFS_I(ia_vi);
720 }
721 
ntfs_ib_read(struct ntfs_index_context * icx,s64 vcn,struct index_block * dst)722 static int ntfs_ib_read(struct ntfs_index_context *icx, s64 vcn, struct index_block *dst)
723 {
724 	s64 pos, ret;
725 
726 	ntfs_debug("vcn: %lld\n", vcn);
727 
728 	pos = ntfs_ib_vcn_to_pos(icx, vcn);
729 
730 	ret = ntfs_inode_attr_pread(VFS_I(icx->ia_ni), pos, icx->block_size, (u8 *)dst);
731 	if (ret != icx->block_size) {
732 		if (ret == -1)
733 			ntfs_error(icx->idx_ni->vol->sb, "Failed to read index block");
734 		else
735 			ntfs_error(icx->idx_ni->vol->sb,
736 				"Failed to read full index block at %lld\n", pos);
737 		return -EIO;
738 	}
739 
740 	post_read_mst_fixup((struct ntfs_record *)((u8 *)dst), icx->block_size);
741 	if (ntfs_index_block_inconsistent(icx->idx_ni->vol, dst,
742 					  icx->block_size, vcn, icx->cr,
743 					  icx->idx_ni->mft_no))
744 		return -EIO;
745 	return 0;
746 }
747 
ntfs_icx_parent_inc(struct ntfs_index_context * icx)748 static int ntfs_icx_parent_inc(struct ntfs_index_context *icx)
749 {
750 	if (icx->pindex >= MAX_PARENT_VCN - 1) {
751 		ntfs_error(icx->idx_ni->vol->sb, "Index is over %d level deep", MAX_PARENT_VCN);
752 		return -EOPNOTSUPP;
753 	}
754 	icx->pindex++;
755 	return 0;
756 }
757 
ntfs_icx_parent_dec(struct ntfs_index_context * icx)758 static int ntfs_icx_parent_dec(struct ntfs_index_context *icx)
759 {
760 	icx->pindex--;
761 	if (icx->pindex < 0) {
762 		ntfs_error(icx->idx_ni->vol->sb, "Corrupt index pointer (%d)", icx->pindex);
763 		return -EINVAL;
764 	}
765 	return 0;
766 }
767 
768 /*
769  * ntfs_index_lookup - find a key in an index and return its index entry
770  * @key:	key for which to search in the index
771  * @key_len:	length of @key in bytes
772  * @icx:	context describing the index and the returned entry
773  *
774  * Before calling ntfs_index_lookup(), @icx must have been obtained from a
775  * call to ntfs_index_ctx_get().
776  *
777  * Look for the @key in the index specified by the index lookup context @icx.
778  * ntfs_index_lookup() walks the contents of the index looking for the @key.
779  *
780  * If the @key is found in the index, 0 is returned and @icx is setup to
781  * describe the index entry containing the matching @key.  @icx->entry is the
782  * index entry and @icx->data and @icx->data_len are the index entry data and
783  * its length in bytes, respectively.
784  *
785  * If the @key is not found in the index, -ENOENT is returned and
786  * @icx is setup to describe the index entry whose key collates immediately
787  * after the search @key, i.e. this is the position in the index at which
788  * an index entry with a key of @key would need to be inserted.
789  *
790  * When finished with the entry and its data, call ntfs_index_ctx_put() to free
791  * the context and other associated resources.
792  *
793  * If the index entry was modified, call ntfs_index_entry_mark_dirty() before
794  * the call to ntfs_index_ctx_put() to ensure that the changes are written
795  * to disk.
796  */
ntfs_index_lookup(const void * key,const u32 key_len,struct ntfs_index_context * icx)797 int ntfs_index_lookup(const void *key, const u32 key_len, struct ntfs_index_context *icx)
798 {
799 	s64 old_vcn, vcn;
800 	struct ntfs_inode *ni = icx->idx_ni;
801 	struct super_block *sb = ni->vol->sb;
802 	struct index_root *ir;
803 	struct index_entry *ie;
804 	struct index_block *ib = NULL;
805 	int err = 0;
806 
807 	ntfs_debug("Entering\n");
808 
809 	if (!key) {
810 		ntfs_error(sb, "key: %p  key_len: %d", key, key_len);
811 		return -EINVAL;
812 	}
813 
814 	ir = ntfs_ir_lookup(ni, icx->name, icx->name_len, &icx->actx);
815 	if (!ir)
816 		return -EIO;
817 
818 	icx->block_size = le32_to_cpu(ir->index_block_size);
819 	if (icx->block_size < NTFS_BLOCK_SIZE) {
820 		err = -EINVAL;
821 		ntfs_error(sb,
822 			"Index block size (%d) is smaller than the sector size (%d)",
823 			icx->block_size, NTFS_BLOCK_SIZE);
824 		goto err_out;
825 	}
826 
827 	if (ni->vol->cluster_size <= icx->block_size)
828 		icx->vcn_size_bits = ni->vol->cluster_size_bits;
829 	else
830 		icx->vcn_size_bits = ni->vol->sector_size_bits;
831 
832 	icx->cr = ir->collation_rule;
833 	if (!ntfs_is_collation_rule_supported(icx->cr)) {
834 		err = -EOPNOTSUPP;
835 		ntfs_error(sb, "Unknown collation rule 0x%x",
836 				(unsigned int)le32_to_cpu(icx->cr));
837 		goto err_out;
838 	}
839 
840 	old_vcn = VCN_INDEX_ROOT_PARENT;
841 	err = ntfs_ie_lookup(key, key_len, icx, &ir->index, &vcn, &ie);
842 	if (err == -ERANGE || err == -EINVAL)
843 		goto err_out;
844 
845 	icx->ir = ir;
846 	if (err != -EAGAIN) {
847 		icx->is_in_root = true;
848 		icx->parent_vcn[icx->pindex] = old_vcn;
849 		goto done;
850 	}
851 
852 	/* Child node present, descend into it. */
853 	icx->ia_ni = ntfs_ia_open(icx, ni);
854 	if (!icx->ia_ni) {
855 		err = -ENOENT;
856 		goto err_out;
857 	}
858 
859 	ib = kvzalloc(icx->block_size, GFP_NOFS);
860 	if (!ib) {
861 		err = -ENOMEM;
862 		goto err_out;
863 	}
864 
865 descend_into_child_node:
866 	icx->parent_vcn[icx->pindex] = old_vcn;
867 	if (ntfs_icx_parent_inc(icx)) {
868 		err = -EIO;
869 		goto err_out;
870 	}
871 	old_vcn = vcn;
872 
873 	ntfs_debug("Descend into node with s64 %lld.\n", vcn);
874 
875 	if (ntfs_ib_read(icx, vcn, ib)) {
876 		err = -EIO;
877 		goto err_out;
878 	}
879 	err = ntfs_ie_lookup(key, key_len, icx, &ib->index, &vcn, &ie);
880 	if (err != -EAGAIN) {
881 		if (err == -EINVAL || err == -ERANGE)
882 			goto err_out;
883 
884 		icx->is_in_root = false;
885 		icx->ib = ib;
886 		icx->parent_vcn[icx->pindex] = vcn;
887 		goto done;
888 	}
889 
890 	if ((ib->index.flags & NODE_MASK) == LEAF_NODE) {
891 		ntfs_error(icx->idx_ni->vol->sb,
892 			"Index entry with child node found in a leaf node in inode 0x%llx.\n",
893 			(unsigned long long)ni->mft_no);
894 		goto err_out;
895 	}
896 
897 	goto descend_into_child_node;
898 err_out:
899 	if (icx->actx) {
900 		ntfs_attr_put_search_ctx(icx->actx);
901 		icx->actx = NULL;
902 	}
903 	kvfree(ib);
904 	if (!err)
905 		err = -EIO;
906 	return err;
907 done:
908 	icx->entry = ie;
909 	icx->data = (u8 *)ie + offsetof(struct index_entry, key);
910 	icx->data_len = le16_to_cpu(ie->key_length);
911 	ntfs_debug("Done.\n");
912 	return err;
913 
914 }
915 
ntfs_ib_alloc(s64 ib_vcn,u32 ib_size,u8 node_type)916 static struct index_block *ntfs_ib_alloc(s64 ib_vcn, u32 ib_size,
917 		u8 node_type)
918 {
919 	struct index_block *ib;
920 	int ih_size = sizeof(struct index_header);
921 
922 	ntfs_debug("Entering ib_vcn = %lld ib_size = %u\n", ib_vcn, ib_size);
923 
924 	ib = kvzalloc(ib_size, GFP_NOFS);
925 	if (!ib)
926 		return NULL;
927 
928 	ib->magic = magic_INDX;
929 	ib->usa_ofs = cpu_to_le16(sizeof(struct index_block));
930 	ib->usa_count = cpu_to_le16(ib_size / NTFS_BLOCK_SIZE + 1);
931 	/* Set USN to 1 */
932 	*(__le16 *)((char *)ib + le16_to_cpu(ib->usa_ofs)) = cpu_to_le16(1);
933 	ib->lsn = 0;
934 	ib->index_block_vcn = cpu_to_le64(ib_vcn);
935 	ib->index.entries_offset = cpu_to_le32((ih_size +
936 				le16_to_cpu(ib->usa_count) * 2 + 7) & ~7);
937 	ib->index.index_length = 0;
938 	ib->index.allocated_size = cpu_to_le32(ib_size -
939 			(sizeof(struct index_block) - ih_size));
940 	ib->index.flags = node_type;
941 
942 	return ib;
943 }
944 
945 /*
946  *  Find the median by going through all the entries
947  */
ntfs_ie_get_median(struct index_header * ih)948 static struct index_entry *ntfs_ie_get_median(struct index_header *ih)
949 {
950 	struct index_entry *ie, *ie_start;
951 	u8 *ie_end;
952 	int i = 0, median;
953 
954 	ntfs_debug("Entering\n");
955 
956 	ie = ie_start = ntfs_ie_get_first(ih);
957 	ie_end = (u8 *)ntfs_ie_get_end(ih);
958 
959 	while ((u8 *)ie < ie_end && !ntfs_ie_end(ie)) {
960 		ie = ntfs_ie_get_next(ie);
961 		i++;
962 	}
963 	/*
964 	 * NOTE: this could be also the entry at the half of the index block.
965 	 */
966 	median = i / 2 - 1;
967 
968 	ntfs_debug("Entries: %d  median: %d\n", i, median);
969 
970 	for (i = 0, ie = ie_start; i <= median; i++)
971 		ie = ntfs_ie_get_next(ie);
972 
973 	return ie;
974 }
975 
ntfs_ibm_vcn_to_pos(struct ntfs_index_context * icx,s64 vcn)976 static u64 ntfs_ibm_vcn_to_pos(struct ntfs_index_context *icx, s64 vcn)
977 {
978 	u64 pos = ntfs_ib_vcn_to_pos(icx, vcn);
979 
980 	do_div(pos, icx->block_size);
981 	return pos;
982 }
983 
ntfs_ibm_pos_to_vcn(struct ntfs_index_context * icx,s64 pos)984 static s64 ntfs_ibm_pos_to_vcn(struct ntfs_index_context *icx, s64 pos)
985 {
986 	return ntfs_ib_pos_to_vcn(icx, pos * icx->block_size);
987 }
988 
ntfs_ibm_add(struct ntfs_index_context * icx)989 static int ntfs_ibm_add(struct ntfs_index_context *icx)
990 {
991 	u8 bmp[8];
992 
993 	ntfs_debug("Entering\n");
994 
995 	if (ntfs_attr_exist(icx->idx_ni, AT_BITMAP, icx->name, icx->name_len))
996 		return 0;
997 	/*
998 	 * AT_BITMAP must be at least 8 bytes.
999 	 */
1000 	memset(bmp, 0, sizeof(bmp));
1001 	if (ntfs_attr_add(icx->idx_ni, AT_BITMAP, icx->name, icx->name_len,
1002 				bmp, sizeof(bmp))) {
1003 		ntfs_error(icx->idx_ni->vol->sb, "Failed to add AT_BITMAP");
1004 		return -EINVAL;
1005 	}
1006 
1007 	return 0;
1008 }
1009 
ntfs_ibm_modify(struct ntfs_index_context * icx,s64 vcn,int set)1010 static int ntfs_ibm_modify(struct ntfs_index_context *icx, s64 vcn, int set)
1011 {
1012 	u8 byte;
1013 	u64 pos = ntfs_ibm_vcn_to_pos(icx, vcn);
1014 	u32 bpos = pos / 8;
1015 	u32 bit = 1 << (pos % 8);
1016 	struct ntfs_inode *bmp_ni;
1017 	struct inode *bmp_vi;
1018 	int ret = 0;
1019 
1020 	ntfs_debug("%s vcn: %lld\n", set ? "set" : "clear", vcn);
1021 
1022 	bmp_vi = ntfs_attr_iget(VFS_I(icx->idx_ni), AT_BITMAP, icx->name, icx->name_len);
1023 	if (IS_ERR(bmp_vi)) {
1024 		ntfs_error(icx->idx_ni->vol->sb, "Failed to open $BITMAP attribute");
1025 		return PTR_ERR(bmp_vi);
1026 	}
1027 
1028 	bmp_ni = NTFS_I(bmp_vi);
1029 
1030 	if (set) {
1031 		if (bmp_ni->data_size < bpos + 1) {
1032 			ret = ntfs_attr_truncate(bmp_ni, (bmp_ni->data_size + 8) & ~7);
1033 			if (ret) {
1034 				ntfs_error(icx->idx_ni->vol->sb, "Failed to truncate AT_BITMAP");
1035 				goto err;
1036 			}
1037 			i_size_write(bmp_vi, (loff_t)bmp_ni->data_size);
1038 		}
1039 	}
1040 
1041 	if (ntfs_inode_attr_pread(bmp_vi, bpos, 1, &byte) != 1) {
1042 		ret = -EIO;
1043 		ntfs_error(icx->idx_ni->vol->sb, "Failed to read $BITMAP");
1044 		goto err;
1045 	}
1046 
1047 	if (set)
1048 		byte |= bit;
1049 	else
1050 		byte &= ~bit;
1051 
1052 	if (ntfs_inode_attr_pwrite(bmp_vi, bpos, 1, &byte, false) != 1) {
1053 		ret = -EIO;
1054 		ntfs_error(icx->idx_ni->vol->sb, "Failed to write $Bitmap");
1055 		goto err;
1056 	}
1057 
1058 err:
1059 	iput(bmp_vi);
1060 	return ret;
1061 }
1062 
ntfs_ibm_set(struct ntfs_index_context * icx,s64 vcn)1063 static int ntfs_ibm_set(struct ntfs_index_context *icx, s64 vcn)
1064 {
1065 	return ntfs_ibm_modify(icx, vcn, 1);
1066 }
1067 
ntfs_ibm_clear(struct ntfs_index_context * icx,s64 vcn)1068 static int ntfs_ibm_clear(struct ntfs_index_context *icx, s64 vcn)
1069 {
1070 	return ntfs_ibm_modify(icx, vcn, 0);
1071 }
1072 
ntfs_ibm_get_free(struct ntfs_index_context * icx)1073 static s64 ntfs_ibm_get_free(struct ntfs_index_context *icx)
1074 {
1075 	u8 *bm;
1076 	int bit;
1077 	s64 vcn, byte, size;
1078 
1079 	ntfs_debug("Entering\n");
1080 
1081 	bm = ntfs_attr_readall(icx->idx_ni, AT_BITMAP,  icx->name, icx->name_len,
1082 			&size);
1083 	if (!bm)
1084 		return (s64)-1;
1085 
1086 	for (byte = 0; byte < size; byte++) {
1087 		if (bm[byte] == 255)
1088 			continue;
1089 
1090 		for (bit = 0; bit < 8; bit++) {
1091 			if (!(bm[byte] & (1 << bit))) {
1092 				vcn = ntfs_ibm_pos_to_vcn(icx, byte * 8 + bit);
1093 				goto out;
1094 			}
1095 		}
1096 	}
1097 
1098 	vcn = ntfs_ibm_pos_to_vcn(icx, size * 8);
1099 out:
1100 	ntfs_debug("allocated vcn: %lld\n", vcn);
1101 
1102 	if (ntfs_ibm_set(icx, vcn))
1103 		vcn = (s64)-1;
1104 
1105 	kvfree(bm);
1106 	return vcn;
1107 }
1108 
ntfs_ir_to_ib(struct index_root * ir,s64 ib_vcn)1109 static struct index_block *ntfs_ir_to_ib(struct index_root *ir, s64 ib_vcn)
1110 {
1111 	struct index_block *ib;
1112 	struct index_entry *ie_last;
1113 	char *ies_start, *ies_end;
1114 	int i;
1115 
1116 	ntfs_debug("Entering\n");
1117 
1118 	ib = ntfs_ib_alloc(ib_vcn, le32_to_cpu(ir->index_block_size), LEAF_NODE);
1119 	if (!ib)
1120 		return NULL;
1121 
1122 	ies_start = (char *)ntfs_ie_get_first(&ir->index);
1123 	ies_end   = (char *)ntfs_ie_get_end(&ir->index);
1124 	ie_last   = ntfs_ie_get_last((struct index_entry *)ies_start, ies_end);
1125 	/*
1126 	 * Copy all entries, including the termination entry
1127 	 * as well, which can never have any data.
1128 	 */
1129 	i = (char *)ie_last - ies_start + le16_to_cpu(ie_last->length);
1130 	memcpy(ntfs_ie_get_first(&ib->index), ies_start, i);
1131 
1132 	ib->index.flags = ir->index.flags;
1133 	ib->index.index_length = cpu_to_le32(i +
1134 			le32_to_cpu(ib->index.entries_offset));
1135 	return ib;
1136 }
1137 
ntfs_ir_nill(struct index_root * ir)1138 static void ntfs_ir_nill(struct index_root *ir)
1139 {
1140 	struct index_entry *ie_last;
1141 	char *ies_start, *ies_end;
1142 
1143 	ntfs_debug("Entering\n");
1144 
1145 	ies_start = (char *)ntfs_ie_get_first(&ir->index);
1146 	ies_end   = (char *)ntfs_ie_get_end(&ir->index);
1147 	ie_last   = ntfs_ie_get_last((struct index_entry *)ies_start, ies_end);
1148 	/*
1149 	 * Move the index root termination entry forward
1150 	 */
1151 	if ((char *)ie_last > ies_start) {
1152 		memmove((char *)ntfs_ie_get_first(&ir->index),
1153 			(char *)ie_last, le16_to_cpu(ie_last->length));
1154 		ie_last = (struct index_entry *)ies_start;
1155 	}
1156 }
1157 
ntfs_ib_copy_tail(struct ntfs_index_context * icx,struct index_block * src,struct index_entry * median,s64 new_vcn)1158 static int ntfs_ib_copy_tail(struct ntfs_index_context *icx, struct index_block *src,
1159 		struct index_entry *median, s64 new_vcn)
1160 {
1161 	u8 *ies_end;
1162 	struct index_entry *ie_head;		/* first entry after the median */
1163 	int tail_size, ret;
1164 	struct index_block *dst;
1165 
1166 	ntfs_debug("Entering\n");
1167 
1168 	dst = ntfs_ib_alloc(new_vcn, icx->block_size,
1169 			src->index.flags & NODE_MASK);
1170 	if (!dst)
1171 		return -ENOMEM;
1172 
1173 	ie_head = ntfs_ie_get_next(median);
1174 
1175 	ies_end = (u8 *)ntfs_ie_get_end(&src->index);
1176 	tail_size = ies_end - (u8 *)ie_head;
1177 	memcpy(ntfs_ie_get_first(&dst->index), ie_head, tail_size);
1178 
1179 	dst->index.index_length = cpu_to_le32(tail_size +
1180 			le32_to_cpu(dst->index.entries_offset));
1181 	ret = ntfs_ib_write(icx, dst);
1182 
1183 	kvfree(dst);
1184 	return ret;
1185 }
1186 
ntfs_ib_cut_tail(struct ntfs_index_context * icx,struct index_block * ib,struct index_entry * ie)1187 static int ntfs_ib_cut_tail(struct ntfs_index_context *icx, struct index_block *ib,
1188 		struct index_entry *ie)
1189 {
1190 	char *ies_start, *ies_end;
1191 	struct index_entry *ie_last;
1192 	int ret;
1193 
1194 	ntfs_debug("Entering\n");
1195 
1196 	ies_start = (char *)ntfs_ie_get_first(&ib->index);
1197 	ies_end   = (char *)ntfs_ie_get_end(&ib->index);
1198 
1199 	ie_last   = ntfs_ie_get_last((struct index_entry *)ies_start, ies_end);
1200 	if (ie_last->flags & INDEX_ENTRY_NODE)
1201 		ntfs_ie_set_vcn(ie_last, ntfs_ie_get_vcn(ie));
1202 
1203 	unsafe_memcpy(ie, ie_last, le16_to_cpu(ie_last->length),
1204 			/* alloc is larger than ie_last->length, see ntfs_ie_get_last() */);
1205 
1206 	ib->index.index_length = cpu_to_le32(((char *)ie - ies_start) +
1207 			le16_to_cpu(ie->length) + le32_to_cpu(ib->index.entries_offset));
1208 
1209 	ret = ntfs_ib_write(icx, ib);
1210 	return ret;
1211 }
1212 
ntfs_ia_add(struct ntfs_index_context * icx)1213 static int ntfs_ia_add(struct ntfs_index_context *icx)
1214 {
1215 	int ret;
1216 
1217 	ntfs_debug("Entering\n");
1218 
1219 	ret = ntfs_ibm_add(icx);
1220 	if (ret)
1221 		return ret;
1222 
1223 	if (!ntfs_attr_exist(icx->idx_ni, AT_INDEX_ALLOCATION, icx->name, icx->name_len)) {
1224 		ret = ntfs_attr_add(icx->idx_ni, AT_INDEX_ALLOCATION, icx->name,
1225 					icx->name_len, NULL, 0);
1226 		if (ret) {
1227 			ntfs_error(icx->idx_ni->vol->sb, "Failed to add AT_INDEX_ALLOCATION");
1228 			return ret;
1229 		}
1230 	}
1231 
1232 	icx->ia_ni = ntfs_ia_open(icx, icx->idx_ni);
1233 	if (!icx->ia_ni)
1234 		return -ENOENT;
1235 
1236 	return 0;
1237 }
1238 
ntfs_ir_reparent(struct ntfs_index_context * icx)1239 static int ntfs_ir_reparent(struct ntfs_index_context *icx)
1240 {
1241 	struct ntfs_attr_search_ctx *ctx = NULL;
1242 	struct index_root *ir;
1243 	struct index_entry *ie;
1244 	struct index_block *ib = NULL;
1245 	s64 new_ib_vcn;
1246 	u32 index_length;
1247 	u32 old_value_length;
1248 	int ix_root_size;
1249 	int ret = 0;
1250 
1251 	ntfs_debug("Entering\n");
1252 
1253 	ir = ntfs_ir_lookup2(icx->idx_ni, icx->name, icx->name_len);
1254 	if (!ir) {
1255 		ret = -ENOENT;
1256 		goto out;
1257 	}
1258 
1259 	if ((ir->index.flags & NODE_MASK) == SMALL_INDEX) {
1260 		ret = ntfs_ia_add(icx);
1261 		if (ret)
1262 			goto out;
1263 	}
1264 
1265 	new_ib_vcn = ntfs_ibm_get_free(icx);
1266 	if (new_ib_vcn < 0) {
1267 		ret = -EINVAL;
1268 		goto out;
1269 	}
1270 
1271 	ir = ntfs_ir_lookup2(icx->idx_ni, icx->name, icx->name_len);
1272 	if (!ir) {
1273 		ret = -ENOENT;
1274 		goto clear_bmp;
1275 	}
1276 
1277 	ib = ntfs_ir_to_ib(ir, new_ib_vcn);
1278 	if (ib == NULL) {
1279 		ret = -EIO;
1280 		ntfs_error(icx->idx_ni->vol->sb, "Failed to move index root to index block");
1281 		goto clear_bmp;
1282 	}
1283 
1284 	ret = ntfs_ib_write(icx, ib);
1285 	if (ret)
1286 		goto clear_bmp;
1287 
1288 retry:
1289 	ir = ntfs_ir_lookup(icx->idx_ni, icx->name, icx->name_len, &ctx);
1290 	if (!ir) {
1291 		ret = -ENOENT;
1292 		goto clear_bmp;
1293 	}
1294 
1295 	old_value_length = le32_to_cpu(ctx->attr->data.resident.value_length);
1296 	index_length = le32_to_cpu(ir->index.entries_offset) +
1297 		sizeof(struct index_entry_header) + sizeof(s64);
1298 	ix_root_size = offsetof(struct index_root, index) + index_length;
1299 	/* Grow the resident value before publishing the larger root header. */
1300 	if (ix_root_size > old_value_length) {
1301 		ret = ntfs_resident_attr_value_resize(ctx->mrec, ctx->attr, ix_root_size);
1302 		if (ret)
1303 			goto resize_failed;
1304 
1305 		icx->idx_ni->data_size = ix_root_size;
1306 		icx->idx_ni->initialized_size = ix_root_size;
1307 		icx->idx_ni->allocated_size = (ix_root_size + 7) & ~7;
1308 	}
1309 
1310 	ntfs_ir_nill(ir);
1311 
1312 	ie = ntfs_ie_get_first(&ir->index);
1313 	ie->flags |= INDEX_ENTRY_NODE;
1314 	ie->length = cpu_to_le16(sizeof(struct index_entry_header) + sizeof(s64));
1315 
1316 	ir->index.flags = LARGE_INDEX;
1317 	NInoSetIndexAllocPresent(icx->idx_ni);
1318 	ir->index.index_length = cpu_to_le32(index_length);
1319 	ir->index.allocated_size = ir->index.index_length;
1320 
1321 	if (ix_root_size <= old_value_length) {
1322 		ret = ntfs_resident_attr_value_resize(ctx->mrec, ctx->attr, ix_root_size);
1323 		if (ret)
1324 			goto resize_failed;
1325 
1326 		icx->idx_ni->data_size = ix_root_size;
1327 		icx->idx_ni->initialized_size = ix_root_size;
1328 		icx->idx_ni->allocated_size = (ix_root_size + 7) & ~7;
1329 	}
1330 	ntfs_ie_set_vcn(ie, new_ib_vcn);
1331 	goto err_out;
1332 
1333 resize_failed:
1334 	/*
1335 	 * When there is no space to build a non-resident
1336 	 * index, we may have to move the root to an extent
1337 	 */
1338 	if ((ret == -ENOSPC) && (ctx->al_entry || !ntfs_inode_add_attrlist(icx->idx_ni))) {
1339 		ntfs_attr_put_search_ctx(ctx);
1340 		ctx = NULL;
1341 		ir = ntfs_ir_lookup(icx->idx_ni, icx->name, icx->name_len, &ctx);
1342 		if (ir && !ntfs_attr_record_move_away(ctx, ix_root_size -
1343 				le32_to_cpu(ctx->attr->data.resident.value_length))) {
1344 			if (ntfs_attrlist_update(ctx->base_ntfs_ino ?
1345 						 ctx->base_ntfs_ino : ctx->ntfs_ino))
1346 				goto clear_bmp;
1347 			ntfs_attr_put_search_ctx(ctx);
1348 			ctx = NULL;
1349 			goto retry;
1350 		}
1351 	}
1352 clear_bmp:
1353 	ntfs_ibm_clear(icx, new_ib_vcn);
1354 	goto err_out;
1355 err_out:
1356 	kvfree(ib);
1357 	if (ctx)
1358 		ntfs_attr_put_search_ctx(ctx);
1359 out:
1360 	return ret;
1361 }
1362 
1363 /*
1364  * ntfs_ir_truncate - Truncate index root attribute
1365  * @icx: index context
1366  * @data_size: new data size for the index root
1367  */
ntfs_ir_truncate(struct ntfs_index_context * icx,int data_size)1368 static int ntfs_ir_truncate(struct ntfs_index_context *icx, int data_size)
1369 {
1370 	int ret;
1371 	u32 old_allocated_size;
1372 	bool shrink;
1373 
1374 	ntfs_debug("Entering\n");
1375 
1376 	old_allocated_size = le32_to_cpu(icx->ir->index.allocated_size);
1377 	shrink = data_size < old_allocated_size;
1378 	if (shrink)
1379 		icx->ir->index.allocated_size = cpu_to_le32(data_size);
1380 
1381 	/*
1382 	 *  INDEX_ROOT must be resident and its entries can be moved to
1383 	 *  struct index_block, so ENOSPC isn't a real error.
1384 	 */
1385 	ret = ntfs_attr_truncate(icx->idx_ni, data_size + offsetof(struct index_root, index));
1386 	if (!ret) {
1387 		i_size_write(VFS_I(icx->idx_ni), icx->idx_ni->initialized_size);
1388 		icx->ir = ntfs_ir_lookup2(icx->idx_ni, icx->name, icx->name_len);
1389 		if (!icx->ir)
1390 			return -ENOENT;
1391 
1392 		if (!shrink)
1393 			icx->ir->index.allocated_size = cpu_to_le32(data_size);
1394 	} else {
1395 		if (shrink)
1396 			icx->ir->index.allocated_size = cpu_to_le32(old_allocated_size);
1397 		if (ret != -ENOSPC)
1398 			ntfs_error(icx->idx_ni->vol->sb, "Failed to truncate INDEX_ROOT");
1399 	}
1400 
1401 	return ret;
1402 }
1403 
1404 /*
1405  * ntfs_ir_make_space - Make more space for the index root attribute
1406  * @icx: index context
1407  * @data_size: required data size for the index root
1408  */
ntfs_ir_make_space(struct ntfs_index_context * icx,int data_size)1409 static int ntfs_ir_make_space(struct ntfs_index_context *icx, int data_size)
1410 {
1411 	int ret;
1412 
1413 	ntfs_debug("Entering\n");
1414 
1415 	ret = ntfs_ir_truncate(icx, data_size);
1416 	if (ret == -ENOSPC) {
1417 		ret = ntfs_ir_reparent(icx);
1418 		if (!ret)
1419 			ret = -EAGAIN;
1420 		else
1421 			ntfs_error(icx->idx_ni->vol->sb, "Failed to modify INDEX_ROOT");
1422 	}
1423 
1424 	return ret;
1425 }
1426 
1427 /*
1428  * NOTE: 'ie' must be a copy of a real index entry.
1429  */
ntfs_ie_add_vcn(struct index_entry ** ie)1430 static int ntfs_ie_add_vcn(struct index_entry **ie)
1431 {
1432 	struct index_entry *p, *old = *ie;
1433 
1434 	old->length = cpu_to_le16(le16_to_cpu(old->length) + sizeof(s64));
1435 	p = krealloc(old, le16_to_cpu(old->length), GFP_NOFS);
1436 	if (!p)
1437 		return -ENOMEM;
1438 
1439 	p->flags |= INDEX_ENTRY_NODE;
1440 	*ie = p;
1441 	return 0;
1442 }
1443 
ntfs_ih_insert(struct index_header * ih,struct index_entry * orig_ie,s64 new_vcn,int pos)1444 static int ntfs_ih_insert(struct index_header *ih, struct index_entry *orig_ie, s64 new_vcn,
1445 		int pos)
1446 {
1447 	struct index_entry *ie_node, *ie;
1448 	int ret = 0;
1449 	s64 old_vcn;
1450 
1451 	ntfs_debug("Entering\n");
1452 	ie = ntfs_ie_dup(orig_ie);
1453 	if (!ie)
1454 		return -ENOMEM;
1455 
1456 	if (!(ie->flags & INDEX_ENTRY_NODE)) {
1457 		ret = ntfs_ie_add_vcn(&ie);
1458 		if (ret)
1459 			goto out;
1460 	}
1461 
1462 	ie_node = ntfs_ie_get_by_pos(ih, pos);
1463 	old_vcn = ntfs_ie_get_vcn(ie_node);
1464 	ntfs_ie_set_vcn(ie_node, new_vcn);
1465 
1466 	ntfs_ie_insert(ih, ie, ie_node);
1467 	ntfs_ie_set_vcn(ie_node, old_vcn);
1468 out:
1469 	kfree(ie);
1470 	return ret;
1471 }
1472 
ntfs_icx_parent_vcn(struct ntfs_index_context * icx)1473 static s64 ntfs_icx_parent_vcn(struct ntfs_index_context *icx)
1474 {
1475 	return icx->parent_vcn[icx->pindex];
1476 }
1477 
ntfs_icx_parent_pos(struct ntfs_index_context * icx)1478 static s64 ntfs_icx_parent_pos(struct ntfs_index_context *icx)
1479 {
1480 	return icx->parent_pos[icx->pindex];
1481 }
1482 
ntfs_ir_insert_median(struct ntfs_index_context * icx,struct index_entry * median,s64 new_vcn)1483 static int ntfs_ir_insert_median(struct ntfs_index_context *icx, struct index_entry *median,
1484 		s64 new_vcn)
1485 {
1486 	u32 new_size;
1487 	int ret;
1488 
1489 	ntfs_debug("Entering\n");
1490 
1491 	icx->ir = ntfs_ir_lookup2(icx->idx_ni, icx->name, icx->name_len);
1492 	if (!icx->ir)
1493 		return -ENOENT;
1494 
1495 	new_size = le32_to_cpu(icx->ir->index.index_length) +
1496 		le16_to_cpu(median->length);
1497 	if (!(median->flags & INDEX_ENTRY_NODE))
1498 		new_size += sizeof(s64);
1499 
1500 	ret = ntfs_ir_make_space(icx, new_size);
1501 	if (ret)
1502 		return ret;
1503 
1504 	icx->ir = ntfs_ir_lookup2(icx->idx_ni, icx->name, icx->name_len);
1505 	if (!icx->ir)
1506 		return -ENOENT;
1507 
1508 	return ntfs_ih_insert(&icx->ir->index, median, new_vcn,
1509 			ntfs_icx_parent_pos(icx));
1510 }
1511 
1512 static int ntfs_ib_split(struct ntfs_index_context *icx, struct index_block *ib);
1513 
1514 struct split_info {
1515 	struct list_head entry;
1516 	s64 new_vcn;
1517 	struct index_block *ib;
1518 };
1519 
ntfs_ib_insert(struct ntfs_index_context * icx,struct index_entry * ie,s64 new_vcn,struct split_info * si)1520 static int ntfs_ib_insert(struct ntfs_index_context *icx, struct index_entry *ie, s64 new_vcn,
1521 		struct split_info *si)
1522 {
1523 	struct index_block *ib;
1524 	u32 idx_size, allocated_size;
1525 	int err;
1526 	s64 old_vcn;
1527 
1528 	ntfs_debug("Entering\n");
1529 
1530 	ib = kvzalloc(icx->block_size, GFP_NOFS);
1531 	if (!ib)
1532 		return -ENOMEM;
1533 
1534 	old_vcn = ntfs_icx_parent_vcn(icx);
1535 
1536 	err = ntfs_ib_read(icx, old_vcn, ib);
1537 	if (err)
1538 		goto err_out;
1539 
1540 	idx_size = le32_to_cpu(ib->index.index_length);
1541 	allocated_size = le32_to_cpu(ib->index.allocated_size);
1542 	if (idx_size + le16_to_cpu(ie->length) + sizeof(s64) > allocated_size) {
1543 		si->ib = ib;
1544 		si->new_vcn = new_vcn;
1545 		return -EAGAIN;
1546 	}
1547 
1548 	err = ntfs_ih_insert(&ib->index, ie, new_vcn, ntfs_icx_parent_pos(icx));
1549 	if (err)
1550 		goto err_out;
1551 
1552 	err = ntfs_ib_write(icx, ib);
1553 
1554 err_out:
1555 	kvfree(ib);
1556 	return err;
1557 }
1558 
1559 /*
1560  * ntfs_ib_split - Split an index block
1561  * @icx: index context
1562  * @ib: index block to split
1563  */
ntfs_ib_split(struct ntfs_index_context * icx,struct index_block * ib)1564 static int ntfs_ib_split(struct ntfs_index_context *icx, struct index_block *ib)
1565 {
1566 	struct index_entry *median;
1567 	s64 new_vcn;
1568 	int ret;
1569 	struct split_info *si;
1570 	LIST_HEAD(ntfs_cut_tail_list);
1571 
1572 	ntfs_debug("Entering\n");
1573 
1574 resplit:
1575 	ret = ntfs_icx_parent_dec(icx);
1576 	if (ret)
1577 		goto out;
1578 
1579 	median  = ntfs_ie_get_median(&ib->index);
1580 	new_vcn = ntfs_ibm_get_free(icx);
1581 	if (new_vcn < 0) {
1582 		ret = -EINVAL;
1583 		goto out;
1584 	}
1585 
1586 	ret = ntfs_ib_copy_tail(icx, ib, median, new_vcn);
1587 	if (ret) {
1588 		ntfs_ibm_clear(icx, new_vcn);
1589 		goto out;
1590 	}
1591 
1592 	if (ntfs_icx_parent_vcn(icx) == VCN_INDEX_ROOT_PARENT) {
1593 		ret = ntfs_ir_insert_median(icx, median, new_vcn);
1594 		if (ret) {
1595 			ntfs_ibm_clear(icx, new_vcn);
1596 			goto out;
1597 		}
1598 	} else {
1599 		si = kzalloc(sizeof(struct split_info), GFP_NOFS);
1600 		if (!si) {
1601 			ntfs_ibm_clear(icx, new_vcn);
1602 			ret = -ENOMEM;
1603 			goto out;
1604 		}
1605 
1606 		ret = ntfs_ib_insert(icx, median, new_vcn, si);
1607 		if (ret == -EAGAIN) {
1608 			list_add_tail(&si->entry, &ntfs_cut_tail_list);
1609 			ib = si->ib;
1610 			goto resplit;
1611 		} else if (ret) {
1612 			kvfree(si->ib);
1613 			kfree(si);
1614 			ntfs_ibm_clear(icx, new_vcn);
1615 			goto out;
1616 		}
1617 		kfree(si);
1618 	}
1619 
1620 	ret = ntfs_ib_cut_tail(icx, ib, median);
1621 
1622 out:
1623 	while (!list_empty(&ntfs_cut_tail_list)) {
1624 		si = list_last_entry(&ntfs_cut_tail_list, struct split_info, entry);
1625 		ntfs_ibm_clear(icx, si->new_vcn);
1626 		kvfree(si->ib);
1627 		list_del(&si->entry);
1628 		kfree(si);
1629 		if (!ret)
1630 			ret = -EAGAIN;
1631 	}
1632 
1633 	return ret;
1634 }
1635 
ntfs_ie_add(struct ntfs_index_context * icx,struct index_entry * ie)1636 int ntfs_ie_add(struct ntfs_index_context *icx, struct index_entry *ie)
1637 {
1638 	struct index_header *ih;
1639 	int allocated_size, new_size;
1640 	int ret;
1641 
1642 	while (1) {
1643 		ret = ntfs_index_lookup(&ie->key, le16_to_cpu(ie->key_length), icx);
1644 		if (!ret) {
1645 			ret = -EEXIST;
1646 			ntfs_error(icx->idx_ni->vol->sb, "Index already have such entry");
1647 			goto err_out;
1648 		}
1649 		if (ret != -ENOENT) {
1650 			ntfs_error(icx->idx_ni->vol->sb, "Failed to find place for new entry");
1651 			goto err_out;
1652 		}
1653 		ret = 0;
1654 
1655 		if (icx->is_in_root)
1656 			ih = &icx->ir->index;
1657 		else
1658 			ih = &icx->ib->index;
1659 
1660 		allocated_size = le32_to_cpu(ih->allocated_size);
1661 		new_size = le32_to_cpu(ih->index_length) + le16_to_cpu(ie->length);
1662 
1663 		if (new_size <= allocated_size)
1664 			break;
1665 
1666 		ntfs_debug("index block sizes: allocated: %d  needed: %d\n",
1667 				allocated_size, new_size);
1668 
1669 		if (icx->is_in_root)
1670 			ret = ntfs_ir_make_space(icx, new_size);
1671 		else
1672 			ret = ntfs_ib_split(icx, icx->ib);
1673 		if (ret && ret != -EAGAIN)
1674 			goto err_out;
1675 
1676 		mark_mft_record_dirty(icx->actx->ntfs_ino);
1677 		ntfs_index_ctx_reinit(icx);
1678 	}
1679 
1680 	ntfs_ie_insert(ih, ie, icx->entry);
1681 	ntfs_index_entry_mark_dirty(icx);
1682 
1683 err_out:
1684 	ntfs_debug("%s\n", ret ? "Failed" : "Done");
1685 	return ret;
1686 }
1687 
1688 /*
1689  * ntfs_index_add_filename - add filename to directory index
1690  * @ni:		ntfs inode describing directory to which index add filename
1691  * @fn:		FILE_NAME attribute to add
1692  * @mref:	reference of the inode which @fn describes
1693  */
ntfs_index_add_filename(struct ntfs_inode * ni,struct file_name_attr * fn,u64 mref)1694 int ntfs_index_add_filename(struct ntfs_inode *ni, struct file_name_attr *fn, u64 mref)
1695 {
1696 	struct index_entry *ie;
1697 	struct ntfs_index_context *icx;
1698 	int fn_size, ie_size, err;
1699 
1700 	ntfs_debug("Entering\n");
1701 
1702 	if (!ni || !fn)
1703 		return -EINVAL;
1704 
1705 	fn_size = (fn->file_name_length * sizeof(__le16)) +
1706 		sizeof(struct file_name_attr);
1707 	ie_size = (sizeof(struct index_entry_header) + fn_size + 7) & ~7;
1708 
1709 	ie = kzalloc(ie_size, GFP_NOFS);
1710 	if (!ie)
1711 		return -ENOMEM;
1712 
1713 	ie->data.dir.indexed_file = cpu_to_le64(mref);
1714 	ie->length	 = cpu_to_le16(ie_size);
1715 	ie->key_length	 = cpu_to_le16(fn_size);
1716 
1717 	unsafe_memcpy(&ie->key, fn, fn_size,
1718 		      /* "fn_size" was correctly calculated above */);
1719 
1720 	icx = ntfs_index_ctx_get(ni, I30, 4);
1721 	if (!icx) {
1722 		err = -ENOMEM;
1723 		goto out;
1724 	}
1725 
1726 	err = ntfs_ie_add(icx, ie);
1727 	ntfs_index_ctx_put(icx);
1728 out:
1729 	kfree(ie);
1730 	return err;
1731 }
1732 
ntfs_ih_takeout(struct ntfs_index_context * icx,struct index_header * ih,struct index_entry * ie,struct index_block * ib)1733 static int ntfs_ih_takeout(struct ntfs_index_context *icx, struct index_header *ih,
1734 		struct index_entry *ie, struct index_block *ib)
1735 {
1736 	struct index_entry *ie_roam;
1737 	int freed_space;
1738 	bool full;
1739 	int ret = 0;
1740 
1741 	ntfs_debug("Entering\n");
1742 
1743 	full = ih->index_length == ih->allocated_size;
1744 	ie_roam = ntfs_ie_dup_novcn(ie);
1745 	if (!ie_roam)
1746 		return -ENOMEM;
1747 
1748 	ntfs_ie_delete(ih, ie);
1749 
1750 	if (ntfs_icx_parent_vcn(icx) == VCN_INDEX_ROOT_PARENT) {
1751 		/*
1752 		 * Recover the space which may have been freed
1753 		 * while deleting an entry from root index
1754 		 */
1755 		freed_space = le32_to_cpu(ih->allocated_size) -
1756 			le32_to_cpu(ih->index_length);
1757 		if (full && (freed_space > 0) && !(freed_space & 7)) {
1758 			ntfs_ir_truncate(icx, le32_to_cpu(ih->index_length));
1759 			/* do nothing if truncation fails */
1760 		}
1761 
1762 		mark_mft_record_dirty(icx->actx->ntfs_ino);
1763 	} else {
1764 		ret = ntfs_ib_write(icx, ib);
1765 		if (ret)
1766 			goto out;
1767 	}
1768 
1769 	ntfs_index_ctx_reinit(icx);
1770 
1771 	ret = ntfs_ie_add(icx, ie_roam);
1772 out:
1773 	kfree(ie_roam);
1774 	return ret;
1775 }
1776 
1777 /*
1778  *  Used if an empty index block to be deleted has END entry as the parent
1779  *  in the INDEX_ROOT which is the only one there.
1780  */
ntfs_ir_leafify(struct ntfs_index_context * icx,struct index_header * ih)1781 static void ntfs_ir_leafify(struct ntfs_index_context *icx, struct index_header *ih)
1782 {
1783 	struct index_entry *ie;
1784 
1785 	ntfs_debug("Entering\n");
1786 
1787 	ie = ntfs_ie_get_first(ih);
1788 	ie->flags &= ~INDEX_ENTRY_NODE;
1789 	ie->length = cpu_to_le16(le16_to_cpu(ie->length) - sizeof(s64));
1790 
1791 	ih->index_length = cpu_to_le32(le32_to_cpu(ih->index_length) - sizeof(s64));
1792 	ih->flags &= ~LARGE_INDEX;
1793 	NInoClearIndexAllocPresent(icx->idx_ni);
1794 
1795 	/* Not fatal error */
1796 	ntfs_ir_truncate(icx, le32_to_cpu(ih->index_length));
1797 }
1798 
1799 /*
1800  *  Used if an empty index block to be deleted has END entry as the parent
1801  *  in the INDEX_ROOT which is not the only one there.
1802  */
ntfs_ih_reparent_end(struct ntfs_index_context * icx,struct index_header * ih,struct index_block * ib)1803 static int ntfs_ih_reparent_end(struct ntfs_index_context *icx, struct index_header *ih,
1804 		struct index_block *ib)
1805 {
1806 	struct index_entry *ie, *ie_prev;
1807 
1808 	ntfs_debug("Entering\n");
1809 
1810 	ie = ntfs_ie_get_by_pos(ih, ntfs_icx_parent_pos(icx));
1811 	ie_prev = ntfs_ie_prev(ih, ie);
1812 	if (!ie_prev)
1813 		return -EIO;
1814 	ntfs_ie_set_vcn(ie, ntfs_ie_get_vcn(ie_prev));
1815 
1816 	return ntfs_ih_takeout(icx, ih, ie_prev, ib);
1817 }
1818 
ntfs_index_rm_leaf(struct ntfs_index_context * icx)1819 static int ntfs_index_rm_leaf(struct ntfs_index_context *icx)
1820 {
1821 	struct index_block *ib = NULL;
1822 	struct index_header *parent_ih;
1823 	struct index_entry *ie;
1824 	int ret;
1825 
1826 	ntfs_debug("pindex: %d\n", icx->pindex);
1827 
1828 	ret = ntfs_icx_parent_dec(icx);
1829 	if (ret)
1830 		return ret;
1831 
1832 	ret = ntfs_ibm_clear(icx, icx->parent_vcn[icx->pindex + 1]);
1833 	if (ret)
1834 		return ret;
1835 
1836 	if (ntfs_icx_parent_vcn(icx) == VCN_INDEX_ROOT_PARENT)
1837 		parent_ih = &icx->ir->index;
1838 	else {
1839 		ib = kvzalloc(icx->block_size, GFP_NOFS);
1840 		if (!ib)
1841 			return -ENOMEM;
1842 
1843 		ret = ntfs_ib_read(icx, ntfs_icx_parent_vcn(icx), ib);
1844 		if (ret)
1845 			goto out;
1846 
1847 		parent_ih = &ib->index;
1848 	}
1849 
1850 	ie = ntfs_ie_get_by_pos(parent_ih, ntfs_icx_parent_pos(icx));
1851 	if (!ntfs_ie_end(ie)) {
1852 		ret = ntfs_ih_takeout(icx, parent_ih, ie, ib);
1853 		goto out;
1854 	}
1855 
1856 	if (ntfs_ih_zero_entry(parent_ih)) {
1857 		if (ntfs_icx_parent_vcn(icx) == VCN_INDEX_ROOT_PARENT) {
1858 			ntfs_ir_leafify(icx, parent_ih);
1859 			goto out;
1860 		}
1861 
1862 		ret = ntfs_index_rm_leaf(icx);
1863 		goto out;
1864 	}
1865 
1866 	ret = ntfs_ih_reparent_end(icx, parent_ih, ib);
1867 out:
1868 	kvfree(ib);
1869 	return ret;
1870 }
1871 
ntfs_index_rm_node(struct ntfs_index_context * icx)1872 static int ntfs_index_rm_node(struct ntfs_index_context *icx)
1873 {
1874 	int entry_pos, pindex;
1875 	s64 vcn;
1876 	struct index_block *ib = NULL;
1877 	struct index_entry *ie_succ, *ie, *entry = icx->entry;
1878 	struct index_header *ih;
1879 	u32 new_size;
1880 	int delta, ret;
1881 
1882 	ntfs_debug("Entering\n");
1883 
1884 	if (!icx->ia_ni) {
1885 		icx->ia_ni = ntfs_ia_open(icx, icx->idx_ni);
1886 		if (!icx->ia_ni)
1887 			return -EINVAL;
1888 	}
1889 
1890 	ib = kvzalloc(icx->block_size, GFP_NOFS);
1891 	if (!ib)
1892 		return -ENOMEM;
1893 
1894 	ie_succ = ntfs_ie_get_next(icx->entry);
1895 	entry_pos = icx->parent_pos[icx->pindex]++;
1896 	pindex = icx->pindex;
1897 descend:
1898 	vcn = ntfs_ie_get_vcn(ie_succ);
1899 	ret = ntfs_ib_read(icx, vcn, ib);
1900 	if (ret)
1901 		goto out;
1902 
1903 	ie_succ = ntfs_ie_get_first(&ib->index);
1904 
1905 	ret = ntfs_icx_parent_inc(icx);
1906 	if (ret)
1907 		goto out;
1908 
1909 	icx->parent_vcn[icx->pindex] = vcn;
1910 	icx->parent_pos[icx->pindex] = 0;
1911 
1912 	if ((ib->index.flags & NODE_MASK) == INDEX_NODE)
1913 		goto descend;
1914 
1915 	if (ntfs_ih_zero_entry(&ib->index)) {
1916 		ret = -EIO;
1917 		ntfs_error(icx->idx_ni->vol->sb, "Empty index block");
1918 		goto out;
1919 	}
1920 
1921 	ie = ntfs_ie_dup(ie_succ);
1922 	if (!ie) {
1923 		ret = -ENOMEM;
1924 		goto out;
1925 	}
1926 
1927 	ret = ntfs_ie_add_vcn(&ie);
1928 	if (ret)
1929 		goto out2;
1930 
1931 	ntfs_ie_set_vcn(ie, ntfs_ie_get_vcn(icx->entry));
1932 
1933 	if (icx->is_in_root)
1934 		ih = &icx->ir->index;
1935 	else
1936 		ih = &icx->ib->index;
1937 
1938 	delta = le16_to_cpu(ie->length) - le16_to_cpu(icx->entry->length);
1939 	new_size = le32_to_cpu(ih->index_length) + delta;
1940 	if (delta > 0) {
1941 		if (icx->is_in_root) {
1942 			ret = ntfs_ir_make_space(icx, new_size);
1943 			if (ret != 0)
1944 				goto out2;
1945 
1946 			ih = &icx->ir->index;
1947 			entry = ntfs_ie_get_by_pos(ih, entry_pos);
1948 
1949 		} else if (new_size > le32_to_cpu(ih->allocated_size)) {
1950 			icx->pindex = pindex;
1951 			ret = ntfs_ib_split(icx, icx->ib);
1952 			if (!ret)
1953 				ret = -EAGAIN;
1954 			goto out2;
1955 		}
1956 	}
1957 
1958 	ntfs_ie_delete(ih, entry);
1959 	ntfs_ie_insert(ih, ie, entry);
1960 
1961 	if (icx->is_in_root)
1962 		ret = ntfs_ir_truncate(icx, new_size);
1963 	else
1964 		ret = ntfs_icx_ib_write(icx);
1965 	if (ret)
1966 		goto out2;
1967 
1968 	ntfs_ie_delete(&ib->index, ie_succ);
1969 
1970 	if (ntfs_ih_zero_entry(&ib->index))
1971 		ret = ntfs_index_rm_leaf(icx);
1972 	else
1973 		ret = ntfs_ib_write(icx, ib);
1974 
1975 out2:
1976 	kfree(ie);
1977 out:
1978 	kvfree(ib);
1979 	return ret;
1980 }
1981 
1982 /*
1983  * ntfs_index_rm - remove entry from the index
1984  * @icx:	index context describing entry to delete
1985  *
1986  * Delete entry described by @icx from the index. Index context is always
1987  * reinitialized after use of this function, so it can be used for index
1988  * lookup once again.
1989  */
ntfs_index_rm(struct ntfs_index_context * icx)1990 int ntfs_index_rm(struct ntfs_index_context *icx)
1991 {
1992 	struct index_header *ih;
1993 	int ret = 0;
1994 
1995 	ntfs_debug("Entering\n");
1996 
1997 	if (!icx || (!icx->ib && !icx->ir) || ntfs_ie_end(icx->entry)) {
1998 		ret = -EINVAL;
1999 		goto err_out;
2000 	}
2001 	if (icx->is_in_root)
2002 		ih = &icx->ir->index;
2003 	else
2004 		ih = &icx->ib->index;
2005 
2006 	if (icx->entry->flags & INDEX_ENTRY_NODE) {
2007 		ret = ntfs_index_rm_node(icx);
2008 		if (ret)
2009 			goto err_out;
2010 	} else if (icx->is_in_root || !ntfs_ih_one_entry(ih)) {
2011 		ntfs_ie_delete(ih, icx->entry);
2012 
2013 		if (icx->is_in_root)
2014 			ret = ntfs_ir_truncate(icx, le32_to_cpu(ih->index_length));
2015 		else
2016 			ret = ntfs_icx_ib_write(icx);
2017 		if (ret)
2018 			goto err_out;
2019 	} else {
2020 		ret = ntfs_index_rm_leaf(icx);
2021 		if (ret)
2022 			goto err_out;
2023 	}
2024 
2025 	return 0;
2026 err_out:
2027 	return ret;
2028 }
2029 
ntfs_index_remove(struct ntfs_inode * dir_ni,const void * key,const u32 keylen)2030 int ntfs_index_remove(struct ntfs_inode *dir_ni, const void *key, const u32 keylen)
2031 {
2032 	int ret = 0;
2033 	struct ntfs_index_context *icx;
2034 
2035 	icx = ntfs_index_ctx_get(dir_ni, I30, 4);
2036 	if (!icx)
2037 		return -EINVAL;
2038 
2039 	while (1) {
2040 		ret = ntfs_index_lookup(key, keylen, icx);
2041 		if (ret)
2042 			goto err_out;
2043 
2044 		ret = ntfs_index_rm(icx);
2045 		if (ret && ret != -EAGAIN)
2046 			goto err_out;
2047 		else if (!ret)
2048 			break;
2049 
2050 		mark_mft_record_dirty(icx->actx->ntfs_ino);
2051 		ntfs_index_ctx_reinit(icx);
2052 	}
2053 
2054 	mark_mft_record_dirty(icx->actx->ntfs_ino);
2055 
2056 	ntfs_index_ctx_put(icx);
2057 	return 0;
2058 err_out:
2059 	ntfs_index_ctx_put(icx);
2060 	ntfs_error(dir_ni->vol->sb, "Delete failed");
2061 	return ret;
2062 }
2063 
2064 /*
2065  * ntfs_index_walk_down - walk down the index tree (leaf bound)
2066  * until there are no subnode in the first index entry returns
2067  * the entry at the bottom left in subnode
2068  */
ntfs_index_walk_down(struct index_entry * ie,struct ntfs_index_context * ictx)2069 struct index_entry *ntfs_index_walk_down(struct index_entry *ie, struct ntfs_index_context *ictx)
2070 {
2071 	struct index_entry *entry;
2072 	struct index_block *ib;
2073 	int err;
2074 	s64 vcn;
2075 
2076 	entry = ie;
2077 	do {
2078 		vcn = ntfs_ie_get_vcn(entry);
2079 		if (ictx->is_in_root) {
2080 			ib = kvzalloc(ictx->block_size, GFP_NOFS);
2081 			if (!ib)
2082 				return ERR_PTR(-ENOMEM);
2083 			/*
2084 			 * Descending from root index (level 0) to the first
2085 			 * child level. is_in_root == true implies pindex == 0,
2086 			 * so advance to level 1.
2087 			 */
2088 			ictx->pindex = 1;
2089 			ictx->ir = NULL;
2090 			ictx->ib = ib;
2091 			ictx->is_in_root = false;
2092 		} else {
2093 			/* down from non-zero level */
2094 			err = ntfs_icx_parent_inc(ictx);
2095 			if (err)
2096 				return ERR_PTR(err);
2097 		}
2098 
2099 		ictx->parent_pos[ictx->pindex] = 0;
2100 		ictx->parent_vcn[ictx->pindex] = vcn;
2101 		if (!ntfs_ib_read(ictx, vcn, ictx->ib)) {
2102 			ictx->entry = ntfs_ie_get_first(&ictx->ib->index);
2103 			entry = ictx->entry;
2104 		} else
2105 			entry = ERR_PTR(-EIO);
2106 	} while (!IS_ERR(entry) && (entry->flags & INDEX_ENTRY_NODE));
2107 
2108 	return entry;
2109 }
2110 
2111 /*
2112  * ntfs_index_walk_up - walk up the index tree (root bound) until
2113  * there is a valid data entry in parent returns the parent entry
2114  * or NULL if no more parent.
2115  * @ie: current index entry
2116  * @ictx: index context
2117  */
ntfs_index_walk_up(struct index_entry * ie,struct ntfs_index_context * ictx)2118 static struct index_entry *ntfs_index_walk_up(struct index_entry *ie,
2119 		struct ntfs_index_context *ictx)
2120 {
2121 	struct index_entry *entry = ie;
2122 	s64 vcn;
2123 
2124 	if (ictx->pindex <= 0)
2125 		return NULL;
2126 
2127 	do {
2128 		ictx->pindex--;
2129 		if (!ictx->pindex) {
2130 			/* we have reached the root */
2131 			kfree(ictx->ib);
2132 			ictx->ib = NULL;
2133 			ictx->is_in_root = true;
2134 			/* a new search context is to be allocated */
2135 			if (ictx->actx)
2136 				ntfs_attr_put_search_ctx(ictx->actx);
2137 			ictx->ir = ntfs_ir_lookup(ictx->idx_ni, ictx->name,
2138 						  ictx->name_len, &ictx->actx);
2139 			if (ictx->ir)
2140 				entry = ntfs_ie_get_by_pos(
2141 					&ictx->ir->index,
2142 					ictx->parent_pos[ictx->pindex]);
2143 			else
2144 				entry = NULL;
2145 		} else {
2146 			/* up into non-root node */
2147 			vcn = ictx->parent_vcn[ictx->pindex];
2148 			if (!ntfs_ib_read(ictx, vcn, ictx->ib)) {
2149 				entry = ntfs_ie_get_by_pos(
2150 					&ictx->ib->index,
2151 					ictx->parent_pos[ictx->pindex]);
2152 			} else
2153 				entry = NULL;
2154 		}
2155 		ictx->entry = entry;
2156 	} while (entry && (ictx->pindex > 0) &&
2157 		 (entry->flags & INDEX_ENTRY_END));
2158 	return entry;
2159 }
2160 
2161 /*
2162  * ntfs_index_next - get next entry in an index according to collating sequence.
2163  * Returns next entry or NULL if none.
2164  *
2165  * Sample layout :
2166  *
2167  *                 +---+---+---+---+---+---+---+---+    n ptrs to subnodes
2168  *                 |   |   | 10| 25| 33|   |   |   |    n-1 keys in between
2169  *                 +---+---+---+---+---+---+---+---+    no key in last entry
2170  *                              | A | A
2171  *                              | | | +-------------------------------+
2172  *   +--------------------------+ | +-----+                           |
2173  *   |                            +--+    |                           |
2174  *   V                               |    V                           |
2175  * +---+---+---+---+---+---+---+---+ |  +---+---+---+---+---+---+---+---+
2176  * | 11| 12| 13| 14| 15| 16| 17|   | |  | 26| 27| 28| 29| 30| 31| 32|   |
2177  * +---+---+---+---+---+---+---+---+ |  +---+---+---+---+---+---+---+---+
2178  *                               |   |
2179  *       +-----------------------+   |
2180  *       |                           |
2181  *     +---+---+---+---+---+---+---+---+
2182  *     | 18| 19| 20| 21| 22| 23| 24|   |
2183  *     +---+---+---+---+---+---+---+---+
2184  *
2185  * @ie: current index entry
2186  * @ictx: index context
2187  */
ntfs_index_next(struct index_entry * ie,struct ntfs_index_context * ictx)2188 struct index_entry *ntfs_index_next(struct index_entry *ie, struct ntfs_index_context *ictx)
2189 {
2190 	struct index_entry *next;
2191 	__le16 flags;
2192 
2193 	/*
2194 	 * lookup() may have returned an invalid node
2195 	 * when searching for a partial key
2196 	 * if this happens, walk up
2197 	 */
2198 	if (ie->flags & INDEX_ENTRY_END)
2199 		next = ntfs_index_walk_up(ie, ictx);
2200 	else {
2201 		/*
2202 		 * get next entry in same node
2203 		 * there is always one after any entry with data
2204 		 */
2205 		next = (struct index_entry *)((char *)ie + le16_to_cpu(ie->length));
2206 		++ictx->parent_pos[ictx->pindex];
2207 		flags = next->flags;
2208 
2209 		/* walk down if it has a subnode */
2210 		if (flags & INDEX_ENTRY_NODE) {
2211 			if (!ictx->ia_ni) {
2212 				ictx->ia_ni = ntfs_ia_open(ictx, ictx->idx_ni);
2213 				if (!ictx->ia_ni)
2214 					return ERR_PTR(-EIO);
2215 			}
2216 
2217 			next = ntfs_index_walk_down(next, ictx);
2218 			if (IS_ERR(next))
2219 				return next;
2220 		} else {
2221 
2222 			/* walk up it has no subnode, nor data */
2223 			if (flags & INDEX_ENTRY_END)
2224 				next = ntfs_index_walk_up(next, ictx);
2225 		}
2226 	}
2227 
2228 	/* return NULL if stuck at end of a block */
2229 	if (next && (next->flags & INDEX_ENTRY_END))
2230 		next = NULL;
2231 
2232 	return next;
2233 }
2234