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