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