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