hammer2 - Try a different approach to bulkfree
[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_chain_t *vchain,
316                       hammer2_ioc_bulkfree_t *bfi)
317 {
318         hammer2_bulkfree_info_t cbinfo;
319         hammer2_chain_save_t *save;
320         hammer2_off_t incr;
321         size_t size;
322         int doabort = 0;
323
324         /*
325          * We have to clear the live dedup cache as it might have entries
326          * that are freeable as of now.  Any new entries in the dedup cache
327          * made after this point, even if they become freeable, will have
328          * previously been fully allocated and will be protected by the
329          * 2-stage bulkfree.
330          */
331         hammer2_dedup_clear(hmp);
332
333         /*
334          * Setup for free pass
335          */
336         bzero(&cbinfo, sizeof(cbinfo));
337         size = (bfi->size + HAMMER2_FREEMAP_LEVELN_PSIZE - 1) &
338                ~(size_t)(HAMMER2_FREEMAP_LEVELN_PSIZE - 1);
339         cbinfo.hmp = hmp;
340         cbinfo.bmap = kmem_alloc_swapbacked(&cbinfo.kp, size, VM_SUBSYS_HAMMER);
341         cbinfo.saved_mirror_tid = hmp->voldata.mirror_tid;
342
343         cbinfo.dedup = kmalloc(sizeof(*cbinfo.dedup) * HAMMER2_DEDUP_HEUR_SIZE,
344                                M_HAMMER2, M_WAITOK | M_ZERO);
345
346         /*
347          * Normalize start point to a 2GB boundary.  We operate on a
348          * 64KB leaf bitmap boundary which represents 2GB of storage.
349          */
350         cbinfo.sbase = bfi->sbase;
351         if (cbinfo.sbase > hmp->voldata.volu_size)
352                 cbinfo.sbase = hmp->voldata.volu_size;
353         cbinfo.sbase &= ~HAMMER2_FREEMAP_LEVEL1_MASK;
354         TAILQ_INIT(&cbinfo.list);
355
356         /*
357          * Loop on a full meta-data scan as many times as required to
358          * get through all available storage.
359          */
360         while (cbinfo.sbase < hmp->voldata.volu_size) {
361                 /*
362                  * We have enough ram to represent (incr) bytes of storage.
363                  * Each 64KB of ram represents 2GB of storage.
364                  */
365                 cbinfo_bmap_init(&cbinfo, size);
366                 incr = size / HAMMER2_FREEMAP_LEVELN_PSIZE *
367                        HAMMER2_FREEMAP_LEVEL1_SIZE;
368                 if (hmp->voldata.volu_size - cbinfo.sbase < incr)
369                         cbinfo.sstop = hmp->voldata.volu_size;
370                 else
371                         cbinfo.sstop = cbinfo.sbase + incr;
372                 if (hammer2_debug & 1) {
373                         kprintf("bulkfree pass %016jx/%jdGB\n",
374                                 (intmax_t)cbinfo.sbase,
375                                 (intmax_t)incr / HAMMER2_FREEMAP_LEVEL1_SIZE);
376                 }
377
378                 /*
379                  * Scan topology for stuff inside this range.
380                  */
381                 hammer2_trans_init(hmp->spmp, 0);
382                 cbinfo.mtid = hammer2_trans_sub(hmp->spmp);
383                 cbinfo.pri = 0;
384                 doabort |= hammer2_bulk_scan(vchain, h2_bulkfree_callback,
385                                              &cbinfo);
386
387                 while ((save = TAILQ_FIRST(&cbinfo.list)) != NULL &&
388                        doabort == 0) {
389                         TAILQ_REMOVE(&cbinfo.list, save, entry);
390                         cbinfo.pri = 0;
391                         doabort |= hammer2_bulk_scan(save->chain,
392                                                      h2_bulkfree_callback,
393                                                      &cbinfo);
394                         hammer2_chain_drop(save->chain);
395                         kfree(save, M_HAMMER2);
396                 }
397                 while (save) {
398                         TAILQ_REMOVE(&cbinfo.list, save, entry);
399                         hammer2_chain_drop(save->chain);
400                         kfree(save, M_HAMMER2);
401                         save = TAILQ_FIRST(&cbinfo.list);
402                 }
403
404                 kprintf("bulkfree lastdrop %d %d doabort=%d\n",
405                         vchain->refs, vchain->core.chain_count, doabort);
406
407                 /*
408                  * If complete scan succeeded we can synchronize our
409                  * in-memory freemap against live storage.  If an abort
410                  * did occur we cannot safely synchronize our partially
411                  * filled-out in-memory freemap.
412                  */
413                 if (doabort == 0) {
414                         h2_bulkfree_sync(&cbinfo);
415
416                         hammer2_voldata_lock(hmp);
417                         hammer2_voldata_modify(hmp);
418                         hmp->voldata.allocator_free += cbinfo.adj_free;
419                         hammer2_voldata_unlock(hmp);
420                 }
421
422                 /*
423                  * Cleanup for next loop.
424                  */
425                 hammer2_trans_done(hmp->spmp);
426                 if (doabort)
427                         break;
428                 cbinfo.sbase = cbinfo.sstop;
429                 cbinfo.adj_free = 0;
430         }
431         kmem_free_swapbacked(&cbinfo.kp);
432         kfree(cbinfo.dedup, M_HAMMER2);
433         cbinfo.dedup = NULL;
434
435         bfi->sstop = cbinfo.sbase;
436
437         incr = bfi->sstop / (hmp->voldata.volu_size / 10000);
438         if (incr > 10000)
439                 incr = 10000;
440
441         kprintf("bulkfree pass statistics (%d.%02d%% storage processed):\n",
442                 (int)incr / 100,
443                 (int)incr % 100);
444
445         kprintf("    transition->free   %ld\n", cbinfo.count_10_00);
446         kprintf("    transition->staged %ld\n", cbinfo.count_11_10);
447         kprintf("    ERR(00)->allocated %ld\n", cbinfo.count_00_11);
448         kprintf("    ERR(01)->allocated %ld\n", cbinfo.count_01_11);
449         kprintf("    staged->allocated  %ld\n", cbinfo.count_10_11);
450         kprintf("    ~2MB segs cleaned  %ld\n", cbinfo.count_l0cleans);
451         kprintf("    linear adjusts     %ld\n", cbinfo.count_linadjusts);
452         kprintf("    dedup factor       %ld\n", cbinfo.count_dedup_factor);
453
454         return doabort;
455 }
456
457 static void
458 cbinfo_bmap_init(hammer2_bulkfree_info_t *cbinfo, size_t size)
459 {
460         hammer2_bmap_data_t *bmap = cbinfo->bmap;
461         hammer2_key_t key = cbinfo->sbase;
462         hammer2_key_t lokey;
463         hammer2_key_t hikey;
464
465         lokey = (cbinfo->hmp->voldata.allocator_beg + HAMMER2_SEGMASK64) &
466                 ~HAMMER2_SEGMASK64;
467         hikey = cbinfo->hmp->voldata.volu_size & ~HAMMER2_SEGMASK64;
468
469         bzero(bmap, size);
470         while (size) {
471                 if (lokey < H2FMBASE(key, HAMMER2_FREEMAP_LEVEL1_RADIX) +
472                             HAMMER2_ZONE_SEG64) {
473                         lokey = H2FMBASE(key, HAMMER2_FREEMAP_LEVEL1_RADIX) +
474                                 HAMMER2_ZONE_SEG64;
475                 }
476                 if (key < lokey || key >= hikey) {
477                         memset(bmap->bitmapq, -1,
478                                sizeof(bmap->bitmapq));
479                         bmap->avail = 0;
480                         bmap->linear = HAMMER2_SEGSIZE;
481                 } else {
482                         bmap->avail = H2FMSHIFT(HAMMER2_FREEMAP_LEVEL0_RADIX);
483                 }
484                 size -= sizeof(*bmap);
485                 key += HAMMER2_FREEMAP_LEVEL0_SIZE;
486                 ++bmap;
487         }
488 }
489
490 static int
491 h2_bulkfree_callback(hammer2_bulkfree_info_t *cbinfo, hammer2_blockref_t *bref)
492 {
493         hammer2_bmap_data_t *bmap;
494         hammer2_off_t data_off;
495         uint16_t class;
496         size_t bytes;
497         int radix;
498         int error;
499
500         /*
501          * Check for signal and allow yield to userland during scan
502          */
503         if (hammer2_signal_check(&cbinfo->save_time))
504                 return HAMMER2_BULK_ABORT;
505         if (bref->type == HAMMER2_BREF_TYPE_INODE) {
506                 ++cbinfo->count_inodes_scanned;
507                 if ((cbinfo->count_inodes_scanned & 65535) == 0)
508                         kprintf(" inodes %6ld bytes %9ld\n",
509                                 cbinfo->count_inodes_scanned,
510                                 cbinfo->bytes_scanned);
511         }
512
513         /*
514          * Calculate the data offset and determine if it is within
515          * the current freemap range being gathered.
516          */
517         error = 0;
518         data_off = bref->data_off & ~HAMMER2_OFF_MASK_RADIX;
519         if (data_off < cbinfo->sbase || data_off >= cbinfo->sstop)
520                 return 0;
521         if (data_off < cbinfo->hmp->voldata.allocator_beg)
522                 return 0;
523         if (data_off >= cbinfo->hmp->voldata.volu_size)
524                 return 0;
525
526         /*
527          * Calculate the information needed to generate the in-memory
528          * freemap record.
529          *
530          * Hammer2 does not allow allocations to cross the L1 (2GB) boundary,
531          * it's a problem if it does.  (Or L0 (2MB) for that matter).
532          */
533         radix = (int)(bref->data_off & HAMMER2_OFF_MASK_RADIX);
534         KKASSERT(radix != 0);
535         bytes = (size_t)1 << radix;
536         class = (bref->type << 8) | hammer2_devblkradix(radix);
537
538         if (data_off + bytes >= cbinfo->sstop) {
539                 kprintf("hammer2_bulkfree_scan: illegal 2GB boundary "
540                         "%016jx %016jx/%d\n",
541                         (intmax_t)bref->data_off,
542                         (intmax_t)bref->key,
543                         bref->keybits);
544                 bytes = cbinfo->sstop - data_off;       /* XXX */
545         }
546
547         /*
548          * Convert to a storage offset relative to the beginning of the
549          * storage range we are collecting.  Then lookup the level0 bmap entry.
550          */
551         data_off -= cbinfo->sbase;
552         bmap = cbinfo->bmap + (data_off >> HAMMER2_FREEMAP_LEVEL0_RADIX);
553
554         /*
555          * Convert data_off to a bmap-relative value (~2MB storage range).
556          * Adjust linear, class, and avail.
557          *
558          * Hammer2 does not allow allocations to cross the L0 (2MB) boundary,
559          */
560         data_off &= HAMMER2_FREEMAP_LEVEL0_MASK;
561         if (data_off + bytes > HAMMER2_FREEMAP_LEVEL0_SIZE) {
562                 kprintf("hammer2_bulkfree_scan: illegal 2MB boundary "
563                         "%016jx %016jx/%d\n",
564                         (intmax_t)bref->data_off,
565                         (intmax_t)bref->key,
566                         bref->keybits);
567                 bytes = HAMMER2_FREEMAP_LEVEL0_SIZE - data_off;
568         }
569
570         if (bmap->class == 0) {
571                 bmap->class = class;
572                 bmap->avail = HAMMER2_FREEMAP_LEVEL0_SIZE;
573         }
574         if (bmap->class != class) {
575                 kprintf("hammer2_bulkfree_scan: illegal mixed class "
576                         "%016jx %016jx/%d (%04x vs %04x)\n",
577                         (intmax_t)bref->data_off,
578                         (intmax_t)bref->key,
579                         bref->keybits,
580                         class, bmap->class);
581         }
582         if (bmap->linear < (int32_t)data_off + (int32_t)bytes)
583                 bmap->linear = (int32_t)data_off + (int32_t)bytes;
584
585         /*
586          * Adjust the hammer2_bitmap_t bitmap[HAMMER2_BMAP_ELEMENTS].
587          * 64-bit entries, 2 bits per entry, to code 11.
588          *
589          * NOTE: The allocation can be smaller than HAMMER2_FREEMAP_BLOCK_SIZE.
590          */
591         while (bytes > 0) {
592                 int bindex;
593                 hammer2_bitmap_t bmask;
594
595                 bindex = (int)data_off >> (HAMMER2_FREEMAP_BLOCK_RADIX +
596                                            HAMMER2_BMAP_INDEX_RADIX);
597                 bmask = (hammer2_bitmap_t)3 <<
598                         ((((int)data_off & HAMMER2_BMAP_INDEX_MASK) >>
599                          HAMMER2_FREEMAP_BLOCK_RADIX) << 1);
600
601                 /*
602                  * NOTE! The (avail) calculation is bitmap-granular.  Multiple
603                  *       sub-granular records can wind up at the same bitmap
604                  *       position.
605                  */
606                 if ((bmap->bitmapq[bindex] & bmask) == 0) {
607                         if (bytes < HAMMER2_FREEMAP_BLOCK_SIZE) {
608                                 bmap->avail -= HAMMER2_FREEMAP_BLOCK_SIZE;
609                         } else {
610                                 bmap->avail -= bytes;
611                         }
612                         bmap->bitmapq[bindex] |= bmask;
613                 }
614                 data_off += HAMMER2_FREEMAP_BLOCK_SIZE;
615                 if (bytes < HAMMER2_FREEMAP_BLOCK_SIZE)
616                         bytes = 0;
617                 else
618                         bytes -= HAMMER2_FREEMAP_BLOCK_SIZE;
619         }
620         return error;
621 }
622
623 /*
624  * Synchronize the in-memory bitmap with the live freemap.  This is not a
625  * direct copy.  Instead the bitmaps must be compared:
626  *
627  *      In-memory       Live-freemap
628  *         00             11 -> 10      (do nothing if live modified)
629  *                        10 -> 00      (do nothing if live modified)
630  *         11             10 -> 11      handles race against live
631  *                        ** -> 11      nominally warn of corruption
632  * 
633  */
634 static void
635 h2_bulkfree_sync(hammer2_bulkfree_info_t *cbinfo)
636 {
637         hammer2_off_t data_off;
638         hammer2_key_t key;
639         hammer2_key_t key_dummy;
640         hammer2_bmap_data_t *bmap;
641         hammer2_bmap_data_t *live;
642         hammer2_chain_t *live_parent;
643         hammer2_chain_t *live_chain;
644         int cache_index = -1;
645         int bmapindex;
646
647         kprintf("hammer2_bulkfree - range ");
648
649         if (cbinfo->sbase < cbinfo->hmp->voldata.allocator_beg)
650                 kprintf("%016jx-",
651                         (intmax_t)cbinfo->hmp->voldata.allocator_beg);
652         else
653                 kprintf("%016jx-",
654                         (intmax_t)cbinfo->sbase);
655
656         if (cbinfo->sstop > cbinfo->hmp->voldata.volu_size)
657                 kprintf("%016jx\n",
658                         (intmax_t)cbinfo->hmp->voldata.volu_size);
659         else
660                 kprintf("%016jx\n",
661                         (intmax_t)cbinfo->sstop);
662                 
663         data_off = cbinfo->sbase;
664         bmap = cbinfo->bmap;
665
666         live_parent = &cbinfo->hmp->fchain;
667         hammer2_chain_ref(live_parent);
668         hammer2_chain_lock(live_parent, HAMMER2_RESOLVE_ALWAYS);
669         live_chain = NULL;
670
671         /*
672          * Iterate each hammer2_bmap_data_t line (128 bytes) managing
673          * 4MB of storage.
674          */
675         while (data_off < cbinfo->sstop) {
676                 /*
677                  * The freemap is not used below allocator_beg or beyond
678                  * volu_size.
679                  */
680                 int nofree;
681
682                 if (data_off < cbinfo->hmp->voldata.allocator_beg)
683                         goto next;
684                 if (data_off >= cbinfo->hmp->voldata.volu_size)
685                         goto next;
686
687                 /*
688                  * Locate the freemap leaf on the live filesystem
689                  */
690                 key = (data_off & ~HAMMER2_FREEMAP_LEVEL1_MASK);
691                 nofree = 0;
692
693                 if (live_chain == NULL || live_chain->bref.key != key) {
694                         if (live_chain) {
695                                 hammer2_chain_unlock(live_chain);
696                                 hammer2_chain_drop(live_chain);
697                         }
698                         live_chain = hammer2_chain_lookup(
699                                             &live_parent,
700                                             &key_dummy,
701                                             key,
702                                             key + HAMMER2_FREEMAP_LEVEL1_MASK,
703                                             &cache_index,
704                                             HAMMER2_LOOKUP_ALWAYS);
705
706 #if 0
707                         /*
708                          * If recent allocations were made we avoid races by
709                          * not staging or freeing any blocks.  We can still
710                          * remark blocks as fully allocated.
711                          */
712                         if (live_chain) {
713                                 if (hammer2_debug & 1) {
714                                         kprintf("live_chain %016jx\n",
715                                                 (intmax_t)key);
716                                 }
717                                 if (live_chain->bref.mirror_tid >
718                                     cbinfo->saved_mirror_tid) {
719                                         kprintf("hammer2_bulkfree: "
720                                                 "avoid %016jx\n",
721                                                 data_off);
722                                         nofree = 1;
723                                 } else {
724                                         nofree = 0;
725                                 }
726                         }
727 #endif
728                 }
729                 if (live_chain == NULL) {
730                         /*
731                          * XXX if we implement a full recovery mode we need
732                          * to create/recreate missing freemap chains if our
733                          * bmap has any allocated blocks.
734                          */
735                         if (bmap->class &&
736                             bmap->avail != HAMMER2_FREEMAP_LEVEL0_SIZE) {
737                                 kprintf("hammer2_bulkfree: cannot locate "
738                                         "live leaf for allocated data "
739                                         "near %016jx\n",
740                                         (intmax_t)data_off);
741                         }
742                         goto next;
743                 }
744                 if (live_chain->error) {
745                         kprintf("hammer2_bulkfree: error %s looking up "
746                                 "live leaf for allocated data near %016jx\n",
747                                 hammer2_error_str(live_chain->error),
748                                 (intmax_t)data_off);
749                         hammer2_chain_unlock(live_chain);
750                         hammer2_chain_drop(live_chain);
751                         live_chain = NULL;
752                         goto next;
753                 }
754
755                 bmapindex = (data_off & HAMMER2_FREEMAP_LEVEL1_MASK) >>
756                             HAMMER2_FREEMAP_LEVEL0_RADIX;
757                 live = &live_chain->data->bmdata[bmapindex];
758
759                 /*
760                  * TODO - we could shortcut this by testing that both
761                  * live->class and bmap->class are 0, and both avails are
762                  * set to HAMMER2_FREEMAP_LEVEL0_SIZE (4MB).
763                  */
764                 if (bcmp(live->bitmapq, bmap->bitmapq,
765                          sizeof(bmap->bitmapq)) == 0) {
766                         goto next;
767                 }
768                 if (hammer2_debug & 1) {
769                         kprintf("live %016jx %04d.%04x (avail=%d)\n",
770                                 data_off, bmapindex, live->class, live->avail);
771                 }
772
773                 hammer2_chain_modify(live_chain, cbinfo->mtid, 0, 0);
774                 live = &live_chain->data->bmdata[bmapindex];
775
776                 h2_bulkfree_sync_adjust(cbinfo, data_off, live, bmap, nofree);
777 next:
778                 data_off += HAMMER2_FREEMAP_LEVEL0_SIZE;
779                 ++bmap;
780         }
781         if (live_chain) {
782                 hammer2_chain_unlock(live_chain);
783                 hammer2_chain_drop(live_chain);
784         }
785         if (live_parent) {
786                 hammer2_chain_unlock(live_parent);
787                 hammer2_chain_drop(live_parent);
788         }
789 }
790
791 /*
792  * When bulkfree is finally able to free a block it must make sure that
793  * the INVALOK bit in any cached DIO is cleared prior to the block being
794  * reused.
795  */
796 static
797 void
798 fixup_dio(hammer2_dev_t *hmp, hammer2_off_t data_off, int bindex, int scount)
799 {
800         data_off += (scount >> 1) * HAMMER2_FREEMAP_BLOCK_SIZE;
801         data_off += bindex *
802                 (HAMMER2_FREEMAP_BLOCK_SIZE * HAMMER2_BMAP_BLOCKS_PER_ELEMENT);
803         hammer2_io_resetinval(hmp, data_off);
804 }
805
806 /*
807  * Merge the bulkfree bitmap against the existing bitmap.
808  *
809  * If nofree is non-zero the merge will only mark free blocks as allocated
810  * and will refuse to free any blocks.
811  */
812 static
813 void
814 h2_bulkfree_sync_adjust(hammer2_bulkfree_info_t *cbinfo,
815                         hammer2_off_t data_off, hammer2_bmap_data_t *live,
816                         hammer2_bmap_data_t *bmap, int nofree)
817 {
818         int bindex;
819         int scount;
820         hammer2_bitmap_t lmask;
821         hammer2_bitmap_t mmask;
822
823         for (bindex = 0; bindex < HAMMER2_BMAP_ELEMENTS; ++bindex) {
824                 lmask = live->bitmapq[bindex];  /* live */
825                 mmask = bmap->bitmapq[bindex];  /* snapshotted bulkfree */
826                 if (lmask == mmask)
827                         continue;
828
829                 for (scount = 0;
830                      scount < HAMMER2_BMAP_BITS_PER_ELEMENT;
831                      scount += 2) {
832                         if ((mmask & 3) == 0) {
833                                 /*
834                                  * in-memory 00         live 11 -> 10
835                                  *                      live 10 -> 00
836                                  *
837                                  * Storage might be marked allocated or
838                                  * staged and must be remarked staged or
839                                  * free.
840                                  */
841                                 switch (lmask & 3) {
842                                 case 0: /* 00 */
843                                         break;
844                                 case 1: /* 01 */
845                                         kprintf("hammer2_bulkfree: cannot "
846                                                 "transition m=00/l=01\n");
847                                         break;
848                                 case 2: /* 10 -> 00 */
849                                         if (nofree)
850                                                 break;
851                                         live->bitmapq[bindex] &=
852                                             ~((hammer2_bitmap_t)2 << scount);
853                                         live->avail +=
854                                                 HAMMER2_FREEMAP_BLOCK_SIZE;
855                                         if (live->avail >
856                                             HAMMER2_FREEMAP_LEVEL0_SIZE) {
857                                                 live->avail =
858                                                     HAMMER2_FREEMAP_LEVEL0_SIZE;
859                                         }
860                                         cbinfo->adj_free +=
861                                                 HAMMER2_FREEMAP_BLOCK_SIZE;
862                                         ++cbinfo->count_10_00;
863                                         break;
864                                 case 3: /* 11 -> 10 */
865                                         live->bitmapq[bindex] &=
866                                             ~((hammer2_bitmap_t)1 << scount);
867                                         ++cbinfo->count_11_10;
868                                         fixup_dio(cbinfo->hmp, data_off,
869                                                   bindex, scount);
870                                         break;
871                                 }
872                         } else if ((mmask & 3) == 3) {
873                                 /*
874                                  * in-memory 11         live 10 -> 11
875                                  *                      live ** -> 11
876                                  *
877                                  * Storage might be incorrectly marked free
878                                  * or staged and must be remarked fully
879                                  * allocated.
880                                  */
881                                 switch (lmask & 3) {
882                                 case 0: /* 00 */
883                                         ++cbinfo->count_00_11;
884                                         cbinfo->adj_free -=
885                                                 HAMMER2_FREEMAP_BLOCK_SIZE;
886                                         live->avail -=
887                                                 HAMMER2_FREEMAP_BLOCK_SIZE;
888                                         if ((int32_t)live->avail < 0)
889                                                 live->avail = 0;
890                                         break;
891                                 case 1: /* 01 */
892                                         ++cbinfo->count_01_11;
893                                         break;
894                                 case 2: /* 10 -> 11 */
895                                         ++cbinfo->count_10_11;
896                                         break;
897                                 case 3: /* 11 */
898                                         break;
899                                 }
900                                 live->bitmapq[bindex] |=
901                                         ((hammer2_bitmap_t)3 << scount);
902                         }
903                         mmask >>= 2;
904                         lmask >>= 2;
905                 }
906         }
907
908         /*
909          * Determine if the live bitmap is completely free and reset its
910          * fields if so.  Otherwise check to see if we can reduce the linear
911          * offset.
912          */
913         for (bindex = HAMMER2_BMAP_ELEMENTS - 1; bindex >= 0; --bindex) {
914                 if (live->bitmapq[bindex] != 0)
915                         break;
916         }
917         if (nofree) {
918                 /* do nothing */
919         } else if (bindex < 0) {
920                 live->avail = HAMMER2_FREEMAP_LEVEL0_SIZE;
921                 live->class = 0;
922                 live->linear = 0;
923                 ++cbinfo->count_l0cleans;
924         } else if (bindex < 7) {
925                 ++bindex;
926                 if (live->linear > bindex * HAMMER2_FREEMAP_BLOCK_SIZE) {
927                         live->linear = bindex * HAMMER2_FREEMAP_BLOCK_SIZE;
928                         ++cbinfo->count_linadjusts;
929                 }
930
931                 /*
932                  * XXX this fine-grained measure still has some issues.
933                  */
934                 if (live->linear < bindex * HAMMER2_FREEMAP_BLOCK_SIZE) {
935                         live->linear = bindex * HAMMER2_FREEMAP_BLOCK_SIZE;
936                         ++cbinfo->count_linadjusts;
937                 }
938         } else {
939                 live->linear = HAMMER2_SEGSIZE;
940         }
941
942 #if 0
943         if (bmap->class) {
944                 kprintf("%016jx %04d.%04x (avail=%7d) "
945                         "%08x %08x %08x %08x %08x %08x %08x %08x\n",
946                         (intmax_t)data_off,
947                         (int)((data_off &
948                                HAMMER2_FREEMAP_LEVEL1_MASK) >>
949                               HAMMER2_FREEMAP_LEVEL0_RADIX),
950                         bmap->class,
951                         bmap->avail,
952                         bmap->bitmap[0], bmap->bitmap[1],
953                         bmap->bitmap[2], bmap->bitmap[3],
954                         bmap->bitmap[4], bmap->bitmap[5],
955                         bmap->bitmap[6], bmap->bitmap[7]);
956         }
957 #endif
958 }
959
960 /*
961  * BULKFREE DEDUP HEURISTIC
962  *
963  * WARNING! This code is SMP safe but the heuristic allows SMP collisions.
964  *          All fields must be loaded into locals and validated.
965  */
966 static
967 int
968 h2_bulkfree_test(hammer2_bulkfree_info_t *cbinfo, hammer2_blockref_t *bref,
969                  int pri)
970 {
971         hammer2_dedup_t *dedup;
972         int best;
973         int n;
974         int i;
975
976         n = hammer2_icrc32(&bref->data_off, sizeof(bref->data_off));
977         dedup = cbinfo->dedup + (n & (HAMMER2_DEDUP_HEUR_MASK & ~7));
978
979         for (i = best = 0; i < 8; ++i) {
980                 if (dedup[i].data_off == bref->data_off) {
981                         if (dedup[i].ticks < pri)
982                                 dedup[i].ticks = pri;
983                         if (pri == 1)
984                                 cbinfo->count_dedup_factor += dedup[i].ticks;
985                         return 1;
986                 }
987                 if (dedup[i].ticks < dedup[best].ticks)
988                         best = i;
989         }
990         dedup[best].data_off = bref->data_off;
991         dedup[best].ticks = pri;
992
993         return 0;
994 }