GNU Linux-libre 4.14.266-gnu1
[releases.git] / fs / xfs / libxfs / xfs_dir2_node.c
1 /*
2  * Copyright (c) 2000-2005 Silicon Graphics, Inc.
3  * Copyright (c) 2013 Red Hat, Inc.
4  * All Rights Reserved.
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License as
8  * published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it would be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write the Free Software Foundation,
17  * Inc.,  51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
18  */
19 #include "xfs.h"
20 #include "xfs_fs.h"
21 #include "xfs_format.h"
22 #include "xfs_log_format.h"
23 #include "xfs_trans_resv.h"
24 #include "xfs_mount.h"
25 #include "xfs_da_format.h"
26 #include "xfs_da_btree.h"
27 #include "xfs_inode.h"
28 #include "xfs_bmap.h"
29 #include "xfs_dir2.h"
30 #include "xfs_dir2_priv.h"
31 #include "xfs_error.h"
32 #include "xfs_trace.h"
33 #include "xfs_trans.h"
34 #include "xfs_buf_item.h"
35 #include "xfs_cksum.h"
36 #include "xfs_log.h"
37
38 /*
39  * Function declarations.
40  */
41 static int xfs_dir2_leafn_add(struct xfs_buf *bp, xfs_da_args_t *args,
42                               int index);
43 static void xfs_dir2_leafn_rebalance(xfs_da_state_t *state,
44                                      xfs_da_state_blk_t *blk1,
45                                      xfs_da_state_blk_t *blk2);
46 static int xfs_dir2_leafn_remove(xfs_da_args_t *args, struct xfs_buf *bp,
47                                  int index, xfs_da_state_blk_t *dblk,
48                                  int *rval);
49 static int xfs_dir2_node_addname_int(xfs_da_args_t *args,
50                                      xfs_da_state_blk_t *fblk);
51
52 /*
53  * Check internal consistency of a leafn block.
54  */
55 #ifdef DEBUG
56 #define xfs_dir3_leaf_check(dp, bp) \
57 do { \
58         if (!xfs_dir3_leafn_check((dp), (bp))) \
59                 ASSERT(0); \
60 } while (0);
61
62 static bool
63 xfs_dir3_leafn_check(
64         struct xfs_inode        *dp,
65         struct xfs_buf          *bp)
66 {
67         struct xfs_dir2_leaf    *leaf = bp->b_addr;
68         struct xfs_dir3_icleaf_hdr leafhdr;
69
70         dp->d_ops->leaf_hdr_from_disk(&leafhdr, leaf);
71
72         if (leafhdr.magic == XFS_DIR3_LEAFN_MAGIC) {
73                 struct xfs_dir3_leaf_hdr *leaf3 = bp->b_addr;
74                 if (be64_to_cpu(leaf3->info.blkno) != bp->b_bn)
75                         return false;
76         } else if (leafhdr.magic != XFS_DIR2_LEAFN_MAGIC)
77                 return false;
78
79         return xfs_dir3_leaf_check_int(dp->i_mount, dp, &leafhdr, leaf);
80 }
81 #else
82 #define xfs_dir3_leaf_check(dp, bp)
83 #endif
84
85 static bool
86 xfs_dir3_free_verify(
87         struct xfs_buf          *bp)
88 {
89         struct xfs_mount        *mp = bp->b_target->bt_mount;
90         struct xfs_dir2_free_hdr *hdr = bp->b_addr;
91
92         if (xfs_sb_version_hascrc(&mp->m_sb)) {
93                 struct xfs_dir3_blk_hdr *hdr3 = bp->b_addr;
94
95                 if (hdr3->magic != cpu_to_be32(XFS_DIR3_FREE_MAGIC))
96                         return false;
97                 if (!uuid_equal(&hdr3->uuid, &mp->m_sb.sb_meta_uuid))
98                         return false;
99                 if (be64_to_cpu(hdr3->blkno) != bp->b_bn)
100                         return false;
101                 if (!xfs_log_check_lsn(mp, be64_to_cpu(hdr3->lsn)))
102                         return false;
103         } else {
104                 if (hdr->magic != cpu_to_be32(XFS_DIR2_FREE_MAGIC))
105                         return false;
106         }
107
108         /* XXX: should bounds check the xfs_dir3_icfree_hdr here */
109
110         return true;
111 }
112
113 static void
114 xfs_dir3_free_read_verify(
115         struct xfs_buf  *bp)
116 {
117         struct xfs_mount        *mp = bp->b_target->bt_mount;
118
119         if (xfs_sb_version_hascrc(&mp->m_sb) &&
120             !xfs_buf_verify_cksum(bp, XFS_DIR3_FREE_CRC_OFF))
121                 xfs_buf_ioerror(bp, -EFSBADCRC);
122         else if (!xfs_dir3_free_verify(bp))
123                 xfs_buf_ioerror(bp, -EFSCORRUPTED);
124
125         if (bp->b_error)
126                 xfs_verifier_error(bp);
127 }
128
129 static void
130 xfs_dir3_free_write_verify(
131         struct xfs_buf  *bp)
132 {
133         struct xfs_mount        *mp = bp->b_target->bt_mount;
134         struct xfs_buf_log_item *bip = bp->b_fspriv;
135         struct xfs_dir3_blk_hdr *hdr3 = bp->b_addr;
136
137         if (!xfs_dir3_free_verify(bp)) {
138                 xfs_buf_ioerror(bp, -EFSCORRUPTED);
139                 xfs_verifier_error(bp);
140                 return;
141         }
142
143         if (!xfs_sb_version_hascrc(&mp->m_sb))
144                 return;
145
146         if (bip)
147                 hdr3->lsn = cpu_to_be64(bip->bli_item.li_lsn);
148
149         xfs_buf_update_cksum(bp, XFS_DIR3_FREE_CRC_OFF);
150 }
151
152 const struct xfs_buf_ops xfs_dir3_free_buf_ops = {
153         .name = "xfs_dir3_free",
154         .verify_read = xfs_dir3_free_read_verify,
155         .verify_write = xfs_dir3_free_write_verify,
156 };
157
158 /* Everything ok in the free block header? */
159 static bool
160 xfs_dir3_free_header_check(
161         struct xfs_inode        *dp,
162         xfs_dablk_t             fbno,
163         struct xfs_buf          *bp)
164 {
165         struct xfs_mount        *mp = dp->i_mount;
166         unsigned int            firstdb;
167         int                     maxbests;
168
169         maxbests = dp->d_ops->free_max_bests(mp->m_dir_geo);
170         firstdb = (xfs_dir2_da_to_db(mp->m_dir_geo, fbno) -
171                    xfs_dir2_byte_to_db(mp->m_dir_geo, XFS_DIR2_FREE_OFFSET)) *
172                         maxbests;
173         if (xfs_sb_version_hascrc(&mp->m_sb)) {
174                 struct xfs_dir3_free_hdr *hdr3 = bp->b_addr;
175
176                 if (be32_to_cpu(hdr3->firstdb) != firstdb)
177                         return false;
178                 if (be32_to_cpu(hdr3->nvalid) > maxbests)
179                         return false;
180                 if (be32_to_cpu(hdr3->nvalid) < be32_to_cpu(hdr3->nused))
181                         return false;
182         } else {
183                 struct xfs_dir2_free_hdr *hdr = bp->b_addr;
184
185                 if (be32_to_cpu(hdr->firstdb) != firstdb)
186                         return false;
187                 if (be32_to_cpu(hdr->nvalid) > maxbests)
188                         return false;
189                 if (be32_to_cpu(hdr->nvalid) < be32_to_cpu(hdr->nused))
190                         return false;
191         }
192         return true;
193 }
194
195 static int
196 __xfs_dir3_free_read(
197         struct xfs_trans        *tp,
198         struct xfs_inode        *dp,
199         xfs_dablk_t             fbno,
200         xfs_daddr_t             mappedbno,
201         struct xfs_buf          **bpp)
202 {
203         int                     err;
204
205         err = xfs_da_read_buf(tp, dp, fbno, mappedbno, bpp,
206                                 XFS_DATA_FORK, &xfs_dir3_free_buf_ops);
207         if (err || !*bpp)
208                 return err;
209
210         /* Check things that we can't do in the verifier. */
211         if (!xfs_dir3_free_header_check(dp, fbno, *bpp)) {
212                 xfs_buf_ioerror(*bpp, -EFSCORRUPTED);
213                 xfs_verifier_error(*bpp);
214                 xfs_trans_brelse(tp, *bpp);
215                 *bpp = NULL;
216                 return -EFSCORRUPTED;
217         }
218
219         /* try read returns without an error or *bpp if it lands in a hole */
220         if (tp)
221                 xfs_trans_buf_set_type(tp, *bpp, XFS_BLFT_DIR_FREE_BUF);
222
223         return 0;
224 }
225
226 int
227 xfs_dir2_free_read(
228         struct xfs_trans        *tp,
229         struct xfs_inode        *dp,
230         xfs_dablk_t             fbno,
231         struct xfs_buf          **bpp)
232 {
233         return __xfs_dir3_free_read(tp, dp, fbno, -1, bpp);
234 }
235
236 static int
237 xfs_dir2_free_try_read(
238         struct xfs_trans        *tp,
239         struct xfs_inode        *dp,
240         xfs_dablk_t             fbno,
241         struct xfs_buf          **bpp)
242 {
243         return __xfs_dir3_free_read(tp, dp, fbno, -2, bpp);
244 }
245
246 static int
247 xfs_dir3_free_get_buf(
248         xfs_da_args_t           *args,
249         xfs_dir2_db_t           fbno,
250         struct xfs_buf          **bpp)
251 {
252         struct xfs_trans        *tp = args->trans;
253         struct xfs_inode        *dp = args->dp;
254         struct xfs_mount        *mp = dp->i_mount;
255         struct xfs_buf          *bp;
256         int                     error;
257         struct xfs_dir3_icfree_hdr hdr;
258
259         error = xfs_da_get_buf(tp, dp, xfs_dir2_db_to_da(args->geo, fbno),
260                                    -1, &bp, XFS_DATA_FORK);
261         if (error)
262                 return error;
263
264         xfs_trans_buf_set_type(tp, bp, XFS_BLFT_DIR_FREE_BUF);
265         bp->b_ops = &xfs_dir3_free_buf_ops;
266
267         /*
268          * Initialize the new block to be empty, and remember
269          * its first slot as our empty slot.
270          */
271         memset(bp->b_addr, 0, sizeof(struct xfs_dir3_free_hdr));
272         memset(&hdr, 0, sizeof(hdr));
273
274         if (xfs_sb_version_hascrc(&mp->m_sb)) {
275                 struct xfs_dir3_free_hdr *hdr3 = bp->b_addr;
276
277                 hdr.magic = XFS_DIR3_FREE_MAGIC;
278
279                 hdr3->hdr.blkno = cpu_to_be64(bp->b_bn);
280                 hdr3->hdr.owner = cpu_to_be64(dp->i_ino);
281                 uuid_copy(&hdr3->hdr.uuid, &mp->m_sb.sb_meta_uuid);
282         } else
283                 hdr.magic = XFS_DIR2_FREE_MAGIC;
284         dp->d_ops->free_hdr_to_disk(bp->b_addr, &hdr);
285         *bpp = bp;
286         return 0;
287 }
288
289 /*
290  * Log entries from a freespace block.
291  */
292 STATIC void
293 xfs_dir2_free_log_bests(
294         struct xfs_da_args      *args,
295         struct xfs_buf          *bp,
296         int                     first,          /* first entry to log */
297         int                     last)           /* last entry to log */
298 {
299         xfs_dir2_free_t         *free;          /* freespace structure */
300         __be16                  *bests;
301
302         free = bp->b_addr;
303         bests = args->dp->d_ops->free_bests_p(free);
304         ASSERT(free->hdr.magic == cpu_to_be32(XFS_DIR2_FREE_MAGIC) ||
305                free->hdr.magic == cpu_to_be32(XFS_DIR3_FREE_MAGIC));
306         xfs_trans_log_buf(args->trans, bp,
307                 (uint)((char *)&bests[first] - (char *)free),
308                 (uint)((char *)&bests[last] - (char *)free +
309                        sizeof(bests[0]) - 1));
310 }
311
312 /*
313  * Log header from a freespace block.
314  */
315 static void
316 xfs_dir2_free_log_header(
317         struct xfs_da_args      *args,
318         struct xfs_buf          *bp)
319 {
320 #ifdef DEBUG
321         xfs_dir2_free_t         *free;          /* freespace structure */
322
323         free = bp->b_addr;
324         ASSERT(free->hdr.magic == cpu_to_be32(XFS_DIR2_FREE_MAGIC) ||
325                free->hdr.magic == cpu_to_be32(XFS_DIR3_FREE_MAGIC));
326 #endif
327         xfs_trans_log_buf(args->trans, bp, 0,
328                           args->dp->d_ops->free_hdr_size - 1);
329 }
330
331 /*
332  * Convert a leaf-format directory to a node-format directory.
333  * We need to change the magic number of the leaf block, and copy
334  * the freespace table out of the leaf block into its own block.
335  */
336 int                                             /* error */
337 xfs_dir2_leaf_to_node(
338         xfs_da_args_t           *args,          /* operation arguments */
339         struct xfs_buf          *lbp)           /* leaf buffer */
340 {
341         xfs_inode_t             *dp;            /* incore directory inode */
342         int                     error;          /* error return value */
343         struct xfs_buf          *fbp;           /* freespace buffer */
344         xfs_dir2_db_t           fdb;            /* freespace block number */
345         xfs_dir2_free_t         *free;          /* freespace structure */
346         __be16                  *from;          /* pointer to freespace entry */
347         int                     i;              /* leaf freespace index */
348         xfs_dir2_leaf_t         *leaf;          /* leaf structure */
349         xfs_dir2_leaf_tail_t    *ltp;           /* leaf tail structure */
350         int                     n;              /* count of live freespc ents */
351         xfs_dir2_data_off_t     off;            /* freespace entry value */
352         __be16                  *to;            /* pointer to freespace entry */
353         xfs_trans_t             *tp;            /* transaction pointer */
354         struct xfs_dir3_icfree_hdr freehdr;
355
356         trace_xfs_dir2_leaf_to_node(args);
357
358         dp = args->dp;
359         tp = args->trans;
360         /*
361          * Add a freespace block to the directory.
362          */
363         if ((error = xfs_dir2_grow_inode(args, XFS_DIR2_FREE_SPACE, &fdb))) {
364                 return error;
365         }
366         ASSERT(fdb == xfs_dir2_byte_to_db(args->geo, XFS_DIR2_FREE_OFFSET));
367         /*
368          * Get the buffer for the new freespace block.
369          */
370         error = xfs_dir3_free_get_buf(args, fdb, &fbp);
371         if (error)
372                 return error;
373
374         free = fbp->b_addr;
375         dp->d_ops->free_hdr_from_disk(&freehdr, free);
376         leaf = lbp->b_addr;
377         ltp = xfs_dir2_leaf_tail_p(args->geo, leaf);
378         ASSERT(be32_to_cpu(ltp->bestcount) <=
379                                 (uint)dp->i_d.di_size / args->geo->blksize);
380
381         /*
382          * Copy freespace entries from the leaf block to the new block.
383          * Count active entries.
384          */
385         from = xfs_dir2_leaf_bests_p(ltp);
386         to = dp->d_ops->free_bests_p(free);
387         for (i = n = 0; i < be32_to_cpu(ltp->bestcount); i++, from++, to++) {
388                 if ((off = be16_to_cpu(*from)) != NULLDATAOFF)
389                         n++;
390                 *to = cpu_to_be16(off);
391         }
392
393         /*
394          * Now initialize the freespace block header.
395          */
396         freehdr.nused = n;
397         freehdr.nvalid = be32_to_cpu(ltp->bestcount);
398
399         dp->d_ops->free_hdr_to_disk(fbp->b_addr, &freehdr);
400         xfs_dir2_free_log_bests(args, fbp, 0, freehdr.nvalid - 1);
401         xfs_dir2_free_log_header(args, fbp);
402
403         /*
404          * Converting the leaf to a leafnode is just a matter of changing the
405          * magic number and the ops. Do the change directly to the buffer as
406          * it's less work (and less code) than decoding the header to host
407          * format and back again.
408          */
409         if (leaf->hdr.info.magic == cpu_to_be16(XFS_DIR2_LEAF1_MAGIC))
410                 leaf->hdr.info.magic = cpu_to_be16(XFS_DIR2_LEAFN_MAGIC);
411         else
412                 leaf->hdr.info.magic = cpu_to_be16(XFS_DIR3_LEAFN_MAGIC);
413         lbp->b_ops = &xfs_dir3_leafn_buf_ops;
414         xfs_trans_buf_set_type(tp, lbp, XFS_BLFT_DIR_LEAFN_BUF);
415         xfs_dir3_leaf_log_header(args, lbp);
416         xfs_dir3_leaf_check(dp, lbp);
417         return 0;
418 }
419
420 /*
421  * Add a leaf entry to a leaf block in a node-form directory.
422  * The other work necessary is done from the caller.
423  */
424 static int                                      /* error */
425 xfs_dir2_leafn_add(
426         struct xfs_buf          *bp,            /* leaf buffer */
427         xfs_da_args_t           *args,          /* operation arguments */
428         int                     index)          /* insertion pt for new entry */
429 {
430         int                     compact;        /* compacting stale leaves */
431         xfs_inode_t             *dp;            /* incore directory inode */
432         int                     highstale;      /* next stale entry */
433         xfs_dir2_leaf_t         *leaf;          /* leaf structure */
434         xfs_dir2_leaf_entry_t   *lep;           /* leaf entry */
435         int                     lfloghigh;      /* high leaf entry logging */
436         int                     lfloglow;       /* low leaf entry logging */
437         int                     lowstale;       /* previous stale entry */
438         struct xfs_dir3_icleaf_hdr leafhdr;
439         struct xfs_dir2_leaf_entry *ents;
440
441         trace_xfs_dir2_leafn_add(args, index);
442
443         dp = args->dp;
444         leaf = bp->b_addr;
445         dp->d_ops->leaf_hdr_from_disk(&leafhdr, leaf);
446         ents = dp->d_ops->leaf_ents_p(leaf);
447
448         /*
449          * Quick check just to make sure we are not going to index
450          * into other peoples memory
451          */
452         if (index < 0)
453                 return -EFSCORRUPTED;
454
455         /*
456          * If there are already the maximum number of leaf entries in
457          * the block, if there are no stale entries it won't fit.
458          * Caller will do a split.  If there are stale entries we'll do
459          * a compact.
460          */
461
462         if (leafhdr.count == dp->d_ops->leaf_max_ents(args->geo)) {
463                 if (!leafhdr.stale)
464                         return -ENOSPC;
465                 compact = leafhdr.stale > 1;
466         } else
467                 compact = 0;
468         ASSERT(index == 0 || be32_to_cpu(ents[index - 1].hashval) <= args->hashval);
469         ASSERT(index == leafhdr.count ||
470                be32_to_cpu(ents[index].hashval) >= args->hashval);
471
472         if (args->op_flags & XFS_DA_OP_JUSTCHECK)
473                 return 0;
474
475         /*
476          * Compact out all but one stale leaf entry.  Leaves behind
477          * the entry closest to index.
478          */
479         if (compact)
480                 xfs_dir3_leaf_compact_x1(&leafhdr, ents, &index, &lowstale,
481                                          &highstale, &lfloglow, &lfloghigh);
482         else if (leafhdr.stale) {
483                 /*
484                  * Set impossible logging indices for this case.
485                  */
486                 lfloglow = leafhdr.count;
487                 lfloghigh = -1;
488         }
489
490         /*
491          * Insert the new entry, log everything.
492          */
493         lep = xfs_dir3_leaf_find_entry(&leafhdr, ents, index, compact, lowstale,
494                                        highstale, &lfloglow, &lfloghigh);
495
496         lep->hashval = cpu_to_be32(args->hashval);
497         lep->address = cpu_to_be32(xfs_dir2_db_off_to_dataptr(args->geo,
498                                 args->blkno, args->index));
499
500         dp->d_ops->leaf_hdr_to_disk(leaf, &leafhdr);
501         xfs_dir3_leaf_log_header(args, bp);
502         xfs_dir3_leaf_log_ents(args, bp, lfloglow, lfloghigh);
503         xfs_dir3_leaf_check(dp, bp);
504         return 0;
505 }
506
507 #ifdef DEBUG
508 static void
509 xfs_dir2_free_hdr_check(
510         struct xfs_inode *dp,
511         struct xfs_buf  *bp,
512         xfs_dir2_db_t   db)
513 {
514         struct xfs_dir3_icfree_hdr hdr;
515
516         dp->d_ops->free_hdr_from_disk(&hdr, bp->b_addr);
517
518         ASSERT((hdr.firstdb %
519                 dp->d_ops->free_max_bests(dp->i_mount->m_dir_geo)) == 0);
520         ASSERT(hdr.firstdb <= db);
521         ASSERT(db < hdr.firstdb + hdr.nvalid);
522 }
523 #else
524 #define xfs_dir2_free_hdr_check(dp, bp, db)
525 #endif  /* DEBUG */
526
527 /*
528  * Return the last hash value in the leaf.
529  * Stale entries are ok.
530  */
531 xfs_dahash_t                                    /* hash value */
532 xfs_dir2_leaf_lasthash(
533         struct xfs_inode *dp,
534         struct xfs_buf  *bp,                    /* leaf buffer */
535         int             *count)                 /* count of entries in leaf */
536 {
537         struct xfs_dir2_leaf    *leaf = bp->b_addr;
538         struct xfs_dir2_leaf_entry *ents;
539         struct xfs_dir3_icleaf_hdr leafhdr;
540
541         dp->d_ops->leaf_hdr_from_disk(&leafhdr, leaf);
542
543         ASSERT(leafhdr.magic == XFS_DIR2_LEAFN_MAGIC ||
544                leafhdr.magic == XFS_DIR3_LEAFN_MAGIC ||
545                leafhdr.magic == XFS_DIR2_LEAF1_MAGIC ||
546                leafhdr.magic == XFS_DIR3_LEAF1_MAGIC);
547
548         if (count)
549                 *count = leafhdr.count;
550         if (!leafhdr.count)
551                 return 0;
552
553         ents = dp->d_ops->leaf_ents_p(leaf);
554         return be32_to_cpu(ents[leafhdr.count - 1].hashval);
555 }
556
557 /*
558  * Look up a leaf entry for space to add a name in a node-format leaf block.
559  * The extrablk in state is a freespace block.
560  */
561 STATIC int
562 xfs_dir2_leafn_lookup_for_addname(
563         struct xfs_buf          *bp,            /* leaf buffer */
564         xfs_da_args_t           *args,          /* operation arguments */
565         int                     *indexp,        /* out: leaf entry index */
566         xfs_da_state_t          *state)         /* state to fill in */
567 {
568         struct xfs_buf          *curbp = NULL;  /* current data/free buffer */
569         xfs_dir2_db_t           curdb = -1;     /* current data block number */
570         xfs_dir2_db_t           curfdb = -1;    /* current free block number */
571         xfs_inode_t             *dp;            /* incore directory inode */
572         int                     error;          /* error return value */
573         int                     fi;             /* free entry index */
574         xfs_dir2_free_t         *free = NULL;   /* free block structure */
575         int                     index;          /* leaf entry index */
576         xfs_dir2_leaf_t         *leaf;          /* leaf structure */
577         int                     length;         /* length of new data entry */
578         xfs_dir2_leaf_entry_t   *lep;           /* leaf entry */
579         xfs_mount_t             *mp;            /* filesystem mount point */
580         xfs_dir2_db_t           newdb;          /* new data block number */
581         xfs_dir2_db_t           newfdb;         /* new free block number */
582         xfs_trans_t             *tp;            /* transaction pointer */
583         struct xfs_dir2_leaf_entry *ents;
584         struct xfs_dir3_icleaf_hdr leafhdr;
585
586         dp = args->dp;
587         tp = args->trans;
588         mp = dp->i_mount;
589         leaf = bp->b_addr;
590         dp->d_ops->leaf_hdr_from_disk(&leafhdr, leaf);
591         ents = dp->d_ops->leaf_ents_p(leaf);
592
593         xfs_dir3_leaf_check(dp, bp);
594         ASSERT(leafhdr.count > 0);
595
596         /*
597          * Look up the hash value in the leaf entries.
598          */
599         index = xfs_dir2_leaf_search_hash(args, bp);
600         /*
601          * Do we have a buffer coming in?
602          */
603         if (state->extravalid) {
604                 /* If so, it's a free block buffer, get the block number. */
605                 curbp = state->extrablk.bp;
606                 curfdb = state->extrablk.blkno;
607                 free = curbp->b_addr;
608                 ASSERT(free->hdr.magic == cpu_to_be32(XFS_DIR2_FREE_MAGIC) ||
609                        free->hdr.magic == cpu_to_be32(XFS_DIR3_FREE_MAGIC));
610         }
611         length = dp->d_ops->data_entsize(args->namelen);
612         /*
613          * Loop over leaf entries with the right hash value.
614          */
615         for (lep = &ents[index];
616              index < leafhdr.count && be32_to_cpu(lep->hashval) == args->hashval;
617              lep++, index++) {
618                 /*
619                  * Skip stale leaf entries.
620                  */
621                 if (be32_to_cpu(lep->address) == XFS_DIR2_NULL_DATAPTR)
622                         continue;
623                 /*
624                  * Pull the data block number from the entry.
625                  */
626                 newdb = xfs_dir2_dataptr_to_db(args->geo,
627                                                be32_to_cpu(lep->address));
628                 /*
629                  * For addname, we're looking for a place to put the new entry.
630                  * We want to use a data block with an entry of equal
631                  * hash value to ours if there is one with room.
632                  *
633                  * If this block isn't the data block we already have
634                  * in hand, take a look at it.
635                  */
636                 if (newdb != curdb) {
637                         __be16 *bests;
638
639                         curdb = newdb;
640                         /*
641                          * Convert the data block to the free block
642                          * holding its freespace information.
643                          */
644                         newfdb = dp->d_ops->db_to_fdb(args->geo, newdb);
645                         /*
646                          * If it's not the one we have in hand, read it in.
647                          */
648                         if (newfdb != curfdb) {
649                                 /*
650                                  * If we had one before, drop it.
651                                  */
652                                 if (curbp)
653                                         xfs_trans_brelse(tp, curbp);
654
655                                 error = xfs_dir2_free_read(tp, dp,
656                                                 xfs_dir2_db_to_da(args->geo,
657                                                                   newfdb),
658                                                 &curbp);
659                                 if (error)
660                                         return error;
661                                 free = curbp->b_addr;
662
663                                 xfs_dir2_free_hdr_check(dp, curbp, curdb);
664                         }
665                         /*
666                          * Get the index for our entry.
667                          */
668                         fi = dp->d_ops->db_to_fdindex(args->geo, curdb);
669                         /*
670                          * If it has room, return it.
671                          */
672                         bests = dp->d_ops->free_bests_p(free);
673                         if (unlikely(bests[fi] == cpu_to_be16(NULLDATAOFF))) {
674                                 XFS_ERROR_REPORT("xfs_dir2_leafn_lookup_int",
675                                                         XFS_ERRLEVEL_LOW, mp);
676                                 if (curfdb != newfdb)
677                                         xfs_trans_brelse(tp, curbp);
678                                 return -EFSCORRUPTED;
679                         }
680                         curfdb = newfdb;
681                         if (be16_to_cpu(bests[fi]) >= length)
682                                 goto out;
683                 }
684         }
685         /* Didn't find any space */
686         fi = -1;
687 out:
688         ASSERT(args->op_flags & XFS_DA_OP_OKNOENT);
689         if (curbp) {
690                 /* Giving back a free block. */
691                 state->extravalid = 1;
692                 state->extrablk.bp = curbp;
693                 state->extrablk.index = fi;
694                 state->extrablk.blkno = curfdb;
695
696                 /*
697                  * Important: this magic number is not in the buffer - it's for
698                  * buffer type information and therefore only the free/data type
699                  * matters here, not whether CRCs are enabled or not.
700                  */
701                 state->extrablk.magic = XFS_DIR2_FREE_MAGIC;
702         } else {
703                 state->extravalid = 0;
704         }
705         /*
706          * Return the index, that will be the insertion point.
707          */
708         *indexp = index;
709         return -ENOENT;
710 }
711
712 /*
713  * Look up a leaf entry in a node-format leaf block.
714  * The extrablk in state a data block.
715  */
716 STATIC int
717 xfs_dir2_leafn_lookup_for_entry(
718         struct xfs_buf          *bp,            /* leaf buffer */
719         xfs_da_args_t           *args,          /* operation arguments */
720         int                     *indexp,        /* out: leaf entry index */
721         xfs_da_state_t          *state)         /* state to fill in */
722 {
723         struct xfs_buf          *curbp = NULL;  /* current data/free buffer */
724         xfs_dir2_db_t           curdb = -1;     /* current data block number */
725         xfs_dir2_data_entry_t   *dep;           /* data block entry */
726         xfs_inode_t             *dp;            /* incore directory inode */
727         int                     error;          /* error return value */
728         int                     index;          /* leaf entry index */
729         xfs_dir2_leaf_t         *leaf;          /* leaf structure */
730         xfs_dir2_leaf_entry_t   *lep;           /* leaf entry */
731         xfs_mount_t             *mp;            /* filesystem mount point */
732         xfs_dir2_db_t           newdb;          /* new data block number */
733         xfs_trans_t             *tp;            /* transaction pointer */
734         enum xfs_dacmp          cmp;            /* comparison result */
735         struct xfs_dir2_leaf_entry *ents;
736         struct xfs_dir3_icleaf_hdr leafhdr;
737
738         dp = args->dp;
739         tp = args->trans;
740         mp = dp->i_mount;
741         leaf = bp->b_addr;
742         dp->d_ops->leaf_hdr_from_disk(&leafhdr, leaf);
743         ents = dp->d_ops->leaf_ents_p(leaf);
744
745         xfs_dir3_leaf_check(dp, bp);
746         ASSERT(leafhdr.count > 0);
747
748         /*
749          * Look up the hash value in the leaf entries.
750          */
751         index = xfs_dir2_leaf_search_hash(args, bp);
752         /*
753          * Do we have a buffer coming in?
754          */
755         if (state->extravalid) {
756                 curbp = state->extrablk.bp;
757                 curdb = state->extrablk.blkno;
758         }
759         /*
760          * Loop over leaf entries with the right hash value.
761          */
762         for (lep = &ents[index];
763              index < leafhdr.count && be32_to_cpu(lep->hashval) == args->hashval;
764              lep++, index++) {
765                 /*
766                  * Skip stale leaf entries.
767                  */
768                 if (be32_to_cpu(lep->address) == XFS_DIR2_NULL_DATAPTR)
769                         continue;
770                 /*
771                  * Pull the data block number from the entry.
772                  */
773                 newdb = xfs_dir2_dataptr_to_db(args->geo,
774                                                be32_to_cpu(lep->address));
775                 /*
776                  * Not adding a new entry, so we really want to find
777                  * the name given to us.
778                  *
779                  * If it's a different data block, go get it.
780                  */
781                 if (newdb != curdb) {
782                         /*
783                          * If we had a block before that we aren't saving
784                          * for a CI name, drop it
785                          */
786                         if (curbp && (args->cmpresult == XFS_CMP_DIFFERENT ||
787                                                 curdb != state->extrablk.blkno))
788                                 xfs_trans_brelse(tp, curbp);
789                         /*
790                          * If needing the block that is saved with a CI match,
791                          * use it otherwise read in the new data block.
792                          */
793                         if (args->cmpresult != XFS_CMP_DIFFERENT &&
794                                         newdb == state->extrablk.blkno) {
795                                 ASSERT(state->extravalid);
796                                 curbp = state->extrablk.bp;
797                         } else {
798                                 error = xfs_dir3_data_read(tp, dp,
799                                                 xfs_dir2_db_to_da(args->geo,
800                                                                   newdb),
801                                                 -1, &curbp);
802                                 if (error)
803                                         return error;
804                         }
805                         xfs_dir3_data_check(dp, curbp);
806                         curdb = newdb;
807                 }
808                 /*
809                  * Point to the data entry.
810                  */
811                 dep = (xfs_dir2_data_entry_t *)((char *)curbp->b_addr +
812                         xfs_dir2_dataptr_to_off(args->geo,
813                                                 be32_to_cpu(lep->address)));
814                 /*
815                  * Compare the entry and if it's an exact match, return
816                  * EEXIST immediately. If it's the first case-insensitive
817                  * match, store the block & inode number and continue looking.
818                  */
819                 cmp = mp->m_dirnameops->compname(args, dep->name, dep->namelen);
820                 if (cmp != XFS_CMP_DIFFERENT && cmp != args->cmpresult) {
821                         /* If there is a CI match block, drop it */
822                         if (args->cmpresult != XFS_CMP_DIFFERENT &&
823                                                 curdb != state->extrablk.blkno)
824                                 xfs_trans_brelse(tp, state->extrablk.bp);
825                         args->cmpresult = cmp;
826                         args->inumber = be64_to_cpu(dep->inumber);
827                         args->filetype = dp->d_ops->data_get_ftype(dep);
828                         *indexp = index;
829                         state->extravalid = 1;
830                         state->extrablk.bp = curbp;
831                         state->extrablk.blkno = curdb;
832                         state->extrablk.index = (int)((char *)dep -
833                                                         (char *)curbp->b_addr);
834                         state->extrablk.magic = XFS_DIR2_DATA_MAGIC;
835                         curbp->b_ops = &xfs_dir3_data_buf_ops;
836                         xfs_trans_buf_set_type(tp, curbp, XFS_BLFT_DIR_DATA_BUF);
837                         if (cmp == XFS_CMP_EXACT)
838                                 return -EEXIST;
839                 }
840         }
841         ASSERT(index == leafhdr.count || (args->op_flags & XFS_DA_OP_OKNOENT));
842         if (curbp) {
843                 if (args->cmpresult == XFS_CMP_DIFFERENT) {
844                         /* Giving back last used data block. */
845                         state->extravalid = 1;
846                         state->extrablk.bp = curbp;
847                         state->extrablk.index = -1;
848                         state->extrablk.blkno = curdb;
849                         state->extrablk.magic = XFS_DIR2_DATA_MAGIC;
850                         curbp->b_ops = &xfs_dir3_data_buf_ops;
851                         xfs_trans_buf_set_type(tp, curbp, XFS_BLFT_DIR_DATA_BUF);
852                 } else {
853                         /* If the curbp is not the CI match block, drop it */
854                         if (state->extrablk.bp != curbp)
855                                 xfs_trans_brelse(tp, curbp);
856                 }
857         } else {
858                 state->extravalid = 0;
859         }
860         *indexp = index;
861         return -ENOENT;
862 }
863
864 /*
865  * Look up a leaf entry in a node-format leaf block.
866  * If this is an addname then the extrablk in state is a freespace block,
867  * otherwise it's a data block.
868  */
869 int
870 xfs_dir2_leafn_lookup_int(
871         struct xfs_buf          *bp,            /* leaf buffer */
872         xfs_da_args_t           *args,          /* operation arguments */
873         int                     *indexp,        /* out: leaf entry index */
874         xfs_da_state_t          *state)         /* state to fill in */
875 {
876         if (args->op_flags & XFS_DA_OP_ADDNAME)
877                 return xfs_dir2_leafn_lookup_for_addname(bp, args, indexp,
878                                                         state);
879         return xfs_dir2_leafn_lookup_for_entry(bp, args, indexp, state);
880 }
881
882 /*
883  * Move count leaf entries from source to destination leaf.
884  * Log entries and headers.  Stale entries are preserved.
885  */
886 static void
887 xfs_dir3_leafn_moveents(
888         xfs_da_args_t                   *args,  /* operation arguments */
889         struct xfs_buf                  *bp_s,  /* source */
890         struct xfs_dir3_icleaf_hdr      *shdr,
891         struct xfs_dir2_leaf_entry      *sents,
892         int                             start_s,/* source leaf index */
893         struct xfs_buf                  *bp_d,  /* destination */
894         struct xfs_dir3_icleaf_hdr      *dhdr,
895         struct xfs_dir2_leaf_entry      *dents,
896         int                             start_d,/* destination leaf index */
897         int                             count)  /* count of leaves to copy */
898 {
899         int                             stale;  /* count stale leaves copied */
900
901         trace_xfs_dir2_leafn_moveents(args, start_s, start_d, count);
902
903         /*
904          * Silently return if nothing to do.
905          */
906         if (count == 0)
907                 return;
908
909         /*
910          * If the destination index is not the end of the current
911          * destination leaf entries, open up a hole in the destination
912          * to hold the new entries.
913          */
914         if (start_d < dhdr->count) {
915                 memmove(&dents[start_d + count], &dents[start_d],
916                         (dhdr->count - start_d) * sizeof(xfs_dir2_leaf_entry_t));
917                 xfs_dir3_leaf_log_ents(args, bp_d, start_d + count,
918                                        count + dhdr->count - 1);
919         }
920         /*
921          * If the source has stale leaves, count the ones in the copy range
922          * so we can update the header correctly.
923          */
924         if (shdr->stale) {
925                 int     i;                      /* temp leaf index */
926
927                 for (i = start_s, stale = 0; i < start_s + count; i++) {
928                         if (sents[i].address ==
929                                         cpu_to_be32(XFS_DIR2_NULL_DATAPTR))
930                                 stale++;
931                 }
932         } else
933                 stale = 0;
934         /*
935          * Copy the leaf entries from source to destination.
936          */
937         memcpy(&dents[start_d], &sents[start_s],
938                 count * sizeof(xfs_dir2_leaf_entry_t));
939         xfs_dir3_leaf_log_ents(args, bp_d, start_d, start_d + count - 1);
940
941         /*
942          * If there are source entries after the ones we copied,
943          * delete the ones we copied by sliding the next ones down.
944          */
945         if (start_s + count < shdr->count) {
946                 memmove(&sents[start_s], &sents[start_s + count],
947                         count * sizeof(xfs_dir2_leaf_entry_t));
948                 xfs_dir3_leaf_log_ents(args, bp_s, start_s, start_s + count - 1);
949         }
950
951         /*
952          * Update the headers and log them.
953          */
954         shdr->count -= count;
955         shdr->stale -= stale;
956         dhdr->count += count;
957         dhdr->stale += stale;
958 }
959
960 /*
961  * Determine the sort order of two leaf blocks.
962  * Returns 1 if both are valid and leaf2 should be before leaf1, else 0.
963  */
964 int                                             /* sort order */
965 xfs_dir2_leafn_order(
966         struct xfs_inode        *dp,
967         struct xfs_buf          *leaf1_bp,              /* leaf1 buffer */
968         struct xfs_buf          *leaf2_bp)              /* leaf2 buffer */
969 {
970         struct xfs_dir2_leaf    *leaf1 = leaf1_bp->b_addr;
971         struct xfs_dir2_leaf    *leaf2 = leaf2_bp->b_addr;
972         struct xfs_dir2_leaf_entry *ents1;
973         struct xfs_dir2_leaf_entry *ents2;
974         struct xfs_dir3_icleaf_hdr hdr1;
975         struct xfs_dir3_icleaf_hdr hdr2;
976
977         dp->d_ops->leaf_hdr_from_disk(&hdr1, leaf1);
978         dp->d_ops->leaf_hdr_from_disk(&hdr2, leaf2);
979         ents1 = dp->d_ops->leaf_ents_p(leaf1);
980         ents2 = dp->d_ops->leaf_ents_p(leaf2);
981
982         if (hdr1.count > 0 && hdr2.count > 0 &&
983             (be32_to_cpu(ents2[0].hashval) < be32_to_cpu(ents1[0].hashval) ||
984              be32_to_cpu(ents2[hdr2.count - 1].hashval) <
985                                 be32_to_cpu(ents1[hdr1.count - 1].hashval)))
986                 return 1;
987         return 0;
988 }
989
990 /*
991  * Rebalance leaf entries between two leaf blocks.
992  * This is actually only called when the second block is new,
993  * though the code deals with the general case.
994  * A new entry will be inserted in one of the blocks, and that
995  * entry is taken into account when balancing.
996  */
997 static void
998 xfs_dir2_leafn_rebalance(
999         xfs_da_state_t          *state,         /* btree cursor */
1000         xfs_da_state_blk_t      *blk1,          /* first btree block */
1001         xfs_da_state_blk_t      *blk2)          /* second btree block */
1002 {
1003         xfs_da_args_t           *args;          /* operation arguments */
1004         int                     count;          /* count (& direction) leaves */
1005         int                     isleft;         /* new goes in left leaf */
1006         xfs_dir2_leaf_t         *leaf1;         /* first leaf structure */
1007         xfs_dir2_leaf_t         *leaf2;         /* second leaf structure */
1008         int                     mid;            /* midpoint leaf index */
1009 #if defined(DEBUG) || defined(XFS_WARN)
1010         int                     oldstale;       /* old count of stale leaves */
1011 #endif
1012         int                     oldsum;         /* old total leaf count */
1013         int                     swap;           /* swapped leaf blocks */
1014         struct xfs_dir2_leaf_entry *ents1;
1015         struct xfs_dir2_leaf_entry *ents2;
1016         struct xfs_dir3_icleaf_hdr hdr1;
1017         struct xfs_dir3_icleaf_hdr hdr2;
1018         struct xfs_inode        *dp = state->args->dp;
1019
1020         args = state->args;
1021         /*
1022          * If the block order is wrong, swap the arguments.
1023          */
1024         if ((swap = xfs_dir2_leafn_order(dp, blk1->bp, blk2->bp))) {
1025                 xfs_da_state_blk_t      *tmp;   /* temp for block swap */
1026
1027                 tmp = blk1;
1028                 blk1 = blk2;
1029                 blk2 = tmp;
1030         }
1031         leaf1 = blk1->bp->b_addr;
1032         leaf2 = blk2->bp->b_addr;
1033         dp->d_ops->leaf_hdr_from_disk(&hdr1, leaf1);
1034         dp->d_ops->leaf_hdr_from_disk(&hdr2, leaf2);
1035         ents1 = dp->d_ops->leaf_ents_p(leaf1);
1036         ents2 = dp->d_ops->leaf_ents_p(leaf2);
1037
1038         oldsum = hdr1.count + hdr2.count;
1039 #if defined(DEBUG) || defined(XFS_WARN)
1040         oldstale = hdr1.stale + hdr2.stale;
1041 #endif
1042         mid = oldsum >> 1;
1043
1044         /*
1045          * If the old leaf count was odd then the new one will be even,
1046          * so we need to divide the new count evenly.
1047          */
1048         if (oldsum & 1) {
1049                 xfs_dahash_t    midhash;        /* middle entry hash value */
1050
1051                 if (mid >= hdr1.count)
1052                         midhash = be32_to_cpu(ents2[mid - hdr1.count].hashval);
1053                 else
1054                         midhash = be32_to_cpu(ents1[mid].hashval);
1055                 isleft = args->hashval <= midhash;
1056         }
1057         /*
1058          * If the old count is even then the new count is odd, so there's
1059          * no preferred side for the new entry.
1060          * Pick the left one.
1061          */
1062         else
1063                 isleft = 1;
1064         /*
1065          * Calculate moved entry count.  Positive means left-to-right,
1066          * negative means right-to-left.  Then move the entries.
1067          */
1068         count = hdr1.count - mid + (isleft == 0);
1069         if (count > 0)
1070                 xfs_dir3_leafn_moveents(args, blk1->bp, &hdr1, ents1,
1071                                         hdr1.count - count, blk2->bp,
1072                                         &hdr2, ents2, 0, count);
1073         else if (count < 0)
1074                 xfs_dir3_leafn_moveents(args, blk2->bp, &hdr2, ents2, 0,
1075                                         blk1->bp, &hdr1, ents1,
1076                                         hdr1.count, count);
1077
1078         ASSERT(hdr1.count + hdr2.count == oldsum);
1079         ASSERT(hdr1.stale + hdr2.stale == oldstale);
1080
1081         /* log the changes made when moving the entries */
1082         dp->d_ops->leaf_hdr_to_disk(leaf1, &hdr1);
1083         dp->d_ops->leaf_hdr_to_disk(leaf2, &hdr2);
1084         xfs_dir3_leaf_log_header(args, blk1->bp);
1085         xfs_dir3_leaf_log_header(args, blk2->bp);
1086
1087         xfs_dir3_leaf_check(dp, blk1->bp);
1088         xfs_dir3_leaf_check(dp, blk2->bp);
1089
1090         /*
1091          * Mark whether we're inserting into the old or new leaf.
1092          */
1093         if (hdr1.count < hdr2.count)
1094                 state->inleaf = swap;
1095         else if (hdr1.count > hdr2.count)
1096                 state->inleaf = !swap;
1097         else
1098                 state->inleaf = swap ^ (blk1->index <= hdr1.count);
1099         /*
1100          * Adjust the expected index for insertion.
1101          */
1102         if (!state->inleaf)
1103                 blk2->index = blk1->index - hdr1.count;
1104
1105         /*
1106          * Finally sanity check just to make sure we are not returning a
1107          * negative index
1108          */
1109         if (blk2->index < 0) {
1110                 state->inleaf = 1;
1111                 blk2->index = 0;
1112                 xfs_alert(dp->i_mount,
1113         "%s: picked the wrong leaf? reverting original leaf: blk1->index %d",
1114                         __func__, blk1->index);
1115         }
1116 }
1117
1118 static int
1119 xfs_dir3_data_block_free(
1120         xfs_da_args_t           *args,
1121         struct xfs_dir2_data_hdr *hdr,
1122         struct xfs_dir2_free    *free,
1123         xfs_dir2_db_t           fdb,
1124         int                     findex,
1125         struct xfs_buf          *fbp,
1126         int                     longest)
1127 {
1128         int                     logfree = 0;
1129         __be16                  *bests;
1130         struct xfs_dir3_icfree_hdr freehdr;
1131         struct xfs_inode        *dp = args->dp;
1132
1133         dp->d_ops->free_hdr_from_disk(&freehdr, free);
1134         bests = dp->d_ops->free_bests_p(free);
1135         if (hdr) {
1136                 /*
1137                  * Data block is not empty, just set the free entry to the new
1138                  * value.
1139                  */
1140                 bests[findex] = cpu_to_be16(longest);
1141                 xfs_dir2_free_log_bests(args, fbp, findex, findex);
1142                 return 0;
1143         }
1144
1145         /* One less used entry in the free table. */
1146         freehdr.nused--;
1147
1148         /*
1149          * If this was the last entry in the table, we can trim the table size
1150          * back.  There might be other entries at the end referring to
1151          * non-existent data blocks, get those too.
1152          */
1153         if (findex == freehdr.nvalid - 1) {
1154                 int     i;              /* free entry index */
1155
1156                 for (i = findex - 1; i >= 0; i--) {
1157                         if (bests[i] != cpu_to_be16(NULLDATAOFF))
1158                                 break;
1159                 }
1160                 freehdr.nvalid = i + 1;
1161                 logfree = 0;
1162         } else {
1163                 /* Not the last entry, just punch it out.  */
1164                 bests[findex] = cpu_to_be16(NULLDATAOFF);
1165                 logfree = 1;
1166         }
1167
1168         dp->d_ops->free_hdr_to_disk(free, &freehdr);
1169         xfs_dir2_free_log_header(args, fbp);
1170
1171         /*
1172          * If there are no useful entries left in the block, get rid of the
1173          * block if we can.
1174          */
1175         if (!freehdr.nused) {
1176                 int error;
1177
1178                 error = xfs_dir2_shrink_inode(args, fdb, fbp);
1179                 if (error == 0) {
1180                         fbp = NULL;
1181                         logfree = 0;
1182                 } else if (error != -ENOSPC || args->total != 0)
1183                         return error;
1184                 /*
1185                  * It's possible to get ENOSPC if there is no
1186                  * space reservation.  In this case some one
1187                  * else will eventually get rid of this block.
1188                  */
1189         }
1190
1191         /* Log the free entry that changed, unless we got rid of it.  */
1192         if (logfree)
1193                 xfs_dir2_free_log_bests(args, fbp, findex, findex);
1194         return 0;
1195 }
1196
1197 /*
1198  * Remove an entry from a node directory.
1199  * This removes the leaf entry and the data entry,
1200  * and updates the free block if necessary.
1201  */
1202 static int                                      /* error */
1203 xfs_dir2_leafn_remove(
1204         xfs_da_args_t           *args,          /* operation arguments */
1205         struct xfs_buf          *bp,            /* leaf buffer */
1206         int                     index,          /* leaf entry index */
1207         xfs_da_state_blk_t      *dblk,          /* data block */
1208         int                     *rval)          /* resulting block needs join */
1209 {
1210         xfs_dir2_data_hdr_t     *hdr;           /* data block header */
1211         xfs_dir2_db_t           db;             /* data block number */
1212         struct xfs_buf          *dbp;           /* data block buffer */
1213         xfs_dir2_data_entry_t   *dep;           /* data block entry */
1214         xfs_inode_t             *dp;            /* incore directory inode */
1215         xfs_dir2_leaf_t         *leaf;          /* leaf structure */
1216         xfs_dir2_leaf_entry_t   *lep;           /* leaf entry */
1217         int                     longest;        /* longest data free entry */
1218         int                     off;            /* data block entry offset */
1219         int                     needlog;        /* need to log data header */
1220         int                     needscan;       /* need to rescan data frees */
1221         xfs_trans_t             *tp;            /* transaction pointer */
1222         struct xfs_dir2_data_free *bf;          /* bestfree table */
1223         struct xfs_dir3_icleaf_hdr leafhdr;
1224         struct xfs_dir2_leaf_entry *ents;
1225
1226         trace_xfs_dir2_leafn_remove(args, index);
1227
1228         dp = args->dp;
1229         tp = args->trans;
1230         leaf = bp->b_addr;
1231         dp->d_ops->leaf_hdr_from_disk(&leafhdr, leaf);
1232         ents = dp->d_ops->leaf_ents_p(leaf);
1233
1234         /*
1235          * Point to the entry we're removing.
1236          */
1237         lep = &ents[index];
1238
1239         /*
1240          * Extract the data block and offset from the entry.
1241          */
1242         db = xfs_dir2_dataptr_to_db(args->geo, be32_to_cpu(lep->address));
1243         ASSERT(dblk->blkno == db);
1244         off = xfs_dir2_dataptr_to_off(args->geo, be32_to_cpu(lep->address));
1245         ASSERT(dblk->index == off);
1246
1247         /*
1248          * Kill the leaf entry by marking it stale.
1249          * Log the leaf block changes.
1250          */
1251         leafhdr.stale++;
1252         dp->d_ops->leaf_hdr_to_disk(leaf, &leafhdr);
1253         xfs_dir3_leaf_log_header(args, bp);
1254
1255         lep->address = cpu_to_be32(XFS_DIR2_NULL_DATAPTR);
1256         xfs_dir3_leaf_log_ents(args, bp, index, index);
1257
1258         /*
1259          * Make the data entry free.  Keep track of the longest freespace
1260          * in the data block in case it changes.
1261          */
1262         dbp = dblk->bp;
1263         hdr = dbp->b_addr;
1264         dep = (xfs_dir2_data_entry_t *)((char *)hdr + off);
1265         bf = dp->d_ops->data_bestfree_p(hdr);
1266         longest = be16_to_cpu(bf[0].length);
1267         needlog = needscan = 0;
1268         xfs_dir2_data_make_free(args, dbp, off,
1269                 dp->d_ops->data_entsize(dep->namelen), &needlog, &needscan);
1270         /*
1271          * Rescan the data block freespaces for bestfree.
1272          * Log the data block header if needed.
1273          */
1274         if (needscan)
1275                 xfs_dir2_data_freescan(dp, hdr, &needlog);
1276         if (needlog)
1277                 xfs_dir2_data_log_header(args, dbp);
1278         xfs_dir3_data_check(dp, dbp);
1279         /*
1280          * If the longest data block freespace changes, need to update
1281          * the corresponding freeblock entry.
1282          */
1283         if (longest < be16_to_cpu(bf[0].length)) {
1284                 int             error;          /* error return value */
1285                 struct xfs_buf  *fbp;           /* freeblock buffer */
1286                 xfs_dir2_db_t   fdb;            /* freeblock block number */
1287                 int             findex;         /* index in freeblock entries */
1288                 xfs_dir2_free_t *free;          /* freeblock structure */
1289
1290                 /*
1291                  * Convert the data block number to a free block,
1292                  * read in the free block.
1293                  */
1294                 fdb = dp->d_ops->db_to_fdb(args->geo, db);
1295                 error = xfs_dir2_free_read(tp, dp,
1296                                            xfs_dir2_db_to_da(args->geo, fdb),
1297                                            &fbp);
1298                 if (error)
1299                         return error;
1300                 free = fbp->b_addr;
1301 #ifdef DEBUG
1302         {
1303                 struct xfs_dir3_icfree_hdr freehdr;
1304                 dp->d_ops->free_hdr_from_disk(&freehdr, free);
1305                 ASSERT(freehdr.firstdb == dp->d_ops->free_max_bests(args->geo) *
1306                         (fdb - xfs_dir2_byte_to_db(args->geo,
1307                                                    XFS_DIR2_FREE_OFFSET)));
1308         }
1309 #endif
1310                 /*
1311                  * Calculate which entry we need to fix.
1312                  */
1313                 findex = dp->d_ops->db_to_fdindex(args->geo, db);
1314                 longest = be16_to_cpu(bf[0].length);
1315                 /*
1316                  * If the data block is now empty we can get rid of it
1317                  * (usually).
1318                  */
1319                 if (longest == args->geo->blksize -
1320                                dp->d_ops->data_entry_offset) {
1321                         /*
1322                          * Try to punch out the data block.
1323                          */
1324                         error = xfs_dir2_shrink_inode(args, db, dbp);
1325                         if (error == 0) {
1326                                 dblk->bp = NULL;
1327                                 hdr = NULL;
1328                         }
1329                         /*
1330                          * We can get ENOSPC if there's no space reservation.
1331                          * In this case just drop the buffer and some one else
1332                          * will eventually get rid of the empty block.
1333                          */
1334                         else if (!(error == -ENOSPC && args->total == 0))
1335                                 return error;
1336                 }
1337                 /*
1338                  * If we got rid of the data block, we can eliminate that entry
1339                  * in the free block.
1340                  */
1341                 error = xfs_dir3_data_block_free(args, hdr, free,
1342                                                  fdb, findex, fbp, longest);
1343                 if (error)
1344                         return error;
1345         }
1346
1347         xfs_dir3_leaf_check(dp, bp);
1348         /*
1349          * Return indication of whether this leaf block is empty enough
1350          * to justify trying to join it with a neighbor.
1351          */
1352         *rval = (dp->d_ops->leaf_hdr_size +
1353                  (uint)sizeof(ents[0]) * (leafhdr.count - leafhdr.stale)) <
1354                 args->geo->magicpct;
1355         return 0;
1356 }
1357
1358 /*
1359  * Split the leaf entries in the old block into old and new blocks.
1360  */
1361 int                                             /* error */
1362 xfs_dir2_leafn_split(
1363         xfs_da_state_t          *state,         /* btree cursor */
1364         xfs_da_state_blk_t      *oldblk,        /* original block */
1365         xfs_da_state_blk_t      *newblk)        /* newly created block */
1366 {
1367         xfs_da_args_t           *args;          /* operation arguments */
1368         xfs_dablk_t             blkno;          /* new leaf block number */
1369         int                     error;          /* error return value */
1370         struct xfs_inode        *dp;
1371
1372         /*
1373          * Allocate space for a new leaf node.
1374          */
1375         args = state->args;
1376         dp = args->dp;
1377         ASSERT(oldblk->magic == XFS_DIR2_LEAFN_MAGIC);
1378         error = xfs_da_grow_inode(args, &blkno);
1379         if (error) {
1380                 return error;
1381         }
1382         /*
1383          * Initialize the new leaf block.
1384          */
1385         error = xfs_dir3_leaf_get_buf(args, xfs_dir2_da_to_db(args->geo, blkno),
1386                                       &newblk->bp, XFS_DIR2_LEAFN_MAGIC);
1387         if (error)
1388                 return error;
1389
1390         newblk->blkno = blkno;
1391         newblk->magic = XFS_DIR2_LEAFN_MAGIC;
1392         /*
1393          * Rebalance the entries across the two leaves, link the new
1394          * block into the leaves.
1395          */
1396         xfs_dir2_leafn_rebalance(state, oldblk, newblk);
1397         error = xfs_da3_blk_link(state, oldblk, newblk);
1398         if (error) {
1399                 return error;
1400         }
1401         /*
1402          * Insert the new entry in the correct block.
1403          */
1404         if (state->inleaf)
1405                 error = xfs_dir2_leafn_add(oldblk->bp, args, oldblk->index);
1406         else
1407                 error = xfs_dir2_leafn_add(newblk->bp, args, newblk->index);
1408         /*
1409          * Update last hashval in each block since we added the name.
1410          */
1411         oldblk->hashval = xfs_dir2_leaf_lasthash(dp, oldblk->bp, NULL);
1412         newblk->hashval = xfs_dir2_leaf_lasthash(dp, newblk->bp, NULL);
1413         xfs_dir3_leaf_check(dp, oldblk->bp);
1414         xfs_dir3_leaf_check(dp, newblk->bp);
1415         return error;
1416 }
1417
1418 /*
1419  * Check a leaf block and its neighbors to see if the block should be
1420  * collapsed into one or the other neighbor.  Always keep the block
1421  * with the smaller block number.
1422  * If the current block is over 50% full, don't try to join it, return 0.
1423  * If the block is empty, fill in the state structure and return 2.
1424  * If it can be collapsed, fill in the state structure and return 1.
1425  * If nothing can be done, return 0.
1426  */
1427 int                                             /* error */
1428 xfs_dir2_leafn_toosmall(
1429         xfs_da_state_t          *state,         /* btree cursor */
1430         int                     *action)        /* resulting action to take */
1431 {
1432         xfs_da_state_blk_t      *blk;           /* leaf block */
1433         xfs_dablk_t             blkno;          /* leaf block number */
1434         struct xfs_buf          *bp;            /* leaf buffer */
1435         int                     bytes;          /* bytes in use */
1436         int                     count;          /* leaf live entry count */
1437         int                     error;          /* error return value */
1438         int                     forward;        /* sibling block direction */
1439         int                     i;              /* sibling counter */
1440         xfs_dir2_leaf_t         *leaf;          /* leaf structure */
1441         int                     rval;           /* result from path_shift */
1442         struct xfs_dir3_icleaf_hdr leafhdr;
1443         struct xfs_dir2_leaf_entry *ents;
1444         struct xfs_inode        *dp = state->args->dp;
1445
1446         /*
1447          * Check for the degenerate case of the block being over 50% full.
1448          * If so, it's not worth even looking to see if we might be able
1449          * to coalesce with a sibling.
1450          */
1451         blk = &state->path.blk[state->path.active - 1];
1452         leaf = blk->bp->b_addr;
1453         dp->d_ops->leaf_hdr_from_disk(&leafhdr, leaf);
1454         ents = dp->d_ops->leaf_ents_p(leaf);
1455         xfs_dir3_leaf_check(dp, blk->bp);
1456
1457         count = leafhdr.count - leafhdr.stale;
1458         bytes = dp->d_ops->leaf_hdr_size + count * sizeof(ents[0]);
1459         if (bytes > (state->args->geo->blksize >> 1)) {
1460                 /*
1461                  * Blk over 50%, don't try to join.
1462                  */
1463                 *action = 0;
1464                 return 0;
1465         }
1466         /*
1467          * Check for the degenerate case of the block being empty.
1468          * If the block is empty, we'll simply delete it, no need to
1469          * coalesce it with a sibling block.  We choose (arbitrarily)
1470          * to merge with the forward block unless it is NULL.
1471          */
1472         if (count == 0) {
1473                 /*
1474                  * Make altpath point to the block we want to keep and
1475                  * path point to the block we want to drop (this one).
1476                  */
1477                 forward = (leafhdr.forw != 0);
1478                 memcpy(&state->altpath, &state->path, sizeof(state->path));
1479                 error = xfs_da3_path_shift(state, &state->altpath, forward, 0,
1480                         &rval);
1481                 if (error)
1482                         return error;
1483                 *action = rval ? 2 : 0;
1484                 return 0;
1485         }
1486         /*
1487          * Examine each sibling block to see if we can coalesce with
1488          * at least 25% free space to spare.  We need to figure out
1489          * whether to merge with the forward or the backward block.
1490          * We prefer coalescing with the lower numbered sibling so as
1491          * to shrink a directory over time.
1492          */
1493         forward = leafhdr.forw < leafhdr.back;
1494         for (i = 0, bp = NULL; i < 2; forward = !forward, i++) {
1495                 struct xfs_dir3_icleaf_hdr hdr2;
1496
1497                 blkno = forward ? leafhdr.forw : leafhdr.back;
1498                 if (blkno == 0)
1499                         continue;
1500                 /*
1501                  * Read the sibling leaf block.
1502                  */
1503                 error = xfs_dir3_leafn_read(state->args->trans, dp,
1504                                             blkno, -1, &bp);
1505                 if (error)
1506                         return error;
1507
1508                 /*
1509                  * Count bytes in the two blocks combined.
1510                  */
1511                 count = leafhdr.count - leafhdr.stale;
1512                 bytes = state->args->geo->blksize -
1513                         (state->args->geo->blksize >> 2);
1514
1515                 leaf = bp->b_addr;
1516                 dp->d_ops->leaf_hdr_from_disk(&hdr2, leaf);
1517                 ents = dp->d_ops->leaf_ents_p(leaf);
1518                 count += hdr2.count - hdr2.stale;
1519                 bytes -= count * sizeof(ents[0]);
1520
1521                 /*
1522                  * Fits with at least 25% to spare.
1523                  */
1524                 if (bytes >= 0)
1525                         break;
1526                 xfs_trans_brelse(state->args->trans, bp);
1527         }
1528         /*
1529          * Didn't like either block, give up.
1530          */
1531         if (i >= 2) {
1532                 *action = 0;
1533                 return 0;
1534         }
1535
1536         /*
1537          * Make altpath point to the block we want to keep (the lower
1538          * numbered block) and path point to the block we want to drop.
1539          */
1540         memcpy(&state->altpath, &state->path, sizeof(state->path));
1541         if (blkno < blk->blkno)
1542                 error = xfs_da3_path_shift(state, &state->altpath, forward, 0,
1543                         &rval);
1544         else
1545                 error = xfs_da3_path_shift(state, &state->path, forward, 0,
1546                         &rval);
1547         if (error) {
1548                 return error;
1549         }
1550         *action = rval ? 0 : 1;
1551         return 0;
1552 }
1553
1554 /*
1555  * Move all the leaf entries from drop_blk to save_blk.
1556  * This is done as part of a join operation.
1557  */
1558 void
1559 xfs_dir2_leafn_unbalance(
1560         xfs_da_state_t          *state,         /* cursor */
1561         xfs_da_state_blk_t      *drop_blk,      /* dead block */
1562         xfs_da_state_blk_t      *save_blk)      /* surviving block */
1563 {
1564         xfs_da_args_t           *args;          /* operation arguments */
1565         xfs_dir2_leaf_t         *drop_leaf;     /* dead leaf structure */
1566         xfs_dir2_leaf_t         *save_leaf;     /* surviving leaf structure */
1567         struct xfs_dir3_icleaf_hdr savehdr;
1568         struct xfs_dir3_icleaf_hdr drophdr;
1569         struct xfs_dir2_leaf_entry *sents;
1570         struct xfs_dir2_leaf_entry *dents;
1571         struct xfs_inode        *dp = state->args->dp;
1572
1573         args = state->args;
1574         ASSERT(drop_blk->magic == XFS_DIR2_LEAFN_MAGIC);
1575         ASSERT(save_blk->magic == XFS_DIR2_LEAFN_MAGIC);
1576         drop_leaf = drop_blk->bp->b_addr;
1577         save_leaf = save_blk->bp->b_addr;
1578
1579         dp->d_ops->leaf_hdr_from_disk(&savehdr, save_leaf);
1580         dp->d_ops->leaf_hdr_from_disk(&drophdr, drop_leaf);
1581         sents = dp->d_ops->leaf_ents_p(save_leaf);
1582         dents = dp->d_ops->leaf_ents_p(drop_leaf);
1583
1584         /*
1585          * If there are any stale leaf entries, take this opportunity
1586          * to purge them.
1587          */
1588         if (drophdr.stale)
1589                 xfs_dir3_leaf_compact(args, &drophdr, drop_blk->bp);
1590         if (savehdr.stale)
1591                 xfs_dir3_leaf_compact(args, &savehdr, save_blk->bp);
1592
1593         /*
1594          * Move the entries from drop to the appropriate end of save.
1595          */
1596         drop_blk->hashval = be32_to_cpu(dents[drophdr.count - 1].hashval);
1597         if (xfs_dir2_leafn_order(dp, save_blk->bp, drop_blk->bp))
1598                 xfs_dir3_leafn_moveents(args, drop_blk->bp, &drophdr, dents, 0,
1599                                         save_blk->bp, &savehdr, sents, 0,
1600                                         drophdr.count);
1601         else
1602                 xfs_dir3_leafn_moveents(args, drop_blk->bp, &drophdr, dents, 0,
1603                                         save_blk->bp, &savehdr, sents,
1604                                         savehdr.count, drophdr.count);
1605         save_blk->hashval = be32_to_cpu(sents[savehdr.count - 1].hashval);
1606
1607         /* log the changes made when moving the entries */
1608         dp->d_ops->leaf_hdr_to_disk(save_leaf, &savehdr);
1609         dp->d_ops->leaf_hdr_to_disk(drop_leaf, &drophdr);
1610         xfs_dir3_leaf_log_header(args, save_blk->bp);
1611         xfs_dir3_leaf_log_header(args, drop_blk->bp);
1612
1613         xfs_dir3_leaf_check(dp, save_blk->bp);
1614         xfs_dir3_leaf_check(dp, drop_blk->bp);
1615 }
1616
1617 /*
1618  * Top-level node form directory addname routine.
1619  */
1620 int                                             /* error */
1621 xfs_dir2_node_addname(
1622         xfs_da_args_t           *args)          /* operation arguments */
1623 {
1624         xfs_da_state_blk_t      *blk;           /* leaf block for insert */
1625         int                     error;          /* error return value */
1626         int                     rval;           /* sub-return value */
1627         xfs_da_state_t          *state;         /* btree cursor */
1628
1629         trace_xfs_dir2_node_addname(args);
1630
1631         /*
1632          * Allocate and initialize the state (btree cursor).
1633          */
1634         state = xfs_da_state_alloc();
1635         state->args = args;
1636         state->mp = args->dp->i_mount;
1637         /*
1638          * Look up the name.  We're not supposed to find it, but
1639          * this gives us the insertion point.
1640          */
1641         error = xfs_da3_node_lookup_int(state, &rval);
1642         if (error)
1643                 rval = error;
1644         if (rval != -ENOENT) {
1645                 goto done;
1646         }
1647         /*
1648          * Add the data entry to a data block.
1649          * Extravalid is set to a freeblock found by lookup.
1650          */
1651         rval = xfs_dir2_node_addname_int(args,
1652                 state->extravalid ? &state->extrablk : NULL);
1653         if (rval) {
1654                 goto done;
1655         }
1656         blk = &state->path.blk[state->path.active - 1];
1657         ASSERT(blk->magic == XFS_DIR2_LEAFN_MAGIC);
1658         /*
1659          * Add the new leaf entry.
1660          */
1661         rval = xfs_dir2_leafn_add(blk->bp, args, blk->index);
1662         if (rval == 0) {
1663                 /*
1664                  * It worked, fix the hash values up the btree.
1665                  */
1666                 if (!(args->op_flags & XFS_DA_OP_JUSTCHECK))
1667                         xfs_da3_fixhashpath(state, &state->path);
1668         } else {
1669                 /*
1670                  * It didn't work, we need to split the leaf block.
1671                  */
1672                 if (args->total == 0) {
1673                         ASSERT(rval == -ENOSPC);
1674                         goto done;
1675                 }
1676                 /*
1677                  * Split the leaf block and insert the new entry.
1678                  */
1679                 rval = xfs_da3_split(state);
1680         }
1681 done:
1682         xfs_da_state_free(state);
1683         return rval;
1684 }
1685
1686 /*
1687  * Add the data entry for a node-format directory name addition.
1688  * The leaf entry is added in xfs_dir2_leafn_add.
1689  * We may enter with a freespace block that the lookup found.
1690  */
1691 static int                                      /* error */
1692 xfs_dir2_node_addname_int(
1693         xfs_da_args_t           *args,          /* operation arguments */
1694         xfs_da_state_blk_t      *fblk)          /* optional freespace block */
1695 {
1696         xfs_dir2_data_hdr_t     *hdr;           /* data block header */
1697         xfs_dir2_db_t           dbno;           /* data block number */
1698         struct xfs_buf          *dbp;           /* data block buffer */
1699         xfs_dir2_data_entry_t   *dep;           /* data entry pointer */
1700         xfs_inode_t             *dp;            /* incore directory inode */
1701         xfs_dir2_data_unused_t  *dup;           /* data unused entry pointer */
1702         int                     error;          /* error return value */
1703         xfs_dir2_db_t           fbno;           /* freespace block number */
1704         struct xfs_buf          *fbp;           /* freespace buffer */
1705         int                     findex;         /* freespace entry index */
1706         xfs_dir2_free_t         *free=NULL;     /* freespace block structure */
1707         xfs_dir2_db_t           ifbno;          /* initial freespace block no */
1708         xfs_dir2_db_t           lastfbno=0;     /* highest freespace block no */
1709         int                     length;         /* length of the new entry */
1710         int                     logfree;        /* need to log free entry */
1711         xfs_mount_t             *mp;            /* filesystem mount point */
1712         int                     needlog;        /* need to log data header */
1713         int                     needscan;       /* need to rescan data frees */
1714         __be16                  *tagp;          /* data entry tag pointer */
1715         xfs_trans_t             *tp;            /* transaction pointer */
1716         __be16                  *bests;
1717         struct xfs_dir3_icfree_hdr freehdr;
1718         struct xfs_dir2_data_free *bf;
1719
1720         dp = args->dp;
1721         mp = dp->i_mount;
1722         tp = args->trans;
1723         length = dp->d_ops->data_entsize(args->namelen);
1724         /*
1725          * If we came in with a freespace block that means that lookup
1726          * found an entry with our hash value.  This is the freespace
1727          * block for that data entry.
1728          */
1729         if (fblk) {
1730                 fbp = fblk->bp;
1731                 /*
1732                  * Remember initial freespace block number.
1733                  */
1734                 ifbno = fblk->blkno;
1735                 free = fbp->b_addr;
1736                 findex = fblk->index;
1737                 bests = dp->d_ops->free_bests_p(free);
1738                 dp->d_ops->free_hdr_from_disk(&freehdr, free);
1739
1740                 /*
1741                  * This means the free entry showed that the data block had
1742                  * space for our entry, so we remembered it.
1743                  * Use that data block.
1744                  */
1745                 if (findex >= 0) {
1746                         ASSERT(findex < freehdr.nvalid);
1747                         ASSERT(be16_to_cpu(bests[findex]) != NULLDATAOFF);
1748                         ASSERT(be16_to_cpu(bests[findex]) >= length);
1749                         dbno = freehdr.firstdb + findex;
1750                 } else {
1751                         /*
1752                          * The data block looked at didn't have enough room.
1753                          * We'll start at the beginning of the freespace entries.
1754                          */
1755                         dbno = -1;
1756                         findex = 0;
1757                 }
1758         } else {
1759                 /*
1760                  * Didn't come in with a freespace block, so no data block.
1761                  */
1762                 ifbno = dbno = -1;
1763                 fbp = NULL;
1764                 findex = 0;
1765         }
1766
1767         /*
1768          * If we don't have a data block yet, we're going to scan the
1769          * freespace blocks looking for one.  Figure out what the
1770          * highest freespace block number is.
1771          */
1772         if (dbno == -1) {
1773                 xfs_fileoff_t   fo;             /* freespace block number */
1774
1775                 if ((error = xfs_bmap_last_offset(dp, &fo, XFS_DATA_FORK)))
1776                         return error;
1777                 lastfbno = xfs_dir2_da_to_db(args->geo, (xfs_dablk_t)fo);
1778                 fbno = ifbno;
1779         }
1780         /*
1781          * While we haven't identified a data block, search the freeblock
1782          * data for a good data block.  If we find a null freeblock entry,
1783          * indicating a hole in the data blocks, remember that.
1784          */
1785         while (dbno == -1) {
1786                 /*
1787                  * If we don't have a freeblock in hand, get the next one.
1788                  */
1789                 if (fbp == NULL) {
1790                         /*
1791                          * Happens the first time through unless lookup gave
1792                          * us a freespace block to start with.
1793                          */
1794                         if (++fbno == 0)
1795                                 fbno = xfs_dir2_byte_to_db(args->geo,
1796                                                         XFS_DIR2_FREE_OFFSET);
1797                         /*
1798                          * If it's ifbno we already looked at it.
1799                          */
1800                         if (fbno == ifbno)
1801                                 fbno++;
1802                         /*
1803                          * If it's off the end we're done.
1804                          */
1805                         if (fbno >= lastfbno)
1806                                 break;
1807                         /*
1808                          * Read the block.  There can be holes in the
1809                          * freespace blocks, so this might not succeed.
1810                          * This should be really rare, so there's no reason
1811                          * to avoid it.
1812                          */
1813                         error = xfs_dir2_free_try_read(tp, dp,
1814                                         xfs_dir2_db_to_da(args->geo, fbno),
1815                                         &fbp);
1816                         if (error)
1817                                 return error;
1818                         if (!fbp)
1819                                 continue;
1820                         free = fbp->b_addr;
1821                         findex = 0;
1822                 }
1823                 /*
1824                  * Look at the current free entry.  Is it good enough?
1825                  *
1826                  * The bests initialisation should be where the bufer is read in
1827                  * the above branch. But gcc is too stupid to realise that bests
1828                  * and the freehdr are actually initialised if they are placed
1829                  * there, so we have to do it here to avoid warnings. Blech.
1830                  */
1831                 bests = dp->d_ops->free_bests_p(free);
1832                 dp->d_ops->free_hdr_from_disk(&freehdr, free);
1833                 if (be16_to_cpu(bests[findex]) != NULLDATAOFF &&
1834                     be16_to_cpu(bests[findex]) >= length)
1835                         dbno = freehdr.firstdb + findex;
1836                 else {
1837                         /*
1838                          * Are we done with the freeblock?
1839                          */
1840                         if (++findex == freehdr.nvalid) {
1841                                 /*
1842                                  * Drop the block.
1843                                  */
1844                                 xfs_trans_brelse(tp, fbp);
1845                                 fbp = NULL;
1846                                 if (fblk && fblk->bp)
1847                                         fblk->bp = NULL;
1848                         }
1849                 }
1850         }
1851         /*
1852          * If we don't have a data block, we need to allocate one and make
1853          * the freespace entries refer to it.
1854          */
1855         if (unlikely(dbno == -1)) {
1856                 /*
1857                  * Not allowed to allocate, return failure.
1858                  */
1859                 if ((args->op_flags & XFS_DA_OP_JUSTCHECK) || args->total == 0)
1860                         return -ENOSPC;
1861
1862                 /*
1863                  * Allocate and initialize the new data block.
1864                  */
1865                 if (unlikely((error = xfs_dir2_grow_inode(args,
1866                                                          XFS_DIR2_DATA_SPACE,
1867                                                          &dbno)) ||
1868                     (error = xfs_dir3_data_init(args, dbno, &dbp))))
1869                         return error;
1870
1871                 /*
1872                  * If (somehow) we have a freespace block, get rid of it.
1873                  */
1874                 if (fbp)
1875                         xfs_trans_brelse(tp, fbp);
1876                 if (fblk && fblk->bp)
1877                         fblk->bp = NULL;
1878
1879                 /*
1880                  * Get the freespace block corresponding to the data block
1881                  * that was just allocated.
1882                  */
1883                 fbno = dp->d_ops->db_to_fdb(args->geo, dbno);
1884                 error = xfs_dir2_free_try_read(tp, dp,
1885                                        xfs_dir2_db_to_da(args->geo, fbno),
1886                                        &fbp);
1887                 if (error)
1888                         return error;
1889
1890                 /*
1891                  * If there wasn't a freespace block, the read will
1892                  * return a NULL fbp.  Allocate and initialize a new one.
1893                  */
1894                 if (!fbp) {
1895                         error = xfs_dir2_grow_inode(args, XFS_DIR2_FREE_SPACE,
1896                                                     &fbno);
1897                         if (error)
1898                                 return error;
1899
1900                         if (dp->d_ops->db_to_fdb(args->geo, dbno) != fbno) {
1901                                 xfs_alert(mp,
1902 "%s: dir ino %llu needed freesp block %lld for data block %lld, got %lld ifbno %llu lastfbno %d",
1903                                         __func__, (unsigned long long)dp->i_ino,
1904                                         (long long)dp->d_ops->db_to_fdb(
1905                                                                 args->geo, dbno),
1906                                         (long long)dbno, (long long)fbno,
1907                                         (unsigned long long)ifbno, lastfbno);
1908                                 if (fblk) {
1909                                         xfs_alert(mp,
1910                                 " fblk 0x%p blkno %llu index %d magic 0x%x",
1911                                                 fblk,
1912                                                 (unsigned long long)fblk->blkno,
1913                                                 fblk->index,
1914                                                 fblk->magic);
1915                                 } else {
1916                                         xfs_alert(mp, " ... fblk is NULL");
1917                                 }
1918                                 XFS_ERROR_REPORT("xfs_dir2_node_addname_int",
1919                                                  XFS_ERRLEVEL_LOW, mp);
1920                                 return -EFSCORRUPTED;
1921                         }
1922
1923                         /*
1924                          * Get a buffer for the new block.
1925                          */
1926                         error = xfs_dir3_free_get_buf(args, fbno, &fbp);
1927                         if (error)
1928                                 return error;
1929                         free = fbp->b_addr;
1930                         bests = dp->d_ops->free_bests_p(free);
1931                         dp->d_ops->free_hdr_from_disk(&freehdr, free);
1932
1933                         /*
1934                          * Remember the first slot as our empty slot.
1935                          */
1936                         freehdr.firstdb =
1937                                 (fbno - xfs_dir2_byte_to_db(args->geo,
1938                                                         XFS_DIR2_FREE_OFFSET)) *
1939                                         dp->d_ops->free_max_bests(args->geo);
1940                 } else {
1941                         free = fbp->b_addr;
1942                         bests = dp->d_ops->free_bests_p(free);
1943                         dp->d_ops->free_hdr_from_disk(&freehdr, free);
1944                 }
1945
1946                 /*
1947                  * Set the freespace block index from the data block number.
1948                  */
1949                 findex = dp->d_ops->db_to_fdindex(args->geo, dbno);
1950                 /*
1951                  * If it's after the end of the current entries in the
1952                  * freespace block, extend that table.
1953                  */
1954                 if (findex >= freehdr.nvalid) {
1955                         ASSERT(findex < dp->d_ops->free_max_bests(args->geo));
1956                         freehdr.nvalid = findex + 1;
1957                         /*
1958                          * Tag new entry so nused will go up.
1959                          */
1960                         bests[findex] = cpu_to_be16(NULLDATAOFF);
1961                 }
1962                 /*
1963                  * If this entry was for an empty data block
1964                  * (this should always be true) then update the header.
1965                  */
1966                 if (bests[findex] == cpu_to_be16(NULLDATAOFF)) {
1967                         freehdr.nused++;
1968                         dp->d_ops->free_hdr_to_disk(fbp->b_addr, &freehdr);
1969                         xfs_dir2_free_log_header(args, fbp);
1970                 }
1971                 /*
1972                  * Update the real value in the table.
1973                  * We haven't allocated the data entry yet so this will
1974                  * change again.
1975                  */
1976                 hdr = dbp->b_addr;
1977                 bf = dp->d_ops->data_bestfree_p(hdr);
1978                 bests[findex] = bf[0].length;
1979                 logfree = 1;
1980         }
1981         /*
1982          * We had a data block so we don't have to make a new one.
1983          */
1984         else {
1985                 /*
1986                  * If just checking, we succeeded.
1987                  */
1988                 if (args->op_flags & XFS_DA_OP_JUSTCHECK)
1989                         return 0;
1990
1991                 /*
1992                  * Read the data block in.
1993                  */
1994                 error = xfs_dir3_data_read(tp, dp,
1995                                            xfs_dir2_db_to_da(args->geo, dbno),
1996                                            -1, &dbp);
1997                 if (error)
1998                         return error;
1999                 hdr = dbp->b_addr;
2000                 bf = dp->d_ops->data_bestfree_p(hdr);
2001                 logfree = 0;
2002         }
2003         ASSERT(be16_to_cpu(bf[0].length) >= length);
2004         /*
2005          * Point to the existing unused space.
2006          */
2007         dup = (xfs_dir2_data_unused_t *)
2008               ((char *)hdr + be16_to_cpu(bf[0].offset));
2009         needscan = needlog = 0;
2010         /*
2011          * Mark the first part of the unused space, inuse for us.
2012          */
2013         xfs_dir2_data_use_free(args, dbp, dup,
2014                 (xfs_dir2_data_aoff_t)((char *)dup - (char *)hdr), length,
2015                 &needlog, &needscan);
2016         /*
2017          * Fill in the new entry and log it.
2018          */
2019         dep = (xfs_dir2_data_entry_t *)dup;
2020         dep->inumber = cpu_to_be64(args->inumber);
2021         dep->namelen = args->namelen;
2022         memcpy(dep->name, args->name, dep->namelen);
2023         dp->d_ops->data_put_ftype(dep, args->filetype);
2024         tagp = dp->d_ops->data_entry_tag_p(dep);
2025         *tagp = cpu_to_be16((char *)dep - (char *)hdr);
2026         xfs_dir2_data_log_entry(args, dbp, dep);
2027         /*
2028          * Rescan the block for bestfree if needed.
2029          */
2030         if (needscan)
2031                 xfs_dir2_data_freescan(dp, hdr, &needlog);
2032         /*
2033          * Log the data block header if needed.
2034          */
2035         if (needlog)
2036                 xfs_dir2_data_log_header(args, dbp);
2037         /*
2038          * If the freespace entry is now wrong, update it.
2039          */
2040         bests = dp->d_ops->free_bests_p(free); /* gcc is so stupid */
2041         if (be16_to_cpu(bests[findex]) != be16_to_cpu(bf[0].length)) {
2042                 bests[findex] = bf[0].length;
2043                 logfree = 1;
2044         }
2045         /*
2046          * Log the freespace entry if needed.
2047          */
2048         if (logfree)
2049                 xfs_dir2_free_log_bests(args, fbp, findex, findex);
2050         /*
2051          * Return the data block and offset in args, then drop the data block.
2052          */
2053         args->blkno = (xfs_dablk_t)dbno;
2054         args->index = be16_to_cpu(*tagp);
2055         return 0;
2056 }
2057
2058 /*
2059  * Lookup an entry in a node-format directory.
2060  * All the real work happens in xfs_da3_node_lookup_int.
2061  * The only real output is the inode number of the entry.
2062  */
2063 int                                             /* error */
2064 xfs_dir2_node_lookup(
2065         xfs_da_args_t   *args)                  /* operation arguments */
2066 {
2067         int             error;                  /* error return value */
2068         int             i;                      /* btree level */
2069         int             rval;                   /* operation return value */
2070         xfs_da_state_t  *state;                 /* btree cursor */
2071
2072         trace_xfs_dir2_node_lookup(args);
2073
2074         /*
2075          * Allocate and initialize the btree cursor.
2076          */
2077         state = xfs_da_state_alloc();
2078         state->args = args;
2079         state->mp = args->dp->i_mount;
2080         /*
2081          * Fill in the path to the entry in the cursor.
2082          */
2083         error = xfs_da3_node_lookup_int(state, &rval);
2084         if (error)
2085                 rval = error;
2086         else if (rval == -ENOENT && args->cmpresult == XFS_CMP_CASE) {
2087                 /* If a CI match, dup the actual name and return -EEXIST */
2088                 xfs_dir2_data_entry_t   *dep;
2089
2090                 dep = (xfs_dir2_data_entry_t *)
2091                         ((char *)state->extrablk.bp->b_addr +
2092                                                  state->extrablk.index);
2093                 rval = xfs_dir_cilookup_result(args, dep->name, dep->namelen);
2094         }
2095         /*
2096          * Release the btree blocks and leaf block.
2097          */
2098         for (i = 0; i < state->path.active; i++) {
2099                 xfs_trans_brelse(args->trans, state->path.blk[i].bp);
2100                 state->path.blk[i].bp = NULL;
2101         }
2102         /*
2103          * Release the data block if we have it.
2104          */
2105         if (state->extravalid && state->extrablk.bp) {
2106                 xfs_trans_brelse(args->trans, state->extrablk.bp);
2107                 state->extrablk.bp = NULL;
2108         }
2109         xfs_da_state_free(state);
2110         return rval;
2111 }
2112
2113 /*
2114  * Remove an entry from a node-format directory.
2115  */
2116 int                                             /* error */
2117 xfs_dir2_node_removename(
2118         struct xfs_da_args      *args)          /* operation arguments */
2119 {
2120         struct xfs_da_state_blk *blk;           /* leaf block */
2121         int                     error;          /* error return value */
2122         int                     rval;           /* operation return value */
2123         struct xfs_da_state     *state;         /* btree cursor */
2124
2125         trace_xfs_dir2_node_removename(args);
2126
2127         /*
2128          * Allocate and initialize the btree cursor.
2129          */
2130         state = xfs_da_state_alloc();
2131         state->args = args;
2132         state->mp = args->dp->i_mount;
2133
2134         /* Look up the entry we're deleting, set up the cursor. */
2135         error = xfs_da3_node_lookup_int(state, &rval);
2136         if (error)
2137                 goto out_free;
2138
2139         /* Didn't find it, upper layer screwed up. */
2140         if (rval != -EEXIST) {
2141                 error = rval;
2142                 goto out_free;
2143         }
2144
2145         blk = &state->path.blk[state->path.active - 1];
2146         ASSERT(blk->magic == XFS_DIR2_LEAFN_MAGIC);
2147         ASSERT(state->extravalid);
2148         /*
2149          * Remove the leaf and data entries.
2150          * Extrablk refers to the data block.
2151          */
2152         error = xfs_dir2_leafn_remove(args, blk->bp, blk->index,
2153                 &state->extrablk, &rval);
2154         if (error)
2155                 goto out_free;
2156         /*
2157          * Fix the hash values up the btree.
2158          */
2159         xfs_da3_fixhashpath(state, &state->path);
2160         /*
2161          * If we need to join leaf blocks, do it.
2162          */
2163         if (rval && state->path.active > 1)
2164                 error = xfs_da3_join(state);
2165         /*
2166          * If no errors so far, try conversion to leaf format.
2167          */
2168         if (!error)
2169                 error = xfs_dir2_node_to_leaf(state);
2170 out_free:
2171         xfs_da_state_free(state);
2172         return error;
2173 }
2174
2175 /*
2176  * Replace an entry's inode number in a node-format directory.
2177  */
2178 int                                             /* error */
2179 xfs_dir2_node_replace(
2180         xfs_da_args_t           *args)          /* operation arguments */
2181 {
2182         xfs_da_state_blk_t      *blk;           /* leaf block */
2183         xfs_dir2_data_hdr_t     *hdr;           /* data block header */
2184         xfs_dir2_data_entry_t   *dep;           /* data entry changed */
2185         int                     error;          /* error return value */
2186         int                     i;              /* btree level */
2187         xfs_ino_t               inum;           /* new inode number */
2188         int                     ftype;          /* new file type */
2189         xfs_dir2_leaf_t         *leaf;          /* leaf structure */
2190         xfs_dir2_leaf_entry_t   *lep;           /* leaf entry being changed */
2191         int                     rval;           /* internal return value */
2192         xfs_da_state_t          *state;         /* btree cursor */
2193
2194         trace_xfs_dir2_node_replace(args);
2195
2196         /*
2197          * Allocate and initialize the btree cursor.
2198          */
2199         state = xfs_da_state_alloc();
2200         state->args = args;
2201         state->mp = args->dp->i_mount;
2202
2203         /*
2204          * We have to save new inode number and ftype since
2205          * xfs_da3_node_lookup_int() is going to overwrite them
2206          */
2207         inum = args->inumber;
2208         ftype = args->filetype;
2209
2210         /*
2211          * Lookup the entry to change in the btree.
2212          */
2213         error = xfs_da3_node_lookup_int(state, &rval);
2214         if (error) {
2215                 rval = error;
2216         }
2217         /*
2218          * It should be found, since the vnodeops layer has looked it up
2219          * and locked it.  But paranoia is good.
2220          */
2221         if (rval == -EEXIST) {
2222                 struct xfs_dir2_leaf_entry *ents;
2223                 /*
2224                  * Find the leaf entry.
2225                  */
2226                 blk = &state->path.blk[state->path.active - 1];
2227                 ASSERT(blk->magic == XFS_DIR2_LEAFN_MAGIC);
2228                 leaf = blk->bp->b_addr;
2229                 ents = args->dp->d_ops->leaf_ents_p(leaf);
2230                 lep = &ents[blk->index];
2231                 ASSERT(state->extravalid);
2232                 /*
2233                  * Point to the data entry.
2234                  */
2235                 hdr = state->extrablk.bp->b_addr;
2236                 ASSERT(hdr->magic == cpu_to_be32(XFS_DIR2_DATA_MAGIC) ||
2237                        hdr->magic == cpu_to_be32(XFS_DIR3_DATA_MAGIC));
2238                 dep = (xfs_dir2_data_entry_t *)
2239                       ((char *)hdr +
2240                        xfs_dir2_dataptr_to_off(args->geo,
2241                                                be32_to_cpu(lep->address)));
2242                 ASSERT(inum != be64_to_cpu(dep->inumber));
2243                 /*
2244                  * Fill in the new inode number and log the entry.
2245                  */
2246                 dep->inumber = cpu_to_be64(inum);
2247                 args->dp->d_ops->data_put_ftype(dep, ftype);
2248                 xfs_dir2_data_log_entry(args, state->extrablk.bp, dep);
2249                 rval = 0;
2250         }
2251         /*
2252          * Didn't find it, and we're holding a data block.  Drop it.
2253          */
2254         else if (state->extravalid) {
2255                 xfs_trans_brelse(args->trans, state->extrablk.bp);
2256                 state->extrablk.bp = NULL;
2257         }
2258         /*
2259          * Release all the buffers in the cursor.
2260          */
2261         for (i = 0; i < state->path.active; i++) {
2262                 xfs_trans_brelse(args->trans, state->path.blk[i].bp);
2263                 state->path.blk[i].bp = NULL;
2264         }
2265         xfs_da_state_free(state);
2266         return rval;
2267 }
2268
2269 /*
2270  * Trim off a trailing empty freespace block.
2271  * Return (in rvalp) 1 if we did it, 0 if not.
2272  */
2273 int                                             /* error */
2274 xfs_dir2_node_trim_free(
2275         xfs_da_args_t           *args,          /* operation arguments */
2276         xfs_fileoff_t           fo,             /* free block number */
2277         int                     *rvalp)         /* out: did something */
2278 {
2279         struct xfs_buf          *bp;            /* freespace buffer */
2280         xfs_inode_t             *dp;            /* incore directory inode */
2281         int                     error;          /* error return code */
2282         xfs_dir2_free_t         *free;          /* freespace structure */
2283         xfs_trans_t             *tp;            /* transaction pointer */
2284         struct xfs_dir3_icfree_hdr freehdr;
2285
2286         dp = args->dp;
2287         tp = args->trans;
2288
2289         *rvalp = 0;
2290
2291         /*
2292          * Read the freespace block.
2293          */
2294         error = xfs_dir2_free_try_read(tp, dp, fo, &bp);
2295         if (error)
2296                 return error;
2297         /*
2298          * There can be holes in freespace.  If fo is a hole, there's
2299          * nothing to do.
2300          */
2301         if (!bp)
2302                 return 0;
2303         free = bp->b_addr;
2304         dp->d_ops->free_hdr_from_disk(&freehdr, free);
2305
2306         /*
2307          * If there are used entries, there's nothing to do.
2308          */
2309         if (freehdr.nused > 0) {
2310                 xfs_trans_brelse(tp, bp);
2311                 return 0;
2312         }
2313         /*
2314          * Blow the block away.
2315          */
2316         error = xfs_dir2_shrink_inode(args,
2317                         xfs_dir2_da_to_db(args->geo, (xfs_dablk_t)fo), bp);
2318         if (error) {
2319                 /*
2320                  * Can't fail with ENOSPC since that only happens with no
2321                  * space reservation, when breaking up an extent into two
2322                  * pieces.  This is the last block of an extent.
2323                  */
2324                 ASSERT(error != -ENOSPC);
2325                 xfs_trans_brelse(tp, bp);
2326                 return error;
2327         }
2328         /*
2329          * Return that we succeeded.
2330          */
2331         *rvalp = 1;
2332         return 0;
2333 }