hammer2 - Change freemap segment delineation, other stuff
[dragonfly.git] / sys / vfs / hammer2 / hammer2_freemap.c
1 /*
2  * Copyright (c) 2011-2013 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 struct hammer2_fiterate {
49         hammer2_off_t   bpref;
50         hammer2_off_t   bnext;
51         int             loops;
52 };
53
54 typedef struct hammer2_fiterate hammer2_fiterate_t;
55
56 static int hammer2_freemap_try_alloc(hammer2_trans_t *trans,
57                         hammer2_chain_t **parentp, hammer2_blockref_t *bref,
58                         int radix, hammer2_fiterate_t *iter);
59 static void hammer2_freemap_init(hammer2_trans_t *trans, hammer2_mount_t *hmp,
60                         hammer2_key_t key, hammer2_chain_t *chain);
61 static int hammer2_bmap_alloc(hammer2_trans_t *trans, hammer2_mount_t *hmp,
62                         hammer2_bmap_data_t *bmap, uint16_t class,
63                         int n, int radix, hammer2_key_t *basep);
64 static int hammer2_freemap_iterate(hammer2_trans_t *trans,
65                         hammer2_chain_t **parentp, hammer2_chain_t **chainp,
66                         hammer2_fiterate_t *iter);
67
68 static __inline
69 int
70 hammer2_freemapradix(int radix)
71 {
72         return(radix);
73 }
74
75 /*
76  * Calculate the device offset for the specified FREEMAP_NODE or FREEMAP_LEAF
77  * bref.  Return a combined media offset and physical size radix.  Freemap
78  * chains use fixed storage offsets in the 4MB reserved area at the
79  * beginning of each 2GB zone
80  *
81  * Rotate between four possibilities.  Theoretically this means we have three
82  * good freemaps in case of a crash which we can use as a base for the fixup
83  * scan at mount-time.
84  */
85 #define H2FMBASE(key, radix)    ((key) & ~(((hammer2_off_t)1 << (radix)) - 1))
86 #define H2FMSHIFT(radix)        ((hammer2_off_t)1 << (radix))
87
88 static
89 int
90 hammer2_freemap_reserve(hammer2_mount_t *hmp, hammer2_blockref_t *bref,
91                         int radix)
92 {
93         hammer2_off_t off;
94         size_t bytes;
95
96         /*
97          * Physical allocation size -> radix.  Typically either 256 for
98          * a level 0 freemap leaf or 65536 for a level N freemap node.
99          *
100          * NOTE: A 256 byte bitmap represents 256 x 8 x 1024 = 2MB of storage.
101          *       Do not use hammer2_allocsize() here as it has a min cap.
102          */
103         bytes = 1 << radix;
104
105         /*
106          * Adjust by HAMMER2_ZONE_FREEMAP_{A,B,C,D} using the existing
107          * offset as a basis.  Start in zone A if previously unallocated.
108          */
109         if ((bref->data_off & ~HAMMER2_OFF_MASK_RADIX) == 0) {
110                 off = HAMMER2_ZONE_FREEMAP_A;
111         } else {
112                 off = bref->data_off & ~HAMMER2_OFF_MASK_RADIX &
113                       (((hammer2_off_t)1 << HAMMER2_FREEMAP_LEVEL1_RADIX) - 1);
114                 off = off / HAMMER2_PBUFSIZE;
115                 KKASSERT(off >= HAMMER2_ZONE_FREEMAP_A);
116                 KKASSERT(off < HAMMER2_ZONE_FREEMAP_D + 4);
117
118                 if (off >= HAMMER2_ZONE_FREEMAP_D)
119                         off = HAMMER2_ZONE_FREEMAP_A;
120                 else if (off >= HAMMER2_ZONE_FREEMAP_C)
121                         off = HAMMER2_ZONE_FREEMAP_D;
122                 else if (off >= HAMMER2_ZONE_FREEMAP_B)
123                         off = HAMMER2_ZONE_FREEMAP_C;
124                 else
125                         off = HAMMER2_ZONE_FREEMAP_B;
126         }
127         off = off * HAMMER2_PBUFSIZE;
128
129         /*
130          * Calculate the block offset of the reserved block.  This will
131          * point into the 4MB reserved area at the base of the appropriate
132          * 2GB zone, once added to the FREEMAP_x selection above.
133          */
134         switch(bref->keybits) {
135         /* case HAMMER2_FREEMAP_LEVEL5_RADIX: not applicable */
136         case HAMMER2_FREEMAP_LEVEL4_RADIX:      /* 2EB */
137                 KKASSERT(bref->type == HAMMER2_BREF_TYPE_FREEMAP_NODE);
138                 KKASSERT(bytes == HAMMER2_FREEMAP_LEVELN_PSIZE);
139                 off += H2FMBASE(bref->key, HAMMER2_FREEMAP_LEVEL4_RADIX) +
140                        HAMMER2_ZONEFM_LEVEL4 * HAMMER2_PBUFSIZE;
141                 break;
142         case HAMMER2_FREEMAP_LEVEL3_RADIX:      /* 2PB */
143                 KKASSERT(bref->type == HAMMER2_BREF_TYPE_FREEMAP_NODE);
144                 KKASSERT(bytes == HAMMER2_FREEMAP_LEVELN_PSIZE);
145                 off += H2FMBASE(bref->key, HAMMER2_FREEMAP_LEVEL3_RADIX) +
146                        HAMMER2_ZONEFM_LEVEL3 * HAMMER2_PBUFSIZE;
147                 break;
148         case HAMMER2_FREEMAP_LEVEL2_RADIX:      /* 2TB */
149                 KKASSERT(bref->type == HAMMER2_BREF_TYPE_FREEMAP_NODE);
150                 KKASSERT(bytes == HAMMER2_FREEMAP_LEVELN_PSIZE);
151                 off += H2FMBASE(bref->key, HAMMER2_FREEMAP_LEVEL2_RADIX) +
152                        HAMMER2_ZONEFM_LEVEL2 * HAMMER2_PBUFSIZE;
153                 break;
154         case HAMMER2_FREEMAP_LEVEL1_RADIX:      /* 2GB */
155                 KKASSERT(bref->type == HAMMER2_BREF_TYPE_FREEMAP_LEAF);
156                 KKASSERT(bytes == HAMMER2_FREEMAP_LEVELN_PSIZE);
157                 off += H2FMBASE(bref->key, HAMMER2_FREEMAP_LEVEL1_RADIX) +
158                        HAMMER2_ZONEFM_LEVEL1 * HAMMER2_PBUFSIZE;
159                 break;
160         default:
161                 panic("freemap: bad radix(2) %p %d\n", bref, bref->keybits);
162                 /* NOT REACHED */
163                 break;
164         }
165         bref->data_off = off | radix;
166         return (0);
167 }
168
169 /*
170  * Normal freemap allocator
171  *
172  * Use available hints to allocate space using the freemap.  Create missing
173  * freemap infrastructure on-the-fly as needed (including marking initial
174  * allocations using the iterator as allocated, instantiating new 2GB zones,
175  * and dealing with the end-of-media edge case).
176  *
177  * ip and bpref are only used as a heuristic to determine locality of
178  * reference.  bref->key may also be used heuristically.
179  */
180 int
181 hammer2_freemap_alloc(hammer2_trans_t *trans, hammer2_mount_t *hmp,
182                       hammer2_blockref_t *bref, size_t bytes)
183 {
184         hammer2_chain_t *parent;
185         int radix;
186         int error;
187         unsigned int hindex;
188         hammer2_fiterate_t iter;
189
190         /*
191          * Validate the allocation size.  It must be a power of 2.
192          *
193          * For now require that the caller be aware of the minimum
194          * allocation (1K).
195          */
196         radix = hammer2_getradix(bytes);
197         KKASSERT((size_t)1 << radix == bytes);
198
199         /*
200          * Freemap blocks themselves are simply assigned from the reserve
201          * area, not allocated from the freemap.
202          */
203         if (bref->type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
204             bref->type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
205                 return(hammer2_freemap_reserve(hmp, bref, radix));
206         }
207
208         if (bref->data_off & ~HAMMER2_OFF_MASK_RADIX)
209                 hammer2_freemap_free(trans, hmp, bref, 0);
210
211         /*
212          * Normal allocations
213          */
214         KKASSERT(bytes >= HAMMER2_MIN_ALLOC && bytes <= HAMMER2_MAX_ALLOC);
215
216         /*
217          * Calculate the starting point for our allocation search.
218          *
219          * Each freemap leaf is dedicated to a specific freemap_radix.
220          * The freemap_radix can be more fine-grained than the device buffer
221          * radix which results in inodes being grouped together in their
222          * own segment, terminal-data (16K or less) and initial indirect
223          * block being grouped together, and then full-indirect and full-data
224          * blocks (64K) being grouped together.
225          *
226          * The single most important aspect of this is the inode grouping
227          * because that is what allows 'find' and 'ls' and other filesystem
228          * topology operations to run fast.
229          */
230 #if 0
231         if (bref->data_off & ~HAMMER2_OFF_MASK_RADIX)
232                 bpref = bref->data_off & ~HAMMER2_OFF_MASK_RADIX;
233         else if (trans->tmp_bpref)
234                 bpref = trans->tmp_bpref;
235         else if (trans->tmp_ip)
236                 bpref = trans->tmp_ip->chain->bref.data_off;
237         else
238 #endif
239         /*
240          * Heuristic tracking index.  We would like one for each distinct
241          * bref type if possible.  heur_freemap[] has room for two classes
242          * for each type.  At a minimum we have to break-up our heuristic
243          * by device block sizes.
244          */
245         hindex = hammer2_devblkradix(radix) - HAMMER2_MINIORADIX;
246         KKASSERT(hindex < HAMMER2_FREEMAP_HEUR_NRADIX);
247         hindex += bref->type * HAMMER2_FREEMAP_HEUR_NRADIX;
248         hindex &= HAMMER2_FREEMAP_HEUR_TYPES * HAMMER2_FREEMAP_HEUR_NRADIX - 1;
249         KKASSERT(hindex < HAMMER2_FREEMAP_HEUR);
250
251         iter.bpref = hmp->heur_freemap[hindex];
252
253         /*
254          * Make sure bpref is in-bounds.  It's ok if bpref covers a zone's
255          * reserved area, the try code will iterate past it.
256          */
257         if (iter.bpref > hmp->voldata.volu_size)
258                 iter.bpref = hmp->voldata.volu_size - 1;
259
260         /*
261          * Iterate the freemap looking for free space before and after.
262          */
263         parent = &hmp->fchain;
264         hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS);
265         error = EAGAIN;
266         iter.bnext = iter.bpref;
267         iter.loops = 0;
268
269         while (error == EAGAIN) {
270                 error = hammer2_freemap_try_alloc(trans, &parent, bref,
271                                                   radix, &iter);
272         }
273         hmp->heur_freemap[hindex] = iter.bnext;
274         hammer2_chain_unlock(parent);
275
276         return (error);
277 }
278
279 static int
280 hammer2_freemap_try_alloc(hammer2_trans_t *trans, hammer2_chain_t **parentp,
281                           hammer2_blockref_t *bref, int radix,
282                           hammer2_fiterate_t *iter)
283 {
284         hammer2_mount_t *hmp = (*parentp)->hmp;
285         hammer2_off_t l0size;
286         hammer2_off_t l1size;
287         hammer2_off_t l1mask;
288         hammer2_chain_t *chain;
289         hammer2_off_t key;
290         size_t bytes;
291         uint16_t class;
292         int error = 0;
293
294
295         /*
296          * Calculate the number of bytes being allocated, the number
297          * of contiguous bits of bitmap being allocated, and the bitmap
298          * mask.
299          *
300          * WARNING! cpu hardware may mask bits == 64 -> 0 and blow up the
301          *          mask calculation.
302          */
303         bytes = (size_t)1 << radix;
304         class = (bref->type << 8) | hammer2_devblkradix(radix);
305
306         /*
307          * Lookup the level1 freemap chain, creating and initializing one
308          * if necessary.  Intermediate levels will be created automatically
309          * when necessary by hammer2_chain_create().
310          */
311         key = H2FMBASE(iter->bnext, HAMMER2_FREEMAP_LEVEL1_RADIX);
312         l0size = H2FMSHIFT(HAMMER2_FREEMAP_LEVEL0_RADIX);
313         l1size = H2FMSHIFT(HAMMER2_FREEMAP_LEVEL1_RADIX);
314         l1mask = l1size - 1;
315
316         chain = hammer2_chain_lookup(parentp, key, key + l1mask,
317                                      HAMMER2_LOOKUP_FREEMAP |
318                                      HAMMER2_LOOKUP_ALWAYS |
319                                      HAMMER2_LOOKUP_MATCHIND/*XXX*/);
320         if (chain == NULL) {
321                 /*
322                  * Create the missing leaf, be sure to initialize
323                  * the auxillary freemap tracking information in
324                  * the bref.check.freemap structure.
325                  */
326 #if 0
327                 kprintf("freemap create L1 @ %016jx bpref %016jx\n",
328                         key, iter->bpref);
329 #endif
330                 error = hammer2_chain_create(trans, parentp, &chain,
331                                      key, HAMMER2_FREEMAP_LEVEL1_RADIX,
332                                      HAMMER2_BREF_TYPE_FREEMAP_LEAF,
333                                      HAMMER2_FREEMAP_LEVELN_PSIZE);
334                 if (error == 0) {
335                         hammer2_chain_modify(trans, &chain, 0);
336                         bzero(&chain->data->bmdata[0],
337                               HAMMER2_FREEMAP_LEVELN_PSIZE);
338                         chain->bref.check.freemap.bigmask = (uint32_t)-1;
339                         chain->bref.check.freemap.avail = l1size;
340                         /* bref.methods should already be inherited */
341
342                         hammer2_freemap_init(trans, hmp, key, chain);
343                 }
344         } else if ((chain->bref.check.freemap.bigmask & (1 << radix)) == 0) {
345                 /*
346                  * Already flagged as not having enough space
347                  */
348                 error = ENOSPC;
349         } else {
350                 /*
351                  * Modify existing chain to setup for adjustment.
352                  */
353                 hammer2_chain_modify(trans, &chain, 0);
354         }
355
356         /*
357          * Scan 2MB entries.
358          */
359         if (error == 0) {
360                 hammer2_bmap_data_t *bmap;
361                 hammer2_key_t base_key;
362                 int count;
363                 int start;
364                 int n;
365
366                 start = (int)((iter->bnext - key) >>
367                               HAMMER2_FREEMAP_LEVEL0_RADIX);
368                 KKASSERT(start >= 0 && start < HAMMER2_FREEMAP_COUNT);
369                 hammer2_chain_modify(trans, &chain, 0);
370
371                 error = ENOSPC;
372                 for (count = 0; count < HAMMER2_FREEMAP_COUNT; ++count) {
373                         if (start + count >= HAMMER2_FREEMAP_COUNT &&
374                             start - count < 0) {
375                                 break;
376                         }
377                         n = start + count;
378                         bmap = &chain->data->bmdata[n];
379                         if (n < HAMMER2_FREEMAP_COUNT && bmap->avail &&
380                             (bmap->class == 0 || bmap->class == class)) {
381                                 base_key = key + n * l0size;
382                                 error = hammer2_bmap_alloc(trans, hmp, bmap,
383                                                            class, n, radix,
384                                                            &base_key);
385                                 if (error != ENOSPC) {
386                                         key = base_key;
387                                         break;
388                                 }
389                         }
390                         n = start - count;
391                         bmap = &chain->data->bmdata[n];
392                         if (n >= 0 && bmap->avail &&
393                             (bmap->class == 0 || bmap->class == class)) {
394                                 base_key = key + n * l0size;
395                                 error = hammer2_bmap_alloc(trans, hmp, bmap,
396                                                            class, n, radix,
397                                                            &base_key);
398                                 if (error != ENOSPC) {
399                                         key = base_key;
400                                         break;
401                                 }
402                         }
403                 }
404                 if (error == ENOSPC)
405                         chain->bref.check.freemap.bigmask &= ~(1 << radix);
406                 /* XXX also scan down from original count */
407         }
408
409         if (error == 0) {
410                 /*
411                  * Assert validity.  Must be beyond the static allocator used
412                  * by newfs_hammer2 (and thus also beyond the aux area),
413                  * not go past the volume size, and must not be in the
414                  * reserved segment area for a zone.
415                  */
416                 KKASSERT(key >= hmp->voldata.allocator_beg &&
417                          key + bytes <= hmp->voldata.volu_size);
418                 KKASSERT((key & HAMMER2_ZONE_MASK64) >= HAMMER2_ZONE_SEG);
419                 bref->data_off = key | radix;
420
421 #if 0
422                 kprintf("alloc cp=%p %016jx %016jx using %016jx\n",
423                         chain,
424                         bref->key, bref->data_off, chain->bref.data_off);
425 #endif
426         } else if (error == ENOSPC) {
427                 /*
428                  * Return EAGAIN with next iteration in iter->bnext, or
429                  * return ENOSPC if the allocation map has been exhausted.
430                  */
431                 error = hammer2_freemap_iterate(trans, parentp, &chain, iter);
432         }
433
434         /*
435          * Cleanup
436          */
437         if (chain)
438                 hammer2_chain_unlock(chain);
439         return (error);
440 }
441
442 /*
443  * Allocate (1<<radix) bytes from the bmap whos base data offset is (*basep).
444  *
445  * If the linear iterator is mid-block we use it directly (the bitmap should
446  * already be marked allocated), otherwise we search for a block in the bitmap
447  * that fits the allocation request.
448  *
449  * A partial bitmap allocation sets the minimum bitmap granularity (16KB)
450  * to fully allocated and adjusts the linear allocator to allow the
451  * remaining space to be allocated.
452  */
453 static
454 int
455 hammer2_bmap_alloc(hammer2_trans_t *trans, hammer2_mount_t *hmp,
456                    hammer2_bmap_data_t *bmap,
457                    uint16_t class, int n, int radix, hammer2_key_t *basep)
458 {
459         struct buf *bp;
460         size_t size;
461         size_t bsize;
462         int bmradix;
463         uint32_t bmmask;
464         int offset;
465         int i;
466         int j;
467
468         /*
469          * Take into account 2-bits per block when calculating bmradix.
470          */
471         size = (size_t)1 << radix;
472
473         if (radix <= HAMMER2_FREEMAP_BLOCK_RADIX) {
474                 bmradix = 2;
475                 bsize = HAMMER2_FREEMAP_BLOCK_SIZE;
476                 /* (16K) 2 bits per allocation block */
477         } else {
478                 bmradix = 2 << (radix - HAMMER2_FREEMAP_BLOCK_RADIX);
479                 bsize = size;
480                 /* (32K-256K) 4, 8, 16, 32 bits per allocation block */
481         }
482
483         /*
484          * Use the linear iterator to pack small allocations, otherwise
485          * fall-back to finding a free 16KB chunk.  The linear iterator
486          * is only valid when *NOT* on a freemap chunking boundary (16KB).
487          * If it is the bitmap must be scanned.  It can become invalid
488          * once we pack to the boundary.  We adjust it after a bitmap
489          * allocation only for sub-16KB allocations (so the perfectly good
490          * previous value can still be used for fragments when 16KB+
491          * allocations are made).
492          *
493          * Beware of hardware artifacts when bmradix == 32 (intermediate
494          * result can wind up being '1' instead of '0' if hardware masks
495          * bit-count & 31).
496          *
497          * NOTE: j needs to be even in the j= calculation.  As an artifact
498          *       of the /2 division, our bitmask has to clear bit 0.
499          *
500          * NOTE: TODO this can leave little unallocatable fragments lying
501          *       around.
502          */
503         if (((uint32_t)bmap->linear & HAMMER2_FREEMAP_BLOCK_MASK) + size <=
504             HAMMER2_FREEMAP_BLOCK_SIZE &&
505             bmap->linear < HAMMER2_SEGSIZE) {
506                 KKASSERT(bmap->linear >= 0 &&
507                          bmap->linear + size <= HAMMER2_SEGSIZE &&
508                          (bmap->linear & (HAMMER2_MIN_ALLOC - 1)) == 0);
509                 offset = bmap->linear;
510                 i = offset / (HAMMER2_SEGSIZE / 8);
511                 j = (offset / (HAMMER2_FREEMAP_BLOCK_SIZE / 2)) & 30;
512                 bmmask = (bmradix == 32) ?
513                          0xFFFFFFFFU : (1 << bmradix) - 1;
514                 bmmask <<= j;
515                 bmap->linear = offset + size;
516         } else {
517                 for (i = 0; i < 8; ++i) {
518                         bmmask = (bmradix == 32) ?
519                                  0xFFFFFFFFU : (1 << bmradix) - 1;
520                         for (j = 0; j < 32; j += bmradix) {
521                                 if ((bmap->bitmap[i] & bmmask) == 0)
522                                         goto success;
523                                 bmmask <<= bmradix;
524                         }
525                 }
526                 /*fragments might remain*/
527                 /*KKASSERT(bmap->avail == 0);*/
528                 return (ENOSPC);
529 success:
530                 offset = i * (HAMMER2_SEGSIZE / 8) +
531                          (j * (HAMMER2_FREEMAP_BLOCK_SIZE / 2));
532                 if (size & HAMMER2_FREEMAP_BLOCK_MASK)
533                         bmap->linear = offset + size;
534         }
535
536         KKASSERT(i >= 0 && i < 8);      /* 8 x 16 -> 128 x 16K -> 2MB */
537
538         /*
539          * Optimize the buffer cache to avoid unnecessary read-before-write
540          * operations.
541          *
542          * The device block size could be larger than the allocation size
543          * so the actual bitmap test is somewhat more involved.  We have
544          * to use a compatible buffer size for this operation.
545          */
546         if (radix < HAMMER2_MINIORADIX && (bmap->bitmap[i] & bmmask) == 0) {
547                 size_t psize = hammer2_devblksize(size);
548                 hammer2_off_t pmask = (hammer2_off_t)psize - 1;
549                 int pbmradix = 2 << (hammer2_devblkradix(radix) -
550                                      HAMMER2_FREEMAP_BLOCK_RADIX);
551                 uint32_t pbmmask;
552
553                 pbmmask = (pbmradix == 32) ? 0xFFFFFFFFU : (1 << pbmradix) - 1;
554                 while ((pbmmask & bmmask) == 0)
555                         pbmmask <<= pbmradix;
556
557                 if ((bmap->bitmap[i] & pbmmask) == 0) {
558                         bp = getblk(hmp->devvp, *basep + (offset & ~pmask),
559                                     psize, GETBLK_NOWAIT, 0);
560                         if (bp) {
561                                 if ((bp->b_flags & B_CACHE) == 0)
562                                         vfs_bio_clrbuf(bp);
563                                 bqrelse(bp);
564                         }
565                 }
566         }
567
568 #if 0
569         /*
570          * When initializing a new inode segment also attempt to initialize
571          * an adjacent segment.  Be careful not to index beyond the array
572          * bounds.
573          *
574          * We do this to try to localize inode accesses to improve
575          * directory scan rates.  XXX doesn't improve scan rates.
576          */
577         if (size == HAMMER2_INODE_BYTES) {
578                 if (n & 1) {
579                         if (bmap[-1].radix == 0 && bmap[-1].avail)
580                                 bmap[-1].radix = radix;
581                 } else {
582                         if (bmap[1].radix == 0 && bmap[1].avail)
583                                 bmap[1].radix = radix;
584                 }
585         }
586 #endif
587
588         /*
589          * Adjust the linear iterator, set the radix if necessary (might as
590          * well just set it unconditionally), adjust *basep to return the
591          * allocated data offset.
592          */
593         bmap->bitmap[i] |= bmmask;
594         bmap->class = class;
595         bmap->avail -= size;
596         *basep += offset;
597
598         return(0);
599 }
600
601 static
602 void
603 hammer2_freemap_init(hammer2_trans_t *trans, hammer2_mount_t *hmp,
604                      hammer2_key_t key, hammer2_chain_t *chain)
605 {
606         hammer2_off_t l1size;
607         hammer2_off_t lokey;
608         hammer2_off_t hikey;
609         hammer2_bmap_data_t *bmap;
610         int count;
611
612         l1size = H2FMSHIFT(HAMMER2_FREEMAP_LEVEL1_RADIX);
613
614         /*
615          * Calculate the portion of the 2GB map that should be initialized
616          * as free.  Portions below or after will be initialized as allocated.
617          * SEGMASK-align the areas so we don't have to worry about sub-scans
618          * or endianess when using memset.
619          *
620          * (1) Ensure that all statically allocated space from newfs_hammer2
621          *     is marked allocated.
622          *
623          * (2) Ensure that the reserved area is marked allocated (typically
624          *     the first 4MB of the 2GB area being represented).
625          *
626          * (3) Ensure that any trailing space at the end-of-volume is marked
627          *     allocated.
628          *
629          * WARNING! It is possible for lokey to be larger than hikey if the
630          *          entire 2GB segment is within the static allocation.
631          */
632         lokey = (hmp->voldata.allocator_beg + HAMMER2_SEGMASK64) &
633                 ~HAMMER2_SEGMASK64;
634
635         if (lokey < H2FMBASE(key, HAMMER2_FREEMAP_LEVEL1_RADIX) +
636                   HAMMER2_ZONE_SEG64) {
637                 lokey = H2FMBASE(key, HAMMER2_FREEMAP_LEVEL1_RADIX) +
638                         HAMMER2_ZONE_SEG64;
639         }
640
641         hikey = key + H2FMSHIFT(HAMMER2_FREEMAP_LEVEL1_RADIX);
642         if (hikey > hmp->voldata.volu_size) {
643                 hikey = hmp->voldata.volu_size & ~HAMMER2_SEGMASK64;
644         }
645
646         chain->bref.check.freemap.avail =
647                 H2FMSHIFT(HAMMER2_FREEMAP_LEVEL1_RADIX);
648         bmap = &chain->data->bmdata[0];
649
650         for (count = 0; count < HAMMER2_FREEMAP_COUNT; ++count) {
651                 if (key < lokey || key >= hikey) {
652                         memset(bmap->bitmap, -1,
653                                sizeof(bmap->bitmap));
654                         bmap->avail = 0;
655                         chain->bref.check.freemap.avail -=
656                                 H2FMSHIFT(HAMMER2_FREEMAP_LEVEL0_RADIX);
657                 } else {
658                         bmap->avail = H2FMSHIFT(HAMMER2_FREEMAP_LEVEL0_RADIX);
659                 }
660                 key += H2FMSHIFT(HAMMER2_FREEMAP_LEVEL0_RADIX);
661                 ++bmap;
662         }
663 }
664
665 /*
666  * The current Level 1 freemap has been exhausted, iterate to the next
667  * one, return ENOSPC if no freemaps remain.
668  *
669  * XXX this should rotate back to the beginning to handle freed-up space
670  * XXX or use intermediate entries to locate free space. TODO
671  */
672 static int
673 hammer2_freemap_iterate(hammer2_trans_t *trans, hammer2_chain_t **parentp,
674                         hammer2_chain_t **chainp, hammer2_fiterate_t *iter)
675 {
676         hammer2_mount_t *hmp = (*parentp)->hmp;
677
678         iter->bnext &= ~(H2FMSHIFT(HAMMER2_FREEMAP_LEVEL1_RADIX) - 1);
679         iter->bnext += H2FMSHIFT(HAMMER2_FREEMAP_LEVEL1_RADIX);
680         if (iter->bnext >= hmp->voldata.volu_size) {
681                 iter->bnext = 0;
682                 if (++iter->loops == 2)
683                         return (ENOSPC);
684         }
685         return(EAGAIN);
686 }
687
688 /*
689  * Free the specified blockref.  This code is only able to fully free
690  * blocks when (how) is non-zero, otherwise the block is marked for
691  * the bulk freeing pass to check.
692  *
693  * Normal use is to only mark inodes as possibly being free.  The underlying
694  * file blocks are not necessarily marked.  The bulk freescan can
695  * theoretically handle the case.
696  *
697  * XXX currently disabled when how == 0 (the normal real-time case).  At
698  * the moment we depend on the bulk freescan to actually free blocks.  It
699  * will still call this routine with a non-zero how to stage possible frees
700  * and to do the actual free.
701  */
702 void
703 hammer2_freemap_free(hammer2_trans_t *trans, hammer2_mount_t *hmp,
704                      hammer2_blockref_t *bref, int how)
705 {
706         hammer2_off_t data_off = bref->data_off;
707         hammer2_chain_t *chain;
708         hammer2_chain_t *parent;
709         hammer2_bmap_data_t *bmap;
710         hammer2_key_t key;
711         hammer2_off_t l0size;
712         hammer2_off_t l1size;
713         hammer2_off_t l1mask;
714         uint32_t *bitmap;
715         const uint32_t bmmask00 = 0;
716         uint32_t bmmask01;
717         uint32_t bmmask10;
718         uint32_t bmmask11;
719         size_t bytes;
720         uint16_t class;
721         int radix;
722         int start;
723         int count;
724         int modified = 0;
725
726         radix = (int)data_off & HAMMER2_OFF_MASK_RADIX;
727         data_off &= ~HAMMER2_OFF_MASK_RADIX;
728         KKASSERT(radix <= HAMMER2_MAX_RADIX);
729
730         bytes = (size_t)1 << radix;
731         class = (bref->type << 8) | hammer2_devblkradix(radix);
732
733         /*
734          * Lookup the level1 freemap chain.  The chain must exist.
735          */
736         key = H2FMBASE(data_off, HAMMER2_FREEMAP_LEVEL1_RADIX);
737         l0size = H2FMSHIFT(HAMMER2_FREEMAP_LEVEL0_RADIX);
738         l1size = H2FMSHIFT(HAMMER2_FREEMAP_LEVEL1_RADIX);
739         l1mask = l1size - 1;
740
741         parent = &hmp->fchain;
742         hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS);
743
744         chain = hammer2_chain_lookup(&parent, key, key + l1mask,
745                                      HAMMER2_LOOKUP_FREEMAP |
746                                      HAMMER2_LOOKUP_ALWAYS |
747                                      HAMMER2_LOOKUP_MATCHIND/*XXX*/);
748         if (chain == NULL) {
749                 kprintf("hammer2_freemap_free: %016jx: no chain\n",
750                         (intmax_t)bref->data_off);
751                 hammer2_chain_unlock(parent);
752                 return;
753         }
754         KKASSERT(chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF);
755
756         /*
757          * Find the bmap entry (covering a 2MB swath)
758          * Find the bitmap array index
759          * Find the bitmap bit index (runs in 2-bit pairs)
760          */
761         bmap = &chain->data->bmdata[(int)(data_off >> HAMMER2_SEGRADIX) &
762                                     (HAMMER2_FREEMAP_COUNT - 1)];
763         bitmap = &bmap->bitmap[(int)(data_off >> (HAMMER2_SEGRADIX - 3)) & 7];
764
765         start = ((int)(data_off >> HAMMER2_FREEMAP_BLOCK_RADIX) & 15) * 2;
766         bmmask01 = 1 << start;
767         bmmask10 = 2 << start;
768         bmmask11 = 3 << start;
769
770         /*
771          * Fixup the bitmap
772          */
773         if (radix < HAMMER2_FREEMAP_BLOCK_RADIX) {
774                 count = 1;
775                 how = 0;        /* partial block, cannot set to 00 */
776         } else {
777                 count = 1 << (radix - HAMMER2_FREEMAP_BLOCK_RADIX);
778         }
779
780         while (count) {
781                 KKASSERT(bmmask11);
782                 KKASSERT((*bitmap & bmmask11) != bmmask00);
783                 if ((*bitmap & bmmask11) == bmmask11) {
784                         if (!modified) {
785                                 hammer2_chain_modify(trans, &chain, 0);
786                                 modified = 1;
787         bmap = &chain->data->bmdata[(int)(data_off >> HAMMER2_SEGRADIX) &
788                                     (HAMMER2_FREEMAP_COUNT - 1)];
789         bitmap = &bmap->bitmap[(int)(data_off >> (HAMMER2_SEGRADIX - 3)) & 7];
790                         }
791                         if (how)
792                                 *bitmap &= ~bmmask11;
793                         else
794                                 *bitmap = (*bitmap & ~bmmask11) | bmmask10;
795                 } else if ((*bitmap & bmmask11) == bmmask10) {
796                         if (how) {
797                                 if (!modified) {
798                                         hammer2_chain_modify(trans, &chain, 0);
799                                         modified = 1;
800         bmap = &chain->data->bmdata[(int)(data_off >> HAMMER2_SEGRADIX) &
801                                     (HAMMER2_FREEMAP_COUNT - 1)];
802         bitmap = &bmap->bitmap[(int)(data_off >> (HAMMER2_SEGRADIX - 3)) & 7];
803                                 }
804                                 *bitmap &= ~bmmask11;
805                         }
806                 } else if ((*bitmap & bmmask11) == bmmask01) {
807                         KKASSERT(0);
808                 }
809                 --count;
810                 bmmask01 <<= 2;
811                 bmmask10 <<= 2;
812                 bmmask11 <<= 2;
813         }
814         if (how && modified) {
815                 bmap->avail += 1 << radix;
816                 KKASSERT(bmap->avail <= HAMMER2_SEGSIZE);
817                 if (bmap->avail == HAMMER2_SEGSIZE &&
818                     bmap->bitmap[0] == 0 &&
819                     bmap->bitmap[1] == 0 &&
820                     bmap->bitmap[2] == 0 &&
821                     bmap->bitmap[3] == 0 &&
822                     bmap->bitmap[4] == 0 &&
823                     bmap->bitmap[5] == 0 &&
824                     bmap->bitmap[6] == 0 &&
825                     bmap->bitmap[7] == 0) {
826                         key = H2FMBASE(data_off, HAMMER2_FREEMAP_LEVEL0_RADIX);
827                         kprintf("Freeseg %016jx\n", (intmax_t)key);
828                         bmap->class = 0;
829                 }
830         }
831
832         /*
833          * chain->bref.check.freemap.bigmask (XXX)
834          */
835         if (modified)
836                 chain->bref.check.freemap.bigmask |= 1 << radix;
837
838         hammer2_chain_unlock(chain);
839         hammer2_chain_unlock(parent);
840 }