Whamcloud - gitweb
LU-32 osd: keep root node BH ref of IAM container
[fs/lustre-release.git] / lustre / osd-ldiskfs / osd_iam.c
1 /* -*- mode: c; c-basic-offset: 8; indent-tabs-mode: nil; -*-
2  * vim:expandtab:shiftwidth=8:tabstop=8:
3  *
4  * GPL HEADER START
5  *
6  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License version 2 only,
10  * as published by the Free Software Foundation.
11  *
12  * This program is distributed in the hope that it will be useful, but
13  * WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * General Public License version 2 for more details (a copy is included
16  * in the LICENSE file that accompanied this code).
17  *
18  * You should have received a copy of the GNU General Public License
19  * version 2 along with this program; If not, see [sun.com URL with a
20  * copy of GPLv2].
21  *
22  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
23  * CA 95054 USA or visit www.sun.com if you need additional information or
24  * have any questions.
25  *
26  * GPL HEADER END
27  */
28 /*
29  * Copyright (c) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
30  * Use is subject to license terms.
31  */
32 /*
33  * This file is part of Lustre, http://www.lustre.org/
34  * Lustre is a trademark of Sun Microsystems, Inc.
35  *
36  * iam.c
37  * Top-level entry points into iam module
38  *
39  * Author: Wang Di <wangdi@clusterfs.com>
40  * Author: Nikita Danilov <nikita@clusterfs.com>
41  */
42
43 /*
44  * iam: big theory statement.
45  *
46  * iam (Index Access Module) is a module providing abstraction of persistent
47  * transactional container on top of generalized ldiskfs htree.
48  *
49  * iam supports:
50  *
51  *     - key, pointer, and record size specifiable per container.
52  *
53  *     - trees taller than 2 index levels.
54  *
55  *     - read/write to existing ldiskfs htree directories as iam containers.
56  *
57  * iam container is a tree, consisting of leaf nodes containing keys and
58  * records stored in this container, and index nodes, containing keys and
59  * pointers to leaf or index nodes.
60  *
61  * iam does not work with keys directly, instead it calls user-supplied key
62  * comparison function (->dpo_keycmp()).
63  *
64  * Pointers are (currently) interpreted as logical offsets (measured in
65  * blocksful) within underlying flat file on top of which iam tree lives.
66  *
67  * On-disk format:
68  *
69  * iam mostly tries to reuse existing htree formats.
70  *
71  * Format of index node:
72  *
73  * +-----+-------+-------+-------+------+-------+------------+
74  * |     | count |       |       |      |       |            |
75  * | gap |   /   | entry | entry | .... | entry | free space |
76  * |     | limit |       |       |      |       |            |
77  * +-----+-------+-------+-------+------+-------+------------+
78  *
79  *       gap           this part of node is never accessed by iam code. It
80  *                     exists for binary compatibility with ldiskfs htree (that,
81  *                     in turn, stores fake struct ext2_dirent for ext2
82  *                     compatibility), and to keep some unspecified per-node
83  *                     data. Gap can be different for root and non-root index
84  *                     nodes. Gap size can be specified for each container
85  *                     (gap of 0 is allowed).
86  *
87  *       count/limit   current number of entries in this node, and the maximal
88  *                     number of entries that can fit into node. count/limit
89  *                     has the same size as entry, and is itself counted in
90  *                     count.
91  *
92  *       entry         index entry: consists of a key immediately followed by
93  *                     a pointer to a child node. Size of a key and size of a
94  *                     pointer depends on container. Entry has neither
95  *                     alignment nor padding.
96  *
97  *       free space    portion of node new entries are added to
98  *
99  * Entries in index node are sorted by their key value.
100  *
101  * Format of a leaf node is not specified. Generic iam code accesses leaf
102  * nodes through ->id_leaf methods in struct iam_descr.
103  *
104  */
105
106 #include <linux/module.h>
107 #include <linux/fs.h>
108 #include <linux/pagemap.h>
109 #include <linux/time.h>
110 #include <linux/fcntl.h>
111 #include <linux/stat.h>
112 #include <linux/string.h>
113 #include <linux/quotaops.h>
114 #include <linux/buffer_head.h>
115 #include <linux/smp_lock.h>
116 #include "osd_internal.h"
117
118 #include "xattr.h"
119 #include "acl.h"
120
121 /*
122  * List of all registered formats.
123  *
124  * No locking. Callers synchronize.
125  */
126 static CFS_LIST_HEAD(iam_formats);
127
128 void iam_format_register(struct iam_format *fmt)
129 {
130         cfs_list_add(&fmt->if_linkage, &iam_formats);
131 }
132 EXPORT_SYMBOL(iam_format_register);
133
134 /*
135  * Determine format of given container. This is done by scanning list of
136  * registered formats and calling ->if_guess() method of each in turn.
137  */
138 static int iam_format_guess(struct iam_container *c)
139 {
140         int result;
141         struct iam_format *fmt;
142
143         /*
144          * XXX temporary initialization hook.
145          */
146         {
147                 static int initialized = 0;
148
149                 if (!initialized) {
150                         iam_lvar_format_init();
151                         iam_lfix_format_init();
152                         initialized = 1;
153                 }
154         }
155
156         result = -ENOENT;
157         cfs_list_for_each_entry(fmt, &iam_formats, if_linkage) {
158                 result = fmt->if_guess(c);
159                 if (result == 0)
160                         break;
161         }
162         return result;
163 }
164
165 /*
166  * Initialize container @c.
167  */
168 int iam_container_init(struct iam_container *c,
169                        struct iam_descr *descr, struct inode *inode)
170 {
171         memset(c, 0, sizeof *c);
172         c->ic_descr  = descr;
173         c->ic_object = inode;
174         cfs_init_rwsem(&c->ic_sem);
175         return 0;
176 }
177 EXPORT_SYMBOL(iam_container_init);
178
179 /*
180  * Determine container format.
181  */
182 int iam_container_setup(struct iam_container *c)
183 {
184         return iam_format_guess(c);
185 }
186 EXPORT_SYMBOL(iam_container_setup);
187
188 /*
189  * Finalize container @c, release all resources.
190  */
191 void iam_container_fini(struct iam_container *c)
192 {
193         brelse(c->ic_root_bh);
194         c->ic_root_bh = NULL;
195 }
196 EXPORT_SYMBOL(iam_container_fini);
197
198 void iam_path_init(struct iam_path *path, struct iam_container *c,
199                    struct iam_path_descr *pd)
200 {
201         memset(path, 0, sizeof *path);
202         path->ip_container = c;
203         path->ip_frame = path->ip_frames;
204         path->ip_data = pd;
205         path->ip_leaf.il_path = path;
206 }
207
208 static void iam_leaf_fini(struct iam_leaf *leaf);
209
210 void iam_path_release(struct iam_path *path)
211 {
212         int i;
213
214         for (i = 0; i < ARRAY_SIZE(path->ip_frames); i++) {
215                 if (path->ip_frames[i].bh != NULL) {
216                         brelse(path->ip_frames[i].bh);
217                         path->ip_frames[i].bh = NULL;
218                 }
219         }
220 }
221
222 void iam_path_fini(struct iam_path *path)
223 {
224         iam_leaf_fini(&path->ip_leaf);
225         iam_path_release(path);
226 }
227
228
229 void iam_path_compat_init(struct iam_path_compat *path, struct inode *inode)
230 {
231         int i;
232
233         path->ipc_hinfo = &path->ipc_hinfo_area;
234         for (i = 0; i < ARRAY_SIZE(path->ipc_scratch); ++i)
235                 path->ipc_descr.ipd_key_scratch[i] =
236                         (struct iam_ikey *)&path->ipc_scratch[i];
237
238         iam_path_init(&path->ipc_path, &path->ipc_container, &path->ipc_descr);
239 }
240
241 void iam_path_compat_fini(struct iam_path_compat *path)
242 {
243         iam_path_fini(&path->ipc_path);
244 }
245
246 /*
247  * Helper function initializing iam_path_descr and its key scratch area.
248  */
249 struct iam_path_descr *iam_ipd_alloc(void *area, int keysize)
250 {
251         struct iam_path_descr *ipd;
252         void *karea;
253         int i;
254
255         ipd = area;
256         karea = ipd + 1;
257         for (i = 0; i < ARRAY_SIZE(ipd->ipd_key_scratch); ++i, karea += keysize)
258                 ipd->ipd_key_scratch[i] = karea;
259         return ipd;
260 }
261 EXPORT_SYMBOL(iam_ipd_alloc);
262
263 void iam_ipd_free(struct iam_path_descr *ipd)
264 {
265 }
266 EXPORT_SYMBOL(iam_ipd_free);
267
268 int iam_node_read(struct iam_container *c, iam_ptr_t ptr,
269                   handle_t *h, struct buffer_head **bh)
270 {
271         int result = 0;
272
273         /* NB: it can be called by iam_lfix_guess() which is still at
274          * very early stage, c->ic_root_bh and c->ic_descr->id_ops
275          * haven't been intialized yet.
276          * Also, we don't have this for IAM dir.
277          */
278         if (c->ic_root_bh != NULL &&
279             c->ic_descr->id_ops->id_root_ptr(c) == ptr) {
280                 get_bh(c->ic_root_bh);
281                 *bh = c->ic_root_bh;
282                 return 0;
283         }
284
285         *bh = ldiskfs_bread(h, c->ic_object, (int)ptr, 0, &result);
286         if (*bh == NULL)
287                 result = -EIO;
288         return result;
289 }
290
291 /*
292  * Return pointer to current leaf record. Pointer is valid while corresponding
293  * leaf node is locked and pinned.
294  */
295 static struct iam_rec *iam_leaf_rec(const struct iam_leaf *leaf)
296 {
297         return iam_leaf_ops(leaf)->rec(leaf);
298 }
299
300 /*
301  * Return pointer to the current leaf key. This function returns pointer to
302  * the key stored in node.
303  *
304  * Caller should assume that returned pointer is only valid while leaf node is
305  * pinned and locked.
306  */
307 static struct iam_key *iam_leaf_key(const struct iam_leaf *leaf)
308 {
309         return iam_leaf_ops(leaf)->key(leaf);
310 }
311
312 static int iam_leaf_key_size(const struct iam_leaf *leaf)
313 {
314         return iam_leaf_ops(leaf)->key_size(leaf);
315 }
316
317 static struct iam_ikey *iam_leaf_ikey(const struct iam_leaf *leaf,
318                                       struct iam_ikey *key)
319 {
320         return iam_leaf_ops(leaf)->ikey(leaf, key);
321 }
322
323 static int iam_leaf_keycmp(const struct iam_leaf *leaf,
324                            const struct iam_key *key)
325 {
326         return iam_leaf_ops(leaf)->key_cmp(leaf, key);
327 }
328
329 static int iam_leaf_keyeq(const struct iam_leaf *leaf,
330                           const struct iam_key *key)
331 {
332         return iam_leaf_ops(leaf)->key_eq(leaf, key);
333 }
334
335 #if LDISKFS_INVARIANT_ON
336 static int iam_leaf_check(struct iam_leaf *leaf);
337 extern int dx_node_check(struct iam_path *p, struct iam_frame *f);
338
339 static int iam_path_check(struct iam_path *p)
340 {
341         int i;
342         int result;
343         struct iam_frame *f;
344         struct iam_descr *param;
345
346         result = 1;
347         param = iam_path_descr(p);
348         for (i = 0; result && i < ARRAY_SIZE(p->ip_frames); ++i) {
349                 f = &p->ip_frames[i];
350                 if (f->bh != NULL) {
351                         result = dx_node_check(p, f);
352                         if (result)
353                                 result = !param->id_ops->id_node_check(p, f);
354                 }
355         }
356         if (result && p->ip_leaf.il_bh != NULL)
357                 result = iam_leaf_check(&p->ip_leaf);
358         if (result == 0) {
359                 ldiskfs_std_error(iam_path_obj(p)->i_sb, result);
360         }
361         return result;
362 }
363 #endif
364
365 static int iam_leaf_load(struct iam_path *path)
366 {
367         iam_ptr_t block;
368         int err;
369         struct iam_container *c;
370         struct buffer_head   *bh;
371         struct iam_leaf      *leaf;
372         struct iam_descr     *descr;
373
374         c     = path->ip_container;
375         leaf  = &path->ip_leaf;
376         descr = iam_path_descr(path);
377         block = path->ip_frame->leaf;
378         if (block == 0) {
379                 /* XXX bug 11027 */
380                 printk(CFS_KERN_EMERG "wrong leaf: %lu %d [%p %p %p]\n",
381                        (long unsigned)path->ip_frame->leaf,
382                        dx_get_count(dx_node_get_entries(path, path->ip_frame)),
383                        path->ip_frames[0].bh, path->ip_frames[1].bh,
384                        path->ip_frames[2].bh);
385         }
386         err   = descr->id_ops->id_node_read(c, block, NULL, &bh);
387         if (err == 0) {
388                 leaf->il_bh = bh;
389                 leaf->il_curidx = block;
390                 err = iam_leaf_ops(leaf)->init(leaf);
391                 assert_inv(ergo(err == 0, iam_leaf_check(leaf)));
392         }
393         return err;
394 }
395
396 static void iam_unlock_htree(struct inode *dir, struct dynlock_handle *lh)
397 {
398         if (lh != NULL)
399                 dynlock_unlock(&LDISKFS_I(dir)->i_htree_lock, lh);
400 }
401
402
403 static void iam_leaf_unlock(struct iam_leaf *leaf)
404 {
405         if (leaf->il_lock != NULL) {
406                 iam_unlock_htree(iam_leaf_container(leaf)->ic_object,
407                                 leaf->il_lock);
408                 do_corr(schedule());
409                 leaf->il_lock = NULL;
410         }
411 }
412
413 static void iam_leaf_fini(struct iam_leaf *leaf)
414 {
415         if (leaf->il_path != NULL) {
416                 iam_leaf_unlock(leaf);
417                 assert_inv(ergo(leaf->il_bh != NULL, iam_leaf_check(leaf)));
418                 iam_leaf_ops(leaf)->fini(leaf);
419                 if (leaf->il_bh) {
420                         brelse(leaf->il_bh);
421                         leaf->il_bh = NULL;
422                         leaf->il_curidx = 0;
423                 }
424         }
425 }
426
427 static void iam_leaf_start(struct iam_leaf *folio)
428 {
429         iam_leaf_ops(folio)->start(folio);
430 }
431
432 void iam_leaf_next(struct iam_leaf *folio)
433 {
434         iam_leaf_ops(folio)->next(folio);
435 }
436
437 static void iam_leaf_rec_add(struct iam_leaf *leaf, const struct iam_key *key,
438                              const struct iam_rec *rec)
439 {
440         iam_leaf_ops(leaf)->rec_add(leaf, key, rec);
441 }
442
443 static void iam_rec_del(struct iam_leaf *leaf, int shift)
444 {
445         iam_leaf_ops(leaf)->rec_del(leaf, shift);
446 }
447
448 int iam_leaf_at_end(const struct iam_leaf *leaf)
449 {
450         return iam_leaf_ops(leaf)->at_end(leaf);
451 }
452
453 void iam_leaf_split(struct iam_leaf *l, struct buffer_head **bh, iam_ptr_t nr)
454 {
455         iam_leaf_ops(l)->split(l, bh, nr);
456 }
457
458 int iam_leaf_can_add(const struct iam_leaf *l,
459                      const struct iam_key *k, const struct iam_rec *r)
460 {
461         return iam_leaf_ops(l)->can_add(l, k, r);
462 }
463
464 #if LDISKFS_INVARIANT_ON
465 static int iam_leaf_check(struct iam_leaf *leaf)
466 {
467         return 1;
468 #if 0
469         struct iam_lentry    *orig;
470         struct iam_path      *path;
471         struct iam_container *bag;
472         struct iam_ikey       *k0;
473         struct iam_ikey       *k1;
474         int result;
475         int first;
476
477         orig = leaf->il_at;
478         path = iam_leaf_path(leaf);
479         bag  = iam_leaf_container(leaf);
480
481         result = iam_leaf_ops(leaf)->init(leaf);
482         if (result != 0)
483                 return result;
484
485         first = 1;
486         iam_leaf_start(leaf);
487         k0 = iam_path_ikey(path, 0);
488         k1 = iam_path_ikey(path, 1);
489         while (!iam_leaf_at_end(leaf)) {
490                 iam_ikeycpy(bag, k0, k1);
491                 iam_ikeycpy(bag, k1, iam_leaf_ikey(leaf, k1));
492                 if (!first && iam_ikeycmp(bag, k0, k1) > 0) {
493                         return 0;
494                 }
495                 first = 0;
496                 iam_leaf_next(leaf);
497         }
498         leaf->il_at = orig;
499         return 1;
500 #endif
501 }
502 #endif
503
504 static int iam_txn_dirty(handle_t *handle,
505                          struct iam_path *path, struct buffer_head *bh)
506 {
507         int result;
508
509         result = ldiskfs_journal_dirty_metadata(handle, bh);
510         if (result != 0)
511                 ldiskfs_std_error(iam_path_obj(path)->i_sb, result);
512         return result;
513 }
514
515 static int iam_txn_add(handle_t *handle,
516                        struct iam_path *path, struct buffer_head *bh)
517 {
518         int result;
519
520         result = ldiskfs_journal_get_write_access(handle, bh);
521         if (result != 0)
522                 ldiskfs_std_error(iam_path_obj(path)->i_sb, result);
523         return result;
524 }
525
526 /***********************************************************************/
527 /* iterator interface                                                  */
528 /***********************************************************************/
529
530 static enum iam_it_state it_state(const struct iam_iterator *it)
531 {
532         return it->ii_state;
533 }
534
535 /*
536  * Helper function returning scratch key.
537  */
538 static struct iam_container *iam_it_container(const struct iam_iterator *it)
539 {
540         return it->ii_path.ip_container;
541 }
542
543 static inline int it_keycmp(const struct iam_iterator *it,
544                             const struct iam_key *k)
545 {
546         return iam_leaf_keycmp(&it->ii_path.ip_leaf, k);
547 }
548
549 static inline int it_keyeq(const struct iam_iterator *it,
550                            const struct iam_key *k)
551 {
552         return iam_leaf_keyeq(&it->ii_path.ip_leaf, k);
553 }
554
555 static int it_ikeycmp(const struct iam_iterator *it, const struct iam_ikey *ik)
556 {
557         return iam_ikeycmp(it->ii_path.ip_container,
558                            iam_leaf_ikey(&it->ii_path.ip_leaf,
559                                          iam_path_ikey(&it->ii_path, 0)), ik);
560 }
561
562 static inline int it_at_rec(const struct iam_iterator *it)
563 {
564         return !iam_leaf_at_end(&it->ii_path.ip_leaf);
565 }
566
567 static inline int it_before(const struct iam_iterator *it)
568 {
569         return it_state(it) == IAM_IT_SKEWED && it_at_rec(it);
570 }
571
572 /*
573  * Helper wrapper around iam_it_get(): returns 0 (success) only when record
574  * with exactly the same key as asked is found.
575  */
576 static int iam_it_get_exact(struct iam_iterator *it, const struct iam_key *k)
577 {
578         int result;
579
580         result = iam_it_get(it, k);
581         if (result > 0)
582                 result = 0;
583         else if (result == 0)
584                 /*
585                  * Return -ENOENT if cursor is located above record with a key
586                  * different from one specified, or in the empty leaf.
587                  *
588                  * XXX returning -ENOENT only works if iam_it_get() never
589                  * returns -ENOENT as a legitimate error.
590                  */
591                 result = -ENOENT;
592         return result;
593 }
594
595 void iam_container_write_lock(struct iam_container *ic)
596 {
597         cfs_down_write(&ic->ic_sem);
598 }
599
600 void iam_container_write_unlock(struct iam_container *ic)
601 {
602         cfs_up_write(&ic->ic_sem);
603 }
604
605 void iam_container_read_lock(struct iam_container *ic)
606 {
607         cfs_down_read(&ic->ic_sem);
608 }
609
610 void iam_container_read_unlock(struct iam_container *ic)
611 {
612         cfs_up_read(&ic->ic_sem);
613 }
614
615 /*
616  * Initialize iterator to IAM_IT_DETACHED state.
617  *
618  * postcondition: it_state(it) == IAM_IT_DETACHED
619  */
620 int  iam_it_init(struct iam_iterator *it, struct iam_container *c, __u32 flags,
621                  struct iam_path_descr *pd)
622 {
623         memset(it, 0, sizeof *it);
624         it->ii_flags  = flags;
625         it->ii_state  = IAM_IT_DETACHED;
626         iam_path_init(&it->ii_path, c, pd);
627         return 0;
628 }
629 EXPORT_SYMBOL(iam_it_init);
630
631 /*
632  * Finalize iterator and release all resources.
633  *
634  * precondition: it_state(it) == IAM_IT_DETACHED
635  */
636 void iam_it_fini(struct iam_iterator *it)
637 {
638         assert_corr(it_state(it) == IAM_IT_DETACHED);
639         iam_path_fini(&it->ii_path);
640 }
641 EXPORT_SYMBOL(iam_it_fini);
642
643 /*
644  * this locking primitives are used to protect parts
645  * of dir's htree. protection unit is block: leaf or index
646  */
647 struct dynlock_handle *iam_lock_htree(struct inode *dir, unsigned long value,
648                                      enum dynlock_type lt)
649 {
650         return dynlock_lock(&LDISKFS_I(dir)->i_htree_lock, value, lt, GFP_NOFS);
651 }
652
653
654
655 int iam_index_lock(struct iam_path *path, struct dynlock_handle **lh)
656 {
657         struct iam_frame *f;
658
659         for (f = path->ip_frame; f >= path->ip_frames; --f, ++lh) {
660                 do_corr(schedule());
661                 *lh = iam_lock_htree(iam_path_obj(path), f->curidx, DLT_READ);
662                 if (*lh == NULL)
663                         return -ENOMEM;
664         }
665         return 0;
666 }
667
668 /*
669  * Fast check for frame consistency.
670  */
671 static int iam_check_fast(struct iam_path *path, struct iam_frame *frame)
672 {
673         struct iam_container *bag;
674         struct iam_entry *next;
675         struct iam_entry *last;
676         struct iam_entry *entries;
677         struct iam_entry *at;
678
679         bag     = path->ip_container;
680         at      = frame->at;
681         entries = frame->entries;
682         last    = iam_entry_shift(path, entries, dx_get_count(entries) - 1);
683
684         if (unlikely(at > last))
685                 return -EAGAIN;
686
687         if (unlikely(dx_get_block(path, at) != frame->leaf))
688                 return -EAGAIN;
689
690         if (unlikely(iam_ikeycmp(bag, iam_ikey_at(path, at),
691                                  path->ip_ikey_target) > 0))
692                 return -EAGAIN;
693
694         next = iam_entry_shift(path, at, +1);
695         if (next <= last) {
696                 if (unlikely(iam_ikeycmp(bag, iam_ikey_at(path, next),
697                                          path->ip_ikey_target) <= 0))
698                         return -EAGAIN;
699         }
700         return 0;
701 }
702
703 int dx_index_is_compat(struct iam_path *path)
704 {
705         return iam_path_descr(path) == NULL;
706 }
707
708 /*
709  * dx_find_position
710  *
711  * search position of specified hash in index
712  *
713  */
714
715 struct iam_entry *iam_find_position(struct iam_path *path,
716                                    struct iam_frame *frame)
717 {
718         int count;
719         struct iam_entry *p;
720         struct iam_entry *q;
721         struct iam_entry *m;
722
723         count = dx_get_count(frame->entries);
724         assert_corr(count && count <= dx_get_limit(frame->entries));
725         p = iam_entry_shift(path, frame->entries,
726                             dx_index_is_compat(path) ? 1 : 2);
727         q = iam_entry_shift(path, frame->entries, count - 1);
728         while (p <= q) {
729                 m = iam_entry_shift(path, p, iam_entry_diff(path, q, p) / 2);
730                 if (iam_ikeycmp(path->ip_container, iam_ikey_at(path, m),
731                                 path->ip_ikey_target) > 0)
732                         q = iam_entry_shift(path, m, -1);
733                 else
734                         p = iam_entry_shift(path, m, +1);
735         }
736         return iam_entry_shift(path, p, -1);
737 }
738
739
740
741 static iam_ptr_t iam_find_ptr(struct iam_path *path, struct iam_frame *frame)
742 {
743         return dx_get_block(path, iam_find_position(path, frame));
744 }
745
746 void iam_insert_key(struct iam_path *path, struct iam_frame *frame,
747                     const struct iam_ikey *key, iam_ptr_t ptr)
748 {
749         struct iam_entry *entries = frame->entries;
750         struct iam_entry *new = iam_entry_shift(path, frame->at, +1);
751         int count = dx_get_count(entries);
752
753         /*
754          * Unfortunately we cannot assert this, as this function is sometimes
755          * called by VFS under i_sem and without pdirops lock.
756          */
757         assert_corr(1 || iam_frame_is_locked(path, frame));
758         assert_corr(count < dx_get_limit(entries));
759         assert_corr(frame->at < iam_entry_shift(path, entries, count));
760         assert_inv(dx_node_check(path, frame));
761
762         memmove(iam_entry_shift(path, new, 1), new,
763                 (char *)iam_entry_shift(path, entries, count) - (char *)new);
764         dx_set_ikey(path, new, key);
765         dx_set_block(path, new, ptr);
766         dx_set_count(entries, count + 1);
767         assert_inv(dx_node_check(path, frame));
768 }
769
770 void iam_insert_key_lock(struct iam_path *path, struct iam_frame *frame,
771                          const struct iam_ikey *key, iam_ptr_t ptr)
772 {
773         iam_lock_bh(frame->bh);
774         iam_insert_key(path, frame, key, ptr);
775         iam_unlock_bh(frame->bh);
776 }
777 /*
778  * returns 0 if path was unchanged, -EAGAIN otherwise.
779  */
780 static int iam_check_path(struct iam_path *path, struct iam_frame *frame)
781 {
782         int equal;
783
784         iam_lock_bh(frame->bh);
785         equal = iam_check_fast(path, frame) == 0 ||
786                 frame->leaf == iam_find_ptr(path, frame);
787         DX_DEVAL(iam_lock_stats.dls_bh_again += !equal);
788         iam_unlock_bh(frame->bh);
789
790         return equal ? 0 : -EAGAIN;
791 }
792
793 static int iam_lookup_try(struct iam_path *path)
794 {
795         u32 ptr;
796         int err = 0;
797         int i;
798
799         struct iam_descr *param;
800         struct iam_frame *frame;
801         struct iam_container *c;
802
803         param = iam_path_descr(path);
804         c = path->ip_container;
805
806         ptr = param->id_ops->id_root_ptr(c);
807         for (frame = path->ip_frames, i = 0; i <= path->ip_indirect;
808              ++frame, ++i) {
809                 err = param->id_ops->id_node_read(c, (iam_ptr_t)ptr, NULL,
810                                                   &frame->bh);
811                 do_corr(schedule());
812
813                 iam_lock_bh(frame->bh);
814                 /*
815                  * node must be initialized under bh lock because concurrent
816                  * creation procedure may change it and iam_lookup_try() will
817                  * see obsolete tree height. -bzzz
818                  */
819                 if (err != 0)
820                         break;
821
822                 if (LDISKFS_INVARIANT_ON) {
823                         err = param->id_ops->id_node_check(path, frame);
824                         if (err != 0)
825                                 break;
826                 }
827
828                 err = param->id_ops->id_node_load(path, frame);
829                 if (err != 0)
830                         break;
831
832                 assert_inv(dx_node_check(path, frame));
833                 /*
834                  * splitting may change root index block and move hash we're
835                  * looking for into another index block so, we have to check
836                  * this situation and repeat from begining if path got changed
837                  * -bzzz
838                  */
839                 if (i > 0) {
840                         err = iam_check_path(path, frame - 1);
841                         if (err != 0)
842                                 break;
843                 }
844
845                 frame->at = iam_find_position(path, frame);
846                 frame->curidx = ptr;
847                 frame->leaf = ptr = dx_get_block(path, frame->at);
848
849                 iam_unlock_bh(frame->bh);
850                 do_corr(schedule());
851         }
852         if (err != 0)
853                 iam_unlock_bh(frame->bh);
854         path->ip_frame = --frame;
855         return err;
856 }
857
858 static int __iam_path_lookup(struct iam_path *path)
859 {
860         int err;
861         int i;
862
863         for (i = 0; i < DX_MAX_TREE_HEIGHT; ++ i)
864                 assert(path->ip_frames[i].bh == NULL);
865
866         do {
867                 err = iam_lookup_try(path);
868                 do_corr(schedule());
869                 if (err != 0)
870                         iam_path_fini(path);
871         } while (err == -EAGAIN);
872
873         return err;
874 }
875
876 /*
877  * returns 0 if path was unchanged, -EAGAIN otherwise.
878  */
879 static int iam_check_full_path(struct iam_path *path, int search)
880 {
881         struct iam_frame *bottom;
882         struct iam_frame *scan;
883         int i;
884         int result;
885
886         do_corr(schedule());
887
888         for (bottom = path->ip_frames, i = 0;
889              i < DX_MAX_TREE_HEIGHT && bottom->bh != NULL; ++bottom, ++i) {
890                 ; /* find last filled in frame */
891         }
892
893         /*
894          * Lock frames, bottom to top.
895          */
896         for (scan = bottom - 1; scan >= path->ip_frames; --scan)
897                 iam_lock_bh(scan->bh);
898         /*
899          * Check them top to bottom.
900          */
901         result = 0;
902         for (scan = path->ip_frames; scan < bottom; ++scan) {
903                 struct iam_entry *pos;
904
905                 if (search) {
906                         if (iam_check_fast(path, scan) == 0)
907                                 continue;
908
909                         pos = iam_find_position(path, scan);
910                         if (scan->leaf != dx_get_block(path, pos)) {
911                                 result = -EAGAIN;
912                                 break;
913                         }
914                         scan->at = pos;
915                 } else {
916                         pos = iam_entry_shift(path, scan->entries,
917                                               dx_get_count(scan->entries) - 1);
918                         if (scan->at > pos ||
919                             scan->leaf != dx_get_block(path, scan->at)) {
920                                 result = -EAGAIN;
921                                 break;
922                         }
923                 }
924         }
925
926         /*
927          * Unlock top to bottom.
928          */
929         for (scan = path->ip_frames; scan < bottom; ++scan)
930                 iam_unlock_bh(scan->bh);
931         DX_DEVAL(iam_lock_stats.dls_bh_full_again += !!result);
932         do_corr(schedule());
933
934         return result;
935 }
936
937
938 /*
939  * Performs path lookup and returns with found leaf (if any) locked by htree
940  * lock.
941  */
942 int iam_lookup_lock(struct iam_path *path,
943                    struct dynlock_handle **dl, enum dynlock_type lt)
944 {
945         int result;
946         struct inode *dir;
947
948         dir = iam_path_obj(path);
949         while ((result = __iam_path_lookup(path)) == 0) {
950                 do_corr(schedule());
951                 *dl = iam_lock_htree(dir, path->ip_frame->leaf, lt);
952                 if (*dl == NULL) {
953                         iam_path_fini(path);
954                         result = -ENOMEM;
955                         break;
956                 }
957                 do_corr(schedule());
958                 /*
959                  * while locking leaf we just found may get split so we need
960                  * to check this -bzzz
961                  */
962                 if (iam_check_full_path(path, 1) == 0)
963                         break;
964                 iam_unlock_htree(dir, *dl);
965                 *dl = NULL;
966                 iam_path_fini(path);
967         }
968         return result;
969 }
970 /*
971  * Performs tree top-to-bottom traversal starting from root, and loads leaf
972  * node.
973  */
974 static int iam_path_lookup(struct iam_path *path, int index)
975 {
976         struct iam_container *c;
977         struct iam_descr *descr;
978         struct iam_leaf  *leaf;
979         int result;
980
981         c = path->ip_container;
982         leaf = &path->ip_leaf;
983         descr = iam_path_descr(path);
984         result = iam_lookup_lock(path, &leaf->il_lock, DLT_WRITE);
985         assert_inv(iam_path_check(path));
986         do_corr(schedule());
987         if (result == 0) {
988                 result = iam_leaf_load(path);
989                 assert_inv(ergo(result == 0, iam_leaf_check(leaf)));
990                 if (result == 0) {
991                         do_corr(schedule());
992                         if (index)
993                                 result = iam_leaf_ops(leaf)->
994                                         ilookup(leaf, path->ip_ikey_target);
995                         else
996                                 result = iam_leaf_ops(leaf)->
997                                         lookup(leaf, path->ip_key_target);
998                         do_corr(schedule());
999                 }
1000                 if (result < 0)
1001                         iam_leaf_unlock(leaf);
1002         }
1003         return result;
1004 }
1005
1006 /*
1007  * Common part of iam_it_{i,}get().
1008  */
1009 static int __iam_it_get(struct iam_iterator *it, int index)
1010 {
1011         int result;
1012         assert_corr(it_state(it) == IAM_IT_DETACHED);
1013
1014         result = iam_path_lookup(&it->ii_path, index);
1015         if (result >= 0) {
1016                 int collision;
1017
1018                 collision = result & IAM_LOOKUP_LAST;
1019                 switch (result & ~IAM_LOOKUP_LAST) {
1020                 case IAM_LOOKUP_EXACT:
1021                         result = +1;
1022                         it->ii_state = IAM_IT_ATTACHED;
1023                         break;
1024                 case IAM_LOOKUP_OK:
1025                         result = 0;
1026                         it->ii_state = IAM_IT_ATTACHED;
1027                         break;
1028                 case IAM_LOOKUP_BEFORE:
1029                 case IAM_LOOKUP_EMPTY:
1030                         result = 0;
1031                         it->ii_state = IAM_IT_SKEWED;
1032                         break;
1033                 default:
1034                         assert(0);
1035                 }
1036                 result |= collision;
1037         }
1038         /*
1039          * See iam_it_get_exact() for explanation.
1040          */
1041         assert_corr(result != -ENOENT);
1042         return result;
1043 }
1044
1045 /*
1046  * Correct hash, but not the same key was found, iterate through hash
1047  * collision chain, looking for correct record.
1048  */
1049 static int iam_it_collision(struct iam_iterator *it)
1050 {
1051         int result;
1052
1053         assert(ergo(it_at_rec(it), !it_keyeq(it, it->ii_path.ip_key_target)));
1054
1055         while ((result = iam_it_next(it)) == 0) {
1056                 do_corr(schedule());
1057                 if (it_ikeycmp(it, it->ii_path.ip_ikey_target) != 0)
1058                         return -ENOENT;
1059                 if (it_keyeq(it, it->ii_path.ip_key_target))
1060                         return 0;
1061         }
1062         return result;
1063 }
1064
1065 /*
1066  * Attach iterator. After successful completion, @it points to record with
1067  * least key not larger than @k.
1068  *
1069  * Return value: 0: positioned on existing record,
1070  *             +ve: exact position found,
1071  *             -ve: error.
1072  *
1073  * precondition:  it_state(it) == IAM_IT_DETACHED
1074  * postcondition: ergo(result == 0 && it_state(it) == IAM_IT_ATTACHED,
1075  *                     it_keycmp(it, k) <= 0)
1076  */
1077 int iam_it_get(struct iam_iterator *it, const struct iam_key *k)
1078 {
1079         int result;
1080         assert_corr(it_state(it) == IAM_IT_DETACHED);
1081
1082         it->ii_path.ip_ikey_target = NULL;
1083         it->ii_path.ip_key_target  = k;
1084
1085         result = __iam_it_get(it, 0);
1086
1087         if (result == IAM_LOOKUP_LAST) {
1088                 result = iam_it_collision(it);
1089                 if (result != 0) {
1090                         iam_it_put(it);
1091                         iam_it_fini(it);
1092                         result = __iam_it_get(it, 0);
1093                 } else
1094                         result = +1;
1095         }
1096         if (result > 0)
1097                 result &= ~IAM_LOOKUP_LAST;
1098
1099         assert_corr(ergo(result > 0, it_keycmp(it, k) == 0));
1100         assert_corr(ergo(result == 0 && it_state(it) == IAM_IT_ATTACHED,
1101                          it_keycmp(it, k) <= 0));
1102         return result;
1103 }
1104 EXPORT_SYMBOL(iam_it_get);
1105
1106 /*
1107  * Attach iterator by index key.
1108  */
1109 static int iam_it_iget(struct iam_iterator *it, const struct iam_ikey *k)
1110 {
1111         assert_corr(it_state(it) == IAM_IT_DETACHED);
1112
1113         it->ii_path.ip_ikey_target = k;
1114         return __iam_it_get(it, 1) & ~IAM_LOOKUP_LAST;
1115 }
1116
1117 /*
1118  * Attach iterator, and assure it points to the record (not skewed).
1119  *
1120  * Return value: 0: positioned on existing record,
1121  *             +ve: exact position found,
1122  *             -ve: error.
1123  *
1124  * precondition:  it_state(it) == IAM_IT_DETACHED &&
1125  *                !(it->ii_flags&IAM_IT_WRITE)
1126  * postcondition: ergo(result == 0, it_state(it) == IAM_IT_ATTACHED)
1127  */
1128 int iam_it_get_at(struct iam_iterator *it, const struct iam_key *k)
1129 {
1130         int result;
1131         assert_corr(it_state(it) == IAM_IT_DETACHED &&
1132                     !(it->ii_flags&IAM_IT_WRITE));
1133         result = iam_it_get(it, k);
1134         if (result == 0) {
1135                 if (it_state(it) != IAM_IT_ATTACHED) {
1136                         assert_corr(it_state(it) == IAM_IT_SKEWED);
1137                         result = iam_it_next(it);
1138                 }
1139         }
1140         assert_corr(ergo(result >= 0, it_state(it) == IAM_IT_ATTACHED));
1141         return result;
1142 }
1143 EXPORT_SYMBOL(iam_it_get_at);
1144
1145 /*
1146  * Duplicates iterator.
1147  *
1148  * postcondition: it_state(dst) == it_state(src) &&
1149  *                iam_it_container(dst) == iam_it_container(src) &&
1150  *                dst->ii_flags = src->ii_flags &&
1151  *                ergo(it_state(src) == IAM_IT_ATTACHED,
1152  *                     iam_it_rec_get(dst) == iam_it_rec_get(src) &&
1153  *                     iam_it_key_get(dst) == iam_it_key_get(src))
1154  */
1155 void iam_it_dup(struct iam_iterator *dst, const struct iam_iterator *src)
1156 {
1157         dst->ii_flags     = src->ii_flags;
1158         dst->ii_state     = src->ii_state;
1159         /* XXX not yet. iam_path_dup(&dst->ii_path, &src->ii_path); */
1160         /*
1161          * XXX: duplicate lock.
1162          */
1163         assert_corr(it_state(dst) == it_state(src));
1164         assert_corr(iam_it_container(dst) == iam_it_container(src));
1165         assert_corr(dst->ii_flags = src->ii_flags);
1166         assert_corr(ergo(it_state(src) == IAM_IT_ATTACHED,
1167                     iam_it_rec_get(dst) == iam_it_rec_get(src) &&
1168                     iam_it_key_get(dst) == iam_it_key_get(src)));
1169
1170 }
1171
1172 /*
1173  * Detach iterator. Does nothing it detached state.
1174  *
1175  * postcondition: it_state(it) == IAM_IT_DETACHED
1176  */
1177 void iam_it_put(struct iam_iterator *it)
1178 {
1179         if (it->ii_state != IAM_IT_DETACHED) {
1180                 it->ii_state = IAM_IT_DETACHED;
1181                 iam_leaf_fini(&it->ii_path.ip_leaf);
1182         }
1183 }
1184 EXPORT_SYMBOL(iam_it_put);
1185
1186 static struct iam_ikey *iam_it_ikey_get(const struct iam_iterator *it,
1187                                         struct iam_ikey *ikey);
1188
1189
1190 /*
1191  * This function increments the frame pointer to search the next leaf
1192  * block, and reads in the necessary intervening nodes if the search
1193  * should be necessary.  Whether or not the search is necessary is
1194  * controlled by the hash parameter.  If the hash value is even, then
1195  * the search is only continued if the next block starts with that
1196  * hash value.  This is used if we are searching for a specific file.
1197  *
1198  * If the hash value is HASH_NB_ALWAYS, then always go to the next block.
1199  *
1200  * This function returns 1 if the caller should continue to search,
1201  * or 0 if it should not.  If there is an error reading one of the
1202  * index blocks, it will a negative error code.
1203  *
1204  * If start_hash is non-null, it will be filled in with the starting
1205  * hash of the next page.
1206  */
1207 static int iam_htree_advance(struct inode *dir, __u32 hash,
1208                               struct iam_path *path, __u32 *start_hash,
1209                               int compat)
1210 {
1211         struct iam_frame *p;
1212         struct buffer_head *bh;
1213         int err, num_frames = 0;
1214         __u32 bhash;
1215
1216         p = path->ip_frame;
1217         /*
1218          * Find the next leaf page by incrementing the frame pointer.
1219          * If we run out of entries in the interior node, loop around and
1220          * increment pointer in the parent node.  When we break out of
1221          * this loop, num_frames indicates the number of interior
1222          * nodes need to be read.
1223          */
1224         while (1) {
1225                 do_corr(schedule());
1226                 iam_lock_bh(p->bh);
1227                 p->at = iam_entry_shift(path, p->at, +1);
1228                 if (p->at < iam_entry_shift(path, p->entries,
1229                                             dx_get_count(p->entries))) {
1230                         p->leaf = dx_get_block(path, p->at);
1231                         iam_unlock_bh(p->bh);
1232                         break;
1233                 }
1234                 iam_unlock_bh(p->bh);
1235                 if (p == path->ip_frames)
1236                         return 0;
1237                 num_frames++;
1238                 --p;
1239         }
1240
1241         if (compat) {
1242                 /*
1243                  * Htree hash magic.
1244                  */
1245         /*
1246          * If the hash is 1, then continue only if the next page has a
1247          * continuation hash of any value.  This is used for readdir
1248          * handling.  Otherwise, check to see if the hash matches the
1249          * desired contiuation hash.  If it doesn't, return since
1250          * there's no point to read in the successive index pages.
1251          */
1252                 dx_get_ikey(path, p->at, (struct iam_ikey *)&bhash);
1253         if (start_hash)
1254                 *start_hash = bhash;
1255         if ((hash & 1) == 0) {
1256                 if ((bhash & ~1) != hash)
1257                         return 0;
1258         }
1259         }
1260         /*
1261          * If the hash is HASH_NB_ALWAYS, we always go to the next
1262          * block so no check is necessary
1263          */
1264         while (num_frames--) {
1265                 iam_ptr_t idx;
1266
1267                 do_corr(schedule());
1268                 iam_lock_bh(p->bh);
1269                 idx = p->leaf = dx_get_block(path, p->at);
1270                 iam_unlock_bh(p->bh);
1271                 err = iam_path_descr(path)->id_ops->
1272                         id_node_read(path->ip_container, idx, NULL, &bh);
1273                 if (err != 0)
1274                         return err; /* Failure */
1275                 ++p;
1276                 brelse(p->bh);
1277                 assert_corr(p->bh != bh);
1278                 p->bh = bh;
1279                 p->entries = dx_node_get_entries(path, p);
1280                 p->at = iam_entry_shift(path, p->entries, !compat);
1281                 assert_corr(p->curidx != idx);
1282                 p->curidx = idx;
1283                 iam_lock_bh(p->bh);
1284                 assert_corr(p->leaf != dx_get_block(path, p->at));
1285                 p->leaf = dx_get_block(path, p->at);
1286                 iam_unlock_bh(p->bh);
1287                 assert_inv(dx_node_check(path, p));
1288         }
1289         return 1;
1290 }
1291
1292
1293 static inline int iam_index_advance(struct iam_path *path)
1294 {
1295         return iam_htree_advance(iam_path_obj(path), 0, path, NULL, 0);
1296 }
1297
1298 static void iam_unlock_array(struct inode *dir, struct dynlock_handle **lh)
1299 {
1300         int i;
1301
1302         for (i = 0; i < DX_MAX_TREE_HEIGHT; ++i, ++lh) {
1303                 if (*lh != NULL) {
1304                         iam_unlock_htree(dir, *lh);
1305                         *lh = NULL;
1306                 }
1307         }
1308 }
1309 /*
1310  * Advance index part of @path to point to the next leaf. Returns 1 on
1311  * success, 0, when end of container was reached. Leaf node is locked.
1312  */
1313 int iam_index_next(struct iam_container *c, struct iam_path *path)
1314 {
1315         iam_ptr_t cursor;
1316         struct dynlock_handle *lh[DX_MAX_TREE_HEIGHT] = { 0, };
1317         int result;
1318         struct inode *object;
1319
1320         /*
1321          * Locking for iam_index_next()... is to be described.
1322          */
1323
1324         object = c->ic_object;
1325         cursor = path->ip_frame->leaf;
1326
1327         while (1) {
1328                 result = iam_index_lock(path, lh);
1329                 do_corr(schedule());
1330                 if (result < 0)
1331                         break;
1332
1333                 result = iam_check_full_path(path, 0);
1334                 if (result == 0 && cursor == path->ip_frame->leaf) {
1335                         result = iam_index_advance(path);
1336
1337                         assert_corr(result == 0 ||
1338                                     cursor != path->ip_frame->leaf);
1339                         break;
1340                 }
1341                 do {
1342                         iam_unlock_array(object, lh);
1343
1344                         iam_path_release(path);
1345                         do_corr(schedule());
1346
1347                         result = __iam_path_lookup(path);
1348                         if (result < 0)
1349                                 break;
1350
1351                         while (path->ip_frame->leaf != cursor) {
1352                                 do_corr(schedule());
1353
1354                                 result = iam_index_lock(path, lh);
1355                                 do_corr(schedule());
1356                                 if (result < 0)
1357                                         break;
1358
1359                                 result = iam_check_full_path(path, 0);
1360                                 if (result != 0)
1361                                         break;
1362
1363                                 result = iam_index_advance(path);
1364                                 if (result == 0) {
1365                                         CERROR("cannot find cursor : %u\n",
1366                                                 cursor);
1367                                         result = -EIO;
1368                                 }
1369                                 if (result < 0)
1370                                         break;
1371                                 result = iam_check_full_path(path, 0);
1372                                 if (result != 0)
1373                                         break;
1374                                 iam_unlock_array(object, lh);
1375                         }
1376                 } while (result == -EAGAIN);
1377                 if (result < 0)
1378                         break;
1379         }
1380         iam_unlock_array(object, lh);
1381         return result;
1382 }
1383
1384 /*
1385  * Move iterator one record right.
1386  *
1387  * Return value: 0: success,
1388  *              +1: end of container reached
1389  *             -ve: error
1390  *
1391  * precondition:  (it_state(it) == IAM_IT_ATTACHED ||
1392  *                 it_state(it) == IAM_IT_SKEWED) && it->ii_flags&IAM_IT_MOVE
1393  * postcondition: ergo(result == 0, it_state(it) == IAM_IT_ATTACHED) &&
1394  *                ergo(result >  0, it_state(it) == IAM_IT_DETACHED)
1395  */
1396 int iam_it_next(struct iam_iterator *it)
1397 {
1398         int result;
1399         struct iam_path      *path;
1400         struct iam_leaf      *leaf;
1401         struct inode         *obj;
1402         do_corr(struct iam_ikey *ik_orig);
1403
1404         /* assert_corr(it->ii_flags&IAM_IT_MOVE); */
1405         assert_corr(it_state(it) == IAM_IT_ATTACHED ||
1406                     it_state(it) == IAM_IT_SKEWED);
1407
1408         path = &it->ii_path;
1409         leaf = &path->ip_leaf;
1410         obj  = iam_path_obj(path);
1411
1412         assert_corr(iam_leaf_is_locked(leaf));
1413
1414         result = 0;
1415         do_corr(ik_orig = it_at_rec(it) ?
1416                 iam_it_ikey_get(it, iam_path_ikey(path, 2)) : NULL);
1417         if (it_before(it)) {
1418                 assert_corr(!iam_leaf_at_end(leaf));
1419                 it->ii_state = IAM_IT_ATTACHED;
1420         } else {
1421                 if (!iam_leaf_at_end(leaf))
1422                         /* advance within leaf node */
1423                         iam_leaf_next(leaf);
1424                 /*
1425                  * multiple iterations may be necessary due to empty leaves.
1426                  */
1427                 while (result == 0 && iam_leaf_at_end(leaf)) {
1428                         do_corr(schedule());
1429                         /* advance index portion of the path */
1430                         result = iam_index_next(iam_it_container(it), path);
1431                         assert_corr(iam_leaf_is_locked(leaf));
1432                         if (result == 1) {
1433                                 struct dynlock_handle *lh;
1434                                 lh = iam_lock_htree(obj, path->ip_frame->leaf,
1435                                                    DLT_WRITE);
1436                                 if (lh != NULL) {
1437                                         iam_leaf_fini(leaf);
1438                                         leaf->il_lock = lh;
1439                                         result = iam_leaf_load(path);
1440                                         if (result == 0)
1441                                                 iam_leaf_start(leaf);
1442                                 } else
1443                                         result = -ENOMEM;
1444                         } else if (result == 0)
1445                                 /* end of container reached */
1446                                 result = +1;
1447                         if (result != 0)
1448                                 iam_it_put(it);
1449                 }
1450                 if (result == 0)
1451                         it->ii_state = IAM_IT_ATTACHED;
1452         }
1453         assert_corr(ergo(result == 0, it_state(it) == IAM_IT_ATTACHED));
1454         assert_corr(ergo(result >  0, it_state(it) == IAM_IT_DETACHED));
1455         assert_corr(ergo(result == 0 && ik_orig != NULL,
1456                          it_ikeycmp(it, ik_orig) >= 0));
1457         return result;
1458 }
1459 EXPORT_SYMBOL(iam_it_next);
1460
1461 /*
1462  * Return pointer to the record under iterator.
1463  *
1464  * precondition:  it_state(it) == IAM_IT_ATTACHED && it_at_rec(it)
1465  * postcondition: it_state(it) == IAM_IT_ATTACHED
1466  */
1467 struct iam_rec *iam_it_rec_get(const struct iam_iterator *it)
1468 {
1469         assert_corr(it_state(it) == IAM_IT_ATTACHED);
1470         assert_corr(it_at_rec(it));
1471         return iam_leaf_rec(&it->ii_path.ip_leaf);
1472 }
1473 EXPORT_SYMBOL(iam_it_rec_get);
1474
1475 static void iam_it_reccpy(struct iam_iterator *it, const struct iam_rec *r)
1476 {
1477         struct iam_leaf *folio;
1478
1479         folio = &it->ii_path.ip_leaf;
1480         iam_leaf_ops(folio)->rec_set(folio, r);
1481 }
1482
1483 /*
1484  * Replace contents of record under iterator.
1485  *
1486  * precondition:  it_state(it) == IAM_IT_ATTACHED &&
1487  *                it->ii_flags&IAM_IT_WRITE
1488  * postcondition: it_state(it) == IAM_IT_ATTACHED &&
1489  *                ergo(result == 0, !memcmp(iam_it_rec_get(it), r, ...))
1490  */
1491 int iam_it_rec_set(handle_t *h,
1492                    struct iam_iterator *it, const struct iam_rec *r)
1493 {
1494         int result;
1495         struct iam_path *path;
1496         struct buffer_head *bh;
1497
1498         assert_corr(it_state(it) == IAM_IT_ATTACHED &&
1499                     it->ii_flags&IAM_IT_WRITE);
1500         assert_corr(it_at_rec(it));
1501
1502         path = &it->ii_path;
1503         bh   = path->ip_leaf.il_bh;
1504         result = iam_txn_add(h, path, bh);
1505         if (result == 0) {
1506                 iam_it_reccpy(it, r);
1507                 result = iam_txn_dirty(h, path, bh);
1508         }
1509         return result;
1510 }
1511 EXPORT_SYMBOL(iam_it_rec_set);
1512
1513 /*
1514  * Return pointer to the index key under iterator.
1515  *
1516  * precondition:  it_state(it) == IAM_IT_ATTACHED ||
1517  *                it_state(it) == IAM_IT_SKEWED
1518  */
1519 static struct iam_ikey *iam_it_ikey_get(const struct iam_iterator *it,
1520                                         struct iam_ikey *ikey)
1521 {
1522         assert_corr(it_state(it) == IAM_IT_ATTACHED ||
1523                     it_state(it) == IAM_IT_SKEWED);
1524         assert_corr(it_at_rec(it));
1525         return iam_leaf_ikey(&it->ii_path.ip_leaf, ikey);
1526 }
1527
1528 /*
1529  * Return pointer to the key under iterator.
1530  *
1531  * precondition:  it_state(it) == IAM_IT_ATTACHED ||
1532  *                it_state(it) == IAM_IT_SKEWED
1533  */
1534 struct iam_key *iam_it_key_get(const struct iam_iterator *it)
1535 {
1536         assert_corr(it_state(it) == IAM_IT_ATTACHED ||
1537                     it_state(it) == IAM_IT_SKEWED);
1538         assert_corr(it_at_rec(it));
1539         return iam_leaf_key(&it->ii_path.ip_leaf);
1540 }
1541 EXPORT_SYMBOL(iam_it_key_get);
1542
1543 /*
1544  * Return size of key under iterator (in bytes)
1545  *
1546  * precondition:  it_state(it) == IAM_IT_ATTACHED ||
1547  *                it_state(it) == IAM_IT_SKEWED
1548  */
1549 int iam_it_key_size(const struct iam_iterator *it)
1550 {
1551         assert_corr(it_state(it) == IAM_IT_ATTACHED ||
1552                     it_state(it) == IAM_IT_SKEWED);
1553         assert_corr(it_at_rec(it));
1554         return iam_leaf_key_size(&it->ii_path.ip_leaf);
1555 }
1556 EXPORT_SYMBOL(iam_it_key_size);
1557
1558 /*
1559  * Insertion of new record. Interaction with jbd during non-trivial case (when
1560  * split happens) is as following:
1561  *
1562  *  - new leaf node is involved into transaction by ldiskfs_append();
1563  *
1564  *  - old leaf node is involved into transaction by iam_add_rec();
1565  *
1566  *  - leaf where insertion point ends in, is marked dirty by iam_add_rec();
1567  *
1568  *  - leaf without insertion point is marked dirty (as @new_leaf) by
1569  *  iam_new_leaf();
1570  *
1571  *  - split index nodes are involved into transaction and marked dirty by
1572  *  split_index_node().
1573  *
1574  *  - "safe" index node, which is no split, but where new pointer is inserted
1575  *  is involved into transaction and marked dirty by split_index_node().
1576  *
1577  *  - index node where pointer to new leaf is inserted is involved into
1578  *  transaction by split_index_node() and marked dirty by iam_add_rec().
1579  *
1580  *  - inode is marked dirty by iam_add_rec().
1581  *
1582  */
1583
1584 static int iam_new_leaf(handle_t *handle, struct iam_leaf *leaf)
1585 {
1586         int err;
1587         iam_ptr_t blknr;
1588         struct buffer_head   *new_leaf;
1589         struct buffer_head   *old_leaf;
1590         struct iam_container *c;
1591         struct inode         *obj;
1592         struct iam_path      *path;
1593
1594         assert_inv(iam_leaf_check(leaf));
1595
1596         c = iam_leaf_container(leaf);
1597         path = leaf->il_path;
1598
1599         obj = c->ic_object;
1600         new_leaf = ldiskfs_append(handle, obj, (__u32 *)&blknr, &err);
1601         do_corr(schedule());
1602         if (new_leaf != NULL) {
1603                 struct dynlock_handle *lh;
1604
1605                 lh = iam_lock_htree(obj, blknr, DLT_WRITE);
1606                 do_corr(schedule());
1607                 if (lh != NULL) {
1608                         iam_leaf_ops(leaf)->init_new(c, new_leaf);
1609                         do_corr(schedule());
1610                         old_leaf = leaf->il_bh;
1611                         iam_leaf_split(leaf, &new_leaf, blknr);
1612                         if (old_leaf != leaf->il_bh) {
1613                                 /*
1614                                  * Switched to the new leaf.
1615                                  */
1616                                 iam_leaf_unlock(leaf);
1617                                 leaf->il_lock = lh;
1618                                 path->ip_frame->leaf = blknr;
1619                         } else
1620                                 iam_unlock_htree(obj, lh);
1621                         do_corr(schedule());
1622                         err = iam_txn_dirty(handle, path, new_leaf);
1623                         brelse(new_leaf);
1624                         if (err == 0)
1625                                 err = ldiskfs_mark_inode_dirty(handle, obj);
1626                         do_corr(schedule());
1627                 } else
1628                         err = -ENOMEM;
1629         }
1630         assert_inv(iam_leaf_check(leaf));
1631         assert_inv(iam_leaf_check(&iam_leaf_path(leaf)->ip_leaf));
1632         assert_inv(iam_path_check(iam_leaf_path(leaf)));
1633         return err;
1634 }
1635
1636 static inline void dx_set_limit(struct iam_entry *entries, unsigned value)
1637 {
1638         ((struct dx_countlimit *) entries)->limit = cpu_to_le16(value);
1639 }
1640
1641 static int iam_shift_entries(struct iam_path *path,
1642                          struct iam_frame *frame, unsigned count,
1643                          struct iam_entry *entries, struct iam_entry *entries2,
1644                          u32 newblock)
1645 {
1646         unsigned count1;
1647         unsigned count2;
1648         int delta;
1649
1650         struct iam_frame *parent = frame - 1;
1651         struct iam_ikey *pivot = iam_path_ikey(path, 3);
1652
1653         delta = dx_index_is_compat(path) ? 0 : +1;
1654
1655         count1 = count/2 + delta;
1656         count2 = count - count1;
1657         dx_get_ikey(path, iam_entry_shift(path, entries, count1), pivot);
1658
1659         dxtrace(printk("Split index %d/%d\n", count1, count2));
1660
1661         memcpy((char *) iam_entry_shift(path, entries2, delta),
1662                (char *) iam_entry_shift(path, entries, count1),
1663                count2 * iam_entry_size(path));
1664
1665         dx_set_count(entries2, count2 + delta);
1666         dx_set_limit(entries2, dx_node_limit(path));
1667
1668         /*
1669          * NOTE: very subtle piece of code competing dx_probe() may find 2nd
1670          * level index in root index, then we insert new index here and set
1671          * new count in that 2nd level index. so, dx_probe() may see 2nd level
1672          * index w/o hash it looks for. the solution is to check root index
1673          * after we locked just founded 2nd level index -bzzz
1674          */
1675         iam_insert_key_lock(path, parent, pivot, newblock);
1676
1677         /*
1678          * now old and new 2nd level index blocks contain all pointers, so
1679          * dx_probe() may find it in the both.  it's OK -bzzz
1680          */
1681         iam_lock_bh(frame->bh);
1682         dx_set_count(entries, count1);
1683         iam_unlock_bh(frame->bh);
1684
1685         /*
1686          * now old 2nd level index block points to first half of leafs. it's
1687          * importand that dx_probe() must check root index block for changes
1688          * under dx_lock_bh(frame->bh) -bzzz
1689          */
1690
1691         return count1;
1692 }
1693
1694
1695 int split_index_node(handle_t *handle, struct iam_path *path,
1696                      struct dynlock_handle **lh)
1697 {
1698
1699         struct iam_entry *entries;   /* old block contents */
1700         struct iam_entry *entries2;  /* new block contents */
1701          struct iam_frame *frame, *safe;
1702         struct buffer_head *bh_new[DX_MAX_TREE_HEIGHT] = {0};
1703         u32 newblock[DX_MAX_TREE_HEIGHT] = {0};
1704         struct dynlock_handle *lock[DX_MAX_TREE_HEIGHT] = {NULL,};
1705         struct dynlock_handle *new_lock[DX_MAX_TREE_HEIGHT] = {NULL,};
1706         struct inode *dir = iam_path_obj(path);
1707         struct iam_descr *descr;
1708         int nr_splet;
1709         int i, err;
1710
1711         descr = iam_path_descr(path);
1712         /*
1713          * Algorithm below depends on this.
1714          */
1715         assert_corr(dx_root_limit(path) < dx_node_limit(path));
1716
1717         frame = path->ip_frame;
1718         entries = frame->entries;
1719
1720         /*
1721          * Tall-tree handling: we might have to split multiple index blocks
1722          * all the way up to tree root. Tricky point here is error handling:
1723          * to avoid complicated undo/rollback we
1724          *
1725          *   - first allocate all necessary blocks
1726          *
1727          *   - insert pointers into them atomically.
1728          */
1729
1730         /*
1731          * Locking: leaf is already locked. htree-locks are acquired on all
1732          * index nodes that require split bottom-to-top, on the "safe" node,
1733          * and on all new nodes
1734          */
1735
1736         dxtrace(printk("using %u of %u node entries\n",
1737                        dx_get_count(entries), dx_get_limit(entries)));
1738
1739         /* What levels need split? */
1740         for (nr_splet = 0; frame >= path->ip_frames &&
1741              dx_get_count(frame->entries) == dx_get_limit(frame->entries);
1742              --frame, ++nr_splet) {
1743                 do_corr(schedule());
1744                 if (nr_splet == DX_MAX_TREE_HEIGHT) {
1745                         /*
1746                         CWARN(dir->i_sb, __FUNCTION__,
1747                                      "Directory index full!\n");
1748                                      */
1749                         err = -ENOSPC;
1750                         goto cleanup;
1751                 }
1752         }
1753
1754         safe = frame;
1755
1756         /*
1757          * Lock all nodes, bottom to top.
1758          */
1759         for (frame = path->ip_frame, i = nr_splet; i >= 0; --i, --frame) {
1760                 do_corr(schedule());
1761                 lock[i] = iam_lock_htree(dir, frame->curidx, DLT_WRITE);
1762                 if (lock[i] == NULL) {
1763                         err = -ENOMEM;
1764                         goto cleanup;
1765                 }
1766         }
1767
1768         /*
1769          * Check for concurrent index modification.
1770          */
1771         err = iam_check_full_path(path, 1);
1772         if (err)
1773                 goto cleanup;
1774         /*
1775          * And check that the same number of nodes is to be split.
1776          */
1777         for (i = 0, frame = path->ip_frame; frame >= path->ip_frames &&
1778              dx_get_count(frame->entries) == dx_get_limit(frame->entries);
1779              --frame, ++i) {
1780                 ;
1781         }
1782         if (i != nr_splet) {
1783                 err = -EAGAIN;
1784                 goto cleanup;
1785         }
1786
1787         /* Go back down, allocating blocks, locking them, and adding into
1788          * transaction... */
1789         for (frame = safe + 1, i = 0; i < nr_splet; ++i, ++frame) {
1790                 bh_new[i] = ldiskfs_append (handle, dir, &newblock[i], &err);
1791                 do_corr(schedule());
1792                 if (!bh_new[i] ||
1793                     descr->id_ops->id_node_init(path->ip_container,
1794                                                 bh_new[i], 0) != 0)
1795                         goto cleanup;
1796                 new_lock[i] = iam_lock_htree(dir, newblock[i], DLT_WRITE);
1797                 if (new_lock[i] == NULL) {
1798                         err = -ENOMEM;
1799                         goto cleanup;
1800                 }
1801                 do_corr(schedule());
1802                 BUFFER_TRACE(frame->bh, "get_write_access");
1803                 err = ldiskfs_journal_get_write_access(handle, frame->bh);
1804                 if (err)
1805                         goto journal_error;
1806         }
1807         /* Add "safe" node to transaction too */
1808         if (safe + 1 != path->ip_frames) {
1809                 do_corr(schedule());
1810                 err = ldiskfs_journal_get_write_access(handle, safe->bh);
1811                 if (err)
1812                         goto journal_error;
1813         }
1814
1815         /* Go through nodes once more, inserting pointers */
1816         for (frame = safe + 1, i = 0; i < nr_splet; ++i, ++frame) {
1817                 unsigned count;
1818                 int idx;
1819                 struct buffer_head *bh2;
1820                 struct buffer_head *bh;
1821
1822                 entries = frame->entries;
1823                 count = dx_get_count(entries);
1824                 idx = iam_entry_diff(path, frame->at, entries);
1825
1826                 bh2 = bh_new[i];
1827                 entries2 = dx_get_entries(path, bh2->b_data, 0);
1828
1829                 bh = frame->bh;
1830                 if (frame == path->ip_frames) {
1831                         /* splitting root node. Tricky point:
1832                          *
1833                          * In the "normal" B-tree we'd split root *and* add
1834                          * new root to the tree with pointers to the old root
1835                          * and its sibling (thus introducing two new nodes).
1836                          *
1837                          * In htree it's enough to add one node, because
1838                          * capacity of the root node is smaller than that of
1839                          * non-root one.
1840                          */
1841                         struct iam_frame *frames;
1842                         struct iam_entry *next;
1843
1844                         assert_corr(i == 0);
1845
1846                         do_corr(schedule());
1847
1848                         frames = path->ip_frames;
1849                         memcpy((char *) entries2, (char *) entries,
1850                                count * iam_entry_size(path));
1851                         dx_set_limit(entries2, dx_node_limit(path));
1852
1853                         /* Set up root */
1854                           iam_lock_bh(frame->bh);
1855                         next = descr->id_ops->id_root_inc(path->ip_container,
1856                                                           path, frame);
1857                         dx_set_block(path, next, newblock[0]);
1858                           iam_unlock_bh(frame->bh);
1859
1860                         do_corr(schedule());
1861                         /* Shift frames in the path */
1862                         memmove(frames + 2, frames + 1,
1863                                 (sizeof path->ip_frames) - 2 * sizeof frames[0]);
1864                         /* Add new access path frame */
1865                         frames[1].at = iam_entry_shift(path, entries2, idx);
1866                         frames[1].entries = entries = entries2;
1867                         frames[1].bh = bh2;
1868                         assert_inv(dx_node_check(path, frame));
1869                         ++ path->ip_frame;
1870                         ++ frame;
1871                         assert_inv(dx_node_check(path, frame));
1872                         bh_new[0] = NULL; /* buffer head is "consumed" */
1873                         err = ldiskfs_journal_get_write_access(handle, bh2);
1874                         if (err)
1875                                 goto journal_error;
1876                         do_corr(schedule());
1877                 } else {
1878                         /* splitting non-root index node. */
1879                         struct iam_frame *parent = frame - 1;
1880
1881                         do_corr(schedule());
1882                         count = iam_shift_entries(path, frame, count,
1883                                               entries, entries2, newblock[i]);
1884                         /* Which index block gets the new entry? */
1885                         if (idx >= count) {
1886                                 int d = dx_index_is_compat(path) ? 0 : +1;
1887
1888                                 frame->at = iam_entry_shift(path, entries2,
1889                                                             idx - count + d);
1890                                 frame->entries = entries = entries2;
1891                                 frame->curidx = newblock[i];
1892                                 swap(frame->bh, bh2);
1893                                 assert_corr(lock[i + 1] != NULL);
1894                                 assert_corr(new_lock[i] != NULL);
1895                                 swap(lock[i + 1], new_lock[i]);
1896                                 bh_new[i] = bh2;
1897                                 parent->at = iam_entry_shift(path,
1898                                                              parent->at, +1);
1899                         }
1900                         assert_inv(dx_node_check(path, frame));
1901                         assert_inv(dx_node_check(path, parent));
1902                         dxtrace(dx_show_index ("node", frame->entries));
1903                         dxtrace(dx_show_index ("node",
1904                                ((struct dx_node *) bh2->b_data)->entries));
1905                         err = ldiskfs_journal_dirty_metadata(handle, bh2);
1906                         if (err)
1907                                 goto journal_error;
1908                         do_corr(schedule());
1909                         err = ldiskfs_journal_dirty_metadata(handle, parent->bh);
1910                         if (err)
1911                                 goto journal_error;
1912                 }
1913                 do_corr(schedule());
1914                 err = ldiskfs_journal_dirty_metadata(handle, bh);
1915                 if (err)
1916                         goto journal_error;
1917         }
1918                 /*
1919                  * This function was called to make insertion of new leaf
1920                  * possible. Check that it fulfilled its obligations.
1921                  */
1922                 assert_corr(dx_get_count(path->ip_frame->entries) <
1923                             dx_get_limit(path->ip_frame->entries));
1924         assert_corr(lock[nr_splet] != NULL);
1925         *lh = lock[nr_splet];
1926         lock[nr_splet] = NULL;
1927         if (nr_splet > 0) {
1928                 /*
1929                  * Log ->i_size modification.
1930                  */
1931                 err = ldiskfs_mark_inode_dirty(handle, dir);
1932                 if (err)
1933                         goto journal_error;
1934         }
1935         goto cleanup;
1936 journal_error:
1937         ldiskfs_std_error(dir->i_sb, err);
1938
1939 cleanup:
1940         iam_unlock_array(dir, lock);
1941         iam_unlock_array(dir, new_lock);
1942
1943         assert_corr(err || iam_frame_is_locked(path, path->ip_frame));
1944
1945         do_corr(schedule());
1946         for (i = 0; i < ARRAY_SIZE(bh_new); ++i) {
1947                 if (bh_new[i] != NULL)
1948                         brelse(bh_new[i]);
1949         }
1950         return err;
1951 }
1952
1953 static int iam_add_rec(handle_t *handle, struct iam_iterator *it,
1954                        struct iam_path *path,
1955                        const struct iam_key *k, const struct iam_rec *r)
1956 {
1957         int err;
1958         struct iam_leaf *leaf;
1959
1960         leaf = &path->ip_leaf;
1961         assert_inv(iam_leaf_check(leaf));
1962         assert_inv(iam_path_check(path));
1963         err = iam_txn_add(handle, path, leaf->il_bh);
1964         if (err == 0) {
1965                 do_corr(schedule());
1966                 if (!iam_leaf_can_add(leaf, k, r)) {
1967                         struct dynlock_handle *lh = NULL;
1968
1969                         do {
1970                                 assert_corr(lh == NULL);
1971                                 do_corr(schedule());
1972                                 err = split_index_node(handle, path, &lh);
1973                                 if (err == -EAGAIN) {
1974                                         assert_corr(lh == NULL);
1975
1976                                         iam_path_fini(path);
1977                                         it->ii_state = IAM_IT_DETACHED;
1978
1979                                         do_corr(schedule());
1980                                         err = iam_it_get_exact(it, k);
1981                                         if (err == -ENOENT)
1982                                                 err = +1; /* repeat split */
1983                                         else if (err == 0)
1984                                                 err = -EEXIST;
1985                                 }
1986                         } while (err > 0);
1987                         assert_inv(iam_path_check(path));
1988                         if (err == 0) {
1989                                 assert_corr(lh != NULL);
1990                                 do_corr(schedule());
1991                                 err = iam_new_leaf(handle, leaf);
1992                                 if (err == 0)
1993                                         err = iam_txn_dirty(handle, path,
1994                                                             path->ip_frame->bh);
1995                         }
1996                         iam_unlock_htree(iam_path_obj(path), lh);
1997                         do_corr(schedule());
1998                 }
1999                 if (err == 0) {
2000                         iam_leaf_rec_add(leaf, k, r);
2001                         err = iam_txn_dirty(handle, path, leaf->il_bh);
2002                 }
2003         }
2004         assert_inv(iam_leaf_check(leaf));
2005         assert_inv(iam_leaf_check(&path->ip_leaf));
2006         assert_inv(iam_path_check(path));
2007         return err;
2008 }
2009
2010 /*
2011  * Insert new record with key @k and contents from @r, shifting records to the
2012  * right. On success, iterator is positioned on the newly inserted record.
2013  *
2014  * precondition: it->ii_flags&IAM_IT_WRITE &&
2015  *               (it_state(it) == IAM_IT_ATTACHED ||
2016  *                it_state(it) == IAM_IT_SKEWED) &&
2017  *               ergo(it_state(it) == IAM_IT_ATTACHED,
2018  *                    it_keycmp(it, k) <= 0) &&
2019  *               ergo(it_before(it), it_keycmp(it, k) > 0));
2020  * postcondition: ergo(result == 0,
2021  *                     it_state(it) == IAM_IT_ATTACHED &&
2022  *                     it_keycmp(it, k) == 0 &&
2023  *                     !memcmp(iam_it_rec_get(it), r, ...))
2024  */
2025 int iam_it_rec_insert(handle_t *h, struct iam_iterator *it,
2026                       const struct iam_key *k, const struct iam_rec *r)
2027 {
2028         int result;
2029         struct iam_path *path;
2030
2031         path = &it->ii_path;
2032
2033         assert_corr(it->ii_flags&IAM_IT_WRITE);
2034         assert_corr(it_state(it) == IAM_IT_ATTACHED ||
2035                     it_state(it) == IAM_IT_SKEWED);
2036         assert_corr(ergo(it_state(it) == IAM_IT_ATTACHED,
2037                          it_keycmp(it, k) <= 0));
2038         assert_corr(ergo(it_before(it), it_keycmp(it, k) > 0));
2039         result = iam_add_rec(h, it, path, k, r);
2040         if (result == 0)
2041                 it->ii_state = IAM_IT_ATTACHED;
2042         assert_corr(ergo(result == 0,
2043                          it_state(it) == IAM_IT_ATTACHED &&
2044                          it_keycmp(it, k) == 0));
2045         return result;
2046 }
2047 EXPORT_SYMBOL(iam_it_rec_insert);
2048
2049 /*
2050  * Delete record under iterator.
2051  *
2052  * precondition:  it_state(it) == IAM_IT_ATTACHED &&
2053  *                it->ii_flags&IAM_IT_WRITE &&
2054  *                it_at_rec(it)
2055  * postcondition: it_state(it) == IAM_IT_ATTACHED ||
2056  *                it_state(it) == IAM_IT_DETACHED
2057  */
2058 int iam_it_rec_delete(handle_t *h, struct iam_iterator *it)
2059 {
2060         int result;
2061         struct iam_leaf *leaf;
2062         struct iam_path *path;
2063
2064         assert_corr(it_state(it) == IAM_IT_ATTACHED &&
2065                     it->ii_flags&IAM_IT_WRITE);
2066         assert_corr(it_at_rec(it));
2067
2068         path = &it->ii_path;
2069         leaf = &path->ip_leaf;
2070
2071         assert_inv(iam_leaf_check(leaf));
2072         assert_inv(iam_path_check(path));
2073
2074         result = iam_txn_add(h, path, leaf->il_bh);
2075         /*
2076          * no compaction for now.
2077          */
2078         if (result == 0) {
2079                 iam_rec_del(leaf, it->ii_flags&IAM_IT_MOVE);
2080                 result = iam_txn_dirty(h, path, leaf->il_bh);
2081                 if (result == 0 && iam_leaf_at_end(leaf) &&
2082                     it->ii_flags&IAM_IT_MOVE) {
2083                         result = iam_it_next(it);
2084                         if (result > 0)
2085                                 result = 0;
2086                 }
2087         }
2088         assert_inv(iam_leaf_check(leaf));
2089         assert_inv(iam_path_check(path));
2090         assert_corr(it_state(it) == IAM_IT_ATTACHED ||
2091                     it_state(it) == IAM_IT_DETACHED);
2092         return result;
2093 }
2094 EXPORT_SYMBOL(iam_it_rec_delete);
2095
2096 /*
2097  * Convert iterator to cookie.
2098  *
2099  * precondition:  it_state(it) == IAM_IT_ATTACHED &&
2100  *                iam_path_descr(it->ii_path)->id_key_size <= sizeof(iam_pos_t)
2101  * postcondition: it_state(it) == IAM_IT_ATTACHED
2102  */
2103 iam_pos_t iam_it_store(const struct iam_iterator *it)
2104 {
2105         iam_pos_t result;
2106
2107         assert_corr(it_state(it) == IAM_IT_ATTACHED);
2108         assert_corr(it_at_rec(it));
2109         assert_corr(iam_it_container(it)->ic_descr->id_ikey_size <=
2110                     sizeof result);
2111
2112         result = 0;
2113         return *(iam_pos_t *)iam_it_ikey_get(it, (void *)&result);
2114 }
2115 EXPORT_SYMBOL(iam_it_store);
2116
2117 /*
2118  * Restore iterator from cookie.
2119  *
2120  * precondition:  it_state(it) == IAM_IT_DETACHED && it->ii_flags&IAM_IT_MOVE &&
2121  *                iam_path_descr(it->ii_path)->id_key_size <= sizeof(iam_pos_t)
2122  * postcondition: ergo(result == 0, it_state(it) == IAM_IT_ATTACHED &&
2123  *                                  iam_it_store(it) == pos)
2124  */
2125 int iam_it_load(struct iam_iterator *it, iam_pos_t pos)
2126 {
2127         assert_corr(it_state(it) == IAM_IT_DETACHED &&
2128                     it->ii_flags&IAM_IT_MOVE);
2129         assert_corr(iam_it_container(it)->ic_descr->id_ikey_size <= sizeof pos);
2130         return iam_it_iget(it, (struct iam_ikey *)&pos);
2131 }
2132 EXPORT_SYMBOL(iam_it_load);
2133
2134 /***********************************************************************/
2135 /* invariants                                                          */
2136 /***********************************************************************/
2137
2138 static inline int ptr_inside(void *base, size_t size, void *ptr)
2139 {
2140         return (base <= ptr) && (ptr < base + size);
2141 }
2142
2143 int iam_frame_invariant(struct iam_frame *f)
2144 {
2145         return
2146                 (f->bh != NULL &&
2147                 f->bh->b_data != NULL &&
2148                 ptr_inside(f->bh->b_data, f->bh->b_size, f->entries) &&
2149                 ptr_inside(f->bh->b_data, f->bh->b_size, f->at) &&
2150                 f->entries <= f->at);
2151 }
2152 int iam_leaf_invariant(struct iam_leaf *l)
2153 {
2154         return
2155                 l->il_bh != NULL &&
2156                 l->il_bh->b_data != NULL &&
2157                 ptr_inside(l->il_bh->b_data, l->il_bh->b_size, l->il_entries) &&
2158                 ptr_inside(l->il_bh->b_data, l->il_bh->b_size, l->il_at) &&
2159                 l->il_entries <= l->il_at;
2160 }
2161
2162 int iam_path_invariant(struct iam_path *p)
2163 {
2164         int i;
2165
2166         if (p->ip_container == NULL ||
2167             p->ip_indirect < 0 || p->ip_indirect > DX_MAX_TREE_HEIGHT - 1 ||
2168             p->ip_frame != p->ip_frames + p->ip_indirect ||
2169             !iam_leaf_invariant(&p->ip_leaf))
2170                 return 0;
2171         for (i = 0; i < ARRAY_SIZE(p->ip_frames); ++i) {
2172                 if (i <= p->ip_indirect) {
2173                         if (!iam_frame_invariant(&p->ip_frames[i]))
2174                                 return 0;
2175                 }
2176         }
2177         return 1;
2178 }
2179
2180 int iam_it_invariant(struct iam_iterator *it)
2181 {
2182         return
2183                 (it->ii_state == IAM_IT_DETACHED ||
2184                  it->ii_state == IAM_IT_ATTACHED ||
2185                  it->ii_state == IAM_IT_SKEWED) &&
2186                 !(it->ii_flags & ~(IAM_IT_MOVE | IAM_IT_WRITE)) &&
2187                 ergo(it->ii_state == IAM_IT_ATTACHED ||
2188                      it->ii_state == IAM_IT_SKEWED,
2189                      iam_path_invariant(&it->ii_path) &&
2190                      equi(it_at_rec(it), it->ii_state == IAM_IT_SKEWED));
2191 }
2192
2193 /*
2194  * Search container @c for record with key @k. If record is found, its data
2195  * are moved into @r.
2196  *
2197  * Return values: 0: found, -ENOENT: not-found, -ve: error
2198  */
2199 int iam_lookup(struct iam_container *c, const struct iam_key *k,
2200                struct iam_rec *r, struct iam_path_descr *pd)
2201 {
2202         struct iam_iterator it;
2203         int result;
2204
2205         iam_it_init(&it, c, 0, pd);
2206
2207         result = iam_it_get_exact(&it, k);
2208         if (result == 0)
2209                 /*
2210                  * record with required key found, copy it into user buffer
2211                  */
2212                 iam_reccpy(&it.ii_path.ip_leaf, r);
2213         iam_it_put(&it);
2214         iam_it_fini(&it);
2215         return result;
2216 }
2217 EXPORT_SYMBOL(iam_lookup);
2218
2219 /*
2220  * Insert new record @r with key @k into container @c (within context of
2221  * transaction @h).
2222  *
2223  * Return values: 0: success, -ve: error, including -EEXIST when record with
2224  * given key is already present.
2225  *
2226  * postcondition: ergo(result == 0 || result == -EEXIST,
2227  *                                  iam_lookup(c, k, r2) > 0;
2228  */
2229 int iam_insert(handle_t *h, struct iam_container *c, const struct iam_key *k,
2230                const struct iam_rec *r, struct iam_path_descr *pd)
2231 {
2232         struct iam_iterator it;
2233         int result;
2234
2235         iam_it_init(&it, c, IAM_IT_WRITE, pd);
2236
2237         result = iam_it_get_exact(&it, k);
2238         if (result == -ENOENT)
2239                 result = iam_it_rec_insert(h, &it, k, r);
2240         else if (result == 0)
2241                 result = -EEXIST;
2242         iam_it_put(&it);
2243         iam_it_fini(&it);
2244         return result;
2245 }
2246 EXPORT_SYMBOL(iam_insert);
2247
2248 /*
2249  * Update record with the key @k in container @c (within context of
2250  * transaction @h), new record is given by @r.
2251  *
2252  * Return values: 0: success, -ve: error, including -ENOENT if no record with
2253  * the given key found.
2254  */
2255 int iam_update(handle_t *h, struct iam_container *c, const struct iam_key *k,
2256                const struct iam_rec *r, struct iam_path_descr *pd)
2257 {
2258         struct iam_iterator it;
2259         int result;
2260
2261         iam_it_init(&it, c, IAM_IT_WRITE, pd);
2262
2263         result = iam_it_get_exact(&it, k);
2264         if (result == 0)
2265                 iam_it_rec_set(h, &it, r);
2266         iam_it_put(&it);
2267         iam_it_fini(&it);
2268         return result;
2269 }
2270 EXPORT_SYMBOL(iam_update);
2271
2272 /*
2273  * Delete existing record with key @k.
2274  *
2275  * Return values: 0: success, -ENOENT: not-found, -ve: other error.
2276  *
2277  * postcondition: ergo(result == 0 || result == -ENOENT,
2278  *                                 !iam_lookup(c, k, *));
2279  */
2280 int iam_delete(handle_t *h, struct iam_container *c, const struct iam_key *k,
2281                struct iam_path_descr *pd)
2282 {
2283         struct iam_iterator it;
2284         int result;
2285
2286         iam_it_init(&it, c, IAM_IT_WRITE, pd);
2287
2288         result = iam_it_get_exact(&it, k);
2289         if (result == 0)
2290                 iam_it_rec_delete(h, &it);
2291         iam_it_put(&it);
2292         iam_it_fini(&it);
2293         return result;
2294 }
2295 EXPORT_SYMBOL(iam_delete);
2296
2297 int iam_root_limit(int rootgap, int blocksize, int size)
2298 {
2299         int limit;
2300         int nlimit;
2301
2302         limit = (blocksize - rootgap) / size;
2303         nlimit = blocksize / size;
2304         if (limit == nlimit)
2305                 limit--;
2306         return limit;
2307 }