sys/vfs/hammer2: Drop unused inline function hammer2_freemapradix()
[dragonfly.git] / sys / vfs / hammer2 / hammer2_freemap.c
1 /*
2  * Copyright (c) 2011-2018 The DragonFly Project.  All rights reserved.
3  *
4  * This code is derived from software contributed to The DragonFly Project
5  * by Matthew Dillon <dillon@dragonflybsd.org>
6  * by Venkatesh Srinivas <vsrinivas@dragonflybsd.org>
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in
16  *    the documentation and/or other materials provided with the
17  *    distribution.
18  * 3. Neither the name of The DragonFly Project nor the names of its
19  *    contributors may be used to endorse or promote products derived
20  *    from this software without specific, prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
25  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
26  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
27  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
28  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
29  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
30  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
31  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
32  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  */
35 #include <sys/param.h>
36 #include <sys/systm.h>
37 #include <sys/kernel.h>
38 #include <sys/fcntl.h>
39 #include <sys/buf.h>
40 #include <sys/proc.h>
41 #include <sys/namei.h>
42 #include <sys/mount.h>
43 #include <sys/vnode.h>
44 #include <sys/mountctl.h>
45
46 #include "hammer2.h"
47
48 #define FREEMAP_DEBUG   0
49
50 struct hammer2_fiterate {
51         hammer2_off_t   bpref;
52         hammer2_off_t   bnext;
53         int             loops;
54         int             relaxed;
55 };
56
57 typedef struct hammer2_fiterate hammer2_fiterate_t;
58
59 static int hammer2_freemap_try_alloc(hammer2_chain_t **parentp,
60                         hammer2_blockref_t *bref, int radix,
61                         hammer2_fiterate_t *iter, hammer2_tid_t mtid);
62 static void hammer2_freemap_init(hammer2_dev_t *hmp,
63                         hammer2_key_t key, hammer2_chain_t *chain);
64 static int hammer2_bmap_alloc(hammer2_dev_t *hmp,
65                         hammer2_bmap_data_t *bmap, uint16_t class,
66                         int n, int sub_key, int radix, hammer2_key_t *basep);
67 static int hammer2_freemap_iterate(hammer2_chain_t **parentp,
68                         hammer2_chain_t **chainp,
69                         hammer2_fiterate_t *iter);
70
71 /*
72  * Calculate the device offset for the specified FREEMAP_NODE or FREEMAP_LEAF
73  * bref.  Return a combined media offset and physical size radix.  Freemap
74  * chains use fixed storage offsets in the 4MB reserved area at the
75  * beginning of each 2GB zone
76  *
77  * XXX I made a mistake and made the reserved area begin at each LEVEL1 zone,
78  *     which is on a 1GB demark.  This will eat a little more space but for
79  *     now we retain compatibility and make FMZONEBASE every 1GB
80  *
81  *     (see same thing in hammer2_bulkfree.c near the top, as well as in
82  *     newfs_hammer2).
83  *
84  * Rotate between four possibilities.  Theoretically this means we have three
85  * good freemaps in case of a crash which we can use as a base for the fixup
86  * scan at mount-time.
87  */
88 #define H2FMZONEBASE(key)       ((key) & ~HAMMER2_FREEMAP_LEVEL1_MASK)
89 #define H2FMBASE(key, radix)    ((key) & ~(((hammer2_off_t)1 << (radix)) - 1))
90 #define H2FMSHIFT(radix)        ((hammer2_off_t)1 << (radix))
91
92 static
93 int
94 hammer2_freemap_reserve(hammer2_chain_t *chain, int radix)
95 {
96         hammer2_blockref_t *bref = &chain->bref;
97         hammer2_off_t off;
98         int index;
99         int index_inc;
100         size_t bytes;
101
102         /*
103          * Physical allocation size.
104          */
105         bytes = (size_t)1 << radix;
106
107         /*
108          * Calculate block selection index 0..7 of current block.  If this
109          * is the first allocation of the block (verses a modification of an
110          * existing block), we use index 0, otherwise we use the next rotating
111          * index.
112          */
113         if ((bref->data_off & ~HAMMER2_OFF_MASK_RADIX) == 0) {
114                 index = 0;
115         } else {
116                 off = bref->data_off & ~HAMMER2_OFF_MASK_RADIX &
117                       (HAMMER2_FREEMAP_LEVEL1_SIZE - 1);
118                 off = off / HAMMER2_PBUFSIZE;
119                 KKASSERT(off >= HAMMER2_ZONE_FREEMAP_00 &&
120                          off < HAMMER2_ZONE_FREEMAP_END);
121                 index = (int)(off - HAMMER2_ZONE_FREEMAP_00) /
122                         HAMMER2_ZONE_FREEMAP_INC;
123                 KKASSERT(index >= 0 && index < HAMMER2_NFREEMAPS);
124                 if (++index == HAMMER2_NFREEMAPS)
125                         index = 0;
126         }
127
128         /*
129          * Calculate the block offset of the reserved block.  This will
130          * point into the 4MB reserved area at the base of the appropriate
131          * 2GB zone, once added to the FREEMAP_x selection above.
132          */
133         index_inc = index * HAMMER2_ZONE_FREEMAP_INC;
134
135         switch(bref->keybits) {
136         /* case HAMMER2_FREEMAP_LEVEL6_RADIX: not applicable */
137         case HAMMER2_FREEMAP_LEVEL5_RADIX:      /* 4EB */
138                 KKASSERT(bref->type == HAMMER2_BREF_TYPE_FREEMAP_NODE);
139                 KKASSERT(bytes == HAMMER2_FREEMAP_LEVELN_PSIZE);
140                 off = H2FMBASE(bref->key, HAMMER2_FREEMAP_LEVEL5_RADIX) +
141                       (index_inc + HAMMER2_ZONE_FREEMAP_00 +
142                        HAMMER2_ZONEFM_LEVEL5) * HAMMER2_PBUFSIZE;
143                 break;
144         case HAMMER2_FREEMAP_LEVEL4_RADIX:      /* 16PB */
145                 KKASSERT(bref->type == HAMMER2_BREF_TYPE_FREEMAP_NODE);
146                 KKASSERT(bytes == HAMMER2_FREEMAP_LEVELN_PSIZE);
147                 off = H2FMBASE(bref->key, HAMMER2_FREEMAP_LEVEL4_RADIX) +
148                       (index_inc + HAMMER2_ZONE_FREEMAP_00 +
149                        HAMMER2_ZONEFM_LEVEL4) * HAMMER2_PBUFSIZE;
150                 break;
151         case HAMMER2_FREEMAP_LEVEL3_RADIX:      /* 64TB */
152                 KKASSERT(bref->type == HAMMER2_BREF_TYPE_FREEMAP_NODE);
153                 KKASSERT(bytes == HAMMER2_FREEMAP_LEVELN_PSIZE);
154                 off = H2FMBASE(bref->key, HAMMER2_FREEMAP_LEVEL3_RADIX) +
155                       (index_inc + HAMMER2_ZONE_FREEMAP_00 +
156                        HAMMER2_ZONEFM_LEVEL3) * HAMMER2_PBUFSIZE;
157                 break;
158         case HAMMER2_FREEMAP_LEVEL2_RADIX:      /* 256GB */
159                 KKASSERT(bref->type == HAMMER2_BREF_TYPE_FREEMAP_NODE);
160                 KKASSERT(bytes == HAMMER2_FREEMAP_LEVELN_PSIZE);
161                 off = H2FMBASE(bref->key, HAMMER2_FREEMAP_LEVEL2_RADIX) +
162                       (index_inc + HAMMER2_ZONE_FREEMAP_00 +
163                        HAMMER2_ZONEFM_LEVEL2) * HAMMER2_PBUFSIZE;
164                 break;
165         case HAMMER2_FREEMAP_LEVEL1_RADIX:      /* 1GB */
166                 KKASSERT(bref->type == HAMMER2_BREF_TYPE_FREEMAP_LEAF);
167                 KKASSERT(bytes == HAMMER2_FREEMAP_LEVELN_PSIZE);
168                 off = H2FMBASE(bref->key, HAMMER2_FREEMAP_LEVEL1_RADIX) +
169                       (index_inc + HAMMER2_ZONE_FREEMAP_00 +
170                        HAMMER2_ZONEFM_LEVEL1) * HAMMER2_PBUFSIZE;
171                 break;
172         default:
173                 panic("freemap: bad radix(2) %p %d\n", bref, bref->keybits);
174                 /* NOT REACHED */
175                 off = (hammer2_off_t)-1;
176                 break;
177         }
178         bref->data_off = off | radix;
179 #if FREEMAP_DEBUG
180         kprintf("FREEMAP BLOCK TYPE %d %016jx/%d DATA_OFF=%016jx\n",
181                 bref->type, bref->key, bref->keybits, bref->data_off);
182 #endif
183         return (0);
184 }
185
186 /*
187  * Normal freemap allocator
188  *
189  * Use available hints to allocate space using the freemap.  Create missing
190  * freemap infrastructure on-the-fly as needed (including marking initial
191  * allocations using the iterator as allocated, instantiating new 2GB zones,
192  * and dealing with the end-of-media edge case).
193  *
194  * ip and bpref are only used as a heuristic to determine locality of
195  * reference.  bref->key may also be used heuristically.
196  *
197  * This function is a NOP if bytes is 0.
198  */
199 int
200 hammer2_freemap_alloc(hammer2_chain_t *chain, size_t bytes)
201 {
202         hammer2_dev_t *hmp = chain->hmp;
203         hammer2_blockref_t *bref = &chain->bref;
204         hammer2_chain_t *parent;
205         hammer2_tid_t mtid;
206         int radix;
207         int error;
208         unsigned int hindex;
209         hammer2_fiterate_t iter;
210
211         /*
212          * If allocating or downsizing to zero we just get rid of whatever
213          * data_off we had.
214          */
215         if (bytes == 0) {
216                 chain->bref.data_off = 0;
217                 return 0;
218         }
219
220         KKASSERT(hmp->spmp);
221         mtid = hammer2_trans_sub(hmp->spmp);
222
223         /*
224          * Validate the allocation size.  It must be a power of 2.
225          *
226          * For now require that the caller be aware of the minimum
227          * allocation (1K).
228          */
229         radix = hammer2_getradix(bytes);
230         KKASSERT((size_t)1 << radix == bytes);
231
232         if (bref->type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
233             bref->type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
234                 /*
235                  * Freemap blocks themselves are assigned from the reserve
236                  * area, not allocated from the freemap.
237                  */
238                 error = hammer2_freemap_reserve(chain, radix);
239
240                 return error;
241         }
242
243         KKASSERT(bytes >= HAMMER2_ALLOC_MIN && bytes <= HAMMER2_ALLOC_MAX);
244
245         /*
246          * Calculate the starting point for our allocation search.
247          *
248          * Each freemap leaf is dedicated to a specific freemap_radix.
249          * The freemap_radix can be more fine-grained than the device buffer
250          * radix which results in inodes being grouped together in their
251          * own segment, terminal-data (16K or less) and initial indirect
252          * block being grouped together, and then full-indirect and full-data
253          * blocks (64K) being grouped together.
254          *
255          * The single most important aspect of this is the inode grouping
256          * because that is what allows 'find' and 'ls' and other filesystem
257          * topology operations to run fast.
258          */
259 #if 0
260         if (bref->data_off & ~HAMMER2_OFF_MASK_RADIX)
261                 bpref = bref->data_off & ~HAMMER2_OFF_MASK_RADIX;
262         else if (trans->tmp_bpref)
263                 bpref = trans->tmp_bpref;
264         else if (trans->tmp_ip)
265                 bpref = trans->tmp_ip->chain->bref.data_off;
266         else
267 #endif
268         /*
269          * Heuristic tracking index.  We would like one for each distinct
270          * bref type if possible.  heur_freemap[] has room for two classes
271          * for each type.  At a minimum we have to break-up our heuristic
272          * by device block sizes.
273          */
274         hindex = hammer2_devblkradix(radix) - HAMMER2_MINIORADIX;
275         KKASSERT(hindex < HAMMER2_FREEMAP_HEUR_NRADIX);
276         hindex += bref->type * HAMMER2_FREEMAP_HEUR_NRADIX;
277         hindex &= HAMMER2_FREEMAP_HEUR_TYPES * HAMMER2_FREEMAP_HEUR_NRADIX - 1;
278         KKASSERT(hindex < HAMMER2_FREEMAP_HEUR_SIZE);
279
280         iter.bpref = hmp->heur_freemap[hindex];
281         iter.relaxed = hmp->freemap_relaxed;
282
283         /*
284          * Make sure bpref is in-bounds.  It's ok if bpref covers a zone's
285          * reserved area, the try code will iterate past it.
286          */
287         if (iter.bpref > hmp->voldata.volu_size)
288                 iter.bpref = hmp->voldata.volu_size - 1;
289
290         /*
291          * Iterate the freemap looking for free space before and after.
292          */
293         parent = &hmp->fchain;
294         hammer2_chain_ref(parent);
295         hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS);
296         error = HAMMER2_ERROR_EAGAIN;
297         iter.bnext = iter.bpref;
298         iter.loops = 0;
299
300         while (error == HAMMER2_ERROR_EAGAIN) {
301                 error = hammer2_freemap_try_alloc(&parent, bref, radix,
302                                                   &iter, mtid);
303         }
304         hmp->freemap_relaxed |= iter.relaxed;   /* heuristical, SMP race ok */
305         hmp->heur_freemap[hindex] = iter.bnext;
306         hammer2_chain_unlock(parent);
307         hammer2_chain_drop(parent);
308
309         return (error);
310 }
311
312 static int
313 hammer2_freemap_try_alloc(hammer2_chain_t **parentp,
314                           hammer2_blockref_t *bref, int radix,
315                           hammer2_fiterate_t *iter, hammer2_tid_t mtid)
316 {
317         hammer2_dev_t *hmp = (*parentp)->hmp;
318         hammer2_off_t l0size;
319         hammer2_off_t l1size;
320         hammer2_off_t l1mask;
321         hammer2_key_t key_dummy;
322         hammer2_chain_t *chain;
323         hammer2_off_t key;
324         size_t bytes;
325         uint16_t class;
326         int error;
327
328         /*
329          * Calculate the number of bytes being allocated, the number
330          * of contiguous bits of bitmap being allocated, and the bitmap
331          * mask.
332          *
333          * WARNING! cpu hardware may mask bits == 64 -> 0 and blow up the
334          *          mask calculation.
335          */
336         bytes = (size_t)1 << radix;
337         class = (bref->type << 8) | hammer2_devblkradix(radix);
338
339         /*
340          * Lookup the level1 freemap chain, creating and initializing one
341          * if necessary.  Intermediate levels will be created automatically
342          * when necessary by hammer2_chain_create().
343          */
344         key = H2FMBASE(iter->bnext, HAMMER2_FREEMAP_LEVEL1_RADIX);
345         l0size = H2FMSHIFT(HAMMER2_FREEMAP_LEVEL0_RADIX);
346         l1size = H2FMSHIFT(HAMMER2_FREEMAP_LEVEL1_RADIX);
347         l1mask = l1size - 1;
348
349         chain = hammer2_chain_lookup(parentp, &key_dummy, key, key + l1mask,
350                                      &error,
351                                      HAMMER2_LOOKUP_ALWAYS |
352                                      HAMMER2_LOOKUP_MATCHIND);
353
354         if (chain == NULL) {
355                 /*
356                  * Create the missing leaf, be sure to initialize
357                  * the auxillary freemap tracking information in
358                  * the bref.check.freemap structure.
359                  */
360 #if 0
361                 kprintf("freemap create L1 @ %016jx bpref %016jx\n",
362                         key, iter->bpref);
363 #endif
364                 error = hammer2_chain_create(parentp, &chain, NULL, hmp->spmp,
365                                      HAMMER2_METH_DEFAULT,
366                                      key, HAMMER2_FREEMAP_LEVEL1_RADIX,
367                                      HAMMER2_BREF_TYPE_FREEMAP_LEAF,
368                                      HAMMER2_FREEMAP_LEVELN_PSIZE,
369                                      mtid, 0, 0);
370                 KKASSERT(error == 0);
371                 if (error == 0) {
372                         hammer2_chain_modify(chain, mtid, 0, 0);
373                         bzero(&chain->data->bmdata[0],
374                               HAMMER2_FREEMAP_LEVELN_PSIZE);
375                         chain->bref.check.freemap.bigmask = (uint32_t)-1;
376                         chain->bref.check.freemap.avail = l1size;
377                         /* bref.methods should already be inherited */
378
379                         hammer2_freemap_init(hmp, key, chain);
380                 }
381         } else if (chain->error) {
382                 /*
383                  * Error during lookup.
384                  */
385                 kprintf("hammer2_freemap_try_alloc: %016jx: error %s\n",
386                         (intmax_t)bref->data_off,
387                         hammer2_error_str(chain->error));
388                 error = HAMMER2_ERROR_EIO;
389         } else if ((chain->bref.check.freemap.bigmask &
390                    ((size_t)1 << radix)) == 0) {
391                 /*
392                  * Already flagged as not having enough space
393                  */
394                 error = HAMMER2_ERROR_ENOSPC;
395         } else {
396                 /*
397                  * Modify existing chain to setup for adjustment.
398                  */
399                 hammer2_chain_modify(chain, mtid, 0, 0);
400         }
401
402         /*
403          * Scan 4MB entries.
404          */
405         if (error == 0) {
406                 hammer2_bmap_data_t *bmap;
407                 hammer2_key_t base_key;
408                 int count;
409                 int start;
410                 int n;
411
412                 KKASSERT(chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF);
413                 start = (int)((iter->bnext - key) >>
414                               HAMMER2_FREEMAP_LEVEL0_RADIX);
415                 KKASSERT(start >= 0 && start < HAMMER2_FREEMAP_COUNT);
416                 hammer2_chain_modify(chain, mtid, 0, 0);
417
418                 error = HAMMER2_ERROR_ENOSPC;
419                 for (count = 0; count < HAMMER2_FREEMAP_COUNT; ++count) {
420                         int availchk;
421
422                         if (start + count >= HAMMER2_FREEMAP_COUNT &&
423                             start - count < 0) {
424                                 break;
425                         }
426
427                         /*
428                          * Calculate bmap pointer from thart starting index
429                          * forwards.
430                          *
431                          * NOTE: bmap pointer is invalid if n >= FREEMAP_COUNT.
432                          */
433                         n = start + count;
434                         bmap = &chain->data->bmdata[n];
435
436                         if (n >= HAMMER2_FREEMAP_COUNT) {
437                                 availchk = 0;
438                         } else if (bmap->avail) {
439                                 availchk = 1;
440                         } else if (radix < HAMMER2_FREEMAP_BLOCK_RADIX &&
441                                   (bmap->linear & HAMMER2_FREEMAP_BLOCK_MASK)) {
442                                 availchk = 1;
443                         } else {
444                                 availchk = 0;
445                         }
446
447                         /*
448                          * Try to allocate from a matching freemap class
449                          * superblock.  If we are in relaxed mode we allocate
450                          * from any freemap class superblock.
451                          */
452                         if (availchk &&
453                             (bmap->class == 0 || bmap->class == class ||
454                              iter->relaxed)) {
455                                 base_key = key + n * l0size;
456                                 error = hammer2_bmap_alloc(hmp, bmap,
457                                                            class, n,
458                                                            (int)bref->key,
459                                                            radix,
460                                                            &base_key);
461                                 if (error != HAMMER2_ERROR_ENOSPC) {
462                                         key = base_key;
463                                         break;
464                                 }
465                         }
466
467                         /*
468                          * Calculate bmap pointer from thart starting index
469                          * backwards (locality).
470                          *
471                          * Must recalculate after potentially having called
472                          * hammer2_bmap_alloc() above in case chain was
473                          * reallocated.
474                          *
475                          * NOTE: bmap pointer is invalid if n < 0.
476                          */
477                         n = start - count;
478                         bmap = &chain->data->bmdata[n];
479                         if (n < 0) {
480                                 availchk = 0;
481                         } else if (bmap->avail) {
482                                 availchk = 1;
483                         } else if (radix < HAMMER2_FREEMAP_BLOCK_RADIX &&
484                                   (bmap->linear & HAMMER2_FREEMAP_BLOCK_MASK)) {
485                                 availchk = 1;
486                         } else {
487                                 availchk = 0;
488                         }
489
490                         /*
491                          * Try to allocate from a matching freemap class
492                          * superblock.  If we are in relaxed mode we allocate
493                          * from any freemap class superblock.
494                          */
495                         if (availchk &&
496                             (bmap->class == 0 || bmap->class == class ||
497                             iter->relaxed)) {
498                                 base_key = key + n * l0size;
499                                 error = hammer2_bmap_alloc(hmp, bmap,
500                                                            class, n,
501                                                            (int)bref->key,
502                                                            radix,
503                                                            &base_key);
504                                 if (error != HAMMER2_ERROR_ENOSPC) {
505                                         key = base_key;
506                                         break;
507                                 }
508                         }
509                 }
510
511                 /*
512                  * We only know for sure that we can clear the bitmap bit
513                  * if we scanned the entire array (start == 0).
514                  */
515                 if (error == HAMMER2_ERROR_ENOSPC && start == 0) {
516                         chain->bref.check.freemap.bigmask &=
517                                 (uint32_t)~((size_t)1 << radix);
518                 }
519                 /* XXX also scan down from original count */
520         }
521
522         if (error == 0) {
523                 /*
524                  * Assert validity.  Must be beyond the static allocator used
525                  * by newfs_hammer2 (and thus also beyond the aux area),
526                  * not go past the volume size, and must not be in the
527                  * reserved segment area for a zone.
528                  */
529                 KKASSERT(key >= hmp->voldata.allocator_beg &&
530                          key + bytes <= hmp->voldata.volu_size);
531                 KKASSERT((key & HAMMER2_ZONE_MASK64) >= HAMMER2_ZONE_SEG);
532                 bref->data_off = key | radix;
533
534                 /*
535                  * Record dedupability.  The dedup bits are cleared
536                  * when bulkfree transitions the freemap from 11->10,
537                  * and asserted to be clear on the 10->00 transition.
538                  *
539                  * We must record the bitmask with the chain locked
540                  * at the time we set the allocation bits to avoid
541                  * racing a bulkfree.
542                  */
543                 if (bref->type == HAMMER2_BREF_TYPE_DATA)
544                         hammer2_io_dedup_set(hmp, bref);
545 #if 0
546                 kprintf("alloc cp=%p %016jx %016jx using %016jx\n",
547                         chain,
548                         bref->key, bref->data_off, chain->bref.data_off);
549 #endif
550         } else if (error == HAMMER2_ERROR_ENOSPC) {
551                 /*
552                  * Return EAGAIN with next iteration in iter->bnext, or
553                  * return ENOSPC if the allocation map has been exhausted.
554                  */
555                 error = hammer2_freemap_iterate(parentp, &chain, iter);
556         }
557
558         /*
559          * Cleanup
560          */
561         if (chain) {
562                 hammer2_chain_unlock(chain);
563                 hammer2_chain_drop(chain);
564         }
565         return (error);
566 }
567
568 /*
569  * Allocate (1<<radix) bytes from the bmap whos base data offset is (*basep).
570  *
571  * If the linear iterator is mid-block we use it directly (the bitmap should
572  * already be marked allocated), otherwise we search for a block in the
573  * bitmap that fits the allocation request.
574  *
575  * A partial bitmap allocation sets the minimum bitmap granularity (16KB)
576  * to fully allocated and adjusts the linear allocator to allow the
577  * remaining space to be allocated.
578  *
579  * sub_key is the lower 32 bits of the chain->bref.key for the chain whos
580  * bref is being allocated.  If the radix represents an allocation >= 16KB
581  * (aka HAMMER2_FREEMAP_BLOCK_RADIX) we try to use this key to select the
582  * blocks directly out of the bmap.
583  */
584 static
585 int
586 hammer2_bmap_alloc(hammer2_dev_t *hmp, hammer2_bmap_data_t *bmap,
587                    uint16_t class, int n, int sub_key,
588                    int radix, hammer2_key_t *basep)
589 {
590         size_t size;
591         size_t bgsize;
592         int bmradix;
593         hammer2_bitmap_t bmmask;
594         int offset;
595         int i;
596         int j;
597
598         /*
599          * Take into account 2-bits per block when calculating bmradix.
600          */
601         size = (size_t)1 << radix;
602
603         if (radix <= HAMMER2_FREEMAP_BLOCK_RADIX) {
604                 bmradix = 2;
605                 /* (16K) 2 bits per allocation block */
606         } else {
607                 bmradix = (hammer2_bitmap_t)2 <<
608                           (radix - HAMMER2_FREEMAP_BLOCK_RADIX);
609                 /* (32K-256K) 4, 8, 16, 32 bits per allocation block */
610         }
611
612         /*
613          * Use the linear iterator to pack small allocations, otherwise
614          * fall-back to finding a free 16KB chunk.  The linear iterator
615          * is only valid when *NOT* on a freemap chunking boundary (16KB).
616          * If it is the bitmap must be scanned.  It can become invalid
617          * once we pack to the boundary.  We adjust it after a bitmap
618          * allocation only for sub-16KB allocations (so the perfectly good
619          * previous value can still be used for fragments when 16KB+
620          * allocations are made inbetween fragmentary allocations).
621          *
622          * Beware of hardware artifacts when bmradix == 64 (intermediate
623          * result can wind up being '1' instead of '0' if hardware masks
624          * bit-count & 63).
625          *
626          * NOTE: j needs to be even in the j= calculation.  As an artifact
627          *       of the /2 division, our bitmask has to clear bit 0.
628          *
629          * NOTE: TODO this can leave little unallocatable fragments lying
630          *       around.
631          */
632         if (((uint32_t)bmap->linear & HAMMER2_FREEMAP_BLOCK_MASK) + size <=
633             HAMMER2_FREEMAP_BLOCK_SIZE &&
634             (bmap->linear & HAMMER2_FREEMAP_BLOCK_MASK) &&
635             bmap->linear < HAMMER2_SEGSIZE) {
636                 /*
637                  * Use linear iterator if it is not block-aligned to avoid
638                  * wasting space.
639                  *
640                  * Calculate the bitmapq[] index (i) and calculate the
641                  * shift count within the 64-bit bitmapq[] entry.
642                  *
643                  * The freemap block size is 16KB, but each bitmap
644                  * entry is two bits so use a little trick to get
645                  * a (j) shift of 0, 2, 4, ... 62 in 16KB chunks.
646                  */
647                 KKASSERT(bmap->linear >= 0 &&
648                          bmap->linear + size <= HAMMER2_SEGSIZE &&
649                          (bmap->linear & (HAMMER2_ALLOC_MIN - 1)) == 0);
650                 offset = bmap->linear;
651                 i = offset / (HAMMER2_SEGSIZE / HAMMER2_BMAP_ELEMENTS);
652                 j = (offset / (HAMMER2_FREEMAP_BLOCK_SIZE / 2)) & 62;
653                 bmmask = (bmradix == HAMMER2_BMAP_BITS_PER_ELEMENT) ?
654                          HAMMER2_BMAP_ALLONES :
655                          ((hammer2_bitmap_t)1 << bmradix) - 1;
656                 bmmask <<= j;
657                 bmap->linear = offset + size;
658         } else {
659                 /*
660                  * Try to index a starting point based on sub_key.  This
661                  * attempts to restore sequential block ordering on-disk
662                  * whenever possible, even if data is committed out of
663                  * order.
664                  *
665                  * i - Index bitmapq[], full data range represented is
666                  *     HAMMER2_BMAP_SIZE.
667                  *
668                  * j - Index within bitmapq[i], full data range represented is
669                  *     HAMMER2_BMAP_INDEX_SIZE.
670                  *
671                  * WARNING!
672                  */
673                 i = -1;
674                 j = -1;
675
676                 switch(class >> 8) {
677                 case HAMMER2_BREF_TYPE_DATA:
678                         if (radix >= HAMMER2_FREEMAP_BLOCK_RADIX) {
679                                 i = (sub_key & HAMMER2_BMAP_MASK) /
680                                     (HAMMER2_BMAP_SIZE / HAMMER2_BMAP_ELEMENTS);
681                                 j = (sub_key & HAMMER2_BMAP_INDEX_MASK) /
682                                     (HAMMER2_BMAP_INDEX_SIZE /
683                                      HAMMER2_BMAP_BLOCKS_PER_ELEMENT);
684                                 j = j * 2;
685                         }
686                         break;
687                 case HAMMER2_BREF_TYPE_INODE:
688                         break;
689                 default:
690                         break;
691                 }
692                 if (i >= 0) {
693                         KKASSERT(i < HAMMER2_BMAP_ELEMENTS &&
694                                  j < 2 * HAMMER2_BMAP_BLOCKS_PER_ELEMENT);
695                         KKASSERT(j + bmradix <= HAMMER2_BMAP_BITS_PER_ELEMENT);
696                         bmmask = (bmradix == HAMMER2_BMAP_BITS_PER_ELEMENT) ?
697                                  HAMMER2_BMAP_ALLONES :
698                                  ((hammer2_bitmap_t)1 << bmradix) - 1;
699                         bmmask <<= j;
700
701                         if ((bmap->bitmapq[i] & bmmask) == 0)
702                                 goto success;
703                 }
704
705                 /*
706                  * General element scan.
707                  *
708                  * WARNING: (j) is iterating a bit index (by 2's)
709                  */
710                 for (i = 0; i < HAMMER2_BMAP_ELEMENTS; ++i) {
711                         bmmask = (bmradix == HAMMER2_BMAP_BITS_PER_ELEMENT) ?
712                                  HAMMER2_BMAP_ALLONES :
713                                  ((hammer2_bitmap_t)1 << bmradix) - 1;
714                         for (j = 0;
715                              j < HAMMER2_BMAP_BITS_PER_ELEMENT;
716                              j += bmradix) {
717                                 if ((bmap->bitmapq[i] & bmmask) == 0)
718                                         goto success;
719                                 bmmask <<= bmradix;
720                         }
721                 }
722                 /*fragments might remain*/
723                 /*KKASSERT(bmap->avail == 0);*/
724                 return (HAMMER2_ERROR_ENOSPC);
725 success:
726                 offset = i * (HAMMER2_SEGSIZE / HAMMER2_BMAP_ELEMENTS) +
727                          (j * (HAMMER2_FREEMAP_BLOCK_SIZE / 2));
728                 if (size & HAMMER2_FREEMAP_BLOCK_MASK)
729                         bmap->linear = offset + size;
730         }
731
732         /* 8 x (64/2) -> 256 x 16K -> 4MB */
733         KKASSERT(i >= 0 && i < HAMMER2_BMAP_ELEMENTS);
734
735         /*
736          * Optimize the buffer cache to avoid unnecessary read-before-write
737          * operations.
738          *
739          * The device block size could be larger than the allocation size
740          * so the actual bitmap test is somewhat more involved.  We have
741          * to use a compatible buffer size for this operation.
742          */
743         if ((bmap->bitmapq[i] & bmmask) == 0 &&
744             hammer2_devblksize(size) != size) {
745                 size_t psize = hammer2_devblksize(size);
746                 hammer2_off_t pmask = (hammer2_off_t)psize - 1;
747                 int pbmradix = (hammer2_bitmap_t)2 <<
748                                         (hammer2_devblkradix(radix) -
749                                HAMMER2_FREEMAP_BLOCK_RADIX);
750                 hammer2_bitmap_t pbmmask;
751                 int pradix = hammer2_getradix(psize);
752
753                 pbmmask = (pbmradix == HAMMER2_BMAP_BITS_PER_ELEMENT) ?
754                         HAMMER2_BMAP_ALLONES :
755                         ((hammer2_bitmap_t)1 << pbmradix) - 1;
756                 while ((pbmmask & bmmask) == 0)
757                         pbmmask <<= pbmradix;
758
759 #if 0
760                 kprintf("%016jx mask %016jx %016jx %016jx (%zd/%zd)\n",
761                         *basep + offset, bmap->bitmapq[i],
762                         pbmmask, bmmask, size, psize);
763 #endif
764
765                 if ((bmap->bitmapq[i] & pbmmask) == 0) {
766                         hammer2_io_t *dio;
767
768                         hammer2_io_newnz(hmp, class >> 8,
769                                         (*basep + (offset & ~pmask)) |
770                                         pradix, psize, &dio);
771                         hammer2_io_putblk(&dio);
772                 }
773         }
774
775 #if 0
776         /*
777          * When initializing a new inode segment also attempt to initialize
778          * an adjacent segment.  Be careful not to index beyond the array
779          * bounds.
780          *
781          * We do this to try to localize inode accesses to improve
782          * directory scan rates.  XXX doesn't improve scan rates.
783          */
784         if (size == HAMMER2_INODE_BYTES) {
785                 if (n & 1) {
786                         if (bmap[-1].radix == 0 && bmap[-1].avail)
787                                 bmap[-1].radix = radix;
788                 } else {
789                         if (bmap[1].radix == 0 && bmap[1].avail)
790                                 bmap[1].radix = radix;
791                 }
792         }
793 #endif
794         /*
795          * Calculate the bitmap-granular change in bgsize for the volume
796          * header.  We cannot use the fine-grained change here because
797          * the bulkfree code can't undo it.  If the bitmap element is already
798          * marked allocated it has already been accounted for.
799          */
800         if (radix < HAMMER2_FREEMAP_BLOCK_RADIX) {
801                 if (bmap->bitmapq[i] & bmmask)
802                         bgsize = 0;
803                 else
804                         bgsize = HAMMER2_FREEMAP_BLOCK_SIZE;
805         } else {
806                 bgsize = size;
807         }
808
809         /*
810          * Adjust the bitmap, set the class (it might have been 0),
811          * and available bytes, update the allocation offset (*basep)
812          * from the L0 base to the actual offset.
813          *
814          * Do not override the class if doing a relaxed class allocation.
815          *
816          * avail must reflect the bitmap-granular availability.  The allocator
817          * tests will also check the linear iterator.
818          */
819         bmap->bitmapq[i] |= bmmask;
820         if (bmap->class == 0)
821                 bmap->class = class;
822         bmap->avail -= bgsize;
823         *basep += offset;
824
825         /*
826          * Adjust the volume header's allocator_free parameter.  This
827          * parameter has to be fixed up by bulkfree which has no way to
828          * figure out sub-16K chunking, so it must be adjusted by the
829          * bitmap-granular size.
830          */
831         if (bgsize) {
832                 hammer2_voldata_lock(hmp);
833                 hammer2_voldata_modify(hmp);
834                 hmp->voldata.allocator_free -= bgsize;
835                 hammer2_voldata_unlock(hmp);
836         }
837
838         return(0);
839 }
840
841 /*
842  * Initialize a freemap for the storage area (in bytes) that begins at (key).
843  */
844 static
845 void
846 hammer2_freemap_init(hammer2_dev_t *hmp, hammer2_key_t key,
847                      hammer2_chain_t *chain)
848 {
849         hammer2_off_t l1size;
850         hammer2_off_t lokey;
851         hammer2_off_t hikey;
852         hammer2_bmap_data_t *bmap;
853         int count;
854
855         /*
856          * LEVEL1 is 1GB, there are two level1 1GB freemaps per 2GB zone.
857          */
858         l1size = H2FMSHIFT(HAMMER2_FREEMAP_LEVEL1_RADIX);
859
860         /*
861          * Calculate the portion of the 1GB map that should be initialized
862          * as free.  Portions below or after will be initialized as allocated.
863          * SEGMASK-align the areas so we don't have to worry about sub-scans
864          * or endianess when using memset.
865          *
866          * WARNING! It is possible for lokey to be larger than hikey if the
867          *          entire 2GB segment is within the static allocation.
868          */
869         /*
870          * (1) Ensure that all statically allocated space from newfs_hammer2
871          *     is marked allocated, and take it up to the level1 base for
872          *     this key.
873          */
874         lokey = (hmp->voldata.allocator_beg + HAMMER2_SEGMASK64) &
875                 ~HAMMER2_SEGMASK64;
876         if (lokey < H2FMBASE(key, HAMMER2_FREEMAP_LEVEL1_RADIX))
877                 lokey = H2FMBASE(key, HAMMER2_FREEMAP_LEVEL1_RADIX);
878
879         /*
880          * (2) Ensure that the reserved area is marked allocated (typically
881          *     the first 4MB of each 2GB area being represented).  Since
882          *     each LEAF represents 1GB of storage and the zone is 2GB, we
883          *     have to adjust lowkey upward every other LEAF sequentially.
884          */
885         if (lokey < H2FMZONEBASE(key) + HAMMER2_ZONE_SEG64)
886                 lokey = H2FMZONEBASE(key) + HAMMER2_ZONE_SEG64;
887
888         /*
889          * (3) Ensure that any trailing space at the end-of-volume is marked
890          *     allocated.
891          */
892         hikey = key + H2FMSHIFT(HAMMER2_FREEMAP_LEVEL1_RADIX);
893         if (hikey > hmp->voldata.volu_size) {
894                 hikey = hmp->voldata.volu_size & ~HAMMER2_SEGMASK64;
895         }
896
897         /*
898          * Heuristic highest possible value
899          */
900         chain->bref.check.freemap.avail =
901                 H2FMSHIFT(HAMMER2_FREEMAP_LEVEL1_RADIX);
902         bmap = &chain->data->bmdata[0];
903
904         /*
905          * Initialize bitmap (bzero'd by caller)
906          */
907         for (count = 0; count < HAMMER2_FREEMAP_COUNT; ++count) {
908                 if (key < lokey || key >= hikey) {
909                         memset(bmap->bitmapq, -1,
910                                sizeof(bmap->bitmapq));
911                         bmap->avail = 0;
912                         bmap->linear = HAMMER2_SEGSIZE;
913                         chain->bref.check.freemap.avail -=
914                                 H2FMSHIFT(HAMMER2_FREEMAP_LEVEL0_RADIX);
915                 } else {
916                         bmap->avail = H2FMSHIFT(HAMMER2_FREEMAP_LEVEL0_RADIX);
917                 }
918                 key += H2FMSHIFT(HAMMER2_FREEMAP_LEVEL0_RADIX);
919                 ++bmap;
920         }
921 }
922
923 /*
924  * The current Level 1 freemap has been exhausted, iterate to the next
925  * one, return ENOSPC if no freemaps remain.
926  *
927  * At least two loops are required.  If we are not in relaxed mode and
928  * we run out of storage we enter relaxed mode and do a third loop.
929  * The relaxed mode is recorded back in the hmp so once we enter the mode
930  * we remain relaxed until stuff begins to get freed and only do 2 loops.
931  *
932  * XXX this should rotate back to the beginning to handle freed-up space
933  * XXX or use intermediate entries to locate free space. TODO
934  */
935 static int
936 hammer2_freemap_iterate(hammer2_chain_t **parentp, hammer2_chain_t **chainp,
937                         hammer2_fiterate_t *iter)
938 {
939         hammer2_dev_t *hmp = (*parentp)->hmp;
940
941         iter->bnext &= ~(H2FMSHIFT(HAMMER2_FREEMAP_LEVEL1_RADIX) - 1);
942         iter->bnext += H2FMSHIFT(HAMMER2_FREEMAP_LEVEL1_RADIX);
943         if (iter->bnext >= hmp->voldata.volu_size) {
944                 iter->bnext = 0;
945                 if (++iter->loops >= 2) {
946                         if (iter->relaxed == 0)
947                                 iter->relaxed = 1;
948                         else
949                                 return (HAMMER2_ERROR_ENOSPC);
950                 }
951         }
952         return(HAMMER2_ERROR_EAGAIN);
953 }
954
955 /*
956  * Adjust the bit-pattern for data in the freemap bitmap according to
957  * (how).  This code is called from on-mount recovery to fixup (mark
958  * as allocated) blocks whos freemap upates might not have been committed
959  * in the last crash and is used by the bulk freemap scan to stage frees.
960  *
961  * WARNING! Cannot be called with a empty-data bref (radix == 0).
962  *
963  * XXX currently disabled when how == 0 (the normal real-time case).  At
964  * the moment we depend on the bulk freescan to actually free blocks.  It
965  * will still call this routine with a non-zero how to stage possible frees
966  * and to do the actual free.
967  */
968 void
969 hammer2_freemap_adjust(hammer2_dev_t *hmp, hammer2_blockref_t *bref,
970                        int how)
971 {
972         hammer2_off_t data_off = bref->data_off;
973         hammer2_chain_t *chain;
974         hammer2_chain_t *parent;
975         hammer2_bmap_data_t *bmap;
976         hammer2_key_t key;
977         hammer2_key_t key_dummy;
978         hammer2_off_t l0size;
979         hammer2_off_t l1size;
980         hammer2_off_t l1mask;
981         hammer2_tid_t mtid;
982         hammer2_bitmap_t *bitmap;
983         const hammer2_bitmap_t bmmask00 = 0;
984         hammer2_bitmap_t bmmask01;
985         hammer2_bitmap_t bmmask10;
986         hammer2_bitmap_t bmmask11;
987         size_t bytes;
988         uint16_t class;
989         int radix;
990         int start;
991         int count;
992         int modified = 0;
993         int error;
994         size_t bgsize = 0;
995
996         KKASSERT(how == HAMMER2_FREEMAP_DORECOVER);
997
998         KKASSERT(hmp->spmp);
999         mtid = hammer2_trans_sub(hmp->spmp);
1000
1001         radix = (int)data_off & HAMMER2_OFF_MASK_RADIX;
1002         KKASSERT(radix != 0);
1003         data_off &= ~HAMMER2_OFF_MASK_RADIX;
1004         KKASSERT(radix <= HAMMER2_RADIX_MAX);
1005
1006         if (radix)
1007                 bytes = (size_t)1 << radix;
1008         else
1009                 bytes = 0;
1010         class = (bref->type << 8) | hammer2_devblkradix(radix);
1011
1012         /*
1013          * We can't adjust the freemap for data allocations made by
1014          * newfs_hammer2.
1015          */
1016         if (data_off < hmp->voldata.allocator_beg)
1017                 return;
1018
1019         KKASSERT((data_off & HAMMER2_ZONE_MASK64) >= HAMMER2_ZONE_SEG);
1020
1021         /*
1022          * Lookup the level1 freemap chain.  The chain must exist.
1023          */
1024         key = H2FMBASE(data_off, HAMMER2_FREEMAP_LEVEL1_RADIX);
1025         l0size = H2FMSHIFT(HAMMER2_FREEMAP_LEVEL0_RADIX);
1026         l1size = H2FMSHIFT(HAMMER2_FREEMAP_LEVEL1_RADIX);
1027         l1mask = l1size - 1;
1028
1029         parent = &hmp->fchain;
1030         hammer2_chain_ref(parent);
1031         hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS);
1032
1033         chain = hammer2_chain_lookup(&parent, &key_dummy, key, key + l1mask,
1034                                      &error,
1035                                      HAMMER2_LOOKUP_ALWAYS |
1036                                      HAMMER2_LOOKUP_MATCHIND);
1037
1038         /*
1039          * Stop early if we are trying to free something but no leaf exists.
1040          */
1041         if (chain == NULL && how != HAMMER2_FREEMAP_DORECOVER) {
1042                 kprintf("hammer2_freemap_adjust: %016jx: no chain\n",
1043                         (intmax_t)bref->data_off);
1044                 goto done;
1045         }
1046         if (chain->error) {
1047                 kprintf("hammer2_freemap_adjust: %016jx: error %s\n",
1048                         (intmax_t)bref->data_off,
1049                         hammer2_error_str(chain->error));
1050                 hammer2_chain_unlock(chain);
1051                 hammer2_chain_drop(chain);
1052                 chain = NULL;
1053                 goto done;
1054         }
1055
1056         /*
1057          * Create any missing leaf(s) if we are doing a recovery (marking
1058          * the block(s) as being allocated instead of being freed).  Be sure
1059          * to initialize the auxillary freemap tracking info in the
1060          * bref.check.freemap structure.
1061          */
1062         if (chain == NULL && how == HAMMER2_FREEMAP_DORECOVER) {
1063                 error = hammer2_chain_create(&parent, &chain, NULL, hmp->spmp,
1064                                      HAMMER2_METH_DEFAULT,
1065                                      key, HAMMER2_FREEMAP_LEVEL1_RADIX,
1066                                      HAMMER2_BREF_TYPE_FREEMAP_LEAF,
1067                                      HAMMER2_FREEMAP_LEVELN_PSIZE,
1068                                      mtid, 0, 0);
1069
1070                 if (hammer2_debug & 0x0040) {
1071                         kprintf("fixup create chain %p %016jx:%d\n",
1072                                 chain, chain->bref.key, chain->bref.keybits);
1073                 }
1074
1075                 if (error == 0) {
1076                         error = hammer2_chain_modify(chain, mtid, 0, 0);
1077                         KKASSERT(error == 0);
1078                         bzero(&chain->data->bmdata[0],
1079                               HAMMER2_FREEMAP_LEVELN_PSIZE);
1080                         chain->bref.check.freemap.bigmask = (uint32_t)-1;
1081                         chain->bref.check.freemap.avail = l1size;
1082                         /* bref.methods should already be inherited */
1083
1084                         hammer2_freemap_init(hmp, key, chain);
1085                 }
1086                 /* XXX handle error */
1087         }
1088
1089 #if FREEMAP_DEBUG
1090         kprintf("FREEMAP ADJUST TYPE %d %016jx/%d DATA_OFF=%016jx\n",
1091                 chain->bref.type, chain->bref.key,
1092                 chain->bref.keybits, chain->bref.data_off);
1093 #endif
1094
1095         /*
1096          * Calculate the bitmask (runs in 2-bit pairs).
1097          */
1098         start = ((int)(data_off >> HAMMER2_FREEMAP_BLOCK_RADIX) & 15) * 2;
1099         bmmask01 = (hammer2_bitmap_t)1 << start;
1100         bmmask10 = (hammer2_bitmap_t)2 << start;
1101         bmmask11 = (hammer2_bitmap_t)3 << start;
1102
1103         /*
1104          * Fixup the bitmap.  Partial blocks cannot be fully freed unless
1105          * a bulk scan is able to roll them up.
1106          */
1107         if (radix < HAMMER2_FREEMAP_BLOCK_RADIX) {
1108                 count = 1;
1109                 if (how == HAMMER2_FREEMAP_DOREALFREE)
1110                         how = HAMMER2_FREEMAP_DOMAYFREE;
1111         } else {
1112                 count = 1 << (radix - HAMMER2_FREEMAP_BLOCK_RADIX);
1113         }
1114
1115         /*
1116          * [re]load the bmap and bitmap pointers.  Each bmap entry covers
1117          * a 4MB swath.  The bmap itself (LEVEL1) covers 2GB.
1118          *
1119          * Be sure to reset the linear iterator to ensure that the adjustment
1120          * is not ignored.
1121          */
1122 again:
1123         bmap = &chain->data->bmdata[(int)(data_off >> HAMMER2_SEGRADIX) &
1124                                     (HAMMER2_FREEMAP_COUNT - 1)];
1125         bitmap = &bmap->bitmapq[(int)(data_off >> (HAMMER2_SEGRADIX - 3)) & 7];
1126
1127         if (modified)
1128                 bmap->linear = 0;
1129
1130         while (count) {
1131                 KKASSERT(bmmask11);
1132                 if (how == HAMMER2_FREEMAP_DORECOVER) {
1133                         /*
1134                          * Recovery request, mark as allocated.
1135                          */
1136                         if ((*bitmap & bmmask11) != bmmask11) {
1137                                 if (modified == 0) {
1138                                         hammer2_chain_modify(chain, mtid, 0, 0);
1139                                         modified = 1;
1140                                         goto again;
1141                                 }
1142                                 if ((*bitmap & bmmask11) == bmmask00) {
1143                                         bmap->avail -=
1144                                                 HAMMER2_FREEMAP_BLOCK_SIZE;
1145                                         bgsize += HAMMER2_FREEMAP_BLOCK_SIZE;
1146                                 }
1147                                 if (bmap->class == 0)
1148                                         bmap->class = class;
1149                                 *bitmap |= bmmask11;
1150                                 if (hammer2_debug & 0x0040) {
1151                                         kprintf("hammer2_freemap_recover: "
1152                                                 "fixup type=%02x "
1153                                                 "block=%016jx/%zd\n",
1154                                                 bref->type, data_off, bytes);
1155                                 }
1156                         } else {
1157                                 /*
1158                                 kprintf("hammer2_freemap_recover:  good "
1159                                         "type=%02x block=%016jx/%zd\n",
1160                                         bref->type, data_off, bytes);
1161                                 */
1162                         }
1163                 }
1164 #if 0
1165                 /*
1166                  * XXX this stuff doesn't work, avail is miscalculated and
1167                  * code 10 means something else now.
1168                  */
1169                 else if ((*bitmap & bmmask11) == bmmask11) {
1170                         /*
1171                          * Mayfree/Realfree request and bitmap is currently
1172                          * marked as being fully allocated.
1173                          */
1174                         if (!modified) {
1175                                 hammer2_chain_modify(chain, 0);
1176                                 modified = 1;
1177                                 goto again;
1178                         }
1179                         if (how == HAMMER2_FREEMAP_DOREALFREE)
1180                                 *bitmap &= ~bmmask11;
1181                         else
1182                                 *bitmap = (*bitmap & ~bmmask11) | bmmask10;
1183                 } else if ((*bitmap & bmmask11) == bmmask10) {
1184                         /*
1185                          * Mayfree/Realfree request and bitmap is currently
1186                          * marked as being possibly freeable.
1187                          */
1188                         if (how == HAMMER2_FREEMAP_DOREALFREE) {
1189                                 if (!modified) {
1190                                         hammer2_chain_modify(chain, 0);
1191                                         modified = 1;
1192                                         goto again;
1193                                 }
1194                                 *bitmap &= ~bmmask11;
1195                         }
1196                 } else {
1197                         /*
1198                          * 01 - Not implemented, currently illegal state
1199                          * 00 - Not allocated at all, illegal free.
1200                          */
1201                         panic("hammer2_freemap_adjust: "
1202                               "Illegal state %08x(%08x)",
1203                               *bitmap, *bitmap & bmmask11);
1204                 }
1205 #endif
1206                 --count;
1207                 bmmask01 <<= 2;
1208                 bmmask10 <<= 2;
1209                 bmmask11 <<= 2;
1210         }
1211 #if HAMMER2_BMAP_ELEMENTS != 8
1212 #error "hammer2_freemap.c: HAMMER2_BMAP_ELEMENTS expected to be 8"
1213 #endif
1214         if (how == HAMMER2_FREEMAP_DOREALFREE && modified) {
1215                 bmap->avail += 1 << radix;
1216                 KKASSERT(bmap->avail <= HAMMER2_SEGSIZE);
1217                 if (bmap->avail == HAMMER2_SEGSIZE &&
1218                     bmap->bitmapq[0] == 0 &&
1219                     bmap->bitmapq[1] == 0 &&
1220                     bmap->bitmapq[2] == 0 &&
1221                     bmap->bitmapq[3] == 0 &&
1222                     bmap->bitmapq[4] == 0 &&
1223                     bmap->bitmapq[5] == 0 &&
1224                     bmap->bitmapq[6] == 0 &&
1225                     bmap->bitmapq[7] == 0) {
1226                         key = H2FMBASE(data_off, HAMMER2_FREEMAP_LEVEL0_RADIX);
1227                         kprintf("Freeseg %016jx\n", (intmax_t)key);
1228                         bmap->class = 0;
1229                 }
1230         }
1231
1232         /*
1233          * chain->bref.check.freemap.bigmask (XXX)
1234          *
1235          * Setting bigmask is a hint to the allocation code that there might
1236          * be something allocatable.  We also set this in recovery... it
1237          * doesn't hurt and we might want to use the hint for other validation
1238          * operations later on.
1239          *
1240          * We could calculate the largest possible allocation and set the
1241          * radii that could fit, but its easier just to set bigmask to -1.
1242          */
1243         if (modified) {
1244                 chain->bref.check.freemap.bigmask = -1;
1245                 hmp->freemap_relaxed = 0;       /* reset heuristic */
1246         }
1247
1248         hammer2_chain_unlock(chain);
1249         hammer2_chain_drop(chain);
1250 done:
1251         hammer2_chain_unlock(parent);
1252         hammer2_chain_drop(parent);
1253
1254         if (bgsize) {
1255                 hammer2_voldata_lock(hmp);
1256                 hammer2_voldata_modify(hmp);
1257                 hmp->voldata.allocator_free -= bgsize;
1258                 hammer2_voldata_unlock(hmp);
1259         }
1260 }
1261
1262 /*
1263  * Validate the freemap, in three stages.
1264  *
1265  * stage-1      ALLOCATED     -> POSSIBLY FREE
1266  *              POSSIBLY FREE -> POSSIBLY FREE (type corrected)
1267  *
1268  *      This transitions bitmap entries from ALLOCATED to POSSIBLY FREE.
1269  *      The POSSIBLY FREE state does not mean that a block is actually free
1270  *      and may be transitioned back to ALLOCATED in stage-2.
1271  *
1272  *      This is typically done during normal filesystem operations when
1273  *      something is deleted or a block is replaced.
1274  *
1275  *      This is done by bulkfree in-bulk after a memory-bounded meta-data
1276  *      scan to try to determine what might be freeable.
1277  *
1278  *      This can be done unconditionally through a freemap scan when the
1279  *      intention is to brute-force recover the proper state of the freemap.
1280  *
1281  * stage-2      POSSIBLY FREE -> ALLOCATED      (scan metadata topology)
1282  *
1283  *      This is done by bulkfree during a meta-data scan to ensure that
1284  *      all blocks still actually allocated by the filesystem are marked
1285  *      as such.
1286  *
1287  *      NOTE! Live filesystem transitions to POSSIBLY FREE can occur while
1288  *            the bulkfree stage-2 and stage-3 is running.  The live filesystem
1289  *            will use the alternative POSSIBLY FREE type (2) to prevent
1290  *            stage-3 from improperly transitioning unvetted possibly-free
1291  *            blocks to FREE.
1292  *
1293  * stage-3      POSSIBLY FREE (type 1) -> FREE  (scan freemap)
1294  *
1295  *      This is done by bulkfree to finalize POSSIBLY FREE states.
1296  *
1297  */