hammer2 - Refactor reserved block selection in freemap code
[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_trans_t *trans, hammer2_chain_t *chain,
91                         int radix)
92 {
93         hammer2_blockref_t *bref = &chain->bref;
94         hammer2_off_t off;
95         int index;
96         size_t bytes;
97
98         /*
99          * Physical allocation size -> radix.  Typically either 256 for
100          * a level 0 freemap leaf or 65536 for a level N freemap node.
101          *
102          * NOTE: A 256 byte bitmap represents 256 x 8 x 1024 = 2MB of storage.
103          *       Do not use hammer2_allocsize() here as it has a min cap.
104          */
105         bytes = 1 << radix;
106
107         /*
108          * Calculate block selection index 0..7 of current block.
109          */
110         if ((bref->data_off & ~HAMMER2_OFF_MASK_RADIX) == 0) {
111                 index = 0;
112         } else {
113                 off = bref->data_off & ~HAMMER2_OFF_MASK_RADIX &
114                       (((hammer2_off_t)1 << HAMMER2_FREEMAP_LEVEL1_RADIX) - 1);
115                 off = off / HAMMER2_PBUFSIZE;
116                 KKASSERT(off >= HAMMER2_ZONE_FREEMAP_00 &&
117                          off < HAMMER2_ZONE_FREEMAP_END);
118                 index = (int)(off - HAMMER2_ZONE_FREEMAP_00) / 4;
119                 KKASSERT(index >= 0 && index < HAMMER2_ZONE_FREEMAP_COPIES);
120         }
121
122         /*
123          * Calculate new index (our 'allocation').  We have to be careful
124          * here as there can be two different transaction ids running
125          * concurrently when a flush is in-progress.
126          *
127          * We also want to make sure, for algorithmic repeatability, that
128          * the index sequences are monotonic with transaction ids.  Some
129          * skipping is allowed as long as we ensure that all four volume
130          * header backups have consistent freemaps.
131          *
132          * FLUSH  NORMAL FLUSH  NORMAL FLUSH  NORMAL FLUSH  NORMAL
133          * N+=1   N+=2
134          * (0->1) (1->3) (3->4) (4->6) (6->7) (7->9) (9->10) (10->12)
135          *
136          * [-concurrent-][-concurrent-][-concurrent-][-concurrent-]
137          *
138          * (alternative first NORMAL might be 0->2 if flush had not yet
139          *  modified the chain, this is the worst case).
140          */
141         if ((trans->flags & HAMMER2_TRANS_ISFLUSH) == 0) {
142                 /*
143                  * Normal transactions always run with the highest TID.
144                  * But if a flush is in-progress we want to reserve a slot
145                  * for the flush with a lower TID running concurrently to
146                  * do a delete-duplicate.
147                  */
148                 index = (index + 2) % HAMMER2_ZONE_FREEMAP_COPIES;
149         } else if (trans->flags & HAMMER2_TRANS_ISALLOCATING) {
150                 /*
151                  * Flush transaction, hammer2_freemap.c itself is doing a
152                  * delete-duplicate during an allocation within the freemap.
153                  */
154                 index = (index + 1) % HAMMER2_ZONE_FREEMAP_COPIES;
155         } else {
156                 /*
157                  * Flush transaction, hammer2_flush.c is doing a
158                  * delete-duplicate on the freemap while flushing
159                  * hmp->fchain.
160                  */
161                 index = (index + 1) % HAMMER2_ZONE_FREEMAP_COPIES;
162         }
163
164         /*
165          * Calculate the block offset of the reserved block.  This will
166          * point into the 4MB reserved area at the base of the appropriate
167          * 2GB zone, once added to the FREEMAP_x selection above.
168          */
169         switch(bref->keybits) {
170         /* case HAMMER2_FREEMAP_LEVEL5_RADIX: not applicable */
171         case HAMMER2_FREEMAP_LEVEL4_RADIX:      /* 2EB */
172                 KKASSERT(bref->type == HAMMER2_BREF_TYPE_FREEMAP_NODE);
173                 KKASSERT(bytes == HAMMER2_FREEMAP_LEVELN_PSIZE);
174                 off = H2FMBASE(bref->key, HAMMER2_FREEMAP_LEVEL4_RADIX) +
175                       (index * 4 + HAMMER2_ZONEFM_LEVEL4) * HAMMER2_PBUFSIZE;
176                 break;
177         case HAMMER2_FREEMAP_LEVEL3_RADIX:      /* 2PB */
178                 KKASSERT(bref->type == HAMMER2_BREF_TYPE_FREEMAP_NODE);
179                 KKASSERT(bytes == HAMMER2_FREEMAP_LEVELN_PSIZE);
180                 off = H2FMBASE(bref->key, HAMMER2_FREEMAP_LEVEL3_RADIX) +
181                       (index * 4 + HAMMER2_ZONEFM_LEVEL3) * HAMMER2_PBUFSIZE;
182                 break;
183         case HAMMER2_FREEMAP_LEVEL2_RADIX:      /* 2TB */
184                 KKASSERT(bref->type == HAMMER2_BREF_TYPE_FREEMAP_NODE);
185                 KKASSERT(bytes == HAMMER2_FREEMAP_LEVELN_PSIZE);
186                 off = H2FMBASE(bref->key, HAMMER2_FREEMAP_LEVEL2_RADIX) +
187                       (index * 4 + HAMMER2_ZONEFM_LEVEL2) * HAMMER2_PBUFSIZE;
188                 break;
189         case HAMMER2_FREEMAP_LEVEL1_RADIX:      /* 2GB */
190                 KKASSERT(bref->type == HAMMER2_BREF_TYPE_FREEMAP_LEAF);
191                 KKASSERT(bytes == HAMMER2_FREEMAP_LEVELN_PSIZE);
192                 off = H2FMBASE(bref->key, HAMMER2_FREEMAP_LEVEL1_RADIX) +
193                       (index * 4 + HAMMER2_ZONEFM_LEVEL1) * HAMMER2_PBUFSIZE;
194                 break;
195         default:
196                 panic("freemap: bad radix(2) %p %d\n", bref, bref->keybits);
197                 /* NOT REACHED */
198                 off = (hammer2_off_t)-1;
199                 break;
200         }
201         bref->data_off = off | radix;
202 #if 0
203         kprintf("-> %016jx\n", bref->data_off);
204 #endif
205         return (0);
206 }
207
208 /*
209  * Normal freemap allocator
210  *
211  * Use available hints to allocate space using the freemap.  Create missing
212  * freemap infrastructure on-the-fly as needed (including marking initial
213  * allocations using the iterator as allocated, instantiating new 2GB zones,
214  * and dealing with the end-of-media edge case).
215  *
216  * ip and bpref are only used as a heuristic to determine locality of
217  * reference.  bref->key may also be used heuristically.
218  *
219  * WARNING! When called from a flush we have to use the 'live' sync_tid
220  *          and not the flush sync_tid.  The live sync_tid is the flush
221  *          sync_tid + 1.  That is, freemap allocations which occur during
222  *          a flush are not part of the flush.  Crash-recovery will restore
223  *          any lost allocations.
224  */
225 int
226 hammer2_freemap_alloc(hammer2_trans_t *trans, hammer2_chain_t *chain,
227                       size_t bytes)
228 {
229         hammer2_mount_t *hmp = chain->hmp;
230         hammer2_blockref_t *bref = &chain->bref;
231         hammer2_chain_t *parent;
232         int radix;
233         int error;
234         unsigned int hindex;
235         hammer2_fiterate_t iter;
236
237         /*
238          * Validate the allocation size.  It must be a power of 2.
239          *
240          * For now require that the caller be aware of the minimum
241          * allocation (1K).
242          */
243         radix = hammer2_getradix(bytes);
244         KKASSERT((size_t)1 << radix == bytes);
245
246         /*
247          * Freemap blocks themselves are simply assigned from the reserve
248          * area, not allocated from the freemap.
249          */
250         if (bref->type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
251             bref->type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
252                 return (hammer2_freemap_reserve(trans, chain, radix));
253         }
254
255         /*
256          * Mark previously allocated block as possibly freeable.  There might
257          * be snapshots and other races so we can't just mark it fully free.
258          * (XXX optimize this for the current-transaction create+delete case)
259          */
260         if (bref->data_off & ~HAMMER2_OFF_MASK_RADIX) {
261                 hammer2_freemap_adjust(trans, hmp, bref,
262                                        HAMMER2_FREEMAP_DOMAYFREE);
263         }
264
265         /*
266          * Setting ISALLOCATING ensures correct operation even when the
267          * flusher itself is making allocations.
268          */
269         KKASSERT(bytes >= HAMMER2_MIN_ALLOC && bytes <= HAMMER2_MAX_ALLOC);
270         KKASSERT((trans->flags & HAMMER2_TRANS_ISALLOCATING) == 0);
271         atomic_set_int(&trans->flags, HAMMER2_TRANS_ISALLOCATING);
272         if (trans->flags & HAMMER2_TRANS_ISFLUSH)
273                 ++trans->sync_tid;
274
275         /*
276          * Calculate the starting point for our allocation search.
277          *
278          * Each freemap leaf is dedicated to a specific freemap_radix.
279          * The freemap_radix can be more fine-grained than the device buffer
280          * radix which results in inodes being grouped together in their
281          * own segment, terminal-data (16K or less) and initial indirect
282          * block being grouped together, and then full-indirect and full-data
283          * blocks (64K) being grouped together.
284          *
285          * The single most important aspect of this is the inode grouping
286          * because that is what allows 'find' and 'ls' and other filesystem
287          * topology operations to run fast.
288          */
289 #if 0
290         if (bref->data_off & ~HAMMER2_OFF_MASK_RADIX)
291                 bpref = bref->data_off & ~HAMMER2_OFF_MASK_RADIX;
292         else if (trans->tmp_bpref)
293                 bpref = trans->tmp_bpref;
294         else if (trans->tmp_ip)
295                 bpref = trans->tmp_ip->chain->bref.data_off;
296         else
297 #endif
298         /*
299          * Heuristic tracking index.  We would like one for each distinct
300          * bref type if possible.  heur_freemap[] has room for two classes
301          * for each type.  At a minimum we have to break-up our heuristic
302          * by device block sizes.
303          */
304         hindex = hammer2_devblkradix(radix) - HAMMER2_MINIORADIX;
305         KKASSERT(hindex < HAMMER2_FREEMAP_HEUR_NRADIX);
306         hindex += bref->type * HAMMER2_FREEMAP_HEUR_NRADIX;
307         hindex &= HAMMER2_FREEMAP_HEUR_TYPES * HAMMER2_FREEMAP_HEUR_NRADIX - 1;
308         KKASSERT(hindex < HAMMER2_FREEMAP_HEUR);
309
310         iter.bpref = hmp->heur_freemap[hindex];
311
312         /*
313          * Make sure bpref is in-bounds.  It's ok if bpref covers a zone's
314          * reserved area, the try code will iterate past it.
315          */
316         if (iter.bpref > hmp->voldata.volu_size)
317                 iter.bpref = hmp->voldata.volu_size - 1;
318
319         /*
320          * Iterate the freemap looking for free space before and after.
321          */
322         parent = &hmp->fchain;
323         hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS);
324         error = EAGAIN;
325         iter.bnext = iter.bpref;
326         iter.loops = 0;
327
328         while (error == EAGAIN) {
329                 error = hammer2_freemap_try_alloc(trans, &parent, bref,
330                                                   radix, &iter);
331         }
332         hmp->heur_freemap[hindex] = iter.bnext;
333         hammer2_chain_unlock(parent);
334
335         atomic_clear_int(&trans->flags, HAMMER2_TRANS_ISALLOCATING);
336         if (trans->flags & HAMMER2_TRANS_ISFLUSH)
337                 --trans->sync_tid;
338
339         return (error);
340 }
341
342 static int
343 hammer2_freemap_try_alloc(hammer2_trans_t *trans, hammer2_chain_t **parentp,
344                           hammer2_blockref_t *bref, int radix,
345                           hammer2_fiterate_t *iter)
346 {
347         hammer2_mount_t *hmp = (*parentp)->hmp;
348         hammer2_off_t l0size;
349         hammer2_off_t l1size;
350         hammer2_off_t l1mask;
351         hammer2_key_t key_dummy;
352         hammer2_chain_t *chain;
353         hammer2_off_t key;
354         size_t bytes;
355         uint16_t class;
356         int error = 0;
357         int cache_index = -1;
358
359
360         /*
361          * Calculate the number of bytes being allocated, the number
362          * of contiguous bits of bitmap being allocated, and the bitmap
363          * mask.
364          *
365          * WARNING! cpu hardware may mask bits == 64 -> 0 and blow up the
366          *          mask calculation.
367          */
368         bytes = (size_t)1 << radix;
369         class = (bref->type << 8) | hammer2_devblkradix(radix);
370
371         /*
372          * Lookup the level1 freemap chain, creating and initializing one
373          * if necessary.  Intermediate levels will be created automatically
374          * when necessary by hammer2_chain_create().
375          */
376         key = H2FMBASE(iter->bnext, HAMMER2_FREEMAP_LEVEL1_RADIX);
377         l0size = H2FMSHIFT(HAMMER2_FREEMAP_LEVEL0_RADIX);
378         l1size = H2FMSHIFT(HAMMER2_FREEMAP_LEVEL1_RADIX);
379         l1mask = l1size - 1;
380
381         chain = hammer2_chain_lookup(parentp, &key_dummy, key, key + l1mask,
382                                      &cache_index,
383                                      HAMMER2_LOOKUP_ALWAYS |
384                                      HAMMER2_LOOKUP_MATCHIND);
385
386         if (chain == NULL) {
387                 /*
388                  * Create the missing leaf, be sure to initialize
389                  * the auxillary freemap tracking information in
390                  * the bref.check.freemap structure.
391                  */
392 #if 0
393                 kprintf("freemap create L1 @ %016jx bpref %016jx\n",
394                         key, iter->bpref);
395 #endif
396                 error = hammer2_chain_create(trans, parentp, &chain,
397                                      key, HAMMER2_FREEMAP_LEVEL1_RADIX,
398                                      HAMMER2_BREF_TYPE_FREEMAP_LEAF,
399                                      HAMMER2_FREEMAP_LEVELN_PSIZE);
400                 KKASSERT(error == 0);
401                 if (error == 0) {
402                         hammer2_chain_modify(trans, &chain, 0);
403                         bzero(&chain->data->bmdata[0],
404                               HAMMER2_FREEMAP_LEVELN_PSIZE);
405                         chain->bref.check.freemap.bigmask = (uint32_t)-1;
406                         chain->bref.check.freemap.avail = l1size;
407                         /* bref.methods should already be inherited */
408
409                         hammer2_freemap_init(trans, hmp, key, chain);
410                 }
411         } else if ((chain->bref.check.freemap.bigmask & (1 << radix)) == 0) {
412                 /*
413                  * Already flagged as not having enough space
414                  */
415                 error = ENOSPC;
416         } else {
417                 /*
418                  * Modify existing chain to setup for adjustment.
419                  */
420                 hammer2_chain_modify(trans, &chain, 0);
421         }
422
423         /*
424          * Scan 2MB entries.
425          */
426         if (error == 0) {
427                 hammer2_bmap_data_t *bmap;
428                 hammer2_key_t base_key;
429                 int count;
430                 int start;
431                 int n;
432
433                 KKASSERT(chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF);
434                 start = (int)((iter->bnext - key) >>
435                               HAMMER2_FREEMAP_LEVEL0_RADIX);
436                 KKASSERT(start >= 0 && start < HAMMER2_FREEMAP_COUNT);
437                 hammer2_chain_modify(trans, &chain, 0);
438
439                 error = ENOSPC;
440                 for (count = 0; count < HAMMER2_FREEMAP_COUNT; ++count) {
441                         if (start + count >= HAMMER2_FREEMAP_COUNT &&
442                             start - count < 0) {
443                                 break;
444                         }
445                         n = start + count;
446                         bmap = &chain->data->bmdata[n];
447                         if (n < HAMMER2_FREEMAP_COUNT && bmap->avail &&
448                             (bmap->class == 0 || bmap->class == class)) {
449                                 base_key = key + n * l0size;
450                                 error = hammer2_bmap_alloc(trans, hmp, bmap,
451                                                            class, n, radix,
452                                                            &base_key);
453                                 if (error != ENOSPC) {
454                                         key = base_key;
455                                         break;
456                                 }
457                         }
458                         n = start - count;
459                         bmap = &chain->data->bmdata[n];
460                         if (n >= 0 && bmap->avail &&
461                             (bmap->class == 0 || bmap->class == class)) {
462                                 base_key = key + n * l0size;
463                                 error = hammer2_bmap_alloc(trans, hmp, bmap,
464                                                            class, n, radix,
465                                                            &base_key);
466                                 if (error != ENOSPC) {
467                                         key = base_key;
468                                         break;
469                                 }
470                         }
471                 }
472                 if (error == ENOSPC)
473                         chain->bref.check.freemap.bigmask &= ~(1 << radix);
474                 /* XXX also scan down from original count */
475         }
476
477         if (error == 0) {
478                 /*
479                  * Assert validity.  Must be beyond the static allocator used
480                  * by newfs_hammer2 (and thus also beyond the aux area),
481                  * not go past the volume size, and must not be in the
482                  * reserved segment area for a zone.
483                  */
484                 KKASSERT(key >= hmp->voldata.allocator_beg &&
485                          key + bytes <= hmp->voldata.volu_size);
486                 KKASSERT((key & HAMMER2_ZONE_MASK64) >= HAMMER2_ZONE_SEG);
487                 bref->data_off = key | radix;
488
489 #if 0
490                 kprintf("alloc cp=%p %016jx %016jx using %016jx\n",
491                         chain,
492                         bref->key, bref->data_off, chain->bref.data_off);
493 #endif
494         } else if (error == ENOSPC) {
495                 /*
496                  * Return EAGAIN with next iteration in iter->bnext, or
497                  * return ENOSPC if the allocation map has been exhausted.
498                  */
499                 error = hammer2_freemap_iterate(trans, parentp, &chain, iter);
500         }
501
502         /*
503          * Cleanup
504          */
505         if (chain)
506                 hammer2_chain_unlock(chain);
507         return (error);
508 }
509
510 /*
511  * Allocate (1<<radix) bytes from the bmap whos base data offset is (*basep).
512  *
513  * If the linear iterator is mid-block we use it directly (the bitmap should
514  * already be marked allocated), otherwise we search for a block in the bitmap
515  * that fits the allocation request.
516  *
517  * A partial bitmap allocation sets the minimum bitmap granularity (16KB)
518  * to fully allocated and adjusts the linear allocator to allow the
519  * remaining space to be allocated.
520  */
521 static
522 int
523 hammer2_bmap_alloc(hammer2_trans_t *trans, hammer2_mount_t *hmp,
524                    hammer2_bmap_data_t *bmap,
525                    uint16_t class, int n, int radix, hammer2_key_t *basep)
526 {
527         hammer2_io_t *dio;
528         size_t size;
529         size_t bsize;
530         int bmradix;
531         uint32_t bmmask;
532         int offset;
533         int error;
534         int i;
535         int j;
536
537         /*
538          * Take into account 2-bits per block when calculating bmradix.
539          */
540         size = (size_t)1 << radix;
541
542         if (radix <= HAMMER2_FREEMAP_BLOCK_RADIX) {
543                 bmradix = 2;
544                 bsize = HAMMER2_FREEMAP_BLOCK_SIZE;
545                 /* (16K) 2 bits per allocation block */
546         } else {
547                 bmradix = 2 << (radix - HAMMER2_FREEMAP_BLOCK_RADIX);
548                 bsize = size;
549                 /* (32K-256K) 4, 8, 16, 32 bits per allocation block */
550         }
551
552         /*
553          * Use the linear iterator to pack small allocations, otherwise
554          * fall-back to finding a free 16KB chunk.  The linear iterator
555          * is only valid when *NOT* on a freemap chunking boundary (16KB).
556          * If it is the bitmap must be scanned.  It can become invalid
557          * once we pack to the boundary.  We adjust it after a bitmap
558          * allocation only for sub-16KB allocations (so the perfectly good
559          * previous value can still be used for fragments when 16KB+
560          * allocations are made).
561          *
562          * Beware of hardware artifacts when bmradix == 32 (intermediate
563          * result can wind up being '1' instead of '0' if hardware masks
564          * bit-count & 31).
565          *
566          * NOTE: j needs to be even in the j= calculation.  As an artifact
567          *       of the /2 division, our bitmask has to clear bit 0.
568          *
569          * NOTE: TODO this can leave little unallocatable fragments lying
570          *       around.
571          */
572         if (((uint32_t)bmap->linear & HAMMER2_FREEMAP_BLOCK_MASK) + size <=
573             HAMMER2_FREEMAP_BLOCK_SIZE &&
574             (bmap->linear & HAMMER2_FREEMAP_BLOCK_MASK) &&
575             bmap->linear < HAMMER2_SEGSIZE) {
576                 KKASSERT(bmap->linear >= 0 &&
577                          bmap->linear + size <= HAMMER2_SEGSIZE &&
578                          (bmap->linear & (HAMMER2_MIN_ALLOC - 1)) == 0);
579                 offset = bmap->linear;
580                 i = offset / (HAMMER2_SEGSIZE / 8);
581                 j = (offset / (HAMMER2_FREEMAP_BLOCK_SIZE / 2)) & 30;
582                 bmmask = (bmradix == 32) ?
583                          0xFFFFFFFFU : (1 << bmradix) - 1;
584                 bmmask <<= j;
585                 bmap->linear = offset + size;
586         } else {
587                 for (i = 0; i < 8; ++i) {
588                         bmmask = (bmradix == 32) ?
589                                  0xFFFFFFFFU : (1 << bmradix) - 1;
590                         for (j = 0; j < 32; j += bmradix) {
591                                 if ((bmap->bitmap[i] & bmmask) == 0)
592                                         goto success;
593                                 bmmask <<= bmradix;
594                         }
595                 }
596                 /*fragments might remain*/
597                 /*KKASSERT(bmap->avail == 0);*/
598                 return (ENOSPC);
599 success:
600                 offset = i * (HAMMER2_SEGSIZE / 8) +
601                          (j * (HAMMER2_FREEMAP_BLOCK_SIZE / 2));
602                 if (size & HAMMER2_FREEMAP_BLOCK_MASK)
603                         bmap->linear = offset + size;
604         }
605
606         KKASSERT(i >= 0 && i < 8);      /* 8 x 16 -> 128 x 16K -> 2MB */
607
608         /*
609          * Optimize the buffer cache to avoid unnecessary read-before-write
610          * operations.
611          *
612          * The device block size could be larger than the allocation size
613          * so the actual bitmap test is somewhat more involved.  We have
614          * to use a compatible buffer size for this operation.
615          */
616         if ((bmap->bitmap[i] & bmmask) == 0 &&
617             hammer2_devblksize(size) != size) {
618                 size_t psize = hammer2_devblksize(size);
619                 hammer2_off_t pmask = (hammer2_off_t)psize - 1;
620                 int pbmradix = 2 << (hammer2_devblkradix(radix) -
621                                      HAMMER2_FREEMAP_BLOCK_RADIX);
622                 uint32_t pbmmask;
623                 int pradix = hammer2_getradix(psize);
624
625                 pbmmask = (pbmradix == 32) ? 0xFFFFFFFFU : (1 << pbmradix) - 1;
626                 while ((pbmmask & bmmask) == 0)
627                         pbmmask <<= pbmradix;
628
629 #if 0
630                 kprintf("%016jx mask %08x %08x %08x (%zd/%zd)\n",
631                         *basep + offset, bmap->bitmap[i],
632                         pbmmask, bmmask, size, psize);
633 #endif
634
635                 if ((bmap->bitmap[i] & pbmmask) == 0) {
636                         error = hammer2_io_newq(hmp,
637                                                 (*basep + (offset & ~pmask)) |
638                                                  pradix,
639                                                 psize, &dio);
640                         hammer2_io_bqrelse(&dio);
641                 }
642         }
643
644 #if 0
645         /*
646          * When initializing a new inode segment also attempt to initialize
647          * an adjacent segment.  Be careful not to index beyond the array
648          * bounds.
649          *
650          * We do this to try to localize inode accesses to improve
651          * directory scan rates.  XXX doesn't improve scan rates.
652          */
653         if (size == HAMMER2_INODE_BYTES) {
654                 if (n & 1) {
655                         if (bmap[-1].radix == 0 && bmap[-1].avail)
656                                 bmap[-1].radix = radix;
657                 } else {
658                         if (bmap[1].radix == 0 && bmap[1].avail)
659                                 bmap[1].radix = radix;
660                 }
661         }
662 #endif
663
664         /*
665          * Adjust the linear iterator, set the radix if necessary (might as
666          * well just set it unconditionally), adjust *basep to return the
667          * allocated data offset.
668          */
669         bmap->bitmap[i] |= bmmask;
670         bmap->class = class;
671         bmap->avail -= size;
672         *basep += offset;
673
674         hammer2_voldata_lock(hmp);
675         hmp->voldata.allocator_free -= size;  /* XXX */
676         hammer2_voldata_unlock(hmp, 1);
677
678         return(0);
679 }
680
681 static
682 void
683 hammer2_freemap_init(hammer2_trans_t *trans, hammer2_mount_t *hmp,
684                      hammer2_key_t key, hammer2_chain_t *chain)
685 {
686         hammer2_off_t l1size;
687         hammer2_off_t lokey;
688         hammer2_off_t hikey;
689         hammer2_bmap_data_t *bmap;
690         int count;
691
692         l1size = H2FMSHIFT(HAMMER2_FREEMAP_LEVEL1_RADIX);
693
694         /*
695          * Calculate the portion of the 2GB map that should be initialized
696          * as free.  Portions below or after will be initialized as allocated.
697          * SEGMASK-align the areas so we don't have to worry about sub-scans
698          * or endianess when using memset.
699          *
700          * (1) Ensure that all statically allocated space from newfs_hammer2
701          *     is marked allocated.
702          *
703          * (2) Ensure that the reserved area is marked allocated (typically
704          *     the first 4MB of the 2GB area being represented).
705          *
706          * (3) Ensure that any trailing space at the end-of-volume is marked
707          *     allocated.
708          *
709          * WARNING! It is possible for lokey to be larger than hikey if the
710          *          entire 2GB segment is within the static allocation.
711          */
712         lokey = (hmp->voldata.allocator_beg + HAMMER2_SEGMASK64) &
713                 ~HAMMER2_SEGMASK64;
714
715         if (lokey < H2FMBASE(key, HAMMER2_FREEMAP_LEVEL1_RADIX) +
716                   HAMMER2_ZONE_SEG64) {
717                 lokey = H2FMBASE(key, HAMMER2_FREEMAP_LEVEL1_RADIX) +
718                         HAMMER2_ZONE_SEG64;
719         }
720
721         hikey = key + H2FMSHIFT(HAMMER2_FREEMAP_LEVEL1_RADIX);
722         if (hikey > hmp->voldata.volu_size) {
723                 hikey = hmp->voldata.volu_size & ~HAMMER2_SEGMASK64;
724         }
725
726         chain->bref.check.freemap.avail =
727                 H2FMSHIFT(HAMMER2_FREEMAP_LEVEL1_RADIX);
728         bmap = &chain->data->bmdata[0];
729
730         for (count = 0; count < HAMMER2_FREEMAP_COUNT; ++count) {
731                 if (key < lokey || key >= hikey) {
732                         memset(bmap->bitmap, -1,
733                                sizeof(bmap->bitmap));
734                         bmap->avail = 0;
735                         bmap->linear = HAMMER2_SEGSIZE;
736                         chain->bref.check.freemap.avail -=
737                                 H2FMSHIFT(HAMMER2_FREEMAP_LEVEL0_RADIX);
738                 } else {
739                         bmap->avail = H2FMSHIFT(HAMMER2_FREEMAP_LEVEL0_RADIX);
740                 }
741                 key += H2FMSHIFT(HAMMER2_FREEMAP_LEVEL0_RADIX);
742                 ++bmap;
743         }
744 }
745
746 /*
747  * The current Level 1 freemap has been exhausted, iterate to the next
748  * one, return ENOSPC if no freemaps remain.
749  *
750  * XXX this should rotate back to the beginning to handle freed-up space
751  * XXX or use intermediate entries to locate free space. TODO
752  */
753 static int
754 hammer2_freemap_iterate(hammer2_trans_t *trans, hammer2_chain_t **parentp,
755                         hammer2_chain_t **chainp, hammer2_fiterate_t *iter)
756 {
757         hammer2_mount_t *hmp = (*parentp)->hmp;
758
759         iter->bnext &= ~(H2FMSHIFT(HAMMER2_FREEMAP_LEVEL1_RADIX) - 1);
760         iter->bnext += H2FMSHIFT(HAMMER2_FREEMAP_LEVEL1_RADIX);
761         if (iter->bnext >= hmp->voldata.volu_size) {
762                 iter->bnext = 0;
763                 if (++iter->loops == 2)
764                         return (ENOSPC);
765         }
766         return(EAGAIN);
767 }
768
769 /*
770  * Free the specified blockref.  This code is only able to fully free
771  * blocks when (how) is non-zero, otherwise the block is marked for
772  * the bulk freeing pass to check.
773  *
774  * Normal use is to only mark inodes as possibly being free.  The underlying
775  * file blocks are not necessarily marked.  The bulk freescan can
776  * theoretically handle the case.
777  *
778  * XXX currently disabled when how == 0 (the normal real-time case).  At
779  * the moment we depend on the bulk freescan to actually free blocks.  It
780  * will still call this routine with a non-zero how to stage possible frees
781  * and to do the actual free.
782  *
783  * WARNING! When called from a flush we have to use the 'live' sync_tid
784  *          and not the flush sync_tid.  The live sync_tid is the flush
785  *          sync_tid + 1.  That is, freemap allocations which occur during
786  *          a flush are not part of the flush.  Crash-recovery will restore
787  *          any lost allocations.
788  */
789 void
790 hammer2_freemap_adjust(hammer2_trans_t *trans, hammer2_mount_t *hmp,
791                        hammer2_blockref_t *bref, int how)
792 {
793         hammer2_off_t data_off = bref->data_off;
794         hammer2_chain_t *chain;
795         hammer2_chain_t *parent;
796         hammer2_bmap_data_t *bmap;
797         hammer2_key_t key;
798         hammer2_key_t key_dummy;
799         hammer2_off_t l0size;
800         hammer2_off_t l1size;
801         hammer2_off_t l1mask;
802         uint32_t *bitmap;
803         const uint32_t bmmask00 = 0;
804         uint32_t bmmask01;
805         uint32_t bmmask10;
806         uint32_t bmmask11;
807         size_t bytes;
808         uint16_t class;
809         int radix;
810         int start;
811         int count;
812         int modified = 0;
813         int cache_index = -1;
814         int error;
815
816         radix = (int)data_off & HAMMER2_OFF_MASK_RADIX;
817         data_off &= ~HAMMER2_OFF_MASK_RADIX;
818         KKASSERT(radix <= HAMMER2_MAX_RADIX);
819
820         bytes = (size_t)1 << radix;
821         class = (bref->type << 8) | hammer2_devblkradix(radix);
822
823         /*
824          * We can't adjust thre freemap for data allocations made by
825          * newfs_hammer2.
826          */
827         if (data_off < hmp->voldata.allocator_beg)
828                 return;
829
830         KKASSERT((data_off & HAMMER2_ZONE_MASK64) >= HAMMER2_ZONE_SEG);
831         KKASSERT((trans->flags & HAMMER2_TRANS_ISALLOCATING) == 0);
832         atomic_set_int(&trans->flags, HAMMER2_TRANS_ISALLOCATING);
833         if (trans->flags & HAMMER2_TRANS_ISFLUSH)
834                 ++trans->sync_tid;
835
836         /*
837          * Lookup the level1 freemap chain.  The chain must exist.
838          */
839         key = H2FMBASE(data_off, HAMMER2_FREEMAP_LEVEL1_RADIX);
840         l0size = H2FMSHIFT(HAMMER2_FREEMAP_LEVEL0_RADIX);
841         l1size = H2FMSHIFT(HAMMER2_FREEMAP_LEVEL1_RADIX);
842         l1mask = l1size - 1;
843
844         parent = &hmp->fchain;
845         hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS);
846
847         chain = hammer2_chain_lookup(&parent, &key_dummy, key, key + l1mask,
848                                      &cache_index,
849                                      HAMMER2_LOOKUP_ALWAYS |
850                                      HAMMER2_LOOKUP_MATCHIND);
851
852         /*
853          * Stop early if we are trying to free something but no leaf exists.
854          */
855         if (chain == NULL && how != HAMMER2_FREEMAP_DORECOVER) {
856                 kprintf("hammer2_freemap_adjust: %016jx: no chain\n",
857                         (intmax_t)bref->data_off);
858                 goto done;
859         }
860
861         /*
862          * Create any missing leaf(s) if we are doing a recovery (marking
863          * the block(s) as being allocated instead of being freed).  Be sure
864          * to initialize the auxillary freemap tracking info in the
865          * bref.check.freemap structure.
866          */
867         if (chain == NULL && how == HAMMER2_FREEMAP_DORECOVER) {
868                 error = hammer2_chain_create(trans, &parent, &chain,
869                                      key, HAMMER2_FREEMAP_LEVEL1_RADIX,
870                                      HAMMER2_BREF_TYPE_FREEMAP_LEAF,
871                                      HAMMER2_FREEMAP_LEVELN_PSIZE);
872
873                 if (hammer2_debug & 0x0040) {
874                         kprintf("fixup create chain %p %016jx:%d\n",
875                                 chain, chain->bref.key, chain->bref.keybits);
876                 }
877
878                 if (error == 0) {
879                         hammer2_chain_modify(trans, &chain, 0);
880                         bzero(&chain->data->bmdata[0],
881                               HAMMER2_FREEMAP_LEVELN_PSIZE);
882                         chain->bref.check.freemap.bigmask = (uint32_t)-1;
883                         chain->bref.check.freemap.avail = l1size;
884                         /* bref.methods should already be inherited */
885
886                         hammer2_freemap_init(trans, hmp, key, chain);
887                 }
888                 /* XXX handle error */
889         }
890
891         /*
892          * Calculate the bitmask (runs in 2-bit pairs).
893          */
894         start = ((int)(data_off >> HAMMER2_FREEMAP_BLOCK_RADIX) & 15) * 2;
895         bmmask01 = 1 << start;
896         bmmask10 = 2 << start;
897         bmmask11 = 3 << start;
898
899         /*
900          * Fixup the bitmap.  Partial blocks cannot be fully freed unless
901          * a bulk scan is able to roll them up.
902          */
903         if (radix < HAMMER2_FREEMAP_BLOCK_RADIX) {
904                 count = 1;
905                 if (how == HAMMER2_FREEMAP_DOREALFREE)
906                         how = HAMMER2_FREEMAP_DOMAYFREE;
907         } else {
908                 count = 1 << (radix - HAMMER2_FREEMAP_BLOCK_RADIX);
909         }
910
911         /*
912          * [re]load the bmap and bitmap pointers.  Each bmap entry covers
913          * a 2MB swath.  The bmap itself (LEVEL1) covers 2GB.
914          */
915 again:
916         bmap = &chain->data->bmdata[(int)(data_off >> HAMMER2_SEGRADIX) &
917                                     (HAMMER2_FREEMAP_COUNT - 1)];
918         bitmap = &bmap->bitmap[(int)(data_off >> (HAMMER2_SEGRADIX - 3)) & 7];
919
920
921         while (count) {
922                 KKASSERT(bmmask11);
923                 if (how == HAMMER2_FREEMAP_DORECOVER) {
924                         /*
925                          * Recovery request, mark as allocated.
926                          */
927                         if ((*bitmap & bmmask11) != bmmask11) {
928                                 if (modified == 0) {
929                                         hammer2_chain_modify(trans, &chain, 0);
930                                         modified = 1;
931                                         goto again;
932                                 }
933                                 if ((*bitmap & bmmask11) == bmmask00)
934                                         bmap->avail -= 1 << radix;
935                                 if (bmap->class == 0)
936                                         bmap->class = class;
937                                 *bitmap |= bmmask11;
938                                 if (hammer2_debug & 0x0040) {
939                                         kprintf("hammer2_freemap_recover: "
940                                                 "fixup type=%02x "
941                                                 "block=%016jx/%zd\n",
942                                                 bref->type, data_off, bytes);
943                                 }
944                         } else {
945                                 /*
946                                 kprintf("hammer2_freemap_recover:  good "
947                                         "type=%02x block=%016jx/%zd\n",
948                                         bref->type, data_off, bytes);
949                                 */
950                         }
951                 } else if ((*bitmap & bmmask11) == bmmask11) {
952                         /*
953                          * Mayfree/Realfree request and bitmap is currently
954                          * marked as being fully allocated.
955                          */
956                         if (!modified) {
957                                 hammer2_chain_modify(trans, &chain, 0);
958                                 modified = 1;
959                                 goto again;
960                         }
961                         if (how == HAMMER2_FREEMAP_DOREALFREE)
962                                 *bitmap &= ~bmmask11;
963                         else
964                                 *bitmap = (*bitmap & ~bmmask11) | bmmask10;
965                 } else if ((*bitmap & bmmask11) == bmmask10) {
966                         /*
967                          * Mayfree/Realfree request and bitmap is currently
968                          * marked as being possibly freeable.
969                          */
970                         if (how == HAMMER2_FREEMAP_DOREALFREE) {
971                                 if (!modified) {
972                                         hammer2_chain_modify(trans, &chain, 0);
973                                         modified = 1;
974                                         goto again;
975                                 }
976                                 *bitmap &= ~bmmask11;
977                         }
978                 } else {
979                         /*
980                          * 01 - Not implemented, currently illegal state
981                          * 00 - Not allocated at all, illegal free.
982                          */
983                         panic("hammer2_freemap_adjust: "
984                               "Illegal state %08x(%08x)",
985                               *bitmap, *bitmap & bmmask11);
986                 }
987                 --count;
988                 bmmask01 <<= 2;
989                 bmmask10 <<= 2;
990                 bmmask11 <<= 2;
991         }
992         if (how == HAMMER2_FREEMAP_DOREALFREE && modified) {
993                 bmap->avail += 1 << radix;
994                 KKASSERT(bmap->avail <= HAMMER2_SEGSIZE);
995                 if (bmap->avail == HAMMER2_SEGSIZE &&
996                     bmap->bitmap[0] == 0 &&
997                     bmap->bitmap[1] == 0 &&
998                     bmap->bitmap[2] == 0 &&
999                     bmap->bitmap[3] == 0 &&
1000                     bmap->bitmap[4] == 0 &&
1001                     bmap->bitmap[5] == 0 &&
1002                     bmap->bitmap[6] == 0 &&
1003                     bmap->bitmap[7] == 0) {
1004                         key = H2FMBASE(data_off, HAMMER2_FREEMAP_LEVEL0_RADIX);
1005                         kprintf("Freeseg %016jx\n", (intmax_t)key);
1006                         bmap->class = 0;
1007                 }
1008         }
1009
1010         /*
1011          * chain->bref.check.freemap.bigmask (XXX)
1012          *
1013          * Setting bigmask is a hint to the allocation code that there might
1014          * be something allocatable.  We also set this in recovery... it
1015          * doesn't hurt and we might want to use the hint for other validation
1016          * operations later on.
1017          */
1018         if (modified)
1019                 chain->bref.check.freemap.bigmask |= 1 << radix;
1020
1021         hammer2_chain_unlock(chain);
1022 done:
1023         hammer2_chain_unlock(parent);
1024         atomic_clear_int(&trans->flags, HAMMER2_TRANS_ISALLOCATING);
1025         if (trans->flags & HAMMER2_TRANS_ISFLUSH)
1026                 --trans->sync_tid;
1027 }