Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0
0002 /*
0003  * Copyright (c) 2000-2005 Silicon Graphics, Inc.
0004  * Copyright (c) 2013 Red Hat, Inc.
0005  * All Rights Reserved.
0006  */
0007 #include "xfs.h"
0008 #include "xfs_fs.h"
0009 #include "xfs_shared.h"
0010 #include "xfs_format.h"
0011 #include "xfs_log_format.h"
0012 #include "xfs_trans_resv.h"
0013 #include "xfs_mount.h"
0014 #include "xfs_inode.h"
0015 #include "xfs_bmap.h"
0016 #include "xfs_dir2.h"
0017 #include "xfs_dir2_priv.h"
0018 #include "xfs_error.h"
0019 #include "xfs_trace.h"
0020 #include "xfs_trans.h"
0021 #include "xfs_buf_item.h"
0022 #include "xfs_log.h"
0023 
0024 /*
0025  * Function declarations.
0026  */
0027 static int xfs_dir2_leafn_add(struct xfs_buf *bp, xfs_da_args_t *args,
0028                   int index);
0029 static void xfs_dir2_leafn_rebalance(xfs_da_state_t *state,
0030                      xfs_da_state_blk_t *blk1,
0031                      xfs_da_state_blk_t *blk2);
0032 static int xfs_dir2_leafn_remove(xfs_da_args_t *args, struct xfs_buf *bp,
0033                  int index, xfs_da_state_blk_t *dblk,
0034                  int *rval);
0035 
0036 /*
0037  * Convert data space db to the corresponding free db.
0038  */
0039 static xfs_dir2_db_t
0040 xfs_dir2_db_to_fdb(struct xfs_da_geometry *geo, xfs_dir2_db_t db)
0041 {
0042     return xfs_dir2_byte_to_db(geo, XFS_DIR2_FREE_OFFSET) +
0043             (db / geo->free_max_bests);
0044 }
0045 
0046 /*
0047  * Convert data space db to the corresponding index in a free db.
0048  */
0049 static int
0050 xfs_dir2_db_to_fdindex(struct xfs_da_geometry *geo, xfs_dir2_db_t db)
0051 {
0052     return db % geo->free_max_bests;
0053 }
0054 
0055 /*
0056  * Check internal consistency of a leafn block.
0057  */
0058 #ifdef DEBUG
0059 static xfs_failaddr_t
0060 xfs_dir3_leafn_check(
0061     struct xfs_inode    *dp,
0062     struct xfs_buf      *bp)
0063 {
0064     struct xfs_dir2_leaf    *leaf = bp->b_addr;
0065     struct xfs_dir3_icleaf_hdr leafhdr;
0066 
0067     xfs_dir2_leaf_hdr_from_disk(dp->i_mount, &leafhdr, leaf);
0068 
0069     if (leafhdr.magic == XFS_DIR3_LEAFN_MAGIC) {
0070         struct xfs_dir3_leaf_hdr *leaf3 = bp->b_addr;
0071         if (be64_to_cpu(leaf3->info.blkno) != xfs_buf_daddr(bp))
0072             return __this_address;
0073     } else if (leafhdr.magic != XFS_DIR2_LEAFN_MAGIC)
0074         return __this_address;
0075 
0076     return xfs_dir3_leaf_check_int(dp->i_mount, &leafhdr, leaf, false);
0077 }
0078 
0079 static inline void
0080 xfs_dir3_leaf_check(
0081     struct xfs_inode    *dp,
0082     struct xfs_buf      *bp)
0083 {
0084     xfs_failaddr_t      fa;
0085 
0086     fa = xfs_dir3_leafn_check(dp, bp);
0087     if (!fa)
0088         return;
0089     xfs_corruption_error(__func__, XFS_ERRLEVEL_LOW, dp->i_mount,
0090             bp->b_addr, BBTOB(bp->b_length), __FILE__, __LINE__,
0091             fa);
0092     ASSERT(0);
0093 }
0094 #else
0095 #define xfs_dir3_leaf_check(dp, bp)
0096 #endif
0097 
0098 static xfs_failaddr_t
0099 xfs_dir3_free_verify(
0100     struct xfs_buf      *bp)
0101 {
0102     struct xfs_mount    *mp = bp->b_mount;
0103     struct xfs_dir2_free_hdr *hdr = bp->b_addr;
0104 
0105     if (!xfs_verify_magic(bp, hdr->magic))
0106         return __this_address;
0107 
0108     if (xfs_has_crc(mp)) {
0109         struct xfs_dir3_blk_hdr *hdr3 = bp->b_addr;
0110 
0111         if (!uuid_equal(&hdr3->uuid, &mp->m_sb.sb_meta_uuid))
0112             return __this_address;
0113         if (be64_to_cpu(hdr3->blkno) != xfs_buf_daddr(bp))
0114             return __this_address;
0115         if (!xfs_log_check_lsn(mp, be64_to_cpu(hdr3->lsn)))
0116             return __this_address;
0117     }
0118 
0119     /* XXX: should bounds check the xfs_dir3_icfree_hdr here */
0120 
0121     return NULL;
0122 }
0123 
0124 static void
0125 xfs_dir3_free_read_verify(
0126     struct xfs_buf  *bp)
0127 {
0128     struct xfs_mount    *mp = bp->b_mount;
0129     xfs_failaddr_t      fa;
0130 
0131     if (xfs_has_crc(mp) &&
0132         !xfs_buf_verify_cksum(bp, XFS_DIR3_FREE_CRC_OFF))
0133         xfs_verifier_error(bp, -EFSBADCRC, __this_address);
0134     else {
0135         fa = xfs_dir3_free_verify(bp);
0136         if (fa)
0137             xfs_verifier_error(bp, -EFSCORRUPTED, fa);
0138     }
0139 }
0140 
0141 static void
0142 xfs_dir3_free_write_verify(
0143     struct xfs_buf  *bp)
0144 {
0145     struct xfs_mount    *mp = bp->b_mount;
0146     struct xfs_buf_log_item *bip = bp->b_log_item;
0147     struct xfs_dir3_blk_hdr *hdr3 = bp->b_addr;
0148     xfs_failaddr_t      fa;
0149 
0150     fa = xfs_dir3_free_verify(bp);
0151     if (fa) {
0152         xfs_verifier_error(bp, -EFSCORRUPTED, fa);
0153         return;
0154     }
0155 
0156     if (!xfs_has_crc(mp))
0157         return;
0158 
0159     if (bip)
0160         hdr3->lsn = cpu_to_be64(bip->bli_item.li_lsn);
0161 
0162     xfs_buf_update_cksum(bp, XFS_DIR3_FREE_CRC_OFF);
0163 }
0164 
0165 const struct xfs_buf_ops xfs_dir3_free_buf_ops = {
0166     .name = "xfs_dir3_free",
0167     .magic = { cpu_to_be32(XFS_DIR2_FREE_MAGIC),
0168            cpu_to_be32(XFS_DIR3_FREE_MAGIC) },
0169     .verify_read = xfs_dir3_free_read_verify,
0170     .verify_write = xfs_dir3_free_write_verify,
0171     .verify_struct = xfs_dir3_free_verify,
0172 };
0173 
0174 /* Everything ok in the free block header? */
0175 static xfs_failaddr_t
0176 xfs_dir3_free_header_check(
0177     struct xfs_inode    *dp,
0178     xfs_dablk_t     fbno,
0179     struct xfs_buf      *bp)
0180 {
0181     struct xfs_mount    *mp = dp->i_mount;
0182     int         maxbests = mp->m_dir_geo->free_max_bests;
0183     unsigned int        firstdb;
0184 
0185     firstdb = (xfs_dir2_da_to_db(mp->m_dir_geo, fbno) -
0186            xfs_dir2_byte_to_db(mp->m_dir_geo, XFS_DIR2_FREE_OFFSET)) *
0187             maxbests;
0188     if (xfs_has_crc(mp)) {
0189         struct xfs_dir3_free_hdr *hdr3 = bp->b_addr;
0190 
0191         if (be32_to_cpu(hdr3->firstdb) != firstdb)
0192             return __this_address;
0193         if (be32_to_cpu(hdr3->nvalid) > maxbests)
0194             return __this_address;
0195         if (be32_to_cpu(hdr3->nvalid) < be32_to_cpu(hdr3->nused))
0196             return __this_address;
0197         if (be64_to_cpu(hdr3->hdr.owner) != dp->i_ino)
0198             return __this_address;
0199     } else {
0200         struct xfs_dir2_free_hdr *hdr = bp->b_addr;
0201 
0202         if (be32_to_cpu(hdr->firstdb) != firstdb)
0203             return __this_address;
0204         if (be32_to_cpu(hdr->nvalid) > maxbests)
0205             return __this_address;
0206         if (be32_to_cpu(hdr->nvalid) < be32_to_cpu(hdr->nused))
0207             return __this_address;
0208     }
0209     return NULL;
0210 }
0211 
0212 static int
0213 __xfs_dir3_free_read(
0214     struct xfs_trans    *tp,
0215     struct xfs_inode    *dp,
0216     xfs_dablk_t     fbno,
0217     unsigned int        flags,
0218     struct xfs_buf      **bpp)
0219 {
0220     xfs_failaddr_t      fa;
0221     int         err;
0222 
0223     err = xfs_da_read_buf(tp, dp, fbno, flags, bpp, XFS_DATA_FORK,
0224             &xfs_dir3_free_buf_ops);
0225     if (err || !*bpp)
0226         return err;
0227 
0228     /* Check things that we can't do in the verifier. */
0229     fa = xfs_dir3_free_header_check(dp, fbno, *bpp);
0230     if (fa) {
0231         __xfs_buf_mark_corrupt(*bpp, fa);
0232         xfs_trans_brelse(tp, *bpp);
0233         *bpp = NULL;
0234         return -EFSCORRUPTED;
0235     }
0236 
0237     /* try read returns without an error or *bpp if it lands in a hole */
0238     if (tp)
0239         xfs_trans_buf_set_type(tp, *bpp, XFS_BLFT_DIR_FREE_BUF);
0240 
0241     return 0;
0242 }
0243 
0244 void
0245 xfs_dir2_free_hdr_from_disk(
0246     struct xfs_mount        *mp,
0247     struct xfs_dir3_icfree_hdr  *to,
0248     struct xfs_dir2_free        *from)
0249 {
0250     if (xfs_has_crc(mp)) {
0251         struct xfs_dir3_free    *from3 = (struct xfs_dir3_free *)from;
0252 
0253         to->magic = be32_to_cpu(from3->hdr.hdr.magic);
0254         to->firstdb = be32_to_cpu(from3->hdr.firstdb);
0255         to->nvalid = be32_to_cpu(from3->hdr.nvalid);
0256         to->nused = be32_to_cpu(from3->hdr.nused);
0257         to->bests = from3->bests;
0258 
0259         ASSERT(to->magic == XFS_DIR3_FREE_MAGIC);
0260     } else {
0261         to->magic = be32_to_cpu(from->hdr.magic);
0262         to->firstdb = be32_to_cpu(from->hdr.firstdb);
0263         to->nvalid = be32_to_cpu(from->hdr.nvalid);
0264         to->nused = be32_to_cpu(from->hdr.nused);
0265         to->bests = from->bests;
0266 
0267         ASSERT(to->magic == XFS_DIR2_FREE_MAGIC);
0268     }
0269 }
0270 
0271 static void
0272 xfs_dir2_free_hdr_to_disk(
0273     struct xfs_mount        *mp,
0274     struct xfs_dir2_free        *to,
0275     struct xfs_dir3_icfree_hdr  *from)
0276 {
0277     if (xfs_has_crc(mp)) {
0278         struct xfs_dir3_free    *to3 = (struct xfs_dir3_free *)to;
0279 
0280         ASSERT(from->magic == XFS_DIR3_FREE_MAGIC);
0281 
0282         to3->hdr.hdr.magic = cpu_to_be32(from->magic);
0283         to3->hdr.firstdb = cpu_to_be32(from->firstdb);
0284         to3->hdr.nvalid = cpu_to_be32(from->nvalid);
0285         to3->hdr.nused = cpu_to_be32(from->nused);
0286     } else {
0287         ASSERT(from->magic == XFS_DIR2_FREE_MAGIC);
0288 
0289         to->hdr.magic = cpu_to_be32(from->magic);
0290         to->hdr.firstdb = cpu_to_be32(from->firstdb);
0291         to->hdr.nvalid = cpu_to_be32(from->nvalid);
0292         to->hdr.nused = cpu_to_be32(from->nused);
0293     }
0294 }
0295 
0296 int
0297 xfs_dir2_free_read(
0298     struct xfs_trans    *tp,
0299     struct xfs_inode    *dp,
0300     xfs_dablk_t     fbno,
0301     struct xfs_buf      **bpp)
0302 {
0303     return __xfs_dir3_free_read(tp, dp, fbno, 0, bpp);
0304 }
0305 
0306 static int
0307 xfs_dir2_free_try_read(
0308     struct xfs_trans    *tp,
0309     struct xfs_inode    *dp,
0310     xfs_dablk_t     fbno,
0311     struct xfs_buf      **bpp)
0312 {
0313     return __xfs_dir3_free_read(tp, dp, fbno, XFS_DABUF_MAP_HOLE_OK, bpp);
0314 }
0315 
0316 static int
0317 xfs_dir3_free_get_buf(
0318     xfs_da_args_t       *args,
0319     xfs_dir2_db_t       fbno,
0320     struct xfs_buf      **bpp)
0321 {
0322     struct xfs_trans    *tp = args->trans;
0323     struct xfs_inode    *dp = args->dp;
0324     struct xfs_mount    *mp = dp->i_mount;
0325     struct xfs_buf      *bp;
0326     int         error;
0327     struct xfs_dir3_icfree_hdr hdr;
0328 
0329     error = xfs_da_get_buf(tp, dp, xfs_dir2_db_to_da(args->geo, fbno),
0330             &bp, XFS_DATA_FORK);
0331     if (error)
0332         return error;
0333 
0334     xfs_trans_buf_set_type(tp, bp, XFS_BLFT_DIR_FREE_BUF);
0335     bp->b_ops = &xfs_dir3_free_buf_ops;
0336 
0337     /*
0338      * Initialize the new block to be empty, and remember
0339      * its first slot as our empty slot.
0340      */
0341     memset(bp->b_addr, 0, sizeof(struct xfs_dir3_free_hdr));
0342     memset(&hdr, 0, sizeof(hdr));
0343 
0344     if (xfs_has_crc(mp)) {
0345         struct xfs_dir3_free_hdr *hdr3 = bp->b_addr;
0346 
0347         hdr.magic = XFS_DIR3_FREE_MAGIC;
0348 
0349         hdr3->hdr.blkno = cpu_to_be64(xfs_buf_daddr(bp));
0350         hdr3->hdr.owner = cpu_to_be64(dp->i_ino);
0351         uuid_copy(&hdr3->hdr.uuid, &mp->m_sb.sb_meta_uuid);
0352     } else
0353         hdr.magic = XFS_DIR2_FREE_MAGIC;
0354     xfs_dir2_free_hdr_to_disk(mp, bp->b_addr, &hdr);
0355     *bpp = bp;
0356     return 0;
0357 }
0358 
0359 /*
0360  * Log entries from a freespace block.
0361  */
0362 STATIC void
0363 xfs_dir2_free_log_bests(
0364     struct xfs_da_args  *args,
0365     struct xfs_dir3_icfree_hdr *hdr,
0366     struct xfs_buf      *bp,
0367     int         first,      /* first entry to log */
0368     int         last)       /* last entry to log */
0369 {
0370     struct xfs_dir2_free    *free = bp->b_addr;
0371 
0372     ASSERT(free->hdr.magic == cpu_to_be32(XFS_DIR2_FREE_MAGIC) ||
0373            free->hdr.magic == cpu_to_be32(XFS_DIR3_FREE_MAGIC));
0374     xfs_trans_log_buf(args->trans, bp,
0375               (char *)&hdr->bests[first] - (char *)free,
0376               (char *)&hdr->bests[last] - (char *)free +
0377                sizeof(hdr->bests[0]) - 1);
0378 }
0379 
0380 /*
0381  * Log header from a freespace block.
0382  */
0383 static void
0384 xfs_dir2_free_log_header(
0385     struct xfs_da_args  *args,
0386     struct xfs_buf      *bp)
0387 {
0388 #ifdef DEBUG
0389     xfs_dir2_free_t     *free;      /* freespace structure */
0390 
0391     free = bp->b_addr;
0392     ASSERT(free->hdr.magic == cpu_to_be32(XFS_DIR2_FREE_MAGIC) ||
0393            free->hdr.magic == cpu_to_be32(XFS_DIR3_FREE_MAGIC));
0394 #endif
0395     xfs_trans_log_buf(args->trans, bp, 0,
0396               args->geo->free_hdr_size - 1);
0397 }
0398 
0399 /*
0400  * Convert a leaf-format directory to a node-format directory.
0401  * We need to change the magic number of the leaf block, and copy
0402  * the freespace table out of the leaf block into its own block.
0403  */
0404 int                     /* error */
0405 xfs_dir2_leaf_to_node(
0406     xfs_da_args_t       *args,      /* operation arguments */
0407     struct xfs_buf      *lbp)       /* leaf buffer */
0408 {
0409     xfs_inode_t     *dp;        /* incore directory inode */
0410     int         error;      /* error return value */
0411     struct xfs_buf      *fbp;       /* freespace buffer */
0412     xfs_dir2_db_t       fdb;        /* freespace block number */
0413     __be16          *from;      /* pointer to freespace entry */
0414     int         i;      /* leaf freespace index */
0415     xfs_dir2_leaf_t     *leaf;      /* leaf structure */
0416     xfs_dir2_leaf_tail_t    *ltp;       /* leaf tail structure */
0417     int         n;      /* count of live freespc ents */
0418     xfs_dir2_data_off_t off;        /* freespace entry value */
0419     xfs_trans_t     *tp;        /* transaction pointer */
0420     struct xfs_dir3_icfree_hdr freehdr;
0421 
0422     trace_xfs_dir2_leaf_to_node(args);
0423 
0424     dp = args->dp;
0425     tp = args->trans;
0426     /*
0427      * Add a freespace block to the directory.
0428      */
0429     if ((error = xfs_dir2_grow_inode(args, XFS_DIR2_FREE_SPACE, &fdb))) {
0430         return error;
0431     }
0432     ASSERT(fdb == xfs_dir2_byte_to_db(args->geo, XFS_DIR2_FREE_OFFSET));
0433     /*
0434      * Get the buffer for the new freespace block.
0435      */
0436     error = xfs_dir3_free_get_buf(args, fdb, &fbp);
0437     if (error)
0438         return error;
0439 
0440     xfs_dir2_free_hdr_from_disk(dp->i_mount, &freehdr, fbp->b_addr);
0441     leaf = lbp->b_addr;
0442     ltp = xfs_dir2_leaf_tail_p(args->geo, leaf);
0443     if (be32_to_cpu(ltp->bestcount) >
0444                 (uint)dp->i_disk_size / args->geo->blksize) {
0445         xfs_buf_mark_corrupt(lbp);
0446         return -EFSCORRUPTED;
0447     }
0448 
0449     /*
0450      * Copy freespace entries from the leaf block to the new block.
0451      * Count active entries.
0452      */
0453     from = xfs_dir2_leaf_bests_p(ltp);
0454     for (i = n = 0; i < be32_to_cpu(ltp->bestcount); i++, from++) {
0455         off = be16_to_cpu(*from);
0456         if (off != NULLDATAOFF)
0457             n++;
0458         freehdr.bests[i] = cpu_to_be16(off);
0459     }
0460 
0461     /*
0462      * Now initialize the freespace block header.
0463      */
0464     freehdr.nused = n;
0465     freehdr.nvalid = be32_to_cpu(ltp->bestcount);
0466 
0467     xfs_dir2_free_hdr_to_disk(dp->i_mount, fbp->b_addr, &freehdr);
0468     xfs_dir2_free_log_bests(args, &freehdr, fbp, 0, freehdr.nvalid - 1);
0469     xfs_dir2_free_log_header(args, fbp);
0470 
0471     /*
0472      * Converting the leaf to a leafnode is just a matter of changing the
0473      * magic number and the ops. Do the change directly to the buffer as
0474      * it's less work (and less code) than decoding the header to host
0475      * format and back again.
0476      */
0477     if (leaf->hdr.info.magic == cpu_to_be16(XFS_DIR2_LEAF1_MAGIC))
0478         leaf->hdr.info.magic = cpu_to_be16(XFS_DIR2_LEAFN_MAGIC);
0479     else
0480         leaf->hdr.info.magic = cpu_to_be16(XFS_DIR3_LEAFN_MAGIC);
0481     lbp->b_ops = &xfs_dir3_leafn_buf_ops;
0482     xfs_trans_buf_set_type(tp, lbp, XFS_BLFT_DIR_LEAFN_BUF);
0483     xfs_dir3_leaf_log_header(args, lbp);
0484     xfs_dir3_leaf_check(dp, lbp);
0485     return 0;
0486 }
0487 
0488 /*
0489  * Add a leaf entry to a leaf block in a node-form directory.
0490  * The other work necessary is done from the caller.
0491  */
0492 static int                  /* error */
0493 xfs_dir2_leafn_add(
0494     struct xfs_buf      *bp,        /* leaf buffer */
0495     struct xfs_da_args  *args,      /* operation arguments */
0496     int         index)      /* insertion pt for new entry */
0497 {
0498     struct xfs_dir3_icleaf_hdr leafhdr;
0499     struct xfs_inode    *dp = args->dp;
0500     struct xfs_dir2_leaf    *leaf = bp->b_addr;
0501     struct xfs_dir2_leaf_entry *lep;
0502     struct xfs_dir2_leaf_entry *ents;
0503     int         compact;    /* compacting stale leaves */
0504     int         highstale = 0;  /* next stale entry */
0505     int         lfloghigh;  /* high leaf entry logging */
0506     int         lfloglow;   /* low leaf entry logging */
0507     int         lowstale = 0;   /* previous stale entry */
0508 
0509     trace_xfs_dir2_leafn_add(args, index);
0510 
0511     xfs_dir2_leaf_hdr_from_disk(dp->i_mount, &leafhdr, leaf);
0512     ents = leafhdr.ents;
0513 
0514     /*
0515      * Quick check just to make sure we are not going to index
0516      * into other peoples memory
0517      */
0518     if (index < 0) {
0519         xfs_buf_mark_corrupt(bp);
0520         return -EFSCORRUPTED;
0521     }
0522 
0523     /*
0524      * If there are already the maximum number of leaf entries in
0525      * the block, if there are no stale entries it won't fit.
0526      * Caller will do a split.  If there are stale entries we'll do
0527      * a compact.
0528      */
0529 
0530     if (leafhdr.count == args->geo->leaf_max_ents) {
0531         if (!leafhdr.stale)
0532             return -ENOSPC;
0533         compact = leafhdr.stale > 1;
0534     } else
0535         compact = 0;
0536     ASSERT(index == 0 || be32_to_cpu(ents[index - 1].hashval) <= args->hashval);
0537     ASSERT(index == leafhdr.count ||
0538            be32_to_cpu(ents[index].hashval) >= args->hashval);
0539 
0540     if (args->op_flags & XFS_DA_OP_JUSTCHECK)
0541         return 0;
0542 
0543     /*
0544      * Compact out all but one stale leaf entry.  Leaves behind
0545      * the entry closest to index.
0546      */
0547     if (compact)
0548         xfs_dir3_leaf_compact_x1(&leafhdr, ents, &index, &lowstale,
0549                      &highstale, &lfloglow, &lfloghigh);
0550     else if (leafhdr.stale) {
0551         /*
0552          * Set impossible logging indices for this case.
0553          */
0554         lfloglow = leafhdr.count;
0555         lfloghigh = -1;
0556     }
0557 
0558     /*
0559      * Insert the new entry, log everything.
0560      */
0561     lep = xfs_dir3_leaf_find_entry(&leafhdr, ents, index, compact, lowstale,
0562                        highstale, &lfloglow, &lfloghigh);
0563 
0564     lep->hashval = cpu_to_be32(args->hashval);
0565     lep->address = cpu_to_be32(xfs_dir2_db_off_to_dataptr(args->geo,
0566                 args->blkno, args->index));
0567 
0568     xfs_dir2_leaf_hdr_to_disk(dp->i_mount, leaf, &leafhdr);
0569     xfs_dir3_leaf_log_header(args, bp);
0570     xfs_dir3_leaf_log_ents(args, &leafhdr, bp, lfloglow, lfloghigh);
0571     xfs_dir3_leaf_check(dp, bp);
0572     return 0;
0573 }
0574 
0575 #ifdef DEBUG
0576 static void
0577 xfs_dir2_free_hdr_check(
0578     struct xfs_inode *dp,
0579     struct xfs_buf  *bp,
0580     xfs_dir2_db_t   db)
0581 {
0582     struct xfs_dir3_icfree_hdr hdr;
0583 
0584     xfs_dir2_free_hdr_from_disk(dp->i_mount, &hdr, bp->b_addr);
0585 
0586     ASSERT((hdr.firstdb % dp->i_mount->m_dir_geo->free_max_bests) == 0);
0587     ASSERT(hdr.firstdb <= db);
0588     ASSERT(db < hdr.firstdb + hdr.nvalid);
0589 }
0590 #else
0591 #define xfs_dir2_free_hdr_check(dp, bp, db)
0592 #endif  /* DEBUG */
0593 
0594 /*
0595  * Return the last hash value in the leaf.
0596  * Stale entries are ok.
0597  */
0598 xfs_dahash_t                    /* hash value */
0599 xfs_dir2_leaf_lasthash(
0600     struct xfs_inode *dp,
0601     struct xfs_buf  *bp,            /* leaf buffer */
0602     int     *count)         /* count of entries in leaf */
0603 {
0604     struct xfs_dir3_icleaf_hdr leafhdr;
0605 
0606     xfs_dir2_leaf_hdr_from_disk(dp->i_mount, &leafhdr, bp->b_addr);
0607 
0608     ASSERT(leafhdr.magic == XFS_DIR2_LEAFN_MAGIC ||
0609            leafhdr.magic == XFS_DIR3_LEAFN_MAGIC ||
0610            leafhdr.magic == XFS_DIR2_LEAF1_MAGIC ||
0611            leafhdr.magic == XFS_DIR3_LEAF1_MAGIC);
0612 
0613     if (count)
0614         *count = leafhdr.count;
0615     if (!leafhdr.count)
0616         return 0;
0617     return be32_to_cpu(leafhdr.ents[leafhdr.count - 1].hashval);
0618 }
0619 
0620 /*
0621  * Look up a leaf entry for space to add a name in a node-format leaf block.
0622  * The extrablk in state is a freespace block.
0623  */
0624 STATIC int
0625 xfs_dir2_leafn_lookup_for_addname(
0626     struct xfs_buf      *bp,        /* leaf buffer */
0627     xfs_da_args_t       *args,      /* operation arguments */
0628     int         *indexp,    /* out: leaf entry index */
0629     xfs_da_state_t      *state)     /* state to fill in */
0630 {
0631     struct xfs_buf      *curbp = NULL;  /* current data/free buffer */
0632     xfs_dir2_db_t       curdb = -1; /* current data block number */
0633     xfs_dir2_db_t       curfdb = -1;    /* current free block number */
0634     xfs_inode_t     *dp;        /* incore directory inode */
0635     int         error;      /* error return value */
0636     int         fi;     /* free entry index */
0637     xfs_dir2_free_t     *free = NULL;   /* free block structure */
0638     int         index;      /* leaf entry index */
0639     xfs_dir2_leaf_t     *leaf;      /* leaf structure */
0640     int         length;     /* length of new data entry */
0641     xfs_dir2_leaf_entry_t   *lep;       /* leaf entry */
0642     xfs_mount_t     *mp;        /* filesystem mount point */
0643     xfs_dir2_db_t       newdb;      /* new data block number */
0644     xfs_dir2_db_t       newfdb;     /* new free block number */
0645     xfs_trans_t     *tp;        /* transaction pointer */
0646     struct xfs_dir3_icleaf_hdr leafhdr;
0647 
0648     dp = args->dp;
0649     tp = args->trans;
0650     mp = dp->i_mount;
0651     leaf = bp->b_addr;
0652     xfs_dir2_leaf_hdr_from_disk(mp, &leafhdr, leaf);
0653 
0654     xfs_dir3_leaf_check(dp, bp);
0655     ASSERT(leafhdr.count > 0);
0656 
0657     /*
0658      * Look up the hash value in the leaf entries.
0659      */
0660     index = xfs_dir2_leaf_search_hash(args, bp);
0661     /*
0662      * Do we have a buffer coming in?
0663      */
0664     if (state->extravalid) {
0665         /* If so, it's a free block buffer, get the block number. */
0666         curbp = state->extrablk.bp;
0667         curfdb = state->extrablk.blkno;
0668         free = curbp->b_addr;
0669         ASSERT(free->hdr.magic == cpu_to_be32(XFS_DIR2_FREE_MAGIC) ||
0670                free->hdr.magic == cpu_to_be32(XFS_DIR3_FREE_MAGIC));
0671     }
0672     length = xfs_dir2_data_entsize(mp, args->namelen);
0673     /*
0674      * Loop over leaf entries with the right hash value.
0675      */
0676     for (lep = &leafhdr.ents[index];
0677          index < leafhdr.count && be32_to_cpu(lep->hashval) == args->hashval;
0678          lep++, index++) {
0679         /*
0680          * Skip stale leaf entries.
0681          */
0682         if (be32_to_cpu(lep->address) == XFS_DIR2_NULL_DATAPTR)
0683             continue;
0684         /*
0685          * Pull the data block number from the entry.
0686          */
0687         newdb = xfs_dir2_dataptr_to_db(args->geo,
0688                            be32_to_cpu(lep->address));
0689         /*
0690          * For addname, we're looking for a place to put the new entry.
0691          * We want to use a data block with an entry of equal
0692          * hash value to ours if there is one with room.
0693          *
0694          * If this block isn't the data block we already have
0695          * in hand, take a look at it.
0696          */
0697         if (newdb != curdb) {
0698             struct xfs_dir3_icfree_hdr freehdr;
0699 
0700             curdb = newdb;
0701             /*
0702              * Convert the data block to the free block
0703              * holding its freespace information.
0704              */
0705             newfdb = xfs_dir2_db_to_fdb(args->geo, newdb);
0706             /*
0707              * If it's not the one we have in hand, read it in.
0708              */
0709             if (newfdb != curfdb) {
0710                 /*
0711                  * If we had one before, drop it.
0712                  */
0713                 if (curbp)
0714                     xfs_trans_brelse(tp, curbp);
0715 
0716                 error = xfs_dir2_free_read(tp, dp,
0717                         xfs_dir2_db_to_da(args->geo,
0718                                   newfdb),
0719                         &curbp);
0720                 if (error)
0721                     return error;
0722                 free = curbp->b_addr;
0723 
0724                 xfs_dir2_free_hdr_check(dp, curbp, curdb);
0725             }
0726             /*
0727              * Get the index for our entry.
0728              */
0729             fi = xfs_dir2_db_to_fdindex(args->geo, curdb);
0730             /*
0731              * If it has room, return it.
0732              */
0733             xfs_dir2_free_hdr_from_disk(mp, &freehdr, free);
0734             if (XFS_IS_CORRUPT(mp,
0735                        freehdr.bests[fi] ==
0736                        cpu_to_be16(NULLDATAOFF))) {
0737                 if (curfdb != newfdb)
0738                     xfs_trans_brelse(tp, curbp);
0739                 return -EFSCORRUPTED;
0740             }
0741             curfdb = newfdb;
0742             if (be16_to_cpu(freehdr.bests[fi]) >= length)
0743                 goto out;
0744         }
0745     }
0746     /* Didn't find any space */
0747     fi = -1;
0748 out:
0749     ASSERT(args->op_flags & XFS_DA_OP_OKNOENT);
0750     if (curbp) {
0751         /* Giving back a free block. */
0752         state->extravalid = 1;
0753         state->extrablk.bp = curbp;
0754         state->extrablk.index = fi;
0755         state->extrablk.blkno = curfdb;
0756 
0757         /*
0758          * Important: this magic number is not in the buffer - it's for
0759          * buffer type information and therefore only the free/data type
0760          * matters here, not whether CRCs are enabled or not.
0761          */
0762         state->extrablk.magic = XFS_DIR2_FREE_MAGIC;
0763     } else {
0764         state->extravalid = 0;
0765     }
0766     /*
0767      * Return the index, that will be the insertion point.
0768      */
0769     *indexp = index;
0770     return -ENOENT;
0771 }
0772 
0773 /*
0774  * Look up a leaf entry in a node-format leaf block.
0775  * The extrablk in state a data block.
0776  */
0777 STATIC int
0778 xfs_dir2_leafn_lookup_for_entry(
0779     struct xfs_buf      *bp,        /* leaf buffer */
0780     xfs_da_args_t       *args,      /* operation arguments */
0781     int         *indexp,    /* out: leaf entry index */
0782     xfs_da_state_t      *state)     /* state to fill in */
0783 {
0784     struct xfs_buf      *curbp = NULL;  /* current data/free buffer */
0785     xfs_dir2_db_t       curdb = -1; /* current data block number */
0786     xfs_dir2_data_entry_t   *dep;       /* data block entry */
0787     xfs_inode_t     *dp;        /* incore directory inode */
0788     int         error;      /* error return value */
0789     int         index;      /* leaf entry index */
0790     xfs_dir2_leaf_t     *leaf;      /* leaf structure */
0791     xfs_dir2_leaf_entry_t   *lep;       /* leaf entry */
0792     xfs_mount_t     *mp;        /* filesystem mount point */
0793     xfs_dir2_db_t       newdb;      /* new data block number */
0794     xfs_trans_t     *tp;        /* transaction pointer */
0795     enum xfs_dacmp      cmp;        /* comparison result */
0796     struct xfs_dir3_icleaf_hdr leafhdr;
0797 
0798     dp = args->dp;
0799     tp = args->trans;
0800     mp = dp->i_mount;
0801     leaf = bp->b_addr;
0802     xfs_dir2_leaf_hdr_from_disk(mp, &leafhdr, leaf);
0803 
0804     xfs_dir3_leaf_check(dp, bp);
0805     if (leafhdr.count <= 0) {
0806         xfs_buf_mark_corrupt(bp);
0807         return -EFSCORRUPTED;
0808     }
0809 
0810     /*
0811      * Look up the hash value in the leaf entries.
0812      */
0813     index = xfs_dir2_leaf_search_hash(args, bp);
0814     /*
0815      * Do we have a buffer coming in?
0816      */
0817     if (state->extravalid) {
0818         curbp = state->extrablk.bp;
0819         curdb = state->extrablk.blkno;
0820     }
0821     /*
0822      * Loop over leaf entries with the right hash value.
0823      */
0824     for (lep = &leafhdr.ents[index];
0825          index < leafhdr.count && be32_to_cpu(lep->hashval) == args->hashval;
0826          lep++, index++) {
0827         /*
0828          * Skip stale leaf entries.
0829          */
0830         if (be32_to_cpu(lep->address) == XFS_DIR2_NULL_DATAPTR)
0831             continue;
0832         /*
0833          * Pull the data block number from the entry.
0834          */
0835         newdb = xfs_dir2_dataptr_to_db(args->geo,
0836                            be32_to_cpu(lep->address));
0837         /*
0838          * Not adding a new entry, so we really want to find
0839          * the name given to us.
0840          *
0841          * If it's a different data block, go get it.
0842          */
0843         if (newdb != curdb) {
0844             /*
0845              * If we had a block before that we aren't saving
0846              * for a CI name, drop it
0847              */
0848             if (curbp && (args->cmpresult == XFS_CMP_DIFFERENT ||
0849                         curdb != state->extrablk.blkno))
0850                 xfs_trans_brelse(tp, curbp);
0851             /*
0852              * If needing the block that is saved with a CI match,
0853              * use it otherwise read in the new data block.
0854              */
0855             if (args->cmpresult != XFS_CMP_DIFFERENT &&
0856                     newdb == state->extrablk.blkno) {
0857                 ASSERT(state->extravalid);
0858                 curbp = state->extrablk.bp;
0859             } else {
0860                 error = xfs_dir3_data_read(tp, dp,
0861                         xfs_dir2_db_to_da(args->geo,
0862                                   newdb),
0863                         0, &curbp);
0864                 if (error)
0865                     return error;
0866             }
0867             xfs_dir3_data_check(dp, curbp);
0868             curdb = newdb;
0869         }
0870         /*
0871          * Point to the data entry.
0872          */
0873         dep = (xfs_dir2_data_entry_t *)((char *)curbp->b_addr +
0874             xfs_dir2_dataptr_to_off(args->geo,
0875                         be32_to_cpu(lep->address)));
0876         /*
0877          * Compare the entry and if it's an exact match, return
0878          * EEXIST immediately. If it's the first case-insensitive
0879          * match, store the block & inode number and continue looking.
0880          */
0881         cmp = xfs_dir2_compname(args, dep->name, dep->namelen);
0882         if (cmp != XFS_CMP_DIFFERENT && cmp != args->cmpresult) {
0883             /* If there is a CI match block, drop it */
0884             if (args->cmpresult != XFS_CMP_DIFFERENT &&
0885                         curdb != state->extrablk.blkno)
0886                 xfs_trans_brelse(tp, state->extrablk.bp);
0887             args->cmpresult = cmp;
0888             args->inumber = be64_to_cpu(dep->inumber);
0889             args->filetype = xfs_dir2_data_get_ftype(mp, dep);
0890             *indexp = index;
0891             state->extravalid = 1;
0892             state->extrablk.bp = curbp;
0893             state->extrablk.blkno = curdb;
0894             state->extrablk.index = (int)((char *)dep -
0895                             (char *)curbp->b_addr);
0896             state->extrablk.magic = XFS_DIR2_DATA_MAGIC;
0897             curbp->b_ops = &xfs_dir3_data_buf_ops;
0898             xfs_trans_buf_set_type(tp, curbp, XFS_BLFT_DIR_DATA_BUF);
0899             if (cmp == XFS_CMP_EXACT)
0900                 return -EEXIST;
0901         }
0902     }
0903     ASSERT(index == leafhdr.count || (args->op_flags & XFS_DA_OP_OKNOENT));
0904     if (curbp) {
0905         if (args->cmpresult == XFS_CMP_DIFFERENT) {
0906             /* Giving back last used data block. */
0907             state->extravalid = 1;
0908             state->extrablk.bp = curbp;
0909             state->extrablk.index = -1;
0910             state->extrablk.blkno = curdb;
0911             state->extrablk.magic = XFS_DIR2_DATA_MAGIC;
0912             curbp->b_ops = &xfs_dir3_data_buf_ops;
0913             xfs_trans_buf_set_type(tp, curbp, XFS_BLFT_DIR_DATA_BUF);
0914         } else {
0915             /* If the curbp is not the CI match block, drop it */
0916             if (state->extrablk.bp != curbp)
0917                 xfs_trans_brelse(tp, curbp);
0918         }
0919     } else {
0920         state->extravalid = 0;
0921     }
0922     *indexp = index;
0923     return -ENOENT;
0924 }
0925 
0926 /*
0927  * Look up a leaf entry in a node-format leaf block.
0928  * If this is an addname then the extrablk in state is a freespace block,
0929  * otherwise it's a data block.
0930  */
0931 int
0932 xfs_dir2_leafn_lookup_int(
0933     struct xfs_buf      *bp,        /* leaf buffer */
0934     xfs_da_args_t       *args,      /* operation arguments */
0935     int         *indexp,    /* out: leaf entry index */
0936     xfs_da_state_t      *state)     /* state to fill in */
0937 {
0938     if (args->op_flags & XFS_DA_OP_ADDNAME)
0939         return xfs_dir2_leafn_lookup_for_addname(bp, args, indexp,
0940                             state);
0941     return xfs_dir2_leafn_lookup_for_entry(bp, args, indexp, state);
0942 }
0943 
0944 /*
0945  * Move count leaf entries from source to destination leaf.
0946  * Log entries and headers.  Stale entries are preserved.
0947  */
0948 static void
0949 xfs_dir3_leafn_moveents(
0950     xfs_da_args_t           *args,  /* operation arguments */
0951     struct xfs_buf          *bp_s,  /* source */
0952     struct xfs_dir3_icleaf_hdr  *shdr,
0953     struct xfs_dir2_leaf_entry  *sents,
0954     int             start_s,/* source leaf index */
0955     struct xfs_buf          *bp_d,  /* destination */
0956     struct xfs_dir3_icleaf_hdr  *dhdr,
0957     struct xfs_dir2_leaf_entry  *dents,
0958     int             start_d,/* destination leaf index */
0959     int             count)  /* count of leaves to copy */
0960 {
0961     int             stale;  /* count stale leaves copied */
0962 
0963     trace_xfs_dir2_leafn_moveents(args, start_s, start_d, count);
0964 
0965     /*
0966      * Silently return if nothing to do.
0967      */
0968     if (count == 0)
0969         return;
0970 
0971     /*
0972      * If the destination index is not the end of the current
0973      * destination leaf entries, open up a hole in the destination
0974      * to hold the new entries.
0975      */
0976     if (start_d < dhdr->count) {
0977         memmove(&dents[start_d + count], &dents[start_d],
0978             (dhdr->count - start_d) * sizeof(xfs_dir2_leaf_entry_t));
0979         xfs_dir3_leaf_log_ents(args, dhdr, bp_d, start_d + count,
0980                        count + dhdr->count - 1);
0981     }
0982     /*
0983      * If the source has stale leaves, count the ones in the copy range
0984      * so we can update the header correctly.
0985      */
0986     if (shdr->stale) {
0987         int i;          /* temp leaf index */
0988 
0989         for (i = start_s, stale = 0; i < start_s + count; i++) {
0990             if (sents[i].address ==
0991                     cpu_to_be32(XFS_DIR2_NULL_DATAPTR))
0992                 stale++;
0993         }
0994     } else
0995         stale = 0;
0996     /*
0997      * Copy the leaf entries from source to destination.
0998      */
0999     memcpy(&dents[start_d], &sents[start_s],
1000         count * sizeof(xfs_dir2_leaf_entry_t));
1001     xfs_dir3_leaf_log_ents(args, dhdr, bp_d, start_d, start_d + count - 1);
1002 
1003     /*
1004      * If there are source entries after the ones we copied,
1005      * delete the ones we copied by sliding the next ones down.
1006      */
1007     if (start_s + count < shdr->count) {
1008         memmove(&sents[start_s], &sents[start_s + count],
1009             count * sizeof(xfs_dir2_leaf_entry_t));
1010         xfs_dir3_leaf_log_ents(args, shdr, bp_s, start_s,
1011                        start_s + count - 1);
1012     }
1013 
1014     /*
1015      * Update the headers and log them.
1016      */
1017     shdr->count -= count;
1018     shdr->stale -= stale;
1019     dhdr->count += count;
1020     dhdr->stale += stale;
1021 }
1022 
1023 /*
1024  * Determine the sort order of two leaf blocks.
1025  * Returns 1 if both are valid and leaf2 should be before leaf1, else 0.
1026  */
1027 int                     /* sort order */
1028 xfs_dir2_leafn_order(
1029     struct xfs_inode    *dp,
1030     struct xfs_buf      *leaf1_bp,      /* leaf1 buffer */
1031     struct xfs_buf      *leaf2_bp)      /* leaf2 buffer */
1032 {
1033     struct xfs_dir2_leaf    *leaf1 = leaf1_bp->b_addr;
1034     struct xfs_dir2_leaf    *leaf2 = leaf2_bp->b_addr;
1035     struct xfs_dir2_leaf_entry *ents1;
1036     struct xfs_dir2_leaf_entry *ents2;
1037     struct xfs_dir3_icleaf_hdr hdr1;
1038     struct xfs_dir3_icleaf_hdr hdr2;
1039 
1040     xfs_dir2_leaf_hdr_from_disk(dp->i_mount, &hdr1, leaf1);
1041     xfs_dir2_leaf_hdr_from_disk(dp->i_mount, &hdr2, leaf2);
1042     ents1 = hdr1.ents;
1043     ents2 = hdr2.ents;
1044 
1045     if (hdr1.count > 0 && hdr2.count > 0 &&
1046         (be32_to_cpu(ents2[0].hashval) < be32_to_cpu(ents1[0].hashval) ||
1047          be32_to_cpu(ents2[hdr2.count - 1].hashval) <
1048                 be32_to_cpu(ents1[hdr1.count - 1].hashval)))
1049         return 1;
1050     return 0;
1051 }
1052 
1053 /*
1054  * Rebalance leaf entries between two leaf blocks.
1055  * This is actually only called when the second block is new,
1056  * though the code deals with the general case.
1057  * A new entry will be inserted in one of the blocks, and that
1058  * entry is taken into account when balancing.
1059  */
1060 static void
1061 xfs_dir2_leafn_rebalance(
1062     xfs_da_state_t      *state,     /* btree cursor */
1063     xfs_da_state_blk_t  *blk1,      /* first btree block */
1064     xfs_da_state_blk_t  *blk2)      /* second btree block */
1065 {
1066     xfs_da_args_t       *args;      /* operation arguments */
1067     int         count;      /* count (& direction) leaves */
1068     int         isleft;     /* new goes in left leaf */
1069     xfs_dir2_leaf_t     *leaf1;     /* first leaf structure */
1070     xfs_dir2_leaf_t     *leaf2;     /* second leaf structure */
1071     int         mid;        /* midpoint leaf index */
1072 #if defined(DEBUG) || defined(XFS_WARN)
1073     int         oldstale;   /* old count of stale leaves */
1074 #endif
1075     int         oldsum;     /* old total leaf count */
1076     int         swap_blocks;    /* swapped leaf blocks */
1077     struct xfs_dir2_leaf_entry *ents1;
1078     struct xfs_dir2_leaf_entry *ents2;
1079     struct xfs_dir3_icleaf_hdr hdr1;
1080     struct xfs_dir3_icleaf_hdr hdr2;
1081     struct xfs_inode    *dp = state->args->dp;
1082 
1083     args = state->args;
1084     /*
1085      * If the block order is wrong, swap the arguments.
1086      */
1087     swap_blocks = xfs_dir2_leafn_order(dp, blk1->bp, blk2->bp);
1088     if (swap_blocks)
1089         swap(blk1, blk2);
1090 
1091     leaf1 = blk1->bp->b_addr;
1092     leaf2 = blk2->bp->b_addr;
1093     xfs_dir2_leaf_hdr_from_disk(dp->i_mount, &hdr1, leaf1);
1094     xfs_dir2_leaf_hdr_from_disk(dp->i_mount, &hdr2, leaf2);
1095     ents1 = hdr1.ents;
1096     ents2 = hdr2.ents;
1097 
1098     oldsum = hdr1.count + hdr2.count;
1099 #if defined(DEBUG) || defined(XFS_WARN)
1100     oldstale = hdr1.stale + hdr2.stale;
1101 #endif
1102     mid = oldsum >> 1;
1103 
1104     /*
1105      * If the old leaf count was odd then the new one will be even,
1106      * so we need to divide the new count evenly.
1107      */
1108     if (oldsum & 1) {
1109         xfs_dahash_t    midhash;    /* middle entry hash value */
1110 
1111         if (mid >= hdr1.count)
1112             midhash = be32_to_cpu(ents2[mid - hdr1.count].hashval);
1113         else
1114             midhash = be32_to_cpu(ents1[mid].hashval);
1115         isleft = args->hashval <= midhash;
1116     }
1117     /*
1118      * If the old count is even then the new count is odd, so there's
1119      * no preferred side for the new entry.
1120      * Pick the left one.
1121      */
1122     else
1123         isleft = 1;
1124     /*
1125      * Calculate moved entry count.  Positive means left-to-right,
1126      * negative means right-to-left.  Then move the entries.
1127      */
1128     count = hdr1.count - mid + (isleft == 0);
1129     if (count > 0)
1130         xfs_dir3_leafn_moveents(args, blk1->bp, &hdr1, ents1,
1131                     hdr1.count - count, blk2->bp,
1132                     &hdr2, ents2, 0, count);
1133     else if (count < 0)
1134         xfs_dir3_leafn_moveents(args, blk2->bp, &hdr2, ents2, 0,
1135                     blk1->bp, &hdr1, ents1,
1136                     hdr1.count, count);
1137 
1138     ASSERT(hdr1.count + hdr2.count == oldsum);
1139     ASSERT(hdr1.stale + hdr2.stale == oldstale);
1140 
1141     /* log the changes made when moving the entries */
1142     xfs_dir2_leaf_hdr_to_disk(dp->i_mount, leaf1, &hdr1);
1143     xfs_dir2_leaf_hdr_to_disk(dp->i_mount, leaf2, &hdr2);
1144     xfs_dir3_leaf_log_header(args, blk1->bp);
1145     xfs_dir3_leaf_log_header(args, blk2->bp);
1146 
1147     xfs_dir3_leaf_check(dp, blk1->bp);
1148     xfs_dir3_leaf_check(dp, blk2->bp);
1149 
1150     /*
1151      * Mark whether we're inserting into the old or new leaf.
1152      */
1153     if (hdr1.count < hdr2.count)
1154         state->inleaf = swap_blocks;
1155     else if (hdr1.count > hdr2.count)
1156         state->inleaf = !swap_blocks;
1157     else
1158         state->inleaf = swap_blocks ^ (blk1->index <= hdr1.count);
1159     /*
1160      * Adjust the expected index for insertion.
1161      */
1162     if (!state->inleaf)
1163         blk2->index = blk1->index - hdr1.count;
1164 
1165     /*
1166      * Finally sanity check just to make sure we are not returning a
1167      * negative index
1168      */
1169     if (blk2->index < 0) {
1170         state->inleaf = 1;
1171         blk2->index = 0;
1172         xfs_alert(dp->i_mount,
1173     "%s: picked the wrong leaf? reverting original leaf: blk1->index %d",
1174             __func__, blk1->index);
1175     }
1176 }
1177 
1178 static int
1179 xfs_dir3_data_block_free(
1180     xfs_da_args_t       *args,
1181     struct xfs_dir2_data_hdr *hdr,
1182     struct xfs_dir2_free    *free,
1183     xfs_dir2_db_t       fdb,
1184     int         findex,
1185     struct xfs_buf      *fbp,
1186     int         longest)
1187 {
1188     int         logfree = 0;
1189     struct xfs_dir3_icfree_hdr freehdr;
1190     struct xfs_inode    *dp = args->dp;
1191 
1192     xfs_dir2_free_hdr_from_disk(dp->i_mount, &freehdr, free);
1193     if (hdr) {
1194         /*
1195          * Data block is not empty, just set the free entry to the new
1196          * value.
1197          */
1198         freehdr.bests[findex] = cpu_to_be16(longest);
1199         xfs_dir2_free_log_bests(args, &freehdr, fbp, findex, findex);
1200         return 0;
1201     }
1202 
1203     /* One less used entry in the free table. */
1204     freehdr.nused--;
1205 
1206     /*
1207      * If this was the last entry in the table, we can trim the table size
1208      * back.  There might be other entries at the end referring to
1209      * non-existent data blocks, get those too.
1210      */
1211     if (findex == freehdr.nvalid - 1) {
1212         int i;      /* free entry index */
1213 
1214         for (i = findex - 1; i >= 0; i--) {
1215             if (freehdr.bests[i] != cpu_to_be16(NULLDATAOFF))
1216                 break;
1217         }
1218         freehdr.nvalid = i + 1;
1219         logfree = 0;
1220     } else {
1221         /* Not the last entry, just punch it out.  */
1222         freehdr.bests[findex] = cpu_to_be16(NULLDATAOFF);
1223         logfree = 1;
1224     }
1225 
1226     xfs_dir2_free_hdr_to_disk(dp->i_mount, free, &freehdr);
1227     xfs_dir2_free_log_header(args, fbp);
1228 
1229     /*
1230      * If there are no useful entries left in the block, get rid of the
1231      * block if we can.
1232      */
1233     if (!freehdr.nused) {
1234         int error;
1235 
1236         error = xfs_dir2_shrink_inode(args, fdb, fbp);
1237         if (error == 0) {
1238             fbp = NULL;
1239             logfree = 0;
1240         } else if (error != -ENOSPC || args->total != 0)
1241             return error;
1242         /*
1243          * It's possible to get ENOSPC if there is no
1244          * space reservation.  In this case some one
1245          * else will eventually get rid of this block.
1246          */
1247     }
1248 
1249     /* Log the free entry that changed, unless we got rid of it.  */
1250     if (logfree)
1251         xfs_dir2_free_log_bests(args, &freehdr, fbp, findex, findex);
1252     return 0;
1253 }
1254 
1255 /*
1256  * Remove an entry from a node directory.
1257  * This removes the leaf entry and the data entry,
1258  * and updates the free block if necessary.
1259  */
1260 static int                  /* error */
1261 xfs_dir2_leafn_remove(
1262     xfs_da_args_t       *args,      /* operation arguments */
1263     struct xfs_buf      *bp,        /* leaf buffer */
1264     int         index,      /* leaf entry index */
1265     xfs_da_state_blk_t  *dblk,      /* data block */
1266     int         *rval)      /* resulting block needs join */
1267 {
1268     struct xfs_da_geometry  *geo = args->geo;
1269     xfs_dir2_data_hdr_t *hdr;       /* data block header */
1270     xfs_dir2_db_t       db;     /* data block number */
1271     struct xfs_buf      *dbp;       /* data block buffer */
1272     xfs_dir2_data_entry_t   *dep;       /* data block entry */
1273     xfs_inode_t     *dp;        /* incore directory inode */
1274     xfs_dir2_leaf_t     *leaf;      /* leaf structure */
1275     xfs_dir2_leaf_entry_t   *lep;       /* leaf entry */
1276     int         longest;    /* longest data free entry */
1277     int         off;        /* data block entry offset */
1278     int         needlog;    /* need to log data header */
1279     int         needscan;   /* need to rescan data frees */
1280     xfs_trans_t     *tp;        /* transaction pointer */
1281     struct xfs_dir2_data_free *bf;      /* bestfree table */
1282     struct xfs_dir3_icleaf_hdr leafhdr;
1283 
1284     trace_xfs_dir2_leafn_remove(args, index);
1285 
1286     dp = args->dp;
1287     tp = args->trans;
1288     leaf = bp->b_addr;
1289     xfs_dir2_leaf_hdr_from_disk(dp->i_mount, &leafhdr, leaf);
1290 
1291     /*
1292      * Point to the entry we're removing.
1293      */
1294     lep = &leafhdr.ents[index];
1295 
1296     /*
1297      * Extract the data block and offset from the entry.
1298      */
1299     db = xfs_dir2_dataptr_to_db(geo, be32_to_cpu(lep->address));
1300     ASSERT(dblk->blkno == db);
1301     off = xfs_dir2_dataptr_to_off(geo, be32_to_cpu(lep->address));
1302     ASSERT(dblk->index == off);
1303 
1304     /*
1305      * Kill the leaf entry by marking it stale.
1306      * Log the leaf block changes.
1307      */
1308     leafhdr.stale++;
1309     xfs_dir2_leaf_hdr_to_disk(dp->i_mount, leaf, &leafhdr);
1310     xfs_dir3_leaf_log_header(args, bp);
1311 
1312     lep->address = cpu_to_be32(XFS_DIR2_NULL_DATAPTR);
1313     xfs_dir3_leaf_log_ents(args, &leafhdr, bp, index, index);
1314 
1315     /*
1316      * Make the data entry free.  Keep track of the longest freespace
1317      * in the data block in case it changes.
1318      */
1319     dbp = dblk->bp;
1320     hdr = dbp->b_addr;
1321     dep = (xfs_dir2_data_entry_t *)((char *)hdr + off);
1322     bf = xfs_dir2_data_bestfree_p(dp->i_mount, hdr);
1323     longest = be16_to_cpu(bf[0].length);
1324     needlog = needscan = 0;
1325     xfs_dir2_data_make_free(args, dbp, off,
1326         xfs_dir2_data_entsize(dp->i_mount, dep->namelen), &needlog,
1327         &needscan);
1328     /*
1329      * Rescan the data block freespaces for bestfree.
1330      * Log the data block header if needed.
1331      */
1332     if (needscan)
1333         xfs_dir2_data_freescan(dp->i_mount, hdr, &needlog);
1334     if (needlog)
1335         xfs_dir2_data_log_header(args, dbp);
1336     xfs_dir3_data_check(dp, dbp);
1337     /*
1338      * If the longest data block freespace changes, need to update
1339      * the corresponding freeblock entry.
1340      */
1341     if (longest < be16_to_cpu(bf[0].length)) {
1342         int     error;      /* error return value */
1343         struct xfs_buf  *fbp;       /* freeblock buffer */
1344         xfs_dir2_db_t   fdb;        /* freeblock block number */
1345         int     findex;     /* index in freeblock entries */
1346         xfs_dir2_free_t *free;      /* freeblock structure */
1347 
1348         /*
1349          * Convert the data block number to a free block,
1350          * read in the free block.
1351          */
1352         fdb = xfs_dir2_db_to_fdb(geo, db);
1353         error = xfs_dir2_free_read(tp, dp, xfs_dir2_db_to_da(geo, fdb),
1354                        &fbp);
1355         if (error)
1356             return error;
1357         free = fbp->b_addr;
1358 #ifdef DEBUG
1359     {
1360         struct xfs_dir3_icfree_hdr freehdr;
1361 
1362         xfs_dir2_free_hdr_from_disk(dp->i_mount, &freehdr, free);
1363         ASSERT(freehdr.firstdb == geo->free_max_bests *
1364             (fdb - xfs_dir2_byte_to_db(geo, XFS_DIR2_FREE_OFFSET)));
1365     }
1366 #endif
1367         /*
1368          * Calculate which entry we need to fix.
1369          */
1370         findex = xfs_dir2_db_to_fdindex(geo, db);
1371         longest = be16_to_cpu(bf[0].length);
1372         /*
1373          * If the data block is now empty we can get rid of it
1374          * (usually).
1375          */
1376         if (longest == geo->blksize - geo->data_entry_offset) {
1377             /*
1378              * Try to punch out the data block.
1379              */
1380             error = xfs_dir2_shrink_inode(args, db, dbp);
1381             if (error == 0) {
1382                 dblk->bp = NULL;
1383                 hdr = NULL;
1384             }
1385             /*
1386              * We can get ENOSPC if there's no space reservation.
1387              * In this case just drop the buffer and some one else
1388              * will eventually get rid of the empty block.
1389              */
1390             else if (!(error == -ENOSPC && args->total == 0))
1391                 return error;
1392         }
1393         /*
1394          * If we got rid of the data block, we can eliminate that entry
1395          * in the free block.
1396          */
1397         error = xfs_dir3_data_block_free(args, hdr, free,
1398                          fdb, findex, fbp, longest);
1399         if (error)
1400             return error;
1401     }
1402 
1403     xfs_dir3_leaf_check(dp, bp);
1404     /*
1405      * Return indication of whether this leaf block is empty enough
1406      * to justify trying to join it with a neighbor.
1407      */
1408     *rval = (geo->leaf_hdr_size +
1409          (uint)sizeof(leafhdr.ents) * (leafhdr.count - leafhdr.stale)) <
1410         geo->magicpct;
1411     return 0;
1412 }
1413 
1414 /*
1415  * Split the leaf entries in the old block into old and new blocks.
1416  */
1417 int                     /* error */
1418 xfs_dir2_leafn_split(
1419     xfs_da_state_t      *state,     /* btree cursor */
1420     xfs_da_state_blk_t  *oldblk,    /* original block */
1421     xfs_da_state_blk_t  *newblk)    /* newly created block */
1422 {
1423     xfs_da_args_t       *args;      /* operation arguments */
1424     xfs_dablk_t     blkno;      /* new leaf block number */
1425     int         error;      /* error return value */
1426     struct xfs_inode    *dp;
1427 
1428     /*
1429      * Allocate space for a new leaf node.
1430      */
1431     args = state->args;
1432     dp = args->dp;
1433     ASSERT(oldblk->magic == XFS_DIR2_LEAFN_MAGIC);
1434     error = xfs_da_grow_inode(args, &blkno);
1435     if (error) {
1436         return error;
1437     }
1438     /*
1439      * Initialize the new leaf block.
1440      */
1441     error = xfs_dir3_leaf_get_buf(args, xfs_dir2_da_to_db(args->geo, blkno),
1442                       &newblk->bp, XFS_DIR2_LEAFN_MAGIC);
1443     if (error)
1444         return error;
1445 
1446     newblk->blkno = blkno;
1447     newblk->magic = XFS_DIR2_LEAFN_MAGIC;
1448     /*
1449      * Rebalance the entries across the two leaves, link the new
1450      * block into the leaves.
1451      */
1452     xfs_dir2_leafn_rebalance(state, oldblk, newblk);
1453     error = xfs_da3_blk_link(state, oldblk, newblk);
1454     if (error) {
1455         return error;
1456     }
1457     /*
1458      * Insert the new entry in the correct block.
1459      */
1460     if (state->inleaf)
1461         error = xfs_dir2_leafn_add(oldblk->bp, args, oldblk->index);
1462     else
1463         error = xfs_dir2_leafn_add(newblk->bp, args, newblk->index);
1464     /*
1465      * Update last hashval in each block since we added the name.
1466      */
1467     oldblk->hashval = xfs_dir2_leaf_lasthash(dp, oldblk->bp, NULL);
1468     newblk->hashval = xfs_dir2_leaf_lasthash(dp, newblk->bp, NULL);
1469     xfs_dir3_leaf_check(dp, oldblk->bp);
1470     xfs_dir3_leaf_check(dp, newblk->bp);
1471     return error;
1472 }
1473 
1474 /*
1475  * Check a leaf block and its neighbors to see if the block should be
1476  * collapsed into one or the other neighbor.  Always keep the block
1477  * with the smaller block number.
1478  * If the current block is over 50% full, don't try to join it, return 0.
1479  * If the block is empty, fill in the state structure and return 2.
1480  * If it can be collapsed, fill in the state structure and return 1.
1481  * If nothing can be done, return 0.
1482  */
1483 int                     /* error */
1484 xfs_dir2_leafn_toosmall(
1485     xfs_da_state_t      *state,     /* btree cursor */
1486     int         *action)    /* resulting action to take */
1487 {
1488     xfs_da_state_blk_t  *blk;       /* leaf block */
1489     xfs_dablk_t     blkno;      /* leaf block number */
1490     struct xfs_buf      *bp;        /* leaf buffer */
1491     int         bytes;      /* bytes in use */
1492     int         count;      /* leaf live entry count */
1493     int         error;      /* error return value */
1494     int         forward;    /* sibling block direction */
1495     int         i;      /* sibling counter */
1496     xfs_dir2_leaf_t     *leaf;      /* leaf structure */
1497     int         rval;       /* result from path_shift */
1498     struct xfs_dir3_icleaf_hdr leafhdr;
1499     struct xfs_dir2_leaf_entry *ents;
1500     struct xfs_inode    *dp = state->args->dp;
1501 
1502     /*
1503      * Check for the degenerate case of the block being over 50% full.
1504      * If so, it's not worth even looking to see if we might be able
1505      * to coalesce with a sibling.
1506      */
1507     blk = &state->path.blk[state->path.active - 1];
1508     leaf = blk->bp->b_addr;
1509     xfs_dir2_leaf_hdr_from_disk(dp->i_mount, &leafhdr, leaf);
1510     ents = leafhdr.ents;
1511     xfs_dir3_leaf_check(dp, blk->bp);
1512 
1513     count = leafhdr.count - leafhdr.stale;
1514     bytes = state->args->geo->leaf_hdr_size + count * sizeof(ents[0]);
1515     if (bytes > (state->args->geo->blksize >> 1)) {
1516         /*
1517          * Blk over 50%, don't try to join.
1518          */
1519         *action = 0;
1520         return 0;
1521     }
1522     /*
1523      * Check for the degenerate case of the block being empty.
1524      * If the block is empty, we'll simply delete it, no need to
1525      * coalesce it with a sibling block.  We choose (arbitrarily)
1526      * to merge with the forward block unless it is NULL.
1527      */
1528     if (count == 0) {
1529         /*
1530          * Make altpath point to the block we want to keep and
1531          * path point to the block we want to drop (this one).
1532          */
1533         forward = (leafhdr.forw != 0);
1534         memcpy(&state->altpath, &state->path, sizeof(state->path));
1535         error = xfs_da3_path_shift(state, &state->altpath, forward, 0,
1536             &rval);
1537         if (error)
1538             return error;
1539         *action = rval ? 2 : 0;
1540         return 0;
1541     }
1542     /*
1543      * Examine each sibling block to see if we can coalesce with
1544      * at least 25% free space to spare.  We need to figure out
1545      * whether to merge with the forward or the backward block.
1546      * We prefer coalescing with the lower numbered sibling so as
1547      * to shrink a directory over time.
1548      */
1549     forward = leafhdr.forw < leafhdr.back;
1550     for (i = 0, bp = NULL; i < 2; forward = !forward, i++) {
1551         struct xfs_dir3_icleaf_hdr hdr2;
1552 
1553         blkno = forward ? leafhdr.forw : leafhdr.back;
1554         if (blkno == 0)
1555             continue;
1556         /*
1557          * Read the sibling leaf block.
1558          */
1559         error = xfs_dir3_leafn_read(state->args->trans, dp, blkno, &bp);
1560         if (error)
1561             return error;
1562 
1563         /*
1564          * Count bytes in the two blocks combined.
1565          */
1566         count = leafhdr.count - leafhdr.stale;
1567         bytes = state->args->geo->blksize -
1568             (state->args->geo->blksize >> 2);
1569 
1570         leaf = bp->b_addr;
1571         xfs_dir2_leaf_hdr_from_disk(dp->i_mount, &hdr2, leaf);
1572         ents = hdr2.ents;
1573         count += hdr2.count - hdr2.stale;
1574         bytes -= count * sizeof(ents[0]);
1575 
1576         /*
1577          * Fits with at least 25% to spare.
1578          */
1579         if (bytes >= 0)
1580             break;
1581         xfs_trans_brelse(state->args->trans, bp);
1582     }
1583     /*
1584      * Didn't like either block, give up.
1585      */
1586     if (i >= 2) {
1587         *action = 0;
1588         return 0;
1589     }
1590 
1591     /*
1592      * Make altpath point to the block we want to keep (the lower
1593      * numbered block) and path point to the block we want to drop.
1594      */
1595     memcpy(&state->altpath, &state->path, sizeof(state->path));
1596     if (blkno < blk->blkno)
1597         error = xfs_da3_path_shift(state, &state->altpath, forward, 0,
1598             &rval);
1599     else
1600         error = xfs_da3_path_shift(state, &state->path, forward, 0,
1601             &rval);
1602     if (error) {
1603         return error;
1604     }
1605     *action = rval ? 0 : 1;
1606     return 0;
1607 }
1608 
1609 /*
1610  * Move all the leaf entries from drop_blk to save_blk.
1611  * This is done as part of a join operation.
1612  */
1613 void
1614 xfs_dir2_leafn_unbalance(
1615     xfs_da_state_t      *state,     /* cursor */
1616     xfs_da_state_blk_t  *drop_blk,  /* dead block */
1617     xfs_da_state_blk_t  *save_blk)  /* surviving block */
1618 {
1619     xfs_da_args_t       *args;      /* operation arguments */
1620     xfs_dir2_leaf_t     *drop_leaf; /* dead leaf structure */
1621     xfs_dir2_leaf_t     *save_leaf; /* surviving leaf structure */
1622     struct xfs_dir3_icleaf_hdr savehdr;
1623     struct xfs_dir3_icleaf_hdr drophdr;
1624     struct xfs_dir2_leaf_entry *sents;
1625     struct xfs_dir2_leaf_entry *dents;
1626     struct xfs_inode    *dp = state->args->dp;
1627 
1628     args = state->args;
1629     ASSERT(drop_blk->magic == XFS_DIR2_LEAFN_MAGIC);
1630     ASSERT(save_blk->magic == XFS_DIR2_LEAFN_MAGIC);
1631     drop_leaf = drop_blk->bp->b_addr;
1632     save_leaf = save_blk->bp->b_addr;
1633 
1634     xfs_dir2_leaf_hdr_from_disk(dp->i_mount, &savehdr, save_leaf);
1635     xfs_dir2_leaf_hdr_from_disk(dp->i_mount, &drophdr, drop_leaf);
1636     sents = savehdr.ents;
1637     dents = drophdr.ents;
1638 
1639     /*
1640      * If there are any stale leaf entries, take this opportunity
1641      * to purge them.
1642      */
1643     if (drophdr.stale)
1644         xfs_dir3_leaf_compact(args, &drophdr, drop_blk->bp);
1645     if (savehdr.stale)
1646         xfs_dir3_leaf_compact(args, &savehdr, save_blk->bp);
1647 
1648     /*
1649      * Move the entries from drop to the appropriate end of save.
1650      */
1651     drop_blk->hashval = be32_to_cpu(dents[drophdr.count - 1].hashval);
1652     if (xfs_dir2_leafn_order(dp, save_blk->bp, drop_blk->bp))
1653         xfs_dir3_leafn_moveents(args, drop_blk->bp, &drophdr, dents, 0,
1654                     save_blk->bp, &savehdr, sents, 0,
1655                     drophdr.count);
1656     else
1657         xfs_dir3_leafn_moveents(args, drop_blk->bp, &drophdr, dents, 0,
1658                     save_blk->bp, &savehdr, sents,
1659                     savehdr.count, drophdr.count);
1660     save_blk->hashval = be32_to_cpu(sents[savehdr.count - 1].hashval);
1661 
1662     /* log the changes made when moving the entries */
1663     xfs_dir2_leaf_hdr_to_disk(dp->i_mount, save_leaf, &savehdr);
1664     xfs_dir2_leaf_hdr_to_disk(dp->i_mount, drop_leaf, &drophdr);
1665     xfs_dir3_leaf_log_header(args, save_blk->bp);
1666     xfs_dir3_leaf_log_header(args, drop_blk->bp);
1667 
1668     xfs_dir3_leaf_check(dp, save_blk->bp);
1669     xfs_dir3_leaf_check(dp, drop_blk->bp);
1670 }
1671 
1672 /*
1673  * Add a new data block to the directory at the free space index that the caller
1674  * has specified.
1675  */
1676 static int
1677 xfs_dir2_node_add_datablk(
1678     struct xfs_da_args  *args,
1679     struct xfs_da_state_blk *fblk,
1680     xfs_dir2_db_t       *dbno,
1681     struct xfs_buf      **dbpp,
1682     struct xfs_buf      **fbpp,
1683     struct xfs_dir3_icfree_hdr *hdr,
1684     int         *findex)
1685 {
1686     struct xfs_inode    *dp = args->dp;
1687     struct xfs_trans    *tp = args->trans;
1688     struct xfs_mount    *mp = dp->i_mount;
1689     struct xfs_dir2_data_free *bf;
1690     xfs_dir2_db_t       fbno;
1691     struct xfs_buf      *fbp;
1692     struct xfs_buf      *dbp;
1693     int         error;
1694 
1695     /* Not allowed to allocate, return failure. */
1696     if (args->total == 0)
1697         return -ENOSPC;
1698 
1699     /* Allocate and initialize the new data block.  */
1700     error = xfs_dir2_grow_inode(args, XFS_DIR2_DATA_SPACE, dbno);
1701     if (error)
1702         return error;
1703     error = xfs_dir3_data_init(args, *dbno, &dbp);
1704     if (error)
1705         return error;
1706 
1707     /*
1708      * Get the freespace block corresponding to the data block
1709      * that was just allocated.
1710      */
1711     fbno = xfs_dir2_db_to_fdb(args->geo, *dbno);
1712     error = xfs_dir2_free_try_read(tp, dp,
1713                    xfs_dir2_db_to_da(args->geo, fbno), &fbp);
1714     if (error)
1715         return error;
1716 
1717     /*
1718      * If there wasn't a freespace block, the read will
1719      * return a NULL fbp.  Allocate and initialize a new one.
1720      */
1721     if (!fbp) {
1722         error = xfs_dir2_grow_inode(args, XFS_DIR2_FREE_SPACE, &fbno);
1723         if (error)
1724             return error;
1725 
1726         if (XFS_IS_CORRUPT(mp,
1727                    xfs_dir2_db_to_fdb(args->geo, *dbno) !=
1728                    fbno)) {
1729             xfs_alert(mp,
1730 "%s: dir ino %llu needed freesp block %lld for data block %lld, got %lld",
1731                 __func__, (unsigned long long)dp->i_ino,
1732                 (long long)xfs_dir2_db_to_fdb(args->geo, *dbno),
1733                 (long long)*dbno, (long long)fbno);
1734             if (fblk) {
1735                 xfs_alert(mp,
1736             " fblk "PTR_FMT" blkno %llu index %d magic 0x%x",
1737                     fblk, (unsigned long long)fblk->blkno,
1738                     fblk->index, fblk->magic);
1739             } else {
1740                 xfs_alert(mp, " ... fblk is NULL");
1741             }
1742             return -EFSCORRUPTED;
1743         }
1744 
1745         /* Get a buffer for the new block. */
1746         error = xfs_dir3_free_get_buf(args, fbno, &fbp);
1747         if (error)
1748             return error;
1749         xfs_dir2_free_hdr_from_disk(mp, hdr, fbp->b_addr);
1750 
1751         /* Remember the first slot as our empty slot. */
1752         hdr->firstdb = (fbno - xfs_dir2_byte_to_db(args->geo,
1753                             XFS_DIR2_FREE_OFFSET)) *
1754                 args->geo->free_max_bests;
1755     } else {
1756         xfs_dir2_free_hdr_from_disk(mp, hdr, fbp->b_addr);
1757     }
1758 
1759     /* Set the freespace block index from the data block number. */
1760     *findex = xfs_dir2_db_to_fdindex(args->geo, *dbno);
1761 
1762     /* Extend the freespace table if the new data block is off the end. */
1763     if (*findex >= hdr->nvalid) {
1764         ASSERT(*findex < args->geo->free_max_bests);
1765         hdr->nvalid = *findex + 1;
1766         hdr->bests[*findex] = cpu_to_be16(NULLDATAOFF);
1767     }
1768 
1769     /*
1770      * If this entry was for an empty data block (this should always be
1771      * true) then update the header.
1772      */
1773     if (hdr->bests[*findex] == cpu_to_be16(NULLDATAOFF)) {
1774         hdr->nused++;
1775         xfs_dir2_free_hdr_to_disk(mp, fbp->b_addr, hdr);
1776         xfs_dir2_free_log_header(args, fbp);
1777     }
1778 
1779     /* Update the freespace value for the new block in the table. */
1780     bf = xfs_dir2_data_bestfree_p(mp, dbp->b_addr);
1781     hdr->bests[*findex] = bf[0].length;
1782 
1783     *dbpp = dbp;
1784     *fbpp = fbp;
1785     return 0;
1786 }
1787 
1788 static int
1789 xfs_dir2_node_find_freeblk(
1790     struct xfs_da_args  *args,
1791     struct xfs_da_state_blk *fblk,
1792     xfs_dir2_db_t       *dbnop,
1793     struct xfs_buf      **fbpp,
1794     struct xfs_dir3_icfree_hdr *hdr,
1795     int         *findexp,
1796     int         length)
1797 {
1798     struct xfs_inode    *dp = args->dp;
1799     struct xfs_trans    *tp = args->trans;
1800     struct xfs_buf      *fbp = NULL;
1801     xfs_dir2_db_t       firstfbno;
1802     xfs_dir2_db_t       lastfbno;
1803     xfs_dir2_db_t       ifbno = -1;
1804     xfs_dir2_db_t       dbno = -1;
1805     xfs_dir2_db_t       fbno;
1806     xfs_fileoff_t       fo;
1807     int         findex = 0;
1808     int         error;
1809 
1810     /*
1811      * If we came in with a freespace block that means that lookup
1812      * found an entry with our hash value.  This is the freespace
1813      * block for that data entry.
1814      */
1815     if (fblk) {
1816         fbp = fblk->bp;
1817         findex = fblk->index;
1818         xfs_dir2_free_hdr_from_disk(dp->i_mount, hdr, fbp->b_addr);
1819         if (findex >= 0) {
1820             /* caller already found the freespace for us. */
1821             ASSERT(findex < hdr->nvalid);
1822             ASSERT(be16_to_cpu(hdr->bests[findex]) != NULLDATAOFF);
1823             ASSERT(be16_to_cpu(hdr->bests[findex]) >= length);
1824             dbno = hdr->firstdb + findex;
1825             goto found_block;
1826         }
1827 
1828         /*
1829          * The data block looked at didn't have enough room.
1830          * We'll start at the beginning of the freespace entries.
1831          */
1832         ifbno = fblk->blkno;
1833         xfs_trans_brelse(tp, fbp);
1834         fbp = NULL;
1835         fblk->bp = NULL;
1836     }
1837 
1838     /*
1839      * If we don't have a data block yet, we're going to scan the freespace
1840      * data for a data block with enough free space in it.
1841      */
1842     error = xfs_bmap_last_offset(dp, &fo, XFS_DATA_FORK);
1843     if (error)
1844         return error;
1845     lastfbno = xfs_dir2_da_to_db(args->geo, (xfs_dablk_t)fo);
1846     firstfbno = xfs_dir2_byte_to_db(args->geo, XFS_DIR2_FREE_OFFSET);
1847 
1848     for (fbno = lastfbno - 1; fbno >= firstfbno; fbno--) {
1849         /* If it's ifbno we already looked at it. */
1850         if (fbno == ifbno)
1851             continue;
1852 
1853         /*
1854          * Read the block.  There can be holes in the freespace blocks,
1855          * so this might not succeed.  This should be really rare, so
1856          * there's no reason to avoid it.
1857          */
1858         error = xfs_dir2_free_try_read(tp, dp,
1859                 xfs_dir2_db_to_da(args->geo, fbno),
1860                 &fbp);
1861         if (error)
1862             return error;
1863         if (!fbp)
1864             continue;
1865 
1866         xfs_dir2_free_hdr_from_disk(dp->i_mount, hdr, fbp->b_addr);
1867 
1868         /* Scan the free entry array for a large enough free space. */
1869         for (findex = hdr->nvalid - 1; findex >= 0; findex--) {
1870             if (be16_to_cpu(hdr->bests[findex]) != NULLDATAOFF &&
1871                 be16_to_cpu(hdr->bests[findex]) >= length) {
1872                 dbno = hdr->firstdb + findex;
1873                 goto found_block;
1874             }
1875         }
1876 
1877         /* Didn't find free space, go on to next free block */
1878         xfs_trans_brelse(tp, fbp);
1879     }
1880 
1881 found_block:
1882     *dbnop = dbno;
1883     *fbpp = fbp;
1884     *findexp = findex;
1885     return 0;
1886 }
1887 
1888 /*
1889  * Add the data entry for a node-format directory name addition.
1890  * The leaf entry is added in xfs_dir2_leafn_add.
1891  * We may enter with a freespace block that the lookup found.
1892  */
1893 static int
1894 xfs_dir2_node_addname_int(
1895     struct xfs_da_args  *args,      /* operation arguments */
1896     struct xfs_da_state_blk *fblk)      /* optional freespace block */
1897 {
1898     struct xfs_dir2_data_unused *dup;   /* data unused entry pointer */
1899     struct xfs_dir2_data_entry *dep;    /* data entry pointer */
1900     struct xfs_dir2_data_hdr *hdr;      /* data block header */
1901     struct xfs_dir2_data_free *bf;
1902     struct xfs_trans    *tp = args->trans;
1903     struct xfs_inode    *dp = args->dp;
1904     struct xfs_dir3_icfree_hdr freehdr;
1905     struct xfs_buf      *dbp;       /* data block buffer */
1906     struct xfs_buf      *fbp;       /* freespace buffer */
1907     xfs_dir2_data_aoff_t    aoff;
1908     xfs_dir2_db_t       dbno;       /* data block number */
1909     int         error;      /* error return value */
1910     int         findex;     /* freespace entry index */
1911     int         length;     /* length of the new entry */
1912     int         logfree = 0;    /* need to log free entry */
1913     int         needlog = 0;    /* need to log data header */
1914     int         needscan = 0;   /* need to rescan data frees */
1915     __be16          *tagp;      /* data entry tag pointer */
1916 
1917     length = xfs_dir2_data_entsize(dp->i_mount, args->namelen);
1918     error = xfs_dir2_node_find_freeblk(args, fblk, &dbno, &fbp, &freehdr,
1919                        &findex, length);
1920     if (error)
1921         return error;
1922 
1923     /*
1924      * Now we know if we must allocate blocks, so if we are checking whether
1925      * we can insert without allocation then we can return now.
1926      */
1927     if (args->op_flags & XFS_DA_OP_JUSTCHECK) {
1928         if (dbno == -1)
1929             return -ENOSPC;
1930         return 0;
1931     }
1932 
1933     /*
1934      * If we don't have a data block, we need to allocate one and make
1935      * the freespace entries refer to it.
1936      */
1937     if (dbno == -1) {
1938         /* we're going to have to log the free block index later */
1939         logfree = 1;
1940         error = xfs_dir2_node_add_datablk(args, fblk, &dbno, &dbp, &fbp,
1941                           &freehdr, &findex);
1942     } else {
1943         /* Read the data block in. */
1944         error = xfs_dir3_data_read(tp, dp,
1945                        xfs_dir2_db_to_da(args->geo, dbno),
1946                        0, &dbp);
1947     }
1948     if (error)
1949         return error;
1950 
1951     /* setup for data block up now */
1952     hdr = dbp->b_addr;
1953     bf = xfs_dir2_data_bestfree_p(dp->i_mount, hdr);
1954     ASSERT(be16_to_cpu(bf[0].length) >= length);
1955 
1956     /* Point to the existing unused space. */
1957     dup = (xfs_dir2_data_unused_t *)
1958           ((char *)hdr + be16_to_cpu(bf[0].offset));
1959 
1960     /* Mark the first part of the unused space, inuse for us. */
1961     aoff = (xfs_dir2_data_aoff_t)((char *)dup - (char *)hdr);
1962     error = xfs_dir2_data_use_free(args, dbp, dup, aoff, length,
1963             &needlog, &needscan);
1964     if (error) {
1965         xfs_trans_brelse(tp, dbp);
1966         return error;
1967     }
1968 
1969     /* Fill in the new entry and log it. */
1970     dep = (xfs_dir2_data_entry_t *)dup;
1971     dep->inumber = cpu_to_be64(args->inumber);
1972     dep->namelen = args->namelen;
1973     memcpy(dep->name, args->name, dep->namelen);
1974     xfs_dir2_data_put_ftype(dp->i_mount, dep, args->filetype);
1975     tagp = xfs_dir2_data_entry_tag_p(dp->i_mount, dep);
1976     *tagp = cpu_to_be16((char *)dep - (char *)hdr);
1977     xfs_dir2_data_log_entry(args, dbp, dep);
1978 
1979     /* Rescan the freespace and log the data block if needed. */
1980     if (needscan)
1981         xfs_dir2_data_freescan(dp->i_mount, hdr, &needlog);
1982     if (needlog)
1983         xfs_dir2_data_log_header(args, dbp);
1984 
1985     /* If the freespace block entry is now wrong, update it. */
1986     if (freehdr.bests[findex] != bf[0].length) {
1987         freehdr.bests[findex] = bf[0].length;
1988         logfree = 1;
1989     }
1990 
1991     /* Log the freespace entry if needed. */
1992     if (logfree)
1993         xfs_dir2_free_log_bests(args, &freehdr, fbp, findex, findex);
1994 
1995     /* Return the data block and offset in args. */
1996     args->blkno = (xfs_dablk_t)dbno;
1997     args->index = be16_to_cpu(*tagp);
1998     return 0;
1999 }
2000 
2001 /*
2002  * Top-level node form directory addname routine.
2003  */
2004 int                     /* error */
2005 xfs_dir2_node_addname(
2006     xfs_da_args_t       *args)      /* operation arguments */
2007 {
2008     xfs_da_state_blk_t  *blk;       /* leaf block for insert */
2009     int         error;      /* error return value */
2010     int         rval;       /* sub-return value */
2011     xfs_da_state_t      *state;     /* btree cursor */
2012 
2013     trace_xfs_dir2_node_addname(args);
2014 
2015     /*
2016      * Allocate and initialize the state (btree cursor).
2017      */
2018     state = xfs_da_state_alloc(args);
2019     /*
2020      * Look up the name.  We're not supposed to find it, but
2021      * this gives us the insertion point.
2022      */
2023     error = xfs_da3_node_lookup_int(state, &rval);
2024     if (error)
2025         rval = error;
2026     if (rval != -ENOENT) {
2027         goto done;
2028     }
2029     /*
2030      * Add the data entry to a data block.
2031      * Extravalid is set to a freeblock found by lookup.
2032      */
2033     rval = xfs_dir2_node_addname_int(args,
2034         state->extravalid ? &state->extrablk : NULL);
2035     if (rval) {
2036         goto done;
2037     }
2038     blk = &state->path.blk[state->path.active - 1];
2039     ASSERT(blk->magic == XFS_DIR2_LEAFN_MAGIC);
2040     /*
2041      * Add the new leaf entry.
2042      */
2043     rval = xfs_dir2_leafn_add(blk->bp, args, blk->index);
2044     if (rval == 0) {
2045         /*
2046          * It worked, fix the hash values up the btree.
2047          */
2048         if (!(args->op_flags & XFS_DA_OP_JUSTCHECK))
2049             xfs_da3_fixhashpath(state, &state->path);
2050     } else {
2051         /*
2052          * It didn't work, we need to split the leaf block.
2053          */
2054         if (args->total == 0) {
2055             ASSERT(rval == -ENOSPC);
2056             goto done;
2057         }
2058         /*
2059          * Split the leaf block and insert the new entry.
2060          */
2061         rval = xfs_da3_split(state);
2062     }
2063 done:
2064     xfs_da_state_free(state);
2065     return rval;
2066 }
2067 
2068 /*
2069  * Lookup an entry in a node-format directory.
2070  * All the real work happens in xfs_da3_node_lookup_int.
2071  * The only real output is the inode number of the entry.
2072  */
2073 int                     /* error */
2074 xfs_dir2_node_lookup(
2075     xfs_da_args_t   *args)          /* operation arguments */
2076 {
2077     int     error;          /* error return value */
2078     int     i;          /* btree level */
2079     int     rval;           /* operation return value */
2080     xfs_da_state_t  *state;         /* btree cursor */
2081 
2082     trace_xfs_dir2_node_lookup(args);
2083 
2084     /*
2085      * Allocate and initialize the btree cursor.
2086      */
2087     state = xfs_da_state_alloc(args);
2088 
2089     /*
2090      * Fill in the path to the entry in the cursor.
2091      */
2092     error = xfs_da3_node_lookup_int(state, &rval);
2093     if (error)
2094         rval = error;
2095     else if (rval == -ENOENT && args->cmpresult == XFS_CMP_CASE) {
2096         /* If a CI match, dup the actual name and return -EEXIST */
2097         xfs_dir2_data_entry_t   *dep;
2098 
2099         dep = (xfs_dir2_data_entry_t *)
2100             ((char *)state->extrablk.bp->b_addr +
2101                          state->extrablk.index);
2102         rval = xfs_dir_cilookup_result(args, dep->name, dep->namelen);
2103     }
2104     /*
2105      * Release the btree blocks and leaf block.
2106      */
2107     for (i = 0; i < state->path.active; i++) {
2108         xfs_trans_brelse(args->trans, state->path.blk[i].bp);
2109         state->path.blk[i].bp = NULL;
2110     }
2111     /*
2112      * Release the data block if we have it.
2113      */
2114     if (state->extravalid && state->extrablk.bp) {
2115         xfs_trans_brelse(args->trans, state->extrablk.bp);
2116         state->extrablk.bp = NULL;
2117     }
2118     xfs_da_state_free(state);
2119     return rval;
2120 }
2121 
2122 /*
2123  * Remove an entry from a node-format directory.
2124  */
2125 int                     /* error */
2126 xfs_dir2_node_removename(
2127     struct xfs_da_args  *args)      /* operation arguments */
2128 {
2129     struct xfs_da_state_blk *blk;       /* leaf block */
2130     int         error;      /* error return value */
2131     int         rval;       /* operation return value */
2132     struct xfs_da_state *state;     /* btree cursor */
2133 
2134     trace_xfs_dir2_node_removename(args);
2135 
2136     /*
2137      * Allocate and initialize the btree cursor.
2138      */
2139     state = xfs_da_state_alloc(args);
2140 
2141     /* Look up the entry we're deleting, set up the cursor. */
2142     error = xfs_da3_node_lookup_int(state, &rval);
2143     if (error)
2144         goto out_free;
2145 
2146     /* Didn't find it, upper layer screwed up. */
2147     if (rval != -EEXIST) {
2148         error = rval;
2149         goto out_free;
2150     }
2151 
2152     blk = &state->path.blk[state->path.active - 1];
2153     ASSERT(blk->magic == XFS_DIR2_LEAFN_MAGIC);
2154     ASSERT(state->extravalid);
2155     /*
2156      * Remove the leaf and data entries.
2157      * Extrablk refers to the data block.
2158      */
2159     error = xfs_dir2_leafn_remove(args, blk->bp, blk->index,
2160         &state->extrablk, &rval);
2161     if (error)
2162         goto out_free;
2163     /*
2164      * Fix the hash values up the btree.
2165      */
2166     xfs_da3_fixhashpath(state, &state->path);
2167     /*
2168      * If we need to join leaf blocks, do it.
2169      */
2170     if (rval && state->path.active > 1)
2171         error = xfs_da3_join(state);
2172     /*
2173      * If no errors so far, try conversion to leaf format.
2174      */
2175     if (!error)
2176         error = xfs_dir2_node_to_leaf(state);
2177 out_free:
2178     xfs_da_state_free(state);
2179     return error;
2180 }
2181 
2182 /*
2183  * Replace an entry's inode number in a node-format directory.
2184  */
2185 int                     /* error */
2186 xfs_dir2_node_replace(
2187     xfs_da_args_t       *args)      /* operation arguments */
2188 {
2189     xfs_da_state_blk_t  *blk;       /* leaf block */
2190     xfs_dir2_data_hdr_t *hdr;       /* data block header */
2191     xfs_dir2_data_entry_t   *dep;       /* data entry changed */
2192     int         error;      /* error return value */
2193     int         i;      /* btree level */
2194     xfs_ino_t       inum;       /* new inode number */
2195     int         ftype;      /* new file type */
2196     int         rval;       /* internal return value */
2197     xfs_da_state_t      *state;     /* btree cursor */
2198 
2199     trace_xfs_dir2_node_replace(args);
2200 
2201     /*
2202      * Allocate and initialize the btree cursor.
2203      */
2204     state = xfs_da_state_alloc(args);
2205 
2206     /*
2207      * We have to save new inode number and ftype since
2208      * xfs_da3_node_lookup_int() is going to overwrite them
2209      */
2210     inum = args->inumber;
2211     ftype = args->filetype;
2212 
2213     /*
2214      * Lookup the entry to change in the btree.
2215      */
2216     error = xfs_da3_node_lookup_int(state, &rval);
2217     if (error) {
2218         rval = error;
2219     }
2220     /*
2221      * It should be found, since the vnodeops layer has looked it up
2222      * and locked it.  But paranoia is good.
2223      */
2224     if (rval == -EEXIST) {
2225         struct xfs_dir3_icleaf_hdr  leafhdr;
2226 
2227         /*
2228          * Find the leaf entry.
2229          */
2230         blk = &state->path.blk[state->path.active - 1];
2231         ASSERT(blk->magic == XFS_DIR2_LEAFN_MAGIC);
2232         ASSERT(state->extravalid);
2233 
2234         xfs_dir2_leaf_hdr_from_disk(state->mp, &leafhdr,
2235                         blk->bp->b_addr);
2236         /*
2237          * Point to the data entry.
2238          */
2239         hdr = state->extrablk.bp->b_addr;
2240         ASSERT(hdr->magic == cpu_to_be32(XFS_DIR2_DATA_MAGIC) ||
2241                hdr->magic == cpu_to_be32(XFS_DIR3_DATA_MAGIC));
2242         dep = (xfs_dir2_data_entry_t *)
2243               ((char *)hdr +
2244                xfs_dir2_dataptr_to_off(args->geo,
2245                 be32_to_cpu(leafhdr.ents[blk->index].address)));
2246         ASSERT(inum != be64_to_cpu(dep->inumber));
2247         /*
2248          * Fill in the new inode number and log the entry.
2249          */
2250         dep->inumber = cpu_to_be64(inum);
2251         xfs_dir2_data_put_ftype(state->mp, dep, ftype);
2252         xfs_dir2_data_log_entry(args, state->extrablk.bp, dep);
2253         rval = 0;
2254     }
2255     /*
2256      * Didn't find it, and we're holding a data block.  Drop it.
2257      */
2258     else if (state->extravalid) {
2259         xfs_trans_brelse(args->trans, state->extrablk.bp);
2260         state->extrablk.bp = NULL;
2261     }
2262     /*
2263      * Release all the buffers in the cursor.
2264      */
2265     for (i = 0; i < state->path.active; i++) {
2266         xfs_trans_brelse(args->trans, state->path.blk[i].bp);
2267         state->path.blk[i].bp = NULL;
2268     }
2269     xfs_da_state_free(state);
2270     return rval;
2271 }
2272 
2273 /*
2274  * Trim off a trailing empty freespace block.
2275  * Return (in rvalp) 1 if we did it, 0 if not.
2276  */
2277 int                     /* error */
2278 xfs_dir2_node_trim_free(
2279     xfs_da_args_t       *args,      /* operation arguments */
2280     xfs_fileoff_t       fo,     /* free block number */
2281     int         *rvalp)     /* out: did something */
2282 {
2283     struct xfs_buf      *bp;        /* freespace buffer */
2284     xfs_inode_t     *dp;        /* incore directory inode */
2285     int         error;      /* error return code */
2286     xfs_dir2_free_t     *free;      /* freespace structure */
2287     xfs_trans_t     *tp;        /* transaction pointer */
2288     struct xfs_dir3_icfree_hdr freehdr;
2289 
2290     dp = args->dp;
2291     tp = args->trans;
2292 
2293     *rvalp = 0;
2294 
2295     /*
2296      * Read the freespace block.
2297      */
2298     error = xfs_dir2_free_try_read(tp, dp, fo, &bp);
2299     if (error)
2300         return error;
2301     /*
2302      * There can be holes in freespace.  If fo is a hole, there's
2303      * nothing to do.
2304      */
2305     if (!bp)
2306         return 0;
2307     free = bp->b_addr;
2308     xfs_dir2_free_hdr_from_disk(dp->i_mount, &freehdr, free);
2309 
2310     /*
2311      * If there are used entries, there's nothing to do.
2312      */
2313     if (freehdr.nused > 0) {
2314         xfs_trans_brelse(tp, bp);
2315         return 0;
2316     }
2317     /*
2318      * Blow the block away.
2319      */
2320     error = xfs_dir2_shrink_inode(args,
2321             xfs_dir2_da_to_db(args->geo, (xfs_dablk_t)fo), bp);
2322     if (error) {
2323         /*
2324          * Can't fail with ENOSPC since that only happens with no
2325          * space reservation, when breaking up an extent into two
2326          * pieces.  This is the last block of an extent.
2327          */
2328         ASSERT(error != -ENOSPC);
2329         xfs_trans_brelse(tp, bp);
2330         return error;
2331     }
2332     /*
2333      * Return that we succeeded.
2334      */
2335     *rvalp = 1;
2336     return 0;
2337 }