xfs: factor out dir2 data block reading
[firefly-linux-kernel-4.4.55.git] / fs / xfs / xfs_dir2_leaf.c
1 /*
2  * Copyright (c) 2000-2003,2005 Silicon Graphics, Inc.
3  * All Rights Reserved.
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License as
7  * published by the Free Software Foundation.
8  *
9  * This program is distributed in the hope that it would be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write the Free Software Foundation,
16  * Inc.,  51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
17  */
18 #include "xfs.h"
19 #include "xfs_fs.h"
20 #include "xfs_types.h"
21 #include "xfs_bit.h"
22 #include "xfs_log.h"
23 #include "xfs_trans.h"
24 #include "xfs_sb.h"
25 #include "xfs_ag.h"
26 #include "xfs_mount.h"
27 #include "xfs_da_btree.h"
28 #include "xfs_bmap_btree.h"
29 #include "xfs_dinode.h"
30 #include "xfs_inode.h"
31 #include "xfs_bmap.h"
32 #include "xfs_dir2_format.h"
33 #include "xfs_dir2_priv.h"
34 #include "xfs_error.h"
35 #include "xfs_trace.h"
36
37 /*
38  * Local function declarations.
39  */
40 #ifdef DEBUG
41 static void xfs_dir2_leaf_check(struct xfs_inode *dp, struct xfs_buf *bp);
42 #else
43 #define xfs_dir2_leaf_check(dp, bp)
44 #endif
45 static int xfs_dir2_leaf_lookup_int(xfs_da_args_t *args, struct xfs_buf **lbpp,
46                                     int *indexp, struct xfs_buf **dbpp);
47 static void xfs_dir2_leaf_log_bests(struct xfs_trans *tp, struct xfs_buf *bp,
48                                     int first, int last);
49 static void xfs_dir2_leaf_log_tail(struct xfs_trans *tp, struct xfs_buf *bp);
50
51
52 /*
53  * Convert a block form directory to a leaf form directory.
54  */
55 int                                             /* error */
56 xfs_dir2_block_to_leaf(
57         xfs_da_args_t           *args,          /* operation arguments */
58         struct xfs_buf          *dbp)           /* input block's buffer */
59 {
60         __be16                  *bestsp;        /* leaf's bestsp entries */
61         xfs_dablk_t             blkno;          /* leaf block's bno */
62         xfs_dir2_data_hdr_t     *hdr;           /* block header */
63         xfs_dir2_leaf_entry_t   *blp;           /* block's leaf entries */
64         xfs_dir2_block_tail_t   *btp;           /* block's tail */
65         xfs_inode_t             *dp;            /* incore directory inode */
66         int                     error;          /* error return code */
67         struct xfs_buf          *lbp;           /* leaf block's buffer */
68         xfs_dir2_db_t           ldb;            /* leaf block's bno */
69         xfs_dir2_leaf_t         *leaf;          /* leaf structure */
70         xfs_dir2_leaf_tail_t    *ltp;           /* leaf's tail */
71         xfs_mount_t             *mp;            /* filesystem mount point */
72         int                     needlog;        /* need to log block header */
73         int                     needscan;       /* need to rescan bestfree */
74         xfs_trans_t             *tp;            /* transaction pointer */
75
76         trace_xfs_dir2_block_to_leaf(args);
77
78         dp = args->dp;
79         mp = dp->i_mount;
80         tp = args->trans;
81         /*
82          * Add the leaf block to the inode.
83          * This interface will only put blocks in the leaf/node range.
84          * Since that's empty now, we'll get the root (block 0 in range).
85          */
86         if ((error = xfs_da_grow_inode(args, &blkno))) {
87                 return error;
88         }
89         ldb = xfs_dir2_da_to_db(mp, blkno);
90         ASSERT(ldb == XFS_DIR2_LEAF_FIRSTDB(mp));
91         /*
92          * Initialize the leaf block, get a buffer for it.
93          */
94         if ((error = xfs_dir2_leaf_init(args, ldb, &lbp, XFS_DIR2_LEAF1_MAGIC))) {
95                 return error;
96         }
97         ASSERT(lbp != NULL);
98         leaf = lbp->b_addr;
99         hdr = dbp->b_addr;
100         xfs_dir2_data_check(dp, dbp);
101         btp = xfs_dir2_block_tail_p(mp, hdr);
102         blp = xfs_dir2_block_leaf_p(btp);
103         /*
104          * Set the counts in the leaf header.
105          */
106         leaf->hdr.count = cpu_to_be16(be32_to_cpu(btp->count));
107         leaf->hdr.stale = cpu_to_be16(be32_to_cpu(btp->stale));
108         /*
109          * Could compact these but I think we always do the conversion
110          * after squeezing out stale entries.
111          */
112         memcpy(leaf->ents, blp, be32_to_cpu(btp->count) * sizeof(xfs_dir2_leaf_entry_t));
113         xfs_dir2_leaf_log_ents(tp, lbp, 0, be16_to_cpu(leaf->hdr.count) - 1);
114         needscan = 0;
115         needlog = 1;
116         /*
117          * Make the space formerly occupied by the leaf entries and block
118          * tail be free.
119          */
120         xfs_dir2_data_make_free(tp, dbp,
121                 (xfs_dir2_data_aoff_t)((char *)blp - (char *)hdr),
122                 (xfs_dir2_data_aoff_t)((char *)hdr + mp->m_dirblksize -
123                                        (char *)blp),
124                 &needlog, &needscan);
125         /*
126          * Fix up the block header, make it a data block.
127          */
128         hdr->magic = cpu_to_be32(XFS_DIR2_DATA_MAGIC);
129         if (needscan)
130                 xfs_dir2_data_freescan(mp, hdr, &needlog);
131         /*
132          * Set up leaf tail and bests table.
133          */
134         ltp = xfs_dir2_leaf_tail_p(mp, leaf);
135         ltp->bestcount = cpu_to_be32(1);
136         bestsp = xfs_dir2_leaf_bests_p(ltp);
137         bestsp[0] =  hdr->bestfree[0].length;
138         /*
139          * Log the data header and leaf bests table.
140          */
141         if (needlog)
142                 xfs_dir2_data_log_header(tp, dbp);
143         xfs_dir2_leaf_check(dp, lbp);
144         xfs_dir2_data_check(dp, dbp);
145         xfs_dir2_leaf_log_bests(tp, lbp, 0, 0);
146         return 0;
147 }
148
149 STATIC void
150 xfs_dir2_leaf_find_stale(
151         struct xfs_dir2_leaf    *leaf,
152         int                     index,
153         int                     *lowstale,
154         int                     *highstale)
155 {
156         /*
157          * Find the first stale entry before our index, if any.
158          */
159         for (*lowstale = index - 1; *lowstale >= 0; --*lowstale) {
160                 if (leaf->ents[*lowstale].address ==
161                     cpu_to_be32(XFS_DIR2_NULL_DATAPTR))
162                         break;
163         }
164
165         /*
166          * Find the first stale entry at or after our index, if any.
167          * Stop if the result would require moving more entries than using
168          * lowstale.
169          */
170         for (*highstale = index;
171              *highstale < be16_to_cpu(leaf->hdr.count);
172              ++*highstale) {
173                 if (leaf->ents[*highstale].address ==
174                     cpu_to_be32(XFS_DIR2_NULL_DATAPTR))
175                         break;
176                 if (*lowstale >= 0 && index - *lowstale <= *highstale - index)
177                         break;
178         }
179 }
180
181 struct xfs_dir2_leaf_entry *
182 xfs_dir2_leaf_find_entry(
183         xfs_dir2_leaf_t         *leaf,          /* leaf structure */
184         int                     index,          /* leaf table position */
185         int                     compact,        /* need to compact leaves */
186         int                     lowstale,       /* index of prev stale leaf */
187         int                     highstale,      /* index of next stale leaf */
188         int                     *lfloglow,      /* low leaf logging index */
189         int                     *lfloghigh)     /* high leaf logging index */
190 {
191         if (!leaf->hdr.stale) {
192                 xfs_dir2_leaf_entry_t   *lep;   /* leaf entry table pointer */
193
194                 /*
195                  * Now we need to make room to insert the leaf entry.
196                  *
197                  * If there are no stale entries, just insert a hole at index.
198                  */
199                 lep = &leaf->ents[index];
200                 if (index < be16_to_cpu(leaf->hdr.count))
201                         memmove(lep + 1, lep,
202                                 (be16_to_cpu(leaf->hdr.count) - index) *
203                                  sizeof(*lep));
204
205                 /*
206                  * Record low and high logging indices for the leaf.
207                  */
208                 *lfloglow = index;
209                 *lfloghigh = be16_to_cpu(leaf->hdr.count);
210                 be16_add_cpu(&leaf->hdr.count, 1);
211                 return lep;
212         }
213
214         /*
215          * There are stale entries.
216          *
217          * We will use one of them for the new entry.  It's probably not at
218          * the right location, so we'll have to shift some up or down first.
219          *
220          * If we didn't compact before, we need to find the nearest stale
221          * entries before and after our insertion point.
222          */
223         if (compact == 0)
224                 xfs_dir2_leaf_find_stale(leaf, index, &lowstale, &highstale);
225
226         /*
227          * If the low one is better, use it.
228          */
229         if (lowstale >= 0 &&
230             (highstale == be16_to_cpu(leaf->hdr.count) ||
231              index - lowstale - 1 < highstale - index)) {
232                 ASSERT(index - lowstale - 1 >= 0);
233                 ASSERT(leaf->ents[lowstale].address ==
234                        cpu_to_be32(XFS_DIR2_NULL_DATAPTR));
235
236                 /*
237                  * Copy entries up to cover the stale entry and make room
238                  * for the new entry.
239                  */
240                 if (index - lowstale - 1 > 0) {
241                         memmove(&leaf->ents[lowstale],
242                                 &leaf->ents[lowstale + 1],
243                                 (index - lowstale - 1) *
244                                 sizeof(xfs_dir2_leaf_entry_t));
245                 }
246                 *lfloglow = MIN(lowstale, *lfloglow);
247                 *lfloghigh = MAX(index - 1, *lfloghigh);
248                 be16_add_cpu(&leaf->hdr.stale, -1);
249                 return &leaf->ents[index - 1];
250         }
251
252         /*
253          * The high one is better, so use that one.
254          */
255         ASSERT(highstale - index >= 0);
256         ASSERT(leaf->ents[highstale].address ==
257                cpu_to_be32(XFS_DIR2_NULL_DATAPTR));
258
259         /*
260          * Copy entries down to cover the stale entry and make room for the
261          * new entry.
262          */
263         if (highstale - index > 0) {
264                 memmove(&leaf->ents[index + 1],
265                         &leaf->ents[index],
266                         (highstale - index) * sizeof(xfs_dir2_leaf_entry_t));
267         }
268         *lfloglow = MIN(index, *lfloglow);
269         *lfloghigh = MAX(highstale, *lfloghigh);
270         be16_add_cpu(&leaf->hdr.stale, -1);
271         return &leaf->ents[index];
272 }
273
274 /*
275  * Add an entry to a leaf form directory.
276  */
277 int                                             /* error */
278 xfs_dir2_leaf_addname(
279         xfs_da_args_t           *args)          /* operation arguments */
280 {
281         __be16                  *bestsp;        /* freespace table in leaf */
282         int                     compact;        /* need to compact leaves */
283         xfs_dir2_data_hdr_t     *hdr;           /* data block header */
284         struct xfs_buf          *dbp;           /* data block buffer */
285         xfs_dir2_data_entry_t   *dep;           /* data block entry */
286         xfs_inode_t             *dp;            /* incore directory inode */
287         xfs_dir2_data_unused_t  *dup;           /* data unused entry */
288         int                     error;          /* error return value */
289         int                     grown;          /* allocated new data block */
290         int                     highstale;      /* index of next stale leaf */
291         int                     i;              /* temporary, index */
292         int                     index;          /* leaf table position */
293         struct xfs_buf          *lbp;           /* leaf's buffer */
294         xfs_dir2_leaf_t         *leaf;          /* leaf structure */
295         int                     length;         /* length of new entry */
296         xfs_dir2_leaf_entry_t   *lep;           /* leaf entry table pointer */
297         int                     lfloglow;       /* low leaf logging index */
298         int                     lfloghigh;      /* high leaf logging index */
299         int                     lowstale;       /* index of prev stale leaf */
300         xfs_dir2_leaf_tail_t    *ltp;           /* leaf tail pointer */
301         xfs_mount_t             *mp;            /* filesystem mount point */
302         int                     needbytes;      /* leaf block bytes needed */
303         int                     needlog;        /* need to log data header */
304         int                     needscan;       /* need to rescan data free */
305         __be16                  *tagp;          /* end of data entry */
306         xfs_trans_t             *tp;            /* transaction pointer */
307         xfs_dir2_db_t           use_block;      /* data block number */
308
309         trace_xfs_dir2_leaf_addname(args);
310
311         dp = args->dp;
312         tp = args->trans;
313         mp = dp->i_mount;
314         /*
315          * Read the leaf block.
316          */
317         error = xfs_da_read_buf(tp, dp, mp->m_dirleafblk, -1, &lbp,
318                                 XFS_DATA_FORK, NULL);
319         if (error)
320                 return error;
321         ASSERT(lbp != NULL);
322         /*
323          * Look up the entry by hash value and name.
324          * We know it's not there, our caller has already done a lookup.
325          * So the index is of the entry to insert in front of.
326          * But if there are dup hash values the index is of the first of those.
327          */
328         index = xfs_dir2_leaf_search_hash(args, lbp);
329         leaf = lbp->b_addr;
330         ltp = xfs_dir2_leaf_tail_p(mp, leaf);
331         bestsp = xfs_dir2_leaf_bests_p(ltp);
332         length = xfs_dir2_data_entsize(args->namelen);
333         /*
334          * See if there are any entries with the same hash value
335          * and space in their block for the new entry.
336          * This is good because it puts multiple same-hash value entries
337          * in a data block, improving the lookup of those entries.
338          */
339         for (use_block = -1, lep = &leaf->ents[index];
340              index < be16_to_cpu(leaf->hdr.count) && be32_to_cpu(lep->hashval) == args->hashval;
341              index++, lep++) {
342                 if (be32_to_cpu(lep->address) == XFS_DIR2_NULL_DATAPTR)
343                         continue;
344                 i = xfs_dir2_dataptr_to_db(mp, be32_to_cpu(lep->address));
345                 ASSERT(i < be32_to_cpu(ltp->bestcount));
346                 ASSERT(bestsp[i] != cpu_to_be16(NULLDATAOFF));
347                 if (be16_to_cpu(bestsp[i]) >= length) {
348                         use_block = i;
349                         break;
350                 }
351         }
352         /*
353          * Didn't find a block yet, linear search all the data blocks.
354          */
355         if (use_block == -1) {
356                 for (i = 0; i < be32_to_cpu(ltp->bestcount); i++) {
357                         /*
358                          * Remember a block we see that's missing.
359                          */
360                         if (bestsp[i] == cpu_to_be16(NULLDATAOFF) &&
361                             use_block == -1)
362                                 use_block = i;
363                         else if (be16_to_cpu(bestsp[i]) >= length) {
364                                 use_block = i;
365                                 break;
366                         }
367                 }
368         }
369         /*
370          * How many bytes do we need in the leaf block?
371          */
372         needbytes = 0;
373         if (!leaf->hdr.stale)
374                 needbytes += sizeof(xfs_dir2_leaf_entry_t);
375         if (use_block == -1)
376                 needbytes += sizeof(xfs_dir2_data_off_t);
377
378         /*
379          * Now kill use_block if it refers to a missing block, so we
380          * can use it as an indication of allocation needed.
381          */
382         if (use_block != -1 && bestsp[use_block] == cpu_to_be16(NULLDATAOFF))
383                 use_block = -1;
384         /*
385          * If we don't have enough free bytes but we can make enough
386          * by compacting out stale entries, we'll do that.
387          */
388         if ((char *)bestsp - (char *)&leaf->ents[be16_to_cpu(leaf->hdr.count)] <
389                                 needbytes && be16_to_cpu(leaf->hdr.stale) > 1) {
390                 compact = 1;
391         }
392         /*
393          * Otherwise if we don't have enough free bytes we need to
394          * convert to node form.
395          */
396         else if ((char *)bestsp - (char *)&leaf->ents[be16_to_cpu(
397                                                 leaf->hdr.count)] < needbytes) {
398                 /*
399                  * Just checking or no space reservation, give up.
400                  */
401                 if ((args->op_flags & XFS_DA_OP_JUSTCHECK) ||
402                                                         args->total == 0) {
403                         xfs_trans_brelse(tp, lbp);
404                         return XFS_ERROR(ENOSPC);
405                 }
406                 /*
407                  * Convert to node form.
408                  */
409                 error = xfs_dir2_leaf_to_node(args, lbp);
410                 if (error)
411                         return error;
412                 /*
413                  * Then add the new entry.
414                  */
415                 return xfs_dir2_node_addname(args);
416         }
417         /*
418          * Otherwise it will fit without compaction.
419          */
420         else
421                 compact = 0;
422         /*
423          * If just checking, then it will fit unless we needed to allocate
424          * a new data block.
425          */
426         if (args->op_flags & XFS_DA_OP_JUSTCHECK) {
427                 xfs_trans_brelse(tp, lbp);
428                 return use_block == -1 ? XFS_ERROR(ENOSPC) : 0;
429         }
430         /*
431          * If no allocations are allowed, return now before we've
432          * changed anything.
433          */
434         if (args->total == 0 && use_block == -1) {
435                 xfs_trans_brelse(tp, lbp);
436                 return XFS_ERROR(ENOSPC);
437         }
438         /*
439          * Need to compact the leaf entries, removing stale ones.
440          * Leave one stale entry behind - the one closest to our
441          * insertion index - and we'll shift that one to our insertion
442          * point later.
443          */
444         if (compact) {
445                 xfs_dir2_leaf_compact_x1(lbp, &index, &lowstale, &highstale,
446                         &lfloglow, &lfloghigh);
447         }
448         /*
449          * There are stale entries, so we'll need log-low and log-high
450          * impossibly bad values later.
451          */
452         else if (be16_to_cpu(leaf->hdr.stale)) {
453                 lfloglow = be16_to_cpu(leaf->hdr.count);
454                 lfloghigh = -1;
455         }
456         /*
457          * If there was no data block space found, we need to allocate
458          * a new one.
459          */
460         if (use_block == -1) {
461                 /*
462                  * Add the new data block.
463                  */
464                 if ((error = xfs_dir2_grow_inode(args, XFS_DIR2_DATA_SPACE,
465                                 &use_block))) {
466                         xfs_trans_brelse(tp, lbp);
467                         return error;
468                 }
469                 /*
470                  * Initialize the block.
471                  */
472                 if ((error = xfs_dir2_data_init(args, use_block, &dbp))) {
473                         xfs_trans_brelse(tp, lbp);
474                         return error;
475                 }
476                 /*
477                  * If we're adding a new data block on the end we need to
478                  * extend the bests table.  Copy it up one entry.
479                  */
480                 if (use_block >= be32_to_cpu(ltp->bestcount)) {
481                         bestsp--;
482                         memmove(&bestsp[0], &bestsp[1],
483                                 be32_to_cpu(ltp->bestcount) * sizeof(bestsp[0]));
484                         be32_add_cpu(&ltp->bestcount, 1);
485                         xfs_dir2_leaf_log_tail(tp, lbp);
486                         xfs_dir2_leaf_log_bests(tp, lbp, 0, be32_to_cpu(ltp->bestcount) - 1);
487                 }
488                 /*
489                  * If we're filling in a previously empty block just log it.
490                  */
491                 else
492                         xfs_dir2_leaf_log_bests(tp, lbp, use_block, use_block);
493                 hdr = dbp->b_addr;
494                 bestsp[use_block] = hdr->bestfree[0].length;
495                 grown = 1;
496         } else {
497                 /*
498                  * Already had space in some data block.
499                  * Just read that one in.
500                  */
501                 error = xfs_dir2_data_read(tp, dp,
502                                            xfs_dir2_db_to_da(mp, use_block),
503                                            -1, &dbp);
504                 if (error) {
505                         xfs_trans_brelse(tp, lbp);
506                         return error;
507                 }
508                 hdr = dbp->b_addr;
509                 grown = 0;
510         }
511         /*
512          * Point to the biggest freespace in our data block.
513          */
514         dup = (xfs_dir2_data_unused_t *)
515               ((char *)hdr + be16_to_cpu(hdr->bestfree[0].offset));
516         ASSERT(be16_to_cpu(dup->length) >= length);
517         needscan = needlog = 0;
518         /*
519          * Mark the initial part of our freespace in use for the new entry.
520          */
521         xfs_dir2_data_use_free(tp, dbp, dup,
522                 (xfs_dir2_data_aoff_t)((char *)dup - (char *)hdr), length,
523                 &needlog, &needscan);
524         /*
525          * Initialize our new entry (at last).
526          */
527         dep = (xfs_dir2_data_entry_t *)dup;
528         dep->inumber = cpu_to_be64(args->inumber);
529         dep->namelen = args->namelen;
530         memcpy(dep->name, args->name, dep->namelen);
531         tagp = xfs_dir2_data_entry_tag_p(dep);
532         *tagp = cpu_to_be16((char *)dep - (char *)hdr);
533         /*
534          * Need to scan fix up the bestfree table.
535          */
536         if (needscan)
537                 xfs_dir2_data_freescan(mp, hdr, &needlog);
538         /*
539          * Need to log the data block's header.
540          */
541         if (needlog)
542                 xfs_dir2_data_log_header(tp, dbp);
543         xfs_dir2_data_log_entry(tp, dbp, dep);
544         /*
545          * If the bests table needs to be changed, do it.
546          * Log the change unless we've already done that.
547          */
548         if (be16_to_cpu(bestsp[use_block]) != be16_to_cpu(hdr->bestfree[0].length)) {
549                 bestsp[use_block] = hdr->bestfree[0].length;
550                 if (!grown)
551                         xfs_dir2_leaf_log_bests(tp, lbp, use_block, use_block);
552         }
553
554         lep = xfs_dir2_leaf_find_entry(leaf, index, compact, lowstale,
555                                        highstale, &lfloglow, &lfloghigh);
556
557         /*
558          * Fill in the new leaf entry.
559          */
560         lep->hashval = cpu_to_be32(args->hashval);
561         lep->address = cpu_to_be32(xfs_dir2_db_off_to_dataptr(mp, use_block,
562                                 be16_to_cpu(*tagp)));
563         /*
564          * Log the leaf fields and give up the buffers.
565          */
566         xfs_dir2_leaf_log_header(tp, lbp);
567         xfs_dir2_leaf_log_ents(tp, lbp, lfloglow, lfloghigh);
568         xfs_dir2_leaf_check(dp, lbp);
569         xfs_dir2_data_check(dp, dbp);
570         return 0;
571 }
572
573 #ifdef DEBUG
574 /*
575  * Check the internal consistency of a leaf1 block.
576  * Pop an assert if something is wrong.
577  */
578 STATIC void
579 xfs_dir2_leaf_check(
580         struct xfs_inode        *dp,            /* incore directory inode */
581         struct xfs_buf          *bp)            /* leaf's buffer */
582 {
583         int                     i;              /* leaf index */
584         xfs_dir2_leaf_t         *leaf;          /* leaf structure */
585         xfs_dir2_leaf_tail_t    *ltp;           /* leaf tail pointer */
586         xfs_mount_t             *mp;            /* filesystem mount point */
587         int                     stale;          /* count of stale leaves */
588
589         leaf = bp->b_addr;
590         mp = dp->i_mount;
591         ASSERT(leaf->hdr.info.magic == cpu_to_be16(XFS_DIR2_LEAF1_MAGIC));
592         /*
593          * This value is not restrictive enough.
594          * Should factor in the size of the bests table as well.
595          * We can deduce a value for that from di_size.
596          */
597         ASSERT(be16_to_cpu(leaf->hdr.count) <= xfs_dir2_max_leaf_ents(mp));
598         ltp = xfs_dir2_leaf_tail_p(mp, leaf);
599         /*
600          * Leaves and bests don't overlap.
601          */
602         ASSERT((char *)&leaf->ents[be16_to_cpu(leaf->hdr.count)] <=
603                (char *)xfs_dir2_leaf_bests_p(ltp));
604         /*
605          * Check hash value order, count stale entries.
606          */
607         for (i = stale = 0; i < be16_to_cpu(leaf->hdr.count); i++) {
608                 if (i + 1 < be16_to_cpu(leaf->hdr.count))
609                         ASSERT(be32_to_cpu(leaf->ents[i].hashval) <=
610                                be32_to_cpu(leaf->ents[i + 1].hashval));
611                 if (leaf->ents[i].address == cpu_to_be32(XFS_DIR2_NULL_DATAPTR))
612                         stale++;
613         }
614         ASSERT(be16_to_cpu(leaf->hdr.stale) == stale);
615 }
616 #endif  /* DEBUG */
617
618 /*
619  * Compact out any stale entries in the leaf.
620  * Log the header and changed leaf entries, if any.
621  */
622 void
623 xfs_dir2_leaf_compact(
624         xfs_da_args_t   *args,          /* operation arguments */
625         struct xfs_buf  *bp)            /* leaf buffer */
626 {
627         int             from;           /* source leaf index */
628         xfs_dir2_leaf_t *leaf;          /* leaf structure */
629         int             loglow;         /* first leaf entry to log */
630         int             to;             /* target leaf index */
631
632         leaf = bp->b_addr;
633         if (!leaf->hdr.stale) {
634                 return;
635         }
636         /*
637          * Compress out the stale entries in place.
638          */
639         for (from = to = 0, loglow = -1; from < be16_to_cpu(leaf->hdr.count); from++) {
640                 if (leaf->ents[from].address ==
641                     cpu_to_be32(XFS_DIR2_NULL_DATAPTR))
642                         continue;
643                 /*
644                  * Only actually copy the entries that are different.
645                  */
646                 if (from > to) {
647                         if (loglow == -1)
648                                 loglow = to;
649                         leaf->ents[to] = leaf->ents[from];
650                 }
651                 to++;
652         }
653         /*
654          * Update and log the header, log the leaf entries.
655          */
656         ASSERT(be16_to_cpu(leaf->hdr.stale) == from - to);
657         be16_add_cpu(&leaf->hdr.count, -(be16_to_cpu(leaf->hdr.stale)));
658         leaf->hdr.stale = 0;
659         xfs_dir2_leaf_log_header(args->trans, bp);
660         if (loglow != -1)
661                 xfs_dir2_leaf_log_ents(args->trans, bp, loglow, to - 1);
662 }
663
664 /*
665  * Compact the leaf entries, removing stale ones.
666  * Leave one stale entry behind - the one closest to our
667  * insertion index - and the caller will shift that one to our insertion
668  * point later.
669  * Return new insertion index, where the remaining stale entry is,
670  * and leaf logging indices.
671  */
672 void
673 xfs_dir2_leaf_compact_x1(
674         struct xfs_buf  *bp,            /* leaf buffer */
675         int             *indexp,        /* insertion index */
676         int             *lowstalep,     /* out: stale entry before us */
677         int             *highstalep,    /* out: stale entry after us */
678         int             *lowlogp,       /* out: low log index */
679         int             *highlogp)      /* out: high log index */
680 {
681         int             from;           /* source copy index */
682         int             highstale;      /* stale entry at/after index */
683         int             index;          /* insertion index */
684         int             keepstale;      /* source index of kept stale */
685         xfs_dir2_leaf_t *leaf;          /* leaf structure */
686         int             lowstale;       /* stale entry before index */
687         int             newindex=0;     /* new insertion index */
688         int             to;             /* destination copy index */
689
690         leaf = bp->b_addr;
691         ASSERT(be16_to_cpu(leaf->hdr.stale) > 1);
692         index = *indexp;
693
694         xfs_dir2_leaf_find_stale(leaf, index, &lowstale, &highstale);
695
696         /*
697          * Pick the better of lowstale and highstale.
698          */
699         if (lowstale >= 0 &&
700             (highstale == be16_to_cpu(leaf->hdr.count) ||
701              index - lowstale <= highstale - index))
702                 keepstale = lowstale;
703         else
704                 keepstale = highstale;
705         /*
706          * Copy the entries in place, removing all the stale entries
707          * except keepstale.
708          */
709         for (from = to = 0; from < be16_to_cpu(leaf->hdr.count); from++) {
710                 /*
711                  * Notice the new value of index.
712                  */
713                 if (index == from)
714                         newindex = to;
715                 if (from != keepstale &&
716                     leaf->ents[from].address ==
717                     cpu_to_be32(XFS_DIR2_NULL_DATAPTR)) {
718                         if (from == to)
719                                 *lowlogp = to;
720                         continue;
721                 }
722                 /*
723                  * Record the new keepstale value for the insertion.
724                  */
725                 if (from == keepstale)
726                         lowstale = highstale = to;
727                 /*
728                  * Copy only the entries that have moved.
729                  */
730                 if (from > to)
731                         leaf->ents[to] = leaf->ents[from];
732                 to++;
733         }
734         ASSERT(from > to);
735         /*
736          * If the insertion point was past the last entry,
737          * set the new insertion point accordingly.
738          */
739         if (index == from)
740                 newindex = to;
741         *indexp = newindex;
742         /*
743          * Adjust the leaf header values.
744          */
745         be16_add_cpu(&leaf->hdr.count, -(from - to));
746         leaf->hdr.stale = cpu_to_be16(1);
747         /*
748          * Remember the low/high stale value only in the "right"
749          * direction.
750          */
751         if (lowstale >= newindex)
752                 lowstale = -1;
753         else
754                 highstale = be16_to_cpu(leaf->hdr.count);
755         *highlogp = be16_to_cpu(leaf->hdr.count) - 1;
756         *lowstalep = lowstale;
757         *highstalep = highstale;
758 }
759
760 struct xfs_dir2_leaf_map_info {
761         xfs_extlen_t    map_blocks;     /* number of fsbs in map */
762         xfs_dablk_t     map_off;        /* last mapped file offset */
763         int             map_size;       /* total entries in *map */
764         int             map_valid;      /* valid entries in *map */
765         int             nmap;           /* mappings to ask xfs_bmapi */
766         xfs_dir2_db_t   curdb;          /* db for current block */
767         int             ra_current;     /* number of read-ahead blks */
768         int             ra_index;       /* *map index for read-ahead */
769         int             ra_offset;      /* map entry offset for ra */
770         int             ra_want;        /* readahead count wanted */
771         struct xfs_bmbt_irec map[];     /* map vector for blocks */
772 };
773
774 STATIC int
775 xfs_dir2_leaf_readbuf(
776         struct xfs_inode        *dp,
777         size_t                  bufsize,
778         struct xfs_dir2_leaf_map_info *mip,
779         xfs_dir2_off_t          *curoff,
780         struct xfs_buf          **bpp)
781 {
782         struct xfs_mount        *mp = dp->i_mount;
783         struct xfs_buf          *bp = *bpp;
784         struct xfs_bmbt_irec    *map = mip->map;
785         int                     error = 0;
786         int                     length;
787         int                     i;
788         int                     j;
789
790         /*
791          * If we have a buffer, we need to release it and
792          * take it out of the mapping.
793          */
794
795         if (bp) {
796                 xfs_trans_brelse(NULL, bp);
797                 bp = NULL;
798                 mip->map_blocks -= mp->m_dirblkfsbs;
799                 /*
800                  * Loop to get rid of the extents for the
801                  * directory block.
802                  */
803                 for (i = mp->m_dirblkfsbs; i > 0; ) {
804                         j = min_t(int, map->br_blockcount, i);
805                         map->br_blockcount -= j;
806                         map->br_startblock += j;
807                         map->br_startoff += j;
808                         /*
809                          * If mapping is done, pitch it from
810                          * the table.
811                          */
812                         if (!map->br_blockcount && --mip->map_valid)
813                                 memmove(&map[0], &map[1],
814                                         sizeof(map[0]) * mip->map_valid);
815                         i -= j;
816                 }
817         }
818
819         /*
820          * Recalculate the readahead blocks wanted.
821          */
822         mip->ra_want = howmany(bufsize + mp->m_dirblksize,
823                                mp->m_sb.sb_blocksize) - 1;
824         ASSERT(mip->ra_want >= 0);
825
826         /*
827          * If we don't have as many as we want, and we haven't
828          * run out of data blocks, get some more mappings.
829          */
830         if (1 + mip->ra_want > mip->map_blocks &&
831             mip->map_off < xfs_dir2_byte_to_da(mp, XFS_DIR2_LEAF_OFFSET)) {
832                 /*
833                  * Get more bmaps, fill in after the ones
834                  * we already have in the table.
835                  */
836                 mip->nmap = mip->map_size - mip->map_valid;
837                 error = xfs_bmapi_read(dp, mip->map_off,
838                                 xfs_dir2_byte_to_da(mp, XFS_DIR2_LEAF_OFFSET) -
839                                                                 mip->map_off,
840                                 &map[mip->map_valid], &mip->nmap, 0);
841
842                 /*
843                  * Don't know if we should ignore this or try to return an
844                  * error.  The trouble with returning errors is that readdir
845                  * will just stop without actually passing the error through.
846                  */
847                 if (error)
848                         goto out;       /* XXX */
849
850                 /*
851                  * If we got all the mappings we asked for, set the final map
852                  * offset based on the last bmap value received.  Otherwise,
853                  * we've reached the end.
854                  */
855                 if (mip->nmap == mip->map_size - mip->map_valid) {
856                         i = mip->map_valid + mip->nmap - 1;
857                         mip->map_off = map[i].br_startoff + map[i].br_blockcount;
858                 } else
859                         mip->map_off = xfs_dir2_byte_to_da(mp,
860                                                         XFS_DIR2_LEAF_OFFSET);
861
862                 /*
863                  * Look for holes in the mapping, and eliminate them.  Count up
864                  * the valid blocks.
865                  */
866                 for (i = mip->map_valid; i < mip->map_valid + mip->nmap; ) {
867                         if (map[i].br_startblock == HOLESTARTBLOCK) {
868                                 mip->nmap--;
869                                 length = mip->map_valid + mip->nmap - i;
870                                 if (length)
871                                         memmove(&map[i], &map[i + 1],
872                                                 sizeof(map[i]) * length);
873                         } else {
874                                 mip->map_blocks += map[i].br_blockcount;
875                                 i++;
876                         }
877                 }
878                 mip->map_valid += mip->nmap;
879         }
880
881         /*
882          * No valid mappings, so no more data blocks.
883          */
884         if (!mip->map_valid) {
885                 *curoff = xfs_dir2_da_to_byte(mp, mip->map_off);
886                 goto out;
887         }
888
889         /*
890          * Read the directory block starting at the first mapping.
891          */
892         mip->curdb = xfs_dir2_da_to_db(mp, map->br_startoff);
893         error = xfs_dir2_data_read(NULL, dp, map->br_startoff,
894                         map->br_blockcount >= mp->m_dirblkfsbs ?
895                             XFS_FSB_TO_DADDR(mp, map->br_startblock) : -1, &bp);
896
897         /*
898          * Should just skip over the data block instead of giving up.
899          */
900         if (error)
901                 goto out;       /* XXX */
902
903         /*
904          * Adjust the current amount of read-ahead: we just read a block that
905          * was previously ra.
906          */
907         if (mip->ra_current)
908                 mip->ra_current -= mp->m_dirblkfsbs;
909
910         /*
911          * Do we need more readahead?
912          */
913         for (mip->ra_index = mip->ra_offset = i = 0;
914              mip->ra_want > mip->ra_current && i < mip->map_blocks;
915              i += mp->m_dirblkfsbs) {
916                 ASSERT(mip->ra_index < mip->map_valid);
917                 /*
918                  * Read-ahead a contiguous directory block.
919                  */
920                 if (i > mip->ra_current &&
921                     map[mip->ra_index].br_blockcount >= mp->m_dirblkfsbs) {
922                         xfs_buf_readahead(mp->m_ddev_targp,
923                                 XFS_FSB_TO_DADDR(mp,
924                                         map[mip->ra_index].br_startblock +
925                                                         mip->ra_offset),
926                                 (int)BTOBB(mp->m_dirblksize), NULL);
927                         mip->ra_current = i;
928                 }
929
930                 /*
931                  * Read-ahead a non-contiguous directory block.  This doesn't
932                  * use our mapping, but this is a very rare case.
933                  */
934                 else if (i > mip->ra_current) {
935                         xfs_da_reada_buf(NULL, dp,
936                                         map[mip->ra_index].br_startoff +
937                                                         mip->ra_offset,
938                                         XFS_DATA_FORK, NULL);
939                         mip->ra_current = i;
940                 }
941
942                 /*
943                  * Advance offset through the mapping table.
944                  */
945                 for (j = 0; j < mp->m_dirblkfsbs; j++) {
946                         /*
947                          * The rest of this extent but not more than a dir
948                          * block.
949                          */
950                         length = min_t(int, mp->m_dirblkfsbs,
951                                         map[mip->ra_index].br_blockcount -
952                                                         mip->ra_offset);
953                         j += length;
954                         mip->ra_offset += length;
955
956                         /*
957                          * Advance to the next mapping if this one is used up.
958                          */
959                         if (mip->ra_offset == map[mip->ra_index].br_blockcount) {
960                                 mip->ra_offset = 0;
961                                 mip->ra_index++;
962                         }
963                 }
964         }
965
966 out:
967         *bpp = bp;
968         return error;
969 }
970
971 /*
972  * Getdents (readdir) for leaf and node directories.
973  * This reads the data blocks only, so is the same for both forms.
974  */
975 int                                             /* error */
976 xfs_dir2_leaf_getdents(
977         xfs_inode_t             *dp,            /* incore directory inode */
978         void                    *dirent,
979         size_t                  bufsize,
980         xfs_off_t               *offset,
981         filldir_t               filldir)
982 {
983         struct xfs_buf          *bp = NULL;     /* data block buffer */
984         xfs_dir2_data_hdr_t     *hdr;           /* data block header */
985         xfs_dir2_data_entry_t   *dep;           /* data entry */
986         xfs_dir2_data_unused_t  *dup;           /* unused entry */
987         int                     error = 0;      /* error return value */
988         int                     length;         /* temporary length value */
989         xfs_mount_t             *mp;            /* filesystem mount point */
990         int                     byteoff;        /* offset in current block */
991         xfs_dir2_off_t          curoff;         /* current overall offset */
992         xfs_dir2_off_t          newoff;         /* new curoff after new blk */
993         char                    *ptr = NULL;    /* pointer to current data */
994         struct xfs_dir2_leaf_map_info *map_info;
995
996         /*
997          * If the offset is at or past the largest allowed value,
998          * give up right away.
999          */
1000         if (*offset >= XFS_DIR2_MAX_DATAPTR)
1001                 return 0;
1002
1003         mp = dp->i_mount;
1004
1005         /*
1006          * Set up to bmap a number of blocks based on the caller's
1007          * buffer size, the directory block size, and the filesystem
1008          * block size.
1009          */
1010         length = howmany(bufsize + mp->m_dirblksize,
1011                                      mp->m_sb.sb_blocksize);
1012         map_info = kmem_zalloc(offsetof(struct xfs_dir2_leaf_map_info, map) +
1013                                 (length * sizeof(struct xfs_bmbt_irec)),
1014                                KM_SLEEP);
1015         map_info->map_size = length;
1016
1017         /*
1018          * Inside the loop we keep the main offset value as a byte offset
1019          * in the directory file.
1020          */
1021         curoff = xfs_dir2_dataptr_to_byte(mp, *offset);
1022
1023         /*
1024          * Force this conversion through db so we truncate the offset
1025          * down to get the start of the data block.
1026          */
1027         map_info->map_off = xfs_dir2_db_to_da(mp,
1028                                               xfs_dir2_byte_to_db(mp, curoff));
1029
1030         /*
1031          * Loop over directory entries until we reach the end offset.
1032          * Get more blocks and readahead as necessary.
1033          */
1034         while (curoff < XFS_DIR2_LEAF_OFFSET) {
1035                 /*
1036                  * If we have no buffer, or we're off the end of the
1037                  * current buffer, need to get another one.
1038                  */
1039                 if (!bp || ptr >= (char *)bp->b_addr + mp->m_dirblksize) {
1040
1041                         error = xfs_dir2_leaf_readbuf(dp, bufsize, map_info,
1042                                                       &curoff, &bp);
1043                         if (error || !map_info->map_valid)
1044                                 break;
1045
1046                         /*
1047                          * Having done a read, we need to set a new offset.
1048                          */
1049                         newoff = xfs_dir2_db_off_to_byte(mp, map_info->curdb, 0);
1050                         /*
1051                          * Start of the current block.
1052                          */
1053                         if (curoff < newoff)
1054                                 curoff = newoff;
1055                         /*
1056                          * Make sure we're in the right block.
1057                          */
1058                         else if (curoff > newoff)
1059                                 ASSERT(xfs_dir2_byte_to_db(mp, curoff) ==
1060                                        map_info->curdb);
1061                         hdr = bp->b_addr;
1062                         xfs_dir2_data_check(dp, bp);
1063                         /*
1064                          * Find our position in the block.
1065                          */
1066                         ptr = (char *)(hdr + 1);
1067                         byteoff = xfs_dir2_byte_to_off(mp, curoff);
1068                         /*
1069                          * Skip past the header.
1070                          */
1071                         if (byteoff == 0)
1072                                 curoff += (uint)sizeof(*hdr);
1073                         /*
1074                          * Skip past entries until we reach our offset.
1075                          */
1076                         else {
1077                                 while ((char *)ptr - (char *)hdr < byteoff) {
1078                                         dup = (xfs_dir2_data_unused_t *)ptr;
1079
1080                                         if (be16_to_cpu(dup->freetag)
1081                                                   == XFS_DIR2_DATA_FREE_TAG) {
1082
1083                                                 length = be16_to_cpu(dup->length);
1084                                                 ptr += length;
1085                                                 continue;
1086                                         }
1087                                         dep = (xfs_dir2_data_entry_t *)ptr;
1088                                         length =
1089                                            xfs_dir2_data_entsize(dep->namelen);
1090                                         ptr += length;
1091                                 }
1092                                 /*
1093                                  * Now set our real offset.
1094                                  */
1095                                 curoff =
1096                                         xfs_dir2_db_off_to_byte(mp,
1097                                             xfs_dir2_byte_to_db(mp, curoff),
1098                                             (char *)ptr - (char *)hdr);
1099                                 if (ptr >= (char *)hdr + mp->m_dirblksize) {
1100                                         continue;
1101                                 }
1102                         }
1103                 }
1104                 /*
1105                  * We have a pointer to an entry.
1106                  * Is it a live one?
1107                  */
1108                 dup = (xfs_dir2_data_unused_t *)ptr;
1109                 /*
1110                  * No, it's unused, skip over it.
1111                  */
1112                 if (be16_to_cpu(dup->freetag) == XFS_DIR2_DATA_FREE_TAG) {
1113                         length = be16_to_cpu(dup->length);
1114                         ptr += length;
1115                         curoff += length;
1116                         continue;
1117                 }
1118
1119                 dep = (xfs_dir2_data_entry_t *)ptr;
1120                 length = xfs_dir2_data_entsize(dep->namelen);
1121
1122                 if (filldir(dirent, (char *)dep->name, dep->namelen,
1123                             xfs_dir2_byte_to_dataptr(mp, curoff) & 0x7fffffff,
1124                             be64_to_cpu(dep->inumber), DT_UNKNOWN))
1125                         break;
1126
1127                 /*
1128                  * Advance to next entry in the block.
1129                  */
1130                 ptr += length;
1131                 curoff += length;
1132                 /* bufsize may have just been a guess; don't go negative */
1133                 bufsize = bufsize > length ? bufsize - length : 0;
1134         }
1135
1136         /*
1137          * All done.  Set output offset value to current offset.
1138          */
1139         if (curoff > xfs_dir2_dataptr_to_byte(mp, XFS_DIR2_MAX_DATAPTR))
1140                 *offset = XFS_DIR2_MAX_DATAPTR & 0x7fffffff;
1141         else
1142                 *offset = xfs_dir2_byte_to_dataptr(mp, curoff) & 0x7fffffff;
1143         kmem_free(map_info);
1144         if (bp)
1145                 xfs_trans_brelse(NULL, bp);
1146         return error;
1147 }
1148
1149 /*
1150  * Initialize a new leaf block, leaf1 or leafn magic accepted.
1151  */
1152 int
1153 xfs_dir2_leaf_init(
1154         xfs_da_args_t           *args,          /* operation arguments */
1155         xfs_dir2_db_t           bno,            /* directory block number */
1156         struct xfs_buf          **bpp,          /* out: leaf buffer */
1157         int                     magic)          /* magic number for block */
1158 {
1159         struct xfs_buf          *bp;            /* leaf buffer */
1160         xfs_inode_t             *dp;            /* incore directory inode */
1161         int                     error;          /* error return code */
1162         xfs_dir2_leaf_t         *leaf;          /* leaf structure */
1163         xfs_dir2_leaf_tail_t    *ltp;           /* leaf tail structure */
1164         xfs_mount_t             *mp;            /* filesystem mount point */
1165         xfs_trans_t             *tp;            /* transaction pointer */
1166
1167         dp = args->dp;
1168         ASSERT(dp != NULL);
1169         tp = args->trans;
1170         mp = dp->i_mount;
1171         ASSERT(bno >= XFS_DIR2_LEAF_FIRSTDB(mp) &&
1172                bno < XFS_DIR2_FREE_FIRSTDB(mp));
1173         /*
1174          * Get the buffer for the block.
1175          */
1176         error = xfs_da_get_buf(tp, dp, xfs_dir2_db_to_da(mp, bno), -1, &bp,
1177                 XFS_DATA_FORK);
1178         if (error) {
1179                 return error;
1180         }
1181         ASSERT(bp != NULL);
1182         leaf = bp->b_addr;
1183         /*
1184          * Initialize the header.
1185          */
1186         leaf->hdr.info.magic = cpu_to_be16(magic);
1187         leaf->hdr.info.forw = 0;
1188         leaf->hdr.info.back = 0;
1189         leaf->hdr.count = 0;
1190         leaf->hdr.stale = 0;
1191         xfs_dir2_leaf_log_header(tp, bp);
1192         /*
1193          * If it's a leaf-format directory initialize the tail.
1194          * In this case our caller has the real bests table to copy into
1195          * the block.
1196          */
1197         if (magic == XFS_DIR2_LEAF1_MAGIC) {
1198                 ltp = xfs_dir2_leaf_tail_p(mp, leaf);
1199                 ltp->bestcount = 0;
1200                 xfs_dir2_leaf_log_tail(tp, bp);
1201         }
1202         *bpp = bp;
1203         return 0;
1204 }
1205
1206 /*
1207  * Log the bests entries indicated from a leaf1 block.
1208  */
1209 static void
1210 xfs_dir2_leaf_log_bests(
1211         xfs_trans_t             *tp,            /* transaction pointer */
1212         struct xfs_buf          *bp,            /* leaf buffer */
1213         int                     first,          /* first entry to log */
1214         int                     last)           /* last entry to log */
1215 {
1216         __be16                  *firstb;        /* pointer to first entry */
1217         __be16                  *lastb;         /* pointer to last entry */
1218         xfs_dir2_leaf_t         *leaf;          /* leaf structure */
1219         xfs_dir2_leaf_tail_t    *ltp;           /* leaf tail structure */
1220
1221         leaf = bp->b_addr;
1222         ASSERT(leaf->hdr.info.magic == cpu_to_be16(XFS_DIR2_LEAF1_MAGIC));
1223         ltp = xfs_dir2_leaf_tail_p(tp->t_mountp, leaf);
1224         firstb = xfs_dir2_leaf_bests_p(ltp) + first;
1225         lastb = xfs_dir2_leaf_bests_p(ltp) + last;
1226         xfs_trans_log_buf(tp, bp, (uint)((char *)firstb - (char *)leaf),
1227                 (uint)((char *)lastb - (char *)leaf + sizeof(*lastb) - 1));
1228 }
1229
1230 /*
1231  * Log the leaf entries indicated from a leaf1 or leafn block.
1232  */
1233 void
1234 xfs_dir2_leaf_log_ents(
1235         xfs_trans_t             *tp,            /* transaction pointer */
1236         struct xfs_buf          *bp,            /* leaf buffer */
1237         int                     first,          /* first entry to log */
1238         int                     last)           /* last entry to log */
1239 {
1240         xfs_dir2_leaf_entry_t   *firstlep;      /* pointer to first entry */
1241         xfs_dir2_leaf_entry_t   *lastlep;       /* pointer to last entry */
1242         xfs_dir2_leaf_t         *leaf;          /* leaf structure */
1243
1244         leaf = bp->b_addr;
1245         ASSERT(leaf->hdr.info.magic == cpu_to_be16(XFS_DIR2_LEAF1_MAGIC) ||
1246                leaf->hdr.info.magic == cpu_to_be16(XFS_DIR2_LEAFN_MAGIC));
1247         firstlep = &leaf->ents[first];
1248         lastlep = &leaf->ents[last];
1249         xfs_trans_log_buf(tp, bp, (uint)((char *)firstlep - (char *)leaf),
1250                 (uint)((char *)lastlep - (char *)leaf + sizeof(*lastlep) - 1));
1251 }
1252
1253 /*
1254  * Log the header of the leaf1 or leafn block.
1255  */
1256 void
1257 xfs_dir2_leaf_log_header(
1258         struct xfs_trans        *tp,
1259         struct xfs_buf          *bp)
1260 {
1261         xfs_dir2_leaf_t         *leaf;          /* leaf structure */
1262
1263         leaf = bp->b_addr;
1264         ASSERT(leaf->hdr.info.magic == cpu_to_be16(XFS_DIR2_LEAF1_MAGIC) ||
1265                leaf->hdr.info.magic == cpu_to_be16(XFS_DIR2_LEAFN_MAGIC));
1266         xfs_trans_log_buf(tp, bp, (uint)((char *)&leaf->hdr - (char *)leaf),
1267                 (uint)(sizeof(leaf->hdr) - 1));
1268 }
1269
1270 /*
1271  * Log the tail of the leaf1 block.
1272  */
1273 STATIC void
1274 xfs_dir2_leaf_log_tail(
1275         struct xfs_trans        *tp,
1276         struct xfs_buf          *bp)
1277 {
1278         xfs_dir2_leaf_t         *leaf;          /* leaf structure */
1279         xfs_dir2_leaf_tail_t    *ltp;           /* leaf tail structure */
1280         xfs_mount_t             *mp;            /* filesystem mount point */
1281
1282         mp = tp->t_mountp;
1283         leaf = bp->b_addr;
1284         ASSERT(leaf->hdr.info.magic == cpu_to_be16(XFS_DIR2_LEAF1_MAGIC));
1285         ltp = xfs_dir2_leaf_tail_p(mp, leaf);
1286         xfs_trans_log_buf(tp, bp, (uint)((char *)ltp - (char *)leaf),
1287                 (uint)(mp->m_dirblksize - 1));
1288 }
1289
1290 /*
1291  * Look up the entry referred to by args in the leaf format directory.
1292  * Most of the work is done by the xfs_dir2_leaf_lookup_int routine which
1293  * is also used by the node-format code.
1294  */
1295 int
1296 xfs_dir2_leaf_lookup(
1297         xfs_da_args_t           *args)          /* operation arguments */
1298 {
1299         struct xfs_buf          *dbp;           /* data block buffer */
1300         xfs_dir2_data_entry_t   *dep;           /* data block entry */
1301         xfs_inode_t             *dp;            /* incore directory inode */
1302         int                     error;          /* error return code */
1303         int                     index;          /* found entry index */
1304         struct xfs_buf          *lbp;           /* leaf buffer */
1305         xfs_dir2_leaf_t         *leaf;          /* leaf structure */
1306         xfs_dir2_leaf_entry_t   *lep;           /* leaf entry */
1307         xfs_trans_t             *tp;            /* transaction pointer */
1308
1309         trace_xfs_dir2_leaf_lookup(args);
1310
1311         /*
1312          * Look up name in the leaf block, returning both buffers and index.
1313          */
1314         if ((error = xfs_dir2_leaf_lookup_int(args, &lbp, &index, &dbp))) {
1315                 return error;
1316         }
1317         tp = args->trans;
1318         dp = args->dp;
1319         xfs_dir2_leaf_check(dp, lbp);
1320         leaf = lbp->b_addr;
1321         /*
1322          * Get to the leaf entry and contained data entry address.
1323          */
1324         lep = &leaf->ents[index];
1325         /*
1326          * Point to the data entry.
1327          */
1328         dep = (xfs_dir2_data_entry_t *)
1329               ((char *)dbp->b_addr +
1330                xfs_dir2_dataptr_to_off(dp->i_mount, be32_to_cpu(lep->address)));
1331         /*
1332          * Return the found inode number & CI name if appropriate
1333          */
1334         args->inumber = be64_to_cpu(dep->inumber);
1335         error = xfs_dir_cilookup_result(args, dep->name, dep->namelen);
1336         xfs_trans_brelse(tp, dbp);
1337         xfs_trans_brelse(tp, lbp);
1338         return XFS_ERROR(error);
1339 }
1340
1341 /*
1342  * Look up name/hash in the leaf block.
1343  * Fill in indexp with the found index, and dbpp with the data buffer.
1344  * If not found dbpp will be NULL, and ENOENT comes back.
1345  * lbpp will always be filled in with the leaf buffer unless there's an error.
1346  */
1347 static int                                      /* error */
1348 xfs_dir2_leaf_lookup_int(
1349         xfs_da_args_t           *args,          /* operation arguments */
1350         struct xfs_buf          **lbpp,         /* out: leaf buffer */
1351         int                     *indexp,        /* out: index in leaf block */
1352         struct xfs_buf          **dbpp)         /* out: data buffer */
1353 {
1354         xfs_dir2_db_t           curdb = -1;     /* current data block number */
1355         struct xfs_buf          *dbp = NULL;    /* data buffer */
1356         xfs_dir2_data_entry_t   *dep;           /* data entry */
1357         xfs_inode_t             *dp;            /* incore directory inode */
1358         int                     error;          /* error return code */
1359         int                     index;          /* index in leaf block */
1360         struct xfs_buf          *lbp;           /* leaf buffer */
1361         xfs_dir2_leaf_entry_t   *lep;           /* leaf entry */
1362         xfs_dir2_leaf_t         *leaf;          /* leaf structure */
1363         xfs_mount_t             *mp;            /* filesystem mount point */
1364         xfs_dir2_db_t           newdb;          /* new data block number */
1365         xfs_trans_t             *tp;            /* transaction pointer */
1366         xfs_dir2_db_t           cidb = -1;      /* case match data block no. */
1367         enum xfs_dacmp          cmp;            /* name compare result */
1368
1369         dp = args->dp;
1370         tp = args->trans;
1371         mp = dp->i_mount;
1372         /*
1373          * Read the leaf block into the buffer.
1374          */
1375         error = xfs_da_read_buf(tp, dp, mp->m_dirleafblk, -1, &lbp,
1376                                                         XFS_DATA_FORK, NULL);
1377         if (error)
1378                 return error;
1379         *lbpp = lbp;
1380         leaf = lbp->b_addr;
1381         xfs_dir2_leaf_check(dp, lbp);
1382         /*
1383          * Look for the first leaf entry with our hash value.
1384          */
1385         index = xfs_dir2_leaf_search_hash(args, lbp);
1386         /*
1387          * Loop over all the entries with the right hash value
1388          * looking to match the name.
1389          */
1390         for (lep = &leaf->ents[index]; index < be16_to_cpu(leaf->hdr.count) &&
1391                                 be32_to_cpu(lep->hashval) == args->hashval;
1392                                 lep++, index++) {
1393                 /*
1394                  * Skip over stale leaf entries.
1395                  */
1396                 if (be32_to_cpu(lep->address) == XFS_DIR2_NULL_DATAPTR)
1397                         continue;
1398                 /*
1399                  * Get the new data block number.
1400                  */
1401                 newdb = xfs_dir2_dataptr_to_db(mp, be32_to_cpu(lep->address));
1402                 /*
1403                  * If it's not the same as the old data block number,
1404                  * need to pitch the old one and read the new one.
1405                  */
1406                 if (newdb != curdb) {
1407                         if (dbp)
1408                                 xfs_trans_brelse(tp, dbp);
1409                         error = xfs_dir2_data_read(tp, dp,
1410                                                    xfs_dir2_db_to_da(mp, newdb),
1411                                                    -1, &dbp);
1412                         if (error) {
1413                                 xfs_trans_brelse(tp, lbp);
1414                                 return error;
1415                         }
1416                         curdb = newdb;
1417                 }
1418                 /*
1419                  * Point to the data entry.
1420                  */
1421                 dep = (xfs_dir2_data_entry_t *)((char *)dbp->b_addr +
1422                         xfs_dir2_dataptr_to_off(mp, be32_to_cpu(lep->address)));
1423                 /*
1424                  * Compare name and if it's an exact match, return the index
1425                  * and buffer. If it's the first case-insensitive match, store
1426                  * the index and buffer and continue looking for an exact match.
1427                  */
1428                 cmp = mp->m_dirnameops->compname(args, dep->name, dep->namelen);
1429                 if (cmp != XFS_CMP_DIFFERENT && cmp != args->cmpresult) {
1430                         args->cmpresult = cmp;
1431                         *indexp = index;
1432                         /* case exact match: return the current buffer. */
1433                         if (cmp == XFS_CMP_EXACT) {
1434                                 *dbpp = dbp;
1435                                 return 0;
1436                         }
1437                         cidb = curdb;
1438                 }
1439         }
1440         ASSERT(args->op_flags & XFS_DA_OP_OKNOENT);
1441         /*
1442          * Here, we can only be doing a lookup (not a rename or remove).
1443          * If a case-insensitive match was found earlier, re-read the
1444          * appropriate data block if required and return it.
1445          */
1446         if (args->cmpresult == XFS_CMP_CASE) {
1447                 ASSERT(cidb != -1);
1448                 if (cidb != curdb) {
1449                         xfs_trans_brelse(tp, dbp);
1450                         error = xfs_dir2_data_read(tp, dp,
1451                                                    xfs_dir2_db_to_da(mp, cidb),
1452                                                    -1, &dbp);
1453                         if (error) {
1454                                 xfs_trans_brelse(tp, lbp);
1455                                 return error;
1456                         }
1457                 }
1458                 *dbpp = dbp;
1459                 return 0;
1460         }
1461         /*
1462          * No match found, return ENOENT.
1463          */
1464         ASSERT(cidb == -1);
1465         if (dbp)
1466                 xfs_trans_brelse(tp, dbp);
1467         xfs_trans_brelse(tp, lbp);
1468         return XFS_ERROR(ENOENT);
1469 }
1470
1471 /*
1472  * Remove an entry from a leaf format directory.
1473  */
1474 int                                             /* error */
1475 xfs_dir2_leaf_removename(
1476         xfs_da_args_t           *args)          /* operation arguments */
1477 {
1478         __be16                  *bestsp;        /* leaf block best freespace */
1479         xfs_dir2_data_hdr_t     *hdr;           /* data block header */
1480         xfs_dir2_db_t           db;             /* data block number */
1481         struct xfs_buf          *dbp;           /* data block buffer */
1482         xfs_dir2_data_entry_t   *dep;           /* data entry structure */
1483         xfs_inode_t             *dp;            /* incore directory inode */
1484         int                     error;          /* error return code */
1485         xfs_dir2_db_t           i;              /* temporary data block # */
1486         int                     index;          /* index into leaf entries */
1487         struct xfs_buf          *lbp;           /* leaf buffer */
1488         xfs_dir2_leaf_t         *leaf;          /* leaf structure */
1489         xfs_dir2_leaf_entry_t   *lep;           /* leaf entry */
1490         xfs_dir2_leaf_tail_t    *ltp;           /* leaf tail structure */
1491         xfs_mount_t             *mp;            /* filesystem mount point */
1492         int                     needlog;        /* need to log data header */
1493         int                     needscan;       /* need to rescan data frees */
1494         xfs_dir2_data_off_t     oldbest;        /* old value of best free */
1495         xfs_trans_t             *tp;            /* transaction pointer */
1496
1497         trace_xfs_dir2_leaf_removename(args);
1498
1499         /*
1500          * Lookup the leaf entry, get the leaf and data blocks read in.
1501          */
1502         if ((error = xfs_dir2_leaf_lookup_int(args, &lbp, &index, &dbp))) {
1503                 return error;
1504         }
1505         dp = args->dp;
1506         tp = args->trans;
1507         mp = dp->i_mount;
1508         leaf = lbp->b_addr;
1509         hdr = dbp->b_addr;
1510         xfs_dir2_data_check(dp, dbp);
1511         /*
1512          * Point to the leaf entry, use that to point to the data entry.
1513          */
1514         lep = &leaf->ents[index];
1515         db = xfs_dir2_dataptr_to_db(mp, be32_to_cpu(lep->address));
1516         dep = (xfs_dir2_data_entry_t *)
1517               ((char *)hdr + xfs_dir2_dataptr_to_off(mp, be32_to_cpu(lep->address)));
1518         needscan = needlog = 0;
1519         oldbest = be16_to_cpu(hdr->bestfree[0].length);
1520         ltp = xfs_dir2_leaf_tail_p(mp, leaf);
1521         bestsp = xfs_dir2_leaf_bests_p(ltp);
1522         ASSERT(be16_to_cpu(bestsp[db]) == oldbest);
1523         /*
1524          * Mark the former data entry unused.
1525          */
1526         xfs_dir2_data_make_free(tp, dbp,
1527                 (xfs_dir2_data_aoff_t)((char *)dep - (char *)hdr),
1528                 xfs_dir2_data_entsize(dep->namelen), &needlog, &needscan);
1529         /*
1530          * We just mark the leaf entry stale by putting a null in it.
1531          */
1532         be16_add_cpu(&leaf->hdr.stale, 1);
1533         xfs_dir2_leaf_log_header(tp, lbp);
1534         lep->address = cpu_to_be32(XFS_DIR2_NULL_DATAPTR);
1535         xfs_dir2_leaf_log_ents(tp, lbp, index, index);
1536         /*
1537          * Scan the freespace in the data block again if necessary,
1538          * log the data block header if necessary.
1539          */
1540         if (needscan)
1541                 xfs_dir2_data_freescan(mp, hdr, &needlog);
1542         if (needlog)
1543                 xfs_dir2_data_log_header(tp, dbp);
1544         /*
1545          * If the longest freespace in the data block has changed,
1546          * put the new value in the bests table and log that.
1547          */
1548         if (be16_to_cpu(hdr->bestfree[0].length) != oldbest) {
1549                 bestsp[db] = hdr->bestfree[0].length;
1550                 xfs_dir2_leaf_log_bests(tp, lbp, db, db);
1551         }
1552         xfs_dir2_data_check(dp, dbp);
1553         /*
1554          * If the data block is now empty then get rid of the data block.
1555          */
1556         if (be16_to_cpu(hdr->bestfree[0].length) ==
1557             mp->m_dirblksize - (uint)sizeof(*hdr)) {
1558                 ASSERT(db != mp->m_dirdatablk);
1559                 if ((error = xfs_dir2_shrink_inode(args, db, dbp))) {
1560                         /*
1561                          * Nope, can't get rid of it because it caused
1562                          * allocation of a bmap btree block to do so.
1563                          * Just go on, returning success, leaving the
1564                          * empty block in place.
1565                          */
1566                         if (error == ENOSPC && args->total == 0)
1567                                 error = 0;
1568                         xfs_dir2_leaf_check(dp, lbp);
1569                         return error;
1570                 }
1571                 dbp = NULL;
1572                 /*
1573                  * If this is the last data block then compact the
1574                  * bests table by getting rid of entries.
1575                  */
1576                 if (db == be32_to_cpu(ltp->bestcount) - 1) {
1577                         /*
1578                          * Look for the last active entry (i).
1579                          */
1580                         for (i = db - 1; i > 0; i--) {
1581                                 if (bestsp[i] != cpu_to_be16(NULLDATAOFF))
1582                                         break;
1583                         }
1584                         /*
1585                          * Copy the table down so inactive entries at the
1586                          * end are removed.
1587                          */
1588                         memmove(&bestsp[db - i], bestsp,
1589                                 (be32_to_cpu(ltp->bestcount) - (db - i)) * sizeof(*bestsp));
1590                         be32_add_cpu(&ltp->bestcount, -(db - i));
1591                         xfs_dir2_leaf_log_tail(tp, lbp);
1592                         xfs_dir2_leaf_log_bests(tp, lbp, 0, be32_to_cpu(ltp->bestcount) - 1);
1593                 } else
1594                         bestsp[db] = cpu_to_be16(NULLDATAOFF);
1595         }
1596         /*
1597          * If the data block was not the first one, drop it.
1598          */
1599         else if (db != mp->m_dirdatablk)
1600                 dbp = NULL;
1601
1602         xfs_dir2_leaf_check(dp, lbp);
1603         /*
1604          * See if we can convert to block form.
1605          */
1606         return xfs_dir2_leaf_to_block(args, lbp, dbp);
1607 }
1608
1609 /*
1610  * Replace the inode number in a leaf format directory entry.
1611  */
1612 int                                             /* error */
1613 xfs_dir2_leaf_replace(
1614         xfs_da_args_t           *args)          /* operation arguments */
1615 {
1616         struct xfs_buf          *dbp;           /* data block buffer */
1617         xfs_dir2_data_entry_t   *dep;           /* data block entry */
1618         xfs_inode_t             *dp;            /* incore directory inode */
1619         int                     error;          /* error return code */
1620         int                     index;          /* index of leaf entry */
1621         struct xfs_buf          *lbp;           /* leaf buffer */
1622         xfs_dir2_leaf_t         *leaf;          /* leaf structure */
1623         xfs_dir2_leaf_entry_t   *lep;           /* leaf entry */
1624         xfs_trans_t             *tp;            /* transaction pointer */
1625
1626         trace_xfs_dir2_leaf_replace(args);
1627
1628         /*
1629          * Look up the entry.
1630          */
1631         if ((error = xfs_dir2_leaf_lookup_int(args, &lbp, &index, &dbp))) {
1632                 return error;
1633         }
1634         dp = args->dp;
1635         leaf = lbp->b_addr;
1636         /*
1637          * Point to the leaf entry, get data address from it.
1638          */
1639         lep = &leaf->ents[index];
1640         /*
1641          * Point to the data entry.
1642          */
1643         dep = (xfs_dir2_data_entry_t *)
1644               ((char *)dbp->b_addr +
1645                xfs_dir2_dataptr_to_off(dp->i_mount, be32_to_cpu(lep->address)));
1646         ASSERT(args->inumber != be64_to_cpu(dep->inumber));
1647         /*
1648          * Put the new inode number in, log it.
1649          */
1650         dep->inumber = cpu_to_be64(args->inumber);
1651         tp = args->trans;
1652         xfs_dir2_data_log_entry(tp, dbp, dep);
1653         xfs_dir2_leaf_check(dp, lbp);
1654         xfs_trans_brelse(tp, lbp);
1655         return 0;
1656 }
1657
1658 /*
1659  * Return index in the leaf block (lbp) which is either the first
1660  * one with this hash value, or if there are none, the insert point
1661  * for that hash value.
1662  */
1663 int                                             /* index value */
1664 xfs_dir2_leaf_search_hash(
1665         xfs_da_args_t           *args,          /* operation arguments */
1666         struct xfs_buf          *lbp)           /* leaf buffer */
1667 {
1668         xfs_dahash_t            hash=0;         /* hash from this entry */
1669         xfs_dahash_t            hashwant;       /* hash value looking for */
1670         int                     high;           /* high leaf index */
1671         int                     low;            /* low leaf index */
1672         xfs_dir2_leaf_t         *leaf;          /* leaf structure */
1673         xfs_dir2_leaf_entry_t   *lep;           /* leaf entry */
1674         int                     mid=0;          /* current leaf index */
1675
1676         leaf = lbp->b_addr;
1677 #ifndef __KERNEL__
1678         if (!leaf->hdr.count)
1679                 return 0;
1680 #endif
1681         /*
1682          * Note, the table cannot be empty, so we have to go through the loop.
1683          * Binary search the leaf entries looking for our hash value.
1684          */
1685         for (lep = leaf->ents, low = 0, high = be16_to_cpu(leaf->hdr.count) - 1,
1686                 hashwant = args->hashval;
1687              low <= high; ) {
1688                 mid = (low + high) >> 1;
1689                 if ((hash = be32_to_cpu(lep[mid].hashval)) == hashwant)
1690                         break;
1691                 if (hash < hashwant)
1692                         low = mid + 1;
1693                 else
1694                         high = mid - 1;
1695         }
1696         /*
1697          * Found one, back up through all the equal hash values.
1698          */
1699         if (hash == hashwant) {
1700                 while (mid > 0 && be32_to_cpu(lep[mid - 1].hashval) == hashwant) {
1701                         mid--;
1702                 }
1703         }
1704         /*
1705          * Need to point to an entry higher than ours.
1706          */
1707         else if (hash < hashwant)
1708                 mid++;
1709         return mid;
1710 }
1711
1712 /*
1713  * Trim off a trailing data block.  We know it's empty since the leaf
1714  * freespace table says so.
1715  */
1716 int                                             /* error */
1717 xfs_dir2_leaf_trim_data(
1718         xfs_da_args_t           *args,          /* operation arguments */
1719         struct xfs_buf          *lbp,           /* leaf buffer */
1720         xfs_dir2_db_t           db)             /* data block number */
1721 {
1722         __be16                  *bestsp;        /* leaf bests table */
1723         struct xfs_buf          *dbp;           /* data block buffer */
1724         xfs_inode_t             *dp;            /* incore directory inode */
1725         int                     error;          /* error return value */
1726         xfs_dir2_leaf_t         *leaf;          /* leaf structure */
1727         xfs_dir2_leaf_tail_t    *ltp;           /* leaf tail structure */
1728         xfs_mount_t             *mp;            /* filesystem mount point */
1729         xfs_trans_t             *tp;            /* transaction pointer */
1730
1731         dp = args->dp;
1732         mp = dp->i_mount;
1733         tp = args->trans;
1734         /*
1735          * Read the offending data block.  We need its buffer.
1736          */
1737         error = xfs_dir2_data_read(tp, dp, xfs_dir2_db_to_da(mp, db), -1, &dbp);
1738         if (error)
1739                 return error;
1740
1741         leaf = lbp->b_addr;
1742         ltp = xfs_dir2_leaf_tail_p(mp, leaf);
1743
1744 #ifdef DEBUG
1745 {
1746         struct xfs_dir2_data_hdr *hdr = dbp->b_addr;
1747
1748         ASSERT(hdr->magic == cpu_to_be32(XFS_DIR2_DATA_MAGIC));
1749         ASSERT(be16_to_cpu(hdr->bestfree[0].length) ==
1750                mp->m_dirblksize - (uint)sizeof(*hdr));
1751         ASSERT(db == be32_to_cpu(ltp->bestcount) - 1);
1752 }
1753 #endif
1754
1755         /*
1756          * Get rid of the data block.
1757          */
1758         if ((error = xfs_dir2_shrink_inode(args, db, dbp))) {
1759                 ASSERT(error != ENOSPC);
1760                 xfs_trans_brelse(tp, dbp);
1761                 return error;
1762         }
1763         /*
1764          * Eliminate the last bests entry from the table.
1765          */
1766         bestsp = xfs_dir2_leaf_bests_p(ltp);
1767         be32_add_cpu(&ltp->bestcount, -1);
1768         memmove(&bestsp[1], &bestsp[0], be32_to_cpu(ltp->bestcount) * sizeof(*bestsp));
1769         xfs_dir2_leaf_log_tail(tp, lbp);
1770         xfs_dir2_leaf_log_bests(tp, lbp, 0, be32_to_cpu(ltp->bestcount) - 1);
1771         return 0;
1772 }
1773
1774 static inline size_t
1775 xfs_dir2_leaf_size(
1776         struct xfs_dir2_leaf_hdr        *hdr,
1777         int                             counts)
1778 {
1779         int                     entries;
1780
1781         entries = be16_to_cpu(hdr->count) - be16_to_cpu(hdr->stale);
1782         return sizeof(xfs_dir2_leaf_hdr_t) +
1783             entries * sizeof(xfs_dir2_leaf_entry_t) +
1784             counts * sizeof(xfs_dir2_data_off_t) +
1785             sizeof(xfs_dir2_leaf_tail_t);
1786 }
1787
1788 /*
1789  * Convert node form directory to leaf form directory.
1790  * The root of the node form dir needs to already be a LEAFN block.
1791  * Just return if we can't do anything.
1792  */
1793 int                                             /* error */
1794 xfs_dir2_node_to_leaf(
1795         xfs_da_state_t          *state)         /* directory operation state */
1796 {
1797         xfs_da_args_t           *args;          /* operation arguments */
1798         xfs_inode_t             *dp;            /* incore directory inode */
1799         int                     error;          /* error return code */
1800         struct xfs_buf          *fbp;           /* buffer for freespace block */
1801         xfs_fileoff_t           fo;             /* freespace file offset */
1802         xfs_dir2_free_t         *free;          /* freespace structure */
1803         struct xfs_buf          *lbp;           /* buffer for leaf block */
1804         xfs_dir2_leaf_tail_t    *ltp;           /* tail of leaf structure */
1805         xfs_dir2_leaf_t         *leaf;          /* leaf structure */
1806         xfs_mount_t             *mp;            /* filesystem mount point */
1807         int                     rval;           /* successful free trim? */
1808         xfs_trans_t             *tp;            /* transaction pointer */
1809
1810         /*
1811          * There's more than a leaf level in the btree, so there must
1812          * be multiple leafn blocks.  Give up.
1813          */
1814         if (state->path.active > 1)
1815                 return 0;
1816         args = state->args;
1817
1818         trace_xfs_dir2_node_to_leaf(args);
1819
1820         mp = state->mp;
1821         dp = args->dp;
1822         tp = args->trans;
1823         /*
1824          * Get the last offset in the file.
1825          */
1826         if ((error = xfs_bmap_last_offset(tp, dp, &fo, XFS_DATA_FORK))) {
1827                 return error;
1828         }
1829         fo -= mp->m_dirblkfsbs;
1830         /*
1831          * If there are freespace blocks other than the first one,
1832          * take this opportunity to remove trailing empty freespace blocks
1833          * that may have been left behind during no-space-reservation
1834          * operations.
1835          */
1836         while (fo > mp->m_dirfreeblk) {
1837                 if ((error = xfs_dir2_node_trim_free(args, fo, &rval))) {
1838                         return error;
1839                 }
1840                 if (rval)
1841                         fo -= mp->m_dirblkfsbs;
1842                 else
1843                         return 0;
1844         }
1845         /*
1846          * Now find the block just before the freespace block.
1847          */
1848         if ((error = xfs_bmap_last_before(tp, dp, &fo, XFS_DATA_FORK))) {
1849                 return error;
1850         }
1851         /*
1852          * If it's not the single leaf block, give up.
1853          */
1854         if (XFS_FSB_TO_B(mp, fo) > XFS_DIR2_LEAF_OFFSET + mp->m_dirblksize)
1855                 return 0;
1856         lbp = state->path.blk[0].bp;
1857         leaf = lbp->b_addr;
1858         ASSERT(leaf->hdr.info.magic == cpu_to_be16(XFS_DIR2_LEAFN_MAGIC));
1859         /*
1860          * Read the freespace block.
1861          */
1862         error = xfs_dir2_free_read(tp, dp,  mp->m_dirfreeblk, &fbp);
1863         if (error)
1864                 return error;
1865         free = fbp->b_addr;
1866         ASSERT(free->hdr.magic == cpu_to_be32(XFS_DIR2_FREE_MAGIC));
1867         ASSERT(!free->hdr.firstdb);
1868
1869         /*
1870          * Now see if the leafn and free data will fit in a leaf1.
1871          * If not, release the buffer and give up.
1872          */
1873         if (xfs_dir2_leaf_size(&leaf->hdr, be32_to_cpu(free->hdr.nvalid)) >
1874                         mp->m_dirblksize) {
1875                 xfs_trans_brelse(tp, fbp);
1876                 return 0;
1877         }
1878
1879         /*
1880          * If the leaf has any stale entries in it, compress them out.
1881          * The compact routine will log the header.
1882          */
1883         if (be16_to_cpu(leaf->hdr.stale))
1884                 xfs_dir2_leaf_compact(args, lbp);
1885         else
1886                 xfs_dir2_leaf_log_header(tp, lbp);
1887         leaf->hdr.info.magic = cpu_to_be16(XFS_DIR2_LEAF1_MAGIC);
1888         /*
1889          * Set up the leaf tail from the freespace block.
1890          */
1891         ltp = xfs_dir2_leaf_tail_p(mp, leaf);
1892         ltp->bestcount = free->hdr.nvalid;
1893         /*
1894          * Set up the leaf bests table.
1895          */
1896         memcpy(xfs_dir2_leaf_bests_p(ltp), free->bests,
1897                 be32_to_cpu(ltp->bestcount) * sizeof(xfs_dir2_data_off_t));
1898         xfs_dir2_leaf_log_bests(tp, lbp, 0, be32_to_cpu(ltp->bestcount) - 1);
1899         xfs_dir2_leaf_log_tail(tp, lbp);
1900         xfs_dir2_leaf_check(dp, lbp);
1901         /*
1902          * Get rid of the freespace block.
1903          */
1904         error = xfs_dir2_shrink_inode(args, XFS_DIR2_FREE_FIRSTDB(mp), fbp);
1905         if (error) {
1906                 /*
1907                  * This can't fail here because it can only happen when
1908                  * punching out the middle of an extent, and this is an
1909                  * isolated block.
1910                  */
1911                 ASSERT(error != ENOSPC);
1912                 return error;
1913         }
1914         fbp = NULL;
1915         /*
1916          * Now see if we can convert the single-leaf directory
1917          * down to a block form directory.
1918          * This routine always kills the dabuf for the leaf, so
1919          * eliminate it from the path.
1920          */
1921         error = xfs_dir2_leaf_to_block(args, lbp, NULL);
1922         state->path.blk[0].bp = NULL;
1923         return error;
1924 }