xfs: add tracepoints and error injection for deferred extent freeing
[cascardo/linux.git] / fs / xfs / libxfs / xfs_alloc.c
1 /*
2  * Copyright (c) 2000-2002,2005 Silicon Graphics, Inc.
3  * All Rights Reserved.
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License as
7  * published by the Free Software Foundation.
8  *
9  * This program is distributed in the hope that it would be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write the Free Software Foundation,
16  * Inc.,  51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
17  */
18 #include "xfs.h"
19 #include "xfs_fs.h"
20 #include "xfs_format.h"
21 #include "xfs_log_format.h"
22 #include "xfs_shared.h"
23 #include "xfs_trans_resv.h"
24 #include "xfs_bit.h"
25 #include "xfs_sb.h"
26 #include "xfs_mount.h"
27 #include "xfs_defer.h"
28 #include "xfs_inode.h"
29 #include "xfs_btree.h"
30 #include "xfs_alloc_btree.h"
31 #include "xfs_alloc.h"
32 #include "xfs_extent_busy.h"
33 #include "xfs_error.h"
34 #include "xfs_cksum.h"
35 #include "xfs_trace.h"
36 #include "xfs_trans.h"
37 #include "xfs_buf_item.h"
38 #include "xfs_log.h"
39
40 struct workqueue_struct *xfs_alloc_wq;
41
42 #define XFS_ABSDIFF(a,b)        (((a) <= (b)) ? ((b) - (a)) : ((a) - (b)))
43
44 #define XFSA_FIXUP_BNO_OK       1
45 #define XFSA_FIXUP_CNT_OK       2
46
47 STATIC int xfs_alloc_ag_vextent_exact(xfs_alloc_arg_t *);
48 STATIC int xfs_alloc_ag_vextent_near(xfs_alloc_arg_t *);
49 STATIC int xfs_alloc_ag_vextent_size(xfs_alloc_arg_t *);
50 STATIC int xfs_alloc_ag_vextent_small(xfs_alloc_arg_t *,
51                 xfs_btree_cur_t *, xfs_agblock_t *, xfs_extlen_t *, int *);
52
53 /*
54  * Lookup the record equal to [bno, len] in the btree given by cur.
55  */
56 STATIC int                              /* error */
57 xfs_alloc_lookup_eq(
58         struct xfs_btree_cur    *cur,   /* btree cursor */
59         xfs_agblock_t           bno,    /* starting block of extent */
60         xfs_extlen_t            len,    /* length of extent */
61         int                     *stat)  /* success/failure */
62 {
63         cur->bc_rec.a.ar_startblock = bno;
64         cur->bc_rec.a.ar_blockcount = len;
65         return xfs_btree_lookup(cur, XFS_LOOKUP_EQ, stat);
66 }
67
68 /*
69  * Lookup the first record greater than or equal to [bno, len]
70  * in the btree given by cur.
71  */
72 int                             /* error */
73 xfs_alloc_lookup_ge(
74         struct xfs_btree_cur    *cur,   /* btree cursor */
75         xfs_agblock_t           bno,    /* starting block of extent */
76         xfs_extlen_t            len,    /* length of extent */
77         int                     *stat)  /* success/failure */
78 {
79         cur->bc_rec.a.ar_startblock = bno;
80         cur->bc_rec.a.ar_blockcount = len;
81         return xfs_btree_lookup(cur, XFS_LOOKUP_GE, stat);
82 }
83
84 /*
85  * Lookup the first record less than or equal to [bno, len]
86  * in the btree given by cur.
87  */
88 static int                              /* error */
89 xfs_alloc_lookup_le(
90         struct xfs_btree_cur    *cur,   /* btree cursor */
91         xfs_agblock_t           bno,    /* starting block of extent */
92         xfs_extlen_t            len,    /* length of extent */
93         int                     *stat)  /* success/failure */
94 {
95         cur->bc_rec.a.ar_startblock = bno;
96         cur->bc_rec.a.ar_blockcount = len;
97         return xfs_btree_lookup(cur, XFS_LOOKUP_LE, stat);
98 }
99
100 /*
101  * Update the record referred to by cur to the value given
102  * by [bno, len].
103  * This either works (return 0) or gets an EFSCORRUPTED error.
104  */
105 STATIC int                              /* error */
106 xfs_alloc_update(
107         struct xfs_btree_cur    *cur,   /* btree cursor */
108         xfs_agblock_t           bno,    /* starting block of extent */
109         xfs_extlen_t            len)    /* length of extent */
110 {
111         union xfs_btree_rec     rec;
112
113         rec.alloc.ar_startblock = cpu_to_be32(bno);
114         rec.alloc.ar_blockcount = cpu_to_be32(len);
115         return xfs_btree_update(cur, &rec);
116 }
117
118 /*
119  * Get the data from the pointed-to record.
120  */
121 int                                     /* error */
122 xfs_alloc_get_rec(
123         struct xfs_btree_cur    *cur,   /* btree cursor */
124         xfs_agblock_t           *bno,   /* output: starting block of extent */
125         xfs_extlen_t            *len,   /* output: length of extent */
126         int                     *stat)  /* output: success/failure */
127 {
128         union xfs_btree_rec     *rec;
129         int                     error;
130
131         error = xfs_btree_get_rec(cur, &rec, stat);
132         if (!error && *stat == 1) {
133                 *bno = be32_to_cpu(rec->alloc.ar_startblock);
134                 *len = be32_to_cpu(rec->alloc.ar_blockcount);
135         }
136         return error;
137 }
138
139 /*
140  * Compute aligned version of the found extent.
141  * Takes alignment and min length into account.
142  */
143 STATIC void
144 xfs_alloc_compute_aligned(
145         xfs_alloc_arg_t *args,          /* allocation argument structure */
146         xfs_agblock_t   foundbno,       /* starting block in found extent */
147         xfs_extlen_t    foundlen,       /* length in found extent */
148         xfs_agblock_t   *resbno,        /* result block number */
149         xfs_extlen_t    *reslen)        /* result length */
150 {
151         xfs_agblock_t   bno;
152         xfs_extlen_t    len;
153         xfs_extlen_t    diff;
154
155         /* Trim busy sections out of found extent */
156         xfs_extent_busy_trim(args, foundbno, foundlen, &bno, &len);
157
158         /*
159          * If we have a largish extent that happens to start before min_agbno,
160          * see if we can shift it into range...
161          */
162         if (bno < args->min_agbno && bno + len > args->min_agbno) {
163                 diff = args->min_agbno - bno;
164                 if (len > diff) {
165                         bno += diff;
166                         len -= diff;
167                 }
168         }
169
170         if (args->alignment > 1 && len >= args->minlen) {
171                 xfs_agblock_t   aligned_bno = roundup(bno, args->alignment);
172
173                 diff = aligned_bno - bno;
174
175                 *resbno = aligned_bno;
176                 *reslen = diff >= len ? 0 : len - diff;
177         } else {
178                 *resbno = bno;
179                 *reslen = len;
180         }
181 }
182
183 /*
184  * Compute best start block and diff for "near" allocations.
185  * freelen >= wantlen already checked by caller.
186  */
187 STATIC xfs_extlen_t                     /* difference value (absolute) */
188 xfs_alloc_compute_diff(
189         xfs_agblock_t   wantbno,        /* target starting block */
190         xfs_extlen_t    wantlen,        /* target length */
191         xfs_extlen_t    alignment,      /* target alignment */
192         char            userdata,       /* are we allocating data? */
193         xfs_agblock_t   freebno,        /* freespace's starting block */
194         xfs_extlen_t    freelen,        /* freespace's length */
195         xfs_agblock_t   *newbnop)       /* result: best start block from free */
196 {
197         xfs_agblock_t   freeend;        /* end of freespace extent */
198         xfs_agblock_t   newbno1;        /* return block number */
199         xfs_agblock_t   newbno2;        /* other new block number */
200         xfs_extlen_t    newlen1=0;      /* length with newbno1 */
201         xfs_extlen_t    newlen2=0;      /* length with newbno2 */
202         xfs_agblock_t   wantend;        /* end of target extent */
203
204         ASSERT(freelen >= wantlen);
205         freeend = freebno + freelen;
206         wantend = wantbno + wantlen;
207         /*
208          * We want to allocate from the start of a free extent if it is past
209          * the desired block or if we are allocating user data and the free
210          * extent is before desired block. The second case is there to allow
211          * for contiguous allocation from the remaining free space if the file
212          * grows in the short term.
213          */
214         if (freebno >= wantbno || (userdata && freeend < wantend)) {
215                 if ((newbno1 = roundup(freebno, alignment)) >= freeend)
216                         newbno1 = NULLAGBLOCK;
217         } else if (freeend >= wantend && alignment > 1) {
218                 newbno1 = roundup(wantbno, alignment);
219                 newbno2 = newbno1 - alignment;
220                 if (newbno1 >= freeend)
221                         newbno1 = NULLAGBLOCK;
222                 else
223                         newlen1 = XFS_EXTLEN_MIN(wantlen, freeend - newbno1);
224                 if (newbno2 < freebno)
225                         newbno2 = NULLAGBLOCK;
226                 else
227                         newlen2 = XFS_EXTLEN_MIN(wantlen, freeend - newbno2);
228                 if (newbno1 != NULLAGBLOCK && newbno2 != NULLAGBLOCK) {
229                         if (newlen1 < newlen2 ||
230                             (newlen1 == newlen2 &&
231                              XFS_ABSDIFF(newbno1, wantbno) >
232                              XFS_ABSDIFF(newbno2, wantbno)))
233                                 newbno1 = newbno2;
234                 } else if (newbno2 != NULLAGBLOCK)
235                         newbno1 = newbno2;
236         } else if (freeend >= wantend) {
237                 newbno1 = wantbno;
238         } else if (alignment > 1) {
239                 newbno1 = roundup(freeend - wantlen, alignment);
240                 if (newbno1 > freeend - wantlen &&
241                     newbno1 - alignment >= freebno)
242                         newbno1 -= alignment;
243                 else if (newbno1 >= freeend)
244                         newbno1 = NULLAGBLOCK;
245         } else
246                 newbno1 = freeend - wantlen;
247         *newbnop = newbno1;
248         return newbno1 == NULLAGBLOCK ? 0 : XFS_ABSDIFF(newbno1, wantbno);
249 }
250
251 /*
252  * Fix up the length, based on mod and prod.
253  * len should be k * prod + mod for some k.
254  * If len is too small it is returned unchanged.
255  * If len hits maxlen it is left alone.
256  */
257 STATIC void
258 xfs_alloc_fix_len(
259         xfs_alloc_arg_t *args)          /* allocation argument structure */
260 {
261         xfs_extlen_t    k;
262         xfs_extlen_t    rlen;
263
264         ASSERT(args->mod < args->prod);
265         rlen = args->len;
266         ASSERT(rlen >= args->minlen);
267         ASSERT(rlen <= args->maxlen);
268         if (args->prod <= 1 || rlen < args->mod || rlen == args->maxlen ||
269             (args->mod == 0 && rlen < args->prod))
270                 return;
271         k = rlen % args->prod;
272         if (k == args->mod)
273                 return;
274         if (k > args->mod)
275                 rlen = rlen - (k - args->mod);
276         else
277                 rlen = rlen - args->prod + (args->mod - k);
278         /* casts to (int) catch length underflows */
279         if ((int)rlen < (int)args->minlen)
280                 return;
281         ASSERT(rlen >= args->minlen && rlen <= args->maxlen);
282         ASSERT(rlen % args->prod == args->mod);
283         args->len = rlen;
284 }
285
286 /*
287  * Fix up length if there is too little space left in the a.g.
288  * Return 1 if ok, 0 if too little, should give up.
289  */
290 STATIC int
291 xfs_alloc_fix_minleft(
292         xfs_alloc_arg_t *args)          /* allocation argument structure */
293 {
294         xfs_agf_t       *agf;           /* a.g. freelist header */
295         int             diff;           /* free space difference */
296
297         if (args->minleft == 0)
298                 return 1;
299         agf = XFS_BUF_TO_AGF(args->agbp);
300         diff = be32_to_cpu(agf->agf_freeblks)
301                 - args->len - args->minleft;
302         if (diff >= 0)
303                 return 1;
304         args->len += diff;              /* shrink the allocated space */
305         /* casts to (int) catch length underflows */
306         if ((int)args->len >= (int)args->minlen)
307                 return 1;
308         args->agbno = NULLAGBLOCK;
309         return 0;
310 }
311
312 /*
313  * Update the two btrees, logically removing from freespace the extent
314  * starting at rbno, rlen blocks.  The extent is contained within the
315  * actual (current) free extent fbno for flen blocks.
316  * Flags are passed in indicating whether the cursors are set to the
317  * relevant records.
318  */
319 STATIC int                              /* error code */
320 xfs_alloc_fixup_trees(
321         xfs_btree_cur_t *cnt_cur,       /* cursor for by-size btree */
322         xfs_btree_cur_t *bno_cur,       /* cursor for by-block btree */
323         xfs_agblock_t   fbno,           /* starting block of free extent */
324         xfs_extlen_t    flen,           /* length of free extent */
325         xfs_agblock_t   rbno,           /* starting block of returned extent */
326         xfs_extlen_t    rlen,           /* length of returned extent */
327         int             flags)          /* flags, XFSA_FIXUP_... */
328 {
329         int             error;          /* error code */
330         int             i;              /* operation results */
331         xfs_agblock_t   nfbno1;         /* first new free startblock */
332         xfs_agblock_t   nfbno2;         /* second new free startblock */
333         xfs_extlen_t    nflen1=0;       /* first new free length */
334         xfs_extlen_t    nflen2=0;       /* second new free length */
335         struct xfs_mount *mp;
336
337         mp = cnt_cur->bc_mp;
338
339         /*
340          * Look up the record in the by-size tree if necessary.
341          */
342         if (flags & XFSA_FIXUP_CNT_OK) {
343 #ifdef DEBUG
344                 if ((error = xfs_alloc_get_rec(cnt_cur, &nfbno1, &nflen1, &i)))
345                         return error;
346                 XFS_WANT_CORRUPTED_RETURN(mp,
347                         i == 1 && nfbno1 == fbno && nflen1 == flen);
348 #endif
349         } else {
350                 if ((error = xfs_alloc_lookup_eq(cnt_cur, fbno, flen, &i)))
351                         return error;
352                 XFS_WANT_CORRUPTED_RETURN(mp, i == 1);
353         }
354         /*
355          * Look up the record in the by-block tree if necessary.
356          */
357         if (flags & XFSA_FIXUP_BNO_OK) {
358 #ifdef DEBUG
359                 if ((error = xfs_alloc_get_rec(bno_cur, &nfbno1, &nflen1, &i)))
360                         return error;
361                 XFS_WANT_CORRUPTED_RETURN(mp,
362                         i == 1 && nfbno1 == fbno && nflen1 == flen);
363 #endif
364         } else {
365                 if ((error = xfs_alloc_lookup_eq(bno_cur, fbno, flen, &i)))
366                         return error;
367                 XFS_WANT_CORRUPTED_RETURN(mp, i == 1);
368         }
369
370 #ifdef DEBUG
371         if (bno_cur->bc_nlevels == 1 && cnt_cur->bc_nlevels == 1) {
372                 struct xfs_btree_block  *bnoblock;
373                 struct xfs_btree_block  *cntblock;
374
375                 bnoblock = XFS_BUF_TO_BLOCK(bno_cur->bc_bufs[0]);
376                 cntblock = XFS_BUF_TO_BLOCK(cnt_cur->bc_bufs[0]);
377
378                 XFS_WANT_CORRUPTED_RETURN(mp,
379                         bnoblock->bb_numrecs == cntblock->bb_numrecs);
380         }
381 #endif
382
383         /*
384          * Deal with all four cases: the allocated record is contained
385          * within the freespace record, so we can have new freespace
386          * at either (or both) end, or no freespace remaining.
387          */
388         if (rbno == fbno && rlen == flen)
389                 nfbno1 = nfbno2 = NULLAGBLOCK;
390         else if (rbno == fbno) {
391                 nfbno1 = rbno + rlen;
392                 nflen1 = flen - rlen;
393                 nfbno2 = NULLAGBLOCK;
394         } else if (rbno + rlen == fbno + flen) {
395                 nfbno1 = fbno;
396                 nflen1 = flen - rlen;
397                 nfbno2 = NULLAGBLOCK;
398         } else {
399                 nfbno1 = fbno;
400                 nflen1 = rbno - fbno;
401                 nfbno2 = rbno + rlen;
402                 nflen2 = (fbno + flen) - nfbno2;
403         }
404         /*
405          * Delete the entry from the by-size btree.
406          */
407         if ((error = xfs_btree_delete(cnt_cur, &i)))
408                 return error;
409         XFS_WANT_CORRUPTED_RETURN(mp, i == 1);
410         /*
411          * Add new by-size btree entry(s).
412          */
413         if (nfbno1 != NULLAGBLOCK) {
414                 if ((error = xfs_alloc_lookup_eq(cnt_cur, nfbno1, nflen1, &i)))
415                         return error;
416                 XFS_WANT_CORRUPTED_RETURN(mp, i == 0);
417                 if ((error = xfs_btree_insert(cnt_cur, &i)))
418                         return error;
419                 XFS_WANT_CORRUPTED_RETURN(mp, i == 1);
420         }
421         if (nfbno2 != NULLAGBLOCK) {
422                 if ((error = xfs_alloc_lookup_eq(cnt_cur, nfbno2, nflen2, &i)))
423                         return error;
424                 XFS_WANT_CORRUPTED_RETURN(mp, i == 0);
425                 if ((error = xfs_btree_insert(cnt_cur, &i)))
426                         return error;
427                 XFS_WANT_CORRUPTED_RETURN(mp, i == 1);
428         }
429         /*
430          * Fix up the by-block btree entry(s).
431          */
432         if (nfbno1 == NULLAGBLOCK) {
433                 /*
434                  * No remaining freespace, just delete the by-block tree entry.
435                  */
436                 if ((error = xfs_btree_delete(bno_cur, &i)))
437                         return error;
438                 XFS_WANT_CORRUPTED_RETURN(mp, i == 1);
439         } else {
440                 /*
441                  * Update the by-block entry to start later|be shorter.
442                  */
443                 if ((error = xfs_alloc_update(bno_cur, nfbno1, nflen1)))
444                         return error;
445         }
446         if (nfbno2 != NULLAGBLOCK) {
447                 /*
448                  * 2 resulting free entries, need to add one.
449                  */
450                 if ((error = xfs_alloc_lookup_eq(bno_cur, nfbno2, nflen2, &i)))
451                         return error;
452                 XFS_WANT_CORRUPTED_RETURN(mp, i == 0);
453                 if ((error = xfs_btree_insert(bno_cur, &i)))
454                         return error;
455                 XFS_WANT_CORRUPTED_RETURN(mp, i == 1);
456         }
457         return 0;
458 }
459
460 static bool
461 xfs_agfl_verify(
462         struct xfs_buf  *bp)
463 {
464         struct xfs_mount *mp = bp->b_target->bt_mount;
465         struct xfs_agfl *agfl = XFS_BUF_TO_AGFL(bp);
466         int             i;
467
468         if (!uuid_equal(&agfl->agfl_uuid, &mp->m_sb.sb_meta_uuid))
469                 return false;
470         if (be32_to_cpu(agfl->agfl_magicnum) != XFS_AGFL_MAGIC)
471                 return false;
472         /*
473          * during growfs operations, the perag is not fully initialised,
474          * so we can't use it for any useful checking. growfs ensures we can't
475          * use it by using uncached buffers that don't have the perag attached
476          * so we can detect and avoid this problem.
477          */
478         if (bp->b_pag && be32_to_cpu(agfl->agfl_seqno) != bp->b_pag->pag_agno)
479                 return false;
480
481         for (i = 0; i < XFS_AGFL_SIZE(mp); i++) {
482                 if (be32_to_cpu(agfl->agfl_bno[i]) != NULLAGBLOCK &&
483                     be32_to_cpu(agfl->agfl_bno[i]) >= mp->m_sb.sb_agblocks)
484                         return false;
485         }
486
487         return xfs_log_check_lsn(mp,
488                                  be64_to_cpu(XFS_BUF_TO_AGFL(bp)->agfl_lsn));
489 }
490
491 static void
492 xfs_agfl_read_verify(
493         struct xfs_buf  *bp)
494 {
495         struct xfs_mount *mp = bp->b_target->bt_mount;
496
497         /*
498          * There is no verification of non-crc AGFLs because mkfs does not
499          * initialise the AGFL to zero or NULL. Hence the only valid part of the
500          * AGFL is what the AGF says is active. We can't get to the AGF, so we
501          * can't verify just those entries are valid.
502          */
503         if (!xfs_sb_version_hascrc(&mp->m_sb))
504                 return;
505
506         if (!xfs_buf_verify_cksum(bp, XFS_AGFL_CRC_OFF))
507                 xfs_buf_ioerror(bp, -EFSBADCRC);
508         else if (!xfs_agfl_verify(bp))
509                 xfs_buf_ioerror(bp, -EFSCORRUPTED);
510
511         if (bp->b_error)
512                 xfs_verifier_error(bp);
513 }
514
515 static void
516 xfs_agfl_write_verify(
517         struct xfs_buf  *bp)
518 {
519         struct xfs_mount *mp = bp->b_target->bt_mount;
520         struct xfs_buf_log_item *bip = bp->b_fspriv;
521
522         /* no verification of non-crc AGFLs */
523         if (!xfs_sb_version_hascrc(&mp->m_sb))
524                 return;
525
526         if (!xfs_agfl_verify(bp)) {
527                 xfs_buf_ioerror(bp, -EFSCORRUPTED);
528                 xfs_verifier_error(bp);
529                 return;
530         }
531
532         if (bip)
533                 XFS_BUF_TO_AGFL(bp)->agfl_lsn = cpu_to_be64(bip->bli_item.li_lsn);
534
535         xfs_buf_update_cksum(bp, XFS_AGFL_CRC_OFF);
536 }
537
538 const struct xfs_buf_ops xfs_agfl_buf_ops = {
539         .name = "xfs_agfl",
540         .verify_read = xfs_agfl_read_verify,
541         .verify_write = xfs_agfl_write_verify,
542 };
543
544 /*
545  * Read in the allocation group free block array.
546  */
547 STATIC int                              /* error */
548 xfs_alloc_read_agfl(
549         xfs_mount_t     *mp,            /* mount point structure */
550         xfs_trans_t     *tp,            /* transaction pointer */
551         xfs_agnumber_t  agno,           /* allocation group number */
552         xfs_buf_t       **bpp)          /* buffer for the ag free block array */
553 {
554         xfs_buf_t       *bp;            /* return value */
555         int             error;
556
557         ASSERT(agno != NULLAGNUMBER);
558         error = xfs_trans_read_buf(
559                         mp, tp, mp->m_ddev_targp,
560                         XFS_AG_DADDR(mp, agno, XFS_AGFL_DADDR(mp)),
561                         XFS_FSS_TO_BB(mp, 1), 0, &bp, &xfs_agfl_buf_ops);
562         if (error)
563                 return error;
564         xfs_buf_set_ref(bp, XFS_AGFL_REF);
565         *bpp = bp;
566         return 0;
567 }
568
569 STATIC int
570 xfs_alloc_update_counters(
571         struct xfs_trans        *tp,
572         struct xfs_perag        *pag,
573         struct xfs_buf          *agbp,
574         long                    len)
575 {
576         struct xfs_agf          *agf = XFS_BUF_TO_AGF(agbp);
577
578         pag->pagf_freeblks += len;
579         be32_add_cpu(&agf->agf_freeblks, len);
580
581         xfs_trans_agblocks_delta(tp, len);
582         if (unlikely(be32_to_cpu(agf->agf_freeblks) >
583                      be32_to_cpu(agf->agf_length)))
584                 return -EFSCORRUPTED;
585
586         xfs_alloc_log_agf(tp, agbp, XFS_AGF_FREEBLKS);
587         return 0;
588 }
589
590 /*
591  * Allocation group level functions.
592  */
593
594 /*
595  * Allocate a variable extent in the allocation group agno.
596  * Type and bno are used to determine where in the allocation group the
597  * extent will start.
598  * Extent's length (returned in *len) will be between minlen and maxlen,
599  * and of the form k * prod + mod unless there's nothing that large.
600  * Return the starting a.g. block, or NULLAGBLOCK if we can't do it.
601  */
602 STATIC int                      /* error */
603 xfs_alloc_ag_vextent(
604         xfs_alloc_arg_t *args)  /* argument structure for allocation */
605 {
606         int             error=0;
607
608         ASSERT(args->minlen > 0);
609         ASSERT(args->maxlen > 0);
610         ASSERT(args->minlen <= args->maxlen);
611         ASSERT(args->mod < args->prod);
612         ASSERT(args->alignment > 0);
613         /*
614          * Branch to correct routine based on the type.
615          */
616         args->wasfromfl = 0;
617         switch (args->type) {
618         case XFS_ALLOCTYPE_THIS_AG:
619                 error = xfs_alloc_ag_vextent_size(args);
620                 break;
621         case XFS_ALLOCTYPE_NEAR_BNO:
622                 error = xfs_alloc_ag_vextent_near(args);
623                 break;
624         case XFS_ALLOCTYPE_THIS_BNO:
625                 error = xfs_alloc_ag_vextent_exact(args);
626                 break;
627         default:
628                 ASSERT(0);
629                 /* NOTREACHED */
630         }
631
632         if (error || args->agbno == NULLAGBLOCK)
633                 return error;
634
635         ASSERT(args->len >= args->minlen);
636         ASSERT(args->len <= args->maxlen);
637         ASSERT(!args->wasfromfl || !args->isfl);
638         ASSERT(args->agbno % args->alignment == 0);
639
640         if (!args->wasfromfl) {
641                 error = xfs_alloc_update_counters(args->tp, args->pag,
642                                                   args->agbp,
643                                                   -((long)(args->len)));
644                 if (error)
645                         return error;
646
647                 ASSERT(!xfs_extent_busy_search(args->mp, args->agno,
648                                               args->agbno, args->len));
649         }
650
651         if (!args->isfl) {
652                 xfs_trans_mod_sb(args->tp, args->wasdel ?
653                                  XFS_TRANS_SB_RES_FDBLOCKS :
654                                  XFS_TRANS_SB_FDBLOCKS,
655                                  -((long)(args->len)));
656         }
657
658         XFS_STATS_INC(args->mp, xs_allocx);
659         XFS_STATS_ADD(args->mp, xs_allocb, args->len);
660         return error;
661 }
662
663 /*
664  * Allocate a variable extent at exactly agno/bno.
665  * Extent's length (returned in *len) will be between minlen and maxlen,
666  * and of the form k * prod + mod unless there's nothing that large.
667  * Return the starting a.g. block (bno), or NULLAGBLOCK if we can't do it.
668  */
669 STATIC int                      /* error */
670 xfs_alloc_ag_vextent_exact(
671         xfs_alloc_arg_t *args)  /* allocation argument structure */
672 {
673         xfs_btree_cur_t *bno_cur;/* by block-number btree cursor */
674         xfs_btree_cur_t *cnt_cur;/* by count btree cursor */
675         int             error;
676         xfs_agblock_t   fbno;   /* start block of found extent */
677         xfs_extlen_t    flen;   /* length of found extent */
678         xfs_agblock_t   tbno;   /* start block of trimmed extent */
679         xfs_extlen_t    tlen;   /* length of trimmed extent */
680         xfs_agblock_t   tend;   /* end block of trimmed extent */
681         int             i;      /* success/failure of operation */
682
683         ASSERT(args->alignment == 1);
684
685         /*
686          * Allocate/initialize a cursor for the by-number freespace btree.
687          */
688         bno_cur = xfs_allocbt_init_cursor(args->mp, args->tp, args->agbp,
689                                           args->agno, XFS_BTNUM_BNO);
690
691         /*
692          * Lookup bno and minlen in the btree (minlen is irrelevant, really).
693          * Look for the closest free block <= bno, it must contain bno
694          * if any free block does.
695          */
696         error = xfs_alloc_lookup_le(bno_cur, args->agbno, args->minlen, &i);
697         if (error)
698                 goto error0;
699         if (!i)
700                 goto not_found;
701
702         /*
703          * Grab the freespace record.
704          */
705         error = xfs_alloc_get_rec(bno_cur, &fbno, &flen, &i);
706         if (error)
707                 goto error0;
708         XFS_WANT_CORRUPTED_GOTO(args->mp, i == 1, error0);
709         ASSERT(fbno <= args->agbno);
710
711         /*
712          * Check for overlapping busy extents.
713          */
714         xfs_extent_busy_trim(args, fbno, flen, &tbno, &tlen);
715
716         /*
717          * Give up if the start of the extent is busy, or the freespace isn't
718          * long enough for the minimum request.
719          */
720         if (tbno > args->agbno)
721                 goto not_found;
722         if (tlen < args->minlen)
723                 goto not_found;
724         tend = tbno + tlen;
725         if (tend < args->agbno + args->minlen)
726                 goto not_found;
727
728         /*
729          * End of extent will be smaller of the freespace end and the
730          * maximal requested end.
731          *
732          * Fix the length according to mod and prod if given.
733          */
734         args->len = XFS_AGBLOCK_MIN(tend, args->agbno + args->maxlen)
735                                                 - args->agbno;
736         xfs_alloc_fix_len(args);
737         if (!xfs_alloc_fix_minleft(args))
738                 goto not_found;
739
740         ASSERT(args->agbno + args->len <= tend);
741
742         /*
743          * We are allocating agbno for args->len
744          * Allocate/initialize a cursor for the by-size btree.
745          */
746         cnt_cur = xfs_allocbt_init_cursor(args->mp, args->tp, args->agbp,
747                 args->agno, XFS_BTNUM_CNT);
748         ASSERT(args->agbno + args->len <=
749                 be32_to_cpu(XFS_BUF_TO_AGF(args->agbp)->agf_length));
750         error = xfs_alloc_fixup_trees(cnt_cur, bno_cur, fbno, flen, args->agbno,
751                                       args->len, XFSA_FIXUP_BNO_OK);
752         if (error) {
753                 xfs_btree_del_cursor(cnt_cur, XFS_BTREE_ERROR);
754                 goto error0;
755         }
756
757         xfs_btree_del_cursor(bno_cur, XFS_BTREE_NOERROR);
758         xfs_btree_del_cursor(cnt_cur, XFS_BTREE_NOERROR);
759
760         args->wasfromfl = 0;
761         trace_xfs_alloc_exact_done(args);
762         return 0;
763
764 not_found:
765         /* Didn't find it, return null. */
766         xfs_btree_del_cursor(bno_cur, XFS_BTREE_NOERROR);
767         args->agbno = NULLAGBLOCK;
768         trace_xfs_alloc_exact_notfound(args);
769         return 0;
770
771 error0:
772         xfs_btree_del_cursor(bno_cur, XFS_BTREE_ERROR);
773         trace_xfs_alloc_exact_error(args);
774         return error;
775 }
776
777 /*
778  * Search the btree in a given direction via the search cursor and compare
779  * the records found against the good extent we've already found.
780  */
781 STATIC int
782 xfs_alloc_find_best_extent(
783         struct xfs_alloc_arg    *args,  /* allocation argument structure */
784         struct xfs_btree_cur    **gcur, /* good cursor */
785         struct xfs_btree_cur    **scur, /* searching cursor */
786         xfs_agblock_t           gdiff,  /* difference for search comparison */
787         xfs_agblock_t           *sbno,  /* extent found by search */
788         xfs_extlen_t            *slen,  /* extent length */
789         xfs_agblock_t           *sbnoa, /* aligned extent found by search */
790         xfs_extlen_t            *slena, /* aligned extent length */
791         int                     dir)    /* 0 = search right, 1 = search left */
792 {
793         xfs_agblock_t           new;
794         xfs_agblock_t           sdiff;
795         int                     error;
796         int                     i;
797
798         /* The good extent is perfect, no need to  search. */
799         if (!gdiff)
800                 goto out_use_good;
801
802         /*
803          * Look until we find a better one, run out of space or run off the end.
804          */
805         do {
806                 error = xfs_alloc_get_rec(*scur, sbno, slen, &i);
807                 if (error)
808                         goto error0;
809                 XFS_WANT_CORRUPTED_GOTO(args->mp, i == 1, error0);
810                 xfs_alloc_compute_aligned(args, *sbno, *slen, sbnoa, slena);
811
812                 /*
813                  * The good extent is closer than this one.
814                  */
815                 if (!dir) {
816                         if (*sbnoa > args->max_agbno)
817                                 goto out_use_good;
818                         if (*sbnoa >= args->agbno + gdiff)
819                                 goto out_use_good;
820                 } else {
821                         if (*sbnoa < args->min_agbno)
822                                 goto out_use_good;
823                         if (*sbnoa <= args->agbno - gdiff)
824                                 goto out_use_good;
825                 }
826
827                 /*
828                  * Same distance, compare length and pick the best.
829                  */
830                 if (*slena >= args->minlen) {
831                         args->len = XFS_EXTLEN_MIN(*slena, args->maxlen);
832                         xfs_alloc_fix_len(args);
833
834                         sdiff = xfs_alloc_compute_diff(args->agbno, args->len,
835                                                        args->alignment,
836                                                        args->userdata, *sbnoa,
837                                                        *slena, &new);
838
839                         /*
840                          * Choose closer size and invalidate other cursor.
841                          */
842                         if (sdiff < gdiff)
843                                 goto out_use_search;
844                         goto out_use_good;
845                 }
846
847                 if (!dir)
848                         error = xfs_btree_increment(*scur, 0, &i);
849                 else
850                         error = xfs_btree_decrement(*scur, 0, &i);
851                 if (error)
852                         goto error0;
853         } while (i);
854
855 out_use_good:
856         xfs_btree_del_cursor(*scur, XFS_BTREE_NOERROR);
857         *scur = NULL;
858         return 0;
859
860 out_use_search:
861         xfs_btree_del_cursor(*gcur, XFS_BTREE_NOERROR);
862         *gcur = NULL;
863         return 0;
864
865 error0:
866         /* caller invalidates cursors */
867         return error;
868 }
869
870 /*
871  * Allocate a variable extent near bno in the allocation group agno.
872  * Extent's length (returned in len) will be between minlen and maxlen,
873  * and of the form k * prod + mod unless there's nothing that large.
874  * Return the starting a.g. block, or NULLAGBLOCK if we can't do it.
875  */
876 STATIC int                              /* error */
877 xfs_alloc_ag_vextent_near(
878         xfs_alloc_arg_t *args)          /* allocation argument structure */
879 {
880         xfs_btree_cur_t *bno_cur_gt;    /* cursor for bno btree, right side */
881         xfs_btree_cur_t *bno_cur_lt;    /* cursor for bno btree, left side */
882         xfs_btree_cur_t *cnt_cur;       /* cursor for count btree */
883         xfs_agblock_t   gtbno;          /* start bno of right side entry */
884         xfs_agblock_t   gtbnoa;         /* aligned ... */
885         xfs_extlen_t    gtdiff;         /* difference to right side entry */
886         xfs_extlen_t    gtlen;          /* length of right side entry */
887         xfs_extlen_t    gtlena;         /* aligned ... */
888         xfs_agblock_t   gtnew;          /* useful start bno of right side */
889         int             error;          /* error code */
890         int             i;              /* result code, temporary */
891         int             j;              /* result code, temporary */
892         xfs_agblock_t   ltbno;          /* start bno of left side entry */
893         xfs_agblock_t   ltbnoa;         /* aligned ... */
894         xfs_extlen_t    ltdiff;         /* difference to left side entry */
895         xfs_extlen_t    ltlen;          /* length of left side entry */
896         xfs_extlen_t    ltlena;         /* aligned ... */
897         xfs_agblock_t   ltnew;          /* useful start bno of left side */
898         xfs_extlen_t    rlen;           /* length of returned extent */
899         int             forced = 0;
900 #ifdef DEBUG
901         /*
902          * Randomly don't execute the first algorithm.
903          */
904         int             dofirst;        /* set to do first algorithm */
905
906         dofirst = prandom_u32() & 1;
907 #endif
908
909         /* handle unitialized agbno range so caller doesn't have to */
910         if (!args->min_agbno && !args->max_agbno)
911                 args->max_agbno = args->mp->m_sb.sb_agblocks - 1;
912         ASSERT(args->min_agbno <= args->max_agbno);
913
914         /* clamp agbno to the range if it's outside */
915         if (args->agbno < args->min_agbno)
916                 args->agbno = args->min_agbno;
917         if (args->agbno > args->max_agbno)
918                 args->agbno = args->max_agbno;
919
920 restart:
921         bno_cur_lt = NULL;
922         bno_cur_gt = NULL;
923         ltlen = 0;
924         gtlena = 0;
925         ltlena = 0;
926
927         /*
928          * Get a cursor for the by-size btree.
929          */
930         cnt_cur = xfs_allocbt_init_cursor(args->mp, args->tp, args->agbp,
931                 args->agno, XFS_BTNUM_CNT);
932
933         /*
934          * See if there are any free extents as big as maxlen.
935          */
936         if ((error = xfs_alloc_lookup_ge(cnt_cur, 0, args->maxlen, &i)))
937                 goto error0;
938         /*
939          * If none, then pick up the last entry in the tree unless the
940          * tree is empty.
941          */
942         if (!i) {
943                 if ((error = xfs_alloc_ag_vextent_small(args, cnt_cur, &ltbno,
944                                 &ltlen, &i)))
945                         goto error0;
946                 if (i == 0 || ltlen == 0) {
947                         xfs_btree_del_cursor(cnt_cur, XFS_BTREE_NOERROR);
948                         trace_xfs_alloc_near_noentry(args);
949                         return 0;
950                 }
951                 ASSERT(i == 1);
952         }
953         args->wasfromfl = 0;
954
955         /*
956          * First algorithm.
957          * If the requested extent is large wrt the freespaces available
958          * in this a.g., then the cursor will be pointing to a btree entry
959          * near the right edge of the tree.  If it's in the last btree leaf
960          * block, then we just examine all the entries in that block
961          * that are big enough, and pick the best one.
962          * This is written as a while loop so we can break out of it,
963          * but we never loop back to the top.
964          */
965         while (xfs_btree_islastblock(cnt_cur, 0)) {
966                 xfs_extlen_t    bdiff;
967                 int             besti=0;
968                 xfs_extlen_t    blen=0;
969                 xfs_agblock_t   bnew=0;
970
971 #ifdef DEBUG
972                 if (dofirst)
973                         break;
974 #endif
975                 /*
976                  * Start from the entry that lookup found, sequence through
977                  * all larger free blocks.  If we're actually pointing at a
978                  * record smaller than maxlen, go to the start of this block,
979                  * and skip all those smaller than minlen.
980                  */
981                 if (ltlen || args->alignment > 1) {
982                         cnt_cur->bc_ptrs[0] = 1;
983                         do {
984                                 if ((error = xfs_alloc_get_rec(cnt_cur, &ltbno,
985                                                 &ltlen, &i)))
986                                         goto error0;
987                                 XFS_WANT_CORRUPTED_GOTO(args->mp, i == 1, error0);
988                                 if (ltlen >= args->minlen)
989                                         break;
990                                 if ((error = xfs_btree_increment(cnt_cur, 0, &i)))
991                                         goto error0;
992                         } while (i);
993                         ASSERT(ltlen >= args->minlen);
994                         if (!i)
995                                 break;
996                 }
997                 i = cnt_cur->bc_ptrs[0];
998                 for (j = 1, blen = 0, bdiff = 0;
999                      !error && j && (blen < args->maxlen || bdiff > 0);
1000                      error = xfs_btree_increment(cnt_cur, 0, &j)) {
1001                         /*
1002                          * For each entry, decide if it's better than
1003                          * the previous best entry.
1004                          */
1005                         if ((error = xfs_alloc_get_rec(cnt_cur, &ltbno, &ltlen, &i)))
1006                                 goto error0;
1007                         XFS_WANT_CORRUPTED_GOTO(args->mp, i == 1, error0);
1008                         xfs_alloc_compute_aligned(args, ltbno, ltlen,
1009                                                   &ltbnoa, &ltlena);
1010                         if (ltlena < args->minlen)
1011                                 continue;
1012                         if (ltbnoa < args->min_agbno || ltbnoa > args->max_agbno)
1013                                 continue;
1014                         args->len = XFS_EXTLEN_MIN(ltlena, args->maxlen);
1015                         xfs_alloc_fix_len(args);
1016                         ASSERT(args->len >= args->minlen);
1017                         if (args->len < blen)
1018                                 continue;
1019                         ltdiff = xfs_alloc_compute_diff(args->agbno, args->len,
1020                                 args->alignment, args->userdata, ltbnoa,
1021                                 ltlena, &ltnew);
1022                         if (ltnew != NULLAGBLOCK &&
1023                             (args->len > blen || ltdiff < bdiff)) {
1024                                 bdiff = ltdiff;
1025                                 bnew = ltnew;
1026                                 blen = args->len;
1027                                 besti = cnt_cur->bc_ptrs[0];
1028                         }
1029                 }
1030                 /*
1031                  * It didn't work.  We COULD be in a case where
1032                  * there's a good record somewhere, so try again.
1033                  */
1034                 if (blen == 0)
1035                         break;
1036                 /*
1037                  * Point at the best entry, and retrieve it again.
1038                  */
1039                 cnt_cur->bc_ptrs[0] = besti;
1040                 if ((error = xfs_alloc_get_rec(cnt_cur, &ltbno, &ltlen, &i)))
1041                         goto error0;
1042                 XFS_WANT_CORRUPTED_GOTO(args->mp, i == 1, error0);
1043                 ASSERT(ltbno + ltlen <= be32_to_cpu(XFS_BUF_TO_AGF(args->agbp)->agf_length));
1044                 args->len = blen;
1045                 if (!xfs_alloc_fix_minleft(args)) {
1046                         xfs_btree_del_cursor(cnt_cur, XFS_BTREE_NOERROR);
1047                         trace_xfs_alloc_near_nominleft(args);
1048                         return 0;
1049                 }
1050                 blen = args->len;
1051                 /*
1052                  * We are allocating starting at bnew for blen blocks.
1053                  */
1054                 args->agbno = bnew;
1055                 ASSERT(bnew >= ltbno);
1056                 ASSERT(bnew + blen <= ltbno + ltlen);
1057                 /*
1058                  * Set up a cursor for the by-bno tree.
1059                  */
1060                 bno_cur_lt = xfs_allocbt_init_cursor(args->mp, args->tp,
1061                         args->agbp, args->agno, XFS_BTNUM_BNO);
1062                 /*
1063                  * Fix up the btree entries.
1064                  */
1065                 if ((error = xfs_alloc_fixup_trees(cnt_cur, bno_cur_lt, ltbno,
1066                                 ltlen, bnew, blen, XFSA_FIXUP_CNT_OK)))
1067                         goto error0;
1068                 xfs_btree_del_cursor(cnt_cur, XFS_BTREE_NOERROR);
1069                 xfs_btree_del_cursor(bno_cur_lt, XFS_BTREE_NOERROR);
1070
1071                 trace_xfs_alloc_near_first(args);
1072                 return 0;
1073         }
1074         /*
1075          * Second algorithm.
1076          * Search in the by-bno tree to the left and to the right
1077          * simultaneously, until in each case we find a space big enough,
1078          * or run into the edge of the tree.  When we run into the edge,
1079          * we deallocate that cursor.
1080          * If both searches succeed, we compare the two spaces and pick
1081          * the better one.
1082          * With alignment, it's possible for both to fail; the upper
1083          * level algorithm that picks allocation groups for allocations
1084          * is not supposed to do this.
1085          */
1086         /*
1087          * Allocate and initialize the cursor for the leftward search.
1088          */
1089         bno_cur_lt = xfs_allocbt_init_cursor(args->mp, args->tp, args->agbp,
1090                 args->agno, XFS_BTNUM_BNO);
1091         /*
1092          * Lookup <= bno to find the leftward search's starting point.
1093          */
1094         if ((error = xfs_alloc_lookup_le(bno_cur_lt, args->agbno, args->maxlen, &i)))
1095                 goto error0;
1096         if (!i) {
1097                 /*
1098                  * Didn't find anything; use this cursor for the rightward
1099                  * search.
1100                  */
1101                 bno_cur_gt = bno_cur_lt;
1102                 bno_cur_lt = NULL;
1103         }
1104         /*
1105          * Found something.  Duplicate the cursor for the rightward search.
1106          */
1107         else if ((error = xfs_btree_dup_cursor(bno_cur_lt, &bno_cur_gt)))
1108                 goto error0;
1109         /*
1110          * Increment the cursor, so we will point at the entry just right
1111          * of the leftward entry if any, or to the leftmost entry.
1112          */
1113         if ((error = xfs_btree_increment(bno_cur_gt, 0, &i)))
1114                 goto error0;
1115         if (!i) {
1116                 /*
1117                  * It failed, there are no rightward entries.
1118                  */
1119                 xfs_btree_del_cursor(bno_cur_gt, XFS_BTREE_NOERROR);
1120                 bno_cur_gt = NULL;
1121         }
1122         /*
1123          * Loop going left with the leftward cursor, right with the
1124          * rightward cursor, until either both directions give up or
1125          * we find an entry at least as big as minlen.
1126          */
1127         do {
1128                 if (bno_cur_lt) {
1129                         if ((error = xfs_alloc_get_rec(bno_cur_lt, &ltbno, &ltlen, &i)))
1130                                 goto error0;
1131                         XFS_WANT_CORRUPTED_GOTO(args->mp, i == 1, error0);
1132                         xfs_alloc_compute_aligned(args, ltbno, ltlen,
1133                                                   &ltbnoa, &ltlena);
1134                         if (ltlena >= args->minlen && ltbnoa >= args->min_agbno)
1135                                 break;
1136                         if ((error = xfs_btree_decrement(bno_cur_lt, 0, &i)))
1137                                 goto error0;
1138                         if (!i || ltbnoa < args->min_agbno) {
1139                                 xfs_btree_del_cursor(bno_cur_lt,
1140                                                      XFS_BTREE_NOERROR);
1141                                 bno_cur_lt = NULL;
1142                         }
1143                 }
1144                 if (bno_cur_gt) {
1145                         if ((error = xfs_alloc_get_rec(bno_cur_gt, &gtbno, &gtlen, &i)))
1146                                 goto error0;
1147                         XFS_WANT_CORRUPTED_GOTO(args->mp, i == 1, error0);
1148                         xfs_alloc_compute_aligned(args, gtbno, gtlen,
1149                                                   &gtbnoa, &gtlena);
1150                         if (gtlena >= args->minlen && gtbnoa <= args->max_agbno)
1151                                 break;
1152                         if ((error = xfs_btree_increment(bno_cur_gt, 0, &i)))
1153                                 goto error0;
1154                         if (!i || gtbnoa > args->max_agbno) {
1155                                 xfs_btree_del_cursor(bno_cur_gt,
1156                                                      XFS_BTREE_NOERROR);
1157                                 bno_cur_gt = NULL;
1158                         }
1159                 }
1160         } while (bno_cur_lt || bno_cur_gt);
1161
1162         /*
1163          * Got both cursors still active, need to find better entry.
1164          */
1165         if (bno_cur_lt && bno_cur_gt) {
1166                 if (ltlena >= args->minlen) {
1167                         /*
1168                          * Left side is good, look for a right side entry.
1169                          */
1170                         args->len = XFS_EXTLEN_MIN(ltlena, args->maxlen);
1171                         xfs_alloc_fix_len(args);
1172                         ltdiff = xfs_alloc_compute_diff(args->agbno, args->len,
1173                                 args->alignment, args->userdata, ltbnoa,
1174                                 ltlena, &ltnew);
1175
1176                         error = xfs_alloc_find_best_extent(args,
1177                                                 &bno_cur_lt, &bno_cur_gt,
1178                                                 ltdiff, &gtbno, &gtlen,
1179                                                 &gtbnoa, &gtlena,
1180                                                 0 /* search right */);
1181                 } else {
1182                         ASSERT(gtlena >= args->minlen);
1183
1184                         /*
1185                          * Right side is good, look for a left side entry.
1186                          */
1187                         args->len = XFS_EXTLEN_MIN(gtlena, args->maxlen);
1188                         xfs_alloc_fix_len(args);
1189                         gtdiff = xfs_alloc_compute_diff(args->agbno, args->len,
1190                                 args->alignment, args->userdata, gtbnoa,
1191                                 gtlena, &gtnew);
1192
1193                         error = xfs_alloc_find_best_extent(args,
1194                                                 &bno_cur_gt, &bno_cur_lt,
1195                                                 gtdiff, &ltbno, &ltlen,
1196                                                 &ltbnoa, &ltlena,
1197                                                 1 /* search left */);
1198                 }
1199
1200                 if (error)
1201                         goto error0;
1202         }
1203
1204         /*
1205          * If we couldn't get anything, give up.
1206          */
1207         if (bno_cur_lt == NULL && bno_cur_gt == NULL) {
1208                 xfs_btree_del_cursor(cnt_cur, XFS_BTREE_NOERROR);
1209
1210                 if (!forced++) {
1211                         trace_xfs_alloc_near_busy(args);
1212                         xfs_log_force(args->mp, XFS_LOG_SYNC);
1213                         goto restart;
1214                 }
1215                 trace_xfs_alloc_size_neither(args);
1216                 args->agbno = NULLAGBLOCK;
1217                 return 0;
1218         }
1219
1220         /*
1221          * At this point we have selected a freespace entry, either to the
1222          * left or to the right.  If it's on the right, copy all the
1223          * useful variables to the "left" set so we only have one
1224          * copy of this code.
1225          */
1226         if (bno_cur_gt) {
1227                 bno_cur_lt = bno_cur_gt;
1228                 bno_cur_gt = NULL;
1229                 ltbno = gtbno;
1230                 ltbnoa = gtbnoa;
1231                 ltlen = gtlen;
1232                 ltlena = gtlena;
1233                 j = 1;
1234         } else
1235                 j = 0;
1236
1237         /*
1238          * Fix up the length and compute the useful address.
1239          */
1240         args->len = XFS_EXTLEN_MIN(ltlena, args->maxlen);
1241         xfs_alloc_fix_len(args);
1242         if (!xfs_alloc_fix_minleft(args)) {
1243                 trace_xfs_alloc_near_nominleft(args);
1244                 xfs_btree_del_cursor(bno_cur_lt, XFS_BTREE_NOERROR);
1245                 xfs_btree_del_cursor(cnt_cur, XFS_BTREE_NOERROR);
1246                 return 0;
1247         }
1248         rlen = args->len;
1249         (void)xfs_alloc_compute_diff(args->agbno, rlen, args->alignment,
1250                                      args->userdata, ltbnoa, ltlena, &ltnew);
1251         ASSERT(ltnew >= ltbno);
1252         ASSERT(ltnew + rlen <= ltbnoa + ltlena);
1253         ASSERT(ltnew + rlen <= be32_to_cpu(XFS_BUF_TO_AGF(args->agbp)->agf_length));
1254         ASSERT(ltnew >= args->min_agbno && ltnew <= args->max_agbno);
1255         args->agbno = ltnew;
1256
1257         if ((error = xfs_alloc_fixup_trees(cnt_cur, bno_cur_lt, ltbno, ltlen,
1258                         ltnew, rlen, XFSA_FIXUP_BNO_OK)))
1259                 goto error0;
1260
1261         if (j)
1262                 trace_xfs_alloc_near_greater(args);
1263         else
1264                 trace_xfs_alloc_near_lesser(args);
1265
1266         xfs_btree_del_cursor(cnt_cur, XFS_BTREE_NOERROR);
1267         xfs_btree_del_cursor(bno_cur_lt, XFS_BTREE_NOERROR);
1268         return 0;
1269
1270  error0:
1271         trace_xfs_alloc_near_error(args);
1272         if (cnt_cur != NULL)
1273                 xfs_btree_del_cursor(cnt_cur, XFS_BTREE_ERROR);
1274         if (bno_cur_lt != NULL)
1275                 xfs_btree_del_cursor(bno_cur_lt, XFS_BTREE_ERROR);
1276         if (bno_cur_gt != NULL)
1277                 xfs_btree_del_cursor(bno_cur_gt, XFS_BTREE_ERROR);
1278         return error;
1279 }
1280
1281 /*
1282  * Allocate a variable extent anywhere in the allocation group agno.
1283  * Extent's length (returned in len) will be between minlen and maxlen,
1284  * and of the form k * prod + mod unless there's nothing that large.
1285  * Return the starting a.g. block, or NULLAGBLOCK if we can't do it.
1286  */
1287 STATIC int                              /* error */
1288 xfs_alloc_ag_vextent_size(
1289         xfs_alloc_arg_t *args)          /* allocation argument structure */
1290 {
1291         xfs_btree_cur_t *bno_cur;       /* cursor for bno btree */
1292         xfs_btree_cur_t *cnt_cur;       /* cursor for cnt btree */
1293         int             error;          /* error result */
1294         xfs_agblock_t   fbno;           /* start of found freespace */
1295         xfs_extlen_t    flen;           /* length of found freespace */
1296         int             i;              /* temp status variable */
1297         xfs_agblock_t   rbno;           /* returned block number */
1298         xfs_extlen_t    rlen;           /* length of returned extent */
1299         int             forced = 0;
1300
1301 restart:
1302         /*
1303          * Allocate and initialize a cursor for the by-size btree.
1304          */
1305         cnt_cur = xfs_allocbt_init_cursor(args->mp, args->tp, args->agbp,
1306                 args->agno, XFS_BTNUM_CNT);
1307         bno_cur = NULL;
1308
1309         /*
1310          * Look for an entry >= maxlen+alignment-1 blocks.
1311          */
1312         if ((error = xfs_alloc_lookup_ge(cnt_cur, 0,
1313                         args->maxlen + args->alignment - 1, &i)))
1314                 goto error0;
1315
1316         /*
1317          * If none or we have busy extents that we cannot allocate from, then
1318          * we have to settle for a smaller extent. In the case that there are
1319          * no large extents, this will return the last entry in the tree unless
1320          * the tree is empty. In the case that there are only busy large
1321          * extents, this will return the largest small extent unless there
1322          * are no smaller extents available.
1323          */
1324         if (!i || forced > 1) {
1325                 error = xfs_alloc_ag_vextent_small(args, cnt_cur,
1326                                                    &fbno, &flen, &i);
1327                 if (error)
1328                         goto error0;
1329                 if (i == 0 || flen == 0) {
1330                         xfs_btree_del_cursor(cnt_cur, XFS_BTREE_NOERROR);
1331                         trace_xfs_alloc_size_noentry(args);
1332                         return 0;
1333                 }
1334                 ASSERT(i == 1);
1335                 xfs_alloc_compute_aligned(args, fbno, flen, &rbno, &rlen);
1336         } else {
1337                 /*
1338                  * Search for a non-busy extent that is large enough.
1339                  * If we are at low space, don't check, or if we fall of
1340                  * the end of the btree, turn off the busy check and
1341                  * restart.
1342                  */
1343                 for (;;) {
1344                         error = xfs_alloc_get_rec(cnt_cur, &fbno, &flen, &i);
1345                         if (error)
1346                                 goto error0;
1347                         XFS_WANT_CORRUPTED_GOTO(args->mp, i == 1, error0);
1348
1349                         xfs_alloc_compute_aligned(args, fbno, flen,
1350                                                   &rbno, &rlen);
1351
1352                         if (rlen >= args->maxlen)
1353                                 break;
1354
1355                         error = xfs_btree_increment(cnt_cur, 0, &i);
1356                         if (error)
1357                                 goto error0;
1358                         if (i == 0) {
1359                                 /*
1360                                  * Our only valid extents must have been busy.
1361                                  * Make it unbusy by forcing the log out and
1362                                  * retrying. If we've been here before, forcing
1363                                  * the log isn't making the extents available,
1364                                  * which means they have probably been freed in
1365                                  * this transaction.  In that case, we have to
1366                                  * give up on them and we'll attempt a minlen
1367                                  * allocation the next time around.
1368                                  */
1369                                 xfs_btree_del_cursor(cnt_cur,
1370                                                      XFS_BTREE_NOERROR);
1371                                 trace_xfs_alloc_size_busy(args);
1372                                 if (!forced++)
1373                                         xfs_log_force(args->mp, XFS_LOG_SYNC);
1374                                 goto restart;
1375                         }
1376                 }
1377         }
1378
1379         /*
1380          * In the first case above, we got the last entry in the
1381          * by-size btree.  Now we check to see if the space hits maxlen
1382          * once aligned; if not, we search left for something better.
1383          * This can't happen in the second case above.
1384          */
1385         rlen = XFS_EXTLEN_MIN(args->maxlen, rlen);
1386         XFS_WANT_CORRUPTED_GOTO(args->mp, rlen == 0 ||
1387                         (rlen <= flen && rbno + rlen <= fbno + flen), error0);
1388         if (rlen < args->maxlen) {
1389                 xfs_agblock_t   bestfbno;
1390                 xfs_extlen_t    bestflen;
1391                 xfs_agblock_t   bestrbno;
1392                 xfs_extlen_t    bestrlen;
1393
1394                 bestrlen = rlen;
1395                 bestrbno = rbno;
1396                 bestflen = flen;
1397                 bestfbno = fbno;
1398                 for (;;) {
1399                         if ((error = xfs_btree_decrement(cnt_cur, 0, &i)))
1400                                 goto error0;
1401                         if (i == 0)
1402                                 break;
1403                         if ((error = xfs_alloc_get_rec(cnt_cur, &fbno, &flen,
1404                                         &i)))
1405                                 goto error0;
1406                         XFS_WANT_CORRUPTED_GOTO(args->mp, i == 1, error0);
1407                         if (flen < bestrlen)
1408                                 break;
1409                         xfs_alloc_compute_aligned(args, fbno, flen,
1410                                                   &rbno, &rlen);
1411                         rlen = XFS_EXTLEN_MIN(args->maxlen, rlen);
1412                         XFS_WANT_CORRUPTED_GOTO(args->mp, rlen == 0 ||
1413                                 (rlen <= flen && rbno + rlen <= fbno + flen),
1414                                 error0);
1415                         if (rlen > bestrlen) {
1416                                 bestrlen = rlen;
1417                                 bestrbno = rbno;
1418                                 bestflen = flen;
1419                                 bestfbno = fbno;
1420                                 if (rlen == args->maxlen)
1421                                         break;
1422                         }
1423                 }
1424                 if ((error = xfs_alloc_lookup_eq(cnt_cur, bestfbno, bestflen,
1425                                 &i)))
1426                         goto error0;
1427                 XFS_WANT_CORRUPTED_GOTO(args->mp, i == 1, error0);
1428                 rlen = bestrlen;
1429                 rbno = bestrbno;
1430                 flen = bestflen;
1431                 fbno = bestfbno;
1432         }
1433         args->wasfromfl = 0;
1434         /*
1435          * Fix up the length.
1436          */
1437         args->len = rlen;
1438         if (rlen < args->minlen) {
1439                 if (!forced++) {
1440                         xfs_btree_del_cursor(cnt_cur, XFS_BTREE_NOERROR);
1441                         trace_xfs_alloc_size_busy(args);
1442                         xfs_log_force(args->mp, XFS_LOG_SYNC);
1443                         goto restart;
1444                 }
1445                 goto out_nominleft;
1446         }
1447         xfs_alloc_fix_len(args);
1448
1449         if (!xfs_alloc_fix_minleft(args))
1450                 goto out_nominleft;
1451         rlen = args->len;
1452         XFS_WANT_CORRUPTED_GOTO(args->mp, rlen <= flen, error0);
1453         /*
1454          * Allocate and initialize a cursor for the by-block tree.
1455          */
1456         bno_cur = xfs_allocbt_init_cursor(args->mp, args->tp, args->agbp,
1457                 args->agno, XFS_BTNUM_BNO);
1458         if ((error = xfs_alloc_fixup_trees(cnt_cur, bno_cur, fbno, flen,
1459                         rbno, rlen, XFSA_FIXUP_CNT_OK)))
1460                 goto error0;
1461         xfs_btree_del_cursor(cnt_cur, XFS_BTREE_NOERROR);
1462         xfs_btree_del_cursor(bno_cur, XFS_BTREE_NOERROR);
1463         cnt_cur = bno_cur = NULL;
1464         args->len = rlen;
1465         args->agbno = rbno;
1466         XFS_WANT_CORRUPTED_GOTO(args->mp,
1467                 args->agbno + args->len <=
1468                         be32_to_cpu(XFS_BUF_TO_AGF(args->agbp)->agf_length),
1469                 error0);
1470         trace_xfs_alloc_size_done(args);
1471         return 0;
1472
1473 error0:
1474         trace_xfs_alloc_size_error(args);
1475         if (cnt_cur)
1476                 xfs_btree_del_cursor(cnt_cur, XFS_BTREE_ERROR);
1477         if (bno_cur)
1478                 xfs_btree_del_cursor(bno_cur, XFS_BTREE_ERROR);
1479         return error;
1480
1481 out_nominleft:
1482         xfs_btree_del_cursor(cnt_cur, XFS_BTREE_NOERROR);
1483         trace_xfs_alloc_size_nominleft(args);
1484         args->agbno = NULLAGBLOCK;
1485         return 0;
1486 }
1487
1488 /*
1489  * Deal with the case where only small freespaces remain.
1490  * Either return the contents of the last freespace record,
1491  * or allocate space from the freelist if there is nothing in the tree.
1492  */
1493 STATIC int                      /* error */
1494 xfs_alloc_ag_vextent_small(
1495         xfs_alloc_arg_t *args,  /* allocation argument structure */
1496         xfs_btree_cur_t *ccur,  /* by-size cursor */
1497         xfs_agblock_t   *fbnop, /* result block number */
1498         xfs_extlen_t    *flenp, /* result length */
1499         int             *stat)  /* status: 0-freelist, 1-normal/none */
1500 {
1501         int             error;
1502         xfs_agblock_t   fbno;
1503         xfs_extlen_t    flen;
1504         int             i;
1505
1506         if ((error = xfs_btree_decrement(ccur, 0, &i)))
1507                 goto error0;
1508         if (i) {
1509                 if ((error = xfs_alloc_get_rec(ccur, &fbno, &flen, &i)))
1510                         goto error0;
1511                 XFS_WANT_CORRUPTED_GOTO(args->mp, i == 1, error0);
1512         }
1513         /*
1514          * Nothing in the btree, try the freelist.  Make sure
1515          * to respect minleft even when pulling from the
1516          * freelist.
1517          */
1518         else if (args->minlen == 1 && args->alignment == 1 && !args->isfl &&
1519                  (be32_to_cpu(XFS_BUF_TO_AGF(args->agbp)->agf_flcount)
1520                   > args->minleft)) {
1521                 error = xfs_alloc_get_freelist(args->tp, args->agbp, &fbno, 0);
1522                 if (error)
1523                         goto error0;
1524                 if (fbno != NULLAGBLOCK) {
1525                         xfs_extent_busy_reuse(args->mp, args->agno, fbno, 1,
1526                                              args->userdata);
1527
1528                         if (args->userdata) {
1529                                 xfs_buf_t       *bp;
1530
1531                                 bp = xfs_btree_get_bufs(args->mp, args->tp,
1532                                         args->agno, fbno, 0);
1533                                 xfs_trans_binval(args->tp, bp);
1534                         }
1535                         args->len = 1;
1536                         args->agbno = fbno;
1537                         XFS_WANT_CORRUPTED_GOTO(args->mp,
1538                                 args->agbno + args->len <=
1539                                 be32_to_cpu(XFS_BUF_TO_AGF(args->agbp)->agf_length),
1540                                 error0);
1541                         args->wasfromfl = 1;
1542                         trace_xfs_alloc_small_freelist(args);
1543                         *stat = 0;
1544                         return 0;
1545                 }
1546                 /*
1547                  * Nothing in the freelist.
1548                  */
1549                 else
1550                         flen = 0;
1551         }
1552         /*
1553          * Can't allocate from the freelist for some reason.
1554          */
1555         else {
1556                 fbno = NULLAGBLOCK;
1557                 flen = 0;
1558         }
1559         /*
1560          * Can't do the allocation, give up.
1561          */
1562         if (flen < args->minlen) {
1563                 args->agbno = NULLAGBLOCK;
1564                 trace_xfs_alloc_small_notenough(args);
1565                 flen = 0;
1566         }
1567         *fbnop = fbno;
1568         *flenp = flen;
1569         *stat = 1;
1570         trace_xfs_alloc_small_done(args);
1571         return 0;
1572
1573 error0:
1574         trace_xfs_alloc_small_error(args);
1575         return error;
1576 }
1577
1578 /*
1579  * Free the extent starting at agno/bno for length.
1580  */
1581 STATIC int                      /* error */
1582 xfs_free_ag_extent(
1583         xfs_trans_t     *tp,    /* transaction pointer */
1584         xfs_buf_t       *agbp,  /* buffer for a.g. freelist header */
1585         xfs_agnumber_t  agno,   /* allocation group number */
1586         xfs_agblock_t   bno,    /* starting block number */
1587         xfs_extlen_t    len,    /* length of extent */
1588         int             isfl)   /* set if is freelist blocks - no sb acctg */
1589 {
1590         xfs_btree_cur_t *bno_cur;       /* cursor for by-block btree */
1591         xfs_btree_cur_t *cnt_cur;       /* cursor for by-size btree */
1592         int             error;          /* error return value */
1593         xfs_agblock_t   gtbno;          /* start of right neighbor block */
1594         xfs_extlen_t    gtlen;          /* length of right neighbor block */
1595         int             haveleft;       /* have a left neighbor block */
1596         int             haveright;      /* have a right neighbor block */
1597         int             i;              /* temp, result code */
1598         xfs_agblock_t   ltbno;          /* start of left neighbor block */
1599         xfs_extlen_t    ltlen;          /* length of left neighbor block */
1600         xfs_mount_t     *mp;            /* mount point struct for filesystem */
1601         xfs_agblock_t   nbno;           /* new starting block of freespace */
1602         xfs_extlen_t    nlen;           /* new length of freespace */
1603         xfs_perag_t     *pag;           /* per allocation group data */
1604
1605         mp = tp->t_mountp;
1606         /*
1607          * Allocate and initialize a cursor for the by-block btree.
1608          */
1609         bno_cur = xfs_allocbt_init_cursor(mp, tp, agbp, agno, XFS_BTNUM_BNO);
1610         cnt_cur = NULL;
1611         /*
1612          * Look for a neighboring block on the left (lower block numbers)
1613          * that is contiguous with this space.
1614          */
1615         if ((error = xfs_alloc_lookup_le(bno_cur, bno, len, &haveleft)))
1616                 goto error0;
1617         if (haveleft) {
1618                 /*
1619                  * There is a block to our left.
1620                  */
1621                 if ((error = xfs_alloc_get_rec(bno_cur, &ltbno, &ltlen, &i)))
1622                         goto error0;
1623                 XFS_WANT_CORRUPTED_GOTO(mp, i == 1, error0);
1624                 /*
1625                  * It's not contiguous, though.
1626                  */
1627                 if (ltbno + ltlen < bno)
1628                         haveleft = 0;
1629                 else {
1630                         /*
1631                          * If this failure happens the request to free this
1632                          * space was invalid, it's (partly) already free.
1633                          * Very bad.
1634                          */
1635                         XFS_WANT_CORRUPTED_GOTO(mp,
1636                                                 ltbno + ltlen <= bno, error0);
1637                 }
1638         }
1639         /*
1640          * Look for a neighboring block on the right (higher block numbers)
1641          * that is contiguous with this space.
1642          */
1643         if ((error = xfs_btree_increment(bno_cur, 0, &haveright)))
1644                 goto error0;
1645         if (haveright) {
1646                 /*
1647                  * There is a block to our right.
1648                  */
1649                 if ((error = xfs_alloc_get_rec(bno_cur, &gtbno, &gtlen, &i)))
1650                         goto error0;
1651                 XFS_WANT_CORRUPTED_GOTO(mp, i == 1, error0);
1652                 /*
1653                  * It's not contiguous, though.
1654                  */
1655                 if (bno + len < gtbno)
1656                         haveright = 0;
1657                 else {
1658                         /*
1659                          * If this failure happens the request to free this
1660                          * space was invalid, it's (partly) already free.
1661                          * Very bad.
1662                          */
1663                         XFS_WANT_CORRUPTED_GOTO(mp, gtbno >= bno + len, error0);
1664                 }
1665         }
1666         /*
1667          * Now allocate and initialize a cursor for the by-size tree.
1668          */
1669         cnt_cur = xfs_allocbt_init_cursor(mp, tp, agbp, agno, XFS_BTNUM_CNT);
1670         /*
1671          * Have both left and right contiguous neighbors.
1672          * Merge all three into a single free block.
1673          */
1674         if (haveleft && haveright) {
1675                 /*
1676                  * Delete the old by-size entry on the left.
1677                  */
1678                 if ((error = xfs_alloc_lookup_eq(cnt_cur, ltbno, ltlen, &i)))
1679                         goto error0;
1680                 XFS_WANT_CORRUPTED_GOTO(mp, i == 1, error0);
1681                 if ((error = xfs_btree_delete(cnt_cur, &i)))
1682                         goto error0;
1683                 XFS_WANT_CORRUPTED_GOTO(mp, i == 1, error0);
1684                 /*
1685                  * Delete the old by-size entry on the right.
1686                  */
1687                 if ((error = xfs_alloc_lookup_eq(cnt_cur, gtbno, gtlen, &i)))
1688                         goto error0;
1689                 XFS_WANT_CORRUPTED_GOTO(mp, i == 1, error0);
1690                 if ((error = xfs_btree_delete(cnt_cur, &i)))
1691                         goto error0;
1692                 XFS_WANT_CORRUPTED_GOTO(mp, i == 1, error0);
1693                 /*
1694                  * Delete the old by-block entry for the right block.
1695                  */
1696                 if ((error = xfs_btree_delete(bno_cur, &i)))
1697                         goto error0;
1698                 XFS_WANT_CORRUPTED_GOTO(mp, i == 1, error0);
1699                 /*
1700                  * Move the by-block cursor back to the left neighbor.
1701                  */
1702                 if ((error = xfs_btree_decrement(bno_cur, 0, &i)))
1703                         goto error0;
1704                 XFS_WANT_CORRUPTED_GOTO(mp, i == 1, error0);
1705 #ifdef DEBUG
1706                 /*
1707                  * Check that this is the right record: delete didn't
1708                  * mangle the cursor.
1709                  */
1710                 {
1711                         xfs_agblock_t   xxbno;
1712                         xfs_extlen_t    xxlen;
1713
1714                         if ((error = xfs_alloc_get_rec(bno_cur, &xxbno, &xxlen,
1715                                         &i)))
1716                                 goto error0;
1717                         XFS_WANT_CORRUPTED_GOTO(mp,
1718                                 i == 1 && xxbno == ltbno && xxlen == ltlen,
1719                                 error0);
1720                 }
1721 #endif
1722                 /*
1723                  * Update remaining by-block entry to the new, joined block.
1724                  */
1725                 nbno = ltbno;
1726                 nlen = len + ltlen + gtlen;
1727                 if ((error = xfs_alloc_update(bno_cur, nbno, nlen)))
1728                         goto error0;
1729         }
1730         /*
1731          * Have only a left contiguous neighbor.
1732          * Merge it together with the new freespace.
1733          */
1734         else if (haveleft) {
1735                 /*
1736                  * Delete the old by-size entry on the left.
1737                  */
1738                 if ((error = xfs_alloc_lookup_eq(cnt_cur, ltbno, ltlen, &i)))
1739                         goto error0;
1740                 XFS_WANT_CORRUPTED_GOTO(mp, i == 1, error0);
1741                 if ((error = xfs_btree_delete(cnt_cur, &i)))
1742                         goto error0;
1743                 XFS_WANT_CORRUPTED_GOTO(mp, i == 1, error0);
1744                 /*
1745                  * Back up the by-block cursor to the left neighbor, and
1746                  * update its length.
1747                  */
1748                 if ((error = xfs_btree_decrement(bno_cur, 0, &i)))
1749                         goto error0;
1750                 XFS_WANT_CORRUPTED_GOTO(mp, i == 1, error0);
1751                 nbno = ltbno;
1752                 nlen = len + ltlen;
1753                 if ((error = xfs_alloc_update(bno_cur, nbno, nlen)))
1754                         goto error0;
1755         }
1756         /*
1757          * Have only a right contiguous neighbor.
1758          * Merge it together with the new freespace.
1759          */
1760         else if (haveright) {
1761                 /*
1762                  * Delete the old by-size entry on the right.
1763                  */
1764                 if ((error = xfs_alloc_lookup_eq(cnt_cur, gtbno, gtlen, &i)))
1765                         goto error0;
1766                 XFS_WANT_CORRUPTED_GOTO(mp, i == 1, error0);
1767                 if ((error = xfs_btree_delete(cnt_cur, &i)))
1768                         goto error0;
1769                 XFS_WANT_CORRUPTED_GOTO(mp, i == 1, error0);
1770                 /*
1771                  * Update the starting block and length of the right
1772                  * neighbor in the by-block tree.
1773                  */
1774                 nbno = bno;
1775                 nlen = len + gtlen;
1776                 if ((error = xfs_alloc_update(bno_cur, nbno, nlen)))
1777                         goto error0;
1778         }
1779         /*
1780          * No contiguous neighbors.
1781          * Insert the new freespace into the by-block tree.
1782          */
1783         else {
1784                 nbno = bno;
1785                 nlen = len;
1786                 if ((error = xfs_btree_insert(bno_cur, &i)))
1787                         goto error0;
1788                 XFS_WANT_CORRUPTED_GOTO(mp, i == 1, error0);
1789         }
1790         xfs_btree_del_cursor(bno_cur, XFS_BTREE_NOERROR);
1791         bno_cur = NULL;
1792         /*
1793          * In all cases we need to insert the new freespace in the by-size tree.
1794          */
1795         if ((error = xfs_alloc_lookup_eq(cnt_cur, nbno, nlen, &i)))
1796                 goto error0;
1797         XFS_WANT_CORRUPTED_GOTO(mp, i == 0, error0);
1798         if ((error = xfs_btree_insert(cnt_cur, &i)))
1799                 goto error0;
1800         XFS_WANT_CORRUPTED_GOTO(mp, i == 1, error0);
1801         xfs_btree_del_cursor(cnt_cur, XFS_BTREE_NOERROR);
1802         cnt_cur = NULL;
1803
1804         /*
1805          * Update the freespace totals in the ag and superblock.
1806          */
1807         pag = xfs_perag_get(mp, agno);
1808         error = xfs_alloc_update_counters(tp, pag, agbp, len);
1809         xfs_perag_put(pag);
1810         if (error)
1811                 goto error0;
1812
1813         if (!isfl)
1814                 xfs_trans_mod_sb(tp, XFS_TRANS_SB_FDBLOCKS, (long)len);
1815         XFS_STATS_INC(mp, xs_freex);
1816         XFS_STATS_ADD(mp, xs_freeb, len);
1817
1818         trace_xfs_free_extent(mp, agno, bno, len, isfl, haveleft, haveright);
1819
1820         return 0;
1821
1822  error0:
1823         trace_xfs_free_extent(mp, agno, bno, len, isfl, -1, -1);
1824         if (bno_cur)
1825                 xfs_btree_del_cursor(bno_cur, XFS_BTREE_ERROR);
1826         if (cnt_cur)
1827                 xfs_btree_del_cursor(cnt_cur, XFS_BTREE_ERROR);
1828         return error;
1829 }
1830
1831 /*
1832  * Visible (exported) allocation/free functions.
1833  * Some of these are used just by xfs_alloc_btree.c and this file.
1834  */
1835
1836 /*
1837  * Compute and fill in value of m_ag_maxlevels.
1838  */
1839 void
1840 xfs_alloc_compute_maxlevels(
1841         xfs_mount_t     *mp)    /* file system mount structure */
1842 {
1843         mp->m_ag_maxlevels = xfs_btree_compute_maxlevels(mp, mp->m_alloc_mnr,
1844                         (mp->m_sb.sb_agblocks + 1) / 2);
1845 }
1846
1847 /*
1848  * Find the length of the longest extent in an AG.
1849  */
1850 xfs_extlen_t
1851 xfs_alloc_longest_free_extent(
1852         struct xfs_mount        *mp,
1853         struct xfs_perag        *pag,
1854         xfs_extlen_t            need)
1855 {
1856         xfs_extlen_t            delta = 0;
1857
1858         if (need > pag->pagf_flcount)
1859                 delta = need - pag->pagf_flcount;
1860
1861         if (pag->pagf_longest > delta)
1862                 return pag->pagf_longest - delta;
1863         return pag->pagf_flcount > 0 || pag->pagf_longest > 0;
1864 }
1865
1866 unsigned int
1867 xfs_alloc_min_freelist(
1868         struct xfs_mount        *mp,
1869         struct xfs_perag        *pag)
1870 {
1871         unsigned int            min_free;
1872
1873         /* space needed by-bno freespace btree */
1874         min_free = min_t(unsigned int, pag->pagf_levels[XFS_BTNUM_BNOi] + 1,
1875                                        mp->m_ag_maxlevels);
1876         /* space needed by-size freespace btree */
1877         min_free += min_t(unsigned int, pag->pagf_levels[XFS_BTNUM_CNTi] + 1,
1878                                        mp->m_ag_maxlevels);
1879
1880         return min_free;
1881 }
1882
1883 /*
1884  * Check if the operation we are fixing up the freelist for should go ahead or
1885  * not. If we are freeing blocks, we always allow it, otherwise the allocation
1886  * is dependent on whether the size and shape of free space available will
1887  * permit the requested allocation to take place.
1888  */
1889 static bool
1890 xfs_alloc_space_available(
1891         struct xfs_alloc_arg    *args,
1892         xfs_extlen_t            min_free,
1893         int                     flags)
1894 {
1895         struct xfs_perag        *pag = args->pag;
1896         xfs_extlen_t            longest;
1897         int                     available;
1898
1899         if (flags & XFS_ALLOC_FLAG_FREEING)
1900                 return true;
1901
1902         /* do we have enough contiguous free space for the allocation? */
1903         longest = xfs_alloc_longest_free_extent(args->mp, pag, min_free);
1904         if ((args->minlen + args->alignment + args->minalignslop - 1) > longest)
1905                 return false;
1906
1907         /* do have enough free space remaining for the allocation? */
1908         available = (int)(pag->pagf_freeblks + pag->pagf_flcount -
1909                           min_free - args->total);
1910         if (available < (int)args->minleft)
1911                 return false;
1912
1913         return true;
1914 }
1915
1916 /*
1917  * Decide whether to use this allocation group for this allocation.
1918  * If so, fix up the btree freelist's size.
1919  */
1920 int                     /* error */
1921 xfs_alloc_fix_freelist(
1922         struct xfs_alloc_arg    *args,  /* allocation argument structure */
1923         int                     flags)  /* XFS_ALLOC_FLAG_... */
1924 {
1925         struct xfs_mount        *mp = args->mp;
1926         struct xfs_perag        *pag = args->pag;
1927         struct xfs_trans        *tp = args->tp;
1928         struct xfs_buf          *agbp = NULL;
1929         struct xfs_buf          *agflbp = NULL;
1930         struct xfs_alloc_arg    targs;  /* local allocation arguments */
1931         xfs_agblock_t           bno;    /* freelist block */
1932         xfs_extlen_t            need;   /* total blocks needed in freelist */
1933         int                     error = 0;
1934
1935         if (!pag->pagf_init) {
1936                 error = xfs_alloc_read_agf(mp, tp, args->agno, flags, &agbp);
1937                 if (error)
1938                         goto out_no_agbp;
1939                 if (!pag->pagf_init) {
1940                         ASSERT(flags & XFS_ALLOC_FLAG_TRYLOCK);
1941                         ASSERT(!(flags & XFS_ALLOC_FLAG_FREEING));
1942                         goto out_agbp_relse;
1943                 }
1944         }
1945
1946         /*
1947          * If this is a metadata preferred pag and we are user data then try
1948          * somewhere else if we are not being asked to try harder at this
1949          * point
1950          */
1951         if (pag->pagf_metadata && args->userdata &&
1952             (flags & XFS_ALLOC_FLAG_TRYLOCK)) {
1953                 ASSERT(!(flags & XFS_ALLOC_FLAG_FREEING));
1954                 goto out_agbp_relse;
1955         }
1956
1957         need = xfs_alloc_min_freelist(mp, pag);
1958         if (!xfs_alloc_space_available(args, need, flags))
1959                 goto out_agbp_relse;
1960
1961         /*
1962          * Get the a.g. freespace buffer.
1963          * Can fail if we're not blocking on locks, and it's held.
1964          */
1965         if (!agbp) {
1966                 error = xfs_alloc_read_agf(mp, tp, args->agno, flags, &agbp);
1967                 if (error)
1968                         goto out_no_agbp;
1969                 if (!agbp) {
1970                         ASSERT(flags & XFS_ALLOC_FLAG_TRYLOCK);
1971                         ASSERT(!(flags & XFS_ALLOC_FLAG_FREEING));
1972                         goto out_no_agbp;
1973                 }
1974         }
1975
1976         /* If there isn't enough total space or single-extent, reject it. */
1977         need = xfs_alloc_min_freelist(mp, pag);
1978         if (!xfs_alloc_space_available(args, need, flags))
1979                 goto out_agbp_relse;
1980
1981         /*
1982          * Make the freelist shorter if it's too long.
1983          *
1984          * Note that from this point onwards, we will always release the agf and
1985          * agfl buffers on error. This handles the case where we error out and
1986          * the buffers are clean or may not have been joined to the transaction
1987          * and hence need to be released manually. If they have been joined to
1988          * the transaction, then xfs_trans_brelse() will handle them
1989          * appropriately based on the recursion count and dirty state of the
1990          * buffer.
1991          *
1992          * XXX (dgc): When we have lots of free space, does this buy us
1993          * anything other than extra overhead when we need to put more blocks
1994          * back on the free list? Maybe we should only do this when space is
1995          * getting low or the AGFL is more than half full?
1996          */
1997         while (pag->pagf_flcount > need) {
1998                 struct xfs_buf  *bp;
1999
2000                 error = xfs_alloc_get_freelist(tp, agbp, &bno, 0);
2001                 if (error)
2002                         goto out_agbp_relse;
2003                 error = xfs_free_ag_extent(tp, agbp, args->agno, bno, 1, 1);
2004                 if (error)
2005                         goto out_agbp_relse;
2006                 bp = xfs_btree_get_bufs(mp, tp, args->agno, bno, 0);
2007                 xfs_trans_binval(tp, bp);
2008         }
2009
2010         memset(&targs, 0, sizeof(targs));
2011         targs.tp = tp;
2012         targs.mp = mp;
2013         targs.agbp = agbp;
2014         targs.agno = args->agno;
2015         targs.alignment = targs.minlen = targs.prod = targs.isfl = 1;
2016         targs.type = XFS_ALLOCTYPE_THIS_AG;
2017         targs.pag = pag;
2018         error = xfs_alloc_read_agfl(mp, tp, targs.agno, &agflbp);
2019         if (error)
2020                 goto out_agbp_relse;
2021
2022         /* Make the freelist longer if it's too short. */
2023         while (pag->pagf_flcount < need) {
2024                 targs.agbno = 0;
2025                 targs.maxlen = need - pag->pagf_flcount;
2026
2027                 /* Allocate as many blocks as possible at once. */
2028                 error = xfs_alloc_ag_vextent(&targs);
2029                 if (error)
2030                         goto out_agflbp_relse;
2031
2032                 /*
2033                  * Stop if we run out.  Won't happen if callers are obeying
2034                  * the restrictions correctly.  Can happen for free calls
2035                  * on a completely full ag.
2036                  */
2037                 if (targs.agbno == NULLAGBLOCK) {
2038                         if (flags & XFS_ALLOC_FLAG_FREEING)
2039                                 break;
2040                         goto out_agflbp_relse;
2041                 }
2042                 /*
2043                  * Put each allocated block on the list.
2044                  */
2045                 for (bno = targs.agbno; bno < targs.agbno + targs.len; bno++) {
2046                         error = xfs_alloc_put_freelist(tp, agbp,
2047                                                         agflbp, bno, 0);
2048                         if (error)
2049                                 goto out_agflbp_relse;
2050                 }
2051         }
2052         xfs_trans_brelse(tp, agflbp);
2053         args->agbp = agbp;
2054         return 0;
2055
2056 out_agflbp_relse:
2057         xfs_trans_brelse(tp, agflbp);
2058 out_agbp_relse:
2059         if (agbp)
2060                 xfs_trans_brelse(tp, agbp);
2061 out_no_agbp:
2062         args->agbp = NULL;
2063         return error;
2064 }
2065
2066 /*
2067  * Get a block from the freelist.
2068  * Returns with the buffer for the block gotten.
2069  */
2070 int                             /* error */
2071 xfs_alloc_get_freelist(
2072         xfs_trans_t     *tp,    /* transaction pointer */
2073         xfs_buf_t       *agbp,  /* buffer containing the agf structure */
2074         xfs_agblock_t   *bnop,  /* block address retrieved from freelist */
2075         int             btreeblk) /* destination is a AGF btree */
2076 {
2077         xfs_agf_t       *agf;   /* a.g. freespace structure */
2078         xfs_buf_t       *agflbp;/* buffer for a.g. freelist structure */
2079         xfs_agblock_t   bno;    /* block number returned */
2080         __be32          *agfl_bno;
2081         int             error;
2082         int             logflags;
2083         xfs_mount_t     *mp = tp->t_mountp;
2084         xfs_perag_t     *pag;   /* per allocation group data */
2085
2086         /*
2087          * Freelist is empty, give up.
2088          */
2089         agf = XFS_BUF_TO_AGF(agbp);
2090         if (!agf->agf_flcount) {
2091                 *bnop = NULLAGBLOCK;
2092                 return 0;
2093         }
2094         /*
2095          * Read the array of free blocks.
2096          */
2097         error = xfs_alloc_read_agfl(mp, tp, be32_to_cpu(agf->agf_seqno),
2098                                     &agflbp);
2099         if (error)
2100                 return error;
2101
2102
2103         /*
2104          * Get the block number and update the data structures.
2105          */
2106         agfl_bno = XFS_BUF_TO_AGFL_BNO(mp, agflbp);
2107         bno = be32_to_cpu(agfl_bno[be32_to_cpu(agf->agf_flfirst)]);
2108         be32_add_cpu(&agf->agf_flfirst, 1);
2109         xfs_trans_brelse(tp, agflbp);
2110         if (be32_to_cpu(agf->agf_flfirst) == XFS_AGFL_SIZE(mp))
2111                 agf->agf_flfirst = 0;
2112
2113         pag = xfs_perag_get(mp, be32_to_cpu(agf->agf_seqno));
2114         be32_add_cpu(&agf->agf_flcount, -1);
2115         xfs_trans_agflist_delta(tp, -1);
2116         pag->pagf_flcount--;
2117         xfs_perag_put(pag);
2118
2119         logflags = XFS_AGF_FLFIRST | XFS_AGF_FLCOUNT;
2120         if (btreeblk) {
2121                 be32_add_cpu(&agf->agf_btreeblks, 1);
2122                 pag->pagf_btreeblks++;
2123                 logflags |= XFS_AGF_BTREEBLKS;
2124         }
2125
2126         xfs_alloc_log_agf(tp, agbp, logflags);
2127         *bnop = bno;
2128
2129         return 0;
2130 }
2131
2132 /*
2133  * Log the given fields from the agf structure.
2134  */
2135 void
2136 xfs_alloc_log_agf(
2137         xfs_trans_t     *tp,    /* transaction pointer */
2138         xfs_buf_t       *bp,    /* buffer for a.g. freelist header */
2139         int             fields) /* mask of fields to be logged (XFS_AGF_...) */
2140 {
2141         int     first;          /* first byte offset */
2142         int     last;           /* last byte offset */
2143         static const short      offsets[] = {
2144                 offsetof(xfs_agf_t, agf_magicnum),
2145                 offsetof(xfs_agf_t, agf_versionnum),
2146                 offsetof(xfs_agf_t, agf_seqno),
2147                 offsetof(xfs_agf_t, agf_length),
2148                 offsetof(xfs_agf_t, agf_roots[0]),
2149                 offsetof(xfs_agf_t, agf_levels[0]),
2150                 offsetof(xfs_agf_t, agf_flfirst),
2151                 offsetof(xfs_agf_t, agf_fllast),
2152                 offsetof(xfs_agf_t, agf_flcount),
2153                 offsetof(xfs_agf_t, agf_freeblks),
2154                 offsetof(xfs_agf_t, agf_longest),
2155                 offsetof(xfs_agf_t, agf_btreeblks),
2156                 offsetof(xfs_agf_t, agf_uuid),
2157                 sizeof(xfs_agf_t)
2158         };
2159
2160         trace_xfs_agf(tp->t_mountp, XFS_BUF_TO_AGF(bp), fields, _RET_IP_);
2161
2162         xfs_trans_buf_set_type(tp, bp, XFS_BLFT_AGF_BUF);
2163
2164         xfs_btree_offsets(fields, offsets, XFS_AGF_NUM_BITS, &first, &last);
2165         xfs_trans_log_buf(tp, bp, (uint)first, (uint)last);
2166 }
2167
2168 /*
2169  * Interface for inode allocation to force the pag data to be initialized.
2170  */
2171 int                                     /* error */
2172 xfs_alloc_pagf_init(
2173         xfs_mount_t             *mp,    /* file system mount structure */
2174         xfs_trans_t             *tp,    /* transaction pointer */
2175         xfs_agnumber_t          agno,   /* allocation group number */
2176         int                     flags)  /* XFS_ALLOC_FLAGS_... */
2177 {
2178         xfs_buf_t               *bp;
2179         int                     error;
2180
2181         if ((error = xfs_alloc_read_agf(mp, tp, agno, flags, &bp)))
2182                 return error;
2183         if (bp)
2184                 xfs_trans_brelse(tp, bp);
2185         return 0;
2186 }
2187
2188 /*
2189  * Put the block on the freelist for the allocation group.
2190  */
2191 int                                     /* error */
2192 xfs_alloc_put_freelist(
2193         xfs_trans_t             *tp,    /* transaction pointer */
2194         xfs_buf_t               *agbp,  /* buffer for a.g. freelist header */
2195         xfs_buf_t               *agflbp,/* buffer for a.g. free block array */
2196         xfs_agblock_t           bno,    /* block being freed */
2197         int                     btreeblk) /* block came from a AGF btree */
2198 {
2199         xfs_agf_t               *agf;   /* a.g. freespace structure */
2200         __be32                  *blockp;/* pointer to array entry */
2201         int                     error;
2202         int                     logflags;
2203         xfs_mount_t             *mp;    /* mount structure */
2204         xfs_perag_t             *pag;   /* per allocation group data */
2205         __be32                  *agfl_bno;
2206         int                     startoff;
2207
2208         agf = XFS_BUF_TO_AGF(agbp);
2209         mp = tp->t_mountp;
2210
2211         if (!agflbp && (error = xfs_alloc_read_agfl(mp, tp,
2212                         be32_to_cpu(agf->agf_seqno), &agflbp)))
2213                 return error;
2214         be32_add_cpu(&agf->agf_fllast, 1);
2215         if (be32_to_cpu(agf->agf_fllast) == XFS_AGFL_SIZE(mp))
2216                 agf->agf_fllast = 0;
2217
2218         pag = xfs_perag_get(mp, be32_to_cpu(agf->agf_seqno));
2219         be32_add_cpu(&agf->agf_flcount, 1);
2220         xfs_trans_agflist_delta(tp, 1);
2221         pag->pagf_flcount++;
2222
2223         logflags = XFS_AGF_FLLAST | XFS_AGF_FLCOUNT;
2224         if (btreeblk) {
2225                 be32_add_cpu(&agf->agf_btreeblks, -1);
2226                 pag->pagf_btreeblks--;
2227                 logflags |= XFS_AGF_BTREEBLKS;
2228         }
2229         xfs_perag_put(pag);
2230
2231         xfs_alloc_log_agf(tp, agbp, logflags);
2232
2233         ASSERT(be32_to_cpu(agf->agf_flcount) <= XFS_AGFL_SIZE(mp));
2234
2235         agfl_bno = XFS_BUF_TO_AGFL_BNO(mp, agflbp);
2236         blockp = &agfl_bno[be32_to_cpu(agf->agf_fllast)];
2237         *blockp = cpu_to_be32(bno);
2238         startoff = (char *)blockp - (char *)agflbp->b_addr;
2239
2240         xfs_alloc_log_agf(tp, agbp, logflags);
2241
2242         xfs_trans_buf_set_type(tp, agflbp, XFS_BLFT_AGFL_BUF);
2243         xfs_trans_log_buf(tp, agflbp, startoff,
2244                           startoff + sizeof(xfs_agblock_t) - 1);
2245         return 0;
2246 }
2247
2248 static bool
2249 xfs_agf_verify(
2250         struct xfs_mount *mp,
2251         struct xfs_buf  *bp)
2252  {
2253         struct xfs_agf  *agf = XFS_BUF_TO_AGF(bp);
2254
2255         if (xfs_sb_version_hascrc(&mp->m_sb)) {
2256                 if (!uuid_equal(&agf->agf_uuid, &mp->m_sb.sb_meta_uuid))
2257                         return false;
2258                 if (!xfs_log_check_lsn(mp,
2259                                 be64_to_cpu(XFS_BUF_TO_AGF(bp)->agf_lsn)))
2260                         return false;
2261         }
2262
2263         if (!(agf->agf_magicnum == cpu_to_be32(XFS_AGF_MAGIC) &&
2264               XFS_AGF_GOOD_VERSION(be32_to_cpu(agf->agf_versionnum)) &&
2265               be32_to_cpu(agf->agf_freeblks) <= be32_to_cpu(agf->agf_length) &&
2266               be32_to_cpu(agf->agf_flfirst) < XFS_AGFL_SIZE(mp) &&
2267               be32_to_cpu(agf->agf_fllast) < XFS_AGFL_SIZE(mp) &&
2268               be32_to_cpu(agf->agf_flcount) <= XFS_AGFL_SIZE(mp)))
2269                 return false;
2270
2271         if (be32_to_cpu(agf->agf_levels[XFS_BTNUM_BNO]) > XFS_BTREE_MAXLEVELS ||
2272             be32_to_cpu(agf->agf_levels[XFS_BTNUM_CNT]) > XFS_BTREE_MAXLEVELS)
2273                 return false;
2274
2275         /*
2276          * during growfs operations, the perag is not fully initialised,
2277          * so we can't use it for any useful checking. growfs ensures we can't
2278          * use it by using uncached buffers that don't have the perag attached
2279          * so we can detect and avoid this problem.
2280          */
2281         if (bp->b_pag && be32_to_cpu(agf->agf_seqno) != bp->b_pag->pag_agno)
2282                 return false;
2283
2284         if (xfs_sb_version_haslazysbcount(&mp->m_sb) &&
2285             be32_to_cpu(agf->agf_btreeblks) > be32_to_cpu(agf->agf_length))
2286                 return false;
2287
2288         return true;;
2289
2290 }
2291
2292 static void
2293 xfs_agf_read_verify(
2294         struct xfs_buf  *bp)
2295 {
2296         struct xfs_mount *mp = bp->b_target->bt_mount;
2297
2298         if (xfs_sb_version_hascrc(&mp->m_sb) &&
2299             !xfs_buf_verify_cksum(bp, XFS_AGF_CRC_OFF))
2300                 xfs_buf_ioerror(bp, -EFSBADCRC);
2301         else if (XFS_TEST_ERROR(!xfs_agf_verify(mp, bp), mp,
2302                                 XFS_ERRTAG_ALLOC_READ_AGF,
2303                                 XFS_RANDOM_ALLOC_READ_AGF))
2304                 xfs_buf_ioerror(bp, -EFSCORRUPTED);
2305
2306         if (bp->b_error)
2307                 xfs_verifier_error(bp);
2308 }
2309
2310 static void
2311 xfs_agf_write_verify(
2312         struct xfs_buf  *bp)
2313 {
2314         struct xfs_mount *mp = bp->b_target->bt_mount;
2315         struct xfs_buf_log_item *bip = bp->b_fspriv;
2316
2317         if (!xfs_agf_verify(mp, bp)) {
2318                 xfs_buf_ioerror(bp, -EFSCORRUPTED);
2319                 xfs_verifier_error(bp);
2320                 return;
2321         }
2322
2323         if (!xfs_sb_version_hascrc(&mp->m_sb))
2324                 return;
2325
2326         if (bip)
2327                 XFS_BUF_TO_AGF(bp)->agf_lsn = cpu_to_be64(bip->bli_item.li_lsn);
2328
2329         xfs_buf_update_cksum(bp, XFS_AGF_CRC_OFF);
2330 }
2331
2332 const struct xfs_buf_ops xfs_agf_buf_ops = {
2333         .name = "xfs_agf",
2334         .verify_read = xfs_agf_read_verify,
2335         .verify_write = xfs_agf_write_verify,
2336 };
2337
2338 /*
2339  * Read in the allocation group header (free/alloc section).
2340  */
2341 int                                     /* error */
2342 xfs_read_agf(
2343         struct xfs_mount        *mp,    /* mount point structure */
2344         struct xfs_trans        *tp,    /* transaction pointer */
2345         xfs_agnumber_t          agno,   /* allocation group number */
2346         int                     flags,  /* XFS_BUF_ */
2347         struct xfs_buf          **bpp)  /* buffer for the ag freelist header */
2348 {
2349         int             error;
2350
2351         trace_xfs_read_agf(mp, agno);
2352
2353         ASSERT(agno != NULLAGNUMBER);
2354         error = xfs_trans_read_buf(
2355                         mp, tp, mp->m_ddev_targp,
2356                         XFS_AG_DADDR(mp, agno, XFS_AGF_DADDR(mp)),
2357                         XFS_FSS_TO_BB(mp, 1), flags, bpp, &xfs_agf_buf_ops);
2358         if (error)
2359                 return error;
2360         if (!*bpp)
2361                 return 0;
2362
2363         ASSERT(!(*bpp)->b_error);
2364         xfs_buf_set_ref(*bpp, XFS_AGF_REF);
2365         return 0;
2366 }
2367
2368 /*
2369  * Read in the allocation group header (free/alloc section).
2370  */
2371 int                                     /* error */
2372 xfs_alloc_read_agf(
2373         struct xfs_mount        *mp,    /* mount point structure */
2374         struct xfs_trans        *tp,    /* transaction pointer */
2375         xfs_agnumber_t          agno,   /* allocation group number */
2376         int                     flags,  /* XFS_ALLOC_FLAG_... */
2377         struct xfs_buf          **bpp)  /* buffer for the ag freelist header */
2378 {
2379         struct xfs_agf          *agf;           /* ag freelist header */
2380         struct xfs_perag        *pag;           /* per allocation group data */
2381         int                     error;
2382
2383         trace_xfs_alloc_read_agf(mp, agno);
2384
2385         ASSERT(agno != NULLAGNUMBER);
2386         error = xfs_read_agf(mp, tp, agno,
2387                         (flags & XFS_ALLOC_FLAG_TRYLOCK) ? XBF_TRYLOCK : 0,
2388                         bpp);
2389         if (error)
2390                 return error;
2391         if (!*bpp)
2392                 return 0;
2393         ASSERT(!(*bpp)->b_error);
2394
2395         agf = XFS_BUF_TO_AGF(*bpp);
2396         pag = xfs_perag_get(mp, agno);
2397         if (!pag->pagf_init) {
2398                 pag->pagf_freeblks = be32_to_cpu(agf->agf_freeblks);
2399                 pag->pagf_btreeblks = be32_to_cpu(agf->agf_btreeblks);
2400                 pag->pagf_flcount = be32_to_cpu(agf->agf_flcount);
2401                 pag->pagf_longest = be32_to_cpu(agf->agf_longest);
2402                 pag->pagf_levels[XFS_BTNUM_BNOi] =
2403                         be32_to_cpu(agf->agf_levels[XFS_BTNUM_BNOi]);
2404                 pag->pagf_levels[XFS_BTNUM_CNTi] =
2405                         be32_to_cpu(agf->agf_levels[XFS_BTNUM_CNTi]);
2406                 spin_lock_init(&pag->pagb_lock);
2407                 pag->pagb_count = 0;
2408                 pag->pagb_tree = RB_ROOT;
2409                 pag->pagf_init = 1;
2410         }
2411 #ifdef DEBUG
2412         else if (!XFS_FORCED_SHUTDOWN(mp)) {
2413                 ASSERT(pag->pagf_freeblks == be32_to_cpu(agf->agf_freeblks));
2414                 ASSERT(pag->pagf_btreeblks == be32_to_cpu(agf->agf_btreeblks));
2415                 ASSERT(pag->pagf_flcount == be32_to_cpu(agf->agf_flcount));
2416                 ASSERT(pag->pagf_longest == be32_to_cpu(agf->agf_longest));
2417                 ASSERT(pag->pagf_levels[XFS_BTNUM_BNOi] ==
2418                        be32_to_cpu(agf->agf_levels[XFS_BTNUM_BNOi]));
2419                 ASSERT(pag->pagf_levels[XFS_BTNUM_CNTi] ==
2420                        be32_to_cpu(agf->agf_levels[XFS_BTNUM_CNTi]));
2421         }
2422 #endif
2423         xfs_perag_put(pag);
2424         return 0;
2425 }
2426
2427 /*
2428  * Allocate an extent (variable-size).
2429  * Depending on the allocation type, we either look in a single allocation
2430  * group or loop over the allocation groups to find the result.
2431  */
2432 int                             /* error */
2433 xfs_alloc_vextent(
2434         xfs_alloc_arg_t *args)  /* allocation argument structure */
2435 {
2436         xfs_agblock_t   agsize; /* allocation group size */
2437         int             error;
2438         int             flags;  /* XFS_ALLOC_FLAG_... locking flags */
2439         xfs_extlen_t    minleft;/* minimum left value, temp copy */
2440         xfs_mount_t     *mp;    /* mount structure pointer */
2441         xfs_agnumber_t  sagno;  /* starting allocation group number */
2442         xfs_alloctype_t type;   /* input allocation type */
2443         int             bump_rotor = 0;
2444         int             no_min = 0;
2445         xfs_agnumber_t  rotorstep = xfs_rotorstep; /* inode32 agf stepper */
2446
2447         mp = args->mp;
2448         type = args->otype = args->type;
2449         args->agbno = NULLAGBLOCK;
2450         /*
2451          * Just fix this up, for the case where the last a.g. is shorter
2452          * (or there's only one a.g.) and the caller couldn't easily figure
2453          * that out (xfs_bmap_alloc).
2454          */
2455         agsize = mp->m_sb.sb_agblocks;
2456         if (args->maxlen > agsize)
2457                 args->maxlen = agsize;
2458         if (args->alignment == 0)
2459                 args->alignment = 1;
2460         ASSERT(XFS_FSB_TO_AGNO(mp, args->fsbno) < mp->m_sb.sb_agcount);
2461         ASSERT(XFS_FSB_TO_AGBNO(mp, args->fsbno) < agsize);
2462         ASSERT(args->minlen <= args->maxlen);
2463         ASSERT(args->minlen <= agsize);
2464         ASSERT(args->mod < args->prod);
2465         if (XFS_FSB_TO_AGNO(mp, args->fsbno) >= mp->m_sb.sb_agcount ||
2466             XFS_FSB_TO_AGBNO(mp, args->fsbno) >= agsize ||
2467             args->minlen > args->maxlen || args->minlen > agsize ||
2468             args->mod >= args->prod) {
2469                 args->fsbno = NULLFSBLOCK;
2470                 trace_xfs_alloc_vextent_badargs(args);
2471                 return 0;
2472         }
2473         minleft = args->minleft;
2474
2475         switch (type) {
2476         case XFS_ALLOCTYPE_THIS_AG:
2477         case XFS_ALLOCTYPE_NEAR_BNO:
2478         case XFS_ALLOCTYPE_THIS_BNO:
2479                 /*
2480                  * These three force us into a single a.g.
2481                  */
2482                 args->agno = XFS_FSB_TO_AGNO(mp, args->fsbno);
2483                 args->pag = xfs_perag_get(mp, args->agno);
2484                 args->minleft = 0;
2485                 error = xfs_alloc_fix_freelist(args, 0);
2486                 args->minleft = minleft;
2487                 if (error) {
2488                         trace_xfs_alloc_vextent_nofix(args);
2489                         goto error0;
2490                 }
2491                 if (!args->agbp) {
2492                         trace_xfs_alloc_vextent_noagbp(args);
2493                         break;
2494                 }
2495                 args->agbno = XFS_FSB_TO_AGBNO(mp, args->fsbno);
2496                 if ((error = xfs_alloc_ag_vextent(args)))
2497                         goto error0;
2498                 break;
2499         case XFS_ALLOCTYPE_START_BNO:
2500                 /*
2501                  * Try near allocation first, then anywhere-in-ag after
2502                  * the first a.g. fails.
2503                  */
2504                 if ((args->userdata & XFS_ALLOC_INITIAL_USER_DATA) &&
2505                     (mp->m_flags & XFS_MOUNT_32BITINODES)) {
2506                         args->fsbno = XFS_AGB_TO_FSB(mp,
2507                                         ((mp->m_agfrotor / rotorstep) %
2508                                         mp->m_sb.sb_agcount), 0);
2509                         bump_rotor = 1;
2510                 }
2511                 args->agbno = XFS_FSB_TO_AGBNO(mp, args->fsbno);
2512                 args->type = XFS_ALLOCTYPE_NEAR_BNO;
2513                 /* FALLTHROUGH */
2514         case XFS_ALLOCTYPE_ANY_AG:
2515         case XFS_ALLOCTYPE_START_AG:
2516         case XFS_ALLOCTYPE_FIRST_AG:
2517                 /*
2518                  * Rotate through the allocation groups looking for a winner.
2519                  */
2520                 if (type == XFS_ALLOCTYPE_ANY_AG) {
2521                         /*
2522                          * Start with the last place we left off.
2523                          */
2524                         args->agno = sagno = (mp->m_agfrotor / rotorstep) %
2525                                         mp->m_sb.sb_agcount;
2526                         args->type = XFS_ALLOCTYPE_THIS_AG;
2527                         flags = XFS_ALLOC_FLAG_TRYLOCK;
2528                 } else if (type == XFS_ALLOCTYPE_FIRST_AG) {
2529                         /*
2530                          * Start with allocation group given by bno.
2531                          */
2532                         args->agno = XFS_FSB_TO_AGNO(mp, args->fsbno);
2533                         args->type = XFS_ALLOCTYPE_THIS_AG;
2534                         sagno = 0;
2535                         flags = 0;
2536                 } else {
2537                         if (type == XFS_ALLOCTYPE_START_AG)
2538                                 args->type = XFS_ALLOCTYPE_THIS_AG;
2539                         /*
2540                          * Start with the given allocation group.
2541                          */
2542                         args->agno = sagno = XFS_FSB_TO_AGNO(mp, args->fsbno);
2543                         flags = XFS_ALLOC_FLAG_TRYLOCK;
2544                 }
2545                 /*
2546                  * Loop over allocation groups twice; first time with
2547                  * trylock set, second time without.
2548                  */
2549                 for (;;) {
2550                         args->pag = xfs_perag_get(mp, args->agno);
2551                         if (no_min) args->minleft = 0;
2552                         error = xfs_alloc_fix_freelist(args, flags);
2553                         args->minleft = minleft;
2554                         if (error) {
2555                                 trace_xfs_alloc_vextent_nofix(args);
2556                                 goto error0;
2557                         }
2558                         /*
2559                          * If we get a buffer back then the allocation will fly.
2560                          */
2561                         if (args->agbp) {
2562                                 if ((error = xfs_alloc_ag_vextent(args)))
2563                                         goto error0;
2564                                 break;
2565                         }
2566
2567                         trace_xfs_alloc_vextent_loopfailed(args);
2568
2569                         /*
2570                          * Didn't work, figure out the next iteration.
2571                          */
2572                         if (args->agno == sagno &&
2573                             type == XFS_ALLOCTYPE_START_BNO)
2574                                 args->type = XFS_ALLOCTYPE_THIS_AG;
2575                         /*
2576                         * For the first allocation, we can try any AG to get
2577                         * space.  However, if we already have allocated a
2578                         * block, we don't want to try AGs whose number is below
2579                         * sagno. Otherwise, we may end up with out-of-order
2580                         * locking of AGF, which might cause deadlock.
2581                         */
2582                         if (++(args->agno) == mp->m_sb.sb_agcount) {
2583                                 if (args->firstblock != NULLFSBLOCK)
2584                                         args->agno = sagno;
2585                                 else
2586                                         args->agno = 0;
2587                         }
2588                         /*
2589                          * Reached the starting a.g., must either be done
2590                          * or switch to non-trylock mode.
2591                          */
2592                         if (args->agno == sagno) {
2593                                 if (no_min == 1) {
2594                                         args->agbno = NULLAGBLOCK;
2595                                         trace_xfs_alloc_vextent_allfailed(args);
2596                                         break;
2597                                 }
2598                                 if (flags == 0) {
2599                                         no_min = 1;
2600                                 } else {
2601                                         flags = 0;
2602                                         if (type == XFS_ALLOCTYPE_START_BNO) {
2603                                                 args->agbno = XFS_FSB_TO_AGBNO(mp,
2604                                                         args->fsbno);
2605                                                 args->type = XFS_ALLOCTYPE_NEAR_BNO;
2606                                         }
2607                                 }
2608                         }
2609                         xfs_perag_put(args->pag);
2610                 }
2611                 if (bump_rotor || (type == XFS_ALLOCTYPE_ANY_AG)) {
2612                         if (args->agno == sagno)
2613                                 mp->m_agfrotor = (mp->m_agfrotor + 1) %
2614                                         (mp->m_sb.sb_agcount * rotorstep);
2615                         else
2616                                 mp->m_agfrotor = (args->agno * rotorstep + 1) %
2617                                         (mp->m_sb.sb_agcount * rotorstep);
2618                 }
2619                 break;
2620         default:
2621                 ASSERT(0);
2622                 /* NOTREACHED */
2623         }
2624         if (args->agbno == NULLAGBLOCK)
2625                 args->fsbno = NULLFSBLOCK;
2626         else {
2627                 args->fsbno = XFS_AGB_TO_FSB(mp, args->agno, args->agbno);
2628 #ifdef DEBUG
2629                 ASSERT(args->len >= args->minlen);
2630                 ASSERT(args->len <= args->maxlen);
2631                 ASSERT(args->agbno % args->alignment == 0);
2632                 XFS_AG_CHECK_DADDR(mp, XFS_FSB_TO_DADDR(mp, args->fsbno),
2633                         args->len);
2634 #endif
2635
2636                 /* Zero the extent if we were asked to do so */
2637                 if (args->userdata & XFS_ALLOC_USERDATA_ZERO) {
2638                         error = xfs_zero_extent(args->ip, args->fsbno, args->len);
2639                         if (error)
2640                                 goto error0;
2641                 }
2642
2643         }
2644         xfs_perag_put(args->pag);
2645         return 0;
2646 error0:
2647         xfs_perag_put(args->pag);
2648         return error;
2649 }
2650
2651 /* Ensure that the freelist is at full capacity. */
2652 int
2653 xfs_free_extent_fix_freelist(
2654         struct xfs_trans        *tp,
2655         xfs_agnumber_t          agno,
2656         struct xfs_buf          **agbp)
2657 {
2658         struct xfs_alloc_arg    args;
2659         int                     error;
2660
2661         memset(&args, 0, sizeof(struct xfs_alloc_arg));
2662         args.tp = tp;
2663         args.mp = tp->t_mountp;
2664         args.agno = agno;
2665
2666         /*
2667          * validate that the block number is legal - the enables us to detect
2668          * and handle a silent filesystem corruption rather than crashing.
2669          */
2670         if (args.agno >= args.mp->m_sb.sb_agcount)
2671                 return -EFSCORRUPTED;
2672
2673         args.pag = xfs_perag_get(args.mp, args.agno);
2674         ASSERT(args.pag);
2675
2676         error = xfs_alloc_fix_freelist(&args, XFS_ALLOC_FLAG_FREEING);
2677         if (error)
2678                 goto out;
2679
2680         *agbp = args.agbp;
2681 out:
2682         xfs_perag_put(args.pag);
2683         return error;
2684 }
2685
2686 /*
2687  * Free an extent.
2688  * Just break up the extent address and hand off to xfs_free_ag_extent
2689  * after fixing up the freelist.
2690  */
2691 int                             /* error */
2692 xfs_free_extent(
2693         struct xfs_trans        *tp,    /* transaction pointer */
2694         xfs_fsblock_t           bno,    /* starting block number of extent */
2695         xfs_extlen_t            len)    /* length of extent */
2696 {
2697         struct xfs_mount        *mp = tp->t_mountp;
2698         struct xfs_buf          *agbp;
2699         xfs_agnumber_t          agno = XFS_FSB_TO_AGNO(mp, bno);
2700         xfs_agblock_t           agbno = XFS_FSB_TO_AGBNO(mp, bno);
2701         int                     error;
2702
2703         ASSERT(len != 0);
2704
2705         trace_xfs_bmap_free_deferred(mp, agno, 0, agbno, len);
2706
2707         if (XFS_TEST_ERROR(false, mp,
2708                         XFS_ERRTAG_FREE_EXTENT,
2709                         XFS_RANDOM_FREE_EXTENT))
2710                 return -EIO;
2711
2712         error = xfs_free_extent_fix_freelist(tp, agno, &agbp);
2713         if (error)
2714                 return error;
2715
2716         XFS_WANT_CORRUPTED_GOTO(mp, agbno < mp->m_sb.sb_agblocks, err);
2717
2718         /* validate the extent size is legal now we have the agf locked */
2719         XFS_WANT_CORRUPTED_GOTO(mp,
2720                 agbno + len <= be32_to_cpu(XFS_BUF_TO_AGF(agbp)->agf_length),
2721                                 err);
2722
2723         error = xfs_free_ag_extent(tp, agbp, agno, agbno, len, 0);
2724         if (error)
2725                 goto err;
2726
2727         xfs_extent_busy_insert(tp, agno, agbno, len, 0);
2728         return 0;
2729
2730 err:
2731         xfs_trans_brelse(tp, agbp);
2732         return error;
2733 }