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