1 /*
2  * This file is part of UBIFS.
3  *
4  * Copyright (C) 2006-2008 Nokia Corporation.
5  *
6  * This program is free software; you can redistribute it and/or modify it
7  * under the terms of the GNU General Public License version 2 as published by
8  * the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful, but WITHOUT
11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
13  * more details.
14  *
15  * You should have received a copy of the GNU General Public License along with
16  * this program; if not, write to the Free Software Foundation, Inc., 51
17  * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18  *
19  * Authors: Adrian Hunter
20  *          Artem Bityutskiy (Битюцкий Артём)
21  */
22 
23 /*
24  * This file implements TNC (Tree Node Cache) which caches indexing nodes of
25  * the UBIFS B-tree.
26  *
27  * At the moment the locking rules of the TNC tree are quite simple and
28  * straightforward. We just have a mutex and lock it when we traverse the
29  * tree. If a znode is not in memory, we read it from flash while still having
30  * the mutex locked.
31  */
32 
33 #include <linux/crc32.h>
34 #include <linux/slab.h>
35 #include "ubifs.h"
36 
37 static int try_read_node(const struct ubifs_info *c, void *buf, int type,
38 			 int len, int lnum, int offs);
39 static int fallible_read_node(struct ubifs_info *c, const union ubifs_key *key,
40 			      struct ubifs_zbranch *zbr, void *node);
41 
42 /*
43  * Returned codes of 'matches_name()' and 'fallible_matches_name()' functions.
44  * @NAME_LESS: name corresponding to the first argument is less than second
45  * @NAME_MATCHES: names match
46  * @NAME_GREATER: name corresponding to the second argument is greater than
47  *                first
48  * @NOT_ON_MEDIA: node referred by zbranch does not exist on the media
49  *
50  * These constants were introduce to improve readability.
51  */
52 enum {
53 	NAME_LESS    = 0,
54 	NAME_MATCHES = 1,
55 	NAME_GREATER = 2,
56 	NOT_ON_MEDIA = 3,
57 };
58 
do_insert_old_idx(struct ubifs_info * c,struct ubifs_old_idx * old_idx)59 static void do_insert_old_idx(struct ubifs_info *c,
60 			      struct ubifs_old_idx *old_idx)
61 {
62 	struct ubifs_old_idx *o;
63 	struct rb_node **p, *parent = NULL;
64 
65 	p = &c->old_idx.rb_node;
66 	while (*p) {
67 		parent = *p;
68 		o = rb_entry(parent, struct ubifs_old_idx, rb);
69 		if (old_idx->lnum < o->lnum)
70 			p = &(*p)->rb_left;
71 		else if (old_idx->lnum > o->lnum)
72 			p = &(*p)->rb_right;
73 		else if (old_idx->offs < o->offs)
74 			p = &(*p)->rb_left;
75 		else if (old_idx->offs > o->offs)
76 			p = &(*p)->rb_right;
77 		else {
78 			ubifs_err(c, "old idx added twice!");
79 			kfree(old_idx);
80 		}
81 	}
82 	rb_link_node(&old_idx->rb, parent, p);
83 	rb_insert_color(&old_idx->rb, &c->old_idx);
84 }
85 
86 /**
87  * insert_old_idx - record an index node obsoleted since the last commit start.
88  * @c: UBIFS file-system description object
89  * @lnum: LEB number of obsoleted index node
90  * @offs: offset of obsoleted index node
91  *
92  * Returns %0 on success, and a negative error code on failure.
93  *
94  * For recovery, there must always be a complete intact version of the index on
95  * flash at all times. That is called the "old index". It is the index as at the
96  * time of the last successful commit. Many of the index nodes in the old index
97  * may be dirty, but they must not be erased until the next successful commit
98  * (at which point that index becomes the old index).
99  *
100  * That means that the garbage collection and the in-the-gaps method of
101  * committing must be able to determine if an index node is in the old index.
102  * Most of the old index nodes can be found by looking up the TNC using the
103  * 'lookup_znode()' function. However, some of the old index nodes may have
104  * been deleted from the current index or may have been changed so much that
105  * they cannot be easily found. In those cases, an entry is added to an RB-tree.
106  * That is what this function does. The RB-tree is ordered by LEB number and
107  * offset because they uniquely identify the old index node.
108  */
insert_old_idx(struct ubifs_info * c,int lnum,int offs)109 static int insert_old_idx(struct ubifs_info *c, int lnum, int offs)
110 {
111 	struct ubifs_old_idx *old_idx;
112 
113 	old_idx = kmalloc(sizeof(struct ubifs_old_idx), GFP_NOFS);
114 	if (unlikely(!old_idx))
115 		return -ENOMEM;
116 	old_idx->lnum = lnum;
117 	old_idx->offs = offs;
118 	do_insert_old_idx(c, old_idx);
119 
120 	return 0;
121 }
122 
123 /**
124  * insert_old_idx_znode - record a znode obsoleted since last commit start.
125  * @c: UBIFS file-system description object
126  * @znode: znode of obsoleted index node
127  *
128  * Returns %0 on success, and a negative error code on failure.
129  */
insert_old_idx_znode(struct ubifs_info * c,struct ubifs_znode * znode)130 int insert_old_idx_znode(struct ubifs_info *c, struct ubifs_znode *znode)
131 {
132 	if (znode->parent) {
133 		struct ubifs_zbranch *zbr;
134 
135 		zbr = &znode->parent->zbranch[znode->iip];
136 		if (zbr->len)
137 			return insert_old_idx(c, zbr->lnum, zbr->offs);
138 	} else
139 		if (c->zroot.len)
140 			return insert_old_idx(c, c->zroot.lnum,
141 					      c->zroot.offs);
142 	return 0;
143 }
144 
145 /**
146  * ins_clr_old_idx_znode - record a znode obsoleted since last commit start.
147  * @c: UBIFS file-system description object
148  * @znode: znode of obsoleted index node
149  *
150  * Returns %0 on success, and a negative error code on failure.
151  */
ins_clr_old_idx_znode(struct ubifs_info * c,struct ubifs_znode * znode)152 static int ins_clr_old_idx_znode(struct ubifs_info *c,
153 				 struct ubifs_znode *znode)
154 {
155 	int err;
156 
157 	if (znode->parent) {
158 		struct ubifs_zbranch *zbr;
159 
160 		zbr = &znode->parent->zbranch[znode->iip];
161 		if (zbr->len) {
162 			err = insert_old_idx(c, zbr->lnum, zbr->offs);
163 			if (err)
164 				return err;
165 			zbr->lnum = 0;
166 			zbr->offs = 0;
167 			zbr->len = 0;
168 		}
169 	} else
170 		if (c->zroot.len) {
171 			err = insert_old_idx(c, c->zroot.lnum, c->zroot.offs);
172 			if (err)
173 				return err;
174 			c->zroot.lnum = 0;
175 			c->zroot.offs = 0;
176 			c->zroot.len = 0;
177 		}
178 	return 0;
179 }
180 
181 /**
182  * destroy_old_idx - destroy the old_idx RB-tree.
183  * @c: UBIFS file-system description object
184  *
185  * During start commit, the old_idx RB-tree is used to avoid overwriting index
186  * nodes that were in the index last commit but have since been deleted.  This
187  * is necessary for recovery i.e. the old index must be kept intact until the
188  * new index is successfully written.  The old-idx RB-tree is used for the
189  * in-the-gaps method of writing index nodes and is destroyed every commit.
190  */
destroy_old_idx(struct ubifs_info * c)191 void destroy_old_idx(struct ubifs_info *c)
192 {
193 	struct ubifs_old_idx *old_idx, *n;
194 
195 	rbtree_postorder_for_each_entry_safe(old_idx, n, &c->old_idx, rb)
196 		kfree(old_idx);
197 
198 	c->old_idx = RB_ROOT;
199 }
200 
201 /**
202  * copy_znode - copy a dirty znode.
203  * @c: UBIFS file-system description object
204  * @znode: znode to copy
205  *
206  * A dirty znode being committed may not be changed, so it is copied.
207  */
copy_znode(struct ubifs_info * c,struct ubifs_znode * znode)208 static struct ubifs_znode *copy_znode(struct ubifs_info *c,
209 				      struct ubifs_znode *znode)
210 {
211 	struct ubifs_znode *zn;
212 
213 	zn = kmemdup(znode, c->max_znode_sz, GFP_NOFS);
214 	if (unlikely(!zn))
215 		return ERR_PTR(-ENOMEM);
216 
217 	zn->cnext = NULL;
218 	__set_bit(DIRTY_ZNODE, &zn->flags);
219 	__clear_bit(COW_ZNODE, &zn->flags);
220 
221 	return zn;
222 }
223 
224 /**
225  * add_idx_dirt - add dirt due to a dirty znode.
226  * @c: UBIFS file-system description object
227  * @lnum: LEB number of index node
228  * @dirt: size of index node
229  *
230  * This function updates lprops dirty space and the new size of the index.
231  */
add_idx_dirt(struct ubifs_info * c,int lnum,int dirt)232 static int add_idx_dirt(struct ubifs_info *c, int lnum, int dirt)
233 {
234 	c->calc_idx_sz -= ALIGN(dirt, 8);
235 	return ubifs_add_dirt(c, lnum, dirt);
236 }
237 
238 /**
239  * replace_znode - replace old znode with new znode.
240  * @c: UBIFS file-system description object
241  * @new_zn: new znode
242  * @old_zn: old znode
243  * @zbr: the branch of parent znode
244  *
245  * Replace old znode with new znode in TNC.
246  */
replace_znode(struct ubifs_info * c,struct ubifs_znode * new_zn,struct ubifs_znode * old_zn,struct ubifs_zbranch * zbr)247 static void replace_znode(struct ubifs_info *c, struct ubifs_znode *new_zn,
248 			  struct ubifs_znode *old_zn, struct ubifs_zbranch *zbr)
249 {
250 	ubifs_assert(c, !ubifs_zn_obsolete(old_zn));
251 	__set_bit(OBSOLETE_ZNODE, &old_zn->flags);
252 
253 	if (old_zn->level != 0) {
254 		int i;
255 		const int n = new_zn->child_cnt;
256 
257 		/* The children now have new parent */
258 		for (i = 0; i < n; i++) {
259 			struct ubifs_zbranch *child = &new_zn->zbranch[i];
260 
261 			if (child->znode)
262 				child->znode->parent = new_zn;
263 		}
264 	}
265 
266 	zbr->znode = new_zn;
267 	zbr->lnum = 0;
268 	zbr->offs = 0;
269 	zbr->len = 0;
270 
271 	atomic_long_inc(&c->dirty_zn_cnt);
272 }
273 
274 /**
275  * dirty_cow_znode - ensure a znode is not being committed.
276  * @c: UBIFS file-system description object
277  * @zbr: branch of znode to check
278  *
279  * Returns dirtied znode on success or negative error code on failure.
280  */
dirty_cow_znode(struct ubifs_info * c,struct ubifs_zbranch * zbr)281 static struct ubifs_znode *dirty_cow_znode(struct ubifs_info *c,
282 					   struct ubifs_zbranch *zbr)
283 {
284 	struct ubifs_znode *znode = zbr->znode;
285 	struct ubifs_znode *zn;
286 	int err;
287 
288 	if (!ubifs_zn_cow(znode)) {
289 		/* znode is not being committed */
290 		if (!test_and_set_bit(DIRTY_ZNODE, &znode->flags)) {
291 			atomic_long_inc(&c->dirty_zn_cnt);
292 			atomic_long_dec(&c->clean_zn_cnt);
293 			atomic_long_dec(&ubifs_clean_zn_cnt);
294 			err = add_idx_dirt(c, zbr->lnum, zbr->len);
295 			if (unlikely(err))
296 				return ERR_PTR(err);
297 		}
298 		return znode;
299 	}
300 
301 	zn = copy_znode(c, znode);
302 	if (IS_ERR(zn))
303 		return zn;
304 
305 	if (zbr->len) {
306 		struct ubifs_old_idx *old_idx;
307 
308 		old_idx = kmalloc(sizeof(struct ubifs_old_idx), GFP_NOFS);
309 		if (unlikely(!old_idx)) {
310 			err = -ENOMEM;
311 			goto out;
312 		}
313 		old_idx->lnum = zbr->lnum;
314 		old_idx->offs = zbr->offs;
315 
316 		err = add_idx_dirt(c, zbr->lnum, zbr->len);
317 		if (err) {
318 			kfree(old_idx);
319 			goto out;
320 		}
321 
322 		do_insert_old_idx(c, old_idx);
323 	}
324 
325 	replace_znode(c, zn, znode, zbr);
326 
327 	return zn;
328 
329 out:
330 	kfree(zn);
331 	return ERR_PTR(err);
332 }
333 
334 /**
335  * lnc_add - add a leaf node to the leaf node cache.
336  * @c: UBIFS file-system description object
337  * @zbr: zbranch of leaf node
338  * @node: leaf node
339  *
340  * Leaf nodes are non-index nodes directory entry nodes or data nodes. The
341  * purpose of the leaf node cache is to save re-reading the same leaf node over
342  * and over again. Most things are cached by VFS, however the file system must
343  * cache directory entries for readdir and for resolving hash collisions. The
344  * present implementation of the leaf node cache is extremely simple, and
345  * allows for error returns that are not used but that may be needed if a more
346  * complex implementation is created.
347  *
348  * Note, this function does not add the @node object to LNC directly, but
349  * allocates a copy of the object and adds the copy to LNC. The reason for this
350  * is that @node has been allocated outside of the TNC subsystem and will be
351  * used with @c->tnc_mutex unlock upon return from the TNC subsystem. But LNC
352  * may be changed at any time, e.g. freed by the shrinker.
353  */
lnc_add(struct ubifs_info * c,struct ubifs_zbranch * zbr,const void * node)354 static int lnc_add(struct ubifs_info *c, struct ubifs_zbranch *zbr,
355 		   const void *node)
356 {
357 	int err;
358 	void *lnc_node;
359 	const struct ubifs_dent_node *dent = node;
360 
361 	ubifs_assert(c, !zbr->leaf);
362 	ubifs_assert(c, zbr->len != 0);
363 	ubifs_assert(c, is_hash_key(c, &zbr->key));
364 
365 	err = ubifs_validate_entry(c, dent);
366 	if (err) {
367 		dump_stack();
368 		ubifs_dump_node(c, dent);
369 		return err;
370 	}
371 
372 	lnc_node = kmemdup(node, zbr->len, GFP_NOFS);
373 	if (!lnc_node)
374 		/* We don't have to have the cache, so no error */
375 		return 0;
376 
377 	zbr->leaf = lnc_node;
378 	return 0;
379 }
380 
381  /**
382  * lnc_add_directly - add a leaf node to the leaf-node-cache.
383  * @c: UBIFS file-system description object
384  * @zbr: zbranch of leaf node
385  * @node: leaf node
386  *
387  * This function is similar to 'lnc_add()', but it does not create a copy of
388  * @node but inserts @node to TNC directly.
389  */
lnc_add_directly(struct ubifs_info * c,struct ubifs_zbranch * zbr,void * node)390 static int lnc_add_directly(struct ubifs_info *c, struct ubifs_zbranch *zbr,
391 			    void *node)
392 {
393 	int err;
394 
395 	ubifs_assert(c, !zbr->leaf);
396 	ubifs_assert(c, zbr->len != 0);
397 
398 	err = ubifs_validate_entry(c, node);
399 	if (err) {
400 		dump_stack();
401 		ubifs_dump_node(c, node);
402 		return err;
403 	}
404 
405 	zbr->leaf = node;
406 	return 0;
407 }
408 
409 /**
410  * lnc_free - remove a leaf node from the leaf node cache.
411  * @zbr: zbranch of leaf node
412  * @node: leaf node
413  */
lnc_free(struct ubifs_zbranch * zbr)414 static void lnc_free(struct ubifs_zbranch *zbr)
415 {
416 	if (!zbr->leaf)
417 		return;
418 	kfree(zbr->leaf);
419 	zbr->leaf = NULL;
420 }
421 
422 /**
423  * tnc_read_hashed_node - read a "hashed" leaf node.
424  * @c: UBIFS file-system description object
425  * @zbr: key and position of the node
426  * @node: node is returned here
427  *
428  * This function reads a "hashed" node defined by @zbr from the leaf node cache
429  * (in it is there) or from the hash media, in which case the node is also
430  * added to LNC. Returns zero in case of success or a negative negative error
431  * code in case of failure.
432  */
tnc_read_hashed_node(struct ubifs_info * c,struct ubifs_zbranch * zbr,void * node)433 static int tnc_read_hashed_node(struct ubifs_info *c, struct ubifs_zbranch *zbr,
434 				void *node)
435 {
436 	int err;
437 
438 	ubifs_assert(c, is_hash_key(c, &zbr->key));
439 
440 	if (zbr->leaf) {
441 		/* Read from the leaf node cache */
442 		ubifs_assert(c, zbr->len != 0);
443 		memcpy(node, zbr->leaf, zbr->len);
444 		return 0;
445 	}
446 
447 	if (c->replaying) {
448 		err = fallible_read_node(c, &zbr->key, zbr, node);
449 		/*
450 		 * When the node was not found, return -ENOENT, 0 otherwise.
451 		 * Negative return codes stay as-is.
452 		 */
453 		if (err == 0)
454 			err = -ENOENT;
455 		else if (err == 1)
456 			err = 0;
457 	} else {
458 		err = ubifs_tnc_read_node(c, zbr, node);
459 	}
460 	if (err)
461 		return err;
462 
463 	/* Add the node to the leaf node cache */
464 	err = lnc_add(c, zbr, node);
465 	return err;
466 }
467 
468 /**
469  * try_read_node - read a node if it is a node.
470  * @c: UBIFS file-system description object
471  * @buf: buffer to read to
472  * @type: node type
473  * @len: node length (not aligned)
474  * @lnum: LEB number of node to read
475  * @offs: offset of node to read
476  *
477  * This function tries to read a node of known type and length, checks it and
478  * stores it in @buf. This function returns %1 if a node is present and %0 if
479  * a node is not present. A negative error code is returned for I/O errors.
480  * This function performs that same function as ubifs_read_node except that
481  * it does not require that there is actually a node present and instead
482  * the return code indicates if a node was read.
483  *
484  * Note, this function does not check CRC of data nodes if @c->no_chk_data_crc
485  * is true (it is controlled by corresponding mount option). However, if
486  * @c->mounting or @c->remounting_rw is true (we are mounting or re-mounting to
487  * R/W mode), @c->no_chk_data_crc is ignored and CRC is checked. This is
488  * because during mounting or re-mounting from R/O mode to R/W mode we may read
489  * journal nodes (when replying the journal or doing the recovery) and the
490  * journal nodes may potentially be corrupted, so checking is required.
491  */
try_read_node(const struct ubifs_info * c,void * buf,int type,int len,int lnum,int offs)492 static int try_read_node(const struct ubifs_info *c, void *buf, int type,
493 			 int len, int lnum, int offs)
494 {
495 	int err, node_len;
496 	struct ubifs_ch *ch = buf;
497 	uint32_t crc, node_crc;
498 
499 	dbg_io("LEB %d:%d, %s, length %d", lnum, offs, dbg_ntype(type), len);
500 
501 	err = ubifs_leb_read(c, lnum, buf, offs, len, 1);
502 	if (err) {
503 		ubifs_err(c, "cannot read node type %d from LEB %d:%d, error %d",
504 			  type, lnum, offs, err);
505 		return err;
506 	}
507 
508 	if (le32_to_cpu(ch->magic) != UBIFS_NODE_MAGIC)
509 		return 0;
510 
511 	if (ch->node_type != type)
512 		return 0;
513 
514 	node_len = le32_to_cpu(ch->len);
515 	if (node_len != len)
516 		return 0;
517 
518 	if (type == UBIFS_DATA_NODE && c->no_chk_data_crc && !c->mounting &&
519 	    !c->remounting_rw)
520 		return 1;
521 
522 	crc = crc32(UBIFS_CRC32_INIT, buf + 8, node_len - 8);
523 	node_crc = le32_to_cpu(ch->crc);
524 	if (crc != node_crc)
525 		return 0;
526 
527 	return 1;
528 }
529 
530 /**
531  * fallible_read_node - try to read a leaf node.
532  * @c: UBIFS file-system description object
533  * @key:  key of node to read
534  * @zbr:  position of node
535  * @node: node returned
536  *
537  * This function tries to read a node and returns %1 if the node is read, %0
538  * if the node is not present, and a negative error code in the case of error.
539  */
fallible_read_node(struct ubifs_info * c,const union ubifs_key * key,struct ubifs_zbranch * zbr,void * node)540 static int fallible_read_node(struct ubifs_info *c, const union ubifs_key *key,
541 			      struct ubifs_zbranch *zbr, void *node)
542 {
543 	int ret;
544 
545 	dbg_tnck(key, "LEB %d:%d, key ", zbr->lnum, zbr->offs);
546 
547 	ret = try_read_node(c, node, key_type(c, key), zbr->len, zbr->lnum,
548 			    zbr->offs);
549 	if (ret == 1) {
550 		union ubifs_key node_key;
551 		struct ubifs_dent_node *dent = node;
552 
553 		/* All nodes have key in the same place */
554 		key_read(c, &dent->key, &node_key);
555 		if (keys_cmp(c, key, &node_key) != 0)
556 			ret = 0;
557 	}
558 	if (ret == 0 && c->replaying)
559 		dbg_mntk(key, "dangling branch LEB %d:%d len %d, key ",
560 			zbr->lnum, zbr->offs, zbr->len);
561 	return ret;
562 }
563 
564 /**
565  * matches_name - determine if a direntry or xattr entry matches a given name.
566  * @c: UBIFS file-system description object
567  * @zbr: zbranch of dent
568  * @nm: name to match
569  *
570  * This function checks if xentry/direntry referred by zbranch @zbr matches name
571  * @nm. Returns %NAME_MATCHES if it does, %NAME_LESS if the name referred by
572  * @zbr is less than @nm, and %NAME_GREATER if it is greater than @nm. In case
573  * of failure, a negative error code is returned.
574  */
matches_name(struct ubifs_info * c,struct ubifs_zbranch * zbr,const struct fscrypt_name * nm)575 static int matches_name(struct ubifs_info *c, struct ubifs_zbranch *zbr,
576 			const struct fscrypt_name *nm)
577 {
578 	struct ubifs_dent_node *dent;
579 	int nlen, err;
580 
581 	/* If possible, match against the dent in the leaf node cache */
582 	if (!zbr->leaf) {
583 		dent = kmalloc(zbr->len, GFP_NOFS);
584 		if (!dent)
585 			return -ENOMEM;
586 
587 		err = ubifs_tnc_read_node(c, zbr, dent);
588 		if (err)
589 			goto out_free;
590 
591 		/* Add the node to the leaf node cache */
592 		err = lnc_add_directly(c, zbr, dent);
593 		if (err)
594 			goto out_free;
595 	} else
596 		dent = zbr->leaf;
597 
598 	nlen = le16_to_cpu(dent->nlen);
599 	err = memcmp(dent->name, fname_name(nm), min_t(int, nlen, fname_len(nm)));
600 	if (err == 0) {
601 		if (nlen == fname_len(nm))
602 			return NAME_MATCHES;
603 		else if (nlen < fname_len(nm))
604 			return NAME_LESS;
605 		else
606 			return NAME_GREATER;
607 	} else if (err < 0)
608 		return NAME_LESS;
609 	else
610 		return NAME_GREATER;
611 
612 out_free:
613 	kfree(dent);
614 	return err;
615 }
616 
617 /**
618  * get_znode - get a TNC znode that may not be loaded yet.
619  * @c: UBIFS file-system description object
620  * @znode: parent znode
621  * @n: znode branch slot number
622  *
623  * This function returns the znode or a negative error code.
624  */
get_znode(struct ubifs_info * c,struct ubifs_znode * znode,int n)625 static struct ubifs_znode *get_znode(struct ubifs_info *c,
626 				     struct ubifs_znode *znode, int n)
627 {
628 	struct ubifs_zbranch *zbr;
629 
630 	zbr = &znode->zbranch[n];
631 	if (zbr->znode)
632 		znode = zbr->znode;
633 	else
634 		znode = ubifs_load_znode(c, zbr, znode, n);
635 	return znode;
636 }
637 
638 /**
639  * tnc_next - find next TNC entry.
640  * @c: UBIFS file-system description object
641  * @zn: znode is passed and returned here
642  * @n: znode branch slot number is passed and returned here
643  *
644  * This function returns %0 if the next TNC entry is found, %-ENOENT if there is
645  * no next entry, or a negative error code otherwise.
646  */
tnc_next(struct ubifs_info * c,struct ubifs_znode ** zn,int * n)647 static int tnc_next(struct ubifs_info *c, struct ubifs_znode **zn, int *n)
648 {
649 	struct ubifs_znode *znode = *zn;
650 	int nn = *n;
651 
652 	nn += 1;
653 	if (nn < znode->child_cnt) {
654 		*n = nn;
655 		return 0;
656 	}
657 	while (1) {
658 		struct ubifs_znode *zp;
659 
660 		zp = znode->parent;
661 		if (!zp)
662 			return -ENOENT;
663 		nn = znode->iip + 1;
664 		znode = zp;
665 		if (nn < znode->child_cnt) {
666 			znode = get_znode(c, znode, nn);
667 			if (IS_ERR(znode))
668 				return PTR_ERR(znode);
669 			while (znode->level != 0) {
670 				znode = get_znode(c, znode, 0);
671 				if (IS_ERR(znode))
672 					return PTR_ERR(znode);
673 			}
674 			nn = 0;
675 			break;
676 		}
677 	}
678 	*zn = znode;
679 	*n = nn;
680 	return 0;
681 }
682 
683 /**
684  * tnc_prev - find previous TNC entry.
685  * @c: UBIFS file-system description object
686  * @zn: znode is returned here
687  * @n: znode branch slot number is passed and returned here
688  *
689  * This function returns %0 if the previous TNC entry is found, %-ENOENT if
690  * there is no next entry, or a negative error code otherwise.
691  */
tnc_prev(struct ubifs_info * c,struct ubifs_znode ** zn,int * n)692 static int tnc_prev(struct ubifs_info *c, struct ubifs_znode **zn, int *n)
693 {
694 	struct ubifs_znode *znode = *zn;
695 	int nn = *n;
696 
697 	if (nn > 0) {
698 		*n = nn - 1;
699 		return 0;
700 	}
701 	while (1) {
702 		struct ubifs_znode *zp;
703 
704 		zp = znode->parent;
705 		if (!zp)
706 			return -ENOENT;
707 		nn = znode->iip - 1;
708 		znode = zp;
709 		if (nn >= 0) {
710 			znode = get_znode(c, znode, nn);
711 			if (IS_ERR(znode))
712 				return PTR_ERR(znode);
713 			while (znode->level != 0) {
714 				nn = znode->child_cnt - 1;
715 				znode = get_znode(c, znode, nn);
716 				if (IS_ERR(znode))
717 					return PTR_ERR(znode);
718 			}
719 			nn = znode->child_cnt - 1;
720 			break;
721 		}
722 	}
723 	*zn = znode;
724 	*n = nn;
725 	return 0;
726 }
727 
728 /**
729  * resolve_collision - resolve a collision.
730  * @c: UBIFS file-system description object
731  * @key: key of a directory or extended attribute entry
732  * @zn: znode is returned here
733  * @n: zbranch number is passed and returned here
734  * @nm: name of the entry
735  *
736  * This function is called for "hashed" keys to make sure that the found key
737  * really corresponds to the looked up node (directory or extended attribute
738  * entry). It returns %1 and sets @zn and @n if the collision is resolved.
739  * %0 is returned if @nm is not found and @zn and @n are set to the previous
740  * entry, i.e. to the entry after which @nm could follow if it were in TNC.
741  * This means that @n may be set to %-1 if the leftmost key in @zn is the
742  * previous one. A negative error code is returned on failures.
743  */
resolve_collision(struct ubifs_info * c,const union ubifs_key * key,struct ubifs_znode ** zn,int * n,const struct fscrypt_name * nm)744 static int resolve_collision(struct ubifs_info *c, const union ubifs_key *key,
745 			     struct ubifs_znode **zn, int *n,
746 			     const struct fscrypt_name *nm)
747 {
748 	int err;
749 
750 	err = matches_name(c, &(*zn)->zbranch[*n], nm);
751 	if (unlikely(err < 0))
752 		return err;
753 	if (err == NAME_MATCHES)
754 		return 1;
755 
756 	if (err == NAME_GREATER) {
757 		/* Look left */
758 		while (1) {
759 			err = tnc_prev(c, zn, n);
760 			if (err == -ENOENT) {
761 				ubifs_assert(c, *n == 0);
762 				*n = -1;
763 				return 0;
764 			}
765 			if (err < 0)
766 				return err;
767 			if (keys_cmp(c, &(*zn)->zbranch[*n].key, key)) {
768 				/*
769 				 * We have found the branch after which we would
770 				 * like to insert, but inserting in this znode
771 				 * may still be wrong. Consider the following 3
772 				 * znodes, in the case where we are resolving a
773 				 * collision with Key2.
774 				 *
775 				 *                  znode zp
776 				 *            ----------------------
777 				 * level 1     |  Key0  |  Key1  |
778 				 *            -----------------------
779 				 *                 |            |
780 				 *       znode za  |            |  znode zb
781 				 *          ------------      ------------
782 				 * level 0  |  Key0  |        |  Key2  |
783 				 *          ------------      ------------
784 				 *
785 				 * The lookup finds Key2 in znode zb. Lets say
786 				 * there is no match and the name is greater so
787 				 * we look left. When we find Key0, we end up
788 				 * here. If we return now, we will insert into
789 				 * znode za at slot n = 1.  But that is invalid
790 				 * according to the parent's keys.  Key2 must
791 				 * be inserted into znode zb.
792 				 *
793 				 * Note, this problem is not relevant for the
794 				 * case when we go right, because
795 				 * 'tnc_insert()' would correct the parent key.
796 				 */
797 				if (*n == (*zn)->child_cnt - 1) {
798 					err = tnc_next(c, zn, n);
799 					if (err) {
800 						/* Should be impossible */
801 						ubifs_assert(c, 0);
802 						if (err == -ENOENT)
803 							err = -EINVAL;
804 						return err;
805 					}
806 					ubifs_assert(c, *n == 0);
807 					*n = -1;
808 				}
809 				return 0;
810 			}
811 			err = matches_name(c, &(*zn)->zbranch[*n], nm);
812 			if (err < 0)
813 				return err;
814 			if (err == NAME_LESS)
815 				return 0;
816 			if (err == NAME_MATCHES)
817 				return 1;
818 			ubifs_assert(c, err == NAME_GREATER);
819 		}
820 	} else {
821 		int nn = *n;
822 		struct ubifs_znode *znode = *zn;
823 
824 		/* Look right */
825 		while (1) {
826 			err = tnc_next(c, &znode, &nn);
827 			if (err == -ENOENT)
828 				return 0;
829 			if (err < 0)
830 				return err;
831 			if (keys_cmp(c, &znode->zbranch[nn].key, key))
832 				return 0;
833 			err = matches_name(c, &znode->zbranch[nn], nm);
834 			if (err < 0)
835 				return err;
836 			if (err == NAME_GREATER)
837 				return 0;
838 			*zn = znode;
839 			*n = nn;
840 			if (err == NAME_MATCHES)
841 				return 1;
842 			ubifs_assert(c, err == NAME_LESS);
843 		}
844 	}
845 }
846 
847 /**
848  * fallible_matches_name - determine if a dent matches a given name.
849  * @c: UBIFS file-system description object
850  * @zbr: zbranch of dent
851  * @nm: name to match
852  *
853  * This is a "fallible" version of 'matches_name()' function which does not
854  * panic if the direntry/xentry referred by @zbr does not exist on the media.
855  *
856  * This function checks if xentry/direntry referred by zbranch @zbr matches name
857  * @nm. Returns %NAME_MATCHES it does, %NAME_LESS if the name referred by @zbr
858  * is less than @nm, %NAME_GREATER if it is greater than @nm, and @NOT_ON_MEDIA
859  * if xentry/direntry referred by @zbr does not exist on the media. A negative
860  * error code is returned in case of failure.
861  */
fallible_matches_name(struct ubifs_info * c,struct ubifs_zbranch * zbr,const struct fscrypt_name * nm)862 static int fallible_matches_name(struct ubifs_info *c,
863 				 struct ubifs_zbranch *zbr,
864 				 const struct fscrypt_name *nm)
865 {
866 	struct ubifs_dent_node *dent;
867 	int nlen, err;
868 
869 	/* If possible, match against the dent in the leaf node cache */
870 	if (!zbr->leaf) {
871 		dent = kmalloc(zbr->len, GFP_NOFS);
872 		if (!dent)
873 			return -ENOMEM;
874 
875 		err = fallible_read_node(c, &zbr->key, zbr, dent);
876 		if (err < 0)
877 			goto out_free;
878 		if (err == 0) {
879 			/* The node was not present */
880 			err = NOT_ON_MEDIA;
881 			goto out_free;
882 		}
883 		ubifs_assert(c, err == 1);
884 
885 		err = lnc_add_directly(c, zbr, dent);
886 		if (err)
887 			goto out_free;
888 	} else
889 		dent = zbr->leaf;
890 
891 	nlen = le16_to_cpu(dent->nlen);
892 	err = memcmp(dent->name, fname_name(nm), min_t(int, nlen, fname_len(nm)));
893 	if (err == 0) {
894 		if (nlen == fname_len(nm))
895 			return NAME_MATCHES;
896 		else if (nlen < fname_len(nm))
897 			return NAME_LESS;
898 		else
899 			return NAME_GREATER;
900 	} else if (err < 0)
901 		return NAME_LESS;
902 	else
903 		return NAME_GREATER;
904 
905 out_free:
906 	kfree(dent);
907 	return err;
908 }
909 
910 /**
911  * fallible_resolve_collision - resolve a collision even if nodes are missing.
912  * @c: UBIFS file-system description object
913  * @key: key
914  * @zn: znode is returned here
915  * @n: branch number is passed and returned here
916  * @nm: name of directory entry
917  * @adding: indicates caller is adding a key to the TNC
918  *
919  * This is a "fallible" version of the 'resolve_collision()' function which
920  * does not panic if one of the nodes referred to by TNC does not exist on the
921  * media. This may happen when replaying the journal if a deleted node was
922  * Garbage-collected and the commit was not done. A branch that refers to a node
923  * that is not present is called a dangling branch. The following are the return
924  * codes for this function:
925  *  o if @nm was found, %1 is returned and @zn and @n are set to the found
926  *    branch;
927  *  o if we are @adding and @nm was not found, %0 is returned;
928  *  o if we are not @adding and @nm was not found, but a dangling branch was
929  *    found, then %1 is returned and @zn and @n are set to the dangling branch;
930  *  o a negative error code is returned in case of failure.
931  */
fallible_resolve_collision(struct ubifs_info * c,const union ubifs_key * key,struct ubifs_znode ** zn,int * n,const struct fscrypt_name * nm,int adding)932 static int fallible_resolve_collision(struct ubifs_info *c,
933 				      const union ubifs_key *key,
934 				      struct ubifs_znode **zn, int *n,
935 				      const struct fscrypt_name *nm,
936 				      int adding)
937 {
938 	struct ubifs_znode *o_znode = NULL, *znode = *zn;
939 	int o_n, err, cmp, unsure = 0, nn = *n;
940 
941 	cmp = fallible_matches_name(c, &znode->zbranch[nn], nm);
942 	if (unlikely(cmp < 0))
943 		return cmp;
944 	if (cmp == NAME_MATCHES)
945 		return 1;
946 	if (cmp == NOT_ON_MEDIA) {
947 		o_znode = znode;
948 		o_n = nn;
949 		/*
950 		 * We are unlucky and hit a dangling branch straight away.
951 		 * Now we do not really know where to go to find the needed
952 		 * branch - to the left or to the right. Well, let's try left.
953 		 */
954 		unsure = 1;
955 	} else if (!adding)
956 		unsure = 1; /* Remove a dangling branch wherever it is */
957 
958 	if (cmp == NAME_GREATER || unsure) {
959 		/* Look left */
960 		while (1) {
961 			err = tnc_prev(c, zn, n);
962 			if (err == -ENOENT) {
963 				ubifs_assert(c, *n == 0);
964 				*n = -1;
965 				break;
966 			}
967 			if (err < 0)
968 				return err;
969 			if (keys_cmp(c, &(*zn)->zbranch[*n].key, key)) {
970 				/* See comments in 'resolve_collision()' */
971 				if (*n == (*zn)->child_cnt - 1) {
972 					err = tnc_next(c, zn, n);
973 					if (err) {
974 						/* Should be impossible */
975 						ubifs_assert(c, 0);
976 						if (err == -ENOENT)
977 							err = -EINVAL;
978 						return err;
979 					}
980 					ubifs_assert(c, *n == 0);
981 					*n = -1;
982 				}
983 				break;
984 			}
985 			err = fallible_matches_name(c, &(*zn)->zbranch[*n], nm);
986 			if (err < 0)
987 				return err;
988 			if (err == NAME_MATCHES)
989 				return 1;
990 			if (err == NOT_ON_MEDIA) {
991 				o_znode = *zn;
992 				o_n = *n;
993 				continue;
994 			}
995 			if (!adding)
996 				continue;
997 			if (err == NAME_LESS)
998 				break;
999 			else
1000 				unsure = 0;
1001 		}
1002 	}
1003 
1004 	if (cmp == NAME_LESS || unsure) {
1005 		/* Look right */
1006 		*zn = znode;
1007 		*n = nn;
1008 		while (1) {
1009 			err = tnc_next(c, &znode, &nn);
1010 			if (err == -ENOENT)
1011 				break;
1012 			if (err < 0)
1013 				return err;
1014 			if (keys_cmp(c, &znode->zbranch[nn].key, key))
1015 				break;
1016 			err = fallible_matches_name(c, &znode->zbranch[nn], nm);
1017 			if (err < 0)
1018 				return err;
1019 			if (err == NAME_GREATER)
1020 				break;
1021 			*zn = znode;
1022 			*n = nn;
1023 			if (err == NAME_MATCHES)
1024 				return 1;
1025 			if (err == NOT_ON_MEDIA) {
1026 				o_znode = znode;
1027 				o_n = nn;
1028 			}
1029 		}
1030 	}
1031 
1032 	/* Never match a dangling branch when adding */
1033 	if (adding || !o_znode)
1034 		return 0;
1035 
1036 	dbg_mntk(key, "dangling match LEB %d:%d len %d key ",
1037 		o_znode->zbranch[o_n].lnum, o_znode->zbranch[o_n].offs,
1038 		o_znode->zbranch[o_n].len);
1039 	*zn = o_znode;
1040 	*n = o_n;
1041 	return 1;
1042 }
1043 
1044 /**
1045  * matches_position - determine if a zbranch matches a given position.
1046  * @zbr: zbranch of dent
1047  * @lnum: LEB number of dent to match
1048  * @offs: offset of dent to match
1049  *
1050  * This function returns %1 if @lnum:@offs matches, and %0 otherwise.
1051  */
matches_position(struct ubifs_zbranch * zbr,int lnum,int offs)1052 static int matches_position(struct ubifs_zbranch *zbr, int lnum, int offs)
1053 {
1054 	if (zbr->lnum == lnum && zbr->offs == offs)
1055 		return 1;
1056 	else
1057 		return 0;
1058 }
1059 
1060 /**
1061  * resolve_collision_directly - resolve a collision directly.
1062  * @c: UBIFS file-system description object
1063  * @key: key of directory entry
1064  * @zn: znode is passed and returned here
1065  * @n: zbranch number is passed and returned here
1066  * @lnum: LEB number of dent node to match
1067  * @offs: offset of dent node to match
1068  *
1069  * This function is used for "hashed" keys to make sure the found directory or
1070  * extended attribute entry node is what was looked for. It is used when the
1071  * flash address of the right node is known (@lnum:@offs) which makes it much
1072  * easier to resolve collisions (no need to read entries and match full
1073  * names). This function returns %1 and sets @zn and @n if the collision is
1074  * resolved, %0 if @lnum:@offs is not found and @zn and @n are set to the
1075  * previous directory entry. Otherwise a negative error code is returned.
1076  */
resolve_collision_directly(struct ubifs_info * c,const union ubifs_key * key,struct ubifs_znode ** zn,int * n,int lnum,int offs)1077 static int resolve_collision_directly(struct ubifs_info *c,
1078 				      const union ubifs_key *key,
1079 				      struct ubifs_znode **zn, int *n,
1080 				      int lnum, int offs)
1081 {
1082 	struct ubifs_znode *znode;
1083 	int nn, err;
1084 
1085 	znode = *zn;
1086 	nn = *n;
1087 	if (matches_position(&znode->zbranch[nn], lnum, offs))
1088 		return 1;
1089 
1090 	/* Look left */
1091 	while (1) {
1092 		err = tnc_prev(c, &znode, &nn);
1093 		if (err == -ENOENT)
1094 			break;
1095 		if (err < 0)
1096 			return err;
1097 		if (keys_cmp(c, &znode->zbranch[nn].key, key))
1098 			break;
1099 		if (matches_position(&znode->zbranch[nn], lnum, offs)) {
1100 			*zn = znode;
1101 			*n = nn;
1102 			return 1;
1103 		}
1104 	}
1105 
1106 	/* Look right */
1107 	znode = *zn;
1108 	nn = *n;
1109 	while (1) {
1110 		err = tnc_next(c, &znode, &nn);
1111 		if (err == -ENOENT)
1112 			return 0;
1113 		if (err < 0)
1114 			return err;
1115 		if (keys_cmp(c, &znode->zbranch[nn].key, key))
1116 			return 0;
1117 		*zn = znode;
1118 		*n = nn;
1119 		if (matches_position(&znode->zbranch[nn], lnum, offs))
1120 			return 1;
1121 	}
1122 }
1123 
1124 /**
1125  * dirty_cow_bottom_up - dirty a znode and its ancestors.
1126  * @c: UBIFS file-system description object
1127  * @znode: znode to dirty
1128  *
1129  * If we do not have a unique key that resides in a znode, then we cannot
1130  * dirty that znode from the top down (i.e. by using lookup_level0_dirty)
1131  * This function records the path back to the last dirty ancestor, and then
1132  * dirties the znodes on that path.
1133  */
dirty_cow_bottom_up(struct ubifs_info * c,struct ubifs_znode * znode)1134 static struct ubifs_znode *dirty_cow_bottom_up(struct ubifs_info *c,
1135 					       struct ubifs_znode *znode)
1136 {
1137 	struct ubifs_znode *zp;
1138 	int *path = c->bottom_up_buf, p = 0;
1139 
1140 	ubifs_assert(c, c->zroot.znode);
1141 	ubifs_assert(c, znode);
1142 	if (c->zroot.znode->level > BOTTOM_UP_HEIGHT) {
1143 		kfree(c->bottom_up_buf);
1144 		c->bottom_up_buf = kmalloc_array(c->zroot.znode->level,
1145 						 sizeof(int),
1146 						 GFP_NOFS);
1147 		if (!c->bottom_up_buf)
1148 			return ERR_PTR(-ENOMEM);
1149 		path = c->bottom_up_buf;
1150 	}
1151 	if (c->zroot.znode->level) {
1152 		/* Go up until parent is dirty */
1153 		while (1) {
1154 			int n;
1155 
1156 			zp = znode->parent;
1157 			if (!zp)
1158 				break;
1159 			n = znode->iip;
1160 			ubifs_assert(c, p < c->zroot.znode->level);
1161 			path[p++] = n;
1162 			if (!zp->cnext && ubifs_zn_dirty(znode))
1163 				break;
1164 			znode = zp;
1165 		}
1166 	}
1167 
1168 	/* Come back down, dirtying as we go */
1169 	while (1) {
1170 		struct ubifs_zbranch *zbr;
1171 
1172 		zp = znode->parent;
1173 		if (zp) {
1174 			ubifs_assert(c, path[p - 1] >= 0);
1175 			ubifs_assert(c, path[p - 1] < zp->child_cnt);
1176 			zbr = &zp->zbranch[path[--p]];
1177 			znode = dirty_cow_znode(c, zbr);
1178 		} else {
1179 			ubifs_assert(c, znode == c->zroot.znode);
1180 			znode = dirty_cow_znode(c, &c->zroot);
1181 		}
1182 		if (IS_ERR(znode) || !p)
1183 			break;
1184 		ubifs_assert(c, path[p - 1] >= 0);
1185 		ubifs_assert(c, path[p - 1] < znode->child_cnt);
1186 		znode = znode->zbranch[path[p - 1]].znode;
1187 	}
1188 
1189 	return znode;
1190 }
1191 
1192 /**
1193  * ubifs_lookup_level0 - search for zero-level znode.
1194  * @c: UBIFS file-system description object
1195  * @key:  key to lookup
1196  * @zn: znode is returned here
1197  * @n: znode branch slot number is returned here
1198  *
1199  * This function looks up the TNC tree and search for zero-level znode which
1200  * refers key @key. The found zero-level znode is returned in @zn. There are 3
1201  * cases:
1202  *   o exact match, i.e. the found zero-level znode contains key @key, then %1
1203  *     is returned and slot number of the matched branch is stored in @n;
1204  *   o not exact match, which means that zero-level znode does not contain
1205  *     @key, then %0 is returned and slot number of the closest branch or %-1
1206  *     is stored in @n; In this case calling tnc_next() is mandatory.
1207  *   o @key is so small that it is even less than the lowest key of the
1208  *     leftmost zero-level node, then %0 is returned and %0 is stored in @n.
1209  *
1210  * Note, when the TNC tree is traversed, some znodes may be absent, then this
1211  * function reads corresponding indexing nodes and inserts them to TNC. In
1212  * case of failure, a negative error code is returned.
1213  */
ubifs_lookup_level0(struct ubifs_info * c,const union ubifs_key * key,struct ubifs_znode ** zn,int * n)1214 int ubifs_lookup_level0(struct ubifs_info *c, const union ubifs_key *key,
1215 			struct ubifs_znode **zn, int *n)
1216 {
1217 	int err, exact;
1218 	struct ubifs_znode *znode;
1219 	time64_t time = ktime_get_seconds();
1220 
1221 	dbg_tnck(key, "search key ");
1222 	ubifs_assert(c, key_type(c, key) < UBIFS_INVALID_KEY);
1223 
1224 	znode = c->zroot.znode;
1225 	if (unlikely(!znode)) {
1226 		znode = ubifs_load_znode(c, &c->zroot, NULL, 0);
1227 		if (IS_ERR(znode))
1228 			return PTR_ERR(znode);
1229 	}
1230 
1231 	znode->time = time;
1232 
1233 	while (1) {
1234 		struct ubifs_zbranch *zbr;
1235 
1236 		exact = ubifs_search_zbranch(c, znode, key, n);
1237 
1238 		if (znode->level == 0)
1239 			break;
1240 
1241 		if (*n < 0)
1242 			*n = 0;
1243 		zbr = &znode->zbranch[*n];
1244 
1245 		if (zbr->znode) {
1246 			znode->time = time;
1247 			znode = zbr->znode;
1248 			continue;
1249 		}
1250 
1251 		/* znode is not in TNC cache, load it from the media */
1252 		znode = ubifs_load_znode(c, zbr, znode, *n);
1253 		if (IS_ERR(znode))
1254 			return PTR_ERR(znode);
1255 	}
1256 
1257 	*zn = znode;
1258 	if (exact || !is_hash_key(c, key) || *n != -1) {
1259 		dbg_tnc("found %d, lvl %d, n %d", exact, znode->level, *n);
1260 		return exact;
1261 	}
1262 
1263 	/*
1264 	 * Here is a tricky place. We have not found the key and this is a
1265 	 * "hashed" key, which may collide. The rest of the code deals with
1266 	 * situations like this:
1267 	 *
1268 	 *                  | 3 | 5 |
1269 	 *                  /       \
1270 	 *          | 3 | 5 |      | 6 | 7 | (x)
1271 	 *
1272 	 * Or more a complex example:
1273 	 *
1274 	 *                | 1 | 5 |
1275 	 *                /       \
1276 	 *       | 1 | 3 |         | 5 | 8 |
1277 	 *              \           /
1278 	 *          | 5 | 5 |   | 6 | 7 | (x)
1279 	 *
1280 	 * In the examples, if we are looking for key "5", we may reach nodes
1281 	 * marked with "(x)". In this case what we have do is to look at the
1282 	 * left and see if there is "5" key there. If there is, we have to
1283 	 * return it.
1284 	 *
1285 	 * Note, this whole situation is possible because we allow to have
1286 	 * elements which are equivalent to the next key in the parent in the
1287 	 * children of current znode. For example, this happens if we split a
1288 	 * znode like this: | 3 | 5 | 5 | 6 | 7 |, which results in something
1289 	 * like this:
1290 	 *                      | 3 | 5 |
1291 	 *                       /     \
1292 	 *                | 3 | 5 |   | 5 | 6 | 7 |
1293 	 *                              ^
1294 	 * And this becomes what is at the first "picture" after key "5" marked
1295 	 * with "^" is removed. What could be done is we could prohibit
1296 	 * splitting in the middle of the colliding sequence. Also, when
1297 	 * removing the leftmost key, we would have to correct the key of the
1298 	 * parent node, which would introduce additional complications. Namely,
1299 	 * if we changed the leftmost key of the parent znode, the garbage
1300 	 * collector would be unable to find it (GC is doing this when GC'ing
1301 	 * indexing LEBs). Although we already have an additional RB-tree where
1302 	 * we save such changed znodes (see 'ins_clr_old_idx_znode()') until
1303 	 * after the commit. But anyway, this does not look easy to implement
1304 	 * so we did not try this.
1305 	 */
1306 	err = tnc_prev(c, &znode, n);
1307 	if (err == -ENOENT) {
1308 		dbg_tnc("found 0, lvl %d, n -1", znode->level);
1309 		*n = -1;
1310 		return 0;
1311 	}
1312 	if (unlikely(err < 0))
1313 		return err;
1314 	if (keys_cmp(c, key, &znode->zbranch[*n].key)) {
1315 		dbg_tnc("found 0, lvl %d, n -1", znode->level);
1316 		*n = -1;
1317 		return 0;
1318 	}
1319 
1320 	dbg_tnc("found 1, lvl %d, n %d", znode->level, *n);
1321 	*zn = znode;
1322 	return 1;
1323 }
1324 
1325 /**
1326  * lookup_level0_dirty - search for zero-level znode dirtying.
1327  * @c: UBIFS file-system description object
1328  * @key:  key to lookup
1329  * @zn: znode is returned here
1330  * @n: znode branch slot number is returned here
1331  *
1332  * This function looks up the TNC tree and search for zero-level znode which
1333  * refers key @key. The found zero-level znode is returned in @zn. There are 3
1334  * cases:
1335  *   o exact match, i.e. the found zero-level znode contains key @key, then %1
1336  *     is returned and slot number of the matched branch is stored in @n;
1337  *   o not exact match, which means that zero-level znode does not contain @key
1338  *     then %0 is returned and slot number of the closed branch is stored in
1339  *     @n;
1340  *   o @key is so small that it is even less than the lowest key of the
1341  *     leftmost zero-level node, then %0 is returned and %-1 is stored in @n.
1342  *
1343  * Additionally all znodes in the path from the root to the located zero-level
1344  * znode are marked as dirty.
1345  *
1346  * Note, when the TNC tree is traversed, some znodes may be absent, then this
1347  * function reads corresponding indexing nodes and inserts them to TNC. In
1348  * case of failure, a negative error code is returned.
1349  */
lookup_level0_dirty(struct ubifs_info * c,const union ubifs_key * key,struct ubifs_znode ** zn,int * n)1350 static int lookup_level0_dirty(struct ubifs_info *c, const union ubifs_key *key,
1351 			       struct ubifs_znode **zn, int *n)
1352 {
1353 	int err, exact;
1354 	struct ubifs_znode *znode;
1355 	time64_t time = ktime_get_seconds();
1356 
1357 	dbg_tnck(key, "search and dirty key ");
1358 
1359 	znode = c->zroot.znode;
1360 	if (unlikely(!znode)) {
1361 		znode = ubifs_load_znode(c, &c->zroot, NULL, 0);
1362 		if (IS_ERR(znode))
1363 			return PTR_ERR(znode);
1364 	}
1365 
1366 	znode = dirty_cow_znode(c, &c->zroot);
1367 	if (IS_ERR(znode))
1368 		return PTR_ERR(znode);
1369 
1370 	znode->time = time;
1371 
1372 	while (1) {
1373 		struct ubifs_zbranch *zbr;
1374 
1375 		exact = ubifs_search_zbranch(c, znode, key, n);
1376 
1377 		if (znode->level == 0)
1378 			break;
1379 
1380 		if (*n < 0)
1381 			*n = 0;
1382 		zbr = &znode->zbranch[*n];
1383 
1384 		if (zbr->znode) {
1385 			znode->time = time;
1386 			znode = dirty_cow_znode(c, zbr);
1387 			if (IS_ERR(znode))
1388 				return PTR_ERR(znode);
1389 			continue;
1390 		}
1391 
1392 		/* znode is not in TNC cache, load it from the media */
1393 		znode = ubifs_load_znode(c, zbr, znode, *n);
1394 		if (IS_ERR(znode))
1395 			return PTR_ERR(znode);
1396 		znode = dirty_cow_znode(c, zbr);
1397 		if (IS_ERR(znode))
1398 			return PTR_ERR(znode);
1399 	}
1400 
1401 	*zn = znode;
1402 	if (exact || !is_hash_key(c, key) || *n != -1) {
1403 		dbg_tnc("found %d, lvl %d, n %d", exact, znode->level, *n);
1404 		return exact;
1405 	}
1406 
1407 	/*
1408 	 * See huge comment at 'lookup_level0_dirty()' what is the rest of the
1409 	 * code.
1410 	 */
1411 	err = tnc_prev(c, &znode, n);
1412 	if (err == -ENOENT) {
1413 		*n = -1;
1414 		dbg_tnc("found 0, lvl %d, n -1", znode->level);
1415 		return 0;
1416 	}
1417 	if (unlikely(err < 0))
1418 		return err;
1419 	if (keys_cmp(c, key, &znode->zbranch[*n].key)) {
1420 		*n = -1;
1421 		dbg_tnc("found 0, lvl %d, n -1", znode->level);
1422 		return 0;
1423 	}
1424 
1425 	if (znode->cnext || !ubifs_zn_dirty(znode)) {
1426 		znode = dirty_cow_bottom_up(c, znode);
1427 		if (IS_ERR(znode))
1428 			return PTR_ERR(znode);
1429 	}
1430 
1431 	dbg_tnc("found 1, lvl %d, n %d", znode->level, *n);
1432 	*zn = znode;
1433 	return 1;
1434 }
1435 
1436 /**
1437  * maybe_leb_gced - determine if a LEB may have been garbage collected.
1438  * @c: UBIFS file-system description object
1439  * @lnum: LEB number
1440  * @gc_seq1: garbage collection sequence number
1441  *
1442  * This function determines if @lnum may have been garbage collected since
1443  * sequence number @gc_seq1. If it may have been then %1 is returned, otherwise
1444  * %0 is returned.
1445  */
maybe_leb_gced(struct ubifs_info * c,int lnum,int gc_seq1)1446 static int maybe_leb_gced(struct ubifs_info *c, int lnum, int gc_seq1)
1447 {
1448 	int gc_seq2, gced_lnum;
1449 
1450 	gced_lnum = c->gced_lnum;
1451 	smp_rmb();
1452 	gc_seq2 = c->gc_seq;
1453 	/* Same seq means no GC */
1454 	if (gc_seq1 == gc_seq2)
1455 		return 0;
1456 	/* Different by more than 1 means we don't know */
1457 	if (gc_seq1 + 1 != gc_seq2)
1458 		return 1;
1459 	/*
1460 	 * We have seen the sequence number has increased by 1. Now we need to
1461 	 * be sure we read the right LEB number, so read it again.
1462 	 */
1463 	smp_rmb();
1464 	if (gced_lnum != c->gced_lnum)
1465 		return 1;
1466 	/* Finally we can check lnum */
1467 	if (gced_lnum == lnum)
1468 		return 1;
1469 	return 0;
1470 }
1471 
1472 /**
1473  * ubifs_tnc_locate - look up a file-system node and return it and its location.
1474  * @c: UBIFS file-system description object
1475  * @key: node key to lookup
1476  * @node: the node is returned here
1477  * @lnum: LEB number is returned here
1478  * @offs: offset is returned here
1479  *
1480  * This function looks up and reads node with key @key. The caller has to make
1481  * sure the @node buffer is large enough to fit the node. Returns zero in case
1482  * of success, %-ENOENT if the node was not found, and a negative error code in
1483  * case of failure. The node location can be returned in @lnum and @offs.
1484  */
ubifs_tnc_locate(struct ubifs_info * c,const union ubifs_key * key,void * node,int * lnum,int * offs)1485 int ubifs_tnc_locate(struct ubifs_info *c, const union ubifs_key *key,
1486 		     void *node, int *lnum, int *offs)
1487 {
1488 	int found, n, err, safely = 0, gc_seq1;
1489 	struct ubifs_znode *znode;
1490 	struct ubifs_zbranch zbr, *zt;
1491 
1492 again:
1493 	mutex_lock(&c->tnc_mutex);
1494 	found = ubifs_lookup_level0(c, key, &znode, &n);
1495 	if (!found) {
1496 		err = -ENOENT;
1497 		goto out;
1498 	} else if (found < 0) {
1499 		err = found;
1500 		goto out;
1501 	}
1502 	zt = &znode->zbranch[n];
1503 	if (lnum) {
1504 		*lnum = zt->lnum;
1505 		*offs = zt->offs;
1506 	}
1507 	if (is_hash_key(c, key)) {
1508 		/*
1509 		 * In this case the leaf node cache gets used, so we pass the
1510 		 * address of the zbranch and keep the mutex locked
1511 		 */
1512 		err = tnc_read_hashed_node(c, zt, node);
1513 		goto out;
1514 	}
1515 	if (safely) {
1516 		err = ubifs_tnc_read_node(c, zt, node);
1517 		goto out;
1518 	}
1519 	/* Drop the TNC mutex prematurely and race with garbage collection */
1520 	zbr = znode->zbranch[n];
1521 	gc_seq1 = c->gc_seq;
1522 	mutex_unlock(&c->tnc_mutex);
1523 
1524 	if (ubifs_get_wbuf(c, zbr.lnum)) {
1525 		/* We do not GC journal heads */
1526 		err = ubifs_tnc_read_node(c, &zbr, node);
1527 		return err;
1528 	}
1529 
1530 	err = fallible_read_node(c, key, &zbr, node);
1531 	if (err <= 0 || maybe_leb_gced(c, zbr.lnum, gc_seq1)) {
1532 		/*
1533 		 * The node may have been GC'ed out from under us so try again
1534 		 * while keeping the TNC mutex locked.
1535 		 */
1536 		safely = 1;
1537 		goto again;
1538 	}
1539 	return 0;
1540 
1541 out:
1542 	mutex_unlock(&c->tnc_mutex);
1543 	return err;
1544 }
1545 
1546 /**
1547  * ubifs_tnc_get_bu_keys - lookup keys for bulk-read.
1548  * @c: UBIFS file-system description object
1549  * @bu: bulk-read parameters and results
1550  *
1551  * Lookup consecutive data node keys for the same inode that reside
1552  * consecutively in the same LEB. This function returns zero in case of success
1553  * and a negative error code in case of failure.
1554  *
1555  * Note, if the bulk-read buffer length (@bu->buf_len) is known, this function
1556  * makes sure bulk-read nodes fit the buffer. Otherwise, this function prepares
1557  * maximum possible amount of nodes for bulk-read.
1558  */
ubifs_tnc_get_bu_keys(struct ubifs_info * c,struct bu_info * bu)1559 int ubifs_tnc_get_bu_keys(struct ubifs_info *c, struct bu_info *bu)
1560 {
1561 	int n, err = 0, lnum = -1, offs;
1562 	int len;
1563 	unsigned int block = key_block(c, &bu->key);
1564 	struct ubifs_znode *znode;
1565 
1566 	bu->cnt = 0;
1567 	bu->blk_cnt = 0;
1568 	bu->eof = 0;
1569 
1570 	mutex_lock(&c->tnc_mutex);
1571 	/* Find first key */
1572 	err = ubifs_lookup_level0(c, &bu->key, &znode, &n);
1573 	if (err < 0)
1574 		goto out;
1575 	if (err) {
1576 		/* Key found */
1577 		len = znode->zbranch[n].len;
1578 		/* The buffer must be big enough for at least 1 node */
1579 		if (len > bu->buf_len) {
1580 			err = -EINVAL;
1581 			goto out;
1582 		}
1583 		/* Add this key */
1584 		bu->zbranch[bu->cnt++] = znode->zbranch[n];
1585 		bu->blk_cnt += 1;
1586 		lnum = znode->zbranch[n].lnum;
1587 		offs = ALIGN(znode->zbranch[n].offs + len, 8);
1588 	}
1589 	while (1) {
1590 		struct ubifs_zbranch *zbr;
1591 		union ubifs_key *key;
1592 		unsigned int next_block;
1593 
1594 		/* Find next key */
1595 		err = tnc_next(c, &znode, &n);
1596 		if (err)
1597 			goto out;
1598 		zbr = &znode->zbranch[n];
1599 		key = &zbr->key;
1600 		/* See if there is another data key for this file */
1601 		if (key_inum(c, key) != key_inum(c, &bu->key) ||
1602 		    key_type(c, key) != UBIFS_DATA_KEY) {
1603 			err = -ENOENT;
1604 			goto out;
1605 		}
1606 		if (lnum < 0) {
1607 			/* First key found */
1608 			lnum = zbr->lnum;
1609 			offs = ALIGN(zbr->offs + zbr->len, 8);
1610 			len = zbr->len;
1611 			if (len > bu->buf_len) {
1612 				err = -EINVAL;
1613 				goto out;
1614 			}
1615 		} else {
1616 			/*
1617 			 * The data nodes must be in consecutive positions in
1618 			 * the same LEB.
1619 			 */
1620 			if (zbr->lnum != lnum || zbr->offs != offs)
1621 				goto out;
1622 			offs += ALIGN(zbr->len, 8);
1623 			len = ALIGN(len, 8) + zbr->len;
1624 			/* Must not exceed buffer length */
1625 			if (len > bu->buf_len)
1626 				goto out;
1627 		}
1628 		/* Allow for holes */
1629 		next_block = key_block(c, key);
1630 		bu->blk_cnt += (next_block - block - 1);
1631 		if (bu->blk_cnt >= UBIFS_MAX_BULK_READ)
1632 			goto out;
1633 		block = next_block;
1634 		/* Add this key */
1635 		bu->zbranch[bu->cnt++] = *zbr;
1636 		bu->blk_cnt += 1;
1637 		/* See if we have room for more */
1638 		if (bu->cnt >= UBIFS_MAX_BULK_READ)
1639 			goto out;
1640 		if (bu->blk_cnt >= UBIFS_MAX_BULK_READ)
1641 			goto out;
1642 	}
1643 out:
1644 	if (err == -ENOENT) {
1645 		bu->eof = 1;
1646 		err = 0;
1647 	}
1648 	bu->gc_seq = c->gc_seq;
1649 	mutex_unlock(&c->tnc_mutex);
1650 	if (err)
1651 		return err;
1652 	/*
1653 	 * An enormous hole could cause bulk-read to encompass too many
1654 	 * page cache pages, so limit the number here.
1655 	 */
1656 	if (bu->blk_cnt > UBIFS_MAX_BULK_READ)
1657 		bu->blk_cnt = UBIFS_MAX_BULK_READ;
1658 	/*
1659 	 * Ensure that bulk-read covers a whole number of page cache
1660 	 * pages.
1661 	 */
1662 	if (UBIFS_BLOCKS_PER_PAGE == 1 ||
1663 	    !(bu->blk_cnt & (UBIFS_BLOCKS_PER_PAGE - 1)))
1664 		return 0;
1665 	if (bu->eof) {
1666 		/* At the end of file we can round up */
1667 		bu->blk_cnt += UBIFS_BLOCKS_PER_PAGE - 1;
1668 		return 0;
1669 	}
1670 	/* Exclude data nodes that do not make up a whole page cache page */
1671 	block = key_block(c, &bu->key) + bu->blk_cnt;
1672 	block &= ~(UBIFS_BLOCKS_PER_PAGE - 1);
1673 	while (bu->cnt) {
1674 		if (key_block(c, &bu->zbranch[bu->cnt - 1].key) < block)
1675 			break;
1676 		bu->cnt -= 1;
1677 	}
1678 	return 0;
1679 }
1680 
1681 /**
1682  * read_wbuf - bulk-read from a LEB with a wbuf.
1683  * @wbuf: wbuf that may overlap the read
1684  * @buf: buffer into which to read
1685  * @len: read length
1686  * @lnum: LEB number from which to read
1687  * @offs: offset from which to read
1688  *
1689  * This functions returns %0 on success or a negative error code on failure.
1690  */
read_wbuf(struct ubifs_wbuf * wbuf,void * buf,int len,int lnum,int offs)1691 static int read_wbuf(struct ubifs_wbuf *wbuf, void *buf, int len, int lnum,
1692 		     int offs)
1693 {
1694 	const struct ubifs_info *c = wbuf->c;
1695 	int rlen, overlap;
1696 
1697 	dbg_io("LEB %d:%d, length %d", lnum, offs, len);
1698 	ubifs_assert(c, wbuf && lnum >= 0 && lnum < c->leb_cnt && offs >= 0);
1699 	ubifs_assert(c, !(offs & 7) && offs < c->leb_size);
1700 	ubifs_assert(c, offs + len <= c->leb_size);
1701 
1702 	spin_lock(&wbuf->lock);
1703 	overlap = (lnum == wbuf->lnum && offs + len > wbuf->offs);
1704 	if (!overlap) {
1705 		/* We may safely unlock the write-buffer and read the data */
1706 		spin_unlock(&wbuf->lock);
1707 		return ubifs_leb_read(c, lnum, buf, offs, len, 0);
1708 	}
1709 
1710 	/* Don't read under wbuf */
1711 	rlen = wbuf->offs - offs;
1712 	if (rlen < 0)
1713 		rlen = 0;
1714 
1715 	/* Copy the rest from the write-buffer */
1716 	memcpy(buf + rlen, wbuf->buf + offs + rlen - wbuf->offs, len - rlen);
1717 	spin_unlock(&wbuf->lock);
1718 
1719 	if (rlen > 0)
1720 		/* Read everything that goes before write-buffer */
1721 		return ubifs_leb_read(c, lnum, buf, offs, rlen, 0);
1722 
1723 	return 0;
1724 }
1725 
1726 /**
1727  * validate_data_node - validate data nodes for bulk-read.
1728  * @c: UBIFS file-system description object
1729  * @buf: buffer containing data node to validate
1730  * @zbr: zbranch of data node to validate
1731  *
1732  * This functions returns %0 on success or a negative error code on failure.
1733  */
validate_data_node(struct ubifs_info * c,void * buf,struct ubifs_zbranch * zbr)1734 static int validate_data_node(struct ubifs_info *c, void *buf,
1735 			      struct ubifs_zbranch *zbr)
1736 {
1737 	union ubifs_key key1;
1738 	struct ubifs_ch *ch = buf;
1739 	int err, len;
1740 
1741 	if (ch->node_type != UBIFS_DATA_NODE) {
1742 		ubifs_err(c, "bad node type (%d but expected %d)",
1743 			  ch->node_type, UBIFS_DATA_NODE);
1744 		goto out_err;
1745 	}
1746 
1747 	err = ubifs_check_node(c, buf, zbr->lnum, zbr->offs, 0, 0);
1748 	if (err) {
1749 		ubifs_err(c, "expected node type %d", UBIFS_DATA_NODE);
1750 		goto out;
1751 	}
1752 
1753 	len = le32_to_cpu(ch->len);
1754 	if (len != zbr->len) {
1755 		ubifs_err(c, "bad node length %d, expected %d", len, zbr->len);
1756 		goto out_err;
1757 	}
1758 
1759 	/* Make sure the key of the read node is correct */
1760 	key_read(c, buf + UBIFS_KEY_OFFSET, &key1);
1761 	if (!keys_eq(c, &zbr->key, &key1)) {
1762 		ubifs_err(c, "bad key in node at LEB %d:%d",
1763 			  zbr->lnum, zbr->offs);
1764 		dbg_tnck(&zbr->key, "looked for key ");
1765 		dbg_tnck(&key1, "found node's key ");
1766 		goto out_err;
1767 	}
1768 
1769 	return 0;
1770 
1771 out_err:
1772 	err = -EINVAL;
1773 out:
1774 	ubifs_err(c, "bad node at LEB %d:%d", zbr->lnum, zbr->offs);
1775 	ubifs_dump_node(c, buf);
1776 	dump_stack();
1777 	return err;
1778 }
1779 
1780 /**
1781  * ubifs_tnc_bulk_read - read a number of data nodes in one go.
1782  * @c: UBIFS file-system description object
1783  * @bu: bulk-read parameters and results
1784  *
1785  * This functions reads and validates the data nodes that were identified by the
1786  * 'ubifs_tnc_get_bu_keys()' function. This functions returns %0 on success,
1787  * -EAGAIN to indicate a race with GC, or another negative error code on
1788  * failure.
1789  */
ubifs_tnc_bulk_read(struct ubifs_info * c,struct bu_info * bu)1790 int ubifs_tnc_bulk_read(struct ubifs_info *c, struct bu_info *bu)
1791 {
1792 	int lnum = bu->zbranch[0].lnum, offs = bu->zbranch[0].offs, len, err, i;
1793 	struct ubifs_wbuf *wbuf;
1794 	void *buf;
1795 
1796 	len = bu->zbranch[bu->cnt - 1].offs;
1797 	len += bu->zbranch[bu->cnt - 1].len - offs;
1798 	if (len > bu->buf_len) {
1799 		ubifs_err(c, "buffer too small %d vs %d", bu->buf_len, len);
1800 		return -EINVAL;
1801 	}
1802 
1803 	/* Do the read */
1804 	wbuf = ubifs_get_wbuf(c, lnum);
1805 	if (wbuf)
1806 		err = read_wbuf(wbuf, bu->buf, len, lnum, offs);
1807 	else
1808 		err = ubifs_leb_read(c, lnum, bu->buf, offs, len, 0);
1809 
1810 	/* Check for a race with GC */
1811 	if (maybe_leb_gced(c, lnum, bu->gc_seq))
1812 		return -EAGAIN;
1813 
1814 	if (err && err != -EBADMSG) {
1815 		ubifs_err(c, "failed to read from LEB %d:%d, error %d",
1816 			  lnum, offs, err);
1817 		dump_stack();
1818 		dbg_tnck(&bu->key, "key ");
1819 		return err;
1820 	}
1821 
1822 	/* Validate the nodes read */
1823 	buf = bu->buf;
1824 	for (i = 0; i < bu->cnt; i++) {
1825 		err = validate_data_node(c, buf, &bu->zbranch[i]);
1826 		if (err)
1827 			return err;
1828 		buf = buf + ALIGN(bu->zbranch[i].len, 8);
1829 	}
1830 
1831 	return 0;
1832 }
1833 
1834 /**
1835  * do_lookup_nm- look up a "hashed" node.
1836  * @c: UBIFS file-system description object
1837  * @key: node key to lookup
1838  * @node: the node is returned here
1839  * @nm: node name
1840  *
1841  * This function looks up and reads a node which contains name hash in the key.
1842  * Since the hash may have collisions, there may be many nodes with the same
1843  * key, so we have to sequentially look to all of them until the needed one is
1844  * found. This function returns zero in case of success, %-ENOENT if the node
1845  * was not found, and a negative error code in case of failure.
1846  */
do_lookup_nm(struct ubifs_info * c,const union ubifs_key * key,void * node,const struct fscrypt_name * nm)1847 static int do_lookup_nm(struct ubifs_info *c, const union ubifs_key *key,
1848 			void *node, const struct fscrypt_name *nm)
1849 {
1850 	int found, n, err;
1851 	struct ubifs_znode *znode;
1852 
1853 	dbg_tnck(key, "key ");
1854 	mutex_lock(&c->tnc_mutex);
1855 	found = ubifs_lookup_level0(c, key, &znode, &n);
1856 	if (!found) {
1857 		err = -ENOENT;
1858 		goto out_unlock;
1859 	} else if (found < 0) {
1860 		err = found;
1861 		goto out_unlock;
1862 	}
1863 
1864 	ubifs_assert(c, n >= 0);
1865 
1866 	err = resolve_collision(c, key, &znode, &n, nm);
1867 	dbg_tnc("rc returned %d, znode %p, n %d", err, znode, n);
1868 	if (unlikely(err < 0))
1869 		goto out_unlock;
1870 	if (err == 0) {
1871 		err = -ENOENT;
1872 		goto out_unlock;
1873 	}
1874 
1875 	err = tnc_read_hashed_node(c, &znode->zbranch[n], node);
1876 
1877 out_unlock:
1878 	mutex_unlock(&c->tnc_mutex);
1879 	return err;
1880 }
1881 
1882 /**
1883  * ubifs_tnc_lookup_nm - look up a "hashed" node.
1884  * @c: UBIFS file-system description object
1885  * @key: node key to lookup
1886  * @node: the node is returned here
1887  * @nm: node name
1888  *
1889  * This function looks up and reads a node which contains name hash in the key.
1890  * Since the hash may have collisions, there may be many nodes with the same
1891  * key, so we have to sequentially look to all of them until the needed one is
1892  * found. This function returns zero in case of success, %-ENOENT if the node
1893  * was not found, and a negative error code in case of failure.
1894  */
ubifs_tnc_lookup_nm(struct ubifs_info * c,const union ubifs_key * key,void * node,const struct fscrypt_name * nm)1895 int ubifs_tnc_lookup_nm(struct ubifs_info *c, const union ubifs_key *key,
1896 			void *node, const struct fscrypt_name *nm)
1897 {
1898 	int err, len;
1899 	const struct ubifs_dent_node *dent = node;
1900 
1901 	/*
1902 	 * We assume that in most of the cases there are no name collisions and
1903 	 * 'ubifs_tnc_lookup()' returns us the right direntry.
1904 	 */
1905 	err = ubifs_tnc_lookup(c, key, node);
1906 	if (err)
1907 		return err;
1908 
1909 	len = le16_to_cpu(dent->nlen);
1910 	if (fname_len(nm) == len && !memcmp(dent->name, fname_name(nm), len))
1911 		return 0;
1912 
1913 	/*
1914 	 * Unluckily, there are hash collisions and we have to iterate over
1915 	 * them look at each direntry with colliding name hash sequentially.
1916 	 */
1917 
1918 	return do_lookup_nm(c, key, node, nm);
1919 }
1920 
search_dh_cookie(struct ubifs_info * c,const union ubifs_key * key,struct ubifs_dent_node * dent,uint32_t cookie,struct ubifs_znode ** zn,int * n,int exact)1921 static int search_dh_cookie(struct ubifs_info *c, const union ubifs_key *key,
1922 			    struct ubifs_dent_node *dent, uint32_t cookie,
1923 			    struct ubifs_znode **zn, int *n, int exact)
1924 {
1925 	int err;
1926 	struct ubifs_znode *znode = *zn;
1927 	struct ubifs_zbranch *zbr;
1928 	union ubifs_key *dkey;
1929 
1930 	if (!exact) {
1931 		err = tnc_next(c, &znode, n);
1932 		if (err)
1933 			return err;
1934 	}
1935 
1936 	for (;;) {
1937 		zbr = &znode->zbranch[*n];
1938 		dkey = &zbr->key;
1939 
1940 		if (key_inum(c, dkey) != key_inum(c, key) ||
1941 		    key_type(c, dkey) != key_type(c, key)) {
1942 			return -ENOENT;
1943 		}
1944 
1945 		err = tnc_read_hashed_node(c, zbr, dent);
1946 		if (err)
1947 			return err;
1948 
1949 		if (key_hash(c, key) == key_hash(c, dkey) &&
1950 		    le32_to_cpu(dent->cookie) == cookie) {
1951 			*zn = znode;
1952 			return 0;
1953 		}
1954 
1955 		err = tnc_next(c, &znode, n);
1956 		if (err)
1957 			return err;
1958 	}
1959 }
1960 
do_lookup_dh(struct ubifs_info * c,const union ubifs_key * key,struct ubifs_dent_node * dent,uint32_t cookie)1961 static int do_lookup_dh(struct ubifs_info *c, const union ubifs_key *key,
1962 			struct ubifs_dent_node *dent, uint32_t cookie)
1963 {
1964 	int n, err;
1965 	struct ubifs_znode *znode;
1966 	union ubifs_key start_key;
1967 
1968 	ubifs_assert(c, is_hash_key(c, key));
1969 
1970 	lowest_dent_key(c, &start_key, key_inum(c, key));
1971 
1972 	mutex_lock(&c->tnc_mutex);
1973 	err = ubifs_lookup_level0(c, &start_key, &znode, &n);
1974 	if (unlikely(err < 0))
1975 		goto out_unlock;
1976 
1977 	err = search_dh_cookie(c, key, dent, cookie, &znode, &n, err);
1978 
1979 out_unlock:
1980 	mutex_unlock(&c->tnc_mutex);
1981 	return err;
1982 }
1983 
1984 /**
1985  * ubifs_tnc_lookup_dh - look up a "double hashed" node.
1986  * @c: UBIFS file-system description object
1987  * @key: node key to lookup
1988  * @node: the node is returned here
1989  * @cookie: node cookie for collision resolution
1990  *
1991  * This function looks up and reads a node which contains name hash in the key.
1992  * Since the hash may have collisions, there may be many nodes with the same
1993  * key, so we have to sequentially look to all of them until the needed one
1994  * with the same cookie value is found.
1995  * This function returns zero in case of success, %-ENOENT if the node
1996  * was not found, and a negative error code in case of failure.
1997  */
ubifs_tnc_lookup_dh(struct ubifs_info * c,const union ubifs_key * key,void * node,uint32_t cookie)1998 int ubifs_tnc_lookup_dh(struct ubifs_info *c, const union ubifs_key *key,
1999 			void *node, uint32_t cookie)
2000 {
2001 	int err;
2002 	const struct ubifs_dent_node *dent = node;
2003 
2004 	if (!c->double_hash)
2005 		return -EOPNOTSUPP;
2006 
2007 	/*
2008 	 * We assume that in most of the cases there are no name collisions and
2009 	 * 'ubifs_tnc_lookup()' returns us the right direntry.
2010 	 */
2011 	err = ubifs_tnc_lookup(c, key, node);
2012 	if (err)
2013 		return err;
2014 
2015 	if (le32_to_cpu(dent->cookie) == cookie)
2016 		return 0;
2017 
2018 	/*
2019 	 * Unluckily, there are hash collisions and we have to iterate over
2020 	 * them look at each direntry with colliding name hash sequentially.
2021 	 */
2022 	return do_lookup_dh(c, key, node, cookie);
2023 }
2024 
2025 /**
2026  * correct_parent_keys - correct parent znodes' keys.
2027  * @c: UBIFS file-system description object
2028  * @znode: znode to correct parent znodes for
2029  *
2030  * This is a helper function for 'tnc_insert()'. When the key of the leftmost
2031  * zbranch changes, keys of parent znodes have to be corrected. This helper
2032  * function is called in such situations and corrects the keys if needed.
2033  */
correct_parent_keys(const struct ubifs_info * c,struct ubifs_znode * znode)2034 static void correct_parent_keys(const struct ubifs_info *c,
2035 				struct ubifs_znode *znode)
2036 {
2037 	union ubifs_key *key, *key1;
2038 
2039 	ubifs_assert(c, znode->parent);
2040 	ubifs_assert(c, znode->iip == 0);
2041 
2042 	key = &znode->zbranch[0].key;
2043 	key1 = &znode->parent->zbranch[0].key;
2044 
2045 	while (keys_cmp(c, key, key1) < 0) {
2046 		key_copy(c, key, key1);
2047 		znode = znode->parent;
2048 		znode->alt = 1;
2049 		if (!znode->parent || znode->iip)
2050 			break;
2051 		key1 = &znode->parent->zbranch[0].key;
2052 	}
2053 }
2054 
2055 /**
2056  * insert_zbranch - insert a zbranch into a znode.
2057  * @c: UBIFS file-system description object
2058  * @znode: znode into which to insert
2059  * @zbr: zbranch to insert
2060  * @n: slot number to insert to
2061  *
2062  * This is a helper function for 'tnc_insert()'. UBIFS does not allow "gaps" in
2063  * znode's array of zbranches and keeps zbranches consolidated, so when a new
2064  * zbranch has to be inserted to the @znode->zbranches[]' array at the @n-th
2065  * slot, zbranches starting from @n have to be moved right.
2066  */
insert_zbranch(struct ubifs_info * c,struct ubifs_znode * znode,const struct ubifs_zbranch * zbr,int n)2067 static void insert_zbranch(struct ubifs_info *c, struct ubifs_znode *znode,
2068 			   const struct ubifs_zbranch *zbr, int n)
2069 {
2070 	int i;
2071 
2072 	ubifs_assert(c, ubifs_zn_dirty(znode));
2073 
2074 	if (znode->level) {
2075 		for (i = znode->child_cnt; i > n; i--) {
2076 			znode->zbranch[i] = znode->zbranch[i - 1];
2077 			if (znode->zbranch[i].znode)
2078 				znode->zbranch[i].znode->iip = i;
2079 		}
2080 		if (zbr->znode)
2081 			zbr->znode->iip = n;
2082 	} else
2083 		for (i = znode->child_cnt; i > n; i--)
2084 			znode->zbranch[i] = znode->zbranch[i - 1];
2085 
2086 	znode->zbranch[n] = *zbr;
2087 	znode->child_cnt += 1;
2088 
2089 	/*
2090 	 * After inserting at slot zero, the lower bound of the key range of
2091 	 * this znode may have changed. If this znode is subsequently split
2092 	 * then the upper bound of the key range may change, and furthermore
2093 	 * it could change to be lower than the original lower bound. If that
2094 	 * happens, then it will no longer be possible to find this znode in the
2095 	 * TNC using the key from the index node on flash. That is bad because
2096 	 * if it is not found, we will assume it is obsolete and may overwrite
2097 	 * it. Then if there is an unclean unmount, we will start using the
2098 	 * old index which will be broken.
2099 	 *
2100 	 * So we first mark znodes that have insertions at slot zero, and then
2101 	 * if they are split we add their lnum/offs to the old_idx tree.
2102 	 */
2103 	if (n == 0)
2104 		znode->alt = 1;
2105 }
2106 
2107 /**
2108  * tnc_insert - insert a node into TNC.
2109  * @c: UBIFS file-system description object
2110  * @znode: znode to insert into
2111  * @zbr: branch to insert
2112  * @n: slot number to insert new zbranch to
2113  *
2114  * This function inserts a new node described by @zbr into znode @znode. If
2115  * znode does not have a free slot for new zbranch, it is split. Parent znodes
2116  * are splat as well if needed. Returns zero in case of success or a negative
2117  * error code in case of failure.
2118  */
tnc_insert(struct ubifs_info * c,struct ubifs_znode * znode,struct ubifs_zbranch * zbr,int n)2119 static int tnc_insert(struct ubifs_info *c, struct ubifs_znode *znode,
2120 		      struct ubifs_zbranch *zbr, int n)
2121 {
2122 	struct ubifs_znode *zn, *zi, *zp;
2123 	int i, keep, move, appending = 0;
2124 	union ubifs_key *key = &zbr->key, *key1;
2125 
2126 	ubifs_assert(c, n >= 0 && n <= c->fanout);
2127 
2128 	/* Implement naive insert for now */
2129 again:
2130 	zp = znode->parent;
2131 	if (znode->child_cnt < c->fanout) {
2132 		ubifs_assert(c, n != c->fanout);
2133 		dbg_tnck(key, "inserted at %d level %d, key ", n, znode->level);
2134 
2135 		insert_zbranch(c, znode, zbr, n);
2136 
2137 		/* Ensure parent's key is correct */
2138 		if (n == 0 && zp && znode->iip == 0)
2139 			correct_parent_keys(c, znode);
2140 
2141 		return 0;
2142 	}
2143 
2144 	/*
2145 	 * Unfortunately, @znode does not have more empty slots and we have to
2146 	 * split it.
2147 	 */
2148 	dbg_tnck(key, "splitting level %d, key ", znode->level);
2149 
2150 	if (znode->alt)
2151 		/*
2152 		 * We can no longer be sure of finding this znode by key, so we
2153 		 * record it in the old_idx tree.
2154 		 */
2155 		ins_clr_old_idx_znode(c, znode);
2156 
2157 	zn = kzalloc(c->max_znode_sz, GFP_NOFS);
2158 	if (!zn)
2159 		return -ENOMEM;
2160 	zn->parent = zp;
2161 	zn->level = znode->level;
2162 
2163 	/* Decide where to split */
2164 	if (znode->level == 0 && key_type(c, key) == UBIFS_DATA_KEY) {
2165 		/* Try not to split consecutive data keys */
2166 		if (n == c->fanout) {
2167 			key1 = &znode->zbranch[n - 1].key;
2168 			if (key_inum(c, key1) == key_inum(c, key) &&
2169 			    key_type(c, key1) == UBIFS_DATA_KEY)
2170 				appending = 1;
2171 		} else
2172 			goto check_split;
2173 	} else if (appending && n != c->fanout) {
2174 		/* Try not to split consecutive data keys */
2175 		appending = 0;
2176 check_split:
2177 		if (n >= (c->fanout + 1) / 2) {
2178 			key1 = &znode->zbranch[0].key;
2179 			if (key_inum(c, key1) == key_inum(c, key) &&
2180 			    key_type(c, key1) == UBIFS_DATA_KEY) {
2181 				key1 = &znode->zbranch[n].key;
2182 				if (key_inum(c, key1) != key_inum(c, key) ||
2183 				    key_type(c, key1) != UBIFS_DATA_KEY) {
2184 					keep = n;
2185 					move = c->fanout - keep;
2186 					zi = znode;
2187 					goto do_split;
2188 				}
2189 			}
2190 		}
2191 	}
2192 
2193 	if (appending) {
2194 		keep = c->fanout;
2195 		move = 0;
2196 	} else {
2197 		keep = (c->fanout + 1) / 2;
2198 		move = c->fanout - keep;
2199 	}
2200 
2201 	/*
2202 	 * Although we don't at present, we could look at the neighbors and see
2203 	 * if we can move some zbranches there.
2204 	 */
2205 
2206 	if (n < keep) {
2207 		/* Insert into existing znode */
2208 		zi = znode;
2209 		move += 1;
2210 		keep -= 1;
2211 	} else {
2212 		/* Insert into new znode */
2213 		zi = zn;
2214 		n -= keep;
2215 		/* Re-parent */
2216 		if (zn->level != 0)
2217 			zbr->znode->parent = zn;
2218 	}
2219 
2220 do_split:
2221 
2222 	__set_bit(DIRTY_ZNODE, &zn->flags);
2223 	atomic_long_inc(&c->dirty_zn_cnt);
2224 
2225 	zn->child_cnt = move;
2226 	znode->child_cnt = keep;
2227 
2228 	dbg_tnc("moving %d, keeping %d", move, keep);
2229 
2230 	/* Move zbranch */
2231 	for (i = 0; i < move; i++) {
2232 		zn->zbranch[i] = znode->zbranch[keep + i];
2233 		/* Re-parent */
2234 		if (zn->level != 0)
2235 			if (zn->zbranch[i].znode) {
2236 				zn->zbranch[i].znode->parent = zn;
2237 				zn->zbranch[i].znode->iip = i;
2238 			}
2239 	}
2240 
2241 	/* Insert new key and branch */
2242 	dbg_tnck(key, "inserting at %d level %d, key ", n, zn->level);
2243 
2244 	insert_zbranch(c, zi, zbr, n);
2245 
2246 	/* Insert new znode (produced by spitting) into the parent */
2247 	if (zp) {
2248 		if (n == 0 && zi == znode && znode->iip == 0)
2249 			correct_parent_keys(c, znode);
2250 
2251 		/* Locate insertion point */
2252 		n = znode->iip + 1;
2253 
2254 		/* Tail recursion */
2255 		zbr->key = zn->zbranch[0].key;
2256 		zbr->znode = zn;
2257 		zbr->lnum = 0;
2258 		zbr->offs = 0;
2259 		zbr->len = 0;
2260 		znode = zp;
2261 
2262 		goto again;
2263 	}
2264 
2265 	/* We have to split root znode */
2266 	dbg_tnc("creating new zroot at level %d", znode->level + 1);
2267 
2268 	zi = kzalloc(c->max_znode_sz, GFP_NOFS);
2269 	if (!zi)
2270 		return -ENOMEM;
2271 
2272 	zi->child_cnt = 2;
2273 	zi->level = znode->level + 1;
2274 
2275 	__set_bit(DIRTY_ZNODE, &zi->flags);
2276 	atomic_long_inc(&c->dirty_zn_cnt);
2277 
2278 	zi->zbranch[0].key = znode->zbranch[0].key;
2279 	zi->zbranch[0].znode = znode;
2280 	zi->zbranch[0].lnum = c->zroot.lnum;
2281 	zi->zbranch[0].offs = c->zroot.offs;
2282 	zi->zbranch[0].len = c->zroot.len;
2283 	zi->zbranch[1].key = zn->zbranch[0].key;
2284 	zi->zbranch[1].znode = zn;
2285 
2286 	c->zroot.lnum = 0;
2287 	c->zroot.offs = 0;
2288 	c->zroot.len = 0;
2289 	c->zroot.znode = zi;
2290 
2291 	zn->parent = zi;
2292 	zn->iip = 1;
2293 	znode->parent = zi;
2294 	znode->iip = 0;
2295 
2296 	return 0;
2297 }
2298 
2299 /**
2300  * ubifs_tnc_add - add a node to TNC.
2301  * @c: UBIFS file-system description object
2302  * @key: key to add
2303  * @lnum: LEB number of node
2304  * @offs: node offset
2305  * @len: node length
2306  *
2307  * This function adds a node with key @key to TNC. The node may be new or it may
2308  * obsolete some existing one. Returns %0 on success or negative error code on
2309  * failure.
2310  */
ubifs_tnc_add(struct ubifs_info * c,const union ubifs_key * key,int lnum,int offs,int len)2311 int ubifs_tnc_add(struct ubifs_info *c, const union ubifs_key *key, int lnum,
2312 		  int offs, int len)
2313 {
2314 	int found, n, err = 0;
2315 	struct ubifs_znode *znode;
2316 
2317 	mutex_lock(&c->tnc_mutex);
2318 	dbg_tnck(key, "%d:%d, len %d, key ", lnum, offs, len);
2319 	found = lookup_level0_dirty(c, key, &znode, &n);
2320 	if (!found) {
2321 		struct ubifs_zbranch zbr;
2322 
2323 		zbr.znode = NULL;
2324 		zbr.lnum = lnum;
2325 		zbr.offs = offs;
2326 		zbr.len = len;
2327 		key_copy(c, key, &zbr.key);
2328 		err = tnc_insert(c, znode, &zbr, n + 1);
2329 	} else if (found == 1) {
2330 		struct ubifs_zbranch *zbr = &znode->zbranch[n];
2331 
2332 		lnc_free(zbr);
2333 		err = ubifs_add_dirt(c, zbr->lnum, zbr->len);
2334 		zbr->lnum = lnum;
2335 		zbr->offs = offs;
2336 		zbr->len = len;
2337 	} else
2338 		err = found;
2339 	if (!err)
2340 		err = dbg_check_tnc(c, 0);
2341 	mutex_unlock(&c->tnc_mutex);
2342 
2343 	return err;
2344 }
2345 
2346 /**
2347  * ubifs_tnc_replace - replace a node in the TNC only if the old node is found.
2348  * @c: UBIFS file-system description object
2349  * @key: key to add
2350  * @old_lnum: LEB number of old node
2351  * @old_offs: old node offset
2352  * @lnum: LEB number of node
2353  * @offs: node offset
2354  * @len: node length
2355  *
2356  * This function replaces a node with key @key in the TNC only if the old node
2357  * is found.  This function is called by garbage collection when node are moved.
2358  * Returns %0 on success or negative error code on failure.
2359  */
ubifs_tnc_replace(struct ubifs_info * c,const union ubifs_key * key,int old_lnum,int old_offs,int lnum,int offs,int len)2360 int ubifs_tnc_replace(struct ubifs_info *c, const union ubifs_key *key,
2361 		      int old_lnum, int old_offs, int lnum, int offs, int len)
2362 {
2363 	int found, n, err = 0;
2364 	struct ubifs_znode *znode;
2365 
2366 	mutex_lock(&c->tnc_mutex);
2367 	dbg_tnck(key, "old LEB %d:%d, new LEB %d:%d, len %d, key ", old_lnum,
2368 		 old_offs, lnum, offs, len);
2369 	found = lookup_level0_dirty(c, key, &znode, &n);
2370 	if (found < 0) {
2371 		err = found;
2372 		goto out_unlock;
2373 	}
2374 
2375 	if (found == 1) {
2376 		struct ubifs_zbranch *zbr = &znode->zbranch[n];
2377 
2378 		found = 0;
2379 		if (zbr->lnum == old_lnum && zbr->offs == old_offs) {
2380 			lnc_free(zbr);
2381 			err = ubifs_add_dirt(c, zbr->lnum, zbr->len);
2382 			if (err)
2383 				goto out_unlock;
2384 			zbr->lnum = lnum;
2385 			zbr->offs = offs;
2386 			zbr->len = len;
2387 			found = 1;
2388 		} else if (is_hash_key(c, key)) {
2389 			found = resolve_collision_directly(c, key, &znode, &n,
2390 							   old_lnum, old_offs);
2391 			dbg_tnc("rc returned %d, znode %p, n %d, LEB %d:%d",
2392 				found, znode, n, old_lnum, old_offs);
2393 			if (found < 0) {
2394 				err = found;
2395 				goto out_unlock;
2396 			}
2397 
2398 			if (found) {
2399 				/* Ensure the znode is dirtied */
2400 				if (znode->cnext || !ubifs_zn_dirty(znode)) {
2401 					znode = dirty_cow_bottom_up(c, znode);
2402 					if (IS_ERR(znode)) {
2403 						err = PTR_ERR(znode);
2404 						goto out_unlock;
2405 					}
2406 				}
2407 				zbr = &znode->zbranch[n];
2408 				lnc_free(zbr);
2409 				err = ubifs_add_dirt(c, zbr->lnum,
2410 						     zbr->len);
2411 				if (err)
2412 					goto out_unlock;
2413 				zbr->lnum = lnum;
2414 				zbr->offs = offs;
2415 				zbr->len = len;
2416 			}
2417 		}
2418 	}
2419 
2420 	if (!found)
2421 		err = ubifs_add_dirt(c, lnum, len);
2422 
2423 	if (!err)
2424 		err = dbg_check_tnc(c, 0);
2425 
2426 out_unlock:
2427 	mutex_unlock(&c->tnc_mutex);
2428 	return err;
2429 }
2430 
2431 /**
2432  * ubifs_tnc_add_nm - add a "hashed" node to TNC.
2433  * @c: UBIFS file-system description object
2434  * @key: key to add
2435  * @lnum: LEB number of node
2436  * @offs: node offset
2437  * @len: node length
2438  * @nm: node name
2439  *
2440  * This is the same as 'ubifs_tnc_add()' but it should be used with keys which
2441  * may have collisions, like directory entry keys.
2442  */
ubifs_tnc_add_nm(struct ubifs_info * c,const union ubifs_key * key,int lnum,int offs,int len,const struct fscrypt_name * nm)2443 int ubifs_tnc_add_nm(struct ubifs_info *c, const union ubifs_key *key,
2444 		     int lnum, int offs, int len,
2445 		     const struct fscrypt_name *nm)
2446 {
2447 	int found, n, err = 0;
2448 	struct ubifs_znode *znode;
2449 
2450 	mutex_lock(&c->tnc_mutex);
2451 	dbg_tnck(key, "LEB %d:%d, key ", lnum, offs);
2452 	found = lookup_level0_dirty(c, key, &znode, &n);
2453 	if (found < 0) {
2454 		err = found;
2455 		goto out_unlock;
2456 	}
2457 
2458 	if (found == 1) {
2459 		if (c->replaying)
2460 			found = fallible_resolve_collision(c, key, &znode, &n,
2461 							   nm, 1);
2462 		else
2463 			found = resolve_collision(c, key, &znode, &n, nm);
2464 		dbg_tnc("rc returned %d, znode %p, n %d", found, znode, n);
2465 		if (found < 0) {
2466 			err = found;
2467 			goto out_unlock;
2468 		}
2469 
2470 		/* Ensure the znode is dirtied */
2471 		if (znode->cnext || !ubifs_zn_dirty(znode)) {
2472 			znode = dirty_cow_bottom_up(c, znode);
2473 			if (IS_ERR(znode)) {
2474 				err = PTR_ERR(znode);
2475 				goto out_unlock;
2476 			}
2477 		}
2478 
2479 		if (found == 1) {
2480 			struct ubifs_zbranch *zbr = &znode->zbranch[n];
2481 
2482 			lnc_free(zbr);
2483 			err = ubifs_add_dirt(c, zbr->lnum, zbr->len);
2484 			zbr->lnum = lnum;
2485 			zbr->offs = offs;
2486 			zbr->len = len;
2487 			goto out_unlock;
2488 		}
2489 	}
2490 
2491 	if (!found) {
2492 		struct ubifs_zbranch zbr;
2493 
2494 		zbr.znode = NULL;
2495 		zbr.lnum = lnum;
2496 		zbr.offs = offs;
2497 		zbr.len = len;
2498 		key_copy(c, key, &zbr.key);
2499 		err = tnc_insert(c, znode, &zbr, n + 1);
2500 		if (err)
2501 			goto out_unlock;
2502 		if (c->replaying) {
2503 			/*
2504 			 * We did not find it in the index so there may be a
2505 			 * dangling branch still in the index. So we remove it
2506 			 * by passing 'ubifs_tnc_remove_nm()' the same key but
2507 			 * an unmatchable name.
2508 			 */
2509 			struct fscrypt_name noname = { .disk_name = { .name = "", .len = 1 } };
2510 
2511 			err = dbg_check_tnc(c, 0);
2512 			mutex_unlock(&c->tnc_mutex);
2513 			if (err)
2514 				return err;
2515 			return ubifs_tnc_remove_nm(c, key, &noname);
2516 		}
2517 	}
2518 
2519 out_unlock:
2520 	if (!err)
2521 		err = dbg_check_tnc(c, 0);
2522 	mutex_unlock(&c->tnc_mutex);
2523 	return err;
2524 }
2525 
2526 /**
2527  * tnc_delete - delete a znode form TNC.
2528  * @c: UBIFS file-system description object
2529  * @znode: znode to delete from
2530  * @n: zbranch slot number to delete
2531  *
2532  * This function deletes a leaf node from @n-th slot of @znode. Returns zero in
2533  * case of success and a negative error code in case of failure.
2534  */
tnc_delete(struct ubifs_info * c,struct ubifs_znode * znode,int n)2535 static int tnc_delete(struct ubifs_info *c, struct ubifs_znode *znode, int n)
2536 {
2537 	struct ubifs_zbranch *zbr;
2538 	struct ubifs_znode *zp;
2539 	int i, err;
2540 
2541 	/* Delete without merge for now */
2542 	ubifs_assert(c, znode->level == 0);
2543 	ubifs_assert(c, n >= 0 && n < c->fanout);
2544 	dbg_tnck(&znode->zbranch[n].key, "deleting key ");
2545 
2546 	zbr = &znode->zbranch[n];
2547 	lnc_free(zbr);
2548 
2549 	err = ubifs_add_dirt(c, zbr->lnum, zbr->len);
2550 	if (err) {
2551 		ubifs_dump_znode(c, znode);
2552 		return err;
2553 	}
2554 
2555 	/* We do not "gap" zbranch slots */
2556 	for (i = n; i < znode->child_cnt - 1; i++)
2557 		znode->zbranch[i] = znode->zbranch[i + 1];
2558 	znode->child_cnt -= 1;
2559 
2560 	if (znode->child_cnt > 0)
2561 		return 0;
2562 
2563 	/*
2564 	 * This was the last zbranch, we have to delete this znode from the
2565 	 * parent.
2566 	 */
2567 
2568 	do {
2569 		ubifs_assert(c, !ubifs_zn_obsolete(znode));
2570 		ubifs_assert(c, ubifs_zn_dirty(znode));
2571 
2572 		zp = znode->parent;
2573 		n = znode->iip;
2574 
2575 		atomic_long_dec(&c->dirty_zn_cnt);
2576 
2577 		err = insert_old_idx_znode(c, znode);
2578 		if (err)
2579 			return err;
2580 
2581 		if (znode->cnext) {
2582 			__set_bit(OBSOLETE_ZNODE, &znode->flags);
2583 			atomic_long_inc(&c->clean_zn_cnt);
2584 			atomic_long_inc(&ubifs_clean_zn_cnt);
2585 		} else
2586 			kfree(znode);
2587 		znode = zp;
2588 	} while (znode->child_cnt == 1); /* while removing last child */
2589 
2590 	/* Remove from znode, entry n - 1 */
2591 	znode->child_cnt -= 1;
2592 	ubifs_assert(c, znode->level != 0);
2593 	for (i = n; i < znode->child_cnt; i++) {
2594 		znode->zbranch[i] = znode->zbranch[i + 1];
2595 		if (znode->zbranch[i].znode)
2596 			znode->zbranch[i].znode->iip = i;
2597 	}
2598 
2599 	/*
2600 	 * If this is the root and it has only 1 child then
2601 	 * collapse the tree.
2602 	 */
2603 	if (!znode->parent) {
2604 		while (znode->child_cnt == 1 && znode->level != 0) {
2605 			zp = znode;
2606 			zbr = &znode->zbranch[0];
2607 			znode = get_znode(c, znode, 0);
2608 			if (IS_ERR(znode))
2609 				return PTR_ERR(znode);
2610 			znode = dirty_cow_znode(c, zbr);
2611 			if (IS_ERR(znode))
2612 				return PTR_ERR(znode);
2613 			znode->parent = NULL;
2614 			znode->iip = 0;
2615 			if (c->zroot.len) {
2616 				err = insert_old_idx(c, c->zroot.lnum,
2617 						     c->zroot.offs);
2618 				if (err)
2619 					return err;
2620 			}
2621 			c->zroot.lnum = zbr->lnum;
2622 			c->zroot.offs = zbr->offs;
2623 			c->zroot.len = zbr->len;
2624 			c->zroot.znode = znode;
2625 			ubifs_assert(c, !ubifs_zn_obsolete(zp));
2626 			ubifs_assert(c, ubifs_zn_dirty(zp));
2627 			atomic_long_dec(&c->dirty_zn_cnt);
2628 
2629 			if (zp->cnext) {
2630 				__set_bit(OBSOLETE_ZNODE, &zp->flags);
2631 				atomic_long_inc(&c->clean_zn_cnt);
2632 				atomic_long_inc(&ubifs_clean_zn_cnt);
2633 			} else
2634 				kfree(zp);
2635 		}
2636 	}
2637 
2638 	return 0;
2639 }
2640 
2641 /**
2642  * ubifs_tnc_remove - remove an index entry of a node.
2643  * @c: UBIFS file-system description object
2644  * @key: key of node
2645  *
2646  * Returns %0 on success or negative error code on failure.
2647  */
ubifs_tnc_remove(struct ubifs_info * c,const union ubifs_key * key)2648 int ubifs_tnc_remove(struct ubifs_info *c, const union ubifs_key *key)
2649 {
2650 	int found, n, err = 0;
2651 	struct ubifs_znode *znode;
2652 
2653 	mutex_lock(&c->tnc_mutex);
2654 	dbg_tnck(key, "key ");
2655 	found = lookup_level0_dirty(c, key, &znode, &n);
2656 	if (found < 0) {
2657 		err = found;
2658 		goto out_unlock;
2659 	}
2660 	if (found == 1)
2661 		err = tnc_delete(c, znode, n);
2662 	if (!err)
2663 		err = dbg_check_tnc(c, 0);
2664 
2665 out_unlock:
2666 	mutex_unlock(&c->tnc_mutex);
2667 	return err;
2668 }
2669 
2670 /**
2671  * ubifs_tnc_remove_nm - remove an index entry for a "hashed" node.
2672  * @c: UBIFS file-system description object
2673  * @key: key of node
2674  * @nm: directory entry name
2675  *
2676  * Returns %0 on success or negative error code on failure.
2677  */
ubifs_tnc_remove_nm(struct ubifs_info * c,const union ubifs_key * key,const struct fscrypt_name * nm)2678 int ubifs_tnc_remove_nm(struct ubifs_info *c, const union ubifs_key *key,
2679 			const struct fscrypt_name *nm)
2680 {
2681 	int n, err;
2682 	struct ubifs_znode *znode;
2683 
2684 	mutex_lock(&c->tnc_mutex);
2685 	dbg_tnck(key, "key ");
2686 	err = lookup_level0_dirty(c, key, &znode, &n);
2687 	if (err < 0)
2688 		goto out_unlock;
2689 
2690 	if (err) {
2691 		if (c->replaying)
2692 			err = fallible_resolve_collision(c, key, &znode, &n,
2693 							 nm, 0);
2694 		else
2695 			err = resolve_collision(c, key, &znode, &n, nm);
2696 		dbg_tnc("rc returned %d, znode %p, n %d", err, znode, n);
2697 		if (err < 0)
2698 			goto out_unlock;
2699 		if (err) {
2700 			/* Ensure the znode is dirtied */
2701 			if (znode->cnext || !ubifs_zn_dirty(znode)) {
2702 				znode = dirty_cow_bottom_up(c, znode);
2703 				if (IS_ERR(znode)) {
2704 					err = PTR_ERR(znode);
2705 					goto out_unlock;
2706 				}
2707 			}
2708 			err = tnc_delete(c, znode, n);
2709 		}
2710 	}
2711 
2712 out_unlock:
2713 	if (!err)
2714 		err = dbg_check_tnc(c, 0);
2715 	mutex_unlock(&c->tnc_mutex);
2716 	return err;
2717 }
2718 
2719 /**
2720  * ubifs_tnc_remove_dh - remove an index entry for a "double hashed" node.
2721  * @c: UBIFS file-system description object
2722  * @key: key of node
2723  * @cookie: node cookie for collision resolution
2724  *
2725  * Returns %0 on success or negative error code on failure.
2726  */
ubifs_tnc_remove_dh(struct ubifs_info * c,const union ubifs_key * key,uint32_t cookie)2727 int ubifs_tnc_remove_dh(struct ubifs_info *c, const union ubifs_key *key,
2728 			uint32_t cookie)
2729 {
2730 	int n, err;
2731 	struct ubifs_znode *znode;
2732 	struct ubifs_dent_node *dent;
2733 	struct ubifs_zbranch *zbr;
2734 
2735 	if (!c->double_hash)
2736 		return -EOPNOTSUPP;
2737 
2738 	mutex_lock(&c->tnc_mutex);
2739 	err = lookup_level0_dirty(c, key, &znode, &n);
2740 	if (err <= 0)
2741 		goto out_unlock;
2742 
2743 	zbr = &znode->zbranch[n];
2744 	dent = kmalloc(UBIFS_MAX_DENT_NODE_SZ, GFP_NOFS);
2745 	if (!dent) {
2746 		err = -ENOMEM;
2747 		goto out_unlock;
2748 	}
2749 
2750 	err = tnc_read_hashed_node(c, zbr, dent);
2751 	if (err)
2752 		goto out_free;
2753 
2754 	/* If the cookie does not match, we're facing a hash collision. */
2755 	if (le32_to_cpu(dent->cookie) != cookie) {
2756 		union ubifs_key start_key;
2757 
2758 		lowest_dent_key(c, &start_key, key_inum(c, key));
2759 
2760 		err = ubifs_lookup_level0(c, &start_key, &znode, &n);
2761 		if (unlikely(err < 0))
2762 			goto out_free;
2763 
2764 		err = search_dh_cookie(c, key, dent, cookie, &znode, &n, err);
2765 		if (err)
2766 			goto out_free;
2767 	}
2768 
2769 	if (znode->cnext || !ubifs_zn_dirty(znode)) {
2770 		znode = dirty_cow_bottom_up(c, znode);
2771 		if (IS_ERR(znode)) {
2772 			err = PTR_ERR(znode);
2773 			goto out_free;
2774 		}
2775 	}
2776 	err = tnc_delete(c, znode, n);
2777 
2778 out_free:
2779 	kfree(dent);
2780 out_unlock:
2781 	if (!err)
2782 		err = dbg_check_tnc(c, 0);
2783 	mutex_unlock(&c->tnc_mutex);
2784 	return err;
2785 }
2786 
2787 /**
2788  * key_in_range - determine if a key falls within a range of keys.
2789  * @c: UBIFS file-system description object
2790  * @key: key to check
2791  * @from_key: lowest key in range
2792  * @to_key: highest key in range
2793  *
2794  * This function returns %1 if the key is in range and %0 otherwise.
2795  */
key_in_range(struct ubifs_info * c,union ubifs_key * key,union ubifs_key * from_key,union ubifs_key * to_key)2796 static int key_in_range(struct ubifs_info *c, union ubifs_key *key,
2797 			union ubifs_key *from_key, union ubifs_key *to_key)
2798 {
2799 	if (keys_cmp(c, key, from_key) < 0)
2800 		return 0;
2801 	if (keys_cmp(c, key, to_key) > 0)
2802 		return 0;
2803 	return 1;
2804 }
2805 
2806 /**
2807  * ubifs_tnc_remove_range - remove index entries in range.
2808  * @c: UBIFS file-system description object
2809  * @from_key: lowest key to remove
2810  * @to_key: highest key to remove
2811  *
2812  * This function removes index entries starting at @from_key and ending at
2813  * @to_key.  This function returns zero in case of success and a negative error
2814  * code in case of failure.
2815  */
ubifs_tnc_remove_range(struct ubifs_info * c,union ubifs_key * from_key,union ubifs_key * to_key)2816 int ubifs_tnc_remove_range(struct ubifs_info *c, union ubifs_key *from_key,
2817 			   union ubifs_key *to_key)
2818 {
2819 	int i, n, k, err = 0;
2820 	struct ubifs_znode *znode;
2821 	union ubifs_key *key;
2822 
2823 	mutex_lock(&c->tnc_mutex);
2824 	while (1) {
2825 		/* Find first level 0 znode that contains keys to remove */
2826 		err = ubifs_lookup_level0(c, from_key, &znode, &n);
2827 		if (err < 0)
2828 			goto out_unlock;
2829 
2830 		if (err)
2831 			key = from_key;
2832 		else {
2833 			err = tnc_next(c, &znode, &n);
2834 			if (err == -ENOENT) {
2835 				err = 0;
2836 				goto out_unlock;
2837 			}
2838 			if (err < 0)
2839 				goto out_unlock;
2840 			key = &znode->zbranch[n].key;
2841 			if (!key_in_range(c, key, from_key, to_key)) {
2842 				err = 0;
2843 				goto out_unlock;
2844 			}
2845 		}
2846 
2847 		/* Ensure the znode is dirtied */
2848 		if (znode->cnext || !ubifs_zn_dirty(znode)) {
2849 			znode = dirty_cow_bottom_up(c, znode);
2850 			if (IS_ERR(znode)) {
2851 				err = PTR_ERR(znode);
2852 				goto out_unlock;
2853 			}
2854 		}
2855 
2856 		/* Remove all keys in range except the first */
2857 		for (i = n + 1, k = 0; i < znode->child_cnt; i++, k++) {
2858 			key = &znode->zbranch[i].key;
2859 			if (!key_in_range(c, key, from_key, to_key))
2860 				break;
2861 			lnc_free(&znode->zbranch[i]);
2862 			err = ubifs_add_dirt(c, znode->zbranch[i].lnum,
2863 					     znode->zbranch[i].len);
2864 			if (err) {
2865 				ubifs_dump_znode(c, znode);
2866 				goto out_unlock;
2867 			}
2868 			dbg_tnck(key, "removing key ");
2869 		}
2870 		if (k) {
2871 			for (i = n + 1 + k; i < znode->child_cnt; i++)
2872 				znode->zbranch[i - k] = znode->zbranch[i];
2873 			znode->child_cnt -= k;
2874 		}
2875 
2876 		/* Now delete the first */
2877 		err = tnc_delete(c, znode, n);
2878 		if (err)
2879 			goto out_unlock;
2880 	}
2881 
2882 out_unlock:
2883 	if (!err)
2884 		err = dbg_check_tnc(c, 0);
2885 	mutex_unlock(&c->tnc_mutex);
2886 	return err;
2887 }
2888 
2889 /**
2890  * ubifs_tnc_remove_ino - remove an inode from TNC.
2891  * @c: UBIFS file-system description object
2892  * @inum: inode number to remove
2893  *
2894  * This function remove inode @inum and all the extended attributes associated
2895  * with the anode from TNC and returns zero in case of success or a negative
2896  * error code in case of failure.
2897  */
ubifs_tnc_remove_ino(struct ubifs_info * c,ino_t inum)2898 int ubifs_tnc_remove_ino(struct ubifs_info *c, ino_t inum)
2899 {
2900 	union ubifs_key key1, key2;
2901 	struct ubifs_dent_node *xent, *pxent = NULL;
2902 	struct fscrypt_name nm = {0};
2903 
2904 	dbg_tnc("ino %lu", (unsigned long)inum);
2905 
2906 	/*
2907 	 * Walk all extended attribute entries and remove them together with
2908 	 * corresponding extended attribute inodes.
2909 	 */
2910 	lowest_xent_key(c, &key1, inum);
2911 	while (1) {
2912 		ino_t xattr_inum;
2913 		int err;
2914 
2915 		xent = ubifs_tnc_next_ent(c, &key1, &nm);
2916 		if (IS_ERR(xent)) {
2917 			err = PTR_ERR(xent);
2918 			if (err == -ENOENT)
2919 				break;
2920 			return err;
2921 		}
2922 
2923 		xattr_inum = le64_to_cpu(xent->inum);
2924 		dbg_tnc("xent '%s', ino %lu", xent->name,
2925 			(unsigned long)xattr_inum);
2926 
2927 		ubifs_evict_xattr_inode(c, xattr_inum);
2928 
2929 		fname_name(&nm) = xent->name;
2930 		fname_len(&nm) = le16_to_cpu(xent->nlen);
2931 		err = ubifs_tnc_remove_nm(c, &key1, &nm);
2932 		if (err) {
2933 			kfree(xent);
2934 			return err;
2935 		}
2936 
2937 		lowest_ino_key(c, &key1, xattr_inum);
2938 		highest_ino_key(c, &key2, xattr_inum);
2939 		err = ubifs_tnc_remove_range(c, &key1, &key2);
2940 		if (err) {
2941 			kfree(xent);
2942 			return err;
2943 		}
2944 
2945 		kfree(pxent);
2946 		pxent = xent;
2947 		key_read(c, &xent->key, &key1);
2948 	}
2949 
2950 	kfree(pxent);
2951 	lowest_ino_key(c, &key1, inum);
2952 	highest_ino_key(c, &key2, inum);
2953 
2954 	return ubifs_tnc_remove_range(c, &key1, &key2);
2955 }
2956 
2957 /**
2958  * ubifs_tnc_next_ent - walk directory or extended attribute entries.
2959  * @c: UBIFS file-system description object
2960  * @key: key of last entry
2961  * @nm: name of last entry found or %NULL
2962  *
2963  * This function finds and reads the next directory or extended attribute entry
2964  * after the given key (@key) if there is one. @nm is used to resolve
2965  * collisions.
2966  *
2967  * If the name of the current entry is not known and only the key is known,
2968  * @nm->name has to be %NULL. In this case the semantics of this function is a
2969  * little bit different and it returns the entry corresponding to this key, not
2970  * the next one. If the key was not found, the closest "right" entry is
2971  * returned.
2972  *
2973  * If the fist entry has to be found, @key has to contain the lowest possible
2974  * key value for this inode and @name has to be %NULL.
2975  *
2976  * This function returns the found directory or extended attribute entry node
2977  * in case of success, %-ENOENT is returned if no entry was found, and a
2978  * negative error code is returned in case of failure.
2979  */
ubifs_tnc_next_ent(struct ubifs_info * c,union ubifs_key * key,const struct fscrypt_name * nm)2980 struct ubifs_dent_node *ubifs_tnc_next_ent(struct ubifs_info *c,
2981 					   union ubifs_key *key,
2982 					   const struct fscrypt_name *nm)
2983 {
2984 	int n, err, type = key_type(c, key);
2985 	struct ubifs_znode *znode;
2986 	struct ubifs_dent_node *dent;
2987 	struct ubifs_zbranch *zbr;
2988 	union ubifs_key *dkey;
2989 
2990 	dbg_tnck(key, "key ");
2991 	ubifs_assert(c, is_hash_key(c, key));
2992 
2993 	mutex_lock(&c->tnc_mutex);
2994 	err = ubifs_lookup_level0(c, key, &znode, &n);
2995 	if (unlikely(err < 0))
2996 		goto out_unlock;
2997 
2998 	if (fname_len(nm) > 0) {
2999 		if (err) {
3000 			/* Handle collisions */
3001 			if (c->replaying)
3002 				err = fallible_resolve_collision(c, key, &znode, &n,
3003 							 nm, 0);
3004 			else
3005 				err = resolve_collision(c, key, &znode, &n, nm);
3006 			dbg_tnc("rc returned %d, znode %p, n %d",
3007 				err, znode, n);
3008 			if (unlikely(err < 0))
3009 				goto out_unlock;
3010 		}
3011 
3012 		/* Now find next entry */
3013 		err = tnc_next(c, &znode, &n);
3014 		if (unlikely(err))
3015 			goto out_unlock;
3016 	} else {
3017 		/*
3018 		 * The full name of the entry was not given, in which case the
3019 		 * behavior of this function is a little different and it
3020 		 * returns current entry, not the next one.
3021 		 */
3022 		if (!err) {
3023 			/*
3024 			 * However, the given key does not exist in the TNC
3025 			 * tree and @znode/@n variables contain the closest
3026 			 * "preceding" element. Switch to the next one.
3027 			 */
3028 			err = tnc_next(c, &znode, &n);
3029 			if (err)
3030 				goto out_unlock;
3031 		}
3032 	}
3033 
3034 	zbr = &znode->zbranch[n];
3035 	dent = kmalloc(zbr->len, GFP_NOFS);
3036 	if (unlikely(!dent)) {
3037 		err = -ENOMEM;
3038 		goto out_unlock;
3039 	}
3040 
3041 	/*
3042 	 * The above 'tnc_next()' call could lead us to the next inode, check
3043 	 * this.
3044 	 */
3045 	dkey = &zbr->key;
3046 	if (key_inum(c, dkey) != key_inum(c, key) ||
3047 	    key_type(c, dkey) != type) {
3048 		err = -ENOENT;
3049 		goto out_free;
3050 	}
3051 
3052 	err = tnc_read_hashed_node(c, zbr, dent);
3053 	if (unlikely(err))
3054 		goto out_free;
3055 
3056 	mutex_unlock(&c->tnc_mutex);
3057 	return dent;
3058 
3059 out_free:
3060 	kfree(dent);
3061 out_unlock:
3062 	mutex_unlock(&c->tnc_mutex);
3063 	return ERR_PTR(err);
3064 }
3065 
3066 /**
3067  * tnc_destroy_cnext - destroy left-over obsolete znodes from a failed commit.
3068  * @c: UBIFS file-system description object
3069  *
3070  * Destroy left-over obsolete znodes from a failed commit.
3071  */
tnc_destroy_cnext(struct ubifs_info * c)3072 static void tnc_destroy_cnext(struct ubifs_info *c)
3073 {
3074 	struct ubifs_znode *cnext;
3075 
3076 	if (!c->cnext)
3077 		return;
3078 	ubifs_assert(c, c->cmt_state == COMMIT_BROKEN);
3079 	cnext = c->cnext;
3080 	do {
3081 		struct ubifs_znode *znode = cnext;
3082 
3083 		cnext = cnext->cnext;
3084 		if (ubifs_zn_obsolete(znode))
3085 			kfree(znode);
3086 		else if (!ubifs_zn_cow(znode)) {
3087 			/*
3088 			 * Don't forget to update clean znode count after
3089 			 * committing failed, because ubifs will check this
3090 			 * count while closing tnc. Non-obsolete znode could
3091 			 * be re-dirtied during committing process, so dirty
3092 			 * flag is untrustable. The flag 'COW_ZNODE' is set
3093 			 * for each dirty znode before committing, and it is
3094 			 * cleared as long as the znode become clean, so we
3095 			 * can statistic clean znode count according to this
3096 			 * flag.
3097 			 */
3098 			atomic_long_inc(&c->clean_zn_cnt);
3099 			atomic_long_inc(&ubifs_clean_zn_cnt);
3100 		}
3101 	} while (cnext && cnext != c->cnext);
3102 }
3103 
3104 /**
3105  * ubifs_tnc_close - close TNC subsystem and free all related resources.
3106  * @c: UBIFS file-system description object
3107  */
ubifs_tnc_close(struct ubifs_info * c)3108 void ubifs_tnc_close(struct ubifs_info *c)
3109 {
3110 	tnc_destroy_cnext(c);
3111 	if (c->zroot.znode) {
3112 		long n, freed;
3113 
3114 		n = atomic_long_read(&c->clean_zn_cnt);
3115 		freed = ubifs_destroy_tnc_subtree(c, c->zroot.znode);
3116 		ubifs_assert(c, freed == n);
3117 		atomic_long_sub(n, &ubifs_clean_zn_cnt);
3118 	}
3119 	kfree(c->gap_lebs);
3120 	kfree(c->ilebs);
3121 	destroy_old_idx(c);
3122 }
3123 
3124 /**
3125  * left_znode - get the znode to the left.
3126  * @c: UBIFS file-system description object
3127  * @znode: znode
3128  *
3129  * This function returns a pointer to the znode to the left of @znode or NULL if
3130  * there is not one. A negative error code is returned on failure.
3131  */
left_znode(struct ubifs_info * c,struct ubifs_znode * znode)3132 static struct ubifs_znode *left_znode(struct ubifs_info *c,
3133 				      struct ubifs_znode *znode)
3134 {
3135 	int level = znode->level;
3136 
3137 	while (1) {
3138 		int n = znode->iip - 1;
3139 
3140 		/* Go up until we can go left */
3141 		znode = znode->parent;
3142 		if (!znode)
3143 			return NULL;
3144 		if (n >= 0) {
3145 			/* Now go down the rightmost branch to 'level' */
3146 			znode = get_znode(c, znode, n);
3147 			if (IS_ERR(znode))
3148 				return znode;
3149 			while (znode->level != level) {
3150 				n = znode->child_cnt - 1;
3151 				znode = get_znode(c, znode, n);
3152 				if (IS_ERR(znode))
3153 					return znode;
3154 			}
3155 			break;
3156 		}
3157 	}
3158 	return znode;
3159 }
3160 
3161 /**
3162  * right_znode - get the znode to the right.
3163  * @c: UBIFS file-system description object
3164  * @znode: znode
3165  *
3166  * This function returns a pointer to the znode to the right of @znode or NULL
3167  * if there is not one. A negative error code is returned on failure.
3168  */
right_znode(struct ubifs_info * c,struct ubifs_znode * znode)3169 static struct ubifs_znode *right_znode(struct ubifs_info *c,
3170 				       struct ubifs_znode *znode)
3171 {
3172 	int level = znode->level;
3173 
3174 	while (1) {
3175 		int n = znode->iip + 1;
3176 
3177 		/* Go up until we can go right */
3178 		znode = znode->parent;
3179 		if (!znode)
3180 			return NULL;
3181 		if (n < znode->child_cnt) {
3182 			/* Now go down the leftmost branch to 'level' */
3183 			znode = get_znode(c, znode, n);
3184 			if (IS_ERR(znode))
3185 				return znode;
3186 			while (znode->level != level) {
3187 				znode = get_znode(c, znode, 0);
3188 				if (IS_ERR(znode))
3189 					return znode;
3190 			}
3191 			break;
3192 		}
3193 	}
3194 	return znode;
3195 }
3196 
3197 /**
3198  * lookup_znode - find a particular indexing node from TNC.
3199  * @c: UBIFS file-system description object
3200  * @key: index node key to lookup
3201  * @level: index node level
3202  * @lnum: index node LEB number
3203  * @offs: index node offset
3204  *
3205  * This function searches an indexing node by its first key @key and its
3206  * address @lnum:@offs. It looks up the indexing tree by pulling all indexing
3207  * nodes it traverses to TNC. This function is called for indexing nodes which
3208  * were found on the media by scanning, for example when garbage-collecting or
3209  * when doing in-the-gaps commit. This means that the indexing node which is
3210  * looked for does not have to have exactly the same leftmost key @key, because
3211  * the leftmost key may have been changed, in which case TNC will contain a
3212  * dirty znode which still refers the same @lnum:@offs. This function is clever
3213  * enough to recognize such indexing nodes.
3214  *
3215  * Note, if a znode was deleted or changed too much, then this function will
3216  * not find it. For situations like this UBIFS has the old index RB-tree
3217  * (indexed by @lnum:@offs).
3218  *
3219  * This function returns a pointer to the znode found or %NULL if it is not
3220  * found. A negative error code is returned on failure.
3221  */
lookup_znode(struct ubifs_info * c,union ubifs_key * key,int level,int lnum,int offs)3222 static struct ubifs_znode *lookup_znode(struct ubifs_info *c,
3223 					union ubifs_key *key, int level,
3224 					int lnum, int offs)
3225 {
3226 	struct ubifs_znode *znode, *zn;
3227 	int n, nn;
3228 
3229 	ubifs_assert(c, key_type(c, key) < UBIFS_INVALID_KEY);
3230 
3231 	/*
3232 	 * The arguments have probably been read off flash, so don't assume
3233 	 * they are valid.
3234 	 */
3235 	if (level < 0)
3236 		return ERR_PTR(-EINVAL);
3237 
3238 	/* Get the root znode */
3239 	znode = c->zroot.znode;
3240 	if (!znode) {
3241 		znode = ubifs_load_znode(c, &c->zroot, NULL, 0);
3242 		if (IS_ERR(znode))
3243 			return znode;
3244 	}
3245 	/* Check if it is the one we are looking for */
3246 	if (c->zroot.lnum == lnum && c->zroot.offs == offs)
3247 		return znode;
3248 	/* Descend to the parent level i.e. (level + 1) */
3249 	if (level >= znode->level)
3250 		return NULL;
3251 	while (1) {
3252 		ubifs_search_zbranch(c, znode, key, &n);
3253 		if (n < 0) {
3254 			/*
3255 			 * We reached a znode where the leftmost key is greater
3256 			 * than the key we are searching for. This is the same
3257 			 * situation as the one described in a huge comment at
3258 			 * the end of the 'ubifs_lookup_level0()' function. And
3259 			 * for exactly the same reasons we have to try to look
3260 			 * left before giving up.
3261 			 */
3262 			znode = left_znode(c, znode);
3263 			if (!znode)
3264 				return NULL;
3265 			if (IS_ERR(znode))
3266 				return znode;
3267 			ubifs_search_zbranch(c, znode, key, &n);
3268 			ubifs_assert(c, n >= 0);
3269 		}
3270 		if (znode->level == level + 1)
3271 			break;
3272 		znode = get_znode(c, znode, n);
3273 		if (IS_ERR(znode))
3274 			return znode;
3275 	}
3276 	/* Check if the child is the one we are looking for */
3277 	if (znode->zbranch[n].lnum == lnum && znode->zbranch[n].offs == offs)
3278 		return get_znode(c, znode, n);
3279 	/* If the key is unique, there is nowhere else to look */
3280 	if (!is_hash_key(c, key))
3281 		return NULL;
3282 	/*
3283 	 * The key is not unique and so may be also in the znodes to either
3284 	 * side.
3285 	 */
3286 	zn = znode;
3287 	nn = n;
3288 	/* Look left */
3289 	while (1) {
3290 		/* Move one branch to the left */
3291 		if (n)
3292 			n -= 1;
3293 		else {
3294 			znode = left_znode(c, znode);
3295 			if (!znode)
3296 				break;
3297 			if (IS_ERR(znode))
3298 				return znode;
3299 			n = znode->child_cnt - 1;
3300 		}
3301 		/* Check it */
3302 		if (znode->zbranch[n].lnum == lnum &&
3303 		    znode->zbranch[n].offs == offs)
3304 			return get_znode(c, znode, n);
3305 		/* Stop if the key is less than the one we are looking for */
3306 		if (keys_cmp(c, &znode->zbranch[n].key, key) < 0)
3307 			break;
3308 	}
3309 	/* Back to the middle */
3310 	znode = zn;
3311 	n = nn;
3312 	/* Look right */
3313 	while (1) {
3314 		/* Move one branch to the right */
3315 		if (++n >= znode->child_cnt) {
3316 			znode = right_znode(c, znode);
3317 			if (!znode)
3318 				break;
3319 			if (IS_ERR(znode))
3320 				return znode;
3321 			n = 0;
3322 		}
3323 		/* Check it */
3324 		if (znode->zbranch[n].lnum == lnum &&
3325 		    znode->zbranch[n].offs == offs)
3326 			return get_znode(c, znode, n);
3327 		/* Stop if the key is greater than the one we are looking for */
3328 		if (keys_cmp(c, &znode->zbranch[n].key, key) > 0)
3329 			break;
3330 	}
3331 	return NULL;
3332 }
3333 
3334 /**
3335  * is_idx_node_in_tnc - determine if an index node is in the TNC.
3336  * @c: UBIFS file-system description object
3337  * @key: key of index node
3338  * @level: index node level
3339  * @lnum: LEB number of index node
3340  * @offs: offset of index node
3341  *
3342  * This function returns %0 if the index node is not referred to in the TNC, %1
3343  * if the index node is referred to in the TNC and the corresponding znode is
3344  * dirty, %2 if an index node is referred to in the TNC and the corresponding
3345  * znode is clean, and a negative error code in case of failure.
3346  *
3347  * Note, the @key argument has to be the key of the first child. Also note,
3348  * this function relies on the fact that 0:0 is never a valid LEB number and
3349  * offset for a main-area node.
3350  */
is_idx_node_in_tnc(struct ubifs_info * c,union ubifs_key * key,int level,int lnum,int offs)3351 int is_idx_node_in_tnc(struct ubifs_info *c, union ubifs_key *key, int level,
3352 		       int lnum, int offs)
3353 {
3354 	struct ubifs_znode *znode;
3355 
3356 	znode = lookup_znode(c, key, level, lnum, offs);
3357 	if (!znode)
3358 		return 0;
3359 	if (IS_ERR(znode))
3360 		return PTR_ERR(znode);
3361 
3362 	return ubifs_zn_dirty(znode) ? 1 : 2;
3363 }
3364 
3365 /**
3366  * is_leaf_node_in_tnc - determine if a non-indexing not is in the TNC.
3367  * @c: UBIFS file-system description object
3368  * @key: node key
3369  * @lnum: node LEB number
3370  * @offs: node offset
3371  *
3372  * This function returns %1 if the node is referred to in the TNC, %0 if it is
3373  * not, and a negative error code in case of failure.
3374  *
3375  * Note, this function relies on the fact that 0:0 is never a valid LEB number
3376  * and offset for a main-area node.
3377  */
is_leaf_node_in_tnc(struct ubifs_info * c,union ubifs_key * key,int lnum,int offs)3378 static int is_leaf_node_in_tnc(struct ubifs_info *c, union ubifs_key *key,
3379 			       int lnum, int offs)
3380 {
3381 	struct ubifs_zbranch *zbr;
3382 	struct ubifs_znode *znode, *zn;
3383 	int n, found, err, nn;
3384 	const int unique = !is_hash_key(c, key);
3385 
3386 	found = ubifs_lookup_level0(c, key, &znode, &n);
3387 	if (found < 0)
3388 		return found; /* Error code */
3389 	if (!found)
3390 		return 0;
3391 	zbr = &znode->zbranch[n];
3392 	if (lnum == zbr->lnum && offs == zbr->offs)
3393 		return 1; /* Found it */
3394 	if (unique)
3395 		return 0;
3396 	/*
3397 	 * Because the key is not unique, we have to look left
3398 	 * and right as well
3399 	 */
3400 	zn = znode;
3401 	nn = n;
3402 	/* Look left */
3403 	while (1) {
3404 		err = tnc_prev(c, &znode, &n);
3405 		if (err == -ENOENT)
3406 			break;
3407 		if (err)
3408 			return err;
3409 		if (keys_cmp(c, key, &znode->zbranch[n].key))
3410 			break;
3411 		zbr = &znode->zbranch[n];
3412 		if (lnum == zbr->lnum && offs == zbr->offs)
3413 			return 1; /* Found it */
3414 	}
3415 	/* Look right */
3416 	znode = zn;
3417 	n = nn;
3418 	while (1) {
3419 		err = tnc_next(c, &znode, &n);
3420 		if (err) {
3421 			if (err == -ENOENT)
3422 				return 0;
3423 			return err;
3424 		}
3425 		if (keys_cmp(c, key, &znode->zbranch[n].key))
3426 			break;
3427 		zbr = &znode->zbranch[n];
3428 		if (lnum == zbr->lnum && offs == zbr->offs)
3429 			return 1; /* Found it */
3430 	}
3431 	return 0;
3432 }
3433 
3434 /**
3435  * ubifs_tnc_has_node - determine whether a node is in the TNC.
3436  * @c: UBIFS file-system description object
3437  * @key: node key
3438  * @level: index node level (if it is an index node)
3439  * @lnum: node LEB number
3440  * @offs: node offset
3441  * @is_idx: non-zero if the node is an index node
3442  *
3443  * This function returns %1 if the node is in the TNC, %0 if it is not, and a
3444  * negative error code in case of failure. For index nodes, @key has to be the
3445  * key of the first child. An index node is considered to be in the TNC only if
3446  * the corresponding znode is clean or has not been loaded.
3447  */
ubifs_tnc_has_node(struct ubifs_info * c,union ubifs_key * key,int level,int lnum,int offs,int is_idx)3448 int ubifs_tnc_has_node(struct ubifs_info *c, union ubifs_key *key, int level,
3449 		       int lnum, int offs, int is_idx)
3450 {
3451 	int err;
3452 
3453 	mutex_lock(&c->tnc_mutex);
3454 	if (is_idx) {
3455 		err = is_idx_node_in_tnc(c, key, level, lnum, offs);
3456 		if (err < 0)
3457 			goto out_unlock;
3458 		if (err == 1)
3459 			/* The index node was found but it was dirty */
3460 			err = 0;
3461 		else if (err == 2)
3462 			/* The index node was found and it was clean */
3463 			err = 1;
3464 		else
3465 			BUG_ON(err != 0);
3466 	} else
3467 		err = is_leaf_node_in_tnc(c, key, lnum, offs);
3468 
3469 out_unlock:
3470 	mutex_unlock(&c->tnc_mutex);
3471 	return err;
3472 }
3473 
3474 /**
3475  * ubifs_dirty_idx_node - dirty an index node.
3476  * @c: UBIFS file-system description object
3477  * @key: index node key
3478  * @level: index node level
3479  * @lnum: index node LEB number
3480  * @offs: index node offset
3481  *
3482  * This function loads and dirties an index node so that it can be garbage
3483  * collected. The @key argument has to be the key of the first child. This
3484  * function relies on the fact that 0:0 is never a valid LEB number and offset
3485  * for a main-area node. Returns %0 on success and a negative error code on
3486  * failure.
3487  */
ubifs_dirty_idx_node(struct ubifs_info * c,union ubifs_key * key,int level,int lnum,int offs)3488 int ubifs_dirty_idx_node(struct ubifs_info *c, union ubifs_key *key, int level,
3489 			 int lnum, int offs)
3490 {
3491 	struct ubifs_znode *znode;
3492 	int err = 0;
3493 
3494 	mutex_lock(&c->tnc_mutex);
3495 	znode = lookup_znode(c, key, level, lnum, offs);
3496 	if (!znode)
3497 		goto out_unlock;
3498 	if (IS_ERR(znode)) {
3499 		err = PTR_ERR(znode);
3500 		goto out_unlock;
3501 	}
3502 	znode = dirty_cow_bottom_up(c, znode);
3503 	if (IS_ERR(znode)) {
3504 		err = PTR_ERR(znode);
3505 		goto out_unlock;
3506 	}
3507 
3508 out_unlock:
3509 	mutex_unlock(&c->tnc_mutex);
3510 	return err;
3511 }
3512 
3513 /**
3514  * dbg_check_inode_size - check if inode size is correct.
3515  * @c: UBIFS file-system description object
3516  * @inum: inode number
3517  * @size: inode size
3518  *
3519  * This function makes sure that the inode size (@size) is correct and it does
3520  * not have any pages beyond @size. Returns zero if the inode is OK, %-EINVAL
3521  * if it has a data page beyond @size, and other negative error code in case of
3522  * other errors.
3523  */
dbg_check_inode_size(struct ubifs_info * c,const struct inode * inode,loff_t size)3524 int dbg_check_inode_size(struct ubifs_info *c, const struct inode *inode,
3525 			 loff_t size)
3526 {
3527 	int err, n;
3528 	union ubifs_key from_key, to_key, *key;
3529 	struct ubifs_znode *znode;
3530 	unsigned int block;
3531 
3532 	if (!S_ISREG(inode->i_mode))
3533 		return 0;
3534 	if (!dbg_is_chk_gen(c))
3535 		return 0;
3536 
3537 	block = (size + UBIFS_BLOCK_SIZE - 1) >> UBIFS_BLOCK_SHIFT;
3538 	data_key_init(c, &from_key, inode->i_ino, block);
3539 	highest_data_key(c, &to_key, inode->i_ino);
3540 
3541 	mutex_lock(&c->tnc_mutex);
3542 	err = ubifs_lookup_level0(c, &from_key, &znode, &n);
3543 	if (err < 0)
3544 		goto out_unlock;
3545 
3546 	if (err) {
3547 		key = &from_key;
3548 		goto out_dump;
3549 	}
3550 
3551 	err = tnc_next(c, &znode, &n);
3552 	if (err == -ENOENT) {
3553 		err = 0;
3554 		goto out_unlock;
3555 	}
3556 	if (err < 0)
3557 		goto out_unlock;
3558 
3559 	ubifs_assert(c, err == 0);
3560 	key = &znode->zbranch[n].key;
3561 	if (!key_in_range(c, key, &from_key, &to_key))
3562 		goto out_unlock;
3563 
3564 out_dump:
3565 	block = key_block(c, key);
3566 	ubifs_err(c, "inode %lu has size %lld, but there are data at offset %lld",
3567 		  (unsigned long)inode->i_ino, size,
3568 		  ((loff_t)block) << UBIFS_BLOCK_SHIFT);
3569 	mutex_unlock(&c->tnc_mutex);
3570 	ubifs_dump_inode(c, inode);
3571 	dump_stack();
3572 	return -EINVAL;
3573 
3574 out_unlock:
3575 	mutex_unlock(&c->tnc_mutex);
3576 	return err;
3577 }
3578