hammer2 - Refactor 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 /*
50  * breadth-first search
51  */
52 typedef struct hammer2_chain_save {
53         TAILQ_ENTRY(hammer2_chain_save) entry;
54         hammer2_chain_t *chain;
55         int pri;
56 } hammer2_chain_save_t;
57
58 TAILQ_HEAD(hammer2_chain_save_list, hammer2_chain_save);
59 typedef struct hammer2_chain_save_list hammer2_chain_save_list_t;
60
61 typedef struct hammer2_bulkfree_info {
62         hammer2_dev_t           *hmp;
63         kmem_anon_desc_t        kp;
64         hammer2_off_t           sbase;          /* sub-loop iteration */
65         hammer2_off_t           sstop;
66         hammer2_bmap_data_t     *bmap;
67         int                     depth;
68         long                    count_10_00;
69         long                    count_11_10;
70         long                    count_10_11;
71         long                    count_l0cleans;
72         long                    count_linadjusts;
73         long                    count_inodes_scanned;
74         long                    count_dedup_factor;
75         long                    bytes_scanned;
76         hammer2_off_t           adj_free;
77         hammer2_tid_t           mtid;
78         hammer2_tid_t           saved_mirror_tid;
79         time_t                  save_time;
80         hammer2_chain_save_list_t list;
81         hammer2_dedup_t         *dedup;
82         int                     pri;
83 } hammer2_bulkfree_info_t;
84
85 static int h2_bulkfree_test(hammer2_bulkfree_info_t *info,
86                         hammer2_blockref_t *bref, int pri);
87
88 /*
89  * General bulk scan function with callback.  Called with a referenced
90  * but UNLOCKED parent.  The parent is returned in the same state.
91  */
92 static
93 int
94 hammer2_bulk_scan(hammer2_chain_t *parent,
95                   int (*func)(hammer2_bulkfree_info_t *info,
96                               hammer2_blockref_t *bref),
97                   hammer2_bulkfree_info_t *info)
98 {
99         hammer2_blockref_t bref;
100         hammer2_chain_t *chain;
101         int cache_index = -1;
102         int doabort = 0;
103         int first = 1;
104
105         ++info->pri;
106
107         hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS |
108                                    HAMMER2_RESOLVE_SHARED);
109         chain = NULL;
110
111         /*
112          * Generally loop on the contents if we have not been flagged
113          * for abort.
114          *
115          * Remember that these chains are completely isolated from
116          * the frontend, so we can release locks temporarily without
117          * imploding.
118          */
119         while ((doabort & HAMMER2_BULK_ABORT) == 0 &&
120                hammer2_chain_scan(parent, &chain, &bref, &first,
121                                   &cache_index,
122                                   HAMMER2_LOOKUP_NODATA |
123                                   HAMMER2_LOOKUP_SHARED) != NULL) {
124                 /*
125                  * Process bref, chain is only non-NULL if the bref
126                  * might be recursable (its possible that we sometimes get
127                  * a non-NULL chain where the bref cannot be recursed).
128                  */
129 #if 0
130                 kprintf("SCAN %016jx\n", bref.data_off);
131                 int xerr = tsleep(&info->pri, PCATCH, "slp", hz / 10);
132                 if (xerr == EINTR || xerr == ERESTART) {
133                         doabort |= HAMMER2_BULK_ABORT;
134                 }
135 #endif
136                 ++info->pri;
137                 if (h2_bulkfree_test(info, &bref, 1))
138                         continue;
139
140                 doabort |= func(info, &bref);
141
142                 if (doabort & HAMMER2_BULK_ABORT)
143                         break;
144
145                 /*
146                  * A non-null chain is always returned if it is
147                  * recursive, otherwise a non-null chain might be
148                  * returned but usually is not when not recursive.
149                  */
150                 if (chain == NULL)
151                         continue;
152
153                 /*
154                  * Else check type and setup depth-first scan.
155                  *
156                  * Account for bytes actually read.
157                  */
158                 info->bytes_scanned += chain->bytes;
159
160                 switch(chain->bref.type) {
161                 case HAMMER2_BREF_TYPE_INODE:
162                 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
163                 case HAMMER2_BREF_TYPE_INDIRECT:
164                 case HAMMER2_BREF_TYPE_VOLUME:
165                 case HAMMER2_BREF_TYPE_FREEMAP:
166                         ++info->depth;
167                         if (info->depth > 16) {
168                                 hammer2_chain_save_t *save;
169                                 save = kmalloc(sizeof(*save), M_HAMMER2,
170                                                M_WAITOK | M_ZERO);
171                                 save->chain = chain;
172                                 hammer2_chain_ref(chain);
173                                 TAILQ_INSERT_TAIL(&info->list, save, entry);
174
175                                 /* guess */
176                                 info->pri += 10;
177                         } else {
178                                 int savepri = info->pri;
179
180                                 hammer2_chain_unlock(chain);
181                                 info->pri = 0;
182                                 doabort |= hammer2_bulk_scan(chain, func, info);
183                                 info->pri += savepri;
184                                 hammer2_chain_lock(chain,
185                                                    HAMMER2_RESOLVE_ALWAYS |
186                                                    HAMMER2_RESOLVE_SHARED);
187                         }
188                         --info->depth;
189                         break;
190                 default:
191                         /* does not recurse */
192                         break;
193                 }
194         }
195         if (chain) {
196                 hammer2_chain_unlock(chain);
197                 hammer2_chain_drop(chain);
198         }
199
200         /*
201          * Save with higher pri now that we know what it is.
202          */
203         h2_bulkfree_test(info, &parent->bref, info->pri + 1);
204
205         hammer2_chain_unlock(parent);
206
207         return doabort;
208 }
209
210 /*
211  * Bulkfree algorithm
212  *
213  * Repeat {
214  *      Chain flush (partial synchronization) XXX removed
215  *      Scan the whole topology - build in-memory freemap (mark 11)
216  *      Reconcile the in-memory freemap against the on-disk freemap.
217  *              ondisk xx -> ondisk 11 (if allocated)
218  *              ondisk 11 -> ondisk 10 (if free in-memory)
219  *              ondisk 10 -> ondisk 00 (if free in-memory) - on next pass
220  * }
221  *
222  * The topology scan may have to be performed multiple times to window
223  * freemaps which are too large to fit in kernel memory.
224  *
225  * Races are handled using a double-transition (11->10, 10->00).  The bulkfree
226  * scan snapshots the volume root's blockset and thus can run concurrent with
227  * normal operations, as long as a full flush is made between each pass to
228  * synchronize any modified chains (otherwise their blocks might be improperly
229  * freed).
230  *
231  * Temporary memory in multiples of 64KB is required to reconstruct the leaf
232  * hammer2_bmap_data blocks so they can later be compared against the live
233  * freemap.  Each 64KB block represents 128 x 16KB x 1024 = ~2 GB of storage.
234  * A 32MB save area thus represents around ~1 TB.  The temporary memory
235  * allocated can be specified.  If it is not sufficient multiple topology
236  * passes will be made.
237  */
238
239 /*
240  * Bulkfree callback info
241  */
242 static int h2_bulkfree_callback(hammer2_bulkfree_info_t *cbinfo,
243                         hammer2_blockref_t *bref);
244 static void h2_bulkfree_sync(hammer2_bulkfree_info_t *cbinfo);
245 static void h2_bulkfree_sync_adjust(hammer2_bulkfree_info_t *cbinfo,
246                         hammer2_bmap_data_t *live, hammer2_bmap_data_t *bmap,
247                         int nofree);
248
249 int
250 hammer2_bulkfree_pass(hammer2_dev_t *hmp, hammer2_ioc_bulkfree_t *bfi)
251 {
252         hammer2_bulkfree_info_t cbinfo;
253         hammer2_chain_t *vchain;
254         hammer2_chain_save_t *save;
255         hammer2_off_t incr;
256         size_t size;
257         int doabort = 0;
258
259         /*
260          * A bulkfree operations lock is required for the duration.  We
261          * must hold it across our flushes to guarantee that we never run
262          * two bulkfree passes in a row without a flush in the middle.
263          */
264         lockmgr(&hmp->bulklk, LK_EXCLUSIVE);
265
266         /*
267          * We have to clear the live dedup cache as it might have entries
268          * that are freeable as of now.  Any new entries in the dedup cache
269          * made after this point, even if they become freeable, will have
270          * previously been fully allocated and will be protected by the
271          * 2-stage bulkfree.
272          */
273         hammer2_dedup_clear(hmp);
274
275 #if 0
276         /*
277          * XXX This has been removed.  Instead of trying to flush, which
278          * appears to have a ton of races against life chains even with
279          * the two-stage scan, we simply refuse to free any blocks
280          * related to freemap chains modified after the last filesystem
281          * sync.
282          *
283          * Do a quick flush so we can snapshot vchain for any blocks that
284          * have been allocated prior to this point.  We don't need to
285          * flush vnodes, logical buffers, or dirty inodes that have not
286          * allocated blocks yet.  We do not want to flush the device buffers
287          * nor do we want to flush the actual volume root to disk here,
288          * that is not needed to perform the snapshot.
289          */
290         hammer2_flush_quick(hmp);
291 #endif
292
293         /*
294          * Setup for free pass
295          */
296         bzero(&cbinfo, sizeof(cbinfo));
297         size = (bfi->size + HAMMER2_FREEMAP_LEVELN_PSIZE - 1) &
298                ~(size_t)(HAMMER2_FREEMAP_LEVELN_PSIZE - 1);
299         cbinfo.hmp = hmp;
300         cbinfo.bmap = kmem_alloc_swapbacked(&cbinfo.kp, size);
301         cbinfo.saved_mirror_tid = hmp->voldata.mirror_tid;
302
303         cbinfo.dedup = kmalloc(sizeof(*cbinfo.dedup) * HAMMER2_DEDUP_HEUR_SIZE,
304                                M_HAMMER2, M_WAITOK | M_ZERO);
305
306         /*
307          * Normalize start point to a 2GB boundary.  We operate on a
308          * 64KB leaf bitmap boundary which represents 2GB of storage.
309          */
310         cbinfo.sbase = bfi->sbase;
311         if (cbinfo.sbase > hmp->voldata.volu_size)
312                 cbinfo.sbase = hmp->voldata.volu_size;
313         cbinfo.sbase &= ~HAMMER2_FREEMAP_LEVEL1_MASK;
314
315         /*
316          * The primary storage scan must use a snapshot of the volume
317          * root to avoid racing renames and other frontend work.
318          *
319          * Note that snapshots only snap synchronized storage, so
320          * we have to flush between each pass or we risk freeing
321          * storage allocated by the frontend.
322          */
323         vchain = hammer2_chain_bulksnap(&hmp->vchain);
324         TAILQ_INIT(&cbinfo.list);
325
326         /*
327          * Loop on a full meta-data scan as many times as required to
328          * get through all available storage.
329          */
330         while (cbinfo.sbase < hmp->voldata.volu_size) {
331                 /*
332                  * We have enough ram to represent (incr) bytes of storage.
333                  * Each 64KB of ram represents 2GB of storage.
334                  */
335                 bzero(cbinfo.bmap, size);
336                 incr = size / HAMMER2_FREEMAP_LEVELN_PSIZE *
337                        HAMMER2_FREEMAP_LEVEL1_SIZE;
338                 if (hmp->voldata.volu_size - cbinfo.sbase < incr)
339                         cbinfo.sstop = hmp->voldata.volu_size;
340                 else
341                         cbinfo.sstop = cbinfo.sbase + incr;
342                 if (hammer2_debug & 1)
343                 kprintf("bulkfree pass %016jx/%jdGB\n",
344                         (intmax_t)cbinfo.sbase,
345                         (intmax_t)incr / HAMMER2_FREEMAP_LEVEL1_SIZE);
346
347                 hammer2_trans_init(hmp->spmp, 0);
348                 cbinfo.mtid = hammer2_trans_sub(hmp->spmp);
349                 cbinfo.pri = 0;
350                 doabort |= hammer2_bulk_scan(vchain, h2_bulkfree_callback,
351                                              &cbinfo);
352
353                 while ((save = TAILQ_FIRST(&cbinfo.list)) != NULL &&
354                        doabort == 0) {
355                         TAILQ_REMOVE(&cbinfo.list, save, entry);
356                         cbinfo.pri = 0;
357                         doabort |= hammer2_bulk_scan(save->chain,
358                                                      h2_bulkfree_callback,
359                                                      &cbinfo);
360                         hammer2_chain_drop(save->chain);
361                         kfree(save, M_HAMMER2);
362                 }
363                 while (save) {
364                         TAILQ_REMOVE(&cbinfo.list, save, entry);
365                         hammer2_chain_drop(save->chain);
366                         kfree(save, M_HAMMER2);
367                         save = TAILQ_FIRST(&cbinfo.list);
368                 }
369
370                 kprintf("bulkfree lastdrop %d %d\n",
371                         vchain->refs, vchain->core.chain_count);
372
373                 /*
374                  * If complete scan succeeded we can synchronize our
375                  * in-memory freemap against live storage.  If an abort
376                  * did occur we cannot safely synchronize our partially
377                  * filled-out in-memory freemap.
378                  */
379                 if (doabort == 0) {
380                         h2_bulkfree_sync(&cbinfo);
381
382                         hammer2_voldata_lock(hmp);
383                         hammer2_voldata_modify(hmp);
384                         hmp->voldata.allocator_free += cbinfo.adj_free;
385                         hammer2_voldata_unlock(hmp);
386                 }
387
388                 /*
389                  * Cleanup for next loop.
390                  */
391                 hammer2_trans_done(hmp->spmp);
392                 if (doabort)
393                         break;
394                 cbinfo.sbase = cbinfo.sstop;
395         }
396         hammer2_chain_bulkdrop(vchain);
397         kmem_free_swapbacked(&cbinfo.kp);
398         kfree(cbinfo.dedup, M_HAMMER2);
399         cbinfo.dedup = NULL;
400
401         bfi->sstop = cbinfo.sbase;
402
403         incr = bfi->sstop / (hmp->voldata.volu_size / 10000);
404         if (incr > 10000)
405                 incr = 10000;
406
407         kprintf("bulkfree pass statistics (%d.%02d%% storage processed):\n",
408                 (int)incr / 100,
409                 (int)incr % 100);
410
411         kprintf("    transition->free   %ld\n", cbinfo.count_10_00);
412         kprintf("    transition->staged %ld\n", cbinfo.count_11_10);
413         kprintf("    raced on           %ld\n", cbinfo.count_10_11);
414         kprintf("    ~2MB segs cleaned  %ld\n", cbinfo.count_l0cleans);
415         kprintf("    linear adjusts     %ld\n", cbinfo.count_linadjusts);
416         kprintf("    dedup factor       %ld\n", cbinfo.count_dedup_factor);
417
418         lockmgr(&hmp->bulklk, LK_RELEASE);
419
420         return doabort;
421 }
422
423 static int
424 h2_bulkfree_callback(hammer2_bulkfree_info_t *cbinfo, hammer2_blockref_t *bref)
425 {
426         hammer2_bmap_data_t *bmap;
427         hammer2_off_t data_off;
428         uint16_t class;
429         size_t bytes;
430         int radix;
431         int error;
432
433         /*
434          * Check for signal and allow yield to userland during scan
435          */
436         if (hammer2_signal_check(&cbinfo->save_time))
437                 return HAMMER2_BULK_ABORT;
438         if (bref->type == HAMMER2_BREF_TYPE_INODE) {
439                 ++cbinfo->count_inodes_scanned;
440                 if ((cbinfo->count_inodes_scanned & 1023) == 0)
441                         kprintf(" inodes %6ld bytes %9ld\n",
442                                 cbinfo->count_inodes_scanned,
443                                 cbinfo->bytes_scanned);
444         }
445
446
447         /*
448          * Calculate the data offset and determine if it is within
449          * the current freemap range being gathered.
450          */
451         error = 0;
452         data_off = bref->data_off & ~HAMMER2_OFF_MASK_RADIX;
453         if (data_off < cbinfo->sbase || data_off > cbinfo->sstop)
454                 return 0;
455         if (data_off < cbinfo->hmp->voldata.allocator_beg)
456                 return 0;
457         if (data_off > cbinfo->hmp->voldata.volu_size)
458                 return 0;
459
460         /*
461          * Calculate the information needed to generate the in-memory
462          * freemap record.
463          *
464          * Hammer2 does not allow allocations to cross the L1 (2GB) boundary,
465          * it's a problem if it does.  (Or L0 (2MB) for that matter).
466          */
467         radix = (int)(bref->data_off & HAMMER2_OFF_MASK_RADIX);
468         bytes = (size_t)1 << radix;
469         class = (bref->type << 8) | hammer2_devblkradix(radix);
470
471         if (data_off + bytes > cbinfo->sstop) {
472                 kprintf("hammer2_bulkfree_scan: illegal 2GB boundary "
473                         "%016jx %016jx/%d\n",
474                         (intmax_t)bref->data_off,
475                         (intmax_t)bref->key,
476                         bref->keybits);
477                 bytes = cbinfo->sstop - data_off;       /* XXX */
478         }
479
480         /*
481          * Convert to a storage offset relative to the beginning of the
482          * storage range we are collecting.  Then lookup the level0 bmap entry.
483          */
484         data_off -= cbinfo->sbase;
485         bmap = cbinfo->bmap + (data_off >> HAMMER2_FREEMAP_LEVEL0_RADIX);
486
487         /*
488          * Convert data_off to a bmap-relative value (~2MB storage range).
489          * Adjust linear, class, and avail.
490          *
491          * Hammer2 does not allow allocations to cross the L0 (2MB) boundary,
492          */
493         data_off &= HAMMER2_FREEMAP_LEVEL0_MASK;
494         if (data_off + bytes > HAMMER2_FREEMAP_LEVEL0_SIZE) {
495                 kprintf("hammer2_bulkfree_scan: illegal 2MB boundary "
496                         "%016jx %016jx/%d\n",
497                         (intmax_t)bref->data_off,
498                         (intmax_t)bref->key,
499                         bref->keybits);
500                 bytes = HAMMER2_FREEMAP_LEVEL0_SIZE - data_off;
501         }
502
503         if (bmap->class == 0) {
504                 bmap->class = class;
505                 bmap->avail = HAMMER2_FREEMAP_LEVEL0_SIZE;
506         }
507         if (bmap->class != class) {
508                 kprintf("hammer2_bulkfree_scan: illegal mixed class "
509                         "%016jx %016jx/%d (%04x vs %04x)\n",
510                         (intmax_t)bref->data_off,
511                         (intmax_t)bref->key,
512                         bref->keybits,
513                         class, bmap->class);
514         }
515         if (bmap->linear < (int32_t)data_off + (int32_t)bytes)
516                 bmap->linear = (int32_t)data_off + (int32_t)bytes;
517
518         /*
519          * Adjust the hammer2_bitmap_t bitmap[HAMMER2_BMAP_ELEMENTS].
520          * 64-bit entries, 2 bits per entry, to code 11.
521          *
522          * NOTE: The allocation can be smaller than HAMMER2_FREEMAP_BLOCK_SIZE.
523          */
524         while (bytes > 0) {
525                 int bindex;
526                 hammer2_bitmap_t bmask;
527
528                 bindex = (int)data_off >> (HAMMER2_FREEMAP_BLOCK_RADIX +
529                                            HAMMER2_BMAP_INDEX_RADIX);
530                 bmask = (hammer2_bitmap_t)3 <<
531                         ((((int)data_off & HAMMER2_BMAP_INDEX_MASK) >>
532                          HAMMER2_FREEMAP_BLOCK_RADIX) << 1);
533
534                 /*
535                  * NOTE! The (avail) calculation is bitmap-granular.  Multiple
536                  *       sub-granular records can wind up at the same bitmap
537                  *       position.
538                  */
539                 if ((bmap->bitmapq[bindex] & bmask) == 0) {
540                         if (bytes < HAMMER2_FREEMAP_BLOCK_SIZE) {
541                                 bmap->avail -= HAMMER2_FREEMAP_BLOCK_SIZE;
542                         } else {
543                                 bmap->avail -= bytes;
544                         }
545                         bmap->bitmapq[bindex] |= bmask;
546                 }
547                 data_off += HAMMER2_FREEMAP_BLOCK_SIZE;
548                 if (bytes < HAMMER2_FREEMAP_BLOCK_SIZE)
549                         bytes = 0;
550                 else
551                         bytes -= HAMMER2_FREEMAP_BLOCK_SIZE;
552         }
553         return error;
554 }
555
556 /*
557  * Synchronize the in-memory bitmap with the live freemap.  This is not a
558  * direct copy.  Instead the bitmaps must be compared:
559  *
560  *      In-memory       Live-freemap
561  *         00             11 -> 10      (do nothing if live modified)
562  *                        10 -> 00      (do nothing if live modified)
563  *         11             10 -> 11      handles race against live
564  *                        ** -> 11      nominally warn of corruption
565  * 
566  */
567 static void
568 h2_bulkfree_sync(hammer2_bulkfree_info_t *cbinfo)
569 {
570         hammer2_off_t data_off;
571         hammer2_key_t key;
572         hammer2_key_t key_dummy;
573         hammer2_bmap_data_t *bmap;
574         hammer2_bmap_data_t *live;
575         hammer2_chain_t *live_parent;
576         hammer2_chain_t *live_chain;
577         int cache_index = -1;
578         int bmapindex;
579         int nofree;
580
581         kprintf("hammer2_bulkfree - range %016jx-%016jx\n",
582                 (intmax_t)cbinfo->sbase,
583                 (intmax_t)cbinfo->sstop);
584                 
585         data_off = cbinfo->sbase;
586         bmap = cbinfo->bmap;
587
588         live_parent = &cbinfo->hmp->fchain;
589         hammer2_chain_ref(live_parent);
590         hammer2_chain_lock(live_parent, HAMMER2_RESOLVE_ALWAYS);
591         live_chain = NULL;
592         nofree = 1;     /* safety */
593
594         while (data_off < cbinfo->sstop) {
595                 /*
596                  * The freemap is not used below allocator_beg or beyond
597                  * volu_size.
598                  */
599                 if (data_off < cbinfo->hmp->voldata.allocator_beg)
600                         goto next;
601                 if (data_off > cbinfo->hmp->voldata.volu_size)
602                         goto next;
603
604                 /*
605                  * Locate the freemap leaf on the live filesystem
606                  */
607                 key = (data_off & ~HAMMER2_FREEMAP_LEVEL1_MASK);
608                 if (live_chain == NULL || live_chain->bref.key != key) {
609                         if (live_chain) {
610                                 hammer2_chain_unlock(live_chain);
611                                 hammer2_chain_drop(live_chain);
612                         }
613                         live_chain = hammer2_chain_lookup(
614                                             &live_parent,
615                                             &key_dummy,
616                                             key,
617                                             key + HAMMER2_FREEMAP_LEVEL1_MASK,
618                                             &cache_index,
619                                             HAMMER2_LOOKUP_ALWAYS);
620                         /*
621                          * If recent allocations were made we avoid races by
622                          * not freeing any blocks.
623                          */
624                         if (live_chain) {
625                                 kprintf("live_chain %016jx\n", (intmax_t)key);
626                                 if (live_chain->bref.mirror_tid >
627                                     cbinfo->saved_mirror_tid) {
628                                         kprintf("hammer2_bulkfree: "
629                                                 "avoid %016jx\n",
630                                                 data_off);
631                                         nofree = 1;
632                                 } else {
633                                         nofree = 0;
634                                 }
635                         }
636                                         
637                 }
638                 if (live_chain == NULL) {
639                         if (bmap->class &&
640                             bmap->avail != HAMMER2_FREEMAP_LEVEL0_SIZE) {
641                                 kprintf("hammer2_bulkfree: cannot locate "
642                                         "live leaf for allocated data "
643                                         "near %016jx\n",
644                                         (intmax_t)data_off);
645                         }
646                         goto next;
647                 }
648                 if (live_chain->error) {
649                         kprintf("hammer2_bulkfree: error %s looking up "
650                                 "live leaf for allocated data near %016jx\n",
651                                 hammer2_error_str(live_chain->error),
652                                 (intmax_t)data_off);
653                         hammer2_chain_unlock(live_chain);
654                         hammer2_chain_drop(live_chain);
655                         live_chain = NULL;
656                         goto next;
657                 }
658
659                 bmapindex = (data_off & HAMMER2_FREEMAP_LEVEL1_MASK) >>
660                             HAMMER2_FREEMAP_LEVEL0_RADIX;
661                 live = &live_chain->data->bmdata[bmapindex];
662
663                 /*
664                  * For now just handle the 11->10, 10->00, and 10->11
665                  * transitions.
666                  */
667                 if (live->class == 0 ||
668                     live->avail == HAMMER2_FREEMAP_LEVEL0_SIZE) {
669                         goto next;
670                 }
671                 if (bcmp(live->bitmapq, bmap->bitmapq,
672                          sizeof(bmap->bitmapq)) == 0) {
673                         goto next;
674                 }
675                 if (hammer2_debug & 1)
676                 kprintf("live %016jx %04d.%04x (avail=%d)\n",
677                         data_off, bmapindex, live->class, live->avail);
678
679                 hammer2_chain_modify(live_chain, cbinfo->mtid, 0, 0);
680                 h2_bulkfree_sync_adjust(cbinfo, live, bmap, nofree);
681 next:
682                 data_off += HAMMER2_FREEMAP_LEVEL0_SIZE;
683                 ++bmap;
684         }
685         if (live_chain) {
686                 hammer2_chain_unlock(live_chain);
687                 hammer2_chain_drop(live_chain);
688         }
689         if (live_parent) {
690                 hammer2_chain_unlock(live_parent);
691                 hammer2_chain_drop(live_parent);
692         }
693 }
694
695 /*
696  * Merge the bulkfree bitmap against the existing bitmap.
697  *
698  * If nofree is non-zero the merge will only mark free blocks as allocated
699  * and will refuse to free any blocks.
700  */
701 static
702 void
703 h2_bulkfree_sync_adjust(hammer2_bulkfree_info_t *cbinfo,
704                         hammer2_bmap_data_t *live, hammer2_bmap_data_t *bmap,
705                         int nofree)
706 {
707         int bindex;
708         int scount;
709         hammer2_bitmap_t lmask;
710         hammer2_bitmap_t mmask;
711
712         for (bindex = 0; bindex < HAMMER2_BMAP_ELEMENTS; ++bindex) {
713                 lmask = live->bitmapq[bindex];
714                 mmask = bmap->bitmapq[bindex];
715                 if (lmask == mmask)
716                         continue;
717
718                 for (scount = 0;
719                      scount < HAMMER2_BMAP_BITS_PER_ELEMENT;
720                      scount += 2) {
721                         if ((mmask & 3) == 0) {
722                                 /*
723                                  * in-memory 00         live 11 -> 10
724                                  *                      live 10 -> 00
725                                  */
726                                 switch (lmask & 3) {
727                                 case 0: /* 00 */
728                                         break;
729                                 case 1: /* 01 */
730                                         kprintf("hammer2_bulkfree: cannot "
731                                                 "transition m=00/l=01\n");
732                                         break;
733                                 case 2: /* 10 -> 00 */
734                                         if (nofree)
735                                                 break;
736                                         live->bitmapq[bindex] &=
737                                             ~((hammer2_bitmap_t)2 << scount);
738                                         live->avail +=
739                                                 HAMMER2_FREEMAP_BLOCK_SIZE;
740                                         cbinfo->adj_free +=
741                                                 HAMMER2_FREEMAP_BLOCK_SIZE;
742                                         ++cbinfo->count_10_00;
743                                         break;
744                                 case 3: /* 11 -> 10 */
745                                         if (nofree)
746                                                 break;
747                                         live->bitmapq[bindex] &=
748                                             ~((hammer2_bitmap_t)1 << scount);
749                                         ++cbinfo->count_11_10;
750                                         break;
751                                 }
752                         } else if ((lmask & 3) == 3) {
753                                 /*
754                                  * in-memory 11         live 10 -> 11
755                                  *                      live ** -> 11
756                                  */
757                                 switch (lmask & 3) {
758                                 case 0: /* 00 */
759                                         kprintf("hammer2_bulkfree: cannot "
760                                                 "transition m=11/l=00\n");
761                                         break;
762                                 case 1: /* 01 */
763                                         kprintf("hammer2_bulkfree: cannot "
764                                                 "transition m=11/l=01\n");
765                                         break;
766                                 case 2: /* 10 -> 11 */
767                                         live->bitmapq[bindex] |=
768                                                 ((hammer2_bitmap_t)1 << scount);
769                                         ++cbinfo->count_10_11;
770                                         break;
771                                 case 3: /* 11 */
772                                         break;
773                                 }
774                         }
775                         mmask >>= 2;
776                         lmask >>= 2;
777                 }
778         }
779
780         /*
781          * Determine if the live bitmap is completely free and reset its
782          * fields if so.  Otherwise check to see if we can reduce the linear
783          * offset.
784          */
785         for (bindex = HAMMER2_BMAP_ELEMENTS - 1; bindex >= 0; --bindex) {
786                 if (live->bitmapq[bindex] != 0)
787                         break;
788         }
789         if (bindex < 0) {
790                 live->avail = HAMMER2_FREEMAP_LEVEL0_SIZE;
791                 live->class = 0;
792                 live->linear = 0;
793                 ++cbinfo->count_l0cleans;
794         } else if (bindex < 7) {
795                 ++bindex;
796                 if (live->linear > bindex * HAMMER2_FREEMAP_BLOCK_SIZE) {
797                         live->linear = bindex * HAMMER2_FREEMAP_BLOCK_SIZE;
798                         ++cbinfo->count_linadjusts;
799                 }
800         }
801
802 #if 0
803         if (bmap->class) {
804                 kprintf("%016jx %04d.%04x (avail=%7d) "
805                         "%08x %08x %08x %08x %08x %08x %08x %08x\n",
806                         (intmax_t)data_off,
807                         (int)((data_off &
808                                HAMMER2_FREEMAP_LEVEL1_MASK) >>
809                               HAMMER2_FREEMAP_LEVEL0_RADIX),
810                         bmap->class,
811                         bmap->avail,
812                         bmap->bitmap[0], bmap->bitmap[1],
813                         bmap->bitmap[2], bmap->bitmap[3],
814                         bmap->bitmap[4], bmap->bitmap[5],
815                         bmap->bitmap[6], bmap->bitmap[7]);
816         }
817 #endif
818 }
819
820 /*
821  * BULKFREE DEDUP HEURISTIC
822  *
823  * WARNING! This code is SMP safe but the heuristic allows SMP collisions.
824  *          All fields must be loaded into locals and validated.
825  */
826 static
827 int
828 h2_bulkfree_test(hammer2_bulkfree_info_t *cbinfo, hammer2_blockref_t *bref,
829                  int pri)
830 {
831         hammer2_dedup_t *dedup;
832         int best;
833         int n;
834         int i;
835
836         n = hammer2_icrc32(&bref->data_off, sizeof(bref->data_off));
837         dedup = cbinfo->dedup + (n & (HAMMER2_DEDUP_HEUR_MASK & ~7));
838
839         for (i = best = 0; i < 8; ++i) {
840                 if (dedup[i].data_off == bref->data_off) {
841                         if (dedup[i].ticks < pri)
842                                 dedup[i].ticks = pri;
843                         if (pri == 1)
844                                 cbinfo->count_dedup_factor += dedup[i].ticks;
845                         return 1;
846                 }
847                 if (dedup[i].ticks < dedup[best].ticks)
848                         best = i;
849         }
850         dedup[best].data_off = bref->data_off;
851         dedup[best].ticks = pri;
852
853         return 0;
854 }