hammer2 - Fix *errorp, instrument strategy errors
[dragonfly.git] / sys / vfs / hammer2 / hammer2_strategy.c
1 /*
2  * Copyright (c) 2011-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  * by Venkatesh Srinivas <vsrinivas@dragonflybsd.org>
7  * by Daniel Flores (GSOC 2013 - mentored by Matthew Dillon, compression) 
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  *
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in
17  *    the documentation and/or other materials provided with the
18  *    distribution.
19  * 3. Neither the name of The DragonFly Project nor the names of its
20  *    contributors may be used to endorse or promote products derived
21  *    from this software without specific, prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
26  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
27  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
28  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
29  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
30  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
31  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
32  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
33  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  */
36 /*
37  * This module handles low level logical file I/O (strategy) which backs
38  * the logical buffer cache.
39  *
40  * [De]compression, zero-block, check codes, and buffer cache operations
41  * for file data is handled here.
42  *
43  * Live dedup makes its home here as well.
44  */
45
46 #include <sys/param.h>
47 #include <sys/systm.h>
48 #include <sys/kernel.h>
49 #include <sys/fcntl.h>
50 #include <sys/buf.h>
51 #include <sys/proc.h>
52 #include <sys/namei.h>
53 #include <sys/mount.h>
54 #include <sys/vnode.h>
55 #include <sys/mountctl.h>
56 #include <sys/dirent.h>
57 #include <sys/uio.h>
58 #include <sys/objcache.h>
59 #include <sys/event.h>
60 #include <sys/file.h>
61 #include <vfs/fifofs/fifo.h>
62
63 #include "hammer2.h"
64 #include "hammer2_lz4.h"
65
66 #include "zlib/hammer2_zlib.h"
67
68 struct objcache *cache_buffer_read;
69 struct objcache *cache_buffer_write;
70
71 /*
72  * Strategy code (async logical file buffer I/O from system)
73  *
74  * WARNING: The strategy code cannot safely use hammer2 transactions
75  *          as this can deadlock against vfs_sync's vfsync() call
76  *          if multiple flushes are queued.  All H2 structures must
77  *          already be present and ready for the DIO.
78  *
79  *          Reads can be initiated asynchronously, writes have to be
80  *          spooled to a separate thread for action to avoid deadlocks.
81  */
82 static void hammer2_strategy_xop_read(hammer2_xop_t *arg, int clindex);
83 static void hammer2_strategy_xop_write(hammer2_xop_t *arg, int clindex);
84 static int hammer2_strategy_read(struct vop_strategy_args *ap);
85 static int hammer2_strategy_write(struct vop_strategy_args *ap);
86 static void hammer2_strategy_read_completion(hammer2_chain_t *chain,
87                                 char *data, struct bio *bio);
88
89 static void hammer2_dedup_record(hammer2_chain_t *chain, char *data);
90 static hammer2_off_t hammer2_dedup_lookup(hammer2_dev_t *hmp,
91                         char **datap, int pblksize);
92
93 int h2timer[32];
94 int h2last;
95 int h2lid;
96
97 #define TIMER(which)    do {                            \
98         if (h2last)                                     \
99                 h2timer[h2lid] += (int)(ticks - h2last);\
100         h2last = ticks;                                 \
101         h2lid = which;                                  \
102 } while(0)
103
104 int
105 hammer2_vop_strategy(struct vop_strategy_args *ap)
106 {
107         struct bio *biop;
108         struct buf *bp;
109         int error;
110
111         biop = ap->a_bio;
112         bp = biop->bio_buf;
113
114         switch(bp->b_cmd) {
115         case BUF_CMD_READ:
116                 error = hammer2_strategy_read(ap);
117                 ++hammer2_iod_file_read;
118                 break;
119         case BUF_CMD_WRITE:
120                 error = hammer2_strategy_write(ap);
121                 ++hammer2_iod_file_write;
122                 break;
123         default:
124                 bp->b_error = error = EINVAL;
125                 bp->b_flags |= B_ERROR;
126                 biodone(biop);
127                 break;
128         }
129         return (error);
130 }
131
132 /*
133  * Return the largest contiguous physical disk range for the logical
134  * request, in bytes.
135  *
136  * (struct vnode *vp, off_t loffset, off_t *doffsetp, int *runp, int *runb)
137  *
138  * Basically disabled, the logical buffer write thread has to deal with
139  * buffers one-at-a-time.  Note that this should not prevent cluster_read()
140  * from reading-ahead, it simply prevents it from trying form a single
141  * cluster buffer for the logical request.  H2 already uses 64KB buffers!
142  */
143 int
144 hammer2_vop_bmap(struct vop_bmap_args *ap)
145 {
146         *ap->a_doffsetp = NOOFFSET;
147         if (ap->a_runp)
148                 *ap->a_runp = 0;
149         if (ap->a_runb)
150                 *ap->a_runb = 0;
151         return (EOPNOTSUPP);
152 }
153
154 /****************************************************************************
155  *                              READ SUPPORT                                *
156  ****************************************************************************/
157 /* 
158  * Callback used in read path in case that a block is compressed with LZ4.
159  */
160 static
161 void
162 hammer2_decompress_LZ4_callback(const char *data, u_int bytes, struct bio *bio)
163 {
164         struct buf *bp;
165         char *compressed_buffer;
166         int compressed_size;
167         int result;
168
169         bp = bio->bio_buf;
170
171 #if 0
172         if bio->bio_caller_info2.index &&
173               bio->bio_caller_info1.uvalue32 !=
174               crc32(bp->b_data, bp->b_bufsize) --- return error
175 #endif
176
177         KKASSERT(bp->b_bufsize <= HAMMER2_PBUFSIZE);
178         compressed_size = *(const int *)data;
179         KKASSERT((uint32_t)compressed_size <= bytes - sizeof(int));
180
181         compressed_buffer = objcache_get(cache_buffer_read, M_INTWAIT);
182         result = LZ4_decompress_safe(__DECONST(char *, &data[sizeof(int)]),
183                                      compressed_buffer,
184                                      compressed_size,
185                                      bp->b_bufsize);
186         if (result < 0) {
187                 kprintf("READ PATH: Error during decompression."
188                         "bio %016jx/%d\n",
189                         (intmax_t)bio->bio_offset, bytes);
190                 /* make sure it isn't random garbage */
191                 bzero(compressed_buffer, bp->b_bufsize);
192         }
193         KKASSERT(result <= bp->b_bufsize);
194         bcopy(compressed_buffer, bp->b_data, bp->b_bufsize);
195         if (result < bp->b_bufsize)
196                 bzero(bp->b_data + result, bp->b_bufsize - result);
197         objcache_put(cache_buffer_read, compressed_buffer);
198         bp->b_resid = 0;
199         bp->b_flags |= B_AGE;
200 }
201
202 /*
203  * Callback used in read path in case that a block is compressed with ZLIB.
204  * It is almost identical to LZ4 callback, so in theory they can be unified,
205  * but we didn't want to make changes in bio structure for that.
206  */
207 static
208 void
209 hammer2_decompress_ZLIB_callback(const char *data, u_int bytes, struct bio *bio)
210 {
211         struct buf *bp;
212         char *compressed_buffer;
213         z_stream strm_decompress;
214         int result;
215         int ret;
216
217         bp = bio->bio_buf;
218
219         KKASSERT(bp->b_bufsize <= HAMMER2_PBUFSIZE);
220         strm_decompress.avail_in = 0;
221         strm_decompress.next_in = Z_NULL;
222
223         ret = inflateInit(&strm_decompress);
224
225         if (ret != Z_OK)
226                 kprintf("HAMMER2 ZLIB: Fatal error in inflateInit.\n");
227
228         compressed_buffer = objcache_get(cache_buffer_read, M_INTWAIT);
229         strm_decompress.next_in = __DECONST(char *, data);
230
231         /* XXX supply proper size, subset of device bp */
232         strm_decompress.avail_in = bytes;
233         strm_decompress.next_out = compressed_buffer;
234         strm_decompress.avail_out = bp->b_bufsize;
235
236         ret = inflate(&strm_decompress, Z_FINISH);
237         if (ret != Z_STREAM_END) {
238                 kprintf("HAMMER2 ZLIB: Fatar error during decompression.\n");
239                 bzero(compressed_buffer, bp->b_bufsize);
240         }
241         bcopy(compressed_buffer, bp->b_data, bp->b_bufsize);
242         result = bp->b_bufsize - strm_decompress.avail_out;
243         if (result < bp->b_bufsize)
244                 bzero(bp->b_data + result, strm_decompress.avail_out);
245         objcache_put(cache_buffer_read, compressed_buffer);
246         ret = inflateEnd(&strm_decompress);
247
248         bp->b_resid = 0;
249         bp->b_flags |= B_AGE;
250 }
251
252 /*
253  * Logical buffer I/O, async read.
254  */
255 static
256 int
257 hammer2_strategy_read(struct vop_strategy_args *ap)
258 {
259         hammer2_xop_strategy_t *xop;
260         struct buf *bp;
261         struct bio *bio;
262         struct bio *nbio;
263         hammer2_inode_t *ip;
264         hammer2_key_t lbase;
265
266         bio = ap->a_bio;
267         bp = bio->bio_buf;
268         ip = VTOI(ap->a_vp);
269         nbio = push_bio(bio);
270
271         lbase = bio->bio_offset;
272         KKASSERT(((int)lbase & HAMMER2_PBUFMASK) == 0);
273
274         if (bp->b_bio1.bio_flags & BIO_SYNC) {
275                 xop = hammer2_xop_alloc(ip, 0);
276         } else {
277                 xop = hammer2_xop_alloc(ip, HAMMER2_XOP_ITERATOR);
278         }
279         xop->finished = 0;
280         xop->bio = bio;
281         xop->lbase = lbase;
282         hammer2_mtx_init(&xop->lock, "h2bior");
283         hammer2_xop_start(&xop->head, hammer2_strategy_xop_read);
284         /* asynchronous completion */
285
286         return(0);
287 }
288
289 /*
290  * Per-node XOP (threaded), do a synchronous lookup of the chain and
291  * its data.  The frontend is asynchronous, so we are also responsible
292  * for racing to terminate the frontend.
293  */
294 static
295 void
296 hammer2_strategy_xop_read(hammer2_xop_t *arg, int clindex)
297 {
298         hammer2_xop_strategy_t *xop = &arg->xop_strategy;
299         hammer2_chain_t *parent;
300         hammer2_chain_t *chain;
301         hammer2_key_t key_dummy;
302         hammer2_key_t lbase;
303         struct bio *bio;
304         struct buf *bp;
305         int cache_index = -1;
306         int error;
307
308         TIMER(0);
309         lbase = xop->lbase;
310         bio = xop->bio;
311         bp = bio->bio_buf;
312
313         /*
314          * This is difficult to optimize.  The logical buffer might be
315          * partially dirty (contain dummy zero-fill pages), which would
316          * mess up our crc calculation if we were to try a direct read.
317          * So for now we always double-buffer through the underlying
318          * storage.
319          *
320          * If not for the above problem we could conditionalize on
321          * (1) 64KB buffer, (2) one chain (not multi-master) and
322          * (3) !hammer2_double_buffer, and issue a direct read into the
323          * logical buffer.
324          */
325         parent = hammer2_inode_chain(xop->head.ip1, clindex,
326                                      HAMMER2_RESOLVE_ALWAYS |
327                                      HAMMER2_RESOLVE_SHARED);
328         TIMER(1);
329         if (parent) {
330                 chain = hammer2_chain_lookup(&parent, &key_dummy,
331                                              lbase, lbase,
332                                              &cache_index,
333                                              HAMMER2_LOOKUP_ALWAYS |
334                                              HAMMER2_LOOKUP_SHARED);
335                 error = chain ? chain->error : 0;
336         } else {
337                 error = EIO;
338                 chain = NULL;
339         }
340         TIMER(2);
341         error = hammer2_xop_feed(&xop->head, chain, clindex, error);
342         TIMER(3);
343         if (chain) {
344                 hammer2_chain_unlock(chain);
345                 hammer2_chain_drop(chain);
346         }
347         if (parent) {
348                 hammer2_chain_unlock(parent);
349                 hammer2_chain_drop(parent);
350         }
351         chain = NULL;   /* safety */
352         parent = NULL;  /* safety */
353         TIMER(4);
354
355         /*
356          * Race to finish the frontend
357          */
358         if (xop->finished)
359                 return;
360         hammer2_mtx_ex(&xop->lock);
361         if (xop->finished) {
362                 hammer2_mtx_unlock(&xop->lock);
363                 return;
364         }
365
366         /*
367          * Async operation has not completed and we now own the lock.
368          * Determine if we can complete the operation by issuing the
369          * frontend collection non-blocking.
370          */
371         error = hammer2_xop_collect(&xop->head, HAMMER2_XOP_COLLECT_NOWAIT);
372         TIMER(5);
373
374         switch(error) {
375         case 0:
376                 xop->finished = 1;
377                 hammer2_mtx_unlock(&xop->lock);
378                 chain = xop->head.cluster.focus;
379                 hammer2_strategy_read_completion(chain, (char *)chain->data,
380                                                  xop->bio);
381                 biodone(bio);
382                 hammer2_xop_retire(&xop->head, HAMMER2_XOPMASK_VOP);
383                 break;
384         case ENOENT:
385                 xop->finished = 1;
386                 hammer2_mtx_unlock(&xop->lock);
387                 bp->b_resid = 0;
388                 bp->b_error = 0;
389                 bzero(bp->b_data, bp->b_bcount);
390                 biodone(bio);
391                 hammer2_xop_retire(&xop->head, HAMMER2_XOPMASK_VOP);
392                 break;
393         case EINPROGRESS:
394                 hammer2_mtx_unlock(&xop->lock);
395                 break;
396         default:
397                 kprintf("strategy_xop_read: error %d loff=%016jx\n",
398                         error, bp->b_loffset);
399                 xop->finished = 1;
400                 hammer2_mtx_unlock(&xop->lock);
401                 bp->b_flags |= B_ERROR;
402                 bp->b_error = EIO;
403                 biodone(bio);
404                 hammer2_xop_retire(&xop->head, HAMMER2_XOPMASK_VOP);
405                 break;
406         }
407         TIMER(6);
408 }
409
410 static
411 void
412 hammer2_strategy_read_completion(hammer2_chain_t *chain, char *data,
413                                  struct bio *bio)
414 {
415         struct buf *bp = bio->bio_buf;
416
417         if (chain->bref.type == HAMMER2_BREF_TYPE_INODE) {
418                 /*
419                  * Data is embedded in the inode (copy from inode).
420                  */
421                 bcopy(((hammer2_inode_data_t *)data)->u.data,
422                       bp->b_data, HAMMER2_EMBEDDED_BYTES);
423                 bzero(bp->b_data + HAMMER2_EMBEDDED_BYTES,
424                       bp->b_bcount - HAMMER2_EMBEDDED_BYTES);
425                 bp->b_resid = 0;
426                 bp->b_error = 0;
427         } else if (chain->bref.type == HAMMER2_BREF_TYPE_DATA) {
428                 /*
429                  * Data is on-media, record for live dedup.
430                  */
431                 hammer2_dedup_record(chain, data);
432
433                 /*
434                  * Decompression and copy.
435                  */
436                 switch (HAMMER2_DEC_COMP(chain->bref.methods)) {
437                 case HAMMER2_COMP_LZ4:
438                         hammer2_decompress_LZ4_callback(data, chain->bytes,
439                                                         bio);
440                         /* b_resid set by call */
441                         break;
442                 case HAMMER2_COMP_ZLIB:
443                         hammer2_decompress_ZLIB_callback(data, chain->bytes,
444                                                          bio);
445                         /* b_resid set by call */
446                         break;
447                 case HAMMER2_COMP_NONE:
448                         KKASSERT(chain->bytes <= bp->b_bcount);
449                         bcopy(data, bp->b_data, chain->bytes);
450                         if (chain->bytes < bp->b_bcount) {
451                                 bzero(bp->b_data + chain->bytes,
452                                       bp->b_bcount - chain->bytes);
453                         }
454                         bp->b_flags |= B_NOTMETA;
455                         bp->b_resid = 0;
456                         bp->b_error = 0;
457                         break;
458                 default:
459                         panic("hammer2_strategy_read: "
460                               "unknown compression type");
461                 }
462         } else {
463                 panic("hammer2_strategy_read: unknown bref type");
464         }
465 }
466
467 /****************************************************************************
468  *                              WRITE SUPPORT                               *
469  ****************************************************************************/
470
471 /* 
472  * Functions for compression in threads,
473  * from hammer2_vnops.c
474  */
475 static void hammer2_write_file_core(struct buf *bp, hammer2_inode_t *ip,
476                                 hammer2_chain_t **parentp,
477                                 hammer2_key_t lbase, int ioflag, int pblksize,
478                                 hammer2_tid_t mtid, int *errorp);
479 static void hammer2_compress_and_write(struct buf *bp, hammer2_inode_t *ip,
480                                 hammer2_chain_t **parentp,
481                                 hammer2_key_t lbase, int ioflag, int pblksize,
482                                 hammer2_tid_t mtid, int *errorp,
483                                 int comp_algo, int check_algo);
484 static void hammer2_zero_check_and_write(struct buf *bp, hammer2_inode_t *ip,
485                                 hammer2_chain_t **parentp,
486                                 hammer2_key_t lbase, int ioflag, int pblksize,
487                                 hammer2_tid_t mtid, int *errorp,
488                                 int check_algo);
489 static int test_block_zeros(const char *buf, size_t bytes);
490 static void zero_write(struct buf *bp, hammer2_inode_t *ip,
491                                 hammer2_chain_t **parentp,
492                                 hammer2_key_t lbase,
493                                 hammer2_tid_t mtid, int *errorp);
494 static void hammer2_write_bp(hammer2_chain_t *chain, struct buf *bp,
495                                 int ioflag, int pblksize,
496                                 hammer2_tid_t mtid, int *errorp,
497                                 int check_algo);
498
499 static
500 int
501 hammer2_strategy_write(struct vop_strategy_args *ap)
502 {       
503         hammer2_xop_strategy_t *xop;
504         hammer2_pfs_t *pmp;
505         struct bio *bio;
506         struct buf *bp;
507         hammer2_inode_t *ip;
508         
509         bio = ap->a_bio;
510         bp = bio->bio_buf;
511         ip = VTOI(ap->a_vp);
512         pmp = ip->pmp;
513         
514         hammer2_lwinprog_ref(pmp);
515         hammer2_trans_assert_strategy(pmp);
516
517         xop = hammer2_xop_alloc(ip, HAMMER2_XOP_MODIFYING);
518         xop->finished = 0;
519         xop->bio = bio;
520         xop->lbase = bio->bio_offset;
521         hammer2_mtx_init(&xop->lock, "h2biow");
522         hammer2_xop_start(&xop->head, hammer2_strategy_xop_write);
523         /* asynchronous completion */
524
525         hammer2_lwinprog_wait(pmp, hammer2_flush_pipe);
526
527         return(0);
528 }
529
530 /*
531  * Per-node XOP (threaded).  Write the logical buffer to the media.
532  */
533 static
534 void
535 hammer2_strategy_xop_write(hammer2_xop_t *arg, int clindex)
536 {
537         hammer2_xop_strategy_t *xop = &arg->xop_strategy;
538         hammer2_chain_t *parent;
539         hammer2_key_t lbase;
540         hammer2_inode_t *ip;
541         struct bio *bio;
542         struct buf *bp;
543         int error;
544         int lblksize;
545         int pblksize;
546
547         lbase = xop->lbase;
548         bio = xop->bio;
549         bp = bio->bio_buf;
550         ip = xop->head.ip1;
551
552         /* hammer2_trans_init(parent->hmp->spmp, HAMMER2_TRANS_BUFCACHE); */
553
554         lblksize = hammer2_calc_logical(ip, bio->bio_offset, &lbase, NULL);
555         pblksize = hammer2_calc_physical(ip, lbase);
556         parent = hammer2_inode_chain(ip, clindex, HAMMER2_RESOLVE_ALWAYS);
557         hammer2_write_file_core(bp, ip, &parent,
558                                 lbase, IO_ASYNC, pblksize,
559                                 xop->head.mtid, &error);
560         if (parent) {
561                 hammer2_chain_unlock(parent);
562                 hammer2_chain_drop(parent);
563                 parent = NULL;  /* safety */
564         }
565         hammer2_xop_feed(&xop->head, NULL, clindex, error);
566
567         /*
568          * Race to finish the frontend
569          */
570         if (xop->finished)
571                 return;
572         hammer2_mtx_ex(&xop->lock);
573         if (xop->finished) {
574                 hammer2_mtx_unlock(&xop->lock);
575                 return;
576         }
577
578         /*
579          * Async operation has not completed and we now own the lock.
580          * Determine if we can complete the operation by issuing the
581          * frontend collection non-blocking.
582          */
583         error = hammer2_xop_collect(&xop->head, HAMMER2_XOP_COLLECT_NOWAIT);
584
585         switch(error) {
586         case ENOENT:
587         case 0:
588                 xop->finished = 1;
589                 hammer2_mtx_unlock(&xop->lock);
590                 bp->b_resid = 0;
591                 bp->b_error = 0;
592                 biodone(bio);
593                 hammer2_xop_retire(&xop->head, HAMMER2_XOPMASK_VOP);
594                 hammer2_lwinprog_drop(ip->pmp);
595                 break;
596         case EINPROGRESS:
597                 hammer2_mtx_unlock(&xop->lock);
598                 break;
599         default:
600                 kprintf("strategy_xop_write: error %d loff=%016jx\n",
601                         error, bp->b_loffset);
602                 xop->finished = 1;
603                 hammer2_mtx_unlock(&xop->lock);
604                 bp->b_flags |= B_ERROR;
605                 bp->b_error = EIO;
606                 biodone(bio);
607                 hammer2_xop_retire(&xop->head, HAMMER2_XOPMASK_VOP);
608                 hammer2_lwinprog_drop(ip->pmp);
609                 break;
610         }
611 }
612
613 /*
614  * Wait for pending I/O to complete
615  */
616 void
617 hammer2_bioq_sync(hammer2_pfs_t *pmp)
618 {
619         hammer2_lwinprog_wait(pmp, 0);
620 }
621
622 /* 
623  * Create a new cluster at (cparent, lbase) and assign physical storage,
624  * returning a cluster suitable for I/O.  The cluster will be in a modified
625  * state.
626  *
627  * cparent can wind up being anything.
628  *
629  * If datap is not NULL, *datap points to the real data we intend to write.
630  * If we can dedup the storage location we set *datap to NULL to indicate
631  * to the caller that a dedup occurred.
632  *
633  * NOTE: Special case for data embedded in inode.
634  */
635 static
636 hammer2_chain_t *
637 hammer2_assign_physical(hammer2_inode_t *ip, hammer2_chain_t **parentp,
638                         hammer2_key_t lbase, int pblksize,
639                         hammer2_tid_t mtid, char **datap, int *errorp)
640 {
641         hammer2_chain_t *chain;
642         hammer2_key_t key_dummy;
643         hammer2_off_t dedup_off;
644         int pradix = hammer2_getradix(pblksize);
645         int cache_index = -1;
646
647         /*
648          * Locate the chain associated with lbase, return a locked chain.
649          * However, do not instantiate any data reference (which utilizes a
650          * device buffer) because we will be using direct IO via the
651          * logical buffer cache buffer.
652          */
653         *errorp = 0;
654         KKASSERT(pblksize >= HAMMER2_ALLOC_MIN);
655 retry:
656         TIMER(30);
657         chain = hammer2_chain_lookup(parentp, &key_dummy,
658                                      lbase, lbase,
659                                      &cache_index,
660                                      HAMMER2_LOOKUP_NODATA);
661
662         if (chain && (chain->flags & HAMMER2_CHAIN_DELETED))
663                 kprintf("assign physical deleted chain @ %016jx\n",
664                         lbase);
665
666         if (chain == NULL) {
667                 /*
668                  * We found a hole, create a new chain entry.
669                  *
670                  * NOTE: DATA chains are created without device backing
671                  *       store (nor do we want any).
672                  */
673                 dedup_off = hammer2_dedup_lookup((*parentp)->hmp, datap,
674                                                  pblksize);
675                 *errorp = hammer2_chain_create(parentp, &chain, ip->pmp,
676                                                lbase, HAMMER2_PBUFRADIX,
677                                                HAMMER2_BREF_TYPE_DATA,
678                                                pblksize, mtid,
679                                                dedup_off, 0);
680                 if (chain == NULL) {
681                         panic("hammer2_chain_create: par=%p error=%d\n",
682                               *parentp, *errorp);
683                         goto retry;
684                 }
685                 /*ip->delta_dcount += pblksize;*/
686         } else {
687                 switch (chain->bref.type) {
688                 case HAMMER2_BREF_TYPE_INODE:
689                         /*
690                          * The data is embedded in the inode, which requires
691                          * a bit more finess.
692                          */
693                         hammer2_chain_modify_ip(ip, chain, mtid, 0);
694                         break;
695                 case HAMMER2_BREF_TYPE_DATA:
696                         dedup_off = hammer2_dedup_lookup(chain->hmp, datap,
697                                                          pblksize);
698                         if (chain->bytes != pblksize) {
699                                 hammer2_chain_resize(ip, *parentp, chain,
700                                                      mtid, dedup_off,
701                                                      pradix,
702                                                      HAMMER2_MODIFY_OPTDATA);
703                         }
704
705                         /*
706                          * DATA buffers must be marked modified whether the
707                          * data is in a logical buffer or not.  We also have
708                          * to make this call to fixup the chain data pointers
709                          * after resizing in case this is an encrypted or
710                          * compressed buffer.
711                          */
712                         hammer2_chain_modify(chain, mtid, dedup_off,
713                                              HAMMER2_MODIFY_OPTDATA);
714                         break;
715                 default:
716                         panic("hammer2_assign_physical: bad type");
717                         /* NOT REACHED */
718                         break;
719                 }
720         }
721         TIMER(31);
722         return (chain);
723 }
724
725 /* 
726  * hammer2_write_file_core() - hammer2_write_thread() helper
727  *
728  * The core write function which determines which path to take
729  * depending on compression settings.  We also have to locate the
730  * related chains so we can calculate and set the check data for
731  * the blockref.
732  */
733 static
734 void
735 hammer2_write_file_core(struct buf *bp, hammer2_inode_t *ip,
736                         hammer2_chain_t **parentp,
737                         hammer2_key_t lbase, int ioflag, int pblksize,
738                         hammer2_tid_t mtid, int *errorp)
739 {
740         hammer2_chain_t *chain;
741         char *data = bp->b_data;
742
743         *errorp = 0;
744
745         switch(HAMMER2_DEC_ALGO(ip->meta.comp_algo)) {
746         case HAMMER2_COMP_NONE:
747                 /*
748                  * We have to assign physical storage to the buffer
749                  * we intend to dirty or write now to avoid deadlocks
750                  * in the strategy code later.
751                  *
752                  * This can return NOOFFSET for inode-embedded data.
753                  * The strategy code will take care of it in that case.
754                  */
755                 chain = hammer2_assign_physical(ip, parentp, lbase, pblksize,
756                                                 mtid, &data, errorp);
757                 if (chain->bref.type == HAMMER2_BREF_TYPE_INODE) {
758                         hammer2_inode_data_t *wipdata;
759
760                         wipdata = &chain->data->ipdata;
761                         KKASSERT(wipdata->meta.op_flags &
762                                  HAMMER2_OPFLAG_DIRECTDATA);
763                         KKASSERT(bp->b_loffset == 0);
764                         bcopy(bp->b_data, wipdata->u.data,
765                               HAMMER2_EMBEDDED_BYTES);
766                         ++hammer2_iod_file_wembed;
767                 } else if (data == NULL) {
768                         /*
769                          * Copy of data already present on-media.
770                          */
771                         chain->bref.methods =
772                                 HAMMER2_ENC_COMP(HAMMER2_COMP_NONE) +
773                                 HAMMER2_ENC_CHECK(ip->meta.check_algo);
774                         hammer2_chain_setcheck(chain, bp->b_data);
775                 } else {
776                         hammer2_write_bp(chain, bp, ioflag, pblksize,
777                                          mtid, errorp, ip->meta.check_algo);
778                 }
779                 if (chain) {
780                         hammer2_chain_unlock(chain);
781                         hammer2_chain_drop(chain);
782                 }
783                 break;
784         case HAMMER2_COMP_AUTOZERO:
785                 /*
786                  * Check for zero-fill only
787                  */
788                 hammer2_zero_check_and_write(bp, ip, parentp,
789                                              lbase, ioflag, pblksize,
790                                              mtid, errorp,
791                                              ip->meta.check_algo);
792                 break;
793         case HAMMER2_COMP_LZ4:
794         case HAMMER2_COMP_ZLIB:
795         default:
796                 /*
797                  * Check for zero-fill and attempt compression.
798                  */
799                 hammer2_compress_and_write(bp, ip, parentp,
800                                            lbase, ioflag, pblksize,
801                                            mtid, errorp,
802                                            ip->meta.comp_algo,
803                                            ip->meta.check_algo);
804                 break;
805         }
806 }
807
808 /*
809  * Helper
810  *
811  * Generic function that will perform the compression in compression
812  * write path. The compression algorithm is determined by the settings
813  * obtained from inode.
814  */
815 static
816 void
817 hammer2_compress_and_write(struct buf *bp, hammer2_inode_t *ip,
818         hammer2_chain_t **parentp,
819         hammer2_key_t lbase, int ioflag, int pblksize,
820         hammer2_tid_t mtid, int *errorp, int comp_algo, int check_algo)
821 {
822         hammer2_chain_t *chain;
823         int comp_size;
824         int comp_block_size;
825         char *comp_buffer;
826         char *data;
827
828         if (test_block_zeros(bp->b_data, pblksize)) {
829                 zero_write(bp, ip, parentp, lbase, mtid, errorp);
830                 return;
831         }
832
833         comp_size = 0;
834         comp_buffer = NULL;
835
836         KKASSERT(pblksize / 2 <= 32768);
837                 
838         if (ip->comp_heuristic < 8 || (ip->comp_heuristic & 7) == 0) {
839                 z_stream strm_compress;
840                 int comp_level;
841                 int ret;
842
843                 switch(HAMMER2_DEC_ALGO(comp_algo)) {
844                 case HAMMER2_COMP_LZ4:
845                         comp_buffer = objcache_get(cache_buffer_write,
846                                                    M_INTWAIT);
847                         comp_size = LZ4_compress_limitedOutput(
848                                         bp->b_data,
849                                         &comp_buffer[sizeof(int)],
850                                         pblksize,
851                                         pblksize / 2 - sizeof(int));
852                         /*
853                          * We need to prefix with the size, LZ4
854                          * doesn't do it for us.  Add the related
855                          * overhead.
856                          */
857                         *(int *)comp_buffer = comp_size;
858                         if (comp_size)
859                                 comp_size += sizeof(int);
860                         break;
861                 case HAMMER2_COMP_ZLIB:
862                         comp_level = HAMMER2_DEC_LEVEL(comp_algo);
863                         if (comp_level == 0)
864                                 comp_level = 6; /* default zlib compression */
865                         else if (comp_level < 6)
866                                 comp_level = 6;
867                         else if (comp_level > 9)
868                                 comp_level = 9;
869                         ret = deflateInit(&strm_compress, comp_level);
870                         if (ret != Z_OK) {
871                                 kprintf("HAMMER2 ZLIB: fatal error "
872                                         "on deflateInit.\n");
873                         }
874
875                         comp_buffer = objcache_get(cache_buffer_write,
876                                                    M_INTWAIT);
877                         strm_compress.next_in = bp->b_data;
878                         strm_compress.avail_in = pblksize;
879                         strm_compress.next_out = comp_buffer;
880                         strm_compress.avail_out = pblksize / 2;
881                         ret = deflate(&strm_compress, Z_FINISH);
882                         if (ret == Z_STREAM_END) {
883                                 comp_size = pblksize / 2 -
884                                             strm_compress.avail_out;
885                         } else {
886                                 comp_size = 0;
887                         }
888                         ret = deflateEnd(&strm_compress);
889                         break;
890                 default:
891                         kprintf("Error: Unknown compression method.\n");
892                         kprintf("Comp_method = %d.\n", comp_algo);
893                         break;
894                 }
895         }
896
897         if (comp_size == 0) {
898                 /*
899                  * compression failed or turned off
900                  */
901                 comp_block_size = pblksize;     /* safety */
902                 if (++ip->comp_heuristic > 128)
903                         ip->comp_heuristic = 8;
904         } else {
905                 /*
906                  * compression succeeded
907                  */
908                 ip->comp_heuristic = 0;
909                 if (comp_size <= 1024) {
910                         comp_block_size = 1024;
911                 } else if (comp_size <= 2048) {
912                         comp_block_size = 2048;
913                 } else if (comp_size <= 4096) {
914                         comp_block_size = 4096;
915                 } else if (comp_size <= 8192) {
916                         comp_block_size = 8192;
917                 } else if (comp_size <= 16384) {
918                         comp_block_size = 16384;
919                 } else if (comp_size <= 32768) {
920                         comp_block_size = 32768;
921                 } else {
922                         panic("hammer2: WRITE PATH: "
923                               "Weird comp_size value.");
924                         /* NOT REACHED */
925                         comp_block_size = pblksize;
926                 }
927
928                 /*
929                  * Must zero the remainder or dedup (which operates on a
930                  * physical block basis) will not find matches.
931                  */
932                 if (comp_size < comp_block_size) {
933                         bzero(comp_buffer + comp_size,
934                               comp_block_size - comp_size);
935                 }
936         }
937
938         /*
939          * Assign physical storage, data will be set to NULL if a live-dedup
940          * was successful.
941          */
942         data = comp_size ? comp_buffer : bp->b_data;
943         chain = hammer2_assign_physical(ip, parentp, lbase, comp_block_size,
944                                         mtid, &data, errorp);
945
946         if (*errorp) {
947                 kprintf("WRITE PATH: An error occurred while "
948                         "assigning physical space.\n");
949                 KKASSERT(chain == NULL);
950                 goto done;
951         }
952
953         if (chain->bref.type == HAMMER2_BREF_TYPE_INODE) {
954                 hammer2_inode_data_t *wipdata;
955
956                 hammer2_chain_modify_ip(ip, chain, mtid, 0);
957                 wipdata = &chain->data->ipdata;
958                 KKASSERT(wipdata->meta.op_flags & HAMMER2_OPFLAG_DIRECTDATA);
959                 KKASSERT(bp->b_loffset == 0);
960                 bcopy(bp->b_data, wipdata->u.data, HAMMER2_EMBEDDED_BYTES);
961                 ++hammer2_iod_file_wembed;
962         } else if (data == NULL) {
963                 /*
964                  * Live deduplication, a copy of the data is already present
965                  * on the media.
966                  */
967                 char *bdata;
968
969                 if (comp_size) {
970                         chain->bref.methods =
971                                 HAMMER2_ENC_COMP(comp_algo) +
972                                 HAMMER2_ENC_CHECK(check_algo);
973                 } else {
974                         chain->bref.methods =
975                                 HAMMER2_ENC_COMP(
976                                         HAMMER2_COMP_NONE) +
977                                 HAMMER2_ENC_CHECK(check_algo);
978                 }
979                 bdata = comp_size ? comp_buffer : bp->b_data;
980                 hammer2_chain_setcheck(chain, bdata);
981                 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
982         } else {
983                 hammer2_io_t *dio;
984                 char *bdata;
985
986                 KKASSERT(chain->flags & HAMMER2_CHAIN_MODIFIED);
987
988                 switch(chain->bref.type) {
989                 case HAMMER2_BREF_TYPE_INODE:
990                         panic("hammer2_write_bp: unexpected inode\n");
991                         break;
992                 case HAMMER2_BREF_TYPE_DATA:
993                         /*
994                          * Optimize out the read-before-write
995                          * if possible.
996                          */
997                         *errorp = hammer2_io_newnz(chain->hmp,
998                                                    chain->bref.type,
999                                                    chain->bref.data_off,
1000                                                    chain->bytes,
1001                                                    &dio);
1002                         if (*errorp) {
1003                                 hammer2_io_brelse(&dio);
1004                                 kprintf("hammer2: WRITE PATH: "
1005                                         "dbp bread error\n");
1006                                 break;
1007                         }
1008                         bdata = hammer2_io_data(dio, chain->bref.data_off);
1009
1010                         /*
1011                          * When loading the block make sure we don't
1012                          * leave garbage after the compressed data.
1013                          */
1014                         if (comp_size) {
1015                                 chain->bref.methods =
1016                                         HAMMER2_ENC_COMP(comp_algo) +
1017                                         HAMMER2_ENC_CHECK(check_algo);
1018                                 bcopy(comp_buffer, bdata, comp_size);
1019                         } else {
1020                                 chain->bref.methods =
1021                                         HAMMER2_ENC_COMP(
1022                                                 HAMMER2_COMP_NONE) +
1023                                         HAMMER2_ENC_CHECK(check_algo);
1024                                 bcopy(bp->b_data, bdata, pblksize);
1025                         }
1026
1027                         /*
1028                          * The flush code doesn't calculate check codes for
1029                          * file data (doing so can result in excessive I/O),
1030                          * so we do it here.
1031                          *
1032                          * Record for dedup only after the DIO's buffer cache
1033                          * buffer has been updated.
1034                          */
1035                         hammer2_chain_setcheck(chain, bdata);
1036                         hammer2_dedup_record(chain, bdata);
1037
1038                         /*
1039                          * Device buffer is now valid, chain is no longer in
1040                          * the initial state.
1041                          *
1042                          * (No blockref table worries with file data)
1043                          */
1044                         atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
1045
1046                         /* Now write the related bdp. */
1047                         if (ioflag & IO_SYNC) {
1048                                 /*
1049                                  * Synchronous I/O requested.
1050                                  */
1051                                 hammer2_io_bwrite(&dio);
1052                         /*
1053                         } else if ((ioflag & IO_DIRECT) &&
1054                                    loff + n == pblksize) {
1055                                 hammer2_io_bdwrite(&dio);
1056                         */
1057                         } else if (ioflag & IO_ASYNC) {
1058                                 hammer2_io_bawrite(&dio);
1059                         } else {
1060                                 hammer2_io_bdwrite(&dio);
1061                         }
1062                         break;
1063                 default:
1064                         panic("hammer2_write_bp: bad chain type %d\n",
1065                                 chain->bref.type);
1066                         /* NOT REACHED */
1067                         break;
1068                 }
1069         }
1070 done:
1071         if (chain) {
1072                 hammer2_chain_unlock(chain);
1073                 hammer2_chain_drop(chain);
1074         }
1075         if (comp_buffer)
1076                 objcache_put(cache_buffer_write, comp_buffer);
1077 }
1078
1079 /*
1080  * Helper
1081  *
1082  * Function that performs zero-checking and writing without compression,
1083  * it corresponds to default zero-checking path.
1084  */
1085 static
1086 void
1087 hammer2_zero_check_and_write(struct buf *bp, hammer2_inode_t *ip,
1088         hammer2_chain_t **parentp,
1089         hammer2_key_t lbase, int ioflag, int pblksize,
1090         hammer2_tid_t mtid, int *errorp,
1091         int check_algo)
1092 {
1093         hammer2_chain_t *chain;
1094         char *data = bp->b_data;
1095
1096         if (test_block_zeros(bp->b_data, pblksize)) {
1097                 zero_write(bp, ip, parentp, lbase, mtid, errorp);
1098         } else {
1099                 chain = hammer2_assign_physical(ip, parentp, lbase, pblksize,
1100                                                 mtid, &data, errorp);
1101                 if (data) {
1102                         hammer2_write_bp(chain, bp, ioflag, pblksize,
1103                                          mtid, errorp, check_algo);
1104                 } /* else dedup occurred */
1105                 if (chain) {
1106                         hammer2_chain_unlock(chain);
1107                         hammer2_chain_drop(chain);
1108                 }
1109         }
1110 }
1111
1112 /*
1113  * Helper
1114  *
1115  * A function to test whether a block of data contains only zeros,
1116  * returns TRUE (non-zero) if the block is all zeros.
1117  */
1118 static
1119 int
1120 test_block_zeros(const char *buf, size_t bytes)
1121 {
1122         size_t i;
1123
1124         for (i = 0; i < bytes; i += sizeof(long)) {
1125                 if (*(const long *)(buf + i) != 0)
1126                         return (0);
1127         }
1128         return (1);
1129 }
1130
1131 /*
1132  * Helper
1133  *
1134  * Function to "write" a block that contains only zeros.
1135  */
1136 static
1137 void
1138 zero_write(struct buf *bp, hammer2_inode_t *ip,
1139            hammer2_chain_t **parentp,
1140            hammer2_key_t lbase, hammer2_tid_t mtid, int *errorp)
1141 {
1142         hammer2_chain_t *chain;
1143         hammer2_key_t key_dummy;
1144         int cache_index = -1;
1145
1146         *errorp = 0;
1147         chain = hammer2_chain_lookup(parentp, &key_dummy,
1148                                      lbase, lbase,
1149                                      &cache_index,
1150                                      HAMMER2_LOOKUP_NODATA);
1151         if (chain) {
1152                 if (chain->bref.type == HAMMER2_BREF_TYPE_INODE) {
1153                         hammer2_inode_data_t *wipdata;
1154
1155                         hammer2_chain_modify_ip(ip, chain, mtid, 0);
1156                         wipdata = &chain->data->ipdata;
1157                         KKASSERT(wipdata->meta.op_flags &
1158                                  HAMMER2_OPFLAG_DIRECTDATA);
1159                         KKASSERT(bp->b_loffset == 0);
1160                         bzero(wipdata->u.data, HAMMER2_EMBEDDED_BYTES);
1161                         ++hammer2_iod_file_wembed;
1162                 } else {
1163                         hammer2_chain_delete(*parentp, chain,
1164                                              mtid, HAMMER2_DELETE_PERMANENT);
1165                         ++hammer2_iod_file_wzero;
1166                 }
1167                 hammer2_chain_unlock(chain);
1168                 hammer2_chain_drop(chain);
1169         } else {
1170                 ++hammer2_iod_file_wzero;
1171         }
1172 }
1173
1174 /*
1175  * Helper
1176  *
1177  * Function to write the data as it is, without performing any sort of
1178  * compression. This function is used in path without compression and
1179  * default zero-checking path.
1180  */
1181 static
1182 void
1183 hammer2_write_bp(hammer2_chain_t *chain, struct buf *bp, int ioflag,
1184                  int pblksize,
1185                  hammer2_tid_t mtid, int *errorp, int check_algo)
1186 {
1187         hammer2_inode_data_t *wipdata;
1188         hammer2_io_t *dio;
1189         char *bdata;
1190         int error;
1191
1192         error = 0;      /* XXX TODO below */
1193
1194         KKASSERT(chain->flags & HAMMER2_CHAIN_MODIFIED);
1195
1196         switch(chain->bref.type) {
1197         case HAMMER2_BREF_TYPE_INODE:
1198                 wipdata = &chain->data->ipdata;
1199                 KKASSERT(wipdata->meta.op_flags & HAMMER2_OPFLAG_DIRECTDATA);
1200                 KKASSERT(bp->b_loffset == 0);
1201                 bcopy(bp->b_data, wipdata->u.data, HAMMER2_EMBEDDED_BYTES);
1202                 error = 0;
1203                 ++hammer2_iod_file_wembed;
1204                 break;
1205         case HAMMER2_BREF_TYPE_DATA:
1206                 error = hammer2_io_newnz(chain->hmp,
1207                                          chain->bref.type,
1208                                          chain->bref.data_off,
1209                                          chain->bytes, &dio);
1210                 if (error) {
1211                         hammer2_io_bqrelse(&dio);
1212                         kprintf("hammer2: WRITE PATH: "
1213                                 "dbp bread error\n");
1214                         break;
1215                 }
1216                 bdata = hammer2_io_data(dio, chain->bref.data_off);
1217
1218                 chain->bref.methods = HAMMER2_ENC_COMP(HAMMER2_COMP_NONE) +
1219                                       HAMMER2_ENC_CHECK(check_algo);
1220                 bcopy(bp->b_data, bdata, chain->bytes);
1221
1222                 /*
1223                  * The flush code doesn't calculate check codes for
1224                  * file data (doing so can result in excessive I/O),
1225                  * so we do it here.
1226                  *
1227                  * Record for dedup only after the DIO's buffer cache
1228                  * buffer has been updated.
1229                  */
1230                 hammer2_chain_setcheck(chain, bdata);
1231                 hammer2_dedup_record(chain, bdata);
1232
1233                 /*
1234                  * Device buffer is now valid, chain is no longer in
1235                  * the initial state.
1236                  *
1237                  * (No blockref table worries with file data)
1238                  */
1239                 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
1240
1241                 if (ioflag & IO_SYNC) {
1242                         /*
1243                          * Synchronous I/O requested.
1244                          */
1245                         hammer2_io_bwrite(&dio);
1246                 /*
1247                 } else if ((ioflag & IO_DIRECT) &&
1248                            loff + n == pblksize) {
1249                         hammer2_io_bdwrite(&dio);
1250                 */
1251                 } else if (ioflag & IO_ASYNC) {
1252                         hammer2_io_bawrite(&dio);
1253                 } else {
1254                         hammer2_io_bdwrite(&dio);
1255                 }
1256                 break;
1257         default:
1258                 panic("hammer2_write_bp: bad chain type %d\n",
1259                       chain->bref.type);
1260                 /* NOT REACHED */
1261                 error = 0;
1262                 break;
1263         }
1264         KKASSERT(error == 0);   /* XXX TODO */
1265         *errorp = error;
1266 }
1267
1268 /*
1269  * LIVE DEDUP HEURISTIC
1270  *
1271  * WARNING! This code is SMP safe but the heuristic allows SMP collisions.
1272  *          All fields must be loaded into locals and validated.
1273  */
1274 static
1275 void
1276 hammer2_dedup_record(hammer2_chain_t *chain, char *data)
1277 {
1278         hammer2_dev_t *hmp;
1279         hammer2_dedup_t *dedup;
1280         uint64_t crc;
1281         int best = 0;
1282         int i;
1283         int dticks;
1284
1285         hmp = chain->hmp;
1286
1287         switch(HAMMER2_DEC_CHECK(chain->bref.methods)) {
1288         case HAMMER2_CHECK_ISCSI32:
1289                 /*
1290                  * XXX use the built-in crc (the dedup lookup sequencing
1291                  * needs to be fixed so the check code is already present
1292                  * when dedup_lookup is called)
1293                  */
1294 #if 0
1295                 crc = (uint64_t)(uint32_t)chain->bref.check.iscsi32.value;
1296 #endif
1297                 crc = XXH64(data, chain->bytes, XXH_HAMMER2_SEED);
1298                 break;
1299         case HAMMER2_CHECK_XXHASH64:
1300                 crc = chain->bref.check.xxhash64.value;
1301                 break;
1302         case HAMMER2_CHECK_SHA192:
1303                 /*
1304                  * XXX use the built-in crc (the dedup lookup sequencing
1305                  * needs to be fixed so the check code is already present
1306                  * when dedup_lookup is called)
1307                  */
1308 #if 0
1309                 crc = ((uint64_t *)chain->bref.check.sha192.data)[0] ^
1310                       ((uint64_t *)chain->bref.check.sha192.data)[1] ^
1311                       ((uint64_t *)chain->bref.check.sha192.data)[2];
1312 #endif
1313                 crc = XXH64(data, chain->bytes, XXH_HAMMER2_SEED);
1314                 break;
1315         default:
1316                 /*
1317                  * Cannot dedup without a check code
1318                  */
1319                 return;
1320         }
1321         dedup = &hmp->heur_dedup[crc & (HAMMER2_DEDUP_HEUR_MASK & ~3)];
1322         for (i = 0; i < 4; ++i) {
1323                 if (dedup[i].data_crc == crc) {
1324                         best = i;
1325                         break;
1326                 }
1327                 dticks = (int)(dedup[i].ticks - dedup[best].ticks);
1328                 if (dticks < 0 || dticks > hz * 60 * 30)
1329                         best = i;
1330         }
1331         dedup += best;
1332         if (hammer2_debug & 0x40000) {
1333                 kprintf("REC %04x %016jx %016jx\n",
1334                         (int)(dedup - hmp->heur_dedup),
1335                         crc,
1336                         chain->bref.data_off);
1337         }
1338         dedup->ticks = ticks;
1339         dedup->data_off = chain->bref.data_off;
1340         dedup->data_crc = crc;
1341         atomic_set_int(&chain->flags, HAMMER2_CHAIN_DEDUP);
1342 }
1343
1344 static
1345 hammer2_off_t
1346 hammer2_dedup_lookup(hammer2_dev_t *hmp, char **datap, int pblksize)
1347 {
1348         hammer2_dedup_t *dedup;
1349         hammer2_io_t *dio;
1350         hammer2_off_t off;
1351         uint64_t crc;
1352         char *data;
1353         int i;
1354
1355         data = *datap;
1356         if (data == NULL)
1357                 return 0;
1358
1359         /*
1360          * XXX use the built-in crc (the dedup lookup sequencing
1361          * needs to be fixed so the check code is already present
1362          * when dedup_lookup is called)
1363          */
1364         crc = XXH64(data, pblksize, XXH_HAMMER2_SEED);
1365         dedup = &hmp->heur_dedup[crc & (HAMMER2_DEDUP_HEUR_MASK & ~3)];
1366
1367         if (hammer2_debug & 0x40000) {
1368                 kprintf("LOC %04x/4 %016jx\n",
1369                         (int)(dedup - hmp->heur_dedup),
1370                         crc);
1371         }
1372
1373         for (i = 0; i < 4; ++i) {
1374                 off = dedup[i].data_off;
1375                 cpu_ccfence();
1376                 if (dedup[i].data_crc != crc)
1377                         continue;
1378                 if ((1 << (int)(off & HAMMER2_OFF_MASK_RADIX)) != pblksize)
1379                         continue;
1380                 dio = hammer2_io_getquick(hmp, off, pblksize);
1381                 if (dio &&
1382                     bcmp(data, hammer2_io_data(dio, off), pblksize) == 0) {
1383                         if (hammer2_debug & 0x40000) {
1384                                 kprintf("DEDUP SUCCESS %016jx\n",
1385                                         (intmax_t)off);
1386                         }
1387                         hammer2_io_putblk(&dio);
1388                         *datap = NULL;
1389                         dedup[i].ticks = ticks; /* update use */
1390                         ++hammer2_iod_file_wdedup;
1391                         return off;             /* RETURN */
1392                 }
1393                 if (dio)
1394                         hammer2_io_putblk(&dio);
1395         }
1396         return 0;
1397 }
1398
1399 /*
1400  * Poof.  Races are ok, if someone gets in and reuses a dedup offset
1401  * before or while we are clearing it they will also recover the freemap
1402  * entry (set it to fully allocated), so a bulkfree race can only set it
1403  * to a possibly-free state.
1404  *
1405  * XXX ok, well, not really sure races are ok but going to run with it
1406  *     for the moment.
1407  */
1408 void
1409 hammer2_dedup_clear(hammer2_dev_t *hmp)
1410 {
1411         int i;
1412
1413         for (i = 0; i < HAMMER2_DEDUP_HEUR_SIZE; ++i) {
1414                 hmp->heur_dedup[i].data_off = 0;
1415                 hmp->heur_dedup[i].ticks = ticks - 1;
1416         }
1417 }