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