GNU Linux-libre 4.9.297-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_leafn_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
546         if (count)
547                 *count = leafhdr.count;
548         if (!leafhdr.count)
549                 return 0;
550
551         ents = dp->d_ops->leaf_ents_p(leaf);
552         return be32_to_cpu(ents[leafhdr.count - 1].hashval);
553 }
554
555 /*
556  * Look up a leaf entry for space to add a name in a node-format leaf block.
557  * The extrablk in state is a freespace block.
558  */
559 STATIC int
560 xfs_dir2_leafn_lookup_for_addname(
561         struct xfs_buf          *bp,            /* leaf buffer */
562         xfs_da_args_t           *args,          /* operation arguments */
563         int                     *indexp,        /* out: leaf entry index */
564         xfs_da_state_t          *state)         /* state to fill in */
565 {
566         struct xfs_buf          *curbp = NULL;  /* current data/free buffer */
567         xfs_dir2_db_t           curdb = -1;     /* current data block number */
568         xfs_dir2_db_t           curfdb = -1;    /* current free block number */
569         xfs_inode_t             *dp;            /* incore directory inode */
570         int                     error;          /* error return value */
571         int                     fi;             /* free entry index */
572         xfs_dir2_free_t         *free = NULL;   /* free block structure */
573         int                     index;          /* leaf entry index */
574         xfs_dir2_leaf_t         *leaf;          /* leaf structure */
575         int                     length;         /* length of new data entry */
576         xfs_dir2_leaf_entry_t   *lep;           /* leaf entry */
577         xfs_mount_t             *mp;            /* filesystem mount point */
578         xfs_dir2_db_t           newdb;          /* new data block number */
579         xfs_dir2_db_t           newfdb;         /* new free block number */
580         xfs_trans_t             *tp;            /* transaction pointer */
581         struct xfs_dir2_leaf_entry *ents;
582         struct xfs_dir3_icleaf_hdr leafhdr;
583
584         dp = args->dp;
585         tp = args->trans;
586         mp = dp->i_mount;
587         leaf = bp->b_addr;
588         dp->d_ops->leaf_hdr_from_disk(&leafhdr, leaf);
589         ents = dp->d_ops->leaf_ents_p(leaf);
590
591         xfs_dir3_leaf_check(dp, bp);
592         ASSERT(leafhdr.count > 0);
593
594         /*
595          * Look up the hash value in the leaf entries.
596          */
597         index = xfs_dir2_leaf_search_hash(args, bp);
598         /*
599          * Do we have a buffer coming in?
600          */
601         if (state->extravalid) {
602                 /* If so, it's a free block buffer, get the block number. */
603                 curbp = state->extrablk.bp;
604                 curfdb = state->extrablk.blkno;
605                 free = curbp->b_addr;
606                 ASSERT(free->hdr.magic == cpu_to_be32(XFS_DIR2_FREE_MAGIC) ||
607                        free->hdr.magic == cpu_to_be32(XFS_DIR3_FREE_MAGIC));
608         }
609         length = dp->d_ops->data_entsize(args->namelen);
610         /*
611          * Loop over leaf entries with the right hash value.
612          */
613         for (lep = &ents[index];
614              index < leafhdr.count && be32_to_cpu(lep->hashval) == args->hashval;
615              lep++, index++) {
616                 /*
617                  * Skip stale leaf entries.
618                  */
619                 if (be32_to_cpu(lep->address) == XFS_DIR2_NULL_DATAPTR)
620                         continue;
621                 /*
622                  * Pull the data block number from the entry.
623                  */
624                 newdb = xfs_dir2_dataptr_to_db(args->geo,
625                                                be32_to_cpu(lep->address));
626                 /*
627                  * For addname, we're looking for a place to put the new entry.
628                  * We want to use a data block with an entry of equal
629                  * hash value to ours if there is one with room.
630                  *
631                  * If this block isn't the data block we already have
632                  * in hand, take a look at it.
633                  */
634                 if (newdb != curdb) {
635                         __be16 *bests;
636
637                         curdb = newdb;
638                         /*
639                          * Convert the data block to the free block
640                          * holding its freespace information.
641                          */
642                         newfdb = dp->d_ops->db_to_fdb(args->geo, newdb);
643                         /*
644                          * If it's not the one we have in hand, read it in.
645                          */
646                         if (newfdb != curfdb) {
647                                 /*
648                                  * If we had one before, drop it.
649                                  */
650                                 if (curbp)
651                                         xfs_trans_brelse(tp, curbp);
652
653                                 error = xfs_dir2_free_read(tp, dp,
654                                                 xfs_dir2_db_to_da(args->geo,
655                                                                   newfdb),
656                                                 &curbp);
657                                 if (error)
658                                         return error;
659                                 free = curbp->b_addr;
660
661                                 xfs_dir2_free_hdr_check(dp, curbp, curdb);
662                         }
663                         /*
664                          * Get the index for our entry.
665                          */
666                         fi = dp->d_ops->db_to_fdindex(args->geo, curdb);
667                         /*
668                          * If it has room, return it.
669                          */
670                         bests = dp->d_ops->free_bests_p(free);
671                         if (unlikely(bests[fi] == cpu_to_be16(NULLDATAOFF))) {
672                                 XFS_ERROR_REPORT("xfs_dir2_leafn_lookup_int",
673                                                         XFS_ERRLEVEL_LOW, mp);
674                                 if (curfdb != newfdb)
675                                         xfs_trans_brelse(tp, curbp);
676                                 return -EFSCORRUPTED;
677                         }
678                         curfdb = newfdb;
679                         if (be16_to_cpu(bests[fi]) >= length)
680                                 goto out;
681                 }
682         }
683         /* Didn't find any space */
684         fi = -1;
685 out:
686         ASSERT(args->op_flags & XFS_DA_OP_OKNOENT);
687         if (curbp) {
688                 /* Giving back a free block. */
689                 state->extravalid = 1;
690                 state->extrablk.bp = curbp;
691                 state->extrablk.index = fi;
692                 state->extrablk.blkno = curfdb;
693
694                 /*
695                  * Important: this magic number is not in the buffer - it's for
696                  * buffer type information and therefore only the free/data type
697                  * matters here, not whether CRCs are enabled or not.
698                  */
699                 state->extrablk.magic = XFS_DIR2_FREE_MAGIC;
700         } else {
701                 state->extravalid = 0;
702         }
703         /*
704          * Return the index, that will be the insertion point.
705          */
706         *indexp = index;
707         return -ENOENT;
708 }
709
710 /*
711  * Look up a leaf entry in a node-format leaf block.
712  * The extrablk in state a data block.
713  */
714 STATIC int
715 xfs_dir2_leafn_lookup_for_entry(
716         struct xfs_buf          *bp,            /* leaf buffer */
717         xfs_da_args_t           *args,          /* operation arguments */
718         int                     *indexp,        /* out: leaf entry index */
719         xfs_da_state_t          *state)         /* state to fill in */
720 {
721         struct xfs_buf          *curbp = NULL;  /* current data/free buffer */
722         xfs_dir2_db_t           curdb = -1;     /* current data block number */
723         xfs_dir2_data_entry_t   *dep;           /* data block entry */
724         xfs_inode_t             *dp;            /* incore directory inode */
725         int                     error;          /* error return value */
726         int                     index;          /* leaf entry index */
727         xfs_dir2_leaf_t         *leaf;          /* leaf structure */
728         xfs_dir2_leaf_entry_t   *lep;           /* leaf entry */
729         xfs_mount_t             *mp;            /* filesystem mount point */
730         xfs_dir2_db_t           newdb;          /* new data block number */
731         xfs_trans_t             *tp;            /* transaction pointer */
732         enum xfs_dacmp          cmp;            /* comparison result */
733         struct xfs_dir2_leaf_entry *ents;
734         struct xfs_dir3_icleaf_hdr leafhdr;
735
736         dp = args->dp;
737         tp = args->trans;
738         mp = dp->i_mount;
739         leaf = bp->b_addr;
740         dp->d_ops->leaf_hdr_from_disk(&leafhdr, leaf);
741         ents = dp->d_ops->leaf_ents_p(leaf);
742
743         xfs_dir3_leaf_check(dp, bp);
744         ASSERT(leafhdr.count > 0);
745
746         /*
747          * Look up the hash value in the leaf entries.
748          */
749         index = xfs_dir2_leaf_search_hash(args, bp);
750         /*
751          * Do we have a buffer coming in?
752          */
753         if (state->extravalid) {
754                 curbp = state->extrablk.bp;
755                 curdb = state->extrablk.blkno;
756         }
757         /*
758          * Loop over leaf entries with the right hash value.
759          */
760         for (lep = &ents[index];
761              index < leafhdr.count && be32_to_cpu(lep->hashval) == args->hashval;
762              lep++, index++) {
763                 /*
764                  * Skip stale leaf entries.
765                  */
766                 if (be32_to_cpu(lep->address) == XFS_DIR2_NULL_DATAPTR)
767                         continue;
768                 /*
769                  * Pull the data block number from the entry.
770                  */
771                 newdb = xfs_dir2_dataptr_to_db(args->geo,
772                                                be32_to_cpu(lep->address));
773                 /*
774                  * Not adding a new entry, so we really want to find
775                  * the name given to us.
776                  *
777                  * If it's a different data block, go get it.
778                  */
779                 if (newdb != curdb) {
780                         /*
781                          * If we had a block before that we aren't saving
782                          * for a CI name, drop it
783                          */
784                         if (curbp && (args->cmpresult == XFS_CMP_DIFFERENT ||
785                                                 curdb != state->extrablk.blkno))
786                                 xfs_trans_brelse(tp, curbp);
787                         /*
788                          * If needing the block that is saved with a CI match,
789                          * use it otherwise read in the new data block.
790                          */
791                         if (args->cmpresult != XFS_CMP_DIFFERENT &&
792                                         newdb == state->extrablk.blkno) {
793                                 ASSERT(state->extravalid);
794                                 curbp = state->extrablk.bp;
795                         } else {
796                                 error = xfs_dir3_data_read(tp, dp,
797                                                 xfs_dir2_db_to_da(args->geo,
798                                                                   newdb),
799                                                 -1, &curbp);
800                                 if (error)
801                                         return error;
802                         }
803                         xfs_dir3_data_check(dp, curbp);
804                         curdb = newdb;
805                 }
806                 /*
807                  * Point to the data entry.
808                  */
809                 dep = (xfs_dir2_data_entry_t *)((char *)curbp->b_addr +
810                         xfs_dir2_dataptr_to_off(args->geo,
811                                                 be32_to_cpu(lep->address)));
812                 /*
813                  * Compare the entry and if it's an exact match, return
814                  * EEXIST immediately. If it's the first case-insensitive
815                  * match, store the block & inode number and continue looking.
816                  */
817                 cmp = mp->m_dirnameops->compname(args, dep->name, dep->namelen);
818                 if (cmp != XFS_CMP_DIFFERENT && cmp != args->cmpresult) {
819                         /* If there is a CI match block, drop it */
820                         if (args->cmpresult != XFS_CMP_DIFFERENT &&
821                                                 curdb != state->extrablk.blkno)
822                                 xfs_trans_brelse(tp, state->extrablk.bp);
823                         args->cmpresult = cmp;
824                         args->inumber = be64_to_cpu(dep->inumber);
825                         args->filetype = dp->d_ops->data_get_ftype(dep);
826                         *indexp = index;
827                         state->extravalid = 1;
828                         state->extrablk.bp = curbp;
829                         state->extrablk.blkno = curdb;
830                         state->extrablk.index = (int)((char *)dep -
831                                                         (char *)curbp->b_addr);
832                         state->extrablk.magic = XFS_DIR2_DATA_MAGIC;
833                         curbp->b_ops = &xfs_dir3_data_buf_ops;
834                         xfs_trans_buf_set_type(tp, curbp, XFS_BLFT_DIR_DATA_BUF);
835                         if (cmp == XFS_CMP_EXACT)
836                                 return -EEXIST;
837                 }
838         }
839         ASSERT(index == leafhdr.count || (args->op_flags & XFS_DA_OP_OKNOENT));
840         if (curbp) {
841                 if (args->cmpresult == XFS_CMP_DIFFERENT) {
842                         /* Giving back last used data block. */
843                         state->extravalid = 1;
844                         state->extrablk.bp = curbp;
845                         state->extrablk.index = -1;
846                         state->extrablk.blkno = curdb;
847                         state->extrablk.magic = XFS_DIR2_DATA_MAGIC;
848                         curbp->b_ops = &xfs_dir3_data_buf_ops;
849                         xfs_trans_buf_set_type(tp, curbp, XFS_BLFT_DIR_DATA_BUF);
850                 } else {
851                         /* If the curbp is not the CI match block, drop it */
852                         if (state->extrablk.bp != curbp)
853                                 xfs_trans_brelse(tp, curbp);
854                 }
855         } else {
856                 state->extravalid = 0;
857         }
858         *indexp = index;
859         return -ENOENT;
860 }
861
862 /*
863  * Look up a leaf entry in a node-format leaf block.
864  * If this is an addname then the extrablk in state is a freespace block,
865  * otherwise it's a data block.
866  */
867 int
868 xfs_dir2_leafn_lookup_int(
869         struct xfs_buf          *bp,            /* leaf buffer */
870         xfs_da_args_t           *args,          /* operation arguments */
871         int                     *indexp,        /* out: leaf entry index */
872         xfs_da_state_t          *state)         /* state to fill in */
873 {
874         if (args->op_flags & XFS_DA_OP_ADDNAME)
875                 return xfs_dir2_leafn_lookup_for_addname(bp, args, indexp,
876                                                         state);
877         return xfs_dir2_leafn_lookup_for_entry(bp, args, indexp, state);
878 }
879
880 /*
881  * Move count leaf entries from source to destination leaf.
882  * Log entries and headers.  Stale entries are preserved.
883  */
884 static void
885 xfs_dir3_leafn_moveents(
886         xfs_da_args_t                   *args,  /* operation arguments */
887         struct xfs_buf                  *bp_s,  /* source */
888         struct xfs_dir3_icleaf_hdr      *shdr,
889         struct xfs_dir2_leaf_entry      *sents,
890         int                             start_s,/* source leaf index */
891         struct xfs_buf                  *bp_d,  /* destination */
892         struct xfs_dir3_icleaf_hdr      *dhdr,
893         struct xfs_dir2_leaf_entry      *dents,
894         int                             start_d,/* destination leaf index */
895         int                             count)  /* count of leaves to copy */
896 {
897         int                             stale;  /* count stale leaves copied */
898
899         trace_xfs_dir2_leafn_moveents(args, start_s, start_d, count);
900
901         /*
902          * Silently return if nothing to do.
903          */
904         if (count == 0)
905                 return;
906
907         /*
908          * If the destination index is not the end of the current
909          * destination leaf entries, open up a hole in the destination
910          * to hold the new entries.
911          */
912         if (start_d < dhdr->count) {
913                 memmove(&dents[start_d + count], &dents[start_d],
914                         (dhdr->count - start_d) * sizeof(xfs_dir2_leaf_entry_t));
915                 xfs_dir3_leaf_log_ents(args, bp_d, start_d + count,
916                                        count + dhdr->count - 1);
917         }
918         /*
919          * If the source has stale leaves, count the ones in the copy range
920          * so we can update the header correctly.
921          */
922         if (shdr->stale) {
923                 int     i;                      /* temp leaf index */
924
925                 for (i = start_s, stale = 0; i < start_s + count; i++) {
926                         if (sents[i].address ==
927                                         cpu_to_be32(XFS_DIR2_NULL_DATAPTR))
928                                 stale++;
929                 }
930         } else
931                 stale = 0;
932         /*
933          * Copy the leaf entries from source to destination.
934          */
935         memcpy(&dents[start_d], &sents[start_s],
936                 count * sizeof(xfs_dir2_leaf_entry_t));
937         xfs_dir3_leaf_log_ents(args, bp_d, start_d, start_d + count - 1);
938
939         /*
940          * If there are source entries after the ones we copied,
941          * delete the ones we copied by sliding the next ones down.
942          */
943         if (start_s + count < shdr->count) {
944                 memmove(&sents[start_s], &sents[start_s + count],
945                         count * sizeof(xfs_dir2_leaf_entry_t));
946                 xfs_dir3_leaf_log_ents(args, bp_s, start_s, start_s + count - 1);
947         }
948
949         /*
950          * Update the headers and log them.
951          */
952         shdr->count -= count;
953         shdr->stale -= stale;
954         dhdr->count += count;
955         dhdr->stale += stale;
956 }
957
958 /*
959  * Determine the sort order of two leaf blocks.
960  * Returns 1 if both are valid and leaf2 should be before leaf1, else 0.
961  */
962 int                                             /* sort order */
963 xfs_dir2_leafn_order(
964         struct xfs_inode        *dp,
965         struct xfs_buf          *leaf1_bp,              /* leaf1 buffer */
966         struct xfs_buf          *leaf2_bp)              /* leaf2 buffer */
967 {
968         struct xfs_dir2_leaf    *leaf1 = leaf1_bp->b_addr;
969         struct xfs_dir2_leaf    *leaf2 = leaf2_bp->b_addr;
970         struct xfs_dir2_leaf_entry *ents1;
971         struct xfs_dir2_leaf_entry *ents2;
972         struct xfs_dir3_icleaf_hdr hdr1;
973         struct xfs_dir3_icleaf_hdr hdr2;
974
975         dp->d_ops->leaf_hdr_from_disk(&hdr1, leaf1);
976         dp->d_ops->leaf_hdr_from_disk(&hdr2, leaf2);
977         ents1 = dp->d_ops->leaf_ents_p(leaf1);
978         ents2 = dp->d_ops->leaf_ents_p(leaf2);
979
980         if (hdr1.count > 0 && hdr2.count > 0 &&
981             (be32_to_cpu(ents2[0].hashval) < be32_to_cpu(ents1[0].hashval) ||
982              be32_to_cpu(ents2[hdr2.count - 1].hashval) <
983                                 be32_to_cpu(ents1[hdr1.count - 1].hashval)))
984                 return 1;
985         return 0;
986 }
987
988 /*
989  * Rebalance leaf entries between two leaf blocks.
990  * This is actually only called when the second block is new,
991  * though the code deals with the general case.
992  * A new entry will be inserted in one of the blocks, and that
993  * entry is taken into account when balancing.
994  */
995 static void
996 xfs_dir2_leafn_rebalance(
997         xfs_da_state_t          *state,         /* btree cursor */
998         xfs_da_state_blk_t      *blk1,          /* first btree block */
999         xfs_da_state_blk_t      *blk2)          /* second btree block */
1000 {
1001         xfs_da_args_t           *args;          /* operation arguments */
1002         int                     count;          /* count (& direction) leaves */
1003         int                     isleft;         /* new goes in left leaf */
1004         xfs_dir2_leaf_t         *leaf1;         /* first leaf structure */
1005         xfs_dir2_leaf_t         *leaf2;         /* second leaf structure */
1006         int                     mid;            /* midpoint leaf index */
1007 #if defined(DEBUG) || defined(XFS_WARN)
1008         int                     oldstale;       /* old count of stale leaves */
1009 #endif
1010         int                     oldsum;         /* old total leaf count */
1011         int                     swap;           /* swapped leaf blocks */
1012         struct xfs_dir2_leaf_entry *ents1;
1013         struct xfs_dir2_leaf_entry *ents2;
1014         struct xfs_dir3_icleaf_hdr hdr1;
1015         struct xfs_dir3_icleaf_hdr hdr2;
1016         struct xfs_inode        *dp = state->args->dp;
1017
1018         args = state->args;
1019         /*
1020          * If the block order is wrong, swap the arguments.
1021          */
1022         if ((swap = xfs_dir2_leafn_order(dp, blk1->bp, blk2->bp))) {
1023                 xfs_da_state_blk_t      *tmp;   /* temp for block swap */
1024
1025                 tmp = blk1;
1026                 blk1 = blk2;
1027                 blk2 = tmp;
1028         }
1029         leaf1 = blk1->bp->b_addr;
1030         leaf2 = blk2->bp->b_addr;
1031         dp->d_ops->leaf_hdr_from_disk(&hdr1, leaf1);
1032         dp->d_ops->leaf_hdr_from_disk(&hdr2, leaf2);
1033         ents1 = dp->d_ops->leaf_ents_p(leaf1);
1034         ents2 = dp->d_ops->leaf_ents_p(leaf2);
1035
1036         oldsum = hdr1.count + hdr2.count;
1037 #if defined(DEBUG) || defined(XFS_WARN)
1038         oldstale = hdr1.stale + hdr2.stale;
1039 #endif
1040         mid = oldsum >> 1;
1041
1042         /*
1043          * If the old leaf count was odd then the new one will be even,
1044          * so we need to divide the new count evenly.
1045          */
1046         if (oldsum & 1) {
1047                 xfs_dahash_t    midhash;        /* middle entry hash value */
1048
1049                 if (mid >= hdr1.count)
1050                         midhash = be32_to_cpu(ents2[mid - hdr1.count].hashval);
1051                 else
1052                         midhash = be32_to_cpu(ents1[mid].hashval);
1053                 isleft = args->hashval <= midhash;
1054         }
1055         /*
1056          * If the old count is even then the new count is odd, so there's
1057          * no preferred side for the new entry.
1058          * Pick the left one.
1059          */
1060         else
1061                 isleft = 1;
1062         /*
1063          * Calculate moved entry count.  Positive means left-to-right,
1064          * negative means right-to-left.  Then move the entries.
1065          */
1066         count = hdr1.count - mid + (isleft == 0);
1067         if (count > 0)
1068                 xfs_dir3_leafn_moveents(args, blk1->bp, &hdr1, ents1,
1069                                         hdr1.count - count, blk2->bp,
1070                                         &hdr2, ents2, 0, count);
1071         else if (count < 0)
1072                 xfs_dir3_leafn_moveents(args, blk2->bp, &hdr2, ents2, 0,
1073                                         blk1->bp, &hdr1, ents1,
1074                                         hdr1.count, count);
1075
1076         ASSERT(hdr1.count + hdr2.count == oldsum);
1077         ASSERT(hdr1.stale + hdr2.stale == oldstale);
1078
1079         /* log the changes made when moving the entries */
1080         dp->d_ops->leaf_hdr_to_disk(leaf1, &hdr1);
1081         dp->d_ops->leaf_hdr_to_disk(leaf2, &hdr2);
1082         xfs_dir3_leaf_log_header(args, blk1->bp);
1083         xfs_dir3_leaf_log_header(args, blk2->bp);
1084
1085         xfs_dir3_leaf_check(dp, blk1->bp);
1086         xfs_dir3_leaf_check(dp, blk2->bp);
1087
1088         /*
1089          * Mark whether we're inserting into the old or new leaf.
1090          */
1091         if (hdr1.count < hdr2.count)
1092                 state->inleaf = swap;
1093         else if (hdr1.count > hdr2.count)
1094                 state->inleaf = !swap;
1095         else
1096                 state->inleaf = swap ^ (blk1->index <= hdr1.count);
1097         /*
1098          * Adjust the expected index for insertion.
1099          */
1100         if (!state->inleaf)
1101                 blk2->index = blk1->index - hdr1.count;
1102
1103         /*
1104          * Finally sanity check just to make sure we are not returning a
1105          * negative index
1106          */
1107         if (blk2->index < 0) {
1108                 state->inleaf = 1;
1109                 blk2->index = 0;
1110                 xfs_alert(dp->i_mount,
1111         "%s: picked the wrong leaf? reverting original leaf: blk1->index %d",
1112                         __func__, blk1->index);
1113         }
1114 }
1115
1116 static int
1117 xfs_dir3_data_block_free(
1118         xfs_da_args_t           *args,
1119         struct xfs_dir2_data_hdr *hdr,
1120         struct xfs_dir2_free    *free,
1121         xfs_dir2_db_t           fdb,
1122         int                     findex,
1123         struct xfs_buf          *fbp,
1124         int                     longest)
1125 {
1126         int                     logfree = 0;
1127         __be16                  *bests;
1128         struct xfs_dir3_icfree_hdr freehdr;
1129         struct xfs_inode        *dp = args->dp;
1130
1131         dp->d_ops->free_hdr_from_disk(&freehdr, free);
1132         bests = dp->d_ops->free_bests_p(free);
1133         if (hdr) {
1134                 /*
1135                  * Data block is not empty, just set the free entry to the new
1136                  * value.
1137                  */
1138                 bests[findex] = cpu_to_be16(longest);
1139                 xfs_dir2_free_log_bests(args, fbp, findex, findex);
1140                 return 0;
1141         }
1142
1143         /* One less used entry in the free table. */
1144         freehdr.nused--;
1145
1146         /*
1147          * If this was the last entry in the table, we can trim the table size
1148          * back.  There might be other entries at the end referring to
1149          * non-existent data blocks, get those too.
1150          */
1151         if (findex == freehdr.nvalid - 1) {
1152                 int     i;              /* free entry index */
1153
1154                 for (i = findex - 1; i >= 0; i--) {
1155                         if (bests[i] != cpu_to_be16(NULLDATAOFF))
1156                                 break;
1157                 }
1158                 freehdr.nvalid = i + 1;
1159                 logfree = 0;
1160         } else {
1161                 /* Not the last entry, just punch it out.  */
1162                 bests[findex] = cpu_to_be16(NULLDATAOFF);
1163                 logfree = 1;
1164         }
1165
1166         dp->d_ops->free_hdr_to_disk(free, &freehdr);
1167         xfs_dir2_free_log_header(args, fbp);
1168
1169         /*
1170          * If there are no useful entries left in the block, get rid of the
1171          * block if we can.
1172          */
1173         if (!freehdr.nused) {
1174                 int error;
1175
1176                 error = xfs_dir2_shrink_inode(args, fdb, fbp);
1177                 if (error == 0) {
1178                         fbp = NULL;
1179                         logfree = 0;
1180                 } else if (error != -ENOSPC || args->total != 0)
1181                         return error;
1182                 /*
1183                  * It's possible to get ENOSPC if there is no
1184                  * space reservation.  In this case some one
1185                  * else will eventually get rid of this block.
1186                  */
1187         }
1188
1189         /* Log the free entry that changed, unless we got rid of it.  */
1190         if (logfree)
1191                 xfs_dir2_free_log_bests(args, fbp, findex, findex);
1192         return 0;
1193 }
1194
1195 /*
1196  * Remove an entry from a node directory.
1197  * This removes the leaf entry and the data entry,
1198  * and updates the free block if necessary.
1199  */
1200 static int                                      /* error */
1201 xfs_dir2_leafn_remove(
1202         xfs_da_args_t           *args,          /* operation arguments */
1203         struct xfs_buf          *bp,            /* leaf buffer */
1204         int                     index,          /* leaf entry index */
1205         xfs_da_state_blk_t      *dblk,          /* data block */
1206         int                     *rval)          /* resulting block needs join */
1207 {
1208         xfs_dir2_data_hdr_t     *hdr;           /* data block header */
1209         xfs_dir2_db_t           db;             /* data block number */
1210         struct xfs_buf          *dbp;           /* data block buffer */
1211         xfs_dir2_data_entry_t   *dep;           /* data block entry */
1212         xfs_inode_t             *dp;            /* incore directory inode */
1213         xfs_dir2_leaf_t         *leaf;          /* leaf structure */
1214         xfs_dir2_leaf_entry_t   *lep;           /* leaf entry */
1215         int                     longest;        /* longest data free entry */
1216         int                     off;            /* data block entry offset */
1217         int                     needlog;        /* need to log data header */
1218         int                     needscan;       /* need to rescan data frees */
1219         xfs_trans_t             *tp;            /* transaction pointer */
1220         struct xfs_dir2_data_free *bf;          /* bestfree table */
1221         struct xfs_dir3_icleaf_hdr leafhdr;
1222         struct xfs_dir2_leaf_entry *ents;
1223
1224         trace_xfs_dir2_leafn_remove(args, index);
1225
1226         dp = args->dp;
1227         tp = args->trans;
1228         leaf = bp->b_addr;
1229         dp->d_ops->leaf_hdr_from_disk(&leafhdr, leaf);
1230         ents = dp->d_ops->leaf_ents_p(leaf);
1231
1232         /*
1233          * Point to the entry we're removing.
1234          */
1235         lep = &ents[index];
1236
1237         /*
1238          * Extract the data block and offset from the entry.
1239          */
1240         db = xfs_dir2_dataptr_to_db(args->geo, be32_to_cpu(lep->address));
1241         ASSERT(dblk->blkno == db);
1242         off = xfs_dir2_dataptr_to_off(args->geo, be32_to_cpu(lep->address));
1243         ASSERT(dblk->index == off);
1244
1245         /*
1246          * Kill the leaf entry by marking it stale.
1247          * Log the leaf block changes.
1248          */
1249         leafhdr.stale++;
1250         dp->d_ops->leaf_hdr_to_disk(leaf, &leafhdr);
1251         xfs_dir3_leaf_log_header(args, bp);
1252
1253         lep->address = cpu_to_be32(XFS_DIR2_NULL_DATAPTR);
1254         xfs_dir3_leaf_log_ents(args, bp, index, index);
1255
1256         /*
1257          * Make the data entry free.  Keep track of the longest freespace
1258          * in the data block in case it changes.
1259          */
1260         dbp = dblk->bp;
1261         hdr = dbp->b_addr;
1262         dep = (xfs_dir2_data_entry_t *)((char *)hdr + off);
1263         bf = dp->d_ops->data_bestfree_p(hdr);
1264         longest = be16_to_cpu(bf[0].length);
1265         needlog = needscan = 0;
1266         xfs_dir2_data_make_free(args, dbp, off,
1267                 dp->d_ops->data_entsize(dep->namelen), &needlog, &needscan);
1268         /*
1269          * Rescan the data block freespaces for bestfree.
1270          * Log the data block header if needed.
1271          */
1272         if (needscan)
1273                 xfs_dir2_data_freescan(dp, hdr, &needlog);
1274         if (needlog)
1275                 xfs_dir2_data_log_header(args, dbp);
1276         xfs_dir3_data_check(dp, dbp);
1277         /*
1278          * If the longest data block freespace changes, need to update
1279          * the corresponding freeblock entry.
1280          */
1281         if (longest < be16_to_cpu(bf[0].length)) {
1282                 int             error;          /* error return value */
1283                 struct xfs_buf  *fbp;           /* freeblock buffer */
1284                 xfs_dir2_db_t   fdb;            /* freeblock block number */
1285                 int             findex;         /* index in freeblock entries */
1286                 xfs_dir2_free_t *free;          /* freeblock structure */
1287
1288                 /*
1289                  * Convert the data block number to a free block,
1290                  * read in the free block.
1291                  */
1292                 fdb = dp->d_ops->db_to_fdb(args->geo, db);
1293                 error = xfs_dir2_free_read(tp, dp,
1294                                            xfs_dir2_db_to_da(args->geo, fdb),
1295                                            &fbp);
1296                 if (error)
1297                         return error;
1298                 free = fbp->b_addr;
1299 #ifdef DEBUG
1300         {
1301                 struct xfs_dir3_icfree_hdr freehdr;
1302                 dp->d_ops->free_hdr_from_disk(&freehdr, free);
1303                 ASSERT(freehdr.firstdb == dp->d_ops->free_max_bests(args->geo) *
1304                         (fdb - xfs_dir2_byte_to_db(args->geo,
1305                                                    XFS_DIR2_FREE_OFFSET)));
1306         }
1307 #endif
1308                 /*
1309                  * Calculate which entry we need to fix.
1310                  */
1311                 findex = dp->d_ops->db_to_fdindex(args->geo, db);
1312                 longest = be16_to_cpu(bf[0].length);
1313                 /*
1314                  * If the data block is now empty we can get rid of it
1315                  * (usually).
1316                  */
1317                 if (longest == args->geo->blksize -
1318                                dp->d_ops->data_entry_offset) {
1319                         /*
1320                          * Try to punch out the data block.
1321                          */
1322                         error = xfs_dir2_shrink_inode(args, db, dbp);
1323                         if (error == 0) {
1324                                 dblk->bp = NULL;
1325                                 hdr = NULL;
1326                         }
1327                         /*
1328                          * We can get ENOSPC if there's no space reservation.
1329                          * In this case just drop the buffer and some one else
1330                          * will eventually get rid of the empty block.
1331                          */
1332                         else if (!(error == -ENOSPC && args->total == 0))
1333                                 return error;
1334                 }
1335                 /*
1336                  * If we got rid of the data block, we can eliminate that entry
1337                  * in the free block.
1338                  */
1339                 error = xfs_dir3_data_block_free(args, hdr, free,
1340                                                  fdb, findex, fbp, longest);
1341                 if (error)
1342                         return error;
1343         }
1344
1345         xfs_dir3_leaf_check(dp, bp);
1346         /*
1347          * Return indication of whether this leaf block is empty enough
1348          * to justify trying to join it with a neighbor.
1349          */
1350         *rval = (dp->d_ops->leaf_hdr_size +
1351                  (uint)sizeof(ents[0]) * (leafhdr.count - leafhdr.stale)) <
1352                 args->geo->magicpct;
1353         return 0;
1354 }
1355
1356 /*
1357  * Split the leaf entries in the old block into old and new blocks.
1358  */
1359 int                                             /* error */
1360 xfs_dir2_leafn_split(
1361         xfs_da_state_t          *state,         /* btree cursor */
1362         xfs_da_state_blk_t      *oldblk,        /* original block */
1363         xfs_da_state_blk_t      *newblk)        /* newly created block */
1364 {
1365         xfs_da_args_t           *args;          /* operation arguments */
1366         xfs_dablk_t             blkno;          /* new leaf block number */
1367         int                     error;          /* error return value */
1368         struct xfs_inode        *dp;
1369
1370         /*
1371          * Allocate space for a new leaf node.
1372          */
1373         args = state->args;
1374         dp = args->dp;
1375         ASSERT(oldblk->magic == XFS_DIR2_LEAFN_MAGIC);
1376         error = xfs_da_grow_inode(args, &blkno);
1377         if (error) {
1378                 return error;
1379         }
1380         /*
1381          * Initialize the new leaf block.
1382          */
1383         error = xfs_dir3_leaf_get_buf(args, xfs_dir2_da_to_db(args->geo, blkno),
1384                                       &newblk->bp, XFS_DIR2_LEAFN_MAGIC);
1385         if (error)
1386                 return error;
1387
1388         newblk->blkno = blkno;
1389         newblk->magic = XFS_DIR2_LEAFN_MAGIC;
1390         /*
1391          * Rebalance the entries across the two leaves, link the new
1392          * block into the leaves.
1393          */
1394         xfs_dir2_leafn_rebalance(state, oldblk, newblk);
1395         error = xfs_da3_blk_link(state, oldblk, newblk);
1396         if (error) {
1397                 return error;
1398         }
1399         /*
1400          * Insert the new entry in the correct block.
1401          */
1402         if (state->inleaf)
1403                 error = xfs_dir2_leafn_add(oldblk->bp, args, oldblk->index);
1404         else
1405                 error = xfs_dir2_leafn_add(newblk->bp, args, newblk->index);
1406         /*
1407          * Update last hashval in each block since we added the name.
1408          */
1409         oldblk->hashval = xfs_dir2_leafn_lasthash(dp, oldblk->bp, NULL);
1410         newblk->hashval = xfs_dir2_leafn_lasthash(dp, newblk->bp, NULL);
1411         xfs_dir3_leaf_check(dp, oldblk->bp);
1412         xfs_dir3_leaf_check(dp, newblk->bp);
1413         return error;
1414 }
1415
1416 /*
1417  * Check a leaf block and its neighbors to see if the block should be
1418  * collapsed into one or the other neighbor.  Always keep the block
1419  * with the smaller block number.
1420  * If the current block is over 50% full, don't try to join it, return 0.
1421  * If the block is empty, fill in the state structure and return 2.
1422  * If it can be collapsed, fill in the state structure and return 1.
1423  * If nothing can be done, return 0.
1424  */
1425 int                                             /* error */
1426 xfs_dir2_leafn_toosmall(
1427         xfs_da_state_t          *state,         /* btree cursor */
1428         int                     *action)        /* resulting action to take */
1429 {
1430         xfs_da_state_blk_t      *blk;           /* leaf block */
1431         xfs_dablk_t             blkno;          /* leaf block number */
1432         struct xfs_buf          *bp;            /* leaf buffer */
1433         int                     bytes;          /* bytes in use */
1434         int                     count;          /* leaf live entry count */
1435         int                     error;          /* error return value */
1436         int                     forward;        /* sibling block direction */
1437         int                     i;              /* sibling counter */
1438         xfs_dir2_leaf_t         *leaf;          /* leaf structure */
1439         int                     rval;           /* result from path_shift */
1440         struct xfs_dir3_icleaf_hdr leafhdr;
1441         struct xfs_dir2_leaf_entry *ents;
1442         struct xfs_inode        *dp = state->args->dp;
1443
1444         /*
1445          * Check for the degenerate case of the block being over 50% full.
1446          * If so, it's not worth even looking to see if we might be able
1447          * to coalesce with a sibling.
1448          */
1449         blk = &state->path.blk[state->path.active - 1];
1450         leaf = blk->bp->b_addr;
1451         dp->d_ops->leaf_hdr_from_disk(&leafhdr, leaf);
1452         ents = dp->d_ops->leaf_ents_p(leaf);
1453         xfs_dir3_leaf_check(dp, blk->bp);
1454
1455         count = leafhdr.count - leafhdr.stale;
1456         bytes = dp->d_ops->leaf_hdr_size + count * sizeof(ents[0]);
1457         if (bytes > (state->args->geo->blksize >> 1)) {
1458                 /*
1459                  * Blk over 50%, don't try to join.
1460                  */
1461                 *action = 0;
1462                 return 0;
1463         }
1464         /*
1465          * Check for the degenerate case of the block being empty.
1466          * If the block is empty, we'll simply delete it, no need to
1467          * coalesce it with a sibling block.  We choose (arbitrarily)
1468          * to merge with the forward block unless it is NULL.
1469          */
1470         if (count == 0) {
1471                 /*
1472                  * Make altpath point to the block we want to keep and
1473                  * path point to the block we want to drop (this one).
1474                  */
1475                 forward = (leafhdr.forw != 0);
1476                 memcpy(&state->altpath, &state->path, sizeof(state->path));
1477                 error = xfs_da3_path_shift(state, &state->altpath, forward, 0,
1478                         &rval);
1479                 if (error)
1480                         return error;
1481                 *action = rval ? 2 : 0;
1482                 return 0;
1483         }
1484         /*
1485          * Examine each sibling block to see if we can coalesce with
1486          * at least 25% free space to spare.  We need to figure out
1487          * whether to merge with the forward or the backward block.
1488          * We prefer coalescing with the lower numbered sibling so as
1489          * to shrink a directory over time.
1490          */
1491         forward = leafhdr.forw < leafhdr.back;
1492         for (i = 0, bp = NULL; i < 2; forward = !forward, i++) {
1493                 struct xfs_dir3_icleaf_hdr hdr2;
1494
1495                 blkno = forward ? leafhdr.forw : leafhdr.back;
1496                 if (blkno == 0)
1497                         continue;
1498                 /*
1499                  * Read the sibling leaf block.
1500                  */
1501                 error = xfs_dir3_leafn_read(state->args->trans, dp,
1502                                             blkno, -1, &bp);
1503                 if (error)
1504                         return error;
1505
1506                 /*
1507                  * Count bytes in the two blocks combined.
1508                  */
1509                 count = leafhdr.count - leafhdr.stale;
1510                 bytes = state->args->geo->blksize -
1511                         (state->args->geo->blksize >> 2);
1512
1513                 leaf = bp->b_addr;
1514                 dp->d_ops->leaf_hdr_from_disk(&hdr2, leaf);
1515                 ents = dp->d_ops->leaf_ents_p(leaf);
1516                 count += hdr2.count - hdr2.stale;
1517                 bytes -= count * sizeof(ents[0]);
1518
1519                 /*
1520                  * Fits with at least 25% to spare.
1521                  */
1522                 if (bytes >= 0)
1523                         break;
1524                 xfs_trans_brelse(state->args->trans, bp);
1525         }
1526         /*
1527          * Didn't like either block, give up.
1528          */
1529         if (i >= 2) {
1530                 *action = 0;
1531                 return 0;
1532         }
1533
1534         /*
1535          * Make altpath point to the block we want to keep (the lower
1536          * numbered block) and path point to the block we want to drop.
1537          */
1538         memcpy(&state->altpath, &state->path, sizeof(state->path));
1539         if (blkno < blk->blkno)
1540                 error = xfs_da3_path_shift(state, &state->altpath, forward, 0,
1541                         &rval);
1542         else
1543                 error = xfs_da3_path_shift(state, &state->path, forward, 0,
1544                         &rval);
1545         if (error) {
1546                 return error;
1547         }
1548         *action = rval ? 0 : 1;
1549         return 0;
1550 }
1551
1552 /*
1553  * Move all the leaf entries from drop_blk to save_blk.
1554  * This is done as part of a join operation.
1555  */
1556 void
1557 xfs_dir2_leafn_unbalance(
1558         xfs_da_state_t          *state,         /* cursor */
1559         xfs_da_state_blk_t      *drop_blk,      /* dead block */
1560         xfs_da_state_blk_t      *save_blk)      /* surviving block */
1561 {
1562         xfs_da_args_t           *args;          /* operation arguments */
1563         xfs_dir2_leaf_t         *drop_leaf;     /* dead leaf structure */
1564         xfs_dir2_leaf_t         *save_leaf;     /* surviving leaf structure */
1565         struct xfs_dir3_icleaf_hdr savehdr;
1566         struct xfs_dir3_icleaf_hdr drophdr;
1567         struct xfs_dir2_leaf_entry *sents;
1568         struct xfs_dir2_leaf_entry *dents;
1569         struct xfs_inode        *dp = state->args->dp;
1570
1571         args = state->args;
1572         ASSERT(drop_blk->magic == XFS_DIR2_LEAFN_MAGIC);
1573         ASSERT(save_blk->magic == XFS_DIR2_LEAFN_MAGIC);
1574         drop_leaf = drop_blk->bp->b_addr;
1575         save_leaf = save_blk->bp->b_addr;
1576
1577         dp->d_ops->leaf_hdr_from_disk(&savehdr, save_leaf);
1578         dp->d_ops->leaf_hdr_from_disk(&drophdr, drop_leaf);
1579         sents = dp->d_ops->leaf_ents_p(save_leaf);
1580         dents = dp->d_ops->leaf_ents_p(drop_leaf);
1581
1582         /*
1583          * If there are any stale leaf entries, take this opportunity
1584          * to purge them.
1585          */
1586         if (drophdr.stale)
1587                 xfs_dir3_leaf_compact(args, &drophdr, drop_blk->bp);
1588         if (savehdr.stale)
1589                 xfs_dir3_leaf_compact(args, &savehdr, save_blk->bp);
1590
1591         /*
1592          * Move the entries from drop to the appropriate end of save.
1593          */
1594         drop_blk->hashval = be32_to_cpu(dents[drophdr.count - 1].hashval);
1595         if (xfs_dir2_leafn_order(dp, save_blk->bp, drop_blk->bp))
1596                 xfs_dir3_leafn_moveents(args, drop_blk->bp, &drophdr, dents, 0,
1597                                         save_blk->bp, &savehdr, sents, 0,
1598                                         drophdr.count);
1599         else
1600                 xfs_dir3_leafn_moveents(args, drop_blk->bp, &drophdr, dents, 0,
1601                                         save_blk->bp, &savehdr, sents,
1602                                         savehdr.count, drophdr.count);
1603         save_blk->hashval = be32_to_cpu(sents[savehdr.count - 1].hashval);
1604
1605         /* log the changes made when moving the entries */
1606         dp->d_ops->leaf_hdr_to_disk(save_leaf, &savehdr);
1607         dp->d_ops->leaf_hdr_to_disk(drop_leaf, &drophdr);
1608         xfs_dir3_leaf_log_header(args, save_blk->bp);
1609         xfs_dir3_leaf_log_header(args, drop_blk->bp);
1610
1611         xfs_dir3_leaf_check(dp, save_blk->bp);
1612         xfs_dir3_leaf_check(dp, drop_blk->bp);
1613 }
1614
1615 /*
1616  * Top-level node form directory addname routine.
1617  */
1618 int                                             /* error */
1619 xfs_dir2_node_addname(
1620         xfs_da_args_t           *args)          /* operation arguments */
1621 {
1622         xfs_da_state_blk_t      *blk;           /* leaf block for insert */
1623         int                     error;          /* error return value */
1624         int                     rval;           /* sub-return value */
1625         xfs_da_state_t          *state;         /* btree cursor */
1626
1627         trace_xfs_dir2_node_addname(args);
1628
1629         /*
1630          * Allocate and initialize the state (btree cursor).
1631          */
1632         state = xfs_da_state_alloc();
1633         state->args = args;
1634         state->mp = args->dp->i_mount;
1635         /*
1636          * Look up the name.  We're not supposed to find it, but
1637          * this gives us the insertion point.
1638          */
1639         error = xfs_da3_node_lookup_int(state, &rval);
1640         if (error)
1641                 rval = error;
1642         if (rval != -ENOENT) {
1643                 goto done;
1644         }
1645         /*
1646          * Add the data entry to a data block.
1647          * Extravalid is set to a freeblock found by lookup.
1648          */
1649         rval = xfs_dir2_node_addname_int(args,
1650                 state->extravalid ? &state->extrablk : NULL);
1651         if (rval) {
1652                 goto done;
1653         }
1654         blk = &state->path.blk[state->path.active - 1];
1655         ASSERT(blk->magic == XFS_DIR2_LEAFN_MAGIC);
1656         /*
1657          * Add the new leaf entry.
1658          */
1659         rval = xfs_dir2_leafn_add(blk->bp, args, blk->index);
1660         if (rval == 0) {
1661                 /*
1662                  * It worked, fix the hash values up the btree.
1663                  */
1664                 if (!(args->op_flags & XFS_DA_OP_JUSTCHECK))
1665                         xfs_da3_fixhashpath(state, &state->path);
1666         } else {
1667                 /*
1668                  * It didn't work, we need to split the leaf block.
1669                  */
1670                 if (args->total == 0) {
1671                         ASSERT(rval == -ENOSPC);
1672                         goto done;
1673                 }
1674                 /*
1675                  * Split the leaf block and insert the new entry.
1676                  */
1677                 rval = xfs_da3_split(state);
1678         }
1679 done:
1680         xfs_da_state_free(state);
1681         return rval;
1682 }
1683
1684 /*
1685  * Add the data entry for a node-format directory name addition.
1686  * The leaf entry is added in xfs_dir2_leafn_add.
1687  * We may enter with a freespace block that the lookup found.
1688  */
1689 static int                                      /* error */
1690 xfs_dir2_node_addname_int(
1691         xfs_da_args_t           *args,          /* operation arguments */
1692         xfs_da_state_blk_t      *fblk)          /* optional freespace block */
1693 {
1694         xfs_dir2_data_hdr_t     *hdr;           /* data block header */
1695         xfs_dir2_db_t           dbno;           /* data block number */
1696         struct xfs_buf          *dbp;           /* data block buffer */
1697         xfs_dir2_data_entry_t   *dep;           /* data entry pointer */
1698         xfs_inode_t             *dp;            /* incore directory inode */
1699         xfs_dir2_data_unused_t  *dup;           /* data unused entry pointer */
1700         int                     error;          /* error return value */
1701         xfs_dir2_db_t           fbno;           /* freespace block number */
1702         struct xfs_buf          *fbp;           /* freespace buffer */
1703         int                     findex;         /* freespace entry index */
1704         xfs_dir2_free_t         *free=NULL;     /* freespace block structure */
1705         xfs_dir2_db_t           ifbno;          /* initial freespace block no */
1706         xfs_dir2_db_t           lastfbno=0;     /* highest freespace block no */
1707         int                     length;         /* length of the new entry */
1708         int                     logfree;        /* need to log free entry */
1709         xfs_mount_t             *mp;            /* filesystem mount point */
1710         int                     needlog;        /* need to log data header */
1711         int                     needscan;       /* need to rescan data frees */
1712         __be16                  *tagp;          /* data entry tag pointer */
1713         xfs_trans_t             *tp;            /* transaction pointer */
1714         __be16                  *bests;
1715         struct xfs_dir3_icfree_hdr freehdr;
1716         struct xfs_dir2_data_free *bf;
1717
1718         dp = args->dp;
1719         mp = dp->i_mount;
1720         tp = args->trans;
1721         length = dp->d_ops->data_entsize(args->namelen);
1722         /*
1723          * If we came in with a freespace block that means that lookup
1724          * found an entry with our hash value.  This is the freespace
1725          * block for that data entry.
1726          */
1727         if (fblk) {
1728                 fbp = fblk->bp;
1729                 /*
1730                  * Remember initial freespace block number.
1731                  */
1732                 ifbno = fblk->blkno;
1733                 free = fbp->b_addr;
1734                 findex = fblk->index;
1735                 bests = dp->d_ops->free_bests_p(free);
1736                 dp->d_ops->free_hdr_from_disk(&freehdr, free);
1737
1738                 /*
1739                  * This means the free entry showed that the data block had
1740                  * space for our entry, so we remembered it.
1741                  * Use that data block.
1742                  */
1743                 if (findex >= 0) {
1744                         ASSERT(findex < freehdr.nvalid);
1745                         ASSERT(be16_to_cpu(bests[findex]) != NULLDATAOFF);
1746                         ASSERT(be16_to_cpu(bests[findex]) >= length);
1747                         dbno = freehdr.firstdb + findex;
1748                 } else {
1749                         /*
1750                          * The data block looked at didn't have enough room.
1751                          * We'll start at the beginning of the freespace entries.
1752                          */
1753                         dbno = -1;
1754                         findex = 0;
1755                 }
1756         } else {
1757                 /*
1758                  * Didn't come in with a freespace block, so no data block.
1759                  */
1760                 ifbno = dbno = -1;
1761                 fbp = NULL;
1762                 findex = 0;
1763         }
1764
1765         /*
1766          * If we don't have a data block yet, we're going to scan the
1767          * freespace blocks looking for one.  Figure out what the
1768          * highest freespace block number is.
1769          */
1770         if (dbno == -1) {
1771                 xfs_fileoff_t   fo;             /* freespace block number */
1772
1773                 if ((error = xfs_bmap_last_offset(dp, &fo, XFS_DATA_FORK)))
1774                         return error;
1775                 lastfbno = xfs_dir2_da_to_db(args->geo, (xfs_dablk_t)fo);
1776                 fbno = ifbno;
1777         }
1778         /*
1779          * While we haven't identified a data block, search the freeblock
1780          * data for a good data block.  If we find a null freeblock entry,
1781          * indicating a hole in the data blocks, remember that.
1782          */
1783         while (dbno == -1) {
1784                 /*
1785                  * If we don't have a freeblock in hand, get the next one.
1786                  */
1787                 if (fbp == NULL) {
1788                         /*
1789                          * Happens the first time through unless lookup gave
1790                          * us a freespace block to start with.
1791                          */
1792                         if (++fbno == 0)
1793                                 fbno = xfs_dir2_byte_to_db(args->geo,
1794                                                         XFS_DIR2_FREE_OFFSET);
1795                         /*
1796                          * If it's ifbno we already looked at it.
1797                          */
1798                         if (fbno == ifbno)
1799                                 fbno++;
1800                         /*
1801                          * If it's off the end we're done.
1802                          */
1803                         if (fbno >= lastfbno)
1804                                 break;
1805                         /*
1806                          * Read the block.  There can be holes in the
1807                          * freespace blocks, so this might not succeed.
1808                          * This should be really rare, so there's no reason
1809                          * to avoid it.
1810                          */
1811                         error = xfs_dir2_free_try_read(tp, dp,
1812                                         xfs_dir2_db_to_da(args->geo, fbno),
1813                                         &fbp);
1814                         if (error)
1815                                 return error;
1816                         if (!fbp)
1817                                 continue;
1818                         free = fbp->b_addr;
1819                         findex = 0;
1820                 }
1821                 /*
1822                  * Look at the current free entry.  Is it good enough?
1823                  *
1824                  * The bests initialisation should be where the bufer is read in
1825                  * the above branch. But gcc is too stupid to realise that bests
1826                  * and the freehdr are actually initialised if they are placed
1827                  * there, so we have to do it here to avoid warnings. Blech.
1828                  */
1829                 bests = dp->d_ops->free_bests_p(free);
1830                 dp->d_ops->free_hdr_from_disk(&freehdr, free);
1831                 if (be16_to_cpu(bests[findex]) != NULLDATAOFF &&
1832                     be16_to_cpu(bests[findex]) >= length)
1833                         dbno = freehdr.firstdb + findex;
1834                 else {
1835                         /*
1836                          * Are we done with the freeblock?
1837                          */
1838                         if (++findex == freehdr.nvalid) {
1839                                 /*
1840                                  * Drop the block.
1841                                  */
1842                                 xfs_trans_brelse(tp, fbp);
1843                                 fbp = NULL;
1844                                 if (fblk && fblk->bp)
1845                                         fblk->bp = NULL;
1846                         }
1847                 }
1848         }
1849         /*
1850          * If we don't have a data block, we need to allocate one and make
1851          * the freespace entries refer to it.
1852          */
1853         if (unlikely(dbno == -1)) {
1854                 /*
1855                  * Not allowed to allocate, return failure.
1856                  */
1857                 if ((args->op_flags & XFS_DA_OP_JUSTCHECK) || args->total == 0)
1858                         return -ENOSPC;
1859
1860                 /*
1861                  * Allocate and initialize the new data block.
1862                  */
1863                 if (unlikely((error = xfs_dir2_grow_inode(args,
1864                                                          XFS_DIR2_DATA_SPACE,
1865                                                          &dbno)) ||
1866                     (error = xfs_dir3_data_init(args, dbno, &dbp))))
1867                         return error;
1868
1869                 /*
1870                  * If (somehow) we have a freespace block, get rid of it.
1871                  */
1872                 if (fbp)
1873                         xfs_trans_brelse(tp, fbp);
1874                 if (fblk && fblk->bp)
1875                         fblk->bp = NULL;
1876
1877                 /*
1878                  * Get the freespace block corresponding to the data block
1879                  * that was just allocated.
1880                  */
1881                 fbno = dp->d_ops->db_to_fdb(args->geo, dbno);
1882                 error = xfs_dir2_free_try_read(tp, dp,
1883                                        xfs_dir2_db_to_da(args->geo, fbno),
1884                                        &fbp);
1885                 if (error)
1886                         return error;
1887
1888                 /*
1889                  * If there wasn't a freespace block, the read will
1890                  * return a NULL fbp.  Allocate and initialize a new one.
1891                  */
1892                 if (!fbp) {
1893                         error = xfs_dir2_grow_inode(args, XFS_DIR2_FREE_SPACE,
1894                                                     &fbno);
1895                         if (error)
1896                                 return error;
1897
1898                         if (dp->d_ops->db_to_fdb(args->geo, dbno) != fbno) {
1899                                 xfs_alert(mp,
1900 "%s: dir ino %llu needed freesp block %lld for data block %lld, got %lld ifbno %llu lastfbno %d",
1901                                         __func__, (unsigned long long)dp->i_ino,
1902                                         (long long)dp->d_ops->db_to_fdb(
1903                                                                 args->geo, dbno),
1904                                         (long long)dbno, (long long)fbno,
1905                                         (unsigned long long)ifbno, lastfbno);
1906                                 if (fblk) {
1907                                         xfs_alert(mp,
1908                                 " fblk 0x%p blkno %llu index %d magic 0x%x",
1909                                                 fblk,
1910                                                 (unsigned long long)fblk->blkno,
1911                                                 fblk->index,
1912                                                 fblk->magic);
1913                                 } else {
1914                                         xfs_alert(mp, " ... fblk is NULL");
1915                                 }
1916                                 XFS_ERROR_REPORT("xfs_dir2_node_addname_int",
1917                                                  XFS_ERRLEVEL_LOW, mp);
1918                                 return -EFSCORRUPTED;
1919                         }
1920
1921                         /*
1922                          * Get a buffer for the new block.
1923                          */
1924                         error = xfs_dir3_free_get_buf(args, fbno, &fbp);
1925                         if (error)
1926                                 return error;
1927                         free = fbp->b_addr;
1928                         bests = dp->d_ops->free_bests_p(free);
1929                         dp->d_ops->free_hdr_from_disk(&freehdr, free);
1930
1931                         /*
1932                          * Remember the first slot as our empty slot.
1933                          */
1934                         freehdr.firstdb =
1935                                 (fbno - xfs_dir2_byte_to_db(args->geo,
1936                                                         XFS_DIR2_FREE_OFFSET)) *
1937                                         dp->d_ops->free_max_bests(args->geo);
1938                 } else {
1939                         free = fbp->b_addr;
1940                         bests = dp->d_ops->free_bests_p(free);
1941                         dp->d_ops->free_hdr_from_disk(&freehdr, free);
1942                 }
1943
1944                 /*
1945                  * Set the freespace block index from the data block number.
1946                  */
1947                 findex = dp->d_ops->db_to_fdindex(args->geo, dbno);
1948                 /*
1949                  * If it's after the end of the current entries in the
1950                  * freespace block, extend that table.
1951                  */
1952                 if (findex >= freehdr.nvalid) {
1953                         ASSERT(findex < dp->d_ops->free_max_bests(args->geo));
1954                         freehdr.nvalid = findex + 1;
1955                         /*
1956                          * Tag new entry so nused will go up.
1957                          */
1958                         bests[findex] = cpu_to_be16(NULLDATAOFF);
1959                 }
1960                 /*
1961                  * If this entry was for an empty data block
1962                  * (this should always be true) then update the header.
1963                  */
1964                 if (bests[findex] == cpu_to_be16(NULLDATAOFF)) {
1965                         freehdr.nused++;
1966                         dp->d_ops->free_hdr_to_disk(fbp->b_addr, &freehdr);
1967                         xfs_dir2_free_log_header(args, fbp);
1968                 }
1969                 /*
1970                  * Update the real value in the table.
1971                  * We haven't allocated the data entry yet so this will
1972                  * change again.
1973                  */
1974                 hdr = dbp->b_addr;
1975                 bf = dp->d_ops->data_bestfree_p(hdr);
1976                 bests[findex] = bf[0].length;
1977                 logfree = 1;
1978         }
1979         /*
1980          * We had a data block so we don't have to make a new one.
1981          */
1982         else {
1983                 /*
1984                  * If just checking, we succeeded.
1985                  */
1986                 if (args->op_flags & XFS_DA_OP_JUSTCHECK)
1987                         return 0;
1988
1989                 /*
1990                  * Read the data block in.
1991                  */
1992                 error = xfs_dir3_data_read(tp, dp,
1993                                            xfs_dir2_db_to_da(args->geo, dbno),
1994                                            -1, &dbp);
1995                 if (error)
1996                         return error;
1997                 hdr = dbp->b_addr;
1998                 bf = dp->d_ops->data_bestfree_p(hdr);
1999                 logfree = 0;
2000         }
2001         ASSERT(be16_to_cpu(bf[0].length) >= length);
2002         /*
2003          * Point to the existing unused space.
2004          */
2005         dup = (xfs_dir2_data_unused_t *)
2006               ((char *)hdr + be16_to_cpu(bf[0].offset));
2007         needscan = needlog = 0;
2008         /*
2009          * Mark the first part of the unused space, inuse for us.
2010          */
2011         xfs_dir2_data_use_free(args, dbp, dup,
2012                 (xfs_dir2_data_aoff_t)((char *)dup - (char *)hdr), length,
2013                 &needlog, &needscan);
2014         /*
2015          * Fill in the new entry and log it.
2016          */
2017         dep = (xfs_dir2_data_entry_t *)dup;
2018         dep->inumber = cpu_to_be64(args->inumber);
2019         dep->namelen = args->namelen;
2020         memcpy(dep->name, args->name, dep->namelen);
2021         dp->d_ops->data_put_ftype(dep, args->filetype);
2022         tagp = dp->d_ops->data_entry_tag_p(dep);
2023         *tagp = cpu_to_be16((char *)dep - (char *)hdr);
2024         xfs_dir2_data_log_entry(args, dbp, dep);
2025         /*
2026          * Rescan the block for bestfree if needed.
2027          */
2028         if (needscan)
2029                 xfs_dir2_data_freescan(dp, hdr, &needlog);
2030         /*
2031          * Log the data block header if needed.
2032          */
2033         if (needlog)
2034                 xfs_dir2_data_log_header(args, dbp);
2035         /*
2036          * If the freespace entry is now wrong, update it.
2037          */
2038         bests = dp->d_ops->free_bests_p(free); /* gcc is so stupid */
2039         if (be16_to_cpu(bests[findex]) != be16_to_cpu(bf[0].length)) {
2040                 bests[findex] = bf[0].length;
2041                 logfree = 1;
2042         }
2043         /*
2044          * Log the freespace entry if needed.
2045          */
2046         if (logfree)
2047                 xfs_dir2_free_log_bests(args, fbp, findex, findex);
2048         /*
2049          * Return the data block and offset in args, then drop the data block.
2050          */
2051         args->blkno = (xfs_dablk_t)dbno;
2052         args->index = be16_to_cpu(*tagp);
2053         return 0;
2054 }
2055
2056 /*
2057  * Lookup an entry in a node-format directory.
2058  * All the real work happens in xfs_da3_node_lookup_int.
2059  * The only real output is the inode number of the entry.
2060  */
2061 int                                             /* error */
2062 xfs_dir2_node_lookup(
2063         xfs_da_args_t   *args)                  /* operation arguments */
2064 {
2065         int             error;                  /* error return value */
2066         int             i;                      /* btree level */
2067         int             rval;                   /* operation return value */
2068         xfs_da_state_t  *state;                 /* btree cursor */
2069
2070         trace_xfs_dir2_node_lookup(args);
2071
2072         /*
2073          * Allocate and initialize the btree cursor.
2074          */
2075         state = xfs_da_state_alloc();
2076         state->args = args;
2077         state->mp = args->dp->i_mount;
2078         /*
2079          * Fill in the path to the entry in the cursor.
2080          */
2081         error = xfs_da3_node_lookup_int(state, &rval);
2082         if (error)
2083                 rval = error;
2084         else if (rval == -ENOENT && args->cmpresult == XFS_CMP_CASE) {
2085                 /* If a CI match, dup the actual name and return -EEXIST */
2086                 xfs_dir2_data_entry_t   *dep;
2087
2088                 dep = (xfs_dir2_data_entry_t *)
2089                         ((char *)state->extrablk.bp->b_addr +
2090                                                  state->extrablk.index);
2091                 rval = xfs_dir_cilookup_result(args, dep->name, dep->namelen);
2092         }
2093         /*
2094          * Release the btree blocks and leaf block.
2095          */
2096         for (i = 0; i < state->path.active; i++) {
2097                 xfs_trans_brelse(args->trans, state->path.blk[i].bp);
2098                 state->path.blk[i].bp = NULL;
2099         }
2100         /*
2101          * Release the data block if we have it.
2102          */
2103         if (state->extravalid && state->extrablk.bp) {
2104                 xfs_trans_brelse(args->trans, state->extrablk.bp);
2105                 state->extrablk.bp = NULL;
2106         }
2107         xfs_da_state_free(state);
2108         return rval;
2109 }
2110
2111 /*
2112  * Remove an entry from a node-format directory.
2113  */
2114 int                                             /* error */
2115 xfs_dir2_node_removename(
2116         struct xfs_da_args      *args)          /* operation arguments */
2117 {
2118         struct xfs_da_state_blk *blk;           /* leaf block */
2119         int                     error;          /* error return value */
2120         int                     rval;           /* operation return value */
2121         struct xfs_da_state     *state;         /* btree cursor */
2122
2123         trace_xfs_dir2_node_removename(args);
2124
2125         /*
2126          * Allocate and initialize the btree cursor.
2127          */
2128         state = xfs_da_state_alloc();
2129         state->args = args;
2130         state->mp = args->dp->i_mount;
2131
2132         /* Look up the entry we're deleting, set up the cursor. */
2133         error = xfs_da3_node_lookup_int(state, &rval);
2134         if (error)
2135                 goto out_free;
2136
2137         /* Didn't find it, upper layer screwed up. */
2138         if (rval != -EEXIST) {
2139                 error = rval;
2140                 goto out_free;
2141         }
2142
2143         blk = &state->path.blk[state->path.active - 1];
2144         ASSERT(blk->magic == XFS_DIR2_LEAFN_MAGIC);
2145         ASSERT(state->extravalid);
2146         /*
2147          * Remove the leaf and data entries.
2148          * Extrablk refers to the data block.
2149          */
2150         error = xfs_dir2_leafn_remove(args, blk->bp, blk->index,
2151                 &state->extrablk, &rval);
2152         if (error)
2153                 goto out_free;
2154         /*
2155          * Fix the hash values up the btree.
2156          */
2157         xfs_da3_fixhashpath(state, &state->path);
2158         /*
2159          * If we need to join leaf blocks, do it.
2160          */
2161         if (rval && state->path.active > 1)
2162                 error = xfs_da3_join(state);
2163         /*
2164          * If no errors so far, try conversion to leaf format.
2165          */
2166         if (!error)
2167                 error = xfs_dir2_node_to_leaf(state);
2168 out_free:
2169         xfs_da_state_free(state);
2170         return error;
2171 }
2172
2173 /*
2174  * Replace an entry's inode number in a node-format directory.
2175  */
2176 int                                             /* error */
2177 xfs_dir2_node_replace(
2178         xfs_da_args_t           *args)          /* operation arguments */
2179 {
2180         xfs_da_state_blk_t      *blk;           /* leaf block */
2181         xfs_dir2_data_hdr_t     *hdr;           /* data block header */
2182         xfs_dir2_data_entry_t   *dep;           /* data entry changed */
2183         int                     error;          /* error return value */
2184         int                     i;              /* btree level */
2185         xfs_ino_t               inum;           /* new inode number */
2186         int                     ftype;          /* new file type */
2187         xfs_dir2_leaf_t         *leaf;          /* leaf structure */
2188         xfs_dir2_leaf_entry_t   *lep;           /* leaf entry being changed */
2189         int                     rval;           /* internal return value */
2190         xfs_da_state_t          *state;         /* btree cursor */
2191
2192         trace_xfs_dir2_node_replace(args);
2193
2194         /*
2195          * Allocate and initialize the btree cursor.
2196          */
2197         state = xfs_da_state_alloc();
2198         state->args = args;
2199         state->mp = args->dp->i_mount;
2200
2201         /*
2202          * We have to save new inode number and ftype since
2203          * xfs_da3_node_lookup_int() is going to overwrite them
2204          */
2205         inum = args->inumber;
2206         ftype = args->filetype;
2207
2208         /*
2209          * Lookup the entry to change in the btree.
2210          */
2211         error = xfs_da3_node_lookup_int(state, &rval);
2212         if (error) {
2213                 rval = error;
2214         }
2215         /*
2216          * It should be found, since the vnodeops layer has looked it up
2217          * and locked it.  But paranoia is good.
2218          */
2219         if (rval == -EEXIST) {
2220                 struct xfs_dir2_leaf_entry *ents;
2221                 /*
2222                  * Find the leaf entry.
2223                  */
2224                 blk = &state->path.blk[state->path.active - 1];
2225                 ASSERT(blk->magic == XFS_DIR2_LEAFN_MAGIC);
2226                 leaf = blk->bp->b_addr;
2227                 ents = args->dp->d_ops->leaf_ents_p(leaf);
2228                 lep = &ents[blk->index];
2229                 ASSERT(state->extravalid);
2230                 /*
2231                  * Point to the data entry.
2232                  */
2233                 hdr = state->extrablk.bp->b_addr;
2234                 ASSERT(hdr->magic == cpu_to_be32(XFS_DIR2_DATA_MAGIC) ||
2235                        hdr->magic == cpu_to_be32(XFS_DIR3_DATA_MAGIC));
2236                 dep = (xfs_dir2_data_entry_t *)
2237                       ((char *)hdr +
2238                        xfs_dir2_dataptr_to_off(args->geo,
2239                                                be32_to_cpu(lep->address)));
2240                 ASSERT(inum != be64_to_cpu(dep->inumber));
2241                 /*
2242                  * Fill in the new inode number and log the entry.
2243                  */
2244                 dep->inumber = cpu_to_be64(inum);
2245                 args->dp->d_ops->data_put_ftype(dep, ftype);
2246                 xfs_dir2_data_log_entry(args, state->extrablk.bp, dep);
2247                 rval = 0;
2248         }
2249         /*
2250          * Didn't find it, and we're holding a data block.  Drop it.
2251          */
2252         else if (state->extravalid) {
2253                 xfs_trans_brelse(args->trans, state->extrablk.bp);
2254                 state->extrablk.bp = NULL;
2255         }
2256         /*
2257          * Release all the buffers in the cursor.
2258          */
2259         for (i = 0; i < state->path.active; i++) {
2260                 xfs_trans_brelse(args->trans, state->path.blk[i].bp);
2261                 state->path.blk[i].bp = NULL;
2262         }
2263         xfs_da_state_free(state);
2264         return rval;
2265 }
2266
2267 /*
2268  * Trim off a trailing empty freespace block.
2269  * Return (in rvalp) 1 if we did it, 0 if not.
2270  */
2271 int                                             /* error */
2272 xfs_dir2_node_trim_free(
2273         xfs_da_args_t           *args,          /* operation arguments */
2274         xfs_fileoff_t           fo,             /* free block number */
2275         int                     *rvalp)         /* out: did something */
2276 {
2277         struct xfs_buf          *bp;            /* freespace buffer */
2278         xfs_inode_t             *dp;            /* incore directory inode */
2279         int                     error;          /* error return code */
2280         xfs_dir2_free_t         *free;          /* freespace structure */
2281         xfs_trans_t             *tp;            /* transaction pointer */
2282         struct xfs_dir3_icfree_hdr freehdr;
2283
2284         dp = args->dp;
2285         tp = args->trans;
2286
2287         *rvalp = 0;
2288
2289         /*
2290          * Read the freespace block.
2291          */
2292         error = xfs_dir2_free_try_read(tp, dp, fo, &bp);
2293         if (error)
2294                 return error;
2295         /*
2296          * There can be holes in freespace.  If fo is a hole, there's
2297          * nothing to do.
2298          */
2299         if (!bp)
2300                 return 0;
2301         free = bp->b_addr;
2302         dp->d_ops->free_hdr_from_disk(&freehdr, free);
2303
2304         /*
2305          * If there are used entries, there's nothing to do.
2306          */
2307         if (freehdr.nused > 0) {
2308                 xfs_trans_brelse(tp, bp);
2309                 return 0;
2310         }
2311         /*
2312          * Blow the block away.
2313          */
2314         error = xfs_dir2_shrink_inode(args,
2315                         xfs_dir2_da_to_db(args->geo, (xfs_dablk_t)fo), bp);
2316         if (error) {
2317                 /*
2318                  * Can't fail with ENOSPC since that only happens with no
2319                  * space reservation, when breaking up an extent into two
2320                  * pieces.  This is the last block of an extent.
2321                  */
2322                 ASSERT(error != -ENOSPC);
2323                 xfs_trans_brelse(tp, bp);
2324                 return error;
2325         }
2326         /*
2327          * Return that we succeeded.
2328          */
2329         *rvalp = 1;
2330         return 0;
2331 }