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