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 contains miscelanious TNC-related functions shared betweend
25  * different files. This file does not form any logically separate TNC
26  * sub-system. The file was created because there is a lot of TNC code and
27  * putting it all in one file would make that file too big and unreadable.
28  */
29 
30 #include "ubifs.h"
31 
32 /**
33  * ubifs_tnc_levelorder_next - next TNC tree element in levelorder traversal.
34  * @c: UBIFS file-system description object
35  * @zr: root of the subtree to traverse
36  * @znode: previous znode
37  *
38  * This function implements levelorder TNC traversal. The LNC is ignored.
39  * Returns the next element or %NULL if @znode is already the last one.
40  */
ubifs_tnc_levelorder_next(const struct ubifs_info * c,struct ubifs_znode * zr,struct ubifs_znode * znode)41 struct ubifs_znode *ubifs_tnc_levelorder_next(const struct ubifs_info *c,
42 					      struct ubifs_znode *zr,
43 					      struct ubifs_znode *znode)
44 {
45 	int level, iip, level_search = 0;
46 	struct ubifs_znode *zn;
47 
48 	ubifs_assert(c, zr);
49 
50 	if (unlikely(!znode))
51 		return zr;
52 
53 	if (unlikely(znode == zr)) {
54 		if (znode->level == 0)
55 			return NULL;
56 		return ubifs_tnc_find_child(zr, 0);
57 	}
58 
59 	level = znode->level;
60 
61 	iip = znode->iip;
62 	while (1) {
63 		ubifs_assert(c, znode->level <= zr->level);
64 
65 		/*
66 		 * First walk up until there is a znode with next branch to
67 		 * look at.
68 		 */
69 		while (znode->parent != zr && iip >= znode->parent->child_cnt) {
70 			znode = znode->parent;
71 			iip = znode->iip;
72 		}
73 
74 		if (unlikely(znode->parent == zr &&
75 			     iip >= znode->parent->child_cnt)) {
76 			/* This level is done, switch to the lower one */
77 			level -= 1;
78 			if (level_search || level < 0)
79 				/*
80 				 * We were already looking for znode at lower
81 				 * level ('level_search'). As we are here
82 				 * again, it just does not exist. Or all levels
83 				 * were finished ('level < 0').
84 				 */
85 				return NULL;
86 
87 			level_search = 1;
88 			iip = -1;
89 			znode = ubifs_tnc_find_child(zr, 0);
90 			ubifs_assert(c, znode);
91 		}
92 
93 		/* Switch to the next index */
94 		zn = ubifs_tnc_find_child(znode->parent, iip + 1);
95 		if (!zn) {
96 			/* No more children to look at, we have walk up */
97 			iip = znode->parent->child_cnt;
98 			continue;
99 		}
100 
101 		/* Walk back down to the level we came from ('level') */
102 		while (zn->level != level) {
103 			znode = zn;
104 			zn = ubifs_tnc_find_child(zn, 0);
105 			if (!zn) {
106 				/*
107 				 * This path is not too deep so it does not
108 				 * reach 'level'. Try next path.
109 				 */
110 				iip = znode->iip;
111 				break;
112 			}
113 		}
114 
115 		if (zn) {
116 			ubifs_assert(c, zn->level >= 0);
117 			return zn;
118 		}
119 	}
120 }
121 
122 /**
123  * ubifs_search_zbranch - search znode branch.
124  * @c: UBIFS file-system description object
125  * @znode: znode to search in
126  * @key: key to search for
127  * @n: znode branch slot number is returned here
128  *
129  * This is a helper function which search branch with key @key in @znode using
130  * binary search. The result of the search may be:
131  *   o exact match, then %1 is returned, and the slot number of the branch is
132  *     stored in @n;
133  *   o no exact match, then %0 is returned and the slot number of the left
134  *     closest branch is returned in @n; the slot if all keys in this znode are
135  *     greater than @key, then %-1 is returned in @n.
136  */
ubifs_search_zbranch(const struct ubifs_info * c,const struct ubifs_znode * znode,const union ubifs_key * key,int * n)137 int ubifs_search_zbranch(const struct ubifs_info *c,
138 			 const struct ubifs_znode *znode,
139 			 const union ubifs_key *key, int *n)
140 {
141 	int beg = 0, end = znode->child_cnt, uninitialized_var(mid);
142 	int uninitialized_var(cmp);
143 	const struct ubifs_zbranch *zbr = &znode->zbranch[0];
144 
145 	ubifs_assert(c, end > beg);
146 
147 	while (end > beg) {
148 		mid = (beg + end) >> 1;
149 		cmp = keys_cmp(c, key, &zbr[mid].key);
150 		if (cmp > 0)
151 			beg = mid + 1;
152 		else if (cmp < 0)
153 			end = mid;
154 		else {
155 			*n = mid;
156 			return 1;
157 		}
158 	}
159 
160 	*n = end - 1;
161 
162 	/* The insert point is after *n */
163 	ubifs_assert(c, *n >= -1 && *n < znode->child_cnt);
164 	if (*n == -1)
165 		ubifs_assert(c, keys_cmp(c, key, &zbr[0].key) < 0);
166 	else
167 		ubifs_assert(c, keys_cmp(c, key, &zbr[*n].key) > 0);
168 	if (*n + 1 < znode->child_cnt)
169 		ubifs_assert(c, keys_cmp(c, key, &zbr[*n + 1].key) < 0);
170 
171 	return 0;
172 }
173 
174 /**
175  * ubifs_tnc_postorder_first - find first znode to do postorder tree traversal.
176  * @znode: znode to start at (root of the sub-tree to traverse)
177  *
178  * Find the lowest leftmost znode in a subtree of the TNC tree. The LNC is
179  * ignored.
180  */
ubifs_tnc_postorder_first(struct ubifs_znode * znode)181 struct ubifs_znode *ubifs_tnc_postorder_first(struct ubifs_znode *znode)
182 {
183 	if (unlikely(!znode))
184 		return NULL;
185 
186 	while (znode->level > 0) {
187 		struct ubifs_znode *child;
188 
189 		child = ubifs_tnc_find_child(znode, 0);
190 		if (!child)
191 			return znode;
192 		znode = child;
193 	}
194 
195 	return znode;
196 }
197 
198 /**
199  * ubifs_tnc_postorder_next - next TNC tree element in postorder traversal.
200  * @c: UBIFS file-system description object
201  * @znode: previous znode
202  *
203  * This function implements postorder TNC traversal. The LNC is ignored.
204  * Returns the next element or %NULL if @znode is already the last one.
205  */
ubifs_tnc_postorder_next(const struct ubifs_info * c,struct ubifs_znode * znode)206 struct ubifs_znode *ubifs_tnc_postorder_next(const struct ubifs_info *c,
207 					     struct ubifs_znode *znode)
208 {
209 	struct ubifs_znode *zn;
210 
211 	ubifs_assert(c, znode);
212 	if (unlikely(!znode->parent))
213 		return NULL;
214 
215 	/* Switch to the next index in the parent */
216 	zn = ubifs_tnc_find_child(znode->parent, znode->iip + 1);
217 	if (!zn)
218 		/* This is in fact the last child, return parent */
219 		return znode->parent;
220 
221 	/* Go to the first znode in this new subtree */
222 	return ubifs_tnc_postorder_first(zn);
223 }
224 
225 /**
226  * ubifs_destroy_tnc_subtree - destroy all znodes connected to a subtree.
227  * @c: UBIFS file-system description object
228  * @znode: znode defining subtree to destroy
229  *
230  * This function destroys subtree of the TNC tree. Returns number of clean
231  * znodes in the subtree.
232  */
ubifs_destroy_tnc_subtree(const struct ubifs_info * c,struct ubifs_znode * znode)233 long ubifs_destroy_tnc_subtree(const struct ubifs_info *c,
234 			       struct ubifs_znode *znode)
235 {
236 	struct ubifs_znode *zn = ubifs_tnc_postorder_first(znode);
237 	long clean_freed = 0;
238 	int n;
239 
240 	ubifs_assert(c, zn);
241 	while (1) {
242 		for (n = 0; n < zn->child_cnt; n++) {
243 			if (!zn->zbranch[n].znode)
244 				continue;
245 
246 			if (zn->level > 0 &&
247 			    !ubifs_zn_dirty(zn->zbranch[n].znode))
248 				clean_freed += 1;
249 
250 			cond_resched();
251 			kfree(zn->zbranch[n].znode);
252 		}
253 
254 		if (zn == znode) {
255 			if (!ubifs_zn_dirty(zn))
256 				clean_freed += 1;
257 			kfree(zn);
258 			return clean_freed;
259 		}
260 
261 		zn = ubifs_tnc_postorder_next(c, zn);
262 	}
263 }
264 
265 /**
266  * read_znode - read an indexing node from flash and fill znode.
267  * @c: UBIFS file-system description object
268  * @lnum: LEB of the indexing node to read
269  * @offs: node offset
270  * @len: node length
271  * @znode: znode to read to
272  *
273  * This function reads an indexing node from the flash media and fills znode
274  * with the read data. Returns zero in case of success and a negative error
275  * code in case of failure. The read indexing node is validated and if anything
276  * is wrong with it, this function prints complaint messages and returns
277  * %-EINVAL.
278  */
read_znode(struct ubifs_info * c,int lnum,int offs,int len,struct ubifs_znode * znode)279 static int read_znode(struct ubifs_info *c, int lnum, int offs, int len,
280 		      struct ubifs_znode *znode)
281 {
282 	int i, err, type, cmp;
283 	struct ubifs_idx_node *idx;
284 
285 	idx = kmalloc(c->max_idx_node_sz, GFP_NOFS);
286 	if (!idx)
287 		return -ENOMEM;
288 
289 	err = ubifs_read_node(c, idx, UBIFS_IDX_NODE, len, lnum, offs);
290 	if (err < 0) {
291 		kfree(idx);
292 		return err;
293 	}
294 
295 	znode->child_cnt = le16_to_cpu(idx->child_cnt);
296 	znode->level = le16_to_cpu(idx->level);
297 
298 	dbg_tnc("LEB %d:%d, level %d, %d branch",
299 		lnum, offs, znode->level, znode->child_cnt);
300 
301 	if (znode->child_cnt > c->fanout || znode->level > UBIFS_MAX_LEVELS) {
302 		ubifs_err(c, "current fanout %d, branch count %d",
303 			  c->fanout, znode->child_cnt);
304 		ubifs_err(c, "max levels %d, znode level %d",
305 			  UBIFS_MAX_LEVELS, znode->level);
306 		err = 1;
307 		goto out_dump;
308 	}
309 
310 	for (i = 0; i < znode->child_cnt; i++) {
311 		const struct ubifs_branch *br = ubifs_idx_branch(c, idx, i);
312 		struct ubifs_zbranch *zbr = &znode->zbranch[i];
313 
314 		key_read(c, &br->key, &zbr->key);
315 		zbr->lnum = le32_to_cpu(br->lnum);
316 		zbr->offs = le32_to_cpu(br->offs);
317 		zbr->len  = le32_to_cpu(br->len);
318 		zbr->znode = NULL;
319 
320 		/* Validate branch */
321 
322 		if (zbr->lnum < c->main_first ||
323 		    zbr->lnum >= c->leb_cnt || zbr->offs < 0 ||
324 		    zbr->offs + zbr->len > c->leb_size || zbr->offs & 7) {
325 			ubifs_err(c, "bad branch %d", i);
326 			err = 2;
327 			goto out_dump;
328 		}
329 
330 		switch (key_type(c, &zbr->key)) {
331 		case UBIFS_INO_KEY:
332 		case UBIFS_DATA_KEY:
333 		case UBIFS_DENT_KEY:
334 		case UBIFS_XENT_KEY:
335 			break;
336 		default:
337 			ubifs_err(c, "bad key type at slot %d: %d",
338 				  i, key_type(c, &zbr->key));
339 			err = 3;
340 			goto out_dump;
341 		}
342 
343 		if (znode->level)
344 			continue;
345 
346 		type = key_type(c, &zbr->key);
347 		if (c->ranges[type].max_len == 0) {
348 			if (zbr->len != c->ranges[type].len) {
349 				ubifs_err(c, "bad target node (type %d) length (%d)",
350 					  type, zbr->len);
351 				ubifs_err(c, "have to be %d", c->ranges[type].len);
352 				err = 4;
353 				goto out_dump;
354 			}
355 		} else if (zbr->len < c->ranges[type].min_len ||
356 			   zbr->len > c->ranges[type].max_len) {
357 			ubifs_err(c, "bad target node (type %d) length (%d)",
358 				  type, zbr->len);
359 			ubifs_err(c, "have to be in range of %d-%d",
360 				  c->ranges[type].min_len,
361 				  c->ranges[type].max_len);
362 			err = 5;
363 			goto out_dump;
364 		}
365 	}
366 
367 	/*
368 	 * Ensure that the next key is greater or equivalent to the
369 	 * previous one.
370 	 */
371 	for (i = 0; i < znode->child_cnt - 1; i++) {
372 		const union ubifs_key *key1, *key2;
373 
374 		key1 = &znode->zbranch[i].key;
375 		key2 = &znode->zbranch[i + 1].key;
376 
377 		cmp = keys_cmp(c, key1, key2);
378 		if (cmp > 0) {
379 			ubifs_err(c, "bad key order (keys %d and %d)", i, i + 1);
380 			err = 6;
381 			goto out_dump;
382 		} else if (cmp == 0 && !is_hash_key(c, key1)) {
383 			/* These can only be keys with colliding hash */
384 			ubifs_err(c, "keys %d and %d are not hashed but equivalent",
385 				  i, i + 1);
386 			err = 7;
387 			goto out_dump;
388 		}
389 	}
390 
391 	kfree(idx);
392 	return 0;
393 
394 out_dump:
395 	ubifs_err(c, "bad indexing node at LEB %d:%d, error %d", lnum, offs, err);
396 	ubifs_dump_node(c, idx);
397 	kfree(idx);
398 	return -EINVAL;
399 }
400 
401 /**
402  * ubifs_load_znode - load znode to TNC cache.
403  * @c: UBIFS file-system description object
404  * @zbr: znode branch
405  * @parent: znode's parent
406  * @iip: index in parent
407  *
408  * This function loads znode pointed to by @zbr into the TNC cache and
409  * returns pointer to it in case of success and a negative error code in case
410  * of failure.
411  */
ubifs_load_znode(struct ubifs_info * c,struct ubifs_zbranch * zbr,struct ubifs_znode * parent,int iip)412 struct ubifs_znode *ubifs_load_znode(struct ubifs_info *c,
413 				     struct ubifs_zbranch *zbr,
414 				     struct ubifs_znode *parent, int iip)
415 {
416 	int err;
417 	struct ubifs_znode *znode;
418 
419 	ubifs_assert(c, !zbr->znode);
420 	/*
421 	 * A slab cache is not presently used for znodes because the znode size
422 	 * depends on the fanout which is stored in the superblock.
423 	 */
424 	znode = kzalloc(c->max_znode_sz, GFP_NOFS);
425 	if (!znode)
426 		return ERR_PTR(-ENOMEM);
427 
428 	err = read_znode(c, zbr->lnum, zbr->offs, zbr->len, znode);
429 	if (err)
430 		goto out;
431 
432 	atomic_long_inc(&c->clean_zn_cnt);
433 
434 	/*
435 	 * Increment the global clean znode counter as well. It is OK that
436 	 * global and per-FS clean znode counters may be inconsistent for some
437 	 * short time (because we might be preempted at this point), the global
438 	 * one is only used in shrinker.
439 	 */
440 	atomic_long_inc(&ubifs_clean_zn_cnt);
441 
442 	zbr->znode = znode;
443 	znode->parent = parent;
444 	znode->time = ktime_get_seconds();
445 	znode->iip = iip;
446 
447 	return znode;
448 
449 out:
450 	kfree(znode);
451 	return ERR_PTR(err);
452 }
453 
454 /**
455  * ubifs_tnc_read_node - read a leaf node from the flash media.
456  * @c: UBIFS file-system description object
457  * @zbr: key and position of the node
458  * @node: node is returned here
459  *
460  * This function reads a node defined by @zbr from the flash media. Returns
461  * zero in case of success or a negative negative error code in case of
462  * failure.
463  */
ubifs_tnc_read_node(struct ubifs_info * c,struct ubifs_zbranch * zbr,void * node)464 int ubifs_tnc_read_node(struct ubifs_info *c, struct ubifs_zbranch *zbr,
465 			void *node)
466 {
467 	union ubifs_key key1, *key = &zbr->key;
468 	int err, type = key_type(c, key);
469 	struct ubifs_wbuf *wbuf;
470 
471 	/*
472 	 * 'zbr' has to point to on-flash node. The node may sit in a bud and
473 	 * may even be in a write buffer, so we have to take care about this.
474 	 */
475 	wbuf = ubifs_get_wbuf(c, zbr->lnum);
476 	if (wbuf)
477 		err = ubifs_read_node_wbuf(wbuf, node, type, zbr->len,
478 					   zbr->lnum, zbr->offs);
479 	else
480 		err = ubifs_read_node(c, node, type, zbr->len, zbr->lnum,
481 				      zbr->offs);
482 
483 	if (err) {
484 		dbg_tnck(key, "key ");
485 		return err;
486 	}
487 
488 	/* Make sure the key of the read node is correct */
489 	key_read(c, node + UBIFS_KEY_OFFSET, &key1);
490 	if (!keys_eq(c, key, &key1)) {
491 		ubifs_err(c, "bad key in node at LEB %d:%d",
492 			  zbr->lnum, zbr->offs);
493 		dbg_tnck(key, "looked for key ");
494 		dbg_tnck(&key1, "but found node's key ");
495 		ubifs_dump_node(c, node);
496 		return -EINVAL;
497 	}
498 
499 	return 0;
500 }
501