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