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