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