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