2a13d418ed4bb0a389da8a56e48ebf075ef01a14
[cascardo/linux.git] / fs / xfs / libxfs / xfs_btree.c
1 /*
2  * Copyright (c) 2000-2002,2005 Silicon Graphics, Inc.
3  * All Rights Reserved.
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License as
7  * published by the Free Software Foundation.
8  *
9  * This program is distributed in the hope that it would be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write the Free Software Foundation,
16  * Inc.,  51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
17  */
18 #include "xfs.h"
19 #include "xfs_fs.h"
20 #include "xfs_shared.h"
21 #include "xfs_format.h"
22 #include "xfs_log_format.h"
23 #include "xfs_trans_resv.h"
24 #include "xfs_bit.h"
25 #include "xfs_mount.h"
26 #include "xfs_defer.h"
27 #include "xfs_inode.h"
28 #include "xfs_trans.h"
29 #include "xfs_inode_item.h"
30 #include "xfs_buf_item.h"
31 #include "xfs_btree.h"
32 #include "xfs_error.h"
33 #include "xfs_trace.h"
34 #include "xfs_cksum.h"
35 #include "xfs_alloc.h"
36 #include "xfs_log.h"
37
38 /*
39  * Cursor allocation zone.
40  */
41 kmem_zone_t     *xfs_btree_cur_zone;
42
43 /*
44  * Btree magic numbers.
45  */
46 static const __uint32_t xfs_magics[2][XFS_BTNUM_MAX] = {
47         { XFS_ABTB_MAGIC, XFS_ABTC_MAGIC, 0, XFS_BMAP_MAGIC, XFS_IBT_MAGIC,
48           XFS_FIBT_MAGIC },
49         { XFS_ABTB_CRC_MAGIC, XFS_ABTC_CRC_MAGIC, XFS_RMAP_CRC_MAGIC,
50           XFS_BMAP_CRC_MAGIC, XFS_IBT_CRC_MAGIC, XFS_FIBT_CRC_MAGIC }
51 };
52 #define xfs_btree_magic(cur) \
53         xfs_magics[!!((cur)->bc_flags & XFS_BTREE_CRC_BLOCKS)][cur->bc_btnum]
54
55 STATIC int                              /* error (0 or EFSCORRUPTED) */
56 xfs_btree_check_lblock(
57         struct xfs_btree_cur    *cur,   /* btree cursor */
58         struct xfs_btree_block  *block, /* btree long form block pointer */
59         int                     level,  /* level of the btree block */
60         struct xfs_buf          *bp)    /* buffer for block, if any */
61 {
62         int                     lblock_ok = 1; /* block passes checks */
63         struct xfs_mount        *mp;    /* file system mount point */
64
65         mp = cur->bc_mp;
66
67         if (xfs_sb_version_hascrc(&mp->m_sb)) {
68                 lblock_ok = lblock_ok &&
69                         uuid_equal(&block->bb_u.l.bb_uuid,
70                                    &mp->m_sb.sb_meta_uuid) &&
71                         block->bb_u.l.bb_blkno == cpu_to_be64(
72                                 bp ? bp->b_bn : XFS_BUF_DADDR_NULL);
73         }
74
75         lblock_ok = lblock_ok &&
76                 be32_to_cpu(block->bb_magic) == xfs_btree_magic(cur) &&
77                 be16_to_cpu(block->bb_level) == level &&
78                 be16_to_cpu(block->bb_numrecs) <=
79                         cur->bc_ops->get_maxrecs(cur, level) &&
80                 block->bb_u.l.bb_leftsib &&
81                 (block->bb_u.l.bb_leftsib == cpu_to_be64(NULLFSBLOCK) ||
82                  XFS_FSB_SANITY_CHECK(mp,
83                         be64_to_cpu(block->bb_u.l.bb_leftsib))) &&
84                 block->bb_u.l.bb_rightsib &&
85                 (block->bb_u.l.bb_rightsib == cpu_to_be64(NULLFSBLOCK) ||
86                  XFS_FSB_SANITY_CHECK(mp,
87                         be64_to_cpu(block->bb_u.l.bb_rightsib)));
88
89         if (unlikely(XFS_TEST_ERROR(!lblock_ok, mp,
90                         XFS_ERRTAG_BTREE_CHECK_LBLOCK,
91                         XFS_RANDOM_BTREE_CHECK_LBLOCK))) {
92                 if (bp)
93                         trace_xfs_btree_corrupt(bp, _RET_IP_);
94                 XFS_ERROR_REPORT(__func__, XFS_ERRLEVEL_LOW, mp);
95                 return -EFSCORRUPTED;
96         }
97         return 0;
98 }
99
100 STATIC int                              /* error (0 or EFSCORRUPTED) */
101 xfs_btree_check_sblock(
102         struct xfs_btree_cur    *cur,   /* btree cursor */
103         struct xfs_btree_block  *block, /* btree short form block pointer */
104         int                     level,  /* level of the btree block */
105         struct xfs_buf          *bp)    /* buffer containing block */
106 {
107         struct xfs_mount        *mp;    /* file system mount point */
108         struct xfs_buf          *agbp;  /* buffer for ag. freespace struct */
109         struct xfs_agf          *agf;   /* ag. freespace structure */
110         xfs_agblock_t           agflen; /* native ag. freespace length */
111         int                     sblock_ok = 1; /* block passes checks */
112
113         mp = cur->bc_mp;
114         agbp = cur->bc_private.a.agbp;
115         agf = XFS_BUF_TO_AGF(agbp);
116         agflen = be32_to_cpu(agf->agf_length);
117
118         if (xfs_sb_version_hascrc(&mp->m_sb)) {
119                 sblock_ok = sblock_ok &&
120                         uuid_equal(&block->bb_u.s.bb_uuid,
121                                    &mp->m_sb.sb_meta_uuid) &&
122                         block->bb_u.s.bb_blkno == cpu_to_be64(
123                                 bp ? bp->b_bn : XFS_BUF_DADDR_NULL);
124         }
125
126         sblock_ok = sblock_ok &&
127                 be32_to_cpu(block->bb_magic) == xfs_btree_magic(cur) &&
128                 be16_to_cpu(block->bb_level) == level &&
129                 be16_to_cpu(block->bb_numrecs) <=
130                         cur->bc_ops->get_maxrecs(cur, level) &&
131                 (block->bb_u.s.bb_leftsib == cpu_to_be32(NULLAGBLOCK) ||
132                  be32_to_cpu(block->bb_u.s.bb_leftsib) < agflen) &&
133                 block->bb_u.s.bb_leftsib &&
134                 (block->bb_u.s.bb_rightsib == cpu_to_be32(NULLAGBLOCK) ||
135                  be32_to_cpu(block->bb_u.s.bb_rightsib) < agflen) &&
136                 block->bb_u.s.bb_rightsib;
137
138         if (unlikely(XFS_TEST_ERROR(!sblock_ok, mp,
139                         XFS_ERRTAG_BTREE_CHECK_SBLOCK,
140                         XFS_RANDOM_BTREE_CHECK_SBLOCK))) {
141                 if (bp)
142                         trace_xfs_btree_corrupt(bp, _RET_IP_);
143                 XFS_ERROR_REPORT(__func__, XFS_ERRLEVEL_LOW, mp);
144                 return -EFSCORRUPTED;
145         }
146         return 0;
147 }
148
149 /*
150  * Debug routine: check that block header is ok.
151  */
152 int
153 xfs_btree_check_block(
154         struct xfs_btree_cur    *cur,   /* btree cursor */
155         struct xfs_btree_block  *block, /* generic btree block pointer */
156         int                     level,  /* level of the btree block */
157         struct xfs_buf          *bp)    /* buffer containing block, if any */
158 {
159         if (cur->bc_flags & XFS_BTREE_LONG_PTRS)
160                 return xfs_btree_check_lblock(cur, block, level, bp);
161         else
162                 return xfs_btree_check_sblock(cur, block, level, bp);
163 }
164
165 /*
166  * Check that (long) pointer is ok.
167  */
168 int                                     /* error (0 or EFSCORRUPTED) */
169 xfs_btree_check_lptr(
170         struct xfs_btree_cur    *cur,   /* btree cursor */
171         xfs_fsblock_t           bno,    /* btree block disk address */
172         int                     level)  /* btree block level */
173 {
174         XFS_WANT_CORRUPTED_RETURN(cur->bc_mp,
175                 level > 0 &&
176                 bno != NULLFSBLOCK &&
177                 XFS_FSB_SANITY_CHECK(cur->bc_mp, bno));
178         return 0;
179 }
180
181 #ifdef DEBUG
182 /*
183  * Check that (short) pointer is ok.
184  */
185 STATIC int                              /* error (0 or EFSCORRUPTED) */
186 xfs_btree_check_sptr(
187         struct xfs_btree_cur    *cur,   /* btree cursor */
188         xfs_agblock_t           bno,    /* btree block disk address */
189         int                     level)  /* btree block level */
190 {
191         xfs_agblock_t           agblocks = cur->bc_mp->m_sb.sb_agblocks;
192
193         XFS_WANT_CORRUPTED_RETURN(cur->bc_mp,
194                 level > 0 &&
195                 bno != NULLAGBLOCK &&
196                 bno != 0 &&
197                 bno < agblocks);
198         return 0;
199 }
200
201 /*
202  * Check that block ptr is ok.
203  */
204 STATIC int                              /* error (0 or EFSCORRUPTED) */
205 xfs_btree_check_ptr(
206         struct xfs_btree_cur    *cur,   /* btree cursor */
207         union xfs_btree_ptr     *ptr,   /* btree block disk address */
208         int                     index,  /* offset from ptr to check */
209         int                     level)  /* btree block level */
210 {
211         if (cur->bc_flags & XFS_BTREE_LONG_PTRS) {
212                 return xfs_btree_check_lptr(cur,
213                                 be64_to_cpu((&ptr->l)[index]), level);
214         } else {
215                 return xfs_btree_check_sptr(cur,
216                                 be32_to_cpu((&ptr->s)[index]), level);
217         }
218 }
219 #endif
220
221 /*
222  * Calculate CRC on the whole btree block and stuff it into the
223  * long-form btree header.
224  *
225  * Prior to calculting the CRC, pull the LSN out of the buffer log item and put
226  * it into the buffer so recovery knows what the last modification was that made
227  * it to disk.
228  */
229 void
230 xfs_btree_lblock_calc_crc(
231         struct xfs_buf          *bp)
232 {
233         struct xfs_btree_block  *block = XFS_BUF_TO_BLOCK(bp);
234         struct xfs_buf_log_item *bip = bp->b_fspriv;
235
236         if (!xfs_sb_version_hascrc(&bp->b_target->bt_mount->m_sb))
237                 return;
238         if (bip)
239                 block->bb_u.l.bb_lsn = cpu_to_be64(bip->bli_item.li_lsn);
240         xfs_buf_update_cksum(bp, XFS_BTREE_LBLOCK_CRC_OFF);
241 }
242
243 bool
244 xfs_btree_lblock_verify_crc(
245         struct xfs_buf          *bp)
246 {
247         struct xfs_btree_block  *block = XFS_BUF_TO_BLOCK(bp);
248         struct xfs_mount        *mp = bp->b_target->bt_mount;
249
250         if (xfs_sb_version_hascrc(&mp->m_sb)) {
251                 if (!xfs_log_check_lsn(mp, be64_to_cpu(block->bb_u.l.bb_lsn)))
252                         return false;
253                 return xfs_buf_verify_cksum(bp, XFS_BTREE_LBLOCK_CRC_OFF);
254         }
255
256         return true;
257 }
258
259 /*
260  * Calculate CRC on the whole btree block and stuff it into the
261  * short-form btree header.
262  *
263  * Prior to calculting the CRC, pull the LSN out of the buffer log item and put
264  * it into the buffer so recovery knows what the last modification was that made
265  * it to disk.
266  */
267 void
268 xfs_btree_sblock_calc_crc(
269         struct xfs_buf          *bp)
270 {
271         struct xfs_btree_block  *block = XFS_BUF_TO_BLOCK(bp);
272         struct xfs_buf_log_item *bip = bp->b_fspriv;
273
274         if (!xfs_sb_version_hascrc(&bp->b_target->bt_mount->m_sb))
275                 return;
276         if (bip)
277                 block->bb_u.s.bb_lsn = cpu_to_be64(bip->bli_item.li_lsn);
278         xfs_buf_update_cksum(bp, XFS_BTREE_SBLOCK_CRC_OFF);
279 }
280
281 bool
282 xfs_btree_sblock_verify_crc(
283         struct xfs_buf          *bp)
284 {
285         struct xfs_btree_block  *block = XFS_BUF_TO_BLOCK(bp);
286         struct xfs_mount        *mp = bp->b_target->bt_mount;
287
288         if (xfs_sb_version_hascrc(&mp->m_sb)) {
289                 if (!xfs_log_check_lsn(mp, be64_to_cpu(block->bb_u.s.bb_lsn)))
290                         return false;
291                 return xfs_buf_verify_cksum(bp, XFS_BTREE_SBLOCK_CRC_OFF);
292         }
293
294         return true;
295 }
296
297 static int
298 xfs_btree_free_block(
299         struct xfs_btree_cur    *cur,
300         struct xfs_buf          *bp)
301 {
302         int                     error;
303
304         error = cur->bc_ops->free_block(cur, bp);
305         if (!error) {
306                 xfs_trans_binval(cur->bc_tp, bp);
307                 XFS_BTREE_STATS_INC(cur, free);
308         }
309         return error;
310 }
311
312 /*
313  * Delete the btree cursor.
314  */
315 void
316 xfs_btree_del_cursor(
317         xfs_btree_cur_t *cur,           /* btree cursor */
318         int             error)          /* del because of error */
319 {
320         int             i;              /* btree level */
321
322         /*
323          * Clear the buffer pointers, and release the buffers.
324          * If we're doing this in the face of an error, we
325          * need to make sure to inspect all of the entries
326          * in the bc_bufs array for buffers to be unlocked.
327          * This is because some of the btree code works from
328          * level n down to 0, and if we get an error along
329          * the way we won't have initialized all the entries
330          * down to 0.
331          */
332         for (i = 0; i < cur->bc_nlevels; i++) {
333                 if (cur->bc_bufs[i])
334                         xfs_trans_brelse(cur->bc_tp, cur->bc_bufs[i]);
335                 else if (!error)
336                         break;
337         }
338         /*
339          * Can't free a bmap cursor without having dealt with the
340          * allocated indirect blocks' accounting.
341          */
342         ASSERT(cur->bc_btnum != XFS_BTNUM_BMAP ||
343                cur->bc_private.b.allocated == 0);
344         /*
345          * Free the cursor.
346          */
347         kmem_zone_free(xfs_btree_cur_zone, cur);
348 }
349
350 /*
351  * Duplicate the btree cursor.
352  * Allocate a new one, copy the record, re-get the buffers.
353  */
354 int                                     /* error */
355 xfs_btree_dup_cursor(
356         xfs_btree_cur_t *cur,           /* input cursor */
357         xfs_btree_cur_t **ncur)         /* output cursor */
358 {
359         xfs_buf_t       *bp;            /* btree block's buffer pointer */
360         int             error;          /* error return value */
361         int             i;              /* level number of btree block */
362         xfs_mount_t     *mp;            /* mount structure for filesystem */
363         xfs_btree_cur_t *new;           /* new cursor value */
364         xfs_trans_t     *tp;            /* transaction pointer, can be NULL */
365
366         tp = cur->bc_tp;
367         mp = cur->bc_mp;
368
369         /*
370          * Allocate a new cursor like the old one.
371          */
372         new = cur->bc_ops->dup_cursor(cur);
373
374         /*
375          * Copy the record currently in the cursor.
376          */
377         new->bc_rec = cur->bc_rec;
378
379         /*
380          * For each level current, re-get the buffer and copy the ptr value.
381          */
382         for (i = 0; i < new->bc_nlevels; i++) {
383                 new->bc_ptrs[i] = cur->bc_ptrs[i];
384                 new->bc_ra[i] = cur->bc_ra[i];
385                 bp = cur->bc_bufs[i];
386                 if (bp) {
387                         error = xfs_trans_read_buf(mp, tp, mp->m_ddev_targp,
388                                                    XFS_BUF_ADDR(bp), mp->m_bsize,
389                                                    0, &bp,
390                                                    cur->bc_ops->buf_ops);
391                         if (error) {
392                                 xfs_btree_del_cursor(new, error);
393                                 *ncur = NULL;
394                                 return error;
395                         }
396                 }
397                 new->bc_bufs[i] = bp;
398         }
399         *ncur = new;
400         return 0;
401 }
402
403 /*
404  * XFS btree block layout and addressing:
405  *
406  * There are two types of blocks in the btree: leaf and non-leaf blocks.
407  *
408  * The leaf record start with a header then followed by records containing
409  * the values.  A non-leaf block also starts with the same header, and
410  * then first contains lookup keys followed by an equal number of pointers
411  * to the btree blocks at the previous level.
412  *
413  *              +--------+-------+-------+-------+-------+-------+-------+
414  * Leaf:        | header | rec 1 | rec 2 | rec 3 | rec 4 | rec 5 | rec N |
415  *              +--------+-------+-------+-------+-------+-------+-------+
416  *
417  *              +--------+-------+-------+-------+-------+-------+-------+
418  * Non-Leaf:    | header | key 1 | key 2 | key N | ptr 1 | ptr 2 | ptr N |
419  *              +--------+-------+-------+-------+-------+-------+-------+
420  *
421  * The header is called struct xfs_btree_block for reasons better left unknown
422  * and comes in different versions for short (32bit) and long (64bit) block
423  * pointers.  The record and key structures are defined by the btree instances
424  * and opaque to the btree core.  The block pointers are simple disk endian
425  * integers, available in a short (32bit) and long (64bit) variant.
426  *
427  * The helpers below calculate the offset of a given record, key or pointer
428  * into a btree block (xfs_btree_*_offset) or return a pointer to the given
429  * record, key or pointer (xfs_btree_*_addr).  Note that all addressing
430  * inside the btree block is done using indices starting at one, not zero!
431  *
432  * If XFS_BTREE_OVERLAPPING is set, then this btree supports keys containing
433  * overlapping intervals.  In such a tree, records are still sorted lowest to
434  * highest and indexed by the smallest key value that refers to the record.
435  * However, nodes are different: each pointer has two associated keys -- one
436  * indexing the lowest key available in the block(s) below (the same behavior
437  * as the key in a regular btree) and another indexing the highest key
438  * available in the block(s) below.  Because records are /not/ sorted by the
439  * highest key, all leaf block updates require us to compute the highest key
440  * that matches any record in the leaf and to recursively update the high keys
441  * in the nodes going further up in the tree, if necessary.  Nodes look like
442  * this:
443  *
444  *              +--------+-----+-----+-----+-----+-----+-------+-------+-----+
445  * Non-Leaf:    | header | lo1 | hi1 | lo2 | hi2 | ... | ptr 1 | ptr 2 | ... |
446  *              +--------+-----+-----+-----+-----+-----+-------+-------+-----+
447  *
448  * To perform an interval query on an overlapped tree, perform the usual
449  * depth-first search and use the low and high keys to decide if we can skip
450  * that particular node.  If a leaf node is reached, return the records that
451  * intersect the interval.  Note that an interval query may return numerous
452  * entries.  For a non-overlapped tree, simply search for the record associated
453  * with the lowest key and iterate forward until a non-matching record is
454  * found.  Section 14.3 ("Interval Trees") of _Introduction to Algorithms_ by
455  * Cormen, Leiserson, Rivest, and Stein (2nd or 3rd ed. only) discuss this in
456  * more detail.
457  *
458  * Why do we care about overlapping intervals?  Let's say you have a bunch of
459  * reverse mapping records on a reflink filesystem:
460  *
461  * 1: +- file A startblock B offset C length D -----------+
462  * 2:      +- file E startblock F offset G length H --------------+
463  * 3:      +- file I startblock F offset J length K --+
464  * 4:                                                        +- file L... --+
465  *
466  * Now say we want to map block (B+D) into file A at offset (C+D).  Ideally,
467  * we'd simply increment the length of record 1.  But how do we find the record
468  * that ends at (B+D-1) (i.e. record 1)?  A LE lookup of (B+D-1) would return
469  * record 3 because the keys are ordered first by startblock.  An interval
470  * query would return records 1 and 2 because they both overlap (B+D-1), and
471  * from that we can pick out record 1 as the appropriate left neighbor.
472  *
473  * In the non-overlapped case you can do a LE lookup and decrement the cursor
474  * because a record's interval must end before the next record.
475  */
476
477 /*
478  * Return size of the btree block header for this btree instance.
479  */
480 static inline size_t xfs_btree_block_len(struct xfs_btree_cur *cur)
481 {
482         if (cur->bc_flags & XFS_BTREE_LONG_PTRS) {
483                 if (cur->bc_flags & XFS_BTREE_CRC_BLOCKS)
484                         return XFS_BTREE_LBLOCK_CRC_LEN;
485                 return XFS_BTREE_LBLOCK_LEN;
486         }
487         if (cur->bc_flags & XFS_BTREE_CRC_BLOCKS)
488                 return XFS_BTREE_SBLOCK_CRC_LEN;
489         return XFS_BTREE_SBLOCK_LEN;
490 }
491
492 /*
493  * Return size of btree block pointers for this btree instance.
494  */
495 static inline size_t xfs_btree_ptr_len(struct xfs_btree_cur *cur)
496 {
497         return (cur->bc_flags & XFS_BTREE_LONG_PTRS) ?
498                 sizeof(__be64) : sizeof(__be32);
499 }
500
501 /*
502  * Calculate offset of the n-th record in a btree block.
503  */
504 STATIC size_t
505 xfs_btree_rec_offset(
506         struct xfs_btree_cur    *cur,
507         int                     n)
508 {
509         return xfs_btree_block_len(cur) +
510                 (n - 1) * cur->bc_ops->rec_len;
511 }
512
513 /*
514  * Calculate offset of the n-th key in a btree block.
515  */
516 STATIC size_t
517 xfs_btree_key_offset(
518         struct xfs_btree_cur    *cur,
519         int                     n)
520 {
521         return xfs_btree_block_len(cur) +
522                 (n - 1) * cur->bc_ops->key_len;
523 }
524
525 /*
526  * Calculate offset of the n-th high key in a btree block.
527  */
528 STATIC size_t
529 xfs_btree_high_key_offset(
530         struct xfs_btree_cur    *cur,
531         int                     n)
532 {
533         return xfs_btree_block_len(cur) +
534                 (n - 1) * cur->bc_ops->key_len + (cur->bc_ops->key_len / 2);
535 }
536
537 /*
538  * Calculate offset of the n-th block pointer in a btree block.
539  */
540 STATIC size_t
541 xfs_btree_ptr_offset(
542         struct xfs_btree_cur    *cur,
543         int                     n,
544         int                     level)
545 {
546         return xfs_btree_block_len(cur) +
547                 cur->bc_ops->get_maxrecs(cur, level) * cur->bc_ops->key_len +
548                 (n - 1) * xfs_btree_ptr_len(cur);
549 }
550
551 /*
552  * Return a pointer to the n-th record in the btree block.
553  */
554 STATIC union xfs_btree_rec *
555 xfs_btree_rec_addr(
556         struct xfs_btree_cur    *cur,
557         int                     n,
558         struct xfs_btree_block  *block)
559 {
560         return (union xfs_btree_rec *)
561                 ((char *)block + xfs_btree_rec_offset(cur, n));
562 }
563
564 /*
565  * Return a pointer to the n-th key in the btree block.
566  */
567 STATIC union xfs_btree_key *
568 xfs_btree_key_addr(
569         struct xfs_btree_cur    *cur,
570         int                     n,
571         struct xfs_btree_block  *block)
572 {
573         return (union xfs_btree_key *)
574                 ((char *)block + xfs_btree_key_offset(cur, n));
575 }
576
577 /*
578  * Return a pointer to the n-th high key in the btree block.
579  */
580 STATIC union xfs_btree_key *
581 xfs_btree_high_key_addr(
582         struct xfs_btree_cur    *cur,
583         int                     n,
584         struct xfs_btree_block  *block)
585 {
586         return (union xfs_btree_key *)
587                 ((char *)block + xfs_btree_high_key_offset(cur, n));
588 }
589
590 /*
591  * Return a pointer to the n-th block pointer in the btree block.
592  */
593 STATIC union xfs_btree_ptr *
594 xfs_btree_ptr_addr(
595         struct xfs_btree_cur    *cur,
596         int                     n,
597         struct xfs_btree_block  *block)
598 {
599         int                     level = xfs_btree_get_level(block);
600
601         ASSERT(block->bb_level != 0);
602
603         return (union xfs_btree_ptr *)
604                 ((char *)block + xfs_btree_ptr_offset(cur, n, level));
605 }
606
607 /*
608  * Get the root block which is stored in the inode.
609  *
610  * For now this btree implementation assumes the btree root is always
611  * stored in the if_broot field of an inode fork.
612  */
613 STATIC struct xfs_btree_block *
614 xfs_btree_get_iroot(
615         struct xfs_btree_cur    *cur)
616 {
617         struct xfs_ifork        *ifp;
618
619         ifp = XFS_IFORK_PTR(cur->bc_private.b.ip, cur->bc_private.b.whichfork);
620         return (struct xfs_btree_block *)ifp->if_broot;
621 }
622
623 /*
624  * Retrieve the block pointer from the cursor at the given level.
625  * This may be an inode btree root or from a buffer.
626  */
627 STATIC struct xfs_btree_block *         /* generic btree block pointer */
628 xfs_btree_get_block(
629         struct xfs_btree_cur    *cur,   /* btree cursor */
630         int                     level,  /* level in btree */
631         struct xfs_buf          **bpp)  /* buffer containing the block */
632 {
633         if ((cur->bc_flags & XFS_BTREE_ROOT_IN_INODE) &&
634             (level == cur->bc_nlevels - 1)) {
635                 *bpp = NULL;
636                 return xfs_btree_get_iroot(cur);
637         }
638
639         *bpp = cur->bc_bufs[level];
640         return XFS_BUF_TO_BLOCK(*bpp);
641 }
642
643 /*
644  * Get a buffer for the block, return it with no data read.
645  * Long-form addressing.
646  */
647 xfs_buf_t *                             /* buffer for fsbno */
648 xfs_btree_get_bufl(
649         xfs_mount_t     *mp,            /* file system mount point */
650         xfs_trans_t     *tp,            /* transaction pointer */
651         xfs_fsblock_t   fsbno,          /* file system block number */
652         uint            lock)           /* lock flags for get_buf */
653 {
654         xfs_daddr_t             d;              /* real disk block address */
655
656         ASSERT(fsbno != NULLFSBLOCK);
657         d = XFS_FSB_TO_DADDR(mp, fsbno);
658         return xfs_trans_get_buf(tp, mp->m_ddev_targp, d, mp->m_bsize, lock);
659 }
660
661 /*
662  * Get a buffer for the block, return it with no data read.
663  * Short-form addressing.
664  */
665 xfs_buf_t *                             /* buffer for agno/agbno */
666 xfs_btree_get_bufs(
667         xfs_mount_t     *mp,            /* file system mount point */
668         xfs_trans_t     *tp,            /* transaction pointer */
669         xfs_agnumber_t  agno,           /* allocation group number */
670         xfs_agblock_t   agbno,          /* allocation group block number */
671         uint            lock)           /* lock flags for get_buf */
672 {
673         xfs_daddr_t             d;              /* real disk block address */
674
675         ASSERT(agno != NULLAGNUMBER);
676         ASSERT(agbno != NULLAGBLOCK);
677         d = XFS_AGB_TO_DADDR(mp, agno, agbno);
678         return xfs_trans_get_buf(tp, mp->m_ddev_targp, d, mp->m_bsize, lock);
679 }
680
681 /*
682  * Check for the cursor referring to the last block at the given level.
683  */
684 int                                     /* 1=is last block, 0=not last block */
685 xfs_btree_islastblock(
686         xfs_btree_cur_t         *cur,   /* btree cursor */
687         int                     level)  /* level to check */
688 {
689         struct xfs_btree_block  *block; /* generic btree block pointer */
690         xfs_buf_t               *bp;    /* buffer containing block */
691
692         block = xfs_btree_get_block(cur, level, &bp);
693         xfs_btree_check_block(cur, block, level, bp);
694         if (cur->bc_flags & XFS_BTREE_LONG_PTRS)
695                 return block->bb_u.l.bb_rightsib == cpu_to_be64(NULLFSBLOCK);
696         else
697                 return block->bb_u.s.bb_rightsib == cpu_to_be32(NULLAGBLOCK);
698 }
699
700 /*
701  * Change the cursor to point to the first record at the given level.
702  * Other levels are unaffected.
703  */
704 STATIC int                              /* success=1, failure=0 */
705 xfs_btree_firstrec(
706         xfs_btree_cur_t         *cur,   /* btree cursor */
707         int                     level)  /* level to change */
708 {
709         struct xfs_btree_block  *block; /* generic btree block pointer */
710         xfs_buf_t               *bp;    /* buffer containing block */
711
712         /*
713          * Get the block pointer for this level.
714          */
715         block = xfs_btree_get_block(cur, level, &bp);
716         xfs_btree_check_block(cur, block, level, bp);
717         /*
718          * It's empty, there is no such record.
719          */
720         if (!block->bb_numrecs)
721                 return 0;
722         /*
723          * Set the ptr value to 1, that's the first record/key.
724          */
725         cur->bc_ptrs[level] = 1;
726         return 1;
727 }
728
729 /*
730  * Change the cursor to point to the last record in the current block
731  * at the given level.  Other levels are unaffected.
732  */
733 STATIC int                              /* success=1, failure=0 */
734 xfs_btree_lastrec(
735         xfs_btree_cur_t         *cur,   /* btree cursor */
736         int                     level)  /* level to change */
737 {
738         struct xfs_btree_block  *block; /* generic btree block pointer */
739         xfs_buf_t               *bp;    /* buffer containing block */
740
741         /*
742          * Get the block pointer for this level.
743          */
744         block = xfs_btree_get_block(cur, level, &bp);
745         xfs_btree_check_block(cur, block, level, bp);
746         /*
747          * It's empty, there is no such record.
748          */
749         if (!block->bb_numrecs)
750                 return 0;
751         /*
752          * Set the ptr value to numrecs, that's the last record/key.
753          */
754         cur->bc_ptrs[level] = be16_to_cpu(block->bb_numrecs);
755         return 1;
756 }
757
758 /*
759  * Compute first and last byte offsets for the fields given.
760  * Interprets the offsets table, which contains struct field offsets.
761  */
762 void
763 xfs_btree_offsets(
764         __int64_t       fields,         /* bitmask of fields */
765         const short     *offsets,       /* table of field offsets */
766         int             nbits,          /* number of bits to inspect */
767         int             *first,         /* output: first byte offset */
768         int             *last)          /* output: last byte offset */
769 {
770         int             i;              /* current bit number */
771         __int64_t       imask;          /* mask for current bit number */
772
773         ASSERT(fields != 0);
774         /*
775          * Find the lowest bit, so the first byte offset.
776          */
777         for (i = 0, imask = 1LL; ; i++, imask <<= 1) {
778                 if (imask & fields) {
779                         *first = offsets[i];
780                         break;
781                 }
782         }
783         /*
784          * Find the highest bit, so the last byte offset.
785          */
786         for (i = nbits - 1, imask = 1LL << i; ; i--, imask >>= 1) {
787                 if (imask & fields) {
788                         *last = offsets[i + 1] - 1;
789                         break;
790                 }
791         }
792 }
793
794 /*
795  * Get a buffer for the block, return it read in.
796  * Long-form addressing.
797  */
798 int
799 xfs_btree_read_bufl(
800         struct xfs_mount        *mp,            /* file system mount point */
801         struct xfs_trans        *tp,            /* transaction pointer */
802         xfs_fsblock_t           fsbno,          /* file system block number */
803         uint                    lock,           /* lock flags for read_buf */
804         struct xfs_buf          **bpp,          /* buffer for fsbno */
805         int                     refval,         /* ref count value for buffer */
806         const struct xfs_buf_ops *ops)
807 {
808         struct xfs_buf          *bp;            /* return value */
809         xfs_daddr_t             d;              /* real disk block address */
810         int                     error;
811
812         ASSERT(fsbno != NULLFSBLOCK);
813         d = XFS_FSB_TO_DADDR(mp, fsbno);
814         error = xfs_trans_read_buf(mp, tp, mp->m_ddev_targp, d,
815                                    mp->m_bsize, lock, &bp, ops);
816         if (error)
817                 return error;
818         if (bp)
819                 xfs_buf_set_ref(bp, refval);
820         *bpp = bp;
821         return 0;
822 }
823
824 /*
825  * Read-ahead the block, don't wait for it, don't return a buffer.
826  * Long-form addressing.
827  */
828 /* ARGSUSED */
829 void
830 xfs_btree_reada_bufl(
831         struct xfs_mount        *mp,            /* file system mount point */
832         xfs_fsblock_t           fsbno,          /* file system block number */
833         xfs_extlen_t            count,          /* count of filesystem blocks */
834         const struct xfs_buf_ops *ops)
835 {
836         xfs_daddr_t             d;
837
838         ASSERT(fsbno != NULLFSBLOCK);
839         d = XFS_FSB_TO_DADDR(mp, fsbno);
840         xfs_buf_readahead(mp->m_ddev_targp, d, mp->m_bsize * count, ops);
841 }
842
843 /*
844  * Read-ahead the block, don't wait for it, don't return a buffer.
845  * Short-form addressing.
846  */
847 /* ARGSUSED */
848 void
849 xfs_btree_reada_bufs(
850         struct xfs_mount        *mp,            /* file system mount point */
851         xfs_agnumber_t          agno,           /* allocation group number */
852         xfs_agblock_t           agbno,          /* allocation group block number */
853         xfs_extlen_t            count,          /* count of filesystem blocks */
854         const struct xfs_buf_ops *ops)
855 {
856         xfs_daddr_t             d;
857
858         ASSERT(agno != NULLAGNUMBER);
859         ASSERT(agbno != NULLAGBLOCK);
860         d = XFS_AGB_TO_DADDR(mp, agno, agbno);
861         xfs_buf_readahead(mp->m_ddev_targp, d, mp->m_bsize * count, ops);
862 }
863
864 STATIC int
865 xfs_btree_readahead_lblock(
866         struct xfs_btree_cur    *cur,
867         int                     lr,
868         struct xfs_btree_block  *block)
869 {
870         int                     rval = 0;
871         xfs_fsblock_t           left = be64_to_cpu(block->bb_u.l.bb_leftsib);
872         xfs_fsblock_t           right = be64_to_cpu(block->bb_u.l.bb_rightsib);
873
874         if ((lr & XFS_BTCUR_LEFTRA) && left != NULLFSBLOCK) {
875                 xfs_btree_reada_bufl(cur->bc_mp, left, 1,
876                                      cur->bc_ops->buf_ops);
877                 rval++;
878         }
879
880         if ((lr & XFS_BTCUR_RIGHTRA) && right != NULLFSBLOCK) {
881                 xfs_btree_reada_bufl(cur->bc_mp, right, 1,
882                                      cur->bc_ops->buf_ops);
883                 rval++;
884         }
885
886         return rval;
887 }
888
889 STATIC int
890 xfs_btree_readahead_sblock(
891         struct xfs_btree_cur    *cur,
892         int                     lr,
893         struct xfs_btree_block *block)
894 {
895         int                     rval = 0;
896         xfs_agblock_t           left = be32_to_cpu(block->bb_u.s.bb_leftsib);
897         xfs_agblock_t           right = be32_to_cpu(block->bb_u.s.bb_rightsib);
898
899
900         if ((lr & XFS_BTCUR_LEFTRA) && left != NULLAGBLOCK) {
901                 xfs_btree_reada_bufs(cur->bc_mp, cur->bc_private.a.agno,
902                                      left, 1, cur->bc_ops->buf_ops);
903                 rval++;
904         }
905
906         if ((lr & XFS_BTCUR_RIGHTRA) && right != NULLAGBLOCK) {
907                 xfs_btree_reada_bufs(cur->bc_mp, cur->bc_private.a.agno,
908                                      right, 1, cur->bc_ops->buf_ops);
909                 rval++;
910         }
911
912         return rval;
913 }
914
915 /*
916  * Read-ahead btree blocks, at the given level.
917  * Bits in lr are set from XFS_BTCUR_{LEFT,RIGHT}RA.
918  */
919 STATIC int
920 xfs_btree_readahead(
921         struct xfs_btree_cur    *cur,           /* btree cursor */
922         int                     lev,            /* level in btree */
923         int                     lr)             /* left/right bits */
924 {
925         struct xfs_btree_block  *block;
926
927         /*
928          * No readahead needed if we are at the root level and the
929          * btree root is stored in the inode.
930          */
931         if ((cur->bc_flags & XFS_BTREE_ROOT_IN_INODE) &&
932             (lev == cur->bc_nlevels - 1))
933                 return 0;
934
935         if ((cur->bc_ra[lev] | lr) == cur->bc_ra[lev])
936                 return 0;
937
938         cur->bc_ra[lev] |= lr;
939         block = XFS_BUF_TO_BLOCK(cur->bc_bufs[lev]);
940
941         if (cur->bc_flags & XFS_BTREE_LONG_PTRS)
942                 return xfs_btree_readahead_lblock(cur, lr, block);
943         return xfs_btree_readahead_sblock(cur, lr, block);
944 }
945
946 STATIC xfs_daddr_t
947 xfs_btree_ptr_to_daddr(
948         struct xfs_btree_cur    *cur,
949         union xfs_btree_ptr     *ptr)
950 {
951         if (cur->bc_flags & XFS_BTREE_LONG_PTRS) {
952                 ASSERT(ptr->l != cpu_to_be64(NULLFSBLOCK));
953
954                 return XFS_FSB_TO_DADDR(cur->bc_mp, be64_to_cpu(ptr->l));
955         } else {
956                 ASSERT(cur->bc_private.a.agno != NULLAGNUMBER);
957                 ASSERT(ptr->s != cpu_to_be32(NULLAGBLOCK));
958
959                 return XFS_AGB_TO_DADDR(cur->bc_mp, cur->bc_private.a.agno,
960                                         be32_to_cpu(ptr->s));
961         }
962 }
963
964 /*
965  * Readahead @count btree blocks at the given @ptr location.
966  *
967  * We don't need to care about long or short form btrees here as we have a
968  * method of converting the ptr directly to a daddr available to us.
969  */
970 STATIC void
971 xfs_btree_readahead_ptr(
972         struct xfs_btree_cur    *cur,
973         union xfs_btree_ptr     *ptr,
974         xfs_extlen_t            count)
975 {
976         xfs_buf_readahead(cur->bc_mp->m_ddev_targp,
977                           xfs_btree_ptr_to_daddr(cur, ptr),
978                           cur->bc_mp->m_bsize * count, cur->bc_ops->buf_ops);
979 }
980
981 /*
982  * Set the buffer for level "lev" in the cursor to bp, releasing
983  * any previous buffer.
984  */
985 STATIC void
986 xfs_btree_setbuf(
987         xfs_btree_cur_t         *cur,   /* btree cursor */
988         int                     lev,    /* level in btree */
989         xfs_buf_t               *bp)    /* new buffer to set */
990 {
991         struct xfs_btree_block  *b;     /* btree block */
992
993         if (cur->bc_bufs[lev])
994                 xfs_trans_brelse(cur->bc_tp, cur->bc_bufs[lev]);
995         cur->bc_bufs[lev] = bp;
996         cur->bc_ra[lev] = 0;
997
998         b = XFS_BUF_TO_BLOCK(bp);
999         if (cur->bc_flags & XFS_BTREE_LONG_PTRS) {
1000                 if (b->bb_u.l.bb_leftsib == cpu_to_be64(NULLFSBLOCK))
1001                         cur->bc_ra[lev] |= XFS_BTCUR_LEFTRA;
1002                 if (b->bb_u.l.bb_rightsib == cpu_to_be64(NULLFSBLOCK))
1003                         cur->bc_ra[lev] |= XFS_BTCUR_RIGHTRA;
1004         } else {
1005                 if (b->bb_u.s.bb_leftsib == cpu_to_be32(NULLAGBLOCK))
1006                         cur->bc_ra[lev] |= XFS_BTCUR_LEFTRA;
1007                 if (b->bb_u.s.bb_rightsib == cpu_to_be32(NULLAGBLOCK))
1008                         cur->bc_ra[lev] |= XFS_BTCUR_RIGHTRA;
1009         }
1010 }
1011
1012 STATIC int
1013 xfs_btree_ptr_is_null(
1014         struct xfs_btree_cur    *cur,
1015         union xfs_btree_ptr     *ptr)
1016 {
1017         if (cur->bc_flags & XFS_BTREE_LONG_PTRS)
1018                 return ptr->l == cpu_to_be64(NULLFSBLOCK);
1019         else
1020                 return ptr->s == cpu_to_be32(NULLAGBLOCK);
1021 }
1022
1023 STATIC void
1024 xfs_btree_set_ptr_null(
1025         struct xfs_btree_cur    *cur,
1026         union xfs_btree_ptr     *ptr)
1027 {
1028         if (cur->bc_flags & XFS_BTREE_LONG_PTRS)
1029                 ptr->l = cpu_to_be64(NULLFSBLOCK);
1030         else
1031                 ptr->s = cpu_to_be32(NULLAGBLOCK);
1032 }
1033
1034 /*
1035  * Get/set/init sibling pointers
1036  */
1037 STATIC void
1038 xfs_btree_get_sibling(
1039         struct xfs_btree_cur    *cur,
1040         struct xfs_btree_block  *block,
1041         union xfs_btree_ptr     *ptr,
1042         int                     lr)
1043 {
1044         ASSERT(lr == XFS_BB_LEFTSIB || lr == XFS_BB_RIGHTSIB);
1045
1046         if (cur->bc_flags & XFS_BTREE_LONG_PTRS) {
1047                 if (lr == XFS_BB_RIGHTSIB)
1048                         ptr->l = block->bb_u.l.bb_rightsib;
1049                 else
1050                         ptr->l = block->bb_u.l.bb_leftsib;
1051         } else {
1052                 if (lr == XFS_BB_RIGHTSIB)
1053                         ptr->s = block->bb_u.s.bb_rightsib;
1054                 else
1055                         ptr->s = block->bb_u.s.bb_leftsib;
1056         }
1057 }
1058
1059 STATIC void
1060 xfs_btree_set_sibling(
1061         struct xfs_btree_cur    *cur,
1062         struct xfs_btree_block  *block,
1063         union xfs_btree_ptr     *ptr,
1064         int                     lr)
1065 {
1066         ASSERT(lr == XFS_BB_LEFTSIB || lr == XFS_BB_RIGHTSIB);
1067
1068         if (cur->bc_flags & XFS_BTREE_LONG_PTRS) {
1069                 if (lr == XFS_BB_RIGHTSIB)
1070                         block->bb_u.l.bb_rightsib = ptr->l;
1071                 else
1072                         block->bb_u.l.bb_leftsib = ptr->l;
1073         } else {
1074                 if (lr == XFS_BB_RIGHTSIB)
1075                         block->bb_u.s.bb_rightsib = ptr->s;
1076                 else
1077                         block->bb_u.s.bb_leftsib = ptr->s;
1078         }
1079 }
1080
1081 void
1082 xfs_btree_init_block_int(
1083         struct xfs_mount        *mp,
1084         struct xfs_btree_block  *buf,
1085         xfs_daddr_t             blkno,
1086         __u32                   magic,
1087         __u16                   level,
1088         __u16                   numrecs,
1089         __u64                   owner,
1090         unsigned int            flags)
1091 {
1092         buf->bb_magic = cpu_to_be32(magic);
1093         buf->bb_level = cpu_to_be16(level);
1094         buf->bb_numrecs = cpu_to_be16(numrecs);
1095
1096         if (flags & XFS_BTREE_LONG_PTRS) {
1097                 buf->bb_u.l.bb_leftsib = cpu_to_be64(NULLFSBLOCK);
1098                 buf->bb_u.l.bb_rightsib = cpu_to_be64(NULLFSBLOCK);
1099                 if (flags & XFS_BTREE_CRC_BLOCKS) {
1100                         buf->bb_u.l.bb_blkno = cpu_to_be64(blkno);
1101                         buf->bb_u.l.bb_owner = cpu_to_be64(owner);
1102                         uuid_copy(&buf->bb_u.l.bb_uuid, &mp->m_sb.sb_meta_uuid);
1103                         buf->bb_u.l.bb_pad = 0;
1104                         buf->bb_u.l.bb_lsn = 0;
1105                 }
1106         } else {
1107                 /* owner is a 32 bit value on short blocks */
1108                 __u32 __owner = (__u32)owner;
1109
1110                 buf->bb_u.s.bb_leftsib = cpu_to_be32(NULLAGBLOCK);
1111                 buf->bb_u.s.bb_rightsib = cpu_to_be32(NULLAGBLOCK);
1112                 if (flags & XFS_BTREE_CRC_BLOCKS) {
1113                         buf->bb_u.s.bb_blkno = cpu_to_be64(blkno);
1114                         buf->bb_u.s.bb_owner = cpu_to_be32(__owner);
1115                         uuid_copy(&buf->bb_u.s.bb_uuid, &mp->m_sb.sb_meta_uuid);
1116                         buf->bb_u.s.bb_lsn = 0;
1117                 }
1118         }
1119 }
1120
1121 void
1122 xfs_btree_init_block(
1123         struct xfs_mount *mp,
1124         struct xfs_buf  *bp,
1125         __u32           magic,
1126         __u16           level,
1127         __u16           numrecs,
1128         __u64           owner,
1129         unsigned int    flags)
1130 {
1131         xfs_btree_init_block_int(mp, XFS_BUF_TO_BLOCK(bp), bp->b_bn,
1132                                  magic, level, numrecs, owner, flags);
1133 }
1134
1135 STATIC void
1136 xfs_btree_init_block_cur(
1137         struct xfs_btree_cur    *cur,
1138         struct xfs_buf          *bp,
1139         int                     level,
1140         int                     numrecs)
1141 {
1142         __u64 owner;
1143
1144         /*
1145          * we can pull the owner from the cursor right now as the different
1146          * owners align directly with the pointer size of the btree. This may
1147          * change in future, but is safe for current users of the generic btree
1148          * code.
1149          */
1150         if (cur->bc_flags & XFS_BTREE_LONG_PTRS)
1151                 owner = cur->bc_private.b.ip->i_ino;
1152         else
1153                 owner = cur->bc_private.a.agno;
1154
1155         xfs_btree_init_block_int(cur->bc_mp, XFS_BUF_TO_BLOCK(bp), bp->b_bn,
1156                                  xfs_btree_magic(cur), level, numrecs,
1157                                  owner, cur->bc_flags);
1158 }
1159
1160 /*
1161  * Return true if ptr is the last record in the btree and
1162  * we need to track updates to this record.  The decision
1163  * will be further refined in the update_lastrec method.
1164  */
1165 STATIC int
1166 xfs_btree_is_lastrec(
1167         struct xfs_btree_cur    *cur,
1168         struct xfs_btree_block  *block,
1169         int                     level)
1170 {
1171         union xfs_btree_ptr     ptr;
1172
1173         if (level > 0)
1174                 return 0;
1175         if (!(cur->bc_flags & XFS_BTREE_LASTREC_UPDATE))
1176                 return 0;
1177
1178         xfs_btree_get_sibling(cur, block, &ptr, XFS_BB_RIGHTSIB);
1179         if (!xfs_btree_ptr_is_null(cur, &ptr))
1180                 return 0;
1181         return 1;
1182 }
1183
1184 STATIC void
1185 xfs_btree_buf_to_ptr(
1186         struct xfs_btree_cur    *cur,
1187         struct xfs_buf          *bp,
1188         union xfs_btree_ptr     *ptr)
1189 {
1190         if (cur->bc_flags & XFS_BTREE_LONG_PTRS)
1191                 ptr->l = cpu_to_be64(XFS_DADDR_TO_FSB(cur->bc_mp,
1192                                         XFS_BUF_ADDR(bp)));
1193         else {
1194                 ptr->s = cpu_to_be32(xfs_daddr_to_agbno(cur->bc_mp,
1195                                         XFS_BUF_ADDR(bp)));
1196         }
1197 }
1198
1199 STATIC void
1200 xfs_btree_set_refs(
1201         struct xfs_btree_cur    *cur,
1202         struct xfs_buf          *bp)
1203 {
1204         switch (cur->bc_btnum) {
1205         case XFS_BTNUM_BNO:
1206         case XFS_BTNUM_CNT:
1207                 xfs_buf_set_ref(bp, XFS_ALLOC_BTREE_REF);
1208                 break;
1209         case XFS_BTNUM_INO:
1210         case XFS_BTNUM_FINO:
1211                 xfs_buf_set_ref(bp, XFS_INO_BTREE_REF);
1212                 break;
1213         case XFS_BTNUM_BMAP:
1214                 xfs_buf_set_ref(bp, XFS_BMAP_BTREE_REF);
1215                 break;
1216         case XFS_BTNUM_RMAP:
1217                 xfs_buf_set_ref(bp, XFS_RMAP_BTREE_REF);
1218                 break;
1219         default:
1220                 ASSERT(0);
1221         }
1222 }
1223
1224 STATIC int
1225 xfs_btree_get_buf_block(
1226         struct xfs_btree_cur    *cur,
1227         union xfs_btree_ptr     *ptr,
1228         int                     flags,
1229         struct xfs_btree_block  **block,
1230         struct xfs_buf          **bpp)
1231 {
1232         struct xfs_mount        *mp = cur->bc_mp;
1233         xfs_daddr_t             d;
1234
1235         /* need to sort out how callers deal with failures first */
1236         ASSERT(!(flags & XBF_TRYLOCK));
1237
1238         d = xfs_btree_ptr_to_daddr(cur, ptr);
1239         *bpp = xfs_trans_get_buf(cur->bc_tp, mp->m_ddev_targp, d,
1240                                  mp->m_bsize, flags);
1241
1242         if (!*bpp)
1243                 return -ENOMEM;
1244
1245         (*bpp)->b_ops = cur->bc_ops->buf_ops;
1246         *block = XFS_BUF_TO_BLOCK(*bpp);
1247         return 0;
1248 }
1249
1250 /*
1251  * Read in the buffer at the given ptr and return the buffer and
1252  * the block pointer within the buffer.
1253  */
1254 STATIC int
1255 xfs_btree_read_buf_block(
1256         struct xfs_btree_cur    *cur,
1257         union xfs_btree_ptr     *ptr,
1258         int                     flags,
1259         struct xfs_btree_block  **block,
1260         struct xfs_buf          **bpp)
1261 {
1262         struct xfs_mount        *mp = cur->bc_mp;
1263         xfs_daddr_t             d;
1264         int                     error;
1265
1266         /* need to sort out how callers deal with failures first */
1267         ASSERT(!(flags & XBF_TRYLOCK));
1268
1269         d = xfs_btree_ptr_to_daddr(cur, ptr);
1270         error = xfs_trans_read_buf(mp, cur->bc_tp, mp->m_ddev_targp, d,
1271                                    mp->m_bsize, flags, bpp,
1272                                    cur->bc_ops->buf_ops);
1273         if (error)
1274                 return error;
1275
1276         xfs_btree_set_refs(cur, *bpp);
1277         *block = XFS_BUF_TO_BLOCK(*bpp);
1278         return 0;
1279 }
1280
1281 /*
1282  * Copy keys from one btree block to another.
1283  */
1284 STATIC void
1285 xfs_btree_copy_keys(
1286         struct xfs_btree_cur    *cur,
1287         union xfs_btree_key     *dst_key,
1288         union xfs_btree_key     *src_key,
1289         int                     numkeys)
1290 {
1291         ASSERT(numkeys >= 0);
1292         memcpy(dst_key, src_key, numkeys * cur->bc_ops->key_len);
1293 }
1294
1295 /*
1296  * Copy records from one btree block to another.
1297  */
1298 STATIC void
1299 xfs_btree_copy_recs(
1300         struct xfs_btree_cur    *cur,
1301         union xfs_btree_rec     *dst_rec,
1302         union xfs_btree_rec     *src_rec,
1303         int                     numrecs)
1304 {
1305         ASSERT(numrecs >= 0);
1306         memcpy(dst_rec, src_rec, numrecs * cur->bc_ops->rec_len);
1307 }
1308
1309 /*
1310  * Copy block pointers from one btree block to another.
1311  */
1312 STATIC void
1313 xfs_btree_copy_ptrs(
1314         struct xfs_btree_cur    *cur,
1315         union xfs_btree_ptr     *dst_ptr,
1316         union xfs_btree_ptr     *src_ptr,
1317         int                     numptrs)
1318 {
1319         ASSERT(numptrs >= 0);
1320         memcpy(dst_ptr, src_ptr, numptrs * xfs_btree_ptr_len(cur));
1321 }
1322
1323 /*
1324  * Shift keys one index left/right inside a single btree block.
1325  */
1326 STATIC void
1327 xfs_btree_shift_keys(
1328         struct xfs_btree_cur    *cur,
1329         union xfs_btree_key     *key,
1330         int                     dir,
1331         int                     numkeys)
1332 {
1333         char                    *dst_key;
1334
1335         ASSERT(numkeys >= 0);
1336         ASSERT(dir == 1 || dir == -1);
1337
1338         dst_key = (char *)key + (dir * cur->bc_ops->key_len);
1339         memmove(dst_key, key, numkeys * cur->bc_ops->key_len);
1340 }
1341
1342 /*
1343  * Shift records one index left/right inside a single btree block.
1344  */
1345 STATIC void
1346 xfs_btree_shift_recs(
1347         struct xfs_btree_cur    *cur,
1348         union xfs_btree_rec     *rec,
1349         int                     dir,
1350         int                     numrecs)
1351 {
1352         char                    *dst_rec;
1353
1354         ASSERT(numrecs >= 0);
1355         ASSERT(dir == 1 || dir == -1);
1356
1357         dst_rec = (char *)rec + (dir * cur->bc_ops->rec_len);
1358         memmove(dst_rec, rec, numrecs * cur->bc_ops->rec_len);
1359 }
1360
1361 /*
1362  * Shift block pointers one index left/right inside a single btree block.
1363  */
1364 STATIC void
1365 xfs_btree_shift_ptrs(
1366         struct xfs_btree_cur    *cur,
1367         union xfs_btree_ptr     *ptr,
1368         int                     dir,
1369         int                     numptrs)
1370 {
1371         char                    *dst_ptr;
1372
1373         ASSERT(numptrs >= 0);
1374         ASSERT(dir == 1 || dir == -1);
1375
1376         dst_ptr = (char *)ptr + (dir * xfs_btree_ptr_len(cur));
1377         memmove(dst_ptr, ptr, numptrs * xfs_btree_ptr_len(cur));
1378 }
1379
1380 /*
1381  * Log key values from the btree block.
1382  */
1383 STATIC void
1384 xfs_btree_log_keys(
1385         struct xfs_btree_cur    *cur,
1386         struct xfs_buf          *bp,
1387         int                     first,
1388         int                     last)
1389 {
1390         XFS_BTREE_TRACE_CURSOR(cur, XBT_ENTRY);
1391         XFS_BTREE_TRACE_ARGBII(cur, bp, first, last);
1392
1393         if (bp) {
1394                 xfs_trans_buf_set_type(cur->bc_tp, bp, XFS_BLFT_BTREE_BUF);
1395                 xfs_trans_log_buf(cur->bc_tp, bp,
1396                                   xfs_btree_key_offset(cur, first),
1397                                   xfs_btree_key_offset(cur, last + 1) - 1);
1398         } else {
1399                 xfs_trans_log_inode(cur->bc_tp, cur->bc_private.b.ip,
1400                                 xfs_ilog_fbroot(cur->bc_private.b.whichfork));
1401         }
1402
1403         XFS_BTREE_TRACE_CURSOR(cur, XBT_EXIT);
1404 }
1405
1406 /*
1407  * Log record values from the btree block.
1408  */
1409 void
1410 xfs_btree_log_recs(
1411         struct xfs_btree_cur    *cur,
1412         struct xfs_buf          *bp,
1413         int                     first,
1414         int                     last)
1415 {
1416         XFS_BTREE_TRACE_CURSOR(cur, XBT_ENTRY);
1417         XFS_BTREE_TRACE_ARGBII(cur, bp, first, last);
1418
1419         xfs_trans_buf_set_type(cur->bc_tp, bp, XFS_BLFT_BTREE_BUF);
1420         xfs_trans_log_buf(cur->bc_tp, bp,
1421                           xfs_btree_rec_offset(cur, first),
1422                           xfs_btree_rec_offset(cur, last + 1) - 1);
1423
1424         XFS_BTREE_TRACE_CURSOR(cur, XBT_EXIT);
1425 }
1426
1427 /*
1428  * Log block pointer fields from a btree block (nonleaf).
1429  */
1430 STATIC void
1431 xfs_btree_log_ptrs(
1432         struct xfs_btree_cur    *cur,   /* btree cursor */
1433         struct xfs_buf          *bp,    /* buffer containing btree block */
1434         int                     first,  /* index of first pointer to log */
1435         int                     last)   /* index of last pointer to log */
1436 {
1437         XFS_BTREE_TRACE_CURSOR(cur, XBT_ENTRY);
1438         XFS_BTREE_TRACE_ARGBII(cur, bp, first, last);
1439
1440         if (bp) {
1441                 struct xfs_btree_block  *block = XFS_BUF_TO_BLOCK(bp);
1442                 int                     level = xfs_btree_get_level(block);
1443
1444                 xfs_trans_buf_set_type(cur->bc_tp, bp, XFS_BLFT_BTREE_BUF);
1445                 xfs_trans_log_buf(cur->bc_tp, bp,
1446                                 xfs_btree_ptr_offset(cur, first, level),
1447                                 xfs_btree_ptr_offset(cur, last + 1, level) - 1);
1448         } else {
1449                 xfs_trans_log_inode(cur->bc_tp, cur->bc_private.b.ip,
1450                         xfs_ilog_fbroot(cur->bc_private.b.whichfork));
1451         }
1452
1453         XFS_BTREE_TRACE_CURSOR(cur, XBT_EXIT);
1454 }
1455
1456 /*
1457  * Log fields from a btree block header.
1458  */
1459 void
1460 xfs_btree_log_block(
1461         struct xfs_btree_cur    *cur,   /* btree cursor */
1462         struct xfs_buf          *bp,    /* buffer containing btree block */
1463         int                     fields) /* mask of fields: XFS_BB_... */
1464 {
1465         int                     first;  /* first byte offset logged */
1466         int                     last;   /* last byte offset logged */
1467         static const short      soffsets[] = {  /* table of offsets (short) */
1468                 offsetof(struct xfs_btree_block, bb_magic),
1469                 offsetof(struct xfs_btree_block, bb_level),
1470                 offsetof(struct xfs_btree_block, bb_numrecs),
1471                 offsetof(struct xfs_btree_block, bb_u.s.bb_leftsib),
1472                 offsetof(struct xfs_btree_block, bb_u.s.bb_rightsib),
1473                 offsetof(struct xfs_btree_block, bb_u.s.bb_blkno),
1474                 offsetof(struct xfs_btree_block, bb_u.s.bb_lsn),
1475                 offsetof(struct xfs_btree_block, bb_u.s.bb_uuid),
1476                 offsetof(struct xfs_btree_block, bb_u.s.bb_owner),
1477                 offsetof(struct xfs_btree_block, bb_u.s.bb_crc),
1478                 XFS_BTREE_SBLOCK_CRC_LEN
1479         };
1480         static const short      loffsets[] = {  /* table of offsets (long) */
1481                 offsetof(struct xfs_btree_block, bb_magic),
1482                 offsetof(struct xfs_btree_block, bb_level),
1483                 offsetof(struct xfs_btree_block, bb_numrecs),
1484                 offsetof(struct xfs_btree_block, bb_u.l.bb_leftsib),
1485                 offsetof(struct xfs_btree_block, bb_u.l.bb_rightsib),
1486                 offsetof(struct xfs_btree_block, bb_u.l.bb_blkno),
1487                 offsetof(struct xfs_btree_block, bb_u.l.bb_lsn),
1488                 offsetof(struct xfs_btree_block, bb_u.l.bb_uuid),
1489                 offsetof(struct xfs_btree_block, bb_u.l.bb_owner),
1490                 offsetof(struct xfs_btree_block, bb_u.l.bb_crc),
1491                 offsetof(struct xfs_btree_block, bb_u.l.bb_pad),
1492                 XFS_BTREE_LBLOCK_CRC_LEN
1493         };
1494
1495         XFS_BTREE_TRACE_CURSOR(cur, XBT_ENTRY);
1496         XFS_BTREE_TRACE_ARGBI(cur, bp, fields);
1497
1498         if (bp) {
1499                 int nbits;
1500
1501                 if (cur->bc_flags & XFS_BTREE_CRC_BLOCKS) {
1502                         /*
1503                          * We don't log the CRC when updating a btree
1504                          * block but instead recreate it during log
1505                          * recovery.  As the log buffers have checksums
1506                          * of their own this is safe and avoids logging a crc
1507                          * update in a lot of places.
1508                          */
1509                         if (fields == XFS_BB_ALL_BITS)
1510                                 fields = XFS_BB_ALL_BITS_CRC;
1511                         nbits = XFS_BB_NUM_BITS_CRC;
1512                 } else {
1513                         nbits = XFS_BB_NUM_BITS;
1514                 }
1515                 xfs_btree_offsets(fields,
1516                                   (cur->bc_flags & XFS_BTREE_LONG_PTRS) ?
1517                                         loffsets : soffsets,
1518                                   nbits, &first, &last);
1519                 xfs_trans_buf_set_type(cur->bc_tp, bp, XFS_BLFT_BTREE_BUF);
1520                 xfs_trans_log_buf(cur->bc_tp, bp, first, last);
1521         } else {
1522                 xfs_trans_log_inode(cur->bc_tp, cur->bc_private.b.ip,
1523                         xfs_ilog_fbroot(cur->bc_private.b.whichfork));
1524         }
1525
1526         XFS_BTREE_TRACE_CURSOR(cur, XBT_EXIT);
1527 }
1528
1529 /*
1530  * Increment cursor by one record at the level.
1531  * For nonzero levels the leaf-ward information is untouched.
1532  */
1533 int                                             /* error */
1534 xfs_btree_increment(
1535         struct xfs_btree_cur    *cur,
1536         int                     level,
1537         int                     *stat)          /* success/failure */
1538 {
1539         struct xfs_btree_block  *block;
1540         union xfs_btree_ptr     ptr;
1541         struct xfs_buf          *bp;
1542         int                     error;          /* error return value */
1543         int                     lev;
1544
1545         XFS_BTREE_TRACE_CURSOR(cur, XBT_ENTRY);
1546         XFS_BTREE_TRACE_ARGI(cur, level);
1547
1548         ASSERT(level < cur->bc_nlevels);
1549
1550         /* Read-ahead to the right at this level. */
1551         xfs_btree_readahead(cur, level, XFS_BTCUR_RIGHTRA);
1552
1553         /* Get a pointer to the btree block. */
1554         block = xfs_btree_get_block(cur, level, &bp);
1555
1556 #ifdef DEBUG
1557         error = xfs_btree_check_block(cur, block, level, bp);
1558         if (error)
1559                 goto error0;
1560 #endif
1561
1562         /* We're done if we remain in the block after the increment. */
1563         if (++cur->bc_ptrs[level] <= xfs_btree_get_numrecs(block))
1564                 goto out1;
1565
1566         /* Fail if we just went off the right edge of the tree. */
1567         xfs_btree_get_sibling(cur, block, &ptr, XFS_BB_RIGHTSIB);
1568         if (xfs_btree_ptr_is_null(cur, &ptr))
1569                 goto out0;
1570
1571         XFS_BTREE_STATS_INC(cur, increment);
1572
1573         /*
1574          * March up the tree incrementing pointers.
1575          * Stop when we don't go off the right edge of a block.
1576          */
1577         for (lev = level + 1; lev < cur->bc_nlevels; lev++) {
1578                 block = xfs_btree_get_block(cur, lev, &bp);
1579
1580 #ifdef DEBUG
1581                 error = xfs_btree_check_block(cur, block, lev, bp);
1582                 if (error)
1583                         goto error0;
1584 #endif
1585
1586                 if (++cur->bc_ptrs[lev] <= xfs_btree_get_numrecs(block))
1587                         break;
1588
1589                 /* Read-ahead the right block for the next loop. */
1590                 xfs_btree_readahead(cur, lev, XFS_BTCUR_RIGHTRA);
1591         }
1592
1593         /*
1594          * If we went off the root then we are either seriously
1595          * confused or have the tree root in an inode.
1596          */
1597         if (lev == cur->bc_nlevels) {
1598                 if (cur->bc_flags & XFS_BTREE_ROOT_IN_INODE)
1599                         goto out0;
1600                 ASSERT(0);
1601                 error = -EFSCORRUPTED;
1602                 goto error0;
1603         }
1604         ASSERT(lev < cur->bc_nlevels);
1605
1606         /*
1607          * Now walk back down the tree, fixing up the cursor's buffer
1608          * pointers and key numbers.
1609          */
1610         for (block = xfs_btree_get_block(cur, lev, &bp); lev > level; ) {
1611                 union xfs_btree_ptr     *ptrp;
1612
1613                 ptrp = xfs_btree_ptr_addr(cur, cur->bc_ptrs[lev], block);
1614                 --lev;
1615                 error = xfs_btree_read_buf_block(cur, ptrp, 0, &block, &bp);
1616                 if (error)
1617                         goto error0;
1618
1619                 xfs_btree_setbuf(cur, lev, bp);
1620                 cur->bc_ptrs[lev] = 1;
1621         }
1622 out1:
1623         XFS_BTREE_TRACE_CURSOR(cur, XBT_EXIT);
1624         *stat = 1;
1625         return 0;
1626
1627 out0:
1628         XFS_BTREE_TRACE_CURSOR(cur, XBT_EXIT);
1629         *stat = 0;
1630         return 0;
1631
1632 error0:
1633         XFS_BTREE_TRACE_CURSOR(cur, XBT_ERROR);
1634         return error;
1635 }
1636
1637 /*
1638  * Decrement cursor by one record at the level.
1639  * For nonzero levels the leaf-ward information is untouched.
1640  */
1641 int                                             /* error */
1642 xfs_btree_decrement(
1643         struct xfs_btree_cur    *cur,
1644         int                     level,
1645         int                     *stat)          /* success/failure */
1646 {
1647         struct xfs_btree_block  *block;
1648         xfs_buf_t               *bp;
1649         int                     error;          /* error return value */
1650         int                     lev;
1651         union xfs_btree_ptr     ptr;
1652
1653         XFS_BTREE_TRACE_CURSOR(cur, XBT_ENTRY);
1654         XFS_BTREE_TRACE_ARGI(cur, level);
1655
1656         ASSERT(level < cur->bc_nlevels);
1657
1658         /* Read-ahead to the left at this level. */
1659         xfs_btree_readahead(cur, level, XFS_BTCUR_LEFTRA);
1660
1661         /* We're done if we remain in the block after the decrement. */
1662         if (--cur->bc_ptrs[level] > 0)
1663                 goto out1;
1664
1665         /* Get a pointer to the btree block. */
1666         block = xfs_btree_get_block(cur, level, &bp);
1667
1668 #ifdef DEBUG
1669         error = xfs_btree_check_block(cur, block, level, bp);
1670         if (error)
1671                 goto error0;
1672 #endif
1673
1674         /* Fail if we just went off the left edge of the tree. */
1675         xfs_btree_get_sibling(cur, block, &ptr, XFS_BB_LEFTSIB);
1676         if (xfs_btree_ptr_is_null(cur, &ptr))
1677                 goto out0;
1678
1679         XFS_BTREE_STATS_INC(cur, decrement);
1680
1681         /*
1682          * March up the tree decrementing pointers.
1683          * Stop when we don't go off the left edge of a block.
1684          */
1685         for (lev = level + 1; lev < cur->bc_nlevels; lev++) {
1686                 if (--cur->bc_ptrs[lev] > 0)
1687                         break;
1688                 /* Read-ahead the left block for the next loop. */
1689                 xfs_btree_readahead(cur, lev, XFS_BTCUR_LEFTRA);
1690         }
1691
1692         /*
1693          * If we went off the root then we are seriously confused.
1694          * or the root of the tree is in an inode.
1695          */
1696         if (lev == cur->bc_nlevels) {
1697                 if (cur->bc_flags & XFS_BTREE_ROOT_IN_INODE)
1698                         goto out0;
1699                 ASSERT(0);
1700                 error = -EFSCORRUPTED;
1701                 goto error0;
1702         }
1703         ASSERT(lev < cur->bc_nlevels);
1704
1705         /*
1706          * Now walk back down the tree, fixing up the cursor's buffer
1707          * pointers and key numbers.
1708          */
1709         for (block = xfs_btree_get_block(cur, lev, &bp); lev > level; ) {
1710                 union xfs_btree_ptr     *ptrp;
1711
1712                 ptrp = xfs_btree_ptr_addr(cur, cur->bc_ptrs[lev], block);
1713                 --lev;
1714                 error = xfs_btree_read_buf_block(cur, ptrp, 0, &block, &bp);
1715                 if (error)
1716                         goto error0;
1717                 xfs_btree_setbuf(cur, lev, bp);
1718                 cur->bc_ptrs[lev] = xfs_btree_get_numrecs(block);
1719         }
1720 out1:
1721         XFS_BTREE_TRACE_CURSOR(cur, XBT_EXIT);
1722         *stat = 1;
1723         return 0;
1724
1725 out0:
1726         XFS_BTREE_TRACE_CURSOR(cur, XBT_EXIT);
1727         *stat = 0;
1728         return 0;
1729
1730 error0:
1731         XFS_BTREE_TRACE_CURSOR(cur, XBT_ERROR);
1732         return error;
1733 }
1734
1735 STATIC int
1736 xfs_btree_lookup_get_block(
1737         struct xfs_btree_cur    *cur,   /* btree cursor */
1738         int                     level,  /* level in the btree */
1739         union xfs_btree_ptr     *pp,    /* ptr to btree block */
1740         struct xfs_btree_block  **blkp) /* return btree block */
1741 {
1742         struct xfs_buf          *bp;    /* buffer pointer for btree block */
1743         int                     error = 0;
1744
1745         /* special case the root block if in an inode */
1746         if ((cur->bc_flags & XFS_BTREE_ROOT_IN_INODE) &&
1747             (level == cur->bc_nlevels - 1)) {
1748                 *blkp = xfs_btree_get_iroot(cur);
1749                 return 0;
1750         }
1751
1752         /*
1753          * If the old buffer at this level for the disk address we are
1754          * looking for re-use it.
1755          *
1756          * Otherwise throw it away and get a new one.
1757          */
1758         bp = cur->bc_bufs[level];
1759         if (bp && XFS_BUF_ADDR(bp) == xfs_btree_ptr_to_daddr(cur, pp)) {
1760                 *blkp = XFS_BUF_TO_BLOCK(bp);
1761                 return 0;
1762         }
1763
1764         error = xfs_btree_read_buf_block(cur, pp, 0, blkp, &bp);
1765         if (error)
1766                 return error;
1767
1768         xfs_btree_setbuf(cur, level, bp);
1769         return 0;
1770 }
1771
1772 /*
1773  * Get current search key.  For level 0 we don't actually have a key
1774  * structure so we make one up from the record.  For all other levels
1775  * we just return the right key.
1776  */
1777 STATIC union xfs_btree_key *
1778 xfs_lookup_get_search_key(
1779         struct xfs_btree_cur    *cur,
1780         int                     level,
1781         int                     keyno,
1782         struct xfs_btree_block  *block,
1783         union xfs_btree_key     *kp)
1784 {
1785         if (level == 0) {
1786                 cur->bc_ops->init_key_from_rec(kp,
1787                                 xfs_btree_rec_addr(cur, keyno, block));
1788                 return kp;
1789         }
1790
1791         return xfs_btree_key_addr(cur, keyno, block);
1792 }
1793
1794 /*
1795  * Lookup the record.  The cursor is made to point to it, based on dir.
1796  * stat is set to 0 if can't find any such record, 1 for success.
1797  */
1798 int                                     /* error */
1799 xfs_btree_lookup(
1800         struct xfs_btree_cur    *cur,   /* btree cursor */
1801         xfs_lookup_t            dir,    /* <=, ==, or >= */
1802         int                     *stat)  /* success/failure */
1803 {
1804         struct xfs_btree_block  *block; /* current btree block */
1805         __int64_t               diff;   /* difference for the current key */
1806         int                     error;  /* error return value */
1807         int                     keyno;  /* current key number */
1808         int                     level;  /* level in the btree */
1809         union xfs_btree_ptr     *pp;    /* ptr to btree block */
1810         union xfs_btree_ptr     ptr;    /* ptr to btree block */
1811
1812         XFS_BTREE_TRACE_CURSOR(cur, XBT_ENTRY);
1813         XFS_BTREE_TRACE_ARGI(cur, dir);
1814
1815         XFS_BTREE_STATS_INC(cur, lookup);
1816
1817         block = NULL;
1818         keyno = 0;
1819
1820         /* initialise start pointer from cursor */
1821         cur->bc_ops->init_ptr_from_cur(cur, &ptr);
1822         pp = &ptr;
1823
1824         /*
1825          * Iterate over each level in the btree, starting at the root.
1826          * For each level above the leaves, find the key we need, based
1827          * on the lookup record, then follow the corresponding block
1828          * pointer down to the next level.
1829          */
1830         for (level = cur->bc_nlevels - 1, diff = 1; level >= 0; level--) {
1831                 /* Get the block we need to do the lookup on. */
1832                 error = xfs_btree_lookup_get_block(cur, level, pp, &block);
1833                 if (error)
1834                         goto error0;
1835
1836                 if (diff == 0) {
1837                         /*
1838                          * If we already had a key match at a higher level, we
1839                          * know we need to use the first entry in this block.
1840                          */
1841                         keyno = 1;
1842                 } else {
1843                         /* Otherwise search this block. Do a binary search. */
1844
1845                         int     high;   /* high entry number */
1846                         int     low;    /* low entry number */
1847
1848                         /* Set low and high entry numbers, 1-based. */
1849                         low = 1;
1850                         high = xfs_btree_get_numrecs(block);
1851                         if (!high) {
1852                                 /* Block is empty, must be an empty leaf. */
1853                                 ASSERT(level == 0 && cur->bc_nlevels == 1);
1854
1855                                 cur->bc_ptrs[0] = dir != XFS_LOOKUP_LE;
1856                                 XFS_BTREE_TRACE_CURSOR(cur, XBT_EXIT);
1857                                 *stat = 0;
1858                                 return 0;
1859                         }
1860
1861                         /* Binary search the block. */
1862                         while (low <= high) {
1863                                 union xfs_btree_key     key;
1864                                 union xfs_btree_key     *kp;
1865
1866                                 XFS_BTREE_STATS_INC(cur, compare);
1867
1868                                 /* keyno is average of low and high. */
1869                                 keyno = (low + high) >> 1;
1870
1871                                 /* Get current search key */
1872                                 kp = xfs_lookup_get_search_key(cur, level,
1873                                                 keyno, block, &key);
1874
1875                                 /*
1876                                  * Compute difference to get next direction:
1877                                  *  - less than, move right
1878                                  *  - greater than, move left
1879                                  *  - equal, we're done
1880                                  */
1881                                 diff = cur->bc_ops->key_diff(cur, kp);
1882                                 if (diff < 0)
1883                                         low = keyno + 1;
1884                                 else if (diff > 0)
1885                                         high = keyno - 1;
1886                                 else
1887                                         break;
1888                         }
1889                 }
1890
1891                 /*
1892                  * If there are more levels, set up for the next level
1893                  * by getting the block number and filling in the cursor.
1894                  */
1895                 if (level > 0) {
1896                         /*
1897                          * If we moved left, need the previous key number,
1898                          * unless there isn't one.
1899                          */
1900                         if (diff > 0 && --keyno < 1)
1901                                 keyno = 1;
1902                         pp = xfs_btree_ptr_addr(cur, keyno, block);
1903
1904 #ifdef DEBUG
1905                         error = xfs_btree_check_ptr(cur, pp, 0, level);
1906                         if (error)
1907                                 goto error0;
1908 #endif
1909                         cur->bc_ptrs[level] = keyno;
1910                 }
1911         }
1912
1913         /* Done with the search. See if we need to adjust the results. */
1914         if (dir != XFS_LOOKUP_LE && diff < 0) {
1915                 keyno++;
1916                 /*
1917                  * If ge search and we went off the end of the block, but it's
1918                  * not the last block, we're in the wrong block.
1919                  */
1920                 xfs_btree_get_sibling(cur, block, &ptr, XFS_BB_RIGHTSIB);
1921                 if (dir == XFS_LOOKUP_GE &&
1922                     keyno > xfs_btree_get_numrecs(block) &&
1923                     !xfs_btree_ptr_is_null(cur, &ptr)) {
1924                         int     i;
1925
1926                         cur->bc_ptrs[0] = keyno;
1927                         error = xfs_btree_increment(cur, 0, &i);
1928                         if (error)
1929                                 goto error0;
1930                         XFS_WANT_CORRUPTED_RETURN(cur->bc_mp, i == 1);
1931                         XFS_BTREE_TRACE_CURSOR(cur, XBT_EXIT);
1932                         *stat = 1;
1933                         return 0;
1934                 }
1935         } else if (dir == XFS_LOOKUP_LE && diff > 0)
1936                 keyno--;
1937         cur->bc_ptrs[0] = keyno;
1938
1939         /* Return if we succeeded or not. */
1940         if (keyno == 0 || keyno > xfs_btree_get_numrecs(block))
1941                 *stat = 0;
1942         else if (dir != XFS_LOOKUP_EQ || diff == 0)
1943                 *stat = 1;
1944         else
1945                 *stat = 0;
1946         XFS_BTREE_TRACE_CURSOR(cur, XBT_EXIT);
1947         return 0;
1948
1949 error0:
1950         XFS_BTREE_TRACE_CURSOR(cur, XBT_ERROR);
1951         return error;
1952 }
1953
1954 /* Find the high key storage area from a regular key. */
1955 STATIC union xfs_btree_key *
1956 xfs_btree_high_key_from_key(
1957         struct xfs_btree_cur    *cur,
1958         union xfs_btree_key     *key)
1959 {
1960         ASSERT(cur->bc_flags & XFS_BTREE_OVERLAPPING);
1961         return (union xfs_btree_key *)((char *)key +
1962                         (cur->bc_ops->key_len / 2));
1963 }
1964
1965 /* Determine the low (and high if overlapped) keys of a leaf block */
1966 STATIC void
1967 xfs_btree_get_leaf_keys(
1968         struct xfs_btree_cur    *cur,
1969         struct xfs_btree_block  *block,
1970         union xfs_btree_key     *key)
1971 {
1972         union xfs_btree_key     max_hkey;
1973         union xfs_btree_key     hkey;
1974         union xfs_btree_rec     *rec;
1975         union xfs_btree_key     *high;
1976         int                     n;
1977
1978         rec = xfs_btree_rec_addr(cur, 1, block);
1979         cur->bc_ops->init_key_from_rec(key, rec);
1980
1981         if (cur->bc_flags & XFS_BTREE_OVERLAPPING) {
1982
1983                 cur->bc_ops->init_high_key_from_rec(&max_hkey, rec);
1984                 for (n = 2; n <= xfs_btree_get_numrecs(block); n++) {
1985                         rec = xfs_btree_rec_addr(cur, n, block);
1986                         cur->bc_ops->init_high_key_from_rec(&hkey, rec);
1987                         if (cur->bc_ops->diff_two_keys(cur, &hkey, &max_hkey)
1988                                         > 0)
1989                                 max_hkey = hkey;
1990                 }
1991
1992                 high = xfs_btree_high_key_from_key(cur, key);
1993                 memcpy(high, &max_hkey, cur->bc_ops->key_len / 2);
1994         }
1995 }
1996
1997 /* Determine the low (and high if overlapped) keys of a node block */
1998 STATIC void
1999 xfs_btree_get_node_keys(
2000         struct xfs_btree_cur    *cur,
2001         struct xfs_btree_block  *block,
2002         union xfs_btree_key     *key)
2003 {
2004         union xfs_btree_key     *hkey;
2005         union xfs_btree_key     *max_hkey;
2006         union xfs_btree_key     *high;
2007         int                     n;
2008
2009         if (cur->bc_flags & XFS_BTREE_OVERLAPPING) {
2010                 memcpy(key, xfs_btree_key_addr(cur, 1, block),
2011                                 cur->bc_ops->key_len / 2);
2012
2013                 max_hkey = xfs_btree_high_key_addr(cur, 1, block);
2014                 for (n = 2; n <= xfs_btree_get_numrecs(block); n++) {
2015                         hkey = xfs_btree_high_key_addr(cur, n, block);
2016                         if (cur->bc_ops->diff_two_keys(cur, hkey, max_hkey) > 0)
2017                                 max_hkey = hkey;
2018                 }
2019
2020                 high = xfs_btree_high_key_from_key(cur, key);
2021                 memcpy(high, max_hkey, cur->bc_ops->key_len / 2);
2022         } else {
2023                 memcpy(key, xfs_btree_key_addr(cur, 1, block),
2024                                 cur->bc_ops->key_len);
2025         }
2026 }
2027
2028 /* Derive the keys for any btree block. */
2029 STATIC void
2030 xfs_btree_get_keys(
2031         struct xfs_btree_cur    *cur,
2032         struct xfs_btree_block  *block,
2033         union xfs_btree_key     *key)
2034 {
2035         if (be16_to_cpu(block->bb_level) == 0)
2036                 xfs_btree_get_leaf_keys(cur, block, key);
2037         else
2038                 xfs_btree_get_node_keys(cur, block, key);
2039 }
2040
2041 /*
2042  * Decide if we need to update the parent keys of a btree block.  For
2043  * a standard btree this is only necessary if we're updating the first
2044  * record/key.  For an overlapping btree, we must always update the
2045  * keys because the highest key can be in any of the records or keys
2046  * in the block.
2047  */
2048 static inline bool
2049 xfs_btree_needs_key_update(
2050         struct xfs_btree_cur    *cur,
2051         int                     ptr)
2052 {
2053         return (cur->bc_flags & XFS_BTREE_OVERLAPPING) || ptr == 1;
2054 }
2055
2056 /*
2057  * Update the low and high parent keys of the given level, progressing
2058  * towards the root.  If force_all is false, stop if the keys for a given
2059  * level do not need updating.
2060  */
2061 STATIC int
2062 __xfs_btree_updkeys(
2063         struct xfs_btree_cur    *cur,
2064         int                     level,
2065         struct xfs_btree_block  *block,
2066         struct xfs_buf          *bp0,
2067         bool                    force_all)
2068 {
2069         union xfs_btree_bigkey  key;    /* keys from current level */
2070         union xfs_btree_key     *lkey;  /* keys from the next level up */
2071         union xfs_btree_key     *hkey;
2072         union xfs_btree_key     *nlkey; /* keys from the next level up */
2073         union xfs_btree_key     *nhkey;
2074         struct xfs_buf          *bp;
2075         int                     ptr;
2076
2077         ASSERT(cur->bc_flags & XFS_BTREE_OVERLAPPING);
2078
2079         /* Exit if there aren't any parent levels to update. */
2080         if (level + 1 >= cur->bc_nlevels)
2081                 return 0;
2082
2083         trace_xfs_btree_updkeys(cur, level, bp0);
2084
2085         lkey = (union xfs_btree_key *)&key;
2086         hkey = xfs_btree_high_key_from_key(cur, lkey);
2087         xfs_btree_get_keys(cur, block, lkey);
2088         for (level++; level < cur->bc_nlevels; level++) {
2089 #ifdef DEBUG
2090                 int             error;
2091 #endif
2092                 block = xfs_btree_get_block(cur, level, &bp);
2093                 trace_xfs_btree_updkeys(cur, level, bp);
2094 #ifdef DEBUG
2095                 error = xfs_btree_check_block(cur, block, level, bp);
2096                 if (error) {
2097                         XFS_BTREE_TRACE_CURSOR(cur, XBT_ERROR);
2098                         return error;
2099                 }
2100 #endif
2101                 ptr = cur->bc_ptrs[level];
2102                 nlkey = xfs_btree_key_addr(cur, ptr, block);
2103                 nhkey = xfs_btree_high_key_addr(cur, ptr, block);
2104                 if (!force_all &&
2105                     !(cur->bc_ops->diff_two_keys(cur, nlkey, lkey) != 0 ||
2106                       cur->bc_ops->diff_two_keys(cur, nhkey, hkey) != 0))
2107                         break;
2108                 xfs_btree_copy_keys(cur, nlkey, lkey, 1);
2109                 xfs_btree_log_keys(cur, bp, ptr, ptr);
2110                 if (level + 1 >= cur->bc_nlevels)
2111                         break;
2112                 xfs_btree_get_node_keys(cur, block, lkey);
2113         }
2114
2115         return 0;
2116 }
2117
2118 /* Update all the keys from some level in cursor back to the root. */
2119 STATIC int
2120 xfs_btree_updkeys_force(
2121         struct xfs_btree_cur    *cur,
2122         int                     level)
2123 {
2124         struct xfs_buf          *bp;
2125         struct xfs_btree_block  *block;
2126
2127         block = xfs_btree_get_block(cur, level, &bp);
2128         return __xfs_btree_updkeys(cur, level, block, bp, true);
2129 }
2130
2131 /*
2132  * Update the parent keys of the given level, progressing towards the root.
2133  */
2134 STATIC int
2135 xfs_btree_update_keys(
2136         struct xfs_btree_cur    *cur,
2137         int                     level)
2138 {
2139         struct xfs_btree_block  *block;
2140         struct xfs_buf          *bp;
2141         union xfs_btree_key     *kp;
2142         union xfs_btree_key     key;
2143         int                     ptr;
2144
2145         ASSERT(level >= 0);
2146
2147         block = xfs_btree_get_block(cur, level, &bp);
2148         if (cur->bc_flags & XFS_BTREE_OVERLAPPING)
2149                 return __xfs_btree_updkeys(cur, level, block, bp, false);
2150
2151         XFS_BTREE_TRACE_CURSOR(cur, XBT_ENTRY);
2152         XFS_BTREE_TRACE_ARGIK(cur, level, keyp);
2153
2154         /*
2155          * Go up the tree from this level toward the root.
2156          * At each level, update the key value to the value input.
2157          * Stop when we reach a level where the cursor isn't pointing
2158          * at the first entry in the block.
2159          */
2160         xfs_btree_get_keys(cur, block, &key);
2161         for (level++, ptr = 1; ptr == 1 && level < cur->bc_nlevels; level++) {
2162 #ifdef DEBUG
2163                 int             error;
2164 #endif
2165                 block = xfs_btree_get_block(cur, level, &bp);
2166 #ifdef DEBUG
2167                 error = xfs_btree_check_block(cur, block, level, bp);
2168                 if (error) {
2169                         XFS_BTREE_TRACE_CURSOR(cur, XBT_ERROR);
2170                         return error;
2171                 }
2172 #endif
2173                 ptr = cur->bc_ptrs[level];
2174                 kp = xfs_btree_key_addr(cur, ptr, block);
2175                 xfs_btree_copy_keys(cur, kp, &key, 1);
2176                 xfs_btree_log_keys(cur, bp, ptr, ptr);
2177         }
2178
2179         XFS_BTREE_TRACE_CURSOR(cur, XBT_EXIT);
2180         return 0;
2181 }
2182
2183 /*
2184  * Update the record referred to by cur to the value in the
2185  * given record. This either works (return 0) or gets an
2186  * EFSCORRUPTED error.
2187  */
2188 int
2189 xfs_btree_update(
2190         struct xfs_btree_cur    *cur,
2191         union xfs_btree_rec     *rec)
2192 {
2193         struct xfs_btree_block  *block;
2194         struct xfs_buf          *bp;
2195         int                     error;
2196         int                     ptr;
2197         union xfs_btree_rec     *rp;
2198
2199         XFS_BTREE_TRACE_CURSOR(cur, XBT_ENTRY);
2200         XFS_BTREE_TRACE_ARGR(cur, rec);
2201
2202         /* Pick up the current block. */
2203         block = xfs_btree_get_block(cur, 0, &bp);
2204
2205 #ifdef DEBUG
2206         error = xfs_btree_check_block(cur, block, 0, bp);
2207         if (error)
2208                 goto error0;
2209 #endif
2210         /* Get the address of the rec to be updated. */
2211         ptr = cur->bc_ptrs[0];
2212         rp = xfs_btree_rec_addr(cur, ptr, block);
2213
2214         /* Fill in the new contents and log them. */
2215         xfs_btree_copy_recs(cur, rp, rec, 1);
2216         xfs_btree_log_recs(cur, bp, ptr, ptr);
2217
2218         /*
2219          * If we are tracking the last record in the tree and
2220          * we are at the far right edge of the tree, update it.
2221          */
2222         if (xfs_btree_is_lastrec(cur, block, 0)) {
2223                 cur->bc_ops->update_lastrec(cur, block, rec,
2224                                             ptr, LASTREC_UPDATE);
2225         }
2226
2227         /* Pass new key value up to our parent. */
2228         if (xfs_btree_needs_key_update(cur, ptr)) {
2229                 error = xfs_btree_update_keys(cur, 0);
2230                 if (error)
2231                         goto error0;
2232         }
2233
2234         XFS_BTREE_TRACE_CURSOR(cur, XBT_EXIT);
2235         return 0;
2236
2237 error0:
2238         XFS_BTREE_TRACE_CURSOR(cur, XBT_ERROR);
2239         return error;
2240 }
2241
2242 /*
2243  * Move 1 record left from cur/level if possible.
2244  * Update cur to reflect the new path.
2245  */
2246 STATIC int                                      /* error */
2247 xfs_btree_lshift(
2248         struct xfs_btree_cur    *cur,
2249         int                     level,
2250         int                     *stat)          /* success/failure */
2251 {
2252         union xfs_btree_key     key;            /* btree key */
2253         struct xfs_buf          *lbp;           /* left buffer pointer */
2254         struct xfs_btree_block  *left;          /* left btree block */
2255         int                     lrecs;          /* left record count */
2256         struct xfs_buf          *rbp;           /* right buffer pointer */
2257         struct xfs_btree_block  *right;         /* right btree block */
2258         struct xfs_btree_cur    *tcur;          /* temporary btree cursor */
2259         int                     rrecs;          /* right record count */
2260         union xfs_btree_ptr     lptr;           /* left btree pointer */
2261         union xfs_btree_key     *rkp = NULL;    /* right btree key */
2262         union xfs_btree_ptr     *rpp = NULL;    /* right address pointer */
2263         union xfs_btree_rec     *rrp = NULL;    /* right record pointer */
2264         int                     error;          /* error return value */
2265         int                     i;
2266
2267         XFS_BTREE_TRACE_CURSOR(cur, XBT_ENTRY);
2268         XFS_BTREE_TRACE_ARGI(cur, level);
2269
2270         if ((cur->bc_flags & XFS_BTREE_ROOT_IN_INODE) &&
2271             level == cur->bc_nlevels - 1)
2272                 goto out0;
2273
2274         /* Set up variables for this block as "right". */
2275         right = xfs_btree_get_block(cur, level, &rbp);
2276
2277 #ifdef DEBUG
2278         error = xfs_btree_check_block(cur, right, level, rbp);
2279         if (error)
2280                 goto error0;
2281 #endif
2282
2283         /* If we've got no left sibling then we can't shift an entry left. */
2284         xfs_btree_get_sibling(cur, right, &lptr, XFS_BB_LEFTSIB);
2285         if (xfs_btree_ptr_is_null(cur, &lptr))
2286                 goto out0;
2287
2288         /*
2289          * If the cursor entry is the one that would be moved, don't
2290          * do it... it's too complicated.
2291          */
2292         if (cur->bc_ptrs[level] <= 1)
2293                 goto out0;
2294
2295         /* Set up the left neighbor as "left". */
2296         error = xfs_btree_read_buf_block(cur, &lptr, 0, &left, &lbp);
2297         if (error)
2298                 goto error0;
2299
2300         /* If it's full, it can't take another entry. */
2301         lrecs = xfs_btree_get_numrecs(left);
2302         if (lrecs == cur->bc_ops->get_maxrecs(cur, level))
2303                 goto out0;
2304
2305         rrecs = xfs_btree_get_numrecs(right);
2306
2307         /*
2308          * We add one entry to the left side and remove one for the right side.
2309          * Account for it here, the changes will be updated on disk and logged
2310          * later.
2311          */
2312         lrecs++;
2313         rrecs--;
2314
2315         XFS_BTREE_STATS_INC(cur, lshift);
2316         XFS_BTREE_STATS_ADD(cur, moves, 1);
2317
2318         /*
2319          * If non-leaf, copy a key and a ptr to the left block.
2320          * Log the changes to the left block.
2321          */
2322         if (level > 0) {
2323                 /* It's a non-leaf.  Move keys and pointers. */
2324                 union xfs_btree_key     *lkp;   /* left btree key */
2325                 union xfs_btree_ptr     *lpp;   /* left address pointer */
2326
2327                 lkp = xfs_btree_key_addr(cur, lrecs, left);
2328                 rkp = xfs_btree_key_addr(cur, 1, right);
2329
2330                 lpp = xfs_btree_ptr_addr(cur, lrecs, left);
2331                 rpp = xfs_btree_ptr_addr(cur, 1, right);
2332 #ifdef DEBUG
2333                 error = xfs_btree_check_ptr(cur, rpp, 0, level);
2334                 if (error)
2335                         goto error0;
2336 #endif
2337                 xfs_btree_copy_keys(cur, lkp, rkp, 1);
2338                 xfs_btree_copy_ptrs(cur, lpp, rpp, 1);
2339
2340                 xfs_btree_log_keys(cur, lbp, lrecs, lrecs);
2341                 xfs_btree_log_ptrs(cur, lbp, lrecs, lrecs);
2342
2343                 ASSERT(cur->bc_ops->keys_inorder(cur,
2344                         xfs_btree_key_addr(cur, lrecs - 1, left), lkp));
2345         } else {
2346                 /* It's a leaf.  Move records.  */
2347                 union xfs_btree_rec     *lrp;   /* left record pointer */
2348
2349                 lrp = xfs_btree_rec_addr(cur, lrecs, left);
2350                 rrp = xfs_btree_rec_addr(cur, 1, right);
2351
2352                 xfs_btree_copy_recs(cur, lrp, rrp, 1);
2353                 xfs_btree_log_recs(cur, lbp, lrecs, lrecs);
2354
2355                 ASSERT(cur->bc_ops->recs_inorder(cur,
2356                         xfs_btree_rec_addr(cur, lrecs - 1, left), lrp));
2357         }
2358
2359         xfs_btree_set_numrecs(left, lrecs);
2360         xfs_btree_log_block(cur, lbp, XFS_BB_NUMRECS);
2361
2362         xfs_btree_set_numrecs(right, rrecs);
2363         xfs_btree_log_block(cur, rbp, XFS_BB_NUMRECS);
2364
2365         /*
2366          * Slide the contents of right down one entry.
2367          */
2368         XFS_BTREE_STATS_ADD(cur, moves, rrecs - 1);
2369         if (level > 0) {
2370                 /* It's a nonleaf. operate on keys and ptrs */
2371 #ifdef DEBUG
2372                 int                     i;              /* loop index */
2373
2374                 for (i = 0; i < rrecs; i++) {
2375                         error = xfs_btree_check_ptr(cur, rpp, i + 1, level);
2376                         if (error)
2377                                 goto error0;
2378                 }
2379 #endif
2380                 xfs_btree_shift_keys(cur,
2381                                 xfs_btree_key_addr(cur, 2, right),
2382                                 -1, rrecs);
2383                 xfs_btree_shift_ptrs(cur,
2384                                 xfs_btree_ptr_addr(cur, 2, right),
2385                                 -1, rrecs);
2386
2387                 xfs_btree_log_keys(cur, rbp, 1, rrecs);
2388                 xfs_btree_log_ptrs(cur, rbp, 1, rrecs);
2389         } else {
2390                 /* It's a leaf. operate on records */
2391                 xfs_btree_shift_recs(cur,
2392                         xfs_btree_rec_addr(cur, 2, right),
2393                         -1, rrecs);
2394                 xfs_btree_log_recs(cur, rbp, 1, rrecs);
2395
2396                 /*
2397                  * If it's the first record in the block, we'll need a key
2398                  * structure to pass up to the next level (updkey).
2399                  */
2400                 cur->bc_ops->init_key_from_rec(&key,
2401                         xfs_btree_rec_addr(cur, 1, right));
2402         }
2403
2404         /*
2405          * Using a temporary cursor, update the parent key values of the
2406          * block on the left.
2407          */
2408         error = xfs_btree_dup_cursor(cur, &tcur);
2409         if (error)
2410                 goto error0;
2411         i = xfs_btree_firstrec(tcur, level);
2412         XFS_WANT_CORRUPTED_GOTO(cur->bc_mp, i == 1, error0);
2413
2414         error = xfs_btree_decrement(tcur, level, &i);
2415         if (error)
2416                 goto error1;
2417
2418         /* Update the parent keys of the right block. */
2419         error = xfs_btree_update_keys(cur, level);
2420         if (error)
2421                 goto error1;
2422
2423         /* Update the parent high keys of the left block, if needed. */
2424         if (tcur->bc_flags & XFS_BTREE_OVERLAPPING) {
2425                 error = xfs_btree_update_keys(tcur, level);
2426                 if (error)
2427                         goto error1;
2428         }
2429
2430         xfs_btree_del_cursor(tcur, XFS_BTREE_NOERROR);
2431
2432         /* Slide the cursor value left one. */
2433         cur->bc_ptrs[level]--;
2434
2435         XFS_BTREE_TRACE_CURSOR(cur, XBT_EXIT);
2436         *stat = 1;
2437         return 0;
2438
2439 out0:
2440         XFS_BTREE_TRACE_CURSOR(cur, XBT_EXIT);
2441         *stat = 0;
2442         return 0;
2443
2444 error0:
2445         XFS_BTREE_TRACE_CURSOR(cur, XBT_ERROR);
2446         return error;
2447
2448 error1:
2449         XFS_BTREE_TRACE_CURSOR(tcur, XBT_ERROR);
2450         xfs_btree_del_cursor(tcur, XFS_BTREE_ERROR);
2451         return error;
2452 }
2453
2454 /*
2455  * Move 1 record right from cur/level if possible.
2456  * Update cur to reflect the new path.
2457  */
2458 STATIC int                                      /* error */
2459 xfs_btree_rshift(
2460         struct xfs_btree_cur    *cur,
2461         int                     level,
2462         int                     *stat)          /* success/failure */
2463 {
2464         union xfs_btree_key     key;            /* btree key */
2465         struct xfs_buf          *lbp;           /* left buffer pointer */
2466         struct xfs_btree_block  *left;          /* left btree block */
2467         struct xfs_buf          *rbp;           /* right buffer pointer */
2468         struct xfs_btree_block  *right;         /* right btree block */
2469         struct xfs_btree_cur    *tcur;          /* temporary btree cursor */
2470         union xfs_btree_ptr     rptr;           /* right block pointer */
2471         union xfs_btree_key     *rkp;           /* right btree key */
2472         int                     rrecs;          /* right record count */
2473         int                     lrecs;          /* left record count */
2474         int                     error;          /* error return value */
2475         int                     i;              /* loop counter */
2476
2477         XFS_BTREE_TRACE_CURSOR(cur, XBT_ENTRY);
2478         XFS_BTREE_TRACE_ARGI(cur, level);
2479
2480         if ((cur->bc_flags & XFS_BTREE_ROOT_IN_INODE) &&
2481             (level == cur->bc_nlevels - 1))
2482                 goto out0;
2483
2484         /* Set up variables for this block as "left". */
2485         left = xfs_btree_get_block(cur, level, &lbp);
2486
2487 #ifdef DEBUG
2488         error = xfs_btree_check_block(cur, left, level, lbp);
2489         if (error)
2490                 goto error0;
2491 #endif
2492
2493         /* If we've got no right sibling then we can't shift an entry right. */
2494         xfs_btree_get_sibling(cur, left, &rptr, XFS_BB_RIGHTSIB);
2495         if (xfs_btree_ptr_is_null(cur, &rptr))
2496                 goto out0;
2497
2498         /*
2499          * If the cursor entry is the one that would be moved, don't
2500          * do it... it's too complicated.
2501          */
2502         lrecs = xfs_btree_get_numrecs(left);
2503         if (cur->bc_ptrs[level] >= lrecs)
2504                 goto out0;
2505
2506         /* Set up the right neighbor as "right". */
2507         error = xfs_btree_read_buf_block(cur, &rptr, 0, &right, &rbp);
2508         if (error)
2509                 goto error0;
2510
2511         /* If it's full, it can't take another entry. */
2512         rrecs = xfs_btree_get_numrecs(right);
2513         if (rrecs == cur->bc_ops->get_maxrecs(cur, level))
2514                 goto out0;
2515
2516         XFS_BTREE_STATS_INC(cur, rshift);
2517         XFS_BTREE_STATS_ADD(cur, moves, rrecs);
2518
2519         /*
2520          * Make a hole at the start of the right neighbor block, then
2521          * copy the last left block entry to the hole.
2522          */
2523         if (level > 0) {
2524                 /* It's a nonleaf. make a hole in the keys and ptrs */
2525                 union xfs_btree_key     *lkp;
2526                 union xfs_btree_ptr     *lpp;
2527                 union xfs_btree_ptr     *rpp;
2528
2529                 lkp = xfs_btree_key_addr(cur, lrecs, left);
2530                 lpp = xfs_btree_ptr_addr(cur, lrecs, left);
2531                 rkp = xfs_btree_key_addr(cur, 1, right);
2532                 rpp = xfs_btree_ptr_addr(cur, 1, right);
2533
2534 #ifdef DEBUG
2535                 for (i = rrecs - 1; i >= 0; i--) {
2536                         error = xfs_btree_check_ptr(cur, rpp, i, level);
2537                         if (error)
2538                                 goto error0;
2539                 }
2540 #endif
2541
2542                 xfs_btree_shift_keys(cur, rkp, 1, rrecs);
2543                 xfs_btree_shift_ptrs(cur, rpp, 1, rrecs);
2544
2545 #ifdef DEBUG
2546                 error = xfs_btree_check_ptr(cur, lpp, 0, level);
2547                 if (error)
2548                         goto error0;
2549 #endif
2550
2551                 /* Now put the new data in, and log it. */
2552                 xfs_btree_copy_keys(cur, rkp, lkp, 1);
2553                 xfs_btree_copy_ptrs(cur, rpp, lpp, 1);
2554
2555                 xfs_btree_log_keys(cur, rbp, 1, rrecs + 1);
2556                 xfs_btree_log_ptrs(cur, rbp, 1, rrecs + 1);
2557
2558                 ASSERT(cur->bc_ops->keys_inorder(cur, rkp,
2559                         xfs_btree_key_addr(cur, 2, right)));
2560         } else {
2561                 /* It's a leaf. make a hole in the records */
2562                 union xfs_btree_rec     *lrp;
2563                 union xfs_btree_rec     *rrp;
2564
2565                 lrp = xfs_btree_rec_addr(cur, lrecs, left);
2566                 rrp = xfs_btree_rec_addr(cur, 1, right);
2567
2568                 xfs_btree_shift_recs(cur, rrp, 1, rrecs);
2569
2570                 /* Now put the new data in, and log it. */
2571                 xfs_btree_copy_recs(cur, rrp, lrp, 1);
2572                 xfs_btree_log_recs(cur, rbp, 1, rrecs + 1);
2573
2574                 cur->bc_ops->init_key_from_rec(&key, rrp);
2575
2576                 ASSERT(cur->bc_ops->recs_inorder(cur, rrp,
2577                         xfs_btree_rec_addr(cur, 2, right)));
2578         }
2579
2580         /*
2581          * Decrement and log left's numrecs, bump and log right's numrecs.
2582          */
2583         xfs_btree_set_numrecs(left, --lrecs);
2584         xfs_btree_log_block(cur, lbp, XFS_BB_NUMRECS);
2585
2586         xfs_btree_set_numrecs(right, ++rrecs);
2587         xfs_btree_log_block(cur, rbp, XFS_BB_NUMRECS);
2588
2589         /*
2590          * Using a temporary cursor, update the parent key values of the
2591          * block on the right.
2592          */
2593         error = xfs_btree_dup_cursor(cur, &tcur);
2594         if (error)
2595                 goto error0;
2596         i = xfs_btree_lastrec(tcur, level);
2597         XFS_WANT_CORRUPTED_GOTO(cur->bc_mp, i == 1, error0);
2598
2599         error = xfs_btree_increment(tcur, level, &i);
2600         if (error)
2601                 goto error1;
2602
2603         /* Update the parent high keys of the left block, if needed. */
2604         if (cur->bc_flags & XFS_BTREE_OVERLAPPING) {
2605                 error = xfs_btree_update_keys(cur, level);
2606                 if (error)
2607                         goto error1;
2608         }
2609
2610         /* Update the parent keys of the right block. */
2611         error = xfs_btree_update_keys(tcur, level);
2612         if (error)
2613                 goto error1;
2614
2615         xfs_btree_del_cursor(tcur, XFS_BTREE_NOERROR);
2616
2617         XFS_BTREE_TRACE_CURSOR(cur, XBT_EXIT);
2618         *stat = 1;
2619         return 0;
2620
2621 out0:
2622         XFS_BTREE_TRACE_CURSOR(cur, XBT_EXIT);
2623         *stat = 0;
2624         return 0;
2625
2626 error0:
2627         XFS_BTREE_TRACE_CURSOR(cur, XBT_ERROR);
2628         return error;
2629
2630 error1:
2631         XFS_BTREE_TRACE_CURSOR(tcur, XBT_ERROR);
2632         xfs_btree_del_cursor(tcur, XFS_BTREE_ERROR);
2633         return error;
2634 }
2635
2636 /*
2637  * Split cur/level block in half.
2638  * Return new block number and the key to its first
2639  * record (to be inserted into parent).
2640  */
2641 STATIC int                                      /* error */
2642 __xfs_btree_split(
2643         struct xfs_btree_cur    *cur,
2644         int                     level,
2645         union xfs_btree_ptr     *ptrp,
2646         union xfs_btree_key     *key,
2647         struct xfs_btree_cur    **curp,
2648         int                     *stat)          /* success/failure */
2649 {
2650         union xfs_btree_ptr     lptr;           /* left sibling block ptr */
2651         struct xfs_buf          *lbp;           /* left buffer pointer */
2652         struct xfs_btree_block  *left;          /* left btree block */
2653         union xfs_btree_ptr     rptr;           /* right sibling block ptr */
2654         struct xfs_buf          *rbp;           /* right buffer pointer */
2655         struct xfs_btree_block  *right;         /* right btree block */
2656         union xfs_btree_ptr     rrptr;          /* right-right sibling ptr */
2657         struct xfs_buf          *rrbp;          /* right-right buffer pointer */
2658         struct xfs_btree_block  *rrblock;       /* right-right btree block */
2659         int                     lrecs;
2660         int                     rrecs;
2661         int                     src_index;
2662         int                     error;          /* error return value */
2663 #ifdef DEBUG
2664         int                     i;
2665 #endif
2666
2667         XFS_BTREE_TRACE_CURSOR(cur, XBT_ENTRY);
2668         XFS_BTREE_TRACE_ARGIPK(cur, level, *ptrp, key);
2669
2670         XFS_BTREE_STATS_INC(cur, split);
2671
2672         /* Set up left block (current one). */
2673         left = xfs_btree_get_block(cur, level, &lbp);
2674
2675 #ifdef DEBUG
2676         error = xfs_btree_check_block(cur, left, level, lbp);
2677         if (error)
2678                 goto error0;
2679 #endif
2680
2681         xfs_btree_buf_to_ptr(cur, lbp, &lptr);
2682
2683         /* Allocate the new block. If we can't do it, we're toast. Give up. */
2684         error = cur->bc_ops->alloc_block(cur, &lptr, &rptr, stat);
2685         if (error)
2686                 goto error0;
2687         if (*stat == 0)
2688                 goto out0;
2689         XFS_BTREE_STATS_INC(cur, alloc);
2690
2691         /* Set up the new block as "right". */
2692         error = xfs_btree_get_buf_block(cur, &rptr, 0, &right, &rbp);
2693         if (error)
2694                 goto error0;
2695
2696         /* Fill in the btree header for the new right block. */
2697         xfs_btree_init_block_cur(cur, rbp, xfs_btree_get_level(left), 0);
2698
2699         /*
2700          * Split the entries between the old and the new block evenly.
2701          * Make sure that if there's an odd number of entries now, that
2702          * each new block will have the same number of entries.
2703          */
2704         lrecs = xfs_btree_get_numrecs(left);
2705         rrecs = lrecs / 2;
2706         if ((lrecs & 1) && cur->bc_ptrs[level] <= rrecs + 1)
2707                 rrecs++;
2708         src_index = (lrecs - rrecs + 1);
2709
2710         XFS_BTREE_STATS_ADD(cur, moves, rrecs);
2711
2712         /* Adjust numrecs for the later get_*_keys() calls. */
2713         lrecs -= rrecs;
2714         xfs_btree_set_numrecs(left, lrecs);
2715         xfs_btree_set_numrecs(right, xfs_btree_get_numrecs(right) + rrecs);
2716
2717         /*
2718          * Copy btree block entries from the left block over to the
2719          * new block, the right. Update the right block and log the
2720          * changes.
2721          */
2722         if (level > 0) {
2723                 /* It's a non-leaf.  Move keys and pointers. */
2724                 union xfs_btree_key     *lkp;   /* left btree key */
2725                 union xfs_btree_ptr     *lpp;   /* left address pointer */
2726                 union xfs_btree_key     *rkp;   /* right btree key */
2727                 union xfs_btree_ptr     *rpp;   /* right address pointer */
2728
2729                 lkp = xfs_btree_key_addr(cur, src_index, left);
2730                 lpp = xfs_btree_ptr_addr(cur, src_index, left);
2731                 rkp = xfs_btree_key_addr(cur, 1, right);
2732                 rpp = xfs_btree_ptr_addr(cur, 1, right);
2733
2734 #ifdef DEBUG
2735                 for (i = src_index; i < rrecs; i++) {
2736                         error = xfs_btree_check_ptr(cur, lpp, i, level);
2737                         if (error)
2738                                 goto error0;
2739                 }
2740 #endif
2741
2742                 /* Copy the keys & pointers to the new block. */
2743                 xfs_btree_copy_keys(cur, rkp, lkp, rrecs);
2744                 xfs_btree_copy_ptrs(cur, rpp, lpp, rrecs);
2745
2746                 xfs_btree_log_keys(cur, rbp, 1, rrecs);
2747                 xfs_btree_log_ptrs(cur, rbp, 1, rrecs);
2748
2749                 /* Stash the keys of the new block for later insertion. */
2750                 xfs_btree_get_node_keys(cur, right, key);
2751         } else {
2752                 /* It's a leaf.  Move records.  */
2753                 union xfs_btree_rec     *lrp;   /* left record pointer */
2754                 union xfs_btree_rec     *rrp;   /* right record pointer */
2755
2756                 lrp = xfs_btree_rec_addr(cur, src_index, left);
2757                 rrp = xfs_btree_rec_addr(cur, 1, right);
2758
2759                 /* Copy records to the new block. */
2760                 xfs_btree_copy_recs(cur, rrp, lrp, rrecs);
2761                 xfs_btree_log_recs(cur, rbp, 1, rrecs);
2762
2763                 /* Stash the keys of the new block for later insertion. */
2764                 xfs_btree_get_leaf_keys(cur, right, key);
2765         }
2766
2767         /*
2768          * Find the left block number by looking in the buffer.
2769          * Adjust sibling pointers.
2770          */
2771         xfs_btree_get_sibling(cur, left, &rrptr, XFS_BB_RIGHTSIB);
2772         xfs_btree_set_sibling(cur, right, &rrptr, XFS_BB_RIGHTSIB);
2773         xfs_btree_set_sibling(cur, right, &lptr, XFS_BB_LEFTSIB);
2774         xfs_btree_set_sibling(cur, left, &rptr, XFS_BB_RIGHTSIB);
2775
2776         xfs_btree_log_block(cur, rbp, XFS_BB_ALL_BITS);
2777         xfs_btree_log_block(cur, lbp, XFS_BB_NUMRECS | XFS_BB_RIGHTSIB);
2778
2779         /*
2780          * If there's a block to the new block's right, make that block
2781          * point back to right instead of to left.
2782          */
2783         if (!xfs_btree_ptr_is_null(cur, &rrptr)) {
2784                 error = xfs_btree_read_buf_block(cur, &rrptr,
2785                                                         0, &rrblock, &rrbp);
2786                 if (error)
2787                         goto error0;
2788                 xfs_btree_set_sibling(cur, rrblock, &rptr, XFS_BB_LEFTSIB);
2789                 xfs_btree_log_block(cur, rrbp, XFS_BB_LEFTSIB);
2790         }
2791
2792         /* Update the parent high keys of the left block, if needed. */
2793         if (cur->bc_flags & XFS_BTREE_OVERLAPPING) {
2794                 error = xfs_btree_update_keys(cur, level);
2795                 if (error)
2796                         goto error0;
2797         }
2798
2799         /*
2800          * If the cursor is really in the right block, move it there.
2801          * If it's just pointing past the last entry in left, then we'll
2802          * insert there, so don't change anything in that case.
2803          */
2804         if (cur->bc_ptrs[level] > lrecs + 1) {
2805                 xfs_btree_setbuf(cur, level, rbp);
2806                 cur->bc_ptrs[level] -= lrecs;
2807         }
2808         /*
2809          * If there are more levels, we'll need another cursor which refers
2810          * the right block, no matter where this cursor was.
2811          */
2812         if (level + 1 < cur->bc_nlevels) {
2813                 error = xfs_btree_dup_cursor(cur, curp);
2814                 if (error)
2815                         goto error0;
2816                 (*curp)->bc_ptrs[level + 1]++;
2817         }
2818         *ptrp = rptr;
2819         XFS_BTREE_TRACE_CURSOR(cur, XBT_EXIT);
2820         *stat = 1;
2821         return 0;
2822 out0:
2823         XFS_BTREE_TRACE_CURSOR(cur, XBT_EXIT);
2824         *stat = 0;
2825         return 0;
2826
2827 error0:
2828         XFS_BTREE_TRACE_CURSOR(cur, XBT_ERROR);
2829         return error;
2830 }
2831
2832 struct xfs_btree_split_args {
2833         struct xfs_btree_cur    *cur;
2834         int                     level;
2835         union xfs_btree_ptr     *ptrp;
2836         union xfs_btree_key     *key;
2837         struct xfs_btree_cur    **curp;
2838         int                     *stat;          /* success/failure */
2839         int                     result;
2840         bool                    kswapd; /* allocation in kswapd context */
2841         struct completion       *done;
2842         struct work_struct      work;
2843 };
2844
2845 /*
2846  * Stack switching interfaces for allocation
2847  */
2848 static void
2849 xfs_btree_split_worker(
2850         struct work_struct      *work)
2851 {
2852         struct xfs_btree_split_args     *args = container_of(work,
2853                                                 struct xfs_btree_split_args, work);
2854         unsigned long           pflags;
2855         unsigned long           new_pflags = PF_FSTRANS;
2856
2857         /*
2858          * we are in a transaction context here, but may also be doing work
2859          * in kswapd context, and hence we may need to inherit that state
2860          * temporarily to ensure that we don't block waiting for memory reclaim
2861          * in any way.
2862          */
2863         if (args->kswapd)
2864                 new_pflags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD;
2865
2866         current_set_flags_nested(&pflags, new_pflags);
2867
2868         args->result = __xfs_btree_split(args->cur, args->level, args->ptrp,
2869                                          args->key, args->curp, args->stat);
2870         complete(args->done);
2871
2872         current_restore_flags_nested(&pflags, new_pflags);
2873 }
2874
2875 /*
2876  * BMBT split requests often come in with little stack to work on. Push
2877  * them off to a worker thread so there is lots of stack to use. For the other
2878  * btree types, just call directly to avoid the context switch overhead here.
2879  */
2880 STATIC int                                      /* error */
2881 xfs_btree_split(
2882         struct xfs_btree_cur    *cur,
2883         int                     level,
2884         union xfs_btree_ptr     *ptrp,
2885         union xfs_btree_key     *key,
2886         struct xfs_btree_cur    **curp,
2887         int                     *stat)          /* success/failure */
2888 {
2889         struct xfs_btree_split_args     args;
2890         DECLARE_COMPLETION_ONSTACK(done);
2891
2892         if (cur->bc_btnum != XFS_BTNUM_BMAP)
2893                 return __xfs_btree_split(cur, level, ptrp, key, curp, stat);
2894
2895         args.cur = cur;
2896         args.level = level;
2897         args.ptrp = ptrp;
2898         args.key = key;
2899         args.curp = curp;
2900         args.stat = stat;
2901         args.done = &done;
2902         args.kswapd = current_is_kswapd();
2903         INIT_WORK_ONSTACK(&args.work, xfs_btree_split_worker);
2904         queue_work(xfs_alloc_wq, &args.work);
2905         wait_for_completion(&done);
2906         destroy_work_on_stack(&args.work);
2907         return args.result;
2908 }
2909
2910
2911 /*
2912  * Copy the old inode root contents into a real block and make the
2913  * broot point to it.
2914  */
2915 int                                             /* error */
2916 xfs_btree_new_iroot(
2917         struct xfs_btree_cur    *cur,           /* btree cursor */
2918         int                     *logflags,      /* logging flags for inode */
2919         int                     *stat)          /* return status - 0 fail */
2920 {
2921         struct xfs_buf          *cbp;           /* buffer for cblock */
2922         struct xfs_btree_block  *block;         /* btree block */
2923         struct xfs_btree_block  *cblock;        /* child btree block */
2924         union xfs_btree_key     *ckp;           /* child key pointer */
2925         union xfs_btree_ptr     *cpp;           /* child ptr pointer */
2926         union xfs_btree_key     *kp;            /* pointer to btree key */
2927         union xfs_btree_ptr     *pp;            /* pointer to block addr */
2928         union xfs_btree_ptr     nptr;           /* new block addr */
2929         int                     level;          /* btree level */
2930         int                     error;          /* error return code */
2931 #ifdef DEBUG
2932         int                     i;              /* loop counter */
2933 #endif
2934
2935         XFS_BTREE_TRACE_CURSOR(cur, XBT_ENTRY);
2936         XFS_BTREE_STATS_INC(cur, newroot);
2937
2938         ASSERT(cur->bc_flags & XFS_BTREE_ROOT_IN_INODE);
2939
2940         level = cur->bc_nlevels - 1;
2941
2942         block = xfs_btree_get_iroot(cur);
2943         pp = xfs_btree_ptr_addr(cur, 1, block);
2944
2945         /* Allocate the new block. If we can't do it, we're toast. Give up. */
2946         error = cur->bc_ops->alloc_block(cur, pp, &nptr, stat);
2947         if (error)
2948                 goto error0;
2949         if (*stat == 0) {
2950                 XFS_BTREE_TRACE_CURSOR(cur, XBT_EXIT);
2951                 return 0;
2952         }
2953         XFS_BTREE_STATS_INC(cur, alloc);
2954
2955         /* Copy the root into a real block. */
2956         error = xfs_btree_get_buf_block(cur, &nptr, 0, &cblock, &cbp);
2957         if (error)
2958                 goto error0;
2959
2960         /*
2961          * we can't just memcpy() the root in for CRC enabled btree blocks.
2962          * In that case have to also ensure the blkno remains correct
2963          */
2964         memcpy(cblock, block, xfs_btree_block_len(cur));
2965         if (cur->bc_flags & XFS_BTREE_CRC_BLOCKS) {
2966                 if (cur->bc_flags & XFS_BTREE_LONG_PTRS)
2967                         cblock->bb_u.l.bb_blkno = cpu_to_be64(cbp->b_bn);
2968                 else
2969                         cblock->bb_u.s.bb_blkno = cpu_to_be64(cbp->b_bn);
2970         }
2971
2972         be16_add_cpu(&block->bb_level, 1);
2973         xfs_btree_set_numrecs(block, 1);
2974         cur->bc_nlevels++;
2975         cur->bc_ptrs[level + 1] = 1;
2976
2977         kp = xfs_btree_key_addr(cur, 1, block);
2978         ckp = xfs_btree_key_addr(cur, 1, cblock);
2979         xfs_btree_copy_keys(cur, ckp, kp, xfs_btree_get_numrecs(cblock));
2980
2981         cpp = xfs_btree_ptr_addr(cur, 1, cblock);
2982 #ifdef DEBUG
2983         for (i = 0; i < be16_to_cpu(cblock->bb_numrecs); i++) {
2984                 error = xfs_btree_check_ptr(cur, pp, i, level);
2985                 if (error)
2986                         goto error0;
2987         }
2988 #endif
2989         xfs_btree_copy_ptrs(cur, cpp, pp, xfs_btree_get_numrecs(cblock));
2990
2991 #ifdef DEBUG
2992         error = xfs_btree_check_ptr(cur, &nptr, 0, level);
2993         if (error)
2994                 goto error0;
2995 #endif
2996         xfs_btree_copy_ptrs(cur, pp, &nptr, 1);
2997
2998         xfs_iroot_realloc(cur->bc_private.b.ip,
2999                           1 - xfs_btree_get_numrecs(cblock),
3000                           cur->bc_private.b.whichfork);
3001
3002         xfs_btree_setbuf(cur, level, cbp);
3003
3004         /*
3005          * Do all this logging at the end so that
3006          * the root is at the right level.
3007          */
3008         xfs_btree_log_block(cur, cbp, XFS_BB_ALL_BITS);
3009         xfs_btree_log_keys(cur, cbp, 1, be16_to_cpu(cblock->bb_numrecs));
3010         xfs_btree_log_ptrs(cur, cbp, 1, be16_to_cpu(cblock->bb_numrecs));
3011
3012         *logflags |=
3013                 XFS_ILOG_CORE | xfs_ilog_fbroot(cur->bc_private.b.whichfork);
3014         *stat = 1;
3015         XFS_BTREE_TRACE_CURSOR(cur, XBT_EXIT);
3016         return 0;
3017 error0:
3018         XFS_BTREE_TRACE_CURSOR(cur, XBT_ERROR);
3019         return error;
3020 }
3021
3022 /*
3023  * Allocate a new root block, fill it in.
3024  */
3025 STATIC int                              /* error */
3026 xfs_btree_new_root(
3027         struct xfs_btree_cur    *cur,   /* btree cursor */
3028         int                     *stat)  /* success/failure */
3029 {
3030         struct xfs_btree_block  *block; /* one half of the old root block */
3031         struct xfs_buf          *bp;    /* buffer containing block */
3032         int                     error;  /* error return value */
3033         struct xfs_buf          *lbp;   /* left buffer pointer */
3034         struct xfs_btree_block  *left;  /* left btree block */
3035         struct xfs_buf          *nbp;   /* new (root) buffer */
3036         struct xfs_btree_block  *new;   /* new (root) btree block */
3037         int                     nptr;   /* new value for key index, 1 or 2 */
3038         struct xfs_buf          *rbp;   /* right buffer pointer */
3039         struct xfs_btree_block  *right; /* right btree block */
3040         union xfs_btree_ptr     rptr;
3041         union xfs_btree_ptr     lptr;
3042
3043         XFS_BTREE_TRACE_CURSOR(cur, XBT_ENTRY);
3044         XFS_BTREE_STATS_INC(cur, newroot);
3045
3046         /* initialise our start point from the cursor */
3047         cur->bc_ops->init_ptr_from_cur(cur, &rptr);
3048
3049         /* Allocate the new block. If we can't do it, we're toast. Give up. */
3050         error = cur->bc_ops->alloc_block(cur, &rptr, &lptr, stat);
3051         if (error)
3052                 goto error0;
3053         if (*stat == 0)
3054                 goto out0;
3055         XFS_BTREE_STATS_INC(cur, alloc);
3056
3057         /* Set up the new block. */
3058         error = xfs_btree_get_buf_block(cur, &lptr, 0, &new, &nbp);
3059         if (error)
3060                 goto error0;
3061
3062         /* Set the root in the holding structure  increasing the level by 1. */
3063         cur->bc_ops->set_root(cur, &lptr, 1);
3064
3065         /*
3066          * At the previous root level there are now two blocks: the old root,
3067          * and the new block generated when it was split.  We don't know which
3068          * one the cursor is pointing at, so we set up variables "left" and
3069          * "right" for each case.
3070          */
3071         block = xfs_btree_get_block(cur, cur->bc_nlevels - 1, &bp);
3072
3073 #ifdef DEBUG
3074         error = xfs_btree_check_block(cur, block, cur->bc_nlevels - 1, bp);
3075         if (error)
3076                 goto error0;
3077 #endif
3078
3079         xfs_btree_get_sibling(cur, block, &rptr, XFS_BB_RIGHTSIB);
3080         if (!xfs_btree_ptr_is_null(cur, &rptr)) {
3081                 /* Our block is left, pick up the right block. */
3082                 lbp = bp;
3083                 xfs_btree_buf_to_ptr(cur, lbp, &lptr);
3084                 left = block;
3085                 error = xfs_btree_read_buf_block(cur, &rptr, 0, &right, &rbp);
3086                 if (error)
3087                         goto error0;
3088                 bp = rbp;
3089                 nptr = 1;
3090         } else {
3091                 /* Our block is right, pick up the left block. */
3092                 rbp = bp;
3093                 xfs_btree_buf_to_ptr(cur, rbp, &rptr);
3094                 right = block;
3095                 xfs_btree_get_sibling(cur, right, &lptr, XFS_BB_LEFTSIB);
3096                 error = xfs_btree_read_buf_block(cur, &lptr, 0, &left, &lbp);
3097                 if (error)
3098                         goto error0;
3099                 bp = lbp;
3100                 nptr = 2;
3101         }
3102
3103         /* Fill in the new block's btree header and log it. */
3104         xfs_btree_init_block_cur(cur, nbp, cur->bc_nlevels, 2);
3105         xfs_btree_log_block(cur, nbp, XFS_BB_ALL_BITS);
3106         ASSERT(!xfs_btree_ptr_is_null(cur, &lptr) &&
3107                         !xfs_btree_ptr_is_null(cur, &rptr));
3108
3109         /* Fill in the key data in the new root. */
3110         if (xfs_btree_get_level(left) > 0) {
3111                 /*
3112                  * Get the keys for the left block's keys and put them directly
3113                  * in the parent block.  Do the same for the right block.
3114                  */
3115                 xfs_btree_get_node_keys(cur, left,
3116                                 xfs_btree_key_addr(cur, 1, new));
3117                 xfs_btree_get_node_keys(cur, right,
3118                                 xfs_btree_key_addr(cur, 2, new));
3119         } else {
3120                 /*
3121                  * Get the keys for the left block's records and put them
3122                  * directly in the parent block.  Do the same for the right
3123                  * block.
3124                  */
3125                 xfs_btree_get_leaf_keys(cur, left,
3126                         xfs_btree_key_addr(cur, 1, new));
3127                 xfs_btree_get_leaf_keys(cur, right,
3128                         xfs_btree_key_addr(cur, 2, new));
3129         }
3130         xfs_btree_log_keys(cur, nbp, 1, 2);
3131
3132         /* Fill in the pointer data in the new root. */
3133         xfs_btree_copy_ptrs(cur,
3134                 xfs_btree_ptr_addr(cur, 1, new), &lptr, 1);
3135         xfs_btree_copy_ptrs(cur,
3136                 xfs_btree_ptr_addr(cur, 2, new), &rptr, 1);
3137         xfs_btree_log_ptrs(cur, nbp, 1, 2);
3138
3139         /* Fix up the cursor. */
3140         xfs_btree_setbuf(cur, cur->bc_nlevels, nbp);
3141         cur->bc_ptrs[cur->bc_nlevels] = nptr;
3142         cur->bc_nlevels++;
3143         XFS_BTREE_TRACE_CURSOR(cur, XBT_EXIT);
3144         *stat = 1;
3145         return 0;
3146 error0:
3147         XFS_BTREE_TRACE_CURSOR(cur, XBT_ERROR);
3148         return error;
3149 out0:
3150         XFS_BTREE_TRACE_CURSOR(cur, XBT_EXIT);
3151         *stat = 0;
3152         return 0;
3153 }
3154
3155 STATIC int
3156 xfs_btree_make_block_unfull(
3157         struct xfs_btree_cur    *cur,   /* btree cursor */
3158         int                     level,  /* btree level */
3159         int                     numrecs,/* # of recs in block */
3160         int                     *oindex,/* old tree index */
3161         int                     *index, /* new tree index */
3162         union xfs_btree_ptr     *nptr,  /* new btree ptr */
3163         struct xfs_btree_cur    **ncur, /* new btree cursor */
3164         union xfs_btree_key     *key,   /* key of new block */
3165         int                     *stat)
3166 {
3167         int                     error = 0;
3168
3169         if ((cur->bc_flags & XFS_BTREE_ROOT_IN_INODE) &&
3170             level == cur->bc_nlevels - 1) {
3171                 struct xfs_inode *ip = cur->bc_private.b.ip;
3172
3173                 if (numrecs < cur->bc_ops->get_dmaxrecs(cur, level)) {
3174                         /* A root block that can be made bigger. */
3175                         xfs_iroot_realloc(ip, 1, cur->bc_private.b.whichfork);
3176                         *stat = 1;
3177                 } else {
3178                         /* A root block that needs replacing */
3179                         int     logflags = 0;
3180
3181                         error = xfs_btree_new_iroot(cur, &logflags, stat);
3182                         if (error || *stat == 0)
3183                                 return error;
3184
3185                         xfs_trans_log_inode(cur->bc_tp, ip, logflags);
3186                 }
3187
3188                 return 0;
3189         }
3190
3191         /* First, try shifting an entry to the right neighbor. */
3192         error = xfs_btree_rshift(cur, level, stat);
3193         if (error || *stat)
3194                 return error;
3195
3196         /* Next, try shifting an entry to the left neighbor. */
3197         error = xfs_btree_lshift(cur, level, stat);
3198         if (error)
3199                 return error;
3200
3201         if (*stat) {
3202                 *oindex = *index = cur->bc_ptrs[level];
3203                 return 0;
3204         }
3205
3206         /*
3207          * Next, try splitting the current block in half.
3208          *
3209          * If this works we have to re-set our variables because we
3210          * could be in a different block now.
3211          */
3212         error = xfs_btree_split(cur, level, nptr, key, ncur, stat);
3213         if (error || *stat == 0)
3214                 return error;
3215
3216
3217         *index = cur->bc_ptrs[level];
3218         return 0;
3219 }
3220
3221 /*
3222  * Insert one record/level.  Return information to the caller
3223  * allowing the next level up to proceed if necessary.
3224  */
3225 STATIC int
3226 xfs_btree_insrec(
3227         struct xfs_btree_cur    *cur,   /* btree cursor */
3228         int                     level,  /* level to insert record at */
3229         union xfs_btree_ptr     *ptrp,  /* i/o: block number inserted */
3230         union xfs_btree_rec     *rec,   /* record to insert */
3231         union xfs_btree_key     *key,   /* i/o: block key for ptrp */
3232         struct xfs_btree_cur    **curp, /* output: new cursor replacing cur */
3233         int                     *stat)  /* success/failure */
3234 {
3235         struct xfs_btree_block  *block; /* btree block */
3236         struct xfs_buf          *bp;    /* buffer for block */
3237         union xfs_btree_ptr     nptr;   /* new block ptr */
3238         struct xfs_btree_cur    *ncur;  /* new btree cursor */
3239         union xfs_btree_bigkey  nkey;   /* new block key */
3240         union xfs_btree_key     *lkey;
3241         int                     optr;   /* old key/record index */
3242         int                     ptr;    /* key/record index */
3243         int                     numrecs;/* number of records */
3244         int                     error;  /* error return value */
3245 #ifdef DEBUG
3246         int                     i;
3247 #endif
3248         xfs_daddr_t             old_bn;
3249
3250         XFS_BTREE_TRACE_CURSOR(cur, XBT_ENTRY);
3251         XFS_BTREE_TRACE_ARGIPR(cur, level, *ptrp, &rec);
3252
3253         ncur = NULL;
3254         lkey = (union xfs_btree_key *)&nkey;
3255
3256         /*
3257          * If we have an external root pointer, and we've made it to the
3258          * root level, allocate a new root block and we're done.
3259          */
3260         if (!(cur->bc_flags & XFS_BTREE_ROOT_IN_INODE) &&
3261             (level >= cur->bc_nlevels)) {
3262                 error = xfs_btree_new_root(cur, stat);
3263                 xfs_btree_set_ptr_null(cur, ptrp);
3264
3265                 XFS_BTREE_TRACE_CURSOR(cur, XBT_EXIT);
3266                 return error;
3267         }
3268
3269         /* If we're off the left edge, return failure. */
3270         ptr = cur->bc_ptrs[level];
3271         if (ptr == 0) {
3272                 XFS_BTREE_TRACE_CURSOR(cur, XBT_EXIT);
3273                 *stat = 0;
3274                 return 0;
3275         }
3276
3277         optr = ptr;
3278
3279         XFS_BTREE_STATS_INC(cur, insrec);
3280
3281         /* Get pointers to the btree buffer and block. */
3282         block = xfs_btree_get_block(cur, level, &bp);
3283         old_bn = bp ? bp->b_bn : XFS_BUF_DADDR_NULL;
3284         numrecs = xfs_btree_get_numrecs(block);
3285
3286 #ifdef DEBUG
3287         error = xfs_btree_check_block(cur, block, level, bp);
3288         if (error)
3289                 goto error0;
3290
3291         /* Check that the new entry is being inserted in the right place. */
3292         if (ptr <= numrecs) {
3293                 if (level == 0) {
3294                         ASSERT(cur->bc_ops->recs_inorder(cur, rec,
3295                                 xfs_btree_rec_addr(cur, ptr, block)));
3296                 } else {
3297                         ASSERT(cur->bc_ops->keys_inorder(cur, key,
3298                                 xfs_btree_key_addr(cur, ptr, block)));
3299                 }
3300         }
3301 #endif
3302
3303         /*
3304          * If the block is full, we can't insert the new entry until we
3305          * make the block un-full.
3306          */
3307         xfs_btree_set_ptr_null(cur, &nptr);
3308         if (numrecs == cur->bc_ops->get_maxrecs(cur, level)) {
3309                 error = xfs_btree_make_block_unfull(cur, level, numrecs,
3310                                         &optr, &ptr, &nptr, &ncur, lkey, stat);
3311                 if (error || *stat == 0)
3312                         goto error0;
3313         }
3314
3315         /*
3316          * The current block may have changed if the block was
3317          * previously full and we have just made space in it.
3318          */
3319         block = xfs_btree_get_block(cur, level, &bp);
3320         numrecs = xfs_btree_get_numrecs(block);
3321
3322 #ifdef DEBUG
3323         error = xfs_btree_check_block(cur, block, level, bp);
3324         if (error)
3325                 return error;
3326 #endif
3327
3328         /*
3329          * At this point we know there's room for our new entry in the block
3330          * we're pointing at.
3331          */
3332         XFS_BTREE_STATS_ADD(cur, moves, numrecs - ptr + 1);
3333
3334         if (level > 0) {
3335                 /* It's a nonleaf. make a hole in the keys and ptrs */
3336                 union xfs_btree_key     *kp;
3337                 union xfs_btree_ptr     *pp;
3338
3339                 kp = xfs_btree_key_addr(cur, ptr, block);
3340                 pp = xfs_btree_ptr_addr(cur, ptr, block);
3341
3342 #ifdef DEBUG
3343                 for (i = numrecs - ptr; i >= 0; i--) {
3344                         error = xfs_btree_check_ptr(cur, pp, i, level);
3345                         if (error)
3346                                 return error;
3347                 }
3348 #endif
3349
3350                 xfs_btree_shift_keys(cur, kp, 1, numrecs - ptr + 1);
3351                 xfs_btree_shift_ptrs(cur, pp, 1, numrecs - ptr + 1);
3352
3353 #ifdef DEBUG
3354                 error = xfs_btree_check_ptr(cur, ptrp, 0, level);
3355                 if (error)
3356                         goto error0;
3357 #endif
3358
3359                 /* Now put the new data in, bump numrecs and log it. */
3360                 xfs_btree_copy_keys(cur, kp, key, 1);
3361                 xfs_btree_copy_ptrs(cur, pp, ptrp, 1);
3362                 numrecs++;
3363                 xfs_btree_set_numrecs(block, numrecs);
3364                 xfs_btree_log_ptrs(cur, bp, ptr, numrecs);
3365                 xfs_btree_log_keys(cur, bp, ptr, numrecs);
3366 #ifdef DEBUG
3367                 if (ptr < numrecs) {
3368                         ASSERT(cur->bc_ops->keys_inorder(cur, kp,
3369                                 xfs_btree_key_addr(cur, ptr + 1, block)));
3370                 }
3371 #endif
3372         } else {
3373                 /* It's a leaf. make a hole in the records */
3374                 union xfs_btree_rec             *rp;
3375
3376                 rp = xfs_btree_rec_addr(cur, ptr, block);
3377
3378                 xfs_btree_shift_recs(cur, rp, 1, numrecs - ptr + 1);
3379
3380                 /* Now put the new data in, bump numrecs and log it. */
3381                 xfs_btree_copy_recs(cur, rp, rec, 1);
3382                 xfs_btree_set_numrecs(block, ++numrecs);
3383                 xfs_btree_log_recs(cur, bp, ptr, numrecs);
3384 #ifdef DEBUG
3385                 if (ptr < numrecs) {
3386                         ASSERT(cur->bc_ops->recs_inorder(cur, rp,
3387                                 xfs_btree_rec_addr(cur, ptr + 1, block)));
3388                 }
3389 #endif
3390         }
3391
3392         /* Log the new number of records in the btree header. */
3393         xfs_btree_log_block(cur, bp, XFS_BB_NUMRECS);
3394
3395         /*
3396          * If we just inserted into a new tree block, we have to
3397          * recalculate nkey here because nkey is out of date.
3398          *
3399          * Otherwise we're just updating an existing block (having shoved
3400          * some records into the new tree block), so use the regular key
3401          * update mechanism.
3402          */
3403         if (bp && bp->b_bn != old_bn) {
3404                 xfs_btree_get_keys(cur, block, lkey);
3405         } else if (xfs_btree_needs_key_update(cur, optr)) {
3406                 error = xfs_btree_update_keys(cur, level);
3407                 if (error)
3408                         goto error0;
3409         }
3410
3411         /*
3412          * If we are tracking the last record in the tree and
3413          * we are at the far right edge of the tree, update it.
3414          */
3415         if (xfs_btree_is_lastrec(cur, block, level)) {
3416                 cur->bc_ops->update_lastrec(cur, block, rec,
3417                                             ptr, LASTREC_INSREC);
3418         }
3419
3420         /*
3421          * Return the new block number, if any.
3422          * If there is one, give back a record value and a cursor too.
3423          */
3424         *ptrp = nptr;
3425         if (!xfs_btree_ptr_is_null(cur, &nptr)) {
3426                 xfs_btree_copy_keys(cur, key, lkey, 1);
3427                 *curp = ncur;
3428         }
3429
3430         XFS_BTREE_TRACE_CURSOR(cur, XBT_EXIT);
3431         *stat = 1;
3432         return 0;
3433
3434 error0:
3435         XFS_BTREE_TRACE_CURSOR(cur, XBT_ERROR);
3436         return error;
3437 }
3438
3439 /*
3440  * Insert the record at the point referenced by cur.
3441  *
3442  * A multi-level split of the tree on insert will invalidate the original
3443  * cursor.  All callers of this function should assume that the cursor is
3444  * no longer valid and revalidate it.
3445  */
3446 int
3447 xfs_btree_insert(
3448         struct xfs_btree_cur    *cur,
3449         int                     *stat)
3450 {
3451         int                     error;  /* error return value */
3452         int                     i;      /* result value, 0 for failure */
3453         int                     level;  /* current level number in btree */
3454         union xfs_btree_ptr     nptr;   /* new block number (split result) */
3455         struct xfs_btree_cur    *ncur;  /* new cursor (split result) */
3456         struct xfs_btree_cur    *pcur;  /* previous level's cursor */
3457         union xfs_btree_bigkey  bkey;   /* key of block to insert */
3458         union xfs_btree_key     *key;
3459         union xfs_btree_rec     rec;    /* record to insert */
3460
3461         level = 0;
3462         ncur = NULL;
3463         pcur = cur;
3464         key = (union xfs_btree_key *)&bkey;
3465
3466         xfs_btree_set_ptr_null(cur, &nptr);
3467
3468         /* Make a key out of the record data to be inserted, and save it. */
3469         cur->bc_ops->init_rec_from_cur(cur, &rec);
3470         cur->bc_ops->init_key_from_rec(key, &rec);
3471
3472         /*
3473          * Loop going up the tree, starting at the leaf level.
3474          * Stop when we don't get a split block, that must mean that
3475          * the insert is finished with this level.
3476          */
3477         do {
3478                 /*
3479                  * Insert nrec/nptr into this level of the tree.
3480                  * Note if we fail, nptr will be null.
3481                  */
3482                 error = xfs_btree_insrec(pcur, level, &nptr, &rec, key,
3483                                 &ncur, &i);
3484                 if (error) {
3485                         if (pcur != cur)
3486                                 xfs_btree_del_cursor(pcur, XFS_BTREE_ERROR);
3487                         goto error0;
3488                 }
3489
3490                 XFS_WANT_CORRUPTED_GOTO(cur->bc_mp, i == 1, error0);
3491                 level++;
3492
3493                 /*
3494                  * See if the cursor we just used is trash.
3495                  * Can't trash the caller's cursor, but otherwise we should
3496                  * if ncur is a new cursor or we're about to be done.
3497                  */
3498                 if (pcur != cur &&
3499                     (ncur || xfs_btree_ptr_is_null(cur, &nptr))) {
3500                         /* Save the state from the cursor before we trash it */
3501                         if (cur->bc_ops->update_cursor)
3502                                 cur->bc_ops->update_cursor(pcur, cur);
3503                         cur->bc_nlevels = pcur->bc_nlevels;
3504                         xfs_btree_del_cursor(pcur, XFS_BTREE_NOERROR);
3505                 }
3506                 /* If we got a new cursor, switch to it. */
3507                 if (ncur) {
3508                         pcur = ncur;
3509                         ncur = NULL;
3510                 }
3511         } while (!xfs_btree_ptr_is_null(cur, &nptr));
3512
3513         XFS_BTREE_TRACE_CURSOR(cur, XBT_EXIT);
3514         *stat = i;
3515         return 0;
3516 error0:
3517         XFS_BTREE_TRACE_CURSOR(cur, XBT_ERROR);
3518         return error;
3519 }
3520
3521 /*
3522  * Try to merge a non-leaf block back into the inode root.
3523  *
3524  * Note: the killroot names comes from the fact that we're effectively
3525  * killing the old root block.  But because we can't just delete the
3526  * inode we have to copy the single block it was pointing to into the
3527  * inode.
3528  */
3529 STATIC int
3530 xfs_btree_kill_iroot(
3531         struct xfs_btree_cur    *cur)
3532 {
3533         int                     whichfork = cur->bc_private.b.whichfork;
3534         struct xfs_inode        *ip = cur->bc_private.b.ip;
3535         struct xfs_ifork        *ifp = XFS_IFORK_PTR(ip, whichfork);
3536         struct xfs_btree_block  *block;
3537         struct xfs_btree_block  *cblock;
3538         union xfs_btree_key     *kp;
3539         union xfs_btree_key     *ckp;
3540         union xfs_btree_ptr     *pp;
3541         union xfs_btree_ptr     *cpp;
3542         struct xfs_buf          *cbp;
3543         int                     level;
3544         int                     index;
3545         int                     numrecs;
3546         int                     error;
3547 #ifdef DEBUG
3548         union xfs_btree_ptr     ptr;
3549         int                     i;
3550 #endif
3551
3552         XFS_BTREE_TRACE_CURSOR(cur, XBT_ENTRY);
3553
3554         ASSERT(cur->bc_flags & XFS_BTREE_ROOT_IN_INODE);
3555         ASSERT(cur->bc_nlevels > 1);
3556
3557         /*
3558          * Don't deal with the root block needs to be a leaf case.
3559          * We're just going to turn the thing back into extents anyway.
3560          */
3561         level = cur->bc_nlevels - 1;
3562         if (level == 1)
3563                 goto out0;
3564
3565         /*
3566          * Give up if the root has multiple children.
3567          */
3568         block = xfs_btree_get_iroot(cur);
3569         if (xfs_btree_get_numrecs(block) != 1)
3570                 goto out0;
3571
3572         cblock = xfs_btree_get_block(cur, level - 1, &cbp);
3573         numrecs = xfs_btree_get_numrecs(cblock);
3574
3575         /*
3576          * Only do this if the next level will fit.
3577          * Then the data must be copied up to the inode,
3578          * instead of freeing the root you free the next level.
3579          */
3580         if (numrecs > cur->bc_ops->get_dmaxrecs(cur, level))
3581                 goto out0;
3582
3583         XFS_BTREE_STATS_INC(cur, killroot);
3584
3585 #ifdef DEBUG
3586         xfs_btree_get_sibling(cur, block, &ptr, XFS_BB_LEFTSIB);
3587         ASSERT(xfs_btree_ptr_is_null(cur, &ptr));
3588         xfs_btree_get_sibling(cur, block, &ptr, XFS_BB_RIGHTSIB);
3589         ASSERT(xfs_btree_ptr_is_null(cur, &ptr));
3590 #endif
3591
3592         index = numrecs - cur->bc_ops->get_maxrecs(cur, level);
3593         if (index) {
3594                 xfs_iroot_realloc(cur->bc_private.b.ip, index,
3595                                   cur->bc_private.b.whichfork);
3596                 block = ifp->if_broot;
3597         }
3598
3599         be16_add_cpu(&block->bb_numrecs, index);
3600         ASSERT(block->bb_numrecs == cblock->bb_numrecs);
3601
3602         kp = xfs_btree_key_addr(cur, 1, block);
3603         ckp = xfs_btree_key_addr(cur, 1, cblock);
3604         xfs_btree_copy_keys(cur, kp, ckp, numrecs);
3605
3606         pp = xfs_btree_ptr_addr(cur, 1, block);
3607         cpp = xfs_btree_ptr_addr(cur, 1, cblock);
3608 #ifdef DEBUG
3609         for (i = 0; i < numrecs; i++) {
3610                 error = xfs_btree_check_ptr(cur, cpp, i, level - 1);
3611                 if (error) {
3612                         XFS_BTREE_TRACE_CURSOR(cur, XBT_ERROR);
3613                         return error;
3614                 }
3615         }
3616 #endif
3617         xfs_btree_copy_ptrs(cur, pp, cpp, numrecs);
3618
3619         error = xfs_btree_free_block(cur, cbp);
3620         if (error) {
3621                 XFS_BTREE_TRACE_CURSOR(cur, XBT_ERROR);
3622                 return error;
3623         }
3624
3625         cur->bc_bufs[level - 1] = NULL;
3626         be16_add_cpu(&block->bb_level, -1);
3627         xfs_trans_log_inode(cur->bc_tp, ip,
3628                 XFS_ILOG_CORE | xfs_ilog_fbroot(cur->bc_private.b.whichfork));
3629         cur->bc_nlevels--;
3630 out0:
3631         XFS_BTREE_TRACE_CURSOR(cur, XBT_EXIT);
3632         return 0;
3633 }
3634
3635 /*
3636  * Kill the current root node, and replace it with it's only child node.
3637  */
3638 STATIC int
3639 xfs_btree_kill_root(
3640         struct xfs_btree_cur    *cur,
3641         struct xfs_buf          *bp,
3642         int                     level,
3643         union xfs_btree_ptr     *newroot)
3644 {
3645         int                     error;
3646
3647         XFS_BTREE_TRACE_CURSOR(cur, XBT_ENTRY);
3648         XFS_BTREE_STATS_INC(cur, killroot);
3649
3650         /*
3651          * Update the root pointer, decreasing the level by 1 and then
3652          * free the old root.
3653          */
3654         cur->bc_ops->set_root(cur, newroot, -1);
3655
3656         error = xfs_btree_free_block(cur, bp);
3657         if (error) {
3658                 XFS_BTREE_TRACE_CURSOR(cur, XBT_ERROR);
3659                 return error;
3660         }
3661
3662         cur->bc_bufs[level] = NULL;
3663         cur->bc_ra[level] = 0;
3664         cur->bc_nlevels--;
3665
3666         XFS_BTREE_TRACE_CURSOR(cur, XBT_EXIT);
3667         return 0;
3668 }
3669
3670 STATIC int
3671 xfs_btree_dec_cursor(
3672         struct xfs_btree_cur    *cur,
3673         int                     level,
3674         int                     *stat)
3675 {
3676         int                     error;
3677         int                     i;
3678
3679         if (level > 0) {
3680                 error = xfs_btree_decrement(cur, level, &i);
3681                 if (error)
3682                         return error;
3683         }
3684
3685         XFS_BTREE_TRACE_CURSOR(cur, XBT_EXIT);
3686         *stat = 1;
3687         return 0;
3688 }
3689
3690 /*
3691  * Single level of the btree record deletion routine.
3692  * Delete record pointed to by cur/level.
3693  * Remove the record from its block then rebalance the tree.
3694  * Return 0 for error, 1 for done, 2 to go on to the next level.
3695  */
3696 STATIC int                                      /* error */
3697 xfs_btree_delrec(
3698         struct xfs_btree_cur    *cur,           /* btree cursor */
3699         int                     level,          /* level removing record from */
3700         int                     *stat)          /* fail/done/go-on */
3701 {
3702         struct xfs_btree_block  *block;         /* btree block */
3703         union xfs_btree_ptr     cptr;           /* current block ptr */
3704         struct xfs_buf          *bp;            /* buffer for block */
3705         int                     error;          /* error return value */
3706         int                     i;              /* loop counter */
3707         union xfs_btree_ptr     lptr;           /* left sibling block ptr */
3708         struct xfs_buf          *lbp;           /* left buffer pointer */
3709         struct xfs_btree_block  *left;          /* left btree block */
3710         int                     lrecs = 0;      /* left record count */
3711         int                     ptr;            /* key/record index */
3712         union xfs_btree_ptr     rptr;           /* right sibling block ptr */
3713         struct xfs_buf          *rbp;           /* right buffer pointer */
3714         struct xfs_btree_block  *right;         /* right btree block */
3715         struct xfs_btree_block  *rrblock;       /* right-right btree block */
3716         struct xfs_buf          *rrbp;          /* right-right buffer pointer */
3717         int                     rrecs = 0;      /* right record count */
3718         struct xfs_btree_cur    *tcur;          /* temporary btree cursor */
3719         int                     numrecs;        /* temporary numrec count */
3720
3721         XFS_BTREE_TRACE_CURSOR(cur, XBT_ENTRY);
3722         XFS_BTREE_TRACE_ARGI(cur, level);
3723
3724         tcur = NULL;
3725
3726         /* Get the index of the entry being deleted, check for nothing there. */
3727         ptr = cur->bc_ptrs[level];
3728         if (ptr == 0) {
3729                 XFS_BTREE_TRACE_CURSOR(cur, XBT_EXIT);
3730                 *stat = 0;
3731                 return 0;
3732         }
3733
3734         /* Get the buffer & block containing the record or key/ptr. */
3735         block = xfs_btree_get_block(cur, level, &bp);
3736         numrecs = xfs_btree_get_numrecs(block);
3737
3738 #ifdef DEBUG
3739         error = xfs_btree_check_block(cur, block, level, bp);
3740         if (error)
3741                 goto error0;
3742 #endif
3743
3744         /* Fail if we're off the end of the block. */
3745         if (ptr > numrecs) {
3746                 XFS_BTREE_TRACE_CURSOR(cur, XBT_EXIT);
3747                 *stat = 0;
3748                 return 0;
3749         }
3750
3751         XFS_BTREE_STATS_INC(cur, delrec);
3752         XFS_BTREE_STATS_ADD(cur, moves, numrecs - ptr);
3753
3754         /* Excise the entries being deleted. */
3755         if (level > 0) {
3756                 /* It's a nonleaf. operate on keys and ptrs */
3757                 union xfs_btree_key     *lkp;
3758                 union xfs_btree_ptr     *lpp;
3759
3760                 lkp = xfs_btree_key_addr(cur, ptr + 1, block);
3761                 lpp = xfs_btree_ptr_addr(cur, ptr + 1, block);
3762
3763 #ifdef DEBUG
3764                 for (i = 0; i < numrecs - ptr; i++) {
3765                         error = xfs_btree_check_ptr(cur, lpp, i, level);
3766                         if (error)
3767                                 goto error0;
3768                 }
3769 #endif
3770
3771                 if (ptr < numrecs) {
3772                         xfs_btree_shift_keys(cur, lkp, -1, numrecs - ptr);
3773                         xfs_btree_shift_ptrs(cur, lpp, -1, numrecs - ptr);
3774                         xfs_btree_log_keys(cur, bp, ptr, numrecs - 1);
3775                         xfs_btree_log_ptrs(cur, bp, ptr, numrecs - 1);
3776                 }
3777         } else {
3778                 /* It's a leaf. operate on records */
3779                 if (ptr < numrecs) {
3780                         xfs_btree_shift_recs(cur,
3781                                 xfs_btree_rec_addr(cur, ptr + 1, block),
3782                                 -1, numrecs - ptr);
3783                         xfs_btree_log_recs(cur, bp, ptr, numrecs - 1);
3784                 }
3785         }
3786
3787         /*
3788          * Decrement and log the number of entries in the block.
3789          */
3790         xfs_btree_set_numrecs(block, --numrecs);
3791         xfs_btree_log_block(cur, bp, XFS_BB_NUMRECS);
3792
3793         /*
3794          * If we are tracking the last record in the tree and
3795          * we are at the far right edge of the tree, update it.
3796          */
3797         if (xfs_btree_is_lastrec(cur, block, level)) {
3798                 cur->bc_ops->update_lastrec(cur, block, NULL,
3799                                             ptr, LASTREC_DELREC);
3800         }
3801
3802         /*
3803          * We're at the root level.  First, shrink the root block in-memory.
3804          * Try to get rid of the next level down.  If we can't then there's
3805          * nothing left to do.
3806          */
3807         if (level == cur->bc_nlevels - 1) {
3808                 if (cur->bc_flags & XFS_BTREE_ROOT_IN_INODE) {
3809                         xfs_iroot_realloc(cur->bc_private.b.ip, -1,
3810                                           cur->bc_private.b.whichfork);
3811
3812                         error = xfs_btree_kill_iroot(cur);
3813                         if (error)
3814                                 goto error0;
3815
3816                         error = xfs_btree_dec_cursor(cur, level, stat);
3817                         if (error)
3818                                 goto error0;
3819                         *stat = 1;
3820                         return 0;
3821                 }
3822
3823                 /*
3824                  * If this is the root level, and there's only one entry left,
3825                  * and it's NOT the leaf level, then we can get rid of this
3826                  * level.
3827                  */
3828                 if (numrecs == 1 && level > 0) {
3829                         union xfs_btree_ptr     *pp;
3830                         /*
3831                          * pp is still set to the first pointer in the block.
3832                          * Make it the new root of the btree.
3833                          */
3834                         pp = xfs_btree_ptr_addr(cur, 1, block);
3835                         error = xfs_btree_kill_root(cur, bp, level, pp);
3836                         if (error)
3837                                 goto error0;
3838                 } else if (level > 0) {
3839                         error = xfs_btree_dec_cursor(cur, level, stat);
3840                         if (error)
3841                                 goto error0;
3842                 }
3843                 *stat = 1;
3844                 return 0;
3845         }
3846
3847         /*
3848          * If we deleted the leftmost entry in the block, update the
3849          * key values above us in the tree.
3850          */
3851         if (xfs_btree_needs_key_update(cur, ptr)) {
3852                 error = xfs_btree_update_keys(cur, level);
3853                 if (error)
3854                         goto error0;
3855         }
3856
3857         /*
3858          * If the number of records remaining in the block is at least
3859          * the minimum, we're done.
3860          */
3861         if (numrecs >= cur->bc_ops->get_minrecs(cur, level)) {
3862                 error = xfs_btree_dec_cursor(cur, level, stat);
3863                 if (error)
3864                         goto error0;
3865                 return 0;
3866         }
3867
3868         /*
3869          * Otherwise, we have to move some records around to keep the
3870          * tree balanced.  Look at the left and right sibling blocks to
3871          * see if we can re-balance by moving only one record.
3872          */
3873         xfs_btree_get_sibling(cur, block, &rptr, XFS_BB_RIGHTSIB);
3874         xfs_btree_get_sibling(cur, block, &lptr, XFS_BB_LEFTSIB);
3875
3876         if (cur->bc_flags & XFS_BTREE_ROOT_IN_INODE) {
3877                 /*
3878                  * One child of root, need to get a chance to copy its contents
3879                  * into the root and delete it. Can't go up to next level,
3880                  * there's nothing to delete there.
3881                  */
3882                 if (xfs_btree_ptr_is_null(cur, &rptr) &&
3883                     xfs_btree_ptr_is_null(cur, &lptr) &&
3884                     level == cur->bc_nlevels - 2) {
3885                         error = xfs_btree_kill_iroot(cur);
3886                         if (!error)
3887                                 error = xfs_btree_dec_cursor(cur, level, stat);
3888                         if (error)
3889                                 goto error0;
3890                         return 0;
3891                 }
3892         }
3893
3894         ASSERT(!xfs_btree_ptr_is_null(cur, &rptr) ||
3895                !xfs_btree_ptr_is_null(cur, &lptr));
3896
3897         /*
3898          * Duplicate the cursor so our btree manipulations here won't
3899          * disrupt the next level up.
3900          */
3901         error = xfs_btree_dup_cursor(cur, &tcur);
3902         if (error)
3903                 goto error0;
3904
3905         /*
3906          * If there's a right sibling, see if it's ok to shift an entry
3907          * out of it.
3908          */
3909         if (!xfs_btree_ptr_is_null(cur, &rptr)) {
3910                 /*
3911                  * Move the temp cursor to the last entry in the next block.
3912                  * Actually any entry but the first would suffice.
3913                  */
3914                 i = xfs_btree_lastrec(tcur, level);
3915                 XFS_WANT_CORRUPTED_GOTO(cur->bc_mp, i == 1, error0);
3916
3917                 error = xfs_btree_increment(tcur, level, &i);
3918                 if (error)
3919                         goto error0;
3920                 XFS_WANT_CORRUPTED_GOTO(cur->bc_mp, i == 1, error0);
3921
3922                 i = xfs_btree_lastrec(tcur, level);
3923                 XFS_WANT_CORRUPTED_GOTO(cur->bc_mp, i == 1, error0);
3924
3925                 /* Grab a pointer to the block. */
3926                 right = xfs_btree_get_block(tcur, level, &rbp);
3927 #ifdef DEBUG
3928                 error = xfs_btree_check_block(tcur, right, level, rbp);
3929                 if (error)
3930                         goto error0;
3931 #endif
3932                 /* Grab the current block number, for future use. */
3933                 xfs_btree_get_sibling(tcur, right, &cptr, XFS_BB_LEFTSIB);
3934
3935                 /*
3936                  * If right block is full enough so that removing one entry
3937                  * won't make it too empty, and left-shifting an entry out
3938                  * of right to us works, we're done.
3939                  */
3940                 if (xfs_btree_get_numrecs(right) - 1 >=
3941                     cur->bc_ops->get_minrecs(tcur, level)) {
3942                         error = xfs_btree_lshift(tcur, level, &i);
3943                         if (error)
3944                                 goto error0;
3945                         if (i) {
3946                                 ASSERT(xfs_btree_get_numrecs(block) >=
3947                                        cur->bc_ops->get_minrecs(tcur, level));
3948
3949                                 xfs_btree_del_cursor(tcur, XFS_BTREE_NOERROR);
3950                                 tcur = NULL;
3951
3952                                 error = xfs_btree_dec_cursor(cur, level, stat);
3953                                 if (error)
3954                                         goto error0;
3955                                 return 0;
3956                         }
3957                 }
3958
3959                 /*
3960                  * Otherwise, grab the number of records in right for
3961                  * future reference, and fix up the temp cursor to point
3962                  * to our block again (last record).
3963                  */
3964                 rrecs = xfs_btree_get_numrecs(right);
3965                 if (!xfs_btree_ptr_is_null(cur, &lptr)) {
3966                         i = xfs_btree_firstrec(tcur, level);
3967                         XFS_WANT_CORRUPTED_GOTO(cur->bc_mp, i == 1, error0);
3968
3969                         error = xfs_btree_decrement(tcur, level, &i);
3970                         if (error)
3971                                 goto error0;
3972                         XFS_WANT_CORRUPTED_GOTO(cur->bc_mp, i == 1, error0);
3973                 }
3974         }
3975
3976         /*
3977          * If there's a left sibling, see if it's ok to shift an entry
3978          * out of it.
3979          */
3980         if (!xfs_btree_ptr_is_null(cur, &lptr)) {
3981                 /*
3982                  * Move the temp cursor to the first entry in the
3983                  * previous block.
3984                  */
3985                 i = xfs_btree_firstrec(tcur, level);
3986                 XFS_WANT_CORRUPTED_GOTO(cur->bc_mp, i == 1, error0);
3987
3988                 error = xfs_btree_decrement(tcur, level, &i);
3989                 if (error)
3990                         goto error0;
3991                 i = xfs_btree_firstrec(tcur, level);
3992                 XFS_WANT_CORRUPTED_GOTO(cur->bc_mp, i == 1, error0);
3993
3994                 /* Grab a pointer to the block. */
3995                 left = xfs_btree_get_block(tcur, level, &lbp);
3996 #ifdef DEBUG
3997                 error = xfs_btree_check_block(cur, left, level, lbp);
3998                 if (error)
3999                         goto error0;
4000 #endif
4001                 /* Grab the current block number, for future use. */
4002                 xfs_btree_get_sibling(tcur, left, &cptr, XFS_BB_RIGHTSIB);
4003
4004                 /*
4005                  * If left block is full enough so that removing one entry
4006                  * won't make it too empty, and right-shifting an entry out
4007                  * of left to us works, we're done.
4008                  */
4009                 if (xfs_btree_get_numrecs(left) - 1 >=
4010                     cur->bc_ops->get_minrecs(tcur, level)) {
4011                         error = xfs_btree_rshift(tcur, level, &i);
4012                         if (error)
4013                                 goto error0;
4014                         if (i) {
4015                                 ASSERT(xfs_btree_get_numrecs(block) >=
4016                                        cur->bc_ops->get_minrecs(tcur, level));
4017                                 xfs_btree_del_cursor(tcur, XFS_BTREE_NOERROR);
4018                                 tcur = NULL;
4019                                 if (level == 0)
4020                                         cur->bc_ptrs[0]++;
4021                                 XFS_BTREE_TRACE_CURSOR(cur, XBT_EXIT);
4022                                 *stat = 1;
4023                                 return 0;
4024                         }
4025                 }
4026
4027                 /*
4028                  * Otherwise, grab the number of records in right for
4029                  * future reference.
4030                  */
4031                 lrecs = xfs_btree_get_numrecs(left);
4032         }
4033
4034         /* Delete the temp cursor, we're done with it. */
4035         xfs_btree_del_cursor(tcur, XFS_BTREE_NOERROR);
4036         tcur = NULL;
4037
4038         /* If here, we need to do a join to keep the tree balanced. */
4039         ASSERT(!xfs_btree_ptr_is_null(cur, &cptr));
4040
4041         if (!xfs_btree_ptr_is_null(cur, &lptr) &&
4042             lrecs + xfs_btree_get_numrecs(block) <=
4043                         cur->bc_ops->get_maxrecs(cur, level)) {
4044                 /*
4045                  * Set "right" to be the starting block,
4046                  * "left" to be the left neighbor.
4047                  */
4048                 rptr = cptr;
4049                 right = block;
4050                 rbp = bp;
4051                 error = xfs_btree_read_buf_block(cur, &lptr, 0, &left, &lbp);
4052                 if (error)
4053                         goto error0;
4054
4055         /*
4056          * If that won't work, see if we can join with the right neighbor block.
4057          */
4058         } else if (!xfs_btree_ptr_is_null(cur, &rptr) &&
4059                    rrecs + xfs_btree_get_numrecs(block) <=
4060                         cur->bc_ops->get_maxrecs(cur, level)) {
4061                 /*
4062                  * Set "left" to be the starting block,
4063                  * "right" to be the right neighbor.
4064                  */
4065                 lptr = cptr;
4066                 left = block;
4067                 lbp = bp;
4068                 error = xfs_btree_read_buf_block(cur, &rptr, 0, &right, &rbp);
4069                 if (error)
4070                         goto error0;
4071
4072         /*
4073          * Otherwise, we can't fix the imbalance.
4074          * Just return.  This is probably a logic error, but it's not fatal.
4075          */
4076         } else {
4077                 error = xfs_btree_dec_cursor(cur, level, stat);
4078                 if (error)
4079                         goto error0;
4080                 return 0;
4081         }
4082
4083         rrecs = xfs_btree_get_numrecs(right);
4084         lrecs = xfs_btree_get_numrecs(left);
4085
4086         /*
4087          * We're now going to join "left" and "right" by moving all the stuff
4088          * in "right" to "left" and deleting "right".
4089          */
4090         XFS_BTREE_STATS_ADD(cur, moves, rrecs);
4091         if (level > 0) {
4092                 /* It's a non-leaf.  Move keys and pointers. */
4093                 union xfs_btree_key     *lkp;   /* left btree key */
4094                 union xfs_btree_ptr     *lpp;   /* left address pointer */
4095                 union xfs_btree_key     *rkp;   /* right btree key */
4096                 union xfs_btree_ptr     *rpp;   /* right address pointer */
4097
4098                 lkp = xfs_btree_key_addr(cur, lrecs + 1, left);
4099                 lpp = xfs_btree_ptr_addr(cur, lrecs + 1, left);
4100                 rkp = xfs_btree_key_addr(cur, 1, right);
4101                 rpp = xfs_btree_ptr_addr(cur, 1, right);
4102 #ifdef DEBUG
4103                 for (i = 1; i < rrecs; i++) {
4104                         error = xfs_btree_check_ptr(cur, rpp, i, level);
4105                         if (error)
4106                                 goto error0;
4107                 }
4108 #endif
4109                 xfs_btree_copy_keys(cur, lkp, rkp, rrecs);
4110                 xfs_btree_copy_ptrs(cur, lpp, rpp, rrecs);
4111
4112                 xfs_btree_log_keys(cur, lbp, lrecs + 1, lrecs + rrecs);
4113                 xfs_btree_log_ptrs(cur, lbp, lrecs + 1, lrecs + rrecs);
4114         } else {
4115                 /* It's a leaf.  Move records.  */
4116                 union xfs_btree_rec     *lrp;   /* left record pointer */
4117                 union xfs_btree_rec     *rrp;   /* right record pointer */
4118
4119                 lrp = xfs_btree_rec_addr(cur, lrecs + 1, left);
4120                 rrp = xfs_btree_rec_addr(cur, 1, right);
4121
4122                 xfs_btree_copy_recs(cur, lrp, rrp, rrecs);
4123                 xfs_btree_log_recs(cur, lbp, lrecs + 1, lrecs + rrecs);
4124         }
4125
4126         XFS_BTREE_STATS_INC(cur, join);
4127
4128         /*
4129          * Fix up the number of records and right block pointer in the
4130          * surviving block, and log it.
4131          */
4132         xfs_btree_set_numrecs(left, lrecs + rrecs);
4133         xfs_btree_get_sibling(cur, right, &cptr, XFS_BB_RIGHTSIB),
4134         xfs_btree_set_sibling(cur, left, &cptr, XFS_BB_RIGHTSIB);
4135         xfs_btree_log_block(cur, lbp, XFS_BB_NUMRECS | XFS_BB_RIGHTSIB);
4136
4137         /* If there is a right sibling, point it to the remaining block. */
4138         xfs_btree_get_sibling(cur, left, &cptr, XFS_BB_RIGHTSIB);
4139         if (!xfs_btree_ptr_is_null(cur, &cptr)) {
4140                 error = xfs_btree_read_buf_block(cur, &cptr, 0, &rrblock, &rrbp);
4141                 if (error)
4142                         goto error0;
4143                 xfs_btree_set_sibling(cur, rrblock, &lptr, XFS_BB_LEFTSIB);
4144                 xfs_btree_log_block(cur, rrbp, XFS_BB_LEFTSIB);
4145         }
4146
4147         /* Free the deleted block. */
4148         error = xfs_btree_free_block(cur, rbp);
4149         if (error)
4150                 goto error0;
4151
4152         /*
4153          * If we joined with the left neighbor, set the buffer in the
4154          * cursor to the left block, and fix up the index.
4155          */
4156         if (bp != lbp) {
4157                 cur->bc_bufs[level] = lbp;
4158                 cur->bc_ptrs[level] += lrecs;
4159                 cur->bc_ra[level] = 0;
4160         }
4161         /*
4162          * If we joined with the right neighbor and there's a level above
4163          * us, increment the cursor at that level.
4164          */
4165         else if ((cur->bc_flags & XFS_BTREE_ROOT_IN_INODE) ||
4166                    (level + 1 < cur->bc_nlevels)) {
4167                 error = xfs_btree_increment(cur, level + 1, &i);
4168                 if (error)
4169                         goto error0;
4170         }
4171
4172         /*
4173          * Readjust the ptr at this level if it's not a leaf, since it's
4174          * still pointing at the deletion point, which makes the cursor
4175          * inconsistent.  If this makes the ptr 0, the caller fixes it up.
4176          * We can't use decrement because it would change the next level up.
4177          */
4178         if (level > 0)
4179                 cur->bc_ptrs[level]--;
4180
4181         /*
4182          * We combined blocks, so we have to update the parent keys if the
4183          * btree supports overlapped intervals.  However, bc_ptrs[level + 1]
4184          * points to the old block so that the caller knows which record to
4185          * delete.  Therefore, the caller must be savvy enough to call updkeys
4186          * for us if we return stat == 2.  The other exit points from this
4187          * function don't require deletions further up the tree, so they can
4188          * call updkeys directly.
4189          */
4190
4191         XFS_BTREE_TRACE_CURSOR(cur, XBT_EXIT);
4192         /* Return value means the next level up has something to do. */
4193         *stat = 2;
4194         return 0;
4195
4196 error0:
4197         XFS_BTREE_TRACE_CURSOR(cur, XBT_ERROR);
4198         if (tcur)
4199                 xfs_btree_del_cursor(tcur, XFS_BTREE_ERROR);
4200         return error;
4201 }
4202
4203 /*
4204  * Delete the record pointed to by cur.
4205  * The cursor refers to the place where the record was (could be inserted)
4206  * when the operation returns.
4207  */
4208 int                                     /* error */
4209 xfs_btree_delete(
4210         struct xfs_btree_cur    *cur,
4211         int                     *stat)  /* success/failure */
4212 {
4213         int                     error;  /* error return value */
4214         int                     level;
4215         int                     i;
4216         bool                    joined = false;
4217
4218         XFS_BTREE_TRACE_CURSOR(cur, XBT_ENTRY);
4219
4220         /*
4221          * Go up the tree, starting at leaf level.
4222          *
4223          * If 2 is returned then a join was done; go to the next level.
4224          * Otherwise we are done.
4225          */
4226         for (level = 0, i = 2; i == 2; level++) {
4227                 error = xfs_btree_delrec(cur, level, &i);
4228                 if (error)
4229                         goto error0;
4230                 if (i == 2)
4231                         joined = true;
4232         }
4233
4234         /*
4235          * If we combined blocks as part of deleting the record, delrec won't
4236          * have updated the parent high keys so we have to do that here.
4237          */
4238         if (joined && (cur->bc_flags & XFS_BTREE_OVERLAPPING)) {
4239                 error = xfs_btree_updkeys_force(cur, 0);
4240                 if (error)
4241                         goto error0;
4242         }
4243
4244         if (i == 0) {
4245                 for (level = 1; level < cur->bc_nlevels; level++) {
4246                         if (cur->bc_ptrs[level] == 0) {
4247                                 error = xfs_btree_decrement(cur, level, &i);
4248                                 if (error)
4249                                         goto error0;
4250                                 break;
4251                         }
4252                 }
4253         }
4254
4255         XFS_BTREE_TRACE_CURSOR(cur, XBT_EXIT);
4256         *stat = i;
4257         return 0;
4258 error0:
4259         XFS_BTREE_TRACE_CURSOR(cur, XBT_ERROR);
4260         return error;
4261 }
4262
4263 /*
4264  * Get the data from the pointed-to record.
4265  */
4266 int                                     /* error */
4267 xfs_btree_get_rec(
4268         struct xfs_btree_cur    *cur,   /* btree cursor */
4269         union xfs_btree_rec     **recp, /* output: btree record */
4270         int                     *stat)  /* output: success/failure */
4271 {
4272         struct xfs_btree_block  *block; /* btree block */
4273         struct xfs_buf          *bp;    /* buffer pointer */
4274         int                     ptr;    /* record number */
4275 #ifdef DEBUG
4276         int                     error;  /* error return value */
4277 #endif
4278
4279         ptr = cur->bc_ptrs[0];
4280         block = xfs_btree_get_block(cur, 0, &bp);
4281
4282 #ifdef DEBUG
4283         error = xfs_btree_check_block(cur, block, 0, bp);
4284         if (error)
4285                 return error;
4286 #endif
4287
4288         /*
4289          * Off the right end or left end, return failure.
4290          */
4291         if (ptr > xfs_btree_get_numrecs(block) || ptr <= 0) {
4292                 *stat = 0;
4293                 return 0;
4294         }
4295
4296         /*
4297          * Point to the record and extract its data.
4298          */
4299         *recp = xfs_btree_rec_addr(cur, ptr, block);
4300         *stat = 1;
4301         return 0;
4302 }
4303
4304 /* Visit a block in a btree. */
4305 STATIC int
4306 xfs_btree_visit_block(
4307         struct xfs_btree_cur            *cur,
4308         int                             level,
4309         xfs_btree_visit_blocks_fn       fn,
4310         void                            *data)
4311 {
4312         struct xfs_btree_block          *block;
4313         struct xfs_buf                  *bp;
4314         union xfs_btree_ptr             rptr;
4315         int                             error;
4316
4317         /* do right sibling readahead */
4318         xfs_btree_readahead(cur, level, XFS_BTCUR_RIGHTRA);
4319         block = xfs_btree_get_block(cur, level, &bp);
4320
4321         /* process the block */
4322         error = fn(cur, level, data);
4323         if (error)
4324                 return error;
4325
4326         /* now read rh sibling block for next iteration */
4327         xfs_btree_get_sibling(cur, block, &rptr, XFS_BB_RIGHTSIB);
4328         if (xfs_btree_ptr_is_null(cur, &rptr))
4329                 return -ENOENT;
4330
4331         return xfs_btree_lookup_get_block(cur, level, &rptr, &block);
4332 }
4333
4334
4335 /* Visit every block in a btree. */
4336 int
4337 xfs_btree_visit_blocks(
4338         struct xfs_btree_cur            *cur,
4339         xfs_btree_visit_blocks_fn       fn,
4340         void                            *data)
4341 {
4342         union xfs_btree_ptr             lptr;
4343         int                             level;
4344         struct xfs_btree_block          *block = NULL;
4345         int                             error = 0;
4346
4347         cur->bc_ops->init_ptr_from_cur(cur, &lptr);
4348
4349         /* for each level */
4350         for (level = cur->bc_nlevels - 1; level >= 0; level--) {
4351                 /* grab the left hand block */
4352                 error = xfs_btree_lookup_get_block(cur, level, &lptr, &block);
4353                 if (error)
4354                         return error;
4355
4356                 /* readahead the left most block for the next level down */
4357                 if (level > 0) {
4358                         union xfs_btree_ptr     *ptr;
4359
4360                         ptr = xfs_btree_ptr_addr(cur, 1, block);
4361                         xfs_btree_readahead_ptr(cur, ptr, 1);
4362
4363                         /* save for the next iteration of the loop */
4364                         lptr = *ptr;
4365                 }
4366
4367                 /* for each buffer in the level */
4368                 do {
4369                         error = xfs_btree_visit_block(cur, level, fn, data);
4370                 } while (!error);
4371
4372                 if (error != -ENOENT)
4373                         return error;
4374         }
4375
4376         return 0;
4377 }
4378
4379 /*
4380  * Change the owner of a btree.
4381  *
4382  * The mechanism we use here is ordered buffer logging. Because we don't know
4383  * how many buffers were are going to need to modify, we don't really want to
4384  * have to make transaction reservations for the worst case of every buffer in a
4385  * full size btree as that may be more space that we can fit in the log....
4386  *
4387  * We do the btree walk in the most optimal manner possible - we have sibling
4388  * pointers so we can just walk all the blocks on each level from left to right
4389  * in a single pass, and then move to the next level and do the same. We can
4390  * also do readahead on the sibling pointers to get IO moving more quickly,
4391  * though for slow disks this is unlikely to make much difference to performance
4392  * as the amount of CPU work we have to do before moving to the next block is
4393  * relatively small.
4394  *
4395  * For each btree block that we load, modify the owner appropriately, set the
4396  * buffer as an ordered buffer and log it appropriately. We need to ensure that
4397  * we mark the region we change dirty so that if the buffer is relogged in
4398  * a subsequent transaction the changes we make here as an ordered buffer are
4399  * correctly relogged in that transaction.  If we are in recovery context, then
4400  * just queue the modified buffer as delayed write buffer so the transaction
4401  * recovery completion writes the changes to disk.
4402  */
4403 struct xfs_btree_block_change_owner_info {
4404         __uint64_t              new_owner;
4405         struct list_head        *buffer_list;
4406 };
4407
4408 static int
4409 xfs_btree_block_change_owner(
4410         struct xfs_btree_cur    *cur,
4411         int                     level,
4412         void                    *data)
4413 {
4414         struct xfs_btree_block_change_owner_info        *bbcoi = data;
4415         struct xfs_btree_block  *block;
4416         struct xfs_buf          *bp;
4417
4418         /* modify the owner */
4419         block = xfs_btree_get_block(cur, level, &bp);
4420         if (cur->bc_flags & XFS_BTREE_LONG_PTRS)
4421                 block->bb_u.l.bb_owner = cpu_to_be64(bbcoi->new_owner);
4422         else
4423                 block->bb_u.s.bb_owner = cpu_to_be32(bbcoi->new_owner);
4424
4425         /*
4426          * If the block is a root block hosted in an inode, we might not have a
4427          * buffer pointer here and we shouldn't attempt to log the change as the
4428          * information is already held in the inode and discarded when the root
4429          * block is formatted into the on-disk inode fork. We still change it,
4430          * though, so everything is consistent in memory.
4431          */
4432         if (bp) {
4433                 if (cur->bc_tp) {
4434                         xfs_trans_ordered_buf(cur->bc_tp, bp);
4435                         xfs_btree_log_block(cur, bp, XFS_BB_OWNER);
4436                 } else {
4437                         xfs_buf_delwri_queue(bp, bbcoi->buffer_list);
4438                 }
4439         } else {
4440                 ASSERT(cur->bc_flags & XFS_BTREE_ROOT_IN_INODE);
4441                 ASSERT(level == cur->bc_nlevels - 1);
4442         }
4443
4444         return 0;
4445 }
4446
4447 int
4448 xfs_btree_change_owner(
4449         struct xfs_btree_cur    *cur,
4450         __uint64_t              new_owner,
4451         struct list_head        *buffer_list)
4452 {
4453         struct xfs_btree_block_change_owner_info        bbcoi;
4454
4455         bbcoi.new_owner = new_owner;
4456         bbcoi.buffer_list = buffer_list;
4457
4458         return xfs_btree_visit_blocks(cur, xfs_btree_block_change_owner,
4459                         &bbcoi);
4460 }
4461
4462 /**
4463  * xfs_btree_sblock_v5hdr_verify() -- verify the v5 fields of a short-format
4464  *                                    btree block
4465  *
4466  * @bp: buffer containing the btree block
4467  * @max_recs: pointer to the m_*_mxr max records field in the xfs mount
4468  * @pag_max_level: pointer to the per-ag max level field
4469  */
4470 bool
4471 xfs_btree_sblock_v5hdr_verify(
4472         struct xfs_buf          *bp)
4473 {
4474         struct xfs_mount        *mp = bp->b_target->bt_mount;
4475         struct xfs_btree_block  *block = XFS_BUF_TO_BLOCK(bp);
4476         struct xfs_perag        *pag = bp->b_pag;
4477
4478         if (!xfs_sb_version_hascrc(&mp->m_sb))
4479                 return false;
4480         if (!uuid_equal(&block->bb_u.s.bb_uuid, &mp->m_sb.sb_meta_uuid))
4481                 return false;
4482         if (block->bb_u.s.bb_blkno != cpu_to_be64(bp->b_bn))
4483                 return false;
4484         if (pag && be32_to_cpu(block->bb_u.s.bb_owner) != pag->pag_agno)
4485                 return false;
4486         return true;
4487 }
4488
4489 /**
4490  * xfs_btree_sblock_verify() -- verify a short-format btree block
4491  *
4492  * @bp: buffer containing the btree block
4493  * @max_recs: maximum records allowed in this btree node
4494  */
4495 bool
4496 xfs_btree_sblock_verify(
4497         struct xfs_buf          *bp,
4498         unsigned int            max_recs)
4499 {
4500         struct xfs_mount        *mp = bp->b_target->bt_mount;
4501         struct xfs_btree_block  *block = XFS_BUF_TO_BLOCK(bp);
4502
4503         /* numrecs verification */
4504         if (be16_to_cpu(block->bb_numrecs) > max_recs)
4505                 return false;
4506
4507         /* sibling pointer verification */
4508         if (!block->bb_u.s.bb_leftsib ||
4509             (be32_to_cpu(block->bb_u.s.bb_leftsib) >= mp->m_sb.sb_agblocks &&
4510              block->bb_u.s.bb_leftsib != cpu_to_be32(NULLAGBLOCK)))
4511                 return false;
4512         if (!block->bb_u.s.bb_rightsib ||
4513             (be32_to_cpu(block->bb_u.s.bb_rightsib) >= mp->m_sb.sb_agblocks &&
4514              block->bb_u.s.bb_rightsib != cpu_to_be32(NULLAGBLOCK)))
4515                 return false;
4516
4517         return true;
4518 }
4519
4520 /*
4521  * Calculate the number of btree levels needed to store a given number of
4522  * records in a short-format btree.
4523  */
4524 uint
4525 xfs_btree_compute_maxlevels(
4526         struct xfs_mount        *mp,
4527         uint                    *limits,
4528         unsigned long           len)
4529 {
4530         uint                    level;
4531         unsigned long           maxblocks;
4532
4533         maxblocks = (len + limits[0] - 1) / limits[0];
4534         for (level = 1; maxblocks > 1; level++)
4535                 maxblocks = (maxblocks + limits[1] - 1) / limits[1];
4536         return level;
4537 }
4538
4539 /*
4540  * Query a regular btree for all records overlapping a given interval.
4541  * Start with a LE lookup of the key of low_rec and return all records
4542  * until we find a record with a key greater than the key of high_rec.
4543  */
4544 STATIC int
4545 xfs_btree_simple_query_range(
4546         struct xfs_btree_cur            *cur,
4547         union xfs_btree_key             *low_key,
4548         union xfs_btree_key             *high_key,
4549         xfs_btree_query_range_fn        fn,
4550         void                            *priv)
4551 {
4552         union xfs_btree_rec             *recp;
4553         union xfs_btree_key             rec_key;
4554         __int64_t                       diff;
4555         int                             stat;
4556         bool                            firstrec = true;
4557         int                             error;
4558
4559         ASSERT(cur->bc_ops->init_high_key_from_rec);
4560         ASSERT(cur->bc_ops->diff_two_keys);
4561
4562         /*
4563          * Find the leftmost record.  The btree cursor must be set
4564          * to the low record used to generate low_key.
4565          */
4566         stat = 0;
4567         error = xfs_btree_lookup(cur, XFS_LOOKUP_LE, &stat);
4568         if (error)
4569                 goto out;
4570
4571         while (stat) {
4572                 /* Find the record. */
4573                 error = xfs_btree_get_rec(cur, &recp, &stat);
4574                 if (error || !stat)
4575                         break;
4576                 cur->bc_ops->init_high_key_from_rec(&rec_key, recp);
4577
4578                 /* Skip if high_key(rec) < low_key. */
4579                 if (firstrec) {
4580                         firstrec = false;
4581                         diff = cur->bc_ops->diff_two_keys(cur, low_key,
4582                                         &rec_key);
4583                         if (diff > 0)
4584                                 goto advloop;
4585                 }
4586
4587                 /* Stop if high_key < low_key(rec). */
4588                 diff = cur->bc_ops->diff_two_keys(cur, &rec_key, high_key);
4589                 if (diff > 0)
4590                         break;
4591
4592                 /* Callback */
4593                 error = fn(cur, recp, priv);
4594                 if (error < 0 || error == XFS_BTREE_QUERY_RANGE_ABORT)
4595                         break;
4596
4597 advloop:
4598                 /* Move on to the next record. */
4599                 error = xfs_btree_increment(cur, 0, &stat);
4600                 if (error)
4601                         break;
4602         }
4603
4604 out:
4605         return error;
4606 }
4607
4608 /*
4609  * Query an overlapped interval btree for all records overlapping a given
4610  * interval.  This function roughly follows the algorithm given in
4611  * "Interval Trees" of _Introduction to Algorithms_, which is section
4612  * 14.3 in the 2nd and 3rd editions.
4613  *
4614  * First, generate keys for the low and high records passed in.
4615  *
4616  * For any leaf node, generate the high and low keys for the record.
4617  * If the record keys overlap with the query low/high keys, pass the
4618  * record to the function iterator.
4619  *
4620  * For any internal node, compare the low and high keys of each
4621  * pointer against the query low/high keys.  If there's an overlap,
4622  * follow the pointer.
4623  *
4624  * As an optimization, we stop scanning a block when we find a low key
4625  * that is greater than the query's high key.
4626  */
4627 STATIC int
4628 xfs_btree_overlapped_query_range(
4629         struct xfs_btree_cur            *cur,
4630         union xfs_btree_key             *low_key,
4631         union xfs_btree_key             *high_key,
4632         xfs_btree_query_range_fn        fn,
4633         void                            *priv)
4634 {
4635         union xfs_btree_ptr             ptr;
4636         union xfs_btree_ptr             *pp;
4637         union xfs_btree_key             rec_key;
4638         union xfs_btree_key             rec_hkey;
4639         union xfs_btree_key             *lkp;
4640         union xfs_btree_key             *hkp;
4641         union xfs_btree_rec             *recp;
4642         struct xfs_btree_block          *block;
4643         __int64_t                       ldiff;
4644         __int64_t                       hdiff;
4645         int                             level;
4646         struct xfs_buf                  *bp;
4647         int                             i;
4648         int                             error;
4649
4650         /* Load the root of the btree. */
4651         level = cur->bc_nlevels - 1;
4652         cur->bc_ops->init_ptr_from_cur(cur, &ptr);
4653         error = xfs_btree_lookup_get_block(cur, level, &ptr, &block);
4654         if (error)
4655                 return error;
4656         xfs_btree_get_block(cur, level, &bp);
4657         trace_xfs_btree_overlapped_query_range(cur, level, bp);
4658 #ifdef DEBUG
4659         error = xfs_btree_check_block(cur, block, level, bp);
4660         if (error)
4661                 goto out;
4662 #endif
4663         cur->bc_ptrs[level] = 1;
4664
4665         while (level < cur->bc_nlevels) {
4666                 block = xfs_btree_get_block(cur, level, &bp);
4667
4668                 /* End of node, pop back towards the root. */
4669                 if (cur->bc_ptrs[level] > be16_to_cpu(block->bb_numrecs)) {
4670 pop_up:
4671                         if (level < cur->bc_nlevels - 1)
4672                                 cur->bc_ptrs[level + 1]++;
4673                         level++;
4674                         continue;
4675                 }
4676
4677                 if (level == 0) {
4678                         /* Handle a leaf node. */
4679                         recp = xfs_btree_rec_addr(cur, cur->bc_ptrs[0], block);
4680
4681                         cur->bc_ops->init_high_key_from_rec(&rec_hkey, recp);
4682                         ldiff = cur->bc_ops->diff_two_keys(cur, &rec_hkey,
4683                                         low_key);
4684
4685                         cur->bc_ops->init_key_from_rec(&rec_key, recp);
4686                         hdiff = cur->bc_ops->diff_two_keys(cur, high_key,
4687                                         &rec_key);
4688
4689                         /*
4690                          * If (record's high key >= query's low key) and
4691                          *    (query's high key >= record's low key), then
4692                          * this record overlaps the query range; callback.
4693                          */
4694                         if (ldiff >= 0 && hdiff >= 0) {
4695                                 error = fn(cur, recp, priv);
4696                                 if (error < 0 ||
4697                                     error == XFS_BTREE_QUERY_RANGE_ABORT)
4698                                         break;
4699                         } else if (hdiff < 0) {
4700                                 /* Record is larger than high key; pop. */
4701                                 goto pop_up;
4702                         }
4703                         cur->bc_ptrs[level]++;
4704                         continue;
4705                 }
4706
4707                 /* Handle an internal node. */
4708                 lkp = xfs_btree_key_addr(cur, cur->bc_ptrs[level], block);
4709                 hkp = xfs_btree_high_key_addr(cur, cur->bc_ptrs[level], block);
4710                 pp = xfs_btree_ptr_addr(cur, cur->bc_ptrs[level], block);
4711
4712                 ldiff = cur->bc_ops->diff_two_keys(cur, hkp, low_key);
4713                 hdiff = cur->bc_ops->diff_two_keys(cur, high_key, lkp);
4714
4715                 /*
4716                  * If (pointer's high key >= query's low key) and
4717                  *    (query's high key >= pointer's low key), then
4718                  * this record overlaps the query range; follow pointer.
4719                  */
4720                 if (ldiff >= 0 && hdiff >= 0) {
4721                         level--;
4722                         error = xfs_btree_lookup_get_block(cur, level, pp,
4723                                         &block);
4724                         if (error)
4725                                 goto out;
4726                         xfs_btree_get_block(cur, level, &bp);
4727                         trace_xfs_btree_overlapped_query_range(cur, level, bp);
4728 #ifdef DEBUG
4729                         error = xfs_btree_check_block(cur, block, level, bp);
4730                         if (error)
4731                                 goto out;
4732 #endif
4733                         cur->bc_ptrs[level] = 1;
4734                         continue;
4735                 } else if (hdiff < 0) {
4736                         /* The low key is larger than the upper range; pop. */
4737                         goto pop_up;
4738                 }
4739                 cur->bc_ptrs[level]++;
4740         }
4741
4742 out:
4743         /*
4744          * If we don't end this function with the cursor pointing at a record
4745          * block, a subsequent non-error cursor deletion will not release
4746          * node-level buffers, causing a buffer leak.  This is quite possible
4747          * with a zero-results range query, so release the buffers if we
4748          * failed to return any results.
4749          */
4750         if (cur->bc_bufs[0] == NULL) {
4751                 for (i = 0; i < cur->bc_nlevels; i++) {
4752                         if (cur->bc_bufs[i]) {
4753                                 xfs_trans_brelse(cur->bc_tp, cur->bc_bufs[i]);
4754                                 cur->bc_bufs[i] = NULL;
4755                                 cur->bc_ptrs[i] = 0;
4756                                 cur->bc_ra[i] = 0;
4757                         }
4758                 }
4759         }
4760
4761         return error;
4762 }
4763
4764 /*
4765  * Query a btree for all records overlapping a given interval of keys.  The
4766  * supplied function will be called with each record found; return one of the
4767  * XFS_BTREE_QUERY_RANGE_{CONTINUE,ABORT} values or the usual negative error
4768  * code.  This function returns XFS_BTREE_QUERY_RANGE_ABORT, zero, or a
4769  * negative error code.
4770  */
4771 int
4772 xfs_btree_query_range(
4773         struct xfs_btree_cur            *cur,
4774         union xfs_btree_irec            *low_rec,
4775         union xfs_btree_irec            *high_rec,
4776         xfs_btree_query_range_fn        fn,
4777         void                            *priv)
4778 {
4779         union xfs_btree_rec             rec;
4780         union xfs_btree_key             low_key;
4781         union xfs_btree_key             high_key;
4782
4783         /* Find the keys of both ends of the interval. */
4784         cur->bc_rec = *high_rec;
4785         cur->bc_ops->init_rec_from_cur(cur, &rec);
4786         cur->bc_ops->init_key_from_rec(&high_key, &rec);
4787
4788         cur->bc_rec = *low_rec;
4789         cur->bc_ops->init_rec_from_cur(cur, &rec);
4790         cur->bc_ops->init_key_from_rec(&low_key, &rec);
4791
4792         /* Enforce low key < high key. */
4793         if (cur->bc_ops->diff_two_keys(cur, &low_key, &high_key) > 0)
4794                 return -EINVAL;
4795
4796         if (!(cur->bc_flags & XFS_BTREE_OVERLAPPING))
4797                 return xfs_btree_simple_query_range(cur, &low_key,
4798                                 &high_key, fn, priv);
4799         return xfs_btree_overlapped_query_range(cur, &low_key, &high_key,
4800                         fn, priv);
4801 }