hammer2 - revamp comments
[dragonfly.git] / sys / vfs / hammer2 / hammer2_bulkfree.c
1 /*
2  * Copyright (c) 2013-2015 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  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in
15  *    the documentation and/or other materials provided with the
16  *    distribution.
17  * 3. Neither the name of The DragonFly Project nor the names of its
18  *    contributors may be used to endorse or promote products derived
19  *    from this software without specific, prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
24  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
25  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
26  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
27  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
28  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
29  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
30  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
31  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34 #include <sys/param.h>
35 #include <sys/systm.h>
36 #include <sys/kernel.h>
37 #include <sys/fcntl.h>
38 #include <sys/buf.h>
39 #include <sys/proc.h>
40 #include <sys/namei.h>
41 #include <sys/mount.h>
42 #include <sys/vnode.h>
43 #include <sys/mountctl.h>
44 #include <vm/vm_kern.h>
45 #include <vm/vm_extern.h>
46
47 #include "hammer2.h"
48
49 #define H2FMBASE(key, radix)    ((key) & ~(((hammer2_off_t)1 << (radix)) - 1))
50 #define H2FMSHIFT(radix)        ((hammer2_off_t)1 << (radix))
51
52 /*
53  * breadth-first search
54  */
55 typedef struct hammer2_chain_save {
56         TAILQ_ENTRY(hammer2_chain_save) entry;
57         hammer2_chain_t *chain;
58         int pri;
59 } hammer2_chain_save_t;
60
61 TAILQ_HEAD(hammer2_chain_save_list, hammer2_chain_save);
62 typedef struct hammer2_chain_save_list hammer2_chain_save_list_t;
63
64 typedef struct hammer2_bulkfree_info {
65         hammer2_dev_t           *hmp;
66         kmem_anon_desc_t        kp;
67         hammer2_off_t           sbase;          /* sub-loop iteration */
68         hammer2_off_t           sstop;
69         hammer2_bmap_data_t     *bmap;
70         int                     depth;
71         long                    count_10_00;    /* staged->free      */
72         long                    count_11_10;    /* allocated->staged */
73         long                    count_00_11;    /* (should not happen) */
74         long                    count_01_11;    /* (should not happen) */
75         long                    count_10_11;    /* staged->allocated */
76         long                    count_l0cleans;
77         long                    count_linadjusts;
78         long                    count_inodes_scanned;
79         long                    count_dedup_factor;
80         long                    bytes_scanned;
81         hammer2_off_t           adj_free;
82         hammer2_tid_t           mtid;
83         hammer2_tid_t           saved_mirror_tid;
84         time_t                  save_time;
85         hammer2_chain_save_list_t list;
86         hammer2_dedup_t         *dedup;
87         int                     pri;
88 } hammer2_bulkfree_info_t;
89
90 static int h2_bulkfree_test(hammer2_bulkfree_info_t *info,
91                         hammer2_blockref_t *bref, int pri);
92
93 /*
94  * General bulk scan function with callback.  Called with a referenced
95  * but UNLOCKED parent.  The parent is returned in the same state.
96  */
97 static
98 int
99 hammer2_bulk_scan(hammer2_chain_t *parent,
100                   int (*func)(hammer2_bulkfree_info_t *info,
101                               hammer2_blockref_t *bref),
102                   hammer2_bulkfree_info_t *info)
103 {
104         hammer2_blockref_t bref;
105         hammer2_chain_t *chain;
106         int cache_index = -1;
107         int doabort = 0;
108         int first = 1;
109
110         ++info->pri;
111
112         hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS |
113                                    HAMMER2_RESOLVE_SHARED);
114         chain = NULL;
115
116         /*
117          * Generally loop on the contents if we have not been flagged
118          * for abort.
119          *
120          * Remember that these chains are completely isolated from
121          * the frontend, so we can release locks temporarily without
122          * imploding.
123          */
124         while ((doabort & HAMMER2_BULK_ABORT) == 0 &&
125                hammer2_chain_scan(parent, &chain, &bref, &first,
126                                   &cache_index,
127                                   HAMMER2_LOOKUP_NODATA |
128                                   HAMMER2_LOOKUP_SHARED) != NULL) {
129                 /*
130                  * Process bref, chain is only non-NULL if the bref
131                  * might be recursable (its possible that we sometimes get
132                  * a non-NULL chain where the bref cannot be recursed).
133                  */
134 #if 0
135                 kprintf("SCAN %016jx\n", bref.data_off);
136                 int xerr = tsleep(&info->pri, PCATCH, "slp", hz / 10);
137                 if (xerr == EINTR || xerr == ERESTART) {
138                         doabort |= HAMMER2_BULK_ABORT;
139                 }
140 #endif
141                 ++info->pri;
142                 if (h2_bulkfree_test(info, &bref, 1))
143                         continue;
144
145                 doabort |= func(info, &bref);
146
147                 if (doabort & HAMMER2_BULK_ABORT)
148                         break;
149
150                 /*
151                  * A non-null chain is always returned if it is
152                  * recursive, otherwise a non-null chain might be
153                  * returned but usually is not when not recursive.
154                  */
155                 if (chain == NULL)
156                         continue;
157
158                 /*
159                  * Else check type and setup depth-first scan.
160                  *
161                  * Account for bytes actually read.
162                  */
163                 info->bytes_scanned += chain->bytes;
164
165                 switch(chain->bref.type) {
166                 case HAMMER2_BREF_TYPE_INODE:
167                 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
168                 case HAMMER2_BREF_TYPE_INDIRECT:
169                 case HAMMER2_BREF_TYPE_VOLUME:
170                 case HAMMER2_BREF_TYPE_FREEMAP:
171                         ++info->depth;
172                         if (info->depth > 16) {
173                                 hammer2_chain_save_t *save;
174                                 save = kmalloc(sizeof(*save), M_HAMMER2,
175                                                M_WAITOK | M_ZERO);
176                                 save->chain = chain;
177                                 hammer2_chain_ref(chain);
178                                 TAILQ_INSERT_TAIL(&info->list, save, entry);
179
180                                 /* guess */
181                                 info->pri += 10;
182                         } else {
183                                 int savepri = info->pri;
184
185                                 hammer2_chain_unlock(chain);
186                                 info->pri = 0;
187                                 doabort |= hammer2_bulk_scan(chain, func, info);
188                                 info->pri += savepri;
189                                 hammer2_chain_lock(chain,
190                                                    HAMMER2_RESOLVE_ALWAYS |
191                                                    HAMMER2_RESOLVE_SHARED);
192                         }
193                         --info->depth;
194                         break;
195                 default:
196                         /* does not recurse */
197                         break;
198                 }
199         }
200         if (chain) {
201                 hammer2_chain_unlock(chain);
202                 hammer2_chain_drop(chain);
203         }
204
205         /*
206          * Save with higher pri now that we know what it is.
207          */
208         h2_bulkfree_test(info, &parent->bref, info->pri + 1);
209
210         hammer2_chain_unlock(parent);
211
212         return doabort;
213 }
214
215 /*
216  * Bulkfree algorithm
217  *
218  * Repeat {
219  *      Chain flush (partial synchronization) XXX removed
220  *      Scan the whole topology - build in-memory freemap (mark 11)
221  *      Reconcile the in-memory freemap against the on-disk freemap.
222  *              ondisk xx -> ondisk 11 (if allocated)
223  *              ondisk 11 -> ondisk 10 (if free in-memory)
224  *              ondisk 10 -> ondisk 00 (if free in-memory) - on next pass
225  * }
226  *
227  * The topology scan may have to be performed multiple times to window
228  * freemaps which are too large to fit in kernel memory.
229  *
230  * Races are handled using a double-transition (11->10, 10->00).  The bulkfree
231  * scan snapshots the volume root's blockset and thus can run concurrent with
232  * normal operations, as long as a full flush is made between each pass to
233  * synchronize any modified chains (otherwise their blocks might be improperly
234  * freed).
235  *
236  * Temporary memory in multiples of 64KB is required to reconstruct the leaf
237  * hammer2_bmap_data blocks so they can later be compared against the live
238  * freemap.  Each 64KB block represents 128 x 16KB x 1024 = ~2 GB of storage.
239  * A 32MB save area thus represents around ~1 TB.  The temporary memory
240  * allocated can be specified.  If it is not sufficient multiple topology
241  * passes will be made.
242  */
243
244 /*
245  * Bulkfree callback info
246  */
247 static void hammer2_bulkfree_thread(void *arg __unused);
248 static void cbinfo_bmap_init(hammer2_bulkfree_info_t *cbinfo, size_t size);
249 static int h2_bulkfree_callback(hammer2_bulkfree_info_t *cbinfo,
250                         hammer2_blockref_t *bref);
251 static void h2_bulkfree_sync(hammer2_bulkfree_info_t *cbinfo);
252 static void h2_bulkfree_sync_adjust(hammer2_bulkfree_info_t *cbinfo,
253                         hammer2_off_t data_off, hammer2_bmap_data_t *live,
254                         hammer2_bmap_data_t *bmap, int nofree);
255
256 void
257 hammer2_bulkfree_init(hammer2_dev_t *hmp)
258 {
259         hammer2_thr_create(&hmp->bfthr, NULL, hmp,
260                            hmp->devrepname, -1, -1,
261                            hammer2_bulkfree_thread);
262 }
263
264 void
265 hammer2_bulkfree_uninit(hammer2_dev_t *hmp)
266 {
267         hammer2_thr_delete(&hmp->bfthr);
268 }
269
270 static void
271 hammer2_bulkfree_thread(void *arg)
272 {
273         hammer2_thread_t *thr = arg;
274         hammer2_ioc_bulkfree_t bfi;
275         uint32_t flags;
276
277         for (;;) {
278                 hammer2_thr_wait_any(thr,
279                                      HAMMER2_THREAD_STOP |
280                                      HAMMER2_THREAD_FREEZE |
281                                      HAMMER2_THREAD_UNFREEZE |
282                                      HAMMER2_THREAD_REMASTER,
283                                      hz * 60);
284
285                 flags = thr->flags;
286                 cpu_ccfence();
287                 if (flags & HAMMER2_THREAD_STOP)
288                         break;
289                 if (flags & HAMMER2_THREAD_FREEZE) {
290                         hammer2_thr_signal2(thr, HAMMER2_THREAD_FROZEN,
291                                                  HAMMER2_THREAD_FREEZE);
292                         continue;
293                 }
294                 if (flags & HAMMER2_THREAD_UNFREEZE) {
295                         hammer2_thr_signal2(thr, 0,
296                                                  HAMMER2_THREAD_FROZEN |
297                                                  HAMMER2_THREAD_UNFREEZE);
298                         continue;
299                 }
300                 if (flags & HAMMER2_THREAD_FROZEN)
301                         continue;
302                 if (flags & HAMMER2_THREAD_REMASTER) {
303                         hammer2_thr_signal2(thr, 0, HAMMER2_THREAD_REMASTER);
304                         bzero(&bfi, sizeof(bfi));
305                         bfi.size = 8192 * 1024;
306                         hammer2_bulkfree_pass(thr->hmp, &bfi);
307                 }
308         }
309         thr->td = NULL;
310         hammer2_thr_signal(thr, HAMMER2_THREAD_STOPPED);
311         /* structure can go invalid at this point */
312 }
313
314 int
315 hammer2_bulkfree_pass(hammer2_dev_t *hmp, hammer2_ioc_bulkfree_t *bfi)
316 {
317         hammer2_bulkfree_info_t cbinfo;
318         hammer2_chain_t *vchain;
319         hammer2_chain_save_t *save;
320         hammer2_off_t incr;
321         size_t size;
322         int doabort = 0;
323
324         /*
325          * A bulk operations lock is required for the duration.  We
326          * must hold it across our flushes to guarantee that we never run
327          * two bulkfree passes in a row without a flush in the middle.
328          * The 2-stage bulkfree requires this flush to work properly.
329          */
330         lockmgr(&hmp->bulklk, LK_EXCLUSIVE);
331
332         /*
333          * We have to clear the live dedup cache as it might have entries
334          * that are freeable as of now.  Any new entries in the dedup cache
335          * made after this point, even if they become freeable, will have
336          * previously been fully allocated and will be protected by the
337          * 2-stage bulkfree.
338          */
339         hammer2_dedup_clear(hmp);
340
341         /*
342          * Create a stable snapshot of the block tree which we can run
343          * the bulkfree pass on.  This allows the bulkfree pass to run
344          * concurrent with all other operations (except another bulkfree)
345          *
346          * This must flush all dirty chain data, but does not have to
347          * flush dirty buffer cache buffers which have not yet been
348          * realized and does not have to flush any newly realized dirty
349          * chains while the bulkfree pass is running, as long as said
350          * newly dirtied chains get flushed the next time, before the
351          * next bulkfree pass.
352          */
353         vchain = hammer2_flush_quick(hmp);
354         hammer2_chain_bulkdrop(vchain);
355         vchain = hammer2_flush_quick(hmp);
356
357         /*
358          * Setup for free pass
359          */
360         bzero(&cbinfo, sizeof(cbinfo));
361         size = (bfi->size + HAMMER2_FREEMAP_LEVELN_PSIZE - 1) &
362                ~(size_t)(HAMMER2_FREEMAP_LEVELN_PSIZE - 1);
363         cbinfo.hmp = hmp;
364         cbinfo.bmap = kmem_alloc_swapbacked(&cbinfo.kp, size, VM_SUBSYS_HAMMER);
365         cbinfo.saved_mirror_tid = hmp->voldata.mirror_tid;
366
367         cbinfo.dedup = kmalloc(sizeof(*cbinfo.dedup) * HAMMER2_DEDUP_HEUR_SIZE,
368                                M_HAMMER2, M_WAITOK | M_ZERO);
369
370         /*
371          * Normalize start point to a 2GB boundary.  We operate on a
372          * 64KB leaf bitmap boundary which represents 2GB of storage.
373          */
374         cbinfo.sbase = bfi->sbase;
375         if (cbinfo.sbase > hmp->voldata.volu_size)
376                 cbinfo.sbase = hmp->voldata.volu_size;
377         cbinfo.sbase &= ~HAMMER2_FREEMAP_LEVEL1_MASK;
378         TAILQ_INIT(&cbinfo.list);
379
380         /*
381          * Loop on a full meta-data scan as many times as required to
382          * get through all available storage.
383          */
384         while (cbinfo.sbase < hmp->voldata.volu_size) {
385                 /*
386                  * We have enough ram to represent (incr) bytes of storage.
387                  * Each 64KB of ram represents 2GB of storage.
388                  */
389                 cbinfo_bmap_init(&cbinfo, size);
390                 incr = size / HAMMER2_FREEMAP_LEVELN_PSIZE *
391                        HAMMER2_FREEMAP_LEVEL1_SIZE;
392                 if (hmp->voldata.volu_size - cbinfo.sbase < incr)
393                         cbinfo.sstop = hmp->voldata.volu_size;
394                 else
395                         cbinfo.sstop = cbinfo.sbase + incr;
396                 if (hammer2_debug & 1) {
397                         kprintf("bulkfree pass %016jx/%jdGB\n",
398                                 (intmax_t)cbinfo.sbase,
399                                 (intmax_t)incr / HAMMER2_FREEMAP_LEVEL1_SIZE);
400                 }
401
402                 /*
403                  * Scan topology for stuff inside this range.
404                  */
405                 hammer2_trans_init(hmp->spmp, 0);
406                 cbinfo.mtid = hammer2_trans_sub(hmp->spmp);
407                 cbinfo.pri = 0;
408                 doabort |= hammer2_bulk_scan(vchain, h2_bulkfree_callback,
409                                              &cbinfo);
410
411                 while ((save = TAILQ_FIRST(&cbinfo.list)) != NULL &&
412                        doabort == 0) {
413                         TAILQ_REMOVE(&cbinfo.list, save, entry);
414                         cbinfo.pri = 0;
415                         doabort |= hammer2_bulk_scan(save->chain,
416                                                      h2_bulkfree_callback,
417                                                      &cbinfo);
418                         hammer2_chain_drop(save->chain);
419                         kfree(save, M_HAMMER2);
420                 }
421                 while (save) {
422                         TAILQ_REMOVE(&cbinfo.list, save, entry);
423                         hammer2_chain_drop(save->chain);
424                         kfree(save, M_HAMMER2);
425                         save = TAILQ_FIRST(&cbinfo.list);
426                 }
427
428                 kprintf("bulkfree lastdrop %d %d doabort=%d\n",
429                         vchain->refs, vchain->core.chain_count, doabort);
430
431                 /*
432                  * If complete scan succeeded we can synchronize our
433                  * in-memory freemap against live storage.  If an abort
434                  * did occur we cannot safely synchronize our partially
435                  * filled-out in-memory freemap.
436                  */
437                 if (doabort == 0) {
438                         h2_bulkfree_sync(&cbinfo);
439
440                         hammer2_voldata_lock(hmp);
441                         hammer2_voldata_modify(hmp);
442                         hmp->voldata.allocator_free += cbinfo.adj_free;
443                         hammer2_voldata_unlock(hmp);
444                 }
445
446                 /*
447                  * Cleanup for next loop.
448                  */
449                 hammer2_trans_done(hmp->spmp);
450                 if (doabort)
451                         break;
452                 cbinfo.sbase = cbinfo.sstop;
453                 cbinfo.adj_free = 0;
454         }
455         hammer2_chain_bulkdrop(vchain);
456         kmem_free_swapbacked(&cbinfo.kp);
457         kfree(cbinfo.dedup, M_HAMMER2);
458         cbinfo.dedup = NULL;
459
460         bfi->sstop = cbinfo.sbase;
461
462         incr = bfi->sstop / (hmp->voldata.volu_size / 10000);
463         if (incr > 10000)
464                 incr = 10000;
465
466         kprintf("bulkfree pass statistics (%d.%02d%% storage processed):\n",
467                 (int)incr / 100,
468                 (int)incr % 100);
469
470         kprintf("    transition->free   %ld\n", cbinfo.count_10_00);
471         kprintf("    transition->staged %ld\n", cbinfo.count_11_10);
472         kprintf("    ERR(00)->allocated %ld\n", cbinfo.count_00_11);
473         kprintf("    ERR(01)->allocated %ld\n", cbinfo.count_01_11);
474         kprintf("    staged->allocated  %ld\n", cbinfo.count_10_11);
475         kprintf("    ~2MB segs cleaned  %ld\n", cbinfo.count_l0cleans);
476         kprintf("    linear adjusts     %ld\n", cbinfo.count_linadjusts);
477         kprintf("    dedup factor       %ld\n", cbinfo.count_dedup_factor);
478
479         lockmgr(&hmp->bulklk, LK_RELEASE);
480         /* hammer2_vfs_sync(mp, MNT_WAIT); sync needed */
481
482         return doabort;
483 }
484
485 static void
486 cbinfo_bmap_init(hammer2_bulkfree_info_t *cbinfo, size_t size)
487 {
488         hammer2_bmap_data_t *bmap = cbinfo->bmap;
489         hammer2_key_t key = cbinfo->sbase;
490         hammer2_key_t lokey;
491         hammer2_key_t hikey;
492
493         lokey = (cbinfo->hmp->voldata.allocator_beg + HAMMER2_SEGMASK64) &
494                 ~HAMMER2_SEGMASK64;
495         hikey = cbinfo->hmp->voldata.volu_size & ~HAMMER2_SEGMASK64;
496
497         bzero(bmap, size);
498         while (size) {
499                 if (lokey < H2FMBASE(key, HAMMER2_FREEMAP_LEVEL1_RADIX) +
500                             HAMMER2_ZONE_SEG64) {
501                         lokey = H2FMBASE(key, HAMMER2_FREEMAP_LEVEL1_RADIX) +
502                                 HAMMER2_ZONE_SEG64;
503                 }
504                 if (key < lokey || key >= hikey) {
505                         memset(bmap->bitmapq, -1,
506                                sizeof(bmap->bitmapq));
507                         bmap->avail = 0;
508                         bmap->linear = HAMMER2_SEGSIZE;
509                 } else {
510                         bmap->avail = H2FMSHIFT(HAMMER2_FREEMAP_LEVEL0_RADIX);
511                 }
512                 size -= sizeof(*bmap);
513                 key += HAMMER2_FREEMAP_LEVEL0_SIZE;
514                 ++bmap;
515         }
516 }
517
518 static int
519 h2_bulkfree_callback(hammer2_bulkfree_info_t *cbinfo, hammer2_blockref_t *bref)
520 {
521         hammer2_bmap_data_t *bmap;
522         hammer2_off_t data_off;
523         uint16_t class;
524         size_t bytes;
525         int radix;
526         int error;
527
528         /*
529          * Check for signal and allow yield to userland during scan
530          */
531         if (hammer2_signal_check(&cbinfo->save_time))
532                 return HAMMER2_BULK_ABORT;
533         if (bref->type == HAMMER2_BREF_TYPE_INODE) {
534                 ++cbinfo->count_inodes_scanned;
535                 if ((cbinfo->count_inodes_scanned & 65535) == 0)
536                         kprintf(" inodes %6ld bytes %9ld\n",
537                                 cbinfo->count_inodes_scanned,
538                                 cbinfo->bytes_scanned);
539         }
540
541         /*
542          * Calculate the data offset and determine if it is within
543          * the current freemap range being gathered.
544          */
545         error = 0;
546         data_off = bref->data_off & ~HAMMER2_OFF_MASK_RADIX;
547         if (data_off < cbinfo->sbase || data_off >= cbinfo->sstop)
548                 return 0;
549         if (data_off < cbinfo->hmp->voldata.allocator_beg)
550                 return 0;
551         if (data_off >= cbinfo->hmp->voldata.volu_size)
552                 return 0;
553
554         /*
555          * Calculate the information needed to generate the in-memory
556          * freemap record.
557          *
558          * Hammer2 does not allow allocations to cross the L1 (2GB) boundary,
559          * it's a problem if it does.  (Or L0 (2MB) for that matter).
560          */
561         radix = (int)(bref->data_off & HAMMER2_OFF_MASK_RADIX);
562         KKASSERT(radix != 0);
563         bytes = (size_t)1 << radix;
564         class = (bref->type << 8) | hammer2_devblkradix(radix);
565
566         if (data_off + bytes >= cbinfo->sstop) {
567                 kprintf("hammer2_bulkfree_scan: illegal 2GB boundary "
568                         "%016jx %016jx/%d\n",
569                         (intmax_t)bref->data_off,
570                         (intmax_t)bref->key,
571                         bref->keybits);
572                 bytes = cbinfo->sstop - data_off;       /* XXX */
573         }
574
575         /*
576          * Convert to a storage offset relative to the beginning of the
577          * storage range we are collecting.  Then lookup the level0 bmap entry.
578          */
579         data_off -= cbinfo->sbase;
580         bmap = cbinfo->bmap + (data_off >> HAMMER2_FREEMAP_LEVEL0_RADIX);
581
582         /*
583          * Convert data_off to a bmap-relative value (~2MB storage range).
584          * Adjust linear, class, and avail.
585          *
586          * Hammer2 does not allow allocations to cross the L0 (2MB) boundary,
587          */
588         data_off &= HAMMER2_FREEMAP_LEVEL0_MASK;
589         if (data_off + bytes > HAMMER2_FREEMAP_LEVEL0_SIZE) {
590                 kprintf("hammer2_bulkfree_scan: illegal 2MB boundary "
591                         "%016jx %016jx/%d\n",
592                         (intmax_t)bref->data_off,
593                         (intmax_t)bref->key,
594                         bref->keybits);
595                 bytes = HAMMER2_FREEMAP_LEVEL0_SIZE - data_off;
596         }
597
598         if (bmap->class == 0) {
599                 bmap->class = class;
600                 bmap->avail = HAMMER2_FREEMAP_LEVEL0_SIZE;
601         }
602         if (bmap->class != class) {
603                 kprintf("hammer2_bulkfree_scan: illegal mixed class "
604                         "%016jx %016jx/%d (%04x vs %04x)\n",
605                         (intmax_t)bref->data_off,
606                         (intmax_t)bref->key,
607                         bref->keybits,
608                         class, bmap->class);
609         }
610         if (bmap->linear < (int32_t)data_off + (int32_t)bytes)
611                 bmap->linear = (int32_t)data_off + (int32_t)bytes;
612
613         /*
614          * Adjust the hammer2_bitmap_t bitmap[HAMMER2_BMAP_ELEMENTS].
615          * 64-bit entries, 2 bits per entry, to code 11.
616          *
617          * NOTE: The allocation can be smaller than HAMMER2_FREEMAP_BLOCK_SIZE.
618          */
619         while (bytes > 0) {
620                 int bindex;
621                 hammer2_bitmap_t bmask;
622
623                 bindex = (int)data_off >> (HAMMER2_FREEMAP_BLOCK_RADIX +
624                                            HAMMER2_BMAP_INDEX_RADIX);
625                 bmask = (hammer2_bitmap_t)3 <<
626                         ((((int)data_off & HAMMER2_BMAP_INDEX_MASK) >>
627                          HAMMER2_FREEMAP_BLOCK_RADIX) << 1);
628
629                 /*
630                  * NOTE! The (avail) calculation is bitmap-granular.  Multiple
631                  *       sub-granular records can wind up at the same bitmap
632                  *       position.
633                  */
634                 if ((bmap->bitmapq[bindex] & bmask) == 0) {
635                         if (bytes < HAMMER2_FREEMAP_BLOCK_SIZE) {
636                                 bmap->avail -= HAMMER2_FREEMAP_BLOCK_SIZE;
637                         } else {
638                                 bmap->avail -= bytes;
639                         }
640                         bmap->bitmapq[bindex] |= bmask;
641                 }
642                 data_off += HAMMER2_FREEMAP_BLOCK_SIZE;
643                 if (bytes < HAMMER2_FREEMAP_BLOCK_SIZE)
644                         bytes = 0;
645                 else
646                         bytes -= HAMMER2_FREEMAP_BLOCK_SIZE;
647         }
648         return error;
649 }
650
651 /*
652  * Synchronize the in-memory bitmap with the live freemap.  This is not a
653  * direct copy.  Instead the bitmaps must be compared:
654  *
655  *      In-memory       Live-freemap
656  *         00             11 -> 10      (do nothing if live modified)
657  *                        10 -> 00      (do nothing if live modified)
658  *         11             10 -> 11      handles race against live
659  *                        ** -> 11      nominally warn of corruption
660  * 
661  */
662 static void
663 h2_bulkfree_sync(hammer2_bulkfree_info_t *cbinfo)
664 {
665         hammer2_off_t data_off;
666         hammer2_key_t key;
667         hammer2_key_t key_dummy;
668         hammer2_bmap_data_t *bmap;
669         hammer2_bmap_data_t *live;
670         hammer2_chain_t *live_parent;
671         hammer2_chain_t *live_chain;
672         int cache_index = -1;
673         int bmapindex;
674
675         kprintf("hammer2_bulkfree - range ");
676
677         if (cbinfo->sbase < cbinfo->hmp->voldata.allocator_beg)
678                 kprintf("%016jx-",
679                         (intmax_t)cbinfo->hmp->voldata.allocator_beg);
680         else
681                 kprintf("%016jx-",
682                         (intmax_t)cbinfo->sbase);
683
684         if (cbinfo->sstop > cbinfo->hmp->voldata.volu_size)
685                 kprintf("%016jx\n",
686                         (intmax_t)cbinfo->hmp->voldata.volu_size);
687         else
688                 kprintf("%016jx\n",
689                         (intmax_t)cbinfo->sstop);
690                 
691         data_off = cbinfo->sbase;
692         bmap = cbinfo->bmap;
693
694         live_parent = &cbinfo->hmp->fchain;
695         hammer2_chain_ref(live_parent);
696         hammer2_chain_lock(live_parent, HAMMER2_RESOLVE_ALWAYS);
697         live_chain = NULL;
698
699         /*
700          * Iterate each hammer2_bmap_data_t line (128 bytes) managing
701          * 4MB of storage.
702          */
703         while (data_off < cbinfo->sstop) {
704                 /*
705                  * The freemap is not used below allocator_beg or beyond
706                  * volu_size.
707                  */
708                 int nofree;
709
710                 if (data_off < cbinfo->hmp->voldata.allocator_beg)
711                         goto next;
712                 if (data_off >= cbinfo->hmp->voldata.volu_size)
713                         goto next;
714
715                 /*
716                  * Locate the freemap leaf on the live filesystem
717                  */
718                 key = (data_off & ~HAMMER2_FREEMAP_LEVEL1_MASK);
719                 nofree = 0;
720
721                 if (live_chain == NULL || live_chain->bref.key != key) {
722                         if (live_chain) {
723                                 hammer2_chain_unlock(live_chain);
724                                 hammer2_chain_drop(live_chain);
725                         }
726                         live_chain = hammer2_chain_lookup(
727                                             &live_parent,
728                                             &key_dummy,
729                                             key,
730                                             key + HAMMER2_FREEMAP_LEVEL1_MASK,
731                                             &cache_index,
732                                             HAMMER2_LOOKUP_ALWAYS);
733
734 #if 0
735                         /*
736                          * If recent allocations were made we avoid races by
737                          * not staging or freeing any blocks.  We can still
738                          * remark blocks as fully allocated.
739                          */
740                         if (live_chain) {
741                                 if (hammer2_debug & 1) {
742                                         kprintf("live_chain %016jx\n",
743                                                 (intmax_t)key);
744                                 }
745                                 if (live_chain->bref.mirror_tid >
746                                     cbinfo->saved_mirror_tid) {
747                                         kprintf("hammer2_bulkfree: "
748                                                 "avoid %016jx\n",
749                                                 data_off);
750                                         nofree = 1;
751                                 } else {
752                                         nofree = 0;
753                                 }
754                         }
755 #endif
756                 }
757                 if (live_chain == NULL) {
758                         /*
759                          * XXX if we implement a full recovery mode we need
760                          * to create/recreate missing freemap chains if our
761                          * bmap has any allocated blocks.
762                          */
763                         if (bmap->class &&
764                             bmap->avail != HAMMER2_FREEMAP_LEVEL0_SIZE) {
765                                 kprintf("hammer2_bulkfree: cannot locate "
766                                         "live leaf for allocated data "
767                                         "near %016jx\n",
768                                         (intmax_t)data_off);
769                         }
770                         goto next;
771                 }
772                 if (live_chain->error) {
773                         kprintf("hammer2_bulkfree: error %s looking up "
774                                 "live leaf for allocated data near %016jx\n",
775                                 hammer2_error_str(live_chain->error),
776                                 (intmax_t)data_off);
777                         hammer2_chain_unlock(live_chain);
778                         hammer2_chain_drop(live_chain);
779                         live_chain = NULL;
780                         goto next;
781                 }
782
783                 bmapindex = (data_off & HAMMER2_FREEMAP_LEVEL1_MASK) >>
784                             HAMMER2_FREEMAP_LEVEL0_RADIX;
785                 live = &live_chain->data->bmdata[bmapindex];
786
787                 /*
788                  * TODO - we could shortcut this by testing that both
789                  * live->class and bmap->class are 0, and both avails are
790                  * set to HAMMER2_FREEMAP_LEVEL0_SIZE (4MB).
791                  */
792                 if (bcmp(live->bitmapq, bmap->bitmapq,
793                          sizeof(bmap->bitmapq)) == 0) {
794                         goto next;
795                 }
796                 if (hammer2_debug & 1) {
797                         kprintf("live %016jx %04d.%04x (avail=%d)\n",
798                                 data_off, bmapindex, live->class, live->avail);
799                 }
800
801                 hammer2_chain_modify(live_chain, cbinfo->mtid, 0, 0);
802                 live = &live_chain->data->bmdata[bmapindex];
803
804                 h2_bulkfree_sync_adjust(cbinfo, data_off, live, bmap, nofree);
805 next:
806                 data_off += HAMMER2_FREEMAP_LEVEL0_SIZE;
807                 ++bmap;
808         }
809         if (live_chain) {
810                 hammer2_chain_unlock(live_chain);
811                 hammer2_chain_drop(live_chain);
812         }
813         if (live_parent) {
814                 hammer2_chain_unlock(live_parent);
815                 hammer2_chain_drop(live_parent);
816         }
817 }
818
819 /*
820  * When bulkfree is finally able to free a block it must make sure that
821  * the INVALOK bit in any cached DIO is cleared prior to the block being
822  * reused.
823  */
824 static
825 void
826 fixup_dio(hammer2_dev_t *hmp, hammer2_off_t data_off, int bindex, int scount)
827 {
828         data_off += (scount >> 1) * HAMMER2_FREEMAP_BLOCK_SIZE;
829         data_off += bindex *
830                 (HAMMER2_FREEMAP_BLOCK_SIZE * HAMMER2_BMAP_BLOCKS_PER_ELEMENT);
831         hammer2_io_resetinval(hmp, data_off);
832 }
833
834 /*
835  * Merge the bulkfree bitmap against the existing bitmap.
836  *
837  * If nofree is non-zero the merge will only mark free blocks as allocated
838  * and will refuse to free any blocks.
839  */
840 static
841 void
842 h2_bulkfree_sync_adjust(hammer2_bulkfree_info_t *cbinfo,
843                         hammer2_off_t data_off, hammer2_bmap_data_t *live,
844                         hammer2_bmap_data_t *bmap, int nofree)
845 {
846         int bindex;
847         int scount;
848         hammer2_bitmap_t lmask;
849         hammer2_bitmap_t mmask;
850
851         for (bindex = 0; bindex < HAMMER2_BMAP_ELEMENTS; ++bindex) {
852                 lmask = live->bitmapq[bindex];  /* live */
853                 mmask = bmap->bitmapq[bindex];  /* snapshotted bulkfree */
854                 if (lmask == mmask)
855                         continue;
856
857                 for (scount = 0;
858                      scount < HAMMER2_BMAP_BITS_PER_ELEMENT;
859                      scount += 2) {
860                         if ((mmask & 3) == 0) {
861                                 /*
862                                  * in-memory 00         live 11 -> 10
863                                  *                      live 10 -> 00
864                                  *
865                                  * Storage might be marked allocated or
866                                  * staged and must be remarked staged or
867                                  * free.
868                                  */
869                                 switch (lmask & 3) {
870                                 case 0: /* 00 */
871                                         break;
872                                 case 1: /* 01 */
873                                         kprintf("hammer2_bulkfree: cannot "
874                                                 "transition m=00/l=01\n");
875                                         break;
876                                 case 2: /* 10 -> 00 */
877                                         if (nofree)
878                                                 break;
879                                         live->bitmapq[bindex] &=
880                                             ~((hammer2_bitmap_t)2 << scount);
881                                         live->avail +=
882                                                 HAMMER2_FREEMAP_BLOCK_SIZE;
883                                         if (live->avail >
884                                             HAMMER2_FREEMAP_LEVEL0_SIZE) {
885                                                 live->avail =
886                                                     HAMMER2_FREEMAP_LEVEL0_SIZE;
887                                         }
888                                         cbinfo->adj_free +=
889                                                 HAMMER2_FREEMAP_BLOCK_SIZE;
890                                         ++cbinfo->count_10_00;
891                                         break;
892                                 case 3: /* 11 -> 10 */
893                                         live->bitmapq[bindex] &=
894                                             ~((hammer2_bitmap_t)1 << scount);
895                                         ++cbinfo->count_11_10;
896                                         fixup_dio(cbinfo->hmp, data_off,
897                                                   bindex, scount);
898                                         break;
899                                 }
900                         } else if ((mmask & 3) == 3) {
901                                 /*
902                                  * in-memory 11         live 10 -> 11
903                                  *                      live ** -> 11
904                                  *
905                                  * Storage might be incorrectly marked free
906                                  * or staged and must be remarked fully
907                                  * allocated.
908                                  */
909                                 switch (lmask & 3) {
910                                 case 0: /* 00 */
911                                         ++cbinfo->count_00_11;
912                                         cbinfo->adj_free -=
913                                                 HAMMER2_FREEMAP_BLOCK_SIZE;
914                                         live->avail -=
915                                                 HAMMER2_FREEMAP_BLOCK_SIZE;
916                                         if ((int32_t)live->avail < 0)
917                                                 live->avail = 0;
918                                         break;
919                                 case 1: /* 01 */
920                                         ++cbinfo->count_01_11;
921                                         break;
922                                 case 2: /* 10 -> 11 */
923                                         ++cbinfo->count_10_11;
924                                         break;
925                                 case 3: /* 11 */
926                                         break;
927                                 }
928                                 live->bitmapq[bindex] |=
929                                         ((hammer2_bitmap_t)3 << scount);
930                         }
931                         mmask >>= 2;
932                         lmask >>= 2;
933                 }
934         }
935
936         /*
937          * Determine if the live bitmap is completely free and reset its
938          * fields if so.  Otherwise check to see if we can reduce the linear
939          * offset.
940          */
941         for (bindex = HAMMER2_BMAP_ELEMENTS - 1; bindex >= 0; --bindex) {
942                 if (live->bitmapq[bindex] != 0)
943                         break;
944         }
945         if (nofree) {
946                 /* do nothing */
947         } else if (bindex < 0) {
948                 live->avail = HAMMER2_FREEMAP_LEVEL0_SIZE;
949                 live->class = 0;
950                 live->linear = 0;
951                 ++cbinfo->count_l0cleans;
952         } else if (bindex < 7) {
953                 ++bindex;
954                 if (live->linear > bindex * HAMMER2_FREEMAP_BLOCK_SIZE) {
955                         live->linear = bindex * HAMMER2_FREEMAP_BLOCK_SIZE;
956                         ++cbinfo->count_linadjusts;
957                 }
958
959                 /*
960                  * XXX this fine-grained measure still has some issues.
961                  */
962                 if (live->linear < bindex * HAMMER2_FREEMAP_BLOCK_SIZE) {
963                         live->linear = bindex * HAMMER2_FREEMAP_BLOCK_SIZE;
964                         ++cbinfo->count_linadjusts;
965                 }
966         } else {
967                 live->linear = HAMMER2_SEGSIZE;
968         }
969
970 #if 0
971         if (bmap->class) {
972                 kprintf("%016jx %04d.%04x (avail=%7d) "
973                         "%08x %08x %08x %08x %08x %08x %08x %08x\n",
974                         (intmax_t)data_off,
975                         (int)((data_off &
976                                HAMMER2_FREEMAP_LEVEL1_MASK) >>
977                               HAMMER2_FREEMAP_LEVEL0_RADIX),
978                         bmap->class,
979                         bmap->avail,
980                         bmap->bitmap[0], bmap->bitmap[1],
981                         bmap->bitmap[2], bmap->bitmap[3],
982                         bmap->bitmap[4], bmap->bitmap[5],
983                         bmap->bitmap[6], bmap->bitmap[7]);
984         }
985 #endif
986 }
987
988 /*
989  * BULKFREE DEDUP HEURISTIC
990  *
991  * WARNING! This code is SMP safe but the heuristic allows SMP collisions.
992  *          All fields must be loaded into locals and validated.
993  */
994 static
995 int
996 h2_bulkfree_test(hammer2_bulkfree_info_t *cbinfo, hammer2_blockref_t *bref,
997                  int pri)
998 {
999         hammer2_dedup_t *dedup;
1000         int best;
1001         int n;
1002         int i;
1003
1004         n = hammer2_icrc32(&bref->data_off, sizeof(bref->data_off));
1005         dedup = cbinfo->dedup + (n & (HAMMER2_DEDUP_HEUR_MASK & ~7));
1006
1007         for (i = best = 0; i < 8; ++i) {
1008                 if (dedup[i].data_off == bref->data_off) {
1009                         if (dedup[i].ticks < pri)
1010                                 dedup[i].ticks = pri;
1011                         if (pri == 1)
1012                                 cbinfo->count_dedup_factor += dedup[i].ticks;
1013                         return 1;
1014                 }
1015                 if (dedup[i].ticks < dedup[best].ticks)
1016                         best = i;
1017         }
1018         dedup[best].data_off = bref->data_off;
1019         dedup[best].ticks = pri;
1020
1021         return 0;
1022 }