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(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 	parent = hammer2_inode_chain(xop->head.ip1, clindex,
314 				     HAMMER2_RESOLVE_ALWAYS |
315 				     HAMMER2_RESOLVE_SHARED);
316 	TIMER(1);
317 	if (parent) {
318 		chain = hammer2_chain_lookup(&parent, &key_dummy,
319 					     lbase, lbase,
320 					     &cache_index,
321 					     HAMMER2_LOOKUP_ALWAYS |
322 					     HAMMER2_LOOKUP_SHARED);
323 		error = chain ? chain->error : 0;
324 	} else {
325 		error = EIO;
326 		chain = NULL;
327 	}
328 	TIMER(2);
329 	error = hammer2_xop_feed(&xop->head, chain, clindex, error);
330 	TIMER(3);
331 	if (chain) {
332 		hammer2_chain_unlock(chain);
333 		hammer2_chain_drop(chain);
334 	}
335 	if (parent) {
336 		hammer2_chain_unlock(parent);
337 		hammer2_chain_drop(parent);
338 	}
339 	chain = NULL;	/* safety */
340 	parent = NULL;	/* safety */
341 	TIMER(4);
342 
343 	/*
344 	 * Race to finish the frontend
345 	 */
346 	if (xop->finished)
347 		return;
348 	hammer2_mtx_ex(&xop->lock);
349 	if (xop->finished) {
350 		hammer2_mtx_unlock(&xop->lock);
351 		return;
352 	}
353 
354 	/*
355 	 * Async operation has not completed and we now own the lock.
356 	 * Determine if we can complete the operation by issuing the
357 	 * frontend collection non-blocking.
358 	 */
359 	error = hammer2_xop_collect(&xop->head, HAMMER2_XOP_COLLECT_NOWAIT);
360 	TIMER(5);
361 
362 	switch(error) {
363 	case 0:
364 		xop->finished = 1;
365 		hammer2_mtx_unlock(&xop->lock);
366 		chain = xop->head.cluster.focus;
367 		hammer2_strategy_read_completion(chain, (char *)chain->data,
368 						 xop->bio);
369 		hammer2_xop_retire(&xop->head, HAMMER2_XOPMASK_VOP);
370 		biodone(bio);
371 		break;
372 	case ENOENT:
373 		xop->finished = 1;
374 		hammer2_mtx_unlock(&xop->lock);
375 		bp->b_resid = 0;
376 		bp->b_error = 0;
377 		bzero(bp->b_data, bp->b_bcount);
378 		biodone(bio);
379 		hammer2_xop_retire(&xop->head, HAMMER2_XOPMASK_VOP);
380 		break;
381 	case EINPROGRESS:
382 		hammer2_mtx_unlock(&xop->lock);
383 		break;
384 	default:
385 		xop->finished = 1;
386 		hammer2_mtx_unlock(&xop->lock);
387 		bp->b_flags |= B_ERROR;
388 		bp->b_error = EIO;
389 		biodone(bio);
390 		hammer2_xop_retire(&xop->head, HAMMER2_XOPMASK_VOP);
391 		break;
392 	}
393 	TIMER(6);
394 }
395 
396 static
397 void
398 hammer2_strategy_read_completion(hammer2_chain_t *chain, char *data,
399 				 struct bio *bio)
400 {
401 	struct buf *bp = bio->bio_buf;
402 
403 	if (chain->bref.type == HAMMER2_BREF_TYPE_INODE) {
404 		/*
405 		 * Data is embedded in the inode (copy from inode).
406 		 */
407 		bcopy(((hammer2_inode_data_t *)data)->u.data,
408 		      bp->b_data, HAMMER2_EMBEDDED_BYTES);
409 		bzero(bp->b_data + HAMMER2_EMBEDDED_BYTES,
410 		      bp->b_bcount - HAMMER2_EMBEDDED_BYTES);
411 		bp->b_resid = 0;
412 		bp->b_error = 0;
413 	} else if (chain->bref.type == HAMMER2_BREF_TYPE_DATA) {
414 		/*
415 		 * Data is on-media, record for live dedup.
416 		 */
417 		hammer2_dedup_record(chain, data);
418 
419 		/*
420 		 * Decopmression and copy.
421 		 */
422 		switch (HAMMER2_DEC_COMP(chain->bref.methods)) {
423 		case HAMMER2_COMP_LZ4:
424 			hammer2_decompress_LZ4_callback(data, chain->bytes,
425 							bio);
426 			break;
427 		case HAMMER2_COMP_ZLIB:
428 			hammer2_decompress_ZLIB_callback(data, chain->bytes,
429 							 bio);
430 			break;
431 		case HAMMER2_COMP_NONE:
432 			KKASSERT(chain->bytes <= bp->b_bcount);
433 			bcopy(data, bp->b_data, chain->bytes);
434 			if (chain->bytes < bp->b_bcount) {
435 				bzero(bp->b_data + chain->bytes,
436 				      bp->b_bcount - chain->bytes);
437 			}
438 			bp->b_flags |= B_NOTMETA;
439 			bp->b_resid = 0;
440 			bp->b_error = 0;
441 			break;
442 		default:
443 			panic("hammer2_strategy_read: "
444 			      "unknown compression type");
445 		}
446 	} else {
447 		panic("hammer2_strategy_read: unknown bref type");
448 	}
449 }
450 
451 /****************************************************************************
452  *				WRITE SUPPORT				    *
453  ****************************************************************************/
454 
455 /*
456  * Functions for compression in threads,
457  * from hammer2_vnops.c
458  */
459 static void hammer2_write_file_core(struct buf *bp, hammer2_inode_t *ip,
460 				hammer2_chain_t **parentp,
461 				hammer2_key_t lbase, int ioflag, int pblksize,
462 				hammer2_tid_t mtid, int *errorp);
463 static void hammer2_compress_and_write(struct buf *bp, hammer2_inode_t *ip,
464 				hammer2_chain_t **parentp,
465 				hammer2_key_t lbase, int ioflag, int pblksize,
466 				hammer2_tid_t mtid, int *errorp,
467 				int comp_algo, int check_algo);
468 static void hammer2_zero_check_and_write(struct buf *bp, hammer2_inode_t *ip,
469 				hammer2_chain_t **parentp,
470 				hammer2_key_t lbase, int ioflag, int pblksize,
471 				hammer2_tid_t mtid, int *errorp,
472 				int check_algo);
473 static int test_block_zeros(const char *buf, size_t bytes);
474 static void zero_write(struct buf *bp, hammer2_inode_t *ip,
475 				hammer2_chain_t **parentp,
476 				hammer2_key_t lbase,
477 				hammer2_tid_t mtid, int *errorp);
478 static void hammer2_write_bp(hammer2_chain_t *chain, struct buf *bp,
479 				int ioflag, int pblksize,
480 				hammer2_tid_t mtid, int *errorp,
481 				int check_algo);
482 
483 static
484 int
485 hammer2_strategy_write(struct vop_strategy_args *ap)
486 {
487 	hammer2_xop_strategy_t *xop;
488 	hammer2_pfs_t *pmp;
489 	struct bio *bio;
490 	struct buf *bp;
491 	hammer2_inode_t *ip;
492 
493 	bio = ap->a_bio;
494 	bp = bio->bio_buf;
495 	ip = VTOI(ap->a_vp);
496 	pmp = ip->pmp;
497 
498 	hammer2_lwinprog_ref(pmp);
499 	hammer2_trans_assert_strategy(pmp);
500 
501 	xop = hammer2_xop_alloc(ip, HAMMER2_XOP_MODIFYING);
502 	xop->finished = 0;
503 	xop->bio = bio;
504 	xop->lbase = bio->bio_offset;
505 	hammer2_mtx_init(&xop->lock, "h2biow");
506 	hammer2_xop_start(&xop->head, hammer2_strategy_xop_write);
507 	/* asynchronous completion */
508 
509 	hammer2_lwinprog_wait(pmp, hammer2_flush_pipe);
510 
511 	return(0);
512 }
513 
514 /*
515  * Per-node XOP (threaded).  Write the logical buffer to the media.
516  */
517 static
518 void
519 hammer2_strategy_xop_write(hammer2_xop_t *arg, int clindex)
520 {
521 	hammer2_xop_strategy_t *xop = &arg->xop_strategy;
522 	hammer2_chain_t *parent;
523 	hammer2_key_t lbase;
524 	hammer2_inode_t *ip;
525 	struct bio *bio;
526 	struct buf *bp;
527 	int error;
528 	int lblksize;
529 	int pblksize;
530 
531 	lbase = xop->lbase;
532 	bio = xop->bio;
533 	bp = bio->bio_buf;
534 	ip = xop->head.ip1;
535 
536 	/* hammer2_trans_init(parent->hmp->spmp, HAMMER2_TRANS_BUFCACHE); */
537 
538 	lblksize = hammer2_calc_logical(ip, bio->bio_offset, &lbase, NULL);
539 	pblksize = hammer2_calc_physical(ip, lbase);
540 	parent = hammer2_inode_chain(ip, clindex, HAMMER2_RESOLVE_ALWAYS);
541 	hammer2_write_file_core(bp, ip, &parent,
542 				lbase, IO_ASYNC, pblksize,
543 				xop->head.mtid, &error);
544 	if (parent) {
545 		hammer2_chain_unlock(parent);
546 		hammer2_chain_drop(parent);
547 		parent = NULL;	/* safety */
548 	}
549 	error = hammer2_xop_feed(&xop->head, NULL, clindex, error);
550 
551 	/*
552 	 * Race to finish the frontend
553 	 */
554 	if (xop->finished)
555 		return;
556 	hammer2_mtx_ex(&xop->lock);
557 	if (xop->finished) {
558 		hammer2_mtx_unlock(&xop->lock);
559 		return;
560 	}
561 
562 	/*
563 	 * Async operation has not completed and we now own the lock.
564 	 * Determine if we can complete the operation by issuing the
565 	 * frontend collection non-blocking.
566 	 */
567 	error = hammer2_xop_collect(&xop->head, HAMMER2_XOP_COLLECT_NOWAIT);
568 
569 	switch(error) {
570 	case ENOENT:
571 	case 0:
572 		xop->finished = 1;
573 		hammer2_mtx_unlock(&xop->lock);
574 		bp->b_resid = 0;
575 		bp->b_error = 0;
576 		biodone(bio);
577 		hammer2_xop_retire(&xop->head, HAMMER2_XOPMASK_VOP);
578 		hammer2_lwinprog_drop(ip->pmp);
579 		break;
580 	case EINPROGRESS:
581 		hammer2_mtx_unlock(&xop->lock);
582 		break;
583 	default:
584 		xop->finished = 1;
585 		hammer2_mtx_unlock(&xop->lock);
586 		bp->b_flags |= B_ERROR;
587 		bp->b_error = EIO;
588 		biodone(bio);
589 		hammer2_xop_retire(&xop->head, HAMMER2_XOPMASK_VOP);
590 		hammer2_lwinprog_drop(ip->pmp);
591 		break;
592 	}
593 }
594 
595 /*
596  * Wait for pending I/O to complete
597  */
598 void
599 hammer2_bioq_sync(hammer2_pfs_t *pmp)
600 {
601 	hammer2_lwinprog_wait(pmp, 0);
602 }
603 
604 /*
605  * Create a new cluster at (cparent, lbase) and assign physical storage,
606  * returning a cluster suitable for I/O.  The cluster will be in a modified
607  * state.
608  *
609  * cparent can wind up being anything.
610  *
611  * If datap is not NULL, *datap points to the real data we intend to write.
612  * If we can dedup the storage location we set *datap to NULL to indicate
613  * to the caller that a dedup occurred.
614  *
615  * NOTE: Special case for data embedded in inode.
616  */
617 static
618 hammer2_chain_t *
619 hammer2_assign_physical(hammer2_inode_t *ip, hammer2_chain_t **parentp,
620 			hammer2_key_t lbase, int pblksize,
621 			hammer2_tid_t mtid, char **datap, int *errorp)
622 {
623 	hammer2_chain_t *chain;
624 	hammer2_key_t key_dummy;
625 	hammer2_off_t dedup_off;
626 	int pradix = hammer2_getradix(pblksize);
627 	int cache_index = -1;
628 
629 	/*
630 	 * Locate the chain associated with lbase, return a locked chain.
631 	 * However, do not instantiate any data reference (which utilizes a
632 	 * device buffer) because we will be using direct IO via the
633 	 * logical buffer cache buffer.
634 	 */
635 	*errorp = 0;
636 	KKASSERT(pblksize >= HAMMER2_ALLOC_MIN);
637 retry:
638 	TIMER(30);
639 	chain = hammer2_chain_lookup(parentp, &key_dummy,
640 				     lbase, lbase,
641 				     &cache_index,
642 				     HAMMER2_LOOKUP_NODATA);
643 	if (chain == NULL) {
644 		/*
645 		 * We found a hole, create a new chain entry.
646 		 *
647 		 * NOTE: DATA chains are created without device backing
648 		 *	 store (nor do we want any).
649 		 */
650 		dedup_off = hammer2_dedup_lookup((*parentp)->hmp, datap,
651 						 pblksize);
652 		*errorp = hammer2_chain_create(parentp, &chain, ip->pmp,
653 					       lbase, HAMMER2_PBUFRADIX,
654 					       HAMMER2_BREF_TYPE_DATA,
655 					       pblksize, mtid,
656 					       dedup_off, 0);
657 		if (chain == NULL) {
658 			panic("hammer2_chain_create: par=%p error=%d\n",
659 			      *parentp, *errorp);
660 			goto retry;
661 		}
662 		/*ip->delta_dcount += pblksize;*/
663 	} else {
664 		switch (chain->bref.type) {
665 		case HAMMER2_BREF_TYPE_INODE:
666 			/*
667 			 * The data is embedded in the inode, which requires
668 			 * a bit more finess.
669 			 */
670 			hammer2_chain_modify_ip(ip, chain, mtid, 0);
671 			break;
672 		case HAMMER2_BREF_TYPE_DATA:
673 			dedup_off = hammer2_dedup_lookup(chain->hmp, datap,
674 							 pblksize);
675 			if (chain->bytes != pblksize) {
676 				hammer2_chain_resize(ip, *parentp, chain,
677 						     mtid, dedup_off,
678 						     pradix,
679 						     HAMMER2_MODIFY_OPTDATA);
680 			}
681 
682 			/*
683 			 * DATA buffers must be marked modified whether the
684 			 * data is in a logical buffer or not.  We also have
685 			 * to make this call to fixup the chain data pointers
686 			 * after resizing in case this is an encrypted or
687 			 * compressed buffer.
688 			 */
689 			hammer2_chain_modify(chain, mtid, dedup_off,
690 					     HAMMER2_MODIFY_OPTDATA);
691 			break;
692 		default:
693 			panic("hammer2_assign_physical: bad type");
694 			/* NOT REACHED */
695 			break;
696 		}
697 	}
698 	TIMER(31);
699 	return (chain);
700 }
701 
702 /*
703  * hammer2_write_file_core() - hammer2_write_thread() helper
704  *
705  * The core write function which determines which path to take
706  * depending on compression settings.  We also have to locate the
707  * related chains so we can calculate and set the check data for
708  * the blockref.
709  */
710 static
711 void
712 hammer2_write_file_core(struct buf *bp, hammer2_inode_t *ip,
713 			hammer2_chain_t **parentp,
714 			hammer2_key_t lbase, int ioflag, int pblksize,
715 			hammer2_tid_t mtid, int *errorp)
716 {
717 	hammer2_chain_t *chain;
718 	char *data = bp->b_data;
719 
720 	switch(HAMMER2_DEC_ALGO(ip->meta.comp_algo)) {
721 	case HAMMER2_COMP_NONE:
722 		/*
723 		 * We have to assign physical storage to the buffer
724 		 * we intend to dirty or write now to avoid deadlocks
725 		 * in the strategy code later.
726 		 *
727 		 * This can return NOOFFSET for inode-embedded data.
728 		 * The strategy code will take care of it in that case.
729 		 */
730 		chain = hammer2_assign_physical(ip, parentp, lbase, pblksize,
731 						mtid, &data, errorp);
732 		if (chain->bref.type == HAMMER2_BREF_TYPE_INODE) {
733 			hammer2_inode_data_t *wipdata;
734 
735 			wipdata = &chain->data->ipdata;
736 			KKASSERT(wipdata->meta.op_flags &
737 				 HAMMER2_OPFLAG_DIRECTDATA);
738 			KKASSERT(bp->b_loffset == 0);
739 			bcopy(bp->b_data, wipdata->u.data,
740 			      HAMMER2_EMBEDDED_BYTES);
741 			++hammer2_iod_file_wembed;
742 		} else if (data == NULL) {
743 			/*
744 			 * Copy of data already present on-media.
745 			 */
746 			chain->bref.methods =
747 				HAMMER2_ENC_COMP(HAMMER2_COMP_NONE) +
748 				HAMMER2_ENC_CHECK(ip->meta.check_algo);
749 			hammer2_chain_setcheck(chain, bp->b_data);
750 		} else {
751 			hammer2_write_bp(chain, bp, ioflag, pblksize,
752 					 mtid, errorp, ip->meta.check_algo);
753 		}
754 		if (chain) {
755 			hammer2_chain_unlock(chain);
756 			hammer2_chain_drop(chain);
757 		}
758 		break;
759 	case HAMMER2_COMP_AUTOZERO:
760 		/*
761 		 * Check for zero-fill only
762 		 */
763 		hammer2_zero_check_and_write(bp, ip, parentp,
764 					     lbase, ioflag, pblksize,
765 					     mtid, errorp,
766 					     ip->meta.check_algo);
767 		break;
768 	case HAMMER2_COMP_LZ4:
769 	case HAMMER2_COMP_ZLIB:
770 	default:
771 		/*
772 		 * Check for zero-fill and attempt compression.
773 		 */
774 		hammer2_compress_and_write(bp, ip, parentp,
775 					   lbase, ioflag, pblksize,
776 					   mtid, errorp,
777 					   ip->meta.comp_algo,
778 					   ip->meta.check_algo);
779 		break;
780 	}
781 }
782 
783 /*
784  * Helper
785  *
786  * Generic function that will perform the compression in compression
787  * write path. The compression algorithm is determined by the settings
788  * obtained from inode.
789  */
790 static
791 void
792 hammer2_compress_and_write(struct buf *bp, hammer2_inode_t *ip,
793 	hammer2_chain_t **parentp,
794 	hammer2_key_t lbase, int ioflag, int pblksize,
795 	hammer2_tid_t mtid, int *errorp, int comp_algo, int check_algo)
796 {
797 	hammer2_chain_t *chain;
798 	int comp_size;
799 	int comp_block_size;
800 	char *comp_buffer;
801 	char *data;
802 
803 	if (test_block_zeros(bp->b_data, pblksize)) {
804 		zero_write(bp, ip, parentp, lbase, mtid, errorp);
805 		return;
806 	}
807 
808 	comp_size = 0;
809 	comp_buffer = NULL;
810 
811 	KKASSERT(pblksize / 2 <= 32768);
812 
813 	if (ip->comp_heuristic < 8 || (ip->comp_heuristic & 7) == 0) {
814 		z_stream strm_compress;
815 		int comp_level;
816 		int ret;
817 
818 		switch(HAMMER2_DEC_ALGO(comp_algo)) {
819 		case HAMMER2_COMP_LZ4:
820 			comp_buffer = objcache_get(cache_buffer_write,
821 						   M_INTWAIT);
822 			comp_size = LZ4_compress_limitedOutput(
823 					bp->b_data,
824 					&comp_buffer[sizeof(int)],
825 					pblksize,
826 					pblksize / 2 - sizeof(int));
827 			/*
828 			 * We need to prefix with the size, LZ4
829 			 * doesn't do it for us.  Add the related
830 			 * overhead.
831 			 */
832 			*(int *)comp_buffer = comp_size;
833 			if (comp_size)
834 				comp_size += sizeof(int);
835 			break;
836 		case HAMMER2_COMP_ZLIB:
837 			comp_level = HAMMER2_DEC_LEVEL(comp_algo);
838 			if (comp_level == 0)
839 				comp_level = 6;	/* default zlib compression */
840 			else if (comp_level < 6)
841 				comp_level = 6;
842 			else if (comp_level > 9)
843 				comp_level = 9;
844 			ret = deflateInit(&strm_compress, comp_level);
845 			if (ret != Z_OK) {
846 				kprintf("HAMMER2 ZLIB: fatal error "
847 					"on deflateInit.\n");
848 			}
849 
850 			comp_buffer = objcache_get(cache_buffer_write,
851 						   M_INTWAIT);
852 			strm_compress.next_in = bp->b_data;
853 			strm_compress.avail_in = pblksize;
854 			strm_compress.next_out = comp_buffer;
855 			strm_compress.avail_out = pblksize / 2;
856 			ret = deflate(&strm_compress, Z_FINISH);
857 			if (ret == Z_STREAM_END) {
858 				comp_size = pblksize / 2 -
859 					    strm_compress.avail_out;
860 			} else {
861 				comp_size = 0;
862 			}
863 			ret = deflateEnd(&strm_compress);
864 			break;
865 		default:
866 			kprintf("Error: Unknown compression method.\n");
867 			kprintf("Comp_method = %d.\n", comp_algo);
868 			break;
869 		}
870 	}
871 
872 	if (comp_size == 0) {
873 		/*
874 		 * compression failed or turned off
875 		 */
876 		comp_block_size = pblksize;	/* safety */
877 		if (++ip->comp_heuristic > 128)
878 			ip->comp_heuristic = 8;
879 	} else {
880 		/*
881 		 * compression succeeded
882 		 */
883 		ip->comp_heuristic = 0;
884 		if (comp_size <= 1024) {
885 			comp_block_size = 1024;
886 		} else if (comp_size <= 2048) {
887 			comp_block_size = 2048;
888 		} else if (comp_size <= 4096) {
889 			comp_block_size = 4096;
890 		} else if (comp_size <= 8192) {
891 			comp_block_size = 8192;
892 		} else if (comp_size <= 16384) {
893 			comp_block_size = 16384;
894 		} else if (comp_size <= 32768) {
895 			comp_block_size = 32768;
896 		} else {
897 			panic("hammer2: WRITE PATH: "
898 			      "Weird comp_size value.");
899 			/* NOT REACHED */
900 			comp_block_size = pblksize;
901 		}
902 
903 		/*
904 		 * Must zero the remainder or dedup (which operates on a
905 		 * physical block basis) will not find matches.
906 		 */
907 		if (comp_size < comp_block_size) {
908 			bzero(comp_buffer + comp_size,
909 			      comp_block_size - comp_size);
910 		}
911 	}
912 
913 	/*
914 	 * Assign physical storage, data will be set to NULL if a live-dedup
915 	 * was successful.
916 	 */
917 	data = comp_size ? comp_buffer : bp->b_data;
918 	chain = hammer2_assign_physical(ip, parentp, lbase, comp_block_size,
919 					mtid, &data, errorp);
920 
921 	if (*errorp) {
922 		kprintf("WRITE PATH: An error occurred while "
923 			"assigning physical space.\n");
924 		KKASSERT(chain == NULL);
925 		goto done;
926 	}
927 
928 	if (chain->bref.type == HAMMER2_BREF_TYPE_INODE) {
929 		hammer2_inode_data_t *wipdata;
930 
931 		hammer2_chain_modify_ip(ip, chain, mtid, 0);
932 		wipdata = &chain->data->ipdata;
933 		KKASSERT(wipdata->meta.op_flags & HAMMER2_OPFLAG_DIRECTDATA);
934 		KKASSERT(bp->b_loffset == 0);
935 		bcopy(bp->b_data, wipdata->u.data, HAMMER2_EMBEDDED_BYTES);
936 		++hammer2_iod_file_wembed;
937 	} else if (data == NULL) {
938 		/*
939 		 * Live deduplication, a copy of the data is already present
940 		 * on the media.
941 		 */
942 		char *bdata;
943 
944 		if (comp_size) {
945 			chain->bref.methods =
946 				HAMMER2_ENC_COMP(comp_algo) +
947 				HAMMER2_ENC_CHECK(check_algo);
948 		} else {
949 			chain->bref.methods =
950 				HAMMER2_ENC_COMP(
951 					HAMMER2_COMP_NONE) +
952 				HAMMER2_ENC_CHECK(check_algo);
953 		}
954 		bdata = comp_size ? comp_buffer : bp->b_data;
955 		hammer2_chain_setcheck(chain, bdata);
956 		atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
957 	} else {
958 		hammer2_io_t *dio;
959 		char *bdata;
960 
961 		KKASSERT(chain->flags & HAMMER2_CHAIN_MODIFIED);
962 
963 		switch(chain->bref.type) {
964 		case HAMMER2_BREF_TYPE_INODE:
965 			panic("hammer2_write_bp: unexpected inode\n");
966 			break;
967 		case HAMMER2_BREF_TYPE_DATA:
968 			/*
969 			 * Optimize out the read-before-write
970 			 * if possible.
971 			 */
972 			*errorp = hammer2_io_newnz(chain->hmp,
973 						   chain->bref.data_off,
974 						   chain->bytes,
975 						   &dio);
976 			if (*errorp) {
977 				hammer2_io_brelse(&dio);
978 				kprintf("hammer2: WRITE PATH: "
979 					"dbp bread error\n");
980 				break;
981 			}
982 			bdata = hammer2_io_data(dio, chain->bref.data_off);
983 
984 			/*
985 			 * When loading the block make sure we don't
986 			 * leave garbage after the compressed data.
987 			 */
988 			if (comp_size) {
989 				chain->bref.methods =
990 					HAMMER2_ENC_COMP(comp_algo) +
991 					HAMMER2_ENC_CHECK(check_algo);
992 				bcopy(comp_buffer, bdata, comp_size);
993 			} else {
994 				chain->bref.methods =
995 					HAMMER2_ENC_COMP(
996 						HAMMER2_COMP_NONE) +
997 					HAMMER2_ENC_CHECK(check_algo);
998 				bcopy(bp->b_data, bdata, pblksize);
999 			}
1000 
1001 			/*
1002 			 * The flush code doesn't calculate check codes for
1003 			 * file data (doing so can result in excessive I/O),
1004 			 * so we do it here.
1005 			 *
1006 			 * Record for dedup only after the DIO's buffer cache
1007 			 * buffer has been updated.
1008 			 */
1009 			hammer2_chain_setcheck(chain, bdata);
1010 			hammer2_dedup_record(chain, bdata);
1011 
1012 			/*
1013 			 * Device buffer is now valid, chain is no longer in
1014 			 * the initial state.
1015 			 *
1016 			 * (No blockref table worries with file data)
1017 			 */
1018 			atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
1019 
1020 			/* Now write the related bdp. */
1021 			if (ioflag & IO_SYNC) {
1022 				/*
1023 				 * Synchronous I/O requested.
1024 				 */
1025 				hammer2_io_bwrite(&dio);
1026 			/*
1027 			} else if ((ioflag & IO_DIRECT) &&
1028 				   loff + n == pblksize) {
1029 				hammer2_io_bdwrite(&dio);
1030 			*/
1031 			} else if (ioflag & IO_ASYNC) {
1032 				hammer2_io_bawrite(&dio);
1033 			} else {
1034 				hammer2_io_bdwrite(&dio);
1035 			}
1036 			break;
1037 		default:
1038 			panic("hammer2_write_bp: bad chain type %d\n",
1039 				chain->bref.type);
1040 			/* NOT REACHED */
1041 			break;
1042 		}
1043 	}
1044 done:
1045 	if (chain) {
1046 		hammer2_chain_unlock(chain);
1047 		hammer2_chain_drop(chain);
1048 	}
1049 	if (comp_buffer)
1050 		objcache_put(cache_buffer_write, comp_buffer);
1051 }
1052 
1053 /*
1054  * Helper
1055  *
1056  * Function that performs zero-checking and writing without compression,
1057  * it corresponds to default zero-checking path.
1058  */
1059 static
1060 void
1061 hammer2_zero_check_and_write(struct buf *bp, hammer2_inode_t *ip,
1062 	hammer2_chain_t **parentp,
1063 	hammer2_key_t lbase, int ioflag, int pblksize,
1064 	hammer2_tid_t mtid, int *errorp,
1065 	int check_algo)
1066 {
1067 	hammer2_chain_t *chain;
1068 	char *data = bp->b_data;
1069 
1070 	if (test_block_zeros(bp->b_data, pblksize)) {
1071 		zero_write(bp, ip, parentp, lbase, mtid, errorp);
1072 	} else {
1073 		chain = hammer2_assign_physical(ip, parentp, lbase, pblksize,
1074 						mtid, &data, errorp);
1075 		if (data) {
1076 			hammer2_write_bp(chain, bp, ioflag, pblksize,
1077 					 mtid, errorp, check_algo);
1078 		} /* else dedup occurred */
1079 		if (chain) {
1080 			hammer2_chain_unlock(chain);
1081 			hammer2_chain_drop(chain);
1082 		}
1083 	}
1084 }
1085 
1086 /*
1087  * Helper
1088  *
1089  * A function to test whether a block of data contains only zeros,
1090  * returns TRUE (non-zero) if the block is all zeros.
1091  */
1092 static
1093 int
1094 test_block_zeros(const char *buf, size_t bytes)
1095 {
1096 	size_t i;
1097 
1098 	for (i = 0; i < bytes; i += sizeof(long)) {
1099 		if (*(const long *)(buf + i) != 0)
1100 			return (0);
1101 	}
1102 	return (1);
1103 }
1104 
1105 /*
1106  * Helper
1107  *
1108  * Function to "write" a block that contains only zeros.
1109  */
1110 static
1111 void
1112 zero_write(struct buf *bp, hammer2_inode_t *ip,
1113 	   hammer2_chain_t **parentp,
1114 	   hammer2_key_t lbase, hammer2_tid_t mtid, int *errorp __unused)
1115 {
1116 	hammer2_chain_t *chain;
1117 	hammer2_key_t key_dummy;
1118 	int cache_index = -1;
1119 
1120 	chain = hammer2_chain_lookup(parentp, &key_dummy,
1121 				     lbase, lbase,
1122 				     &cache_index,
1123 				     HAMMER2_LOOKUP_NODATA);
1124 	if (chain) {
1125 		if (chain->bref.type == HAMMER2_BREF_TYPE_INODE) {
1126 			hammer2_inode_data_t *wipdata;
1127 
1128 			hammer2_chain_modify_ip(ip, chain, mtid, 0);
1129 			wipdata = &chain->data->ipdata;
1130 			KKASSERT(wipdata->meta.op_flags &
1131 				 HAMMER2_OPFLAG_DIRECTDATA);
1132 			KKASSERT(bp->b_loffset == 0);
1133 			bzero(wipdata->u.data, HAMMER2_EMBEDDED_BYTES);
1134 			++hammer2_iod_file_wembed;
1135 		} else {
1136 			hammer2_chain_delete(*parentp, chain,
1137 					     mtid, HAMMER2_DELETE_PERMANENT);
1138 			++hammer2_iod_file_wzero;
1139 		}
1140 		hammer2_chain_unlock(chain);
1141 		hammer2_chain_drop(chain);
1142 	} else {
1143 		++hammer2_iod_file_wzero;
1144 	}
1145 }
1146 
1147 /*
1148  * Helper
1149  *
1150  * Function to write the data as it is, without performing any sort of
1151  * compression. This function is used in path without compression and
1152  * default zero-checking path.
1153  */
1154 static
1155 void
1156 hammer2_write_bp(hammer2_chain_t *chain, struct buf *bp, int ioflag,
1157 		 int pblksize,
1158 		 hammer2_tid_t mtid, int *errorp, int check_algo)
1159 {
1160 	hammer2_inode_data_t *wipdata;
1161 	hammer2_io_t *dio;
1162 	char *bdata;
1163 	int error;
1164 
1165 	error = 0;	/* XXX TODO below */
1166 
1167 	KKASSERT(chain->flags & HAMMER2_CHAIN_MODIFIED);
1168 
1169 	switch(chain->bref.type) {
1170 	case HAMMER2_BREF_TYPE_INODE:
1171 		wipdata = &chain->data->ipdata;
1172 		KKASSERT(wipdata->meta.op_flags & HAMMER2_OPFLAG_DIRECTDATA);
1173 		KKASSERT(bp->b_loffset == 0);
1174 		bcopy(bp->b_data, wipdata->u.data, HAMMER2_EMBEDDED_BYTES);
1175 		error = 0;
1176 		++hammer2_iod_file_wembed;
1177 		break;
1178 	case HAMMER2_BREF_TYPE_DATA:
1179 		error = hammer2_io_newnz(chain->hmp,
1180 					 chain->bref.data_off,
1181 					 chain->bytes, &dio);
1182 		if (error) {
1183 			hammer2_io_bqrelse(&dio);
1184 			kprintf("hammer2: WRITE PATH: "
1185 				"dbp bread error\n");
1186 			break;
1187 		}
1188 		bdata = hammer2_io_data(dio, chain->bref.data_off);
1189 
1190 		chain->bref.methods = HAMMER2_ENC_COMP(HAMMER2_COMP_NONE) +
1191 				      HAMMER2_ENC_CHECK(check_algo);
1192 		bcopy(bp->b_data, bdata, chain->bytes);
1193 
1194 		/*
1195 		 * The flush code doesn't calculate check codes for
1196 		 * file data (doing so can result in excessive I/O),
1197 		 * so we do it here.
1198 		 *
1199 		 * Record for dedup only after the DIO's buffer cache
1200 		 * buffer has been updated.
1201 		 */
1202 		hammer2_chain_setcheck(chain, bdata);
1203 		hammer2_dedup_record(chain, bdata);
1204 
1205 		/*
1206 		 * Device buffer is now valid, chain is no longer in
1207 		 * the initial state.
1208 		 *
1209 		 * (No blockref table worries with file data)
1210 		 */
1211 		atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
1212 
1213 		if (ioflag & IO_SYNC) {
1214 			/*
1215 			 * Synchronous I/O requested.
1216 			 */
1217 			hammer2_io_bwrite(&dio);
1218 		/*
1219 		} else if ((ioflag & IO_DIRECT) &&
1220 			   loff + n == pblksize) {
1221 			hammer2_io_bdwrite(&dio);
1222 		*/
1223 		} else if (ioflag & IO_ASYNC) {
1224 			hammer2_io_bawrite(&dio);
1225 		} else {
1226 			hammer2_io_bdwrite(&dio);
1227 		}
1228 		break;
1229 	default:
1230 		panic("hammer2_write_bp: bad chain type %d\n",
1231 		      chain->bref.type);
1232 		/* NOT REACHED */
1233 		error = 0;
1234 		break;
1235 	}
1236 	KKASSERT(error == 0);	/* XXX TODO */
1237 	*errorp = error;
1238 }
1239 
1240 /*
1241  * LIVE DEDUP HEURISTIC
1242  *
1243  * WARNING! This code is SMP safe but the heuristic allows SMP collisions.
1244  *	    All fields must be loaded into locals and validated.
1245  */
1246 static
1247 void
1248 hammer2_dedup_record(hammer2_chain_t *chain, char *data)
1249 {
1250 	hammer2_dev_t *hmp;
1251 	hammer2_dedup_t *dedup;
1252 	uint64_t crc;
1253 	int best = 0;
1254 	int i;
1255 	int dticks;
1256 
1257 	hmp = chain->hmp;
1258 
1259 	switch(HAMMER2_DEC_CHECK(chain->bref.methods)) {
1260 	case HAMMER2_CHECK_ISCSI32:
1261 		/*
1262 		 * XXX use the built-in crc (the dedup lookup sequencing
1263 		 * needs to be fixed so the check code is already present
1264 		 * when dedup_lookup is called)
1265 		 */
1266 #if 0
1267 		crc = (uint64_t)(uint32_t)chain->bref.check.iscsi32.value;
1268 #endif
1269 		crc = XXH64(data, chain->bytes, XXH_HAMMER2_SEED);
1270 		break;
1271 	case HAMMER2_CHECK_XXHASH64:
1272 		crc = chain->bref.check.xxhash64.value;
1273 		break;
1274 	case HAMMER2_CHECK_SHA192:
1275 		/*
1276 		 * XXX use the built-in crc (the dedup lookup sequencing
1277 		 * needs to be fixed so the check code is already present
1278 		 * when dedup_lookup is called)
1279 		 */
1280 #if 0
1281 		crc = ((uint64_t *)chain->bref.check.sha192.data)[0] ^
1282 		      ((uint64_t *)chain->bref.check.sha192.data)[1] ^
1283 		      ((uint64_t *)chain->bref.check.sha192.data)[2];
1284 #endif
1285 		crc = XXH64(data, chain->bytes, XXH_HAMMER2_SEED);
1286 		break;
1287 	default:
1288 		/*
1289 		 * Cannot dedup without a check code
1290 		 */
1291 		return;
1292 	}
1293 	dedup = &hmp->heur_dedup[crc & (HAMMER2_DEDUP_HEUR_MASK & ~3)];
1294 	for (i = 0; i < 4; ++i) {
1295 		if (dedup[i].data_crc == crc) {
1296 			best = i;
1297 			break;
1298 		}
1299 		dticks = (int)(dedup[i].ticks - dedup[best].ticks);
1300 		if (dticks < 0 || dticks > hz * 60 * 30)
1301 			best = i;
1302 	}
1303 	dedup += best;
1304 	if (hammer2_debug & 0x40000) {
1305 		kprintf("REC %04x %016jx %016jx\n",
1306 			(int)(dedup - hmp->heur_dedup),
1307 			crc,
1308 			chain->bref.data_off);
1309 	}
1310 	dedup->ticks = ticks;
1311 	dedup->data_off = chain->bref.data_off;
1312 	dedup->data_crc = crc;
1313 	atomic_set_int(&chain->flags, HAMMER2_CHAIN_DEDUP);
1314 }
1315 
1316 static
1317 hammer2_off_t
1318 hammer2_dedup_lookup(hammer2_dev_t *hmp, char **datap, int pblksize)
1319 {
1320 	hammer2_dedup_t *dedup;
1321 	hammer2_io_t *dio;
1322 	hammer2_off_t off;
1323 	uint64_t crc;
1324 	char *data;
1325 	int i;
1326 
1327 	data = *datap;
1328 	if (data == NULL)
1329 		return 0;
1330 
1331 	/*
1332 	 * XXX use the built-in crc (the dedup lookup sequencing
1333 	 * needs to be fixed so the check code is already present
1334 	 * when dedup_lookup is called)
1335 	 */
1336 	crc = XXH64(data, pblksize, XXH_HAMMER2_SEED);
1337 	dedup = &hmp->heur_dedup[crc & (HAMMER2_DEDUP_HEUR_MASK & ~3)];
1338 
1339 	if (hammer2_debug & 0x40000) {
1340 		kprintf("LOC %04x/4 %016jx\n",
1341 			(int)(dedup - hmp->heur_dedup),
1342 			crc);
1343 	}
1344 
1345 	for (i = 0; i < 4; ++i) {
1346 		off = dedup[i].data_off;
1347 		cpu_ccfence();
1348 		if (dedup[i].data_crc != crc)
1349 			continue;
1350 		if ((1 << (int)(off & HAMMER2_OFF_MASK_RADIX)) != pblksize)
1351 			continue;
1352 		dio = hammer2_io_getquick(hmp, off, pblksize);
1353 		if (dio &&
1354 		    bcmp(data, hammer2_io_data(dio, off), pblksize) == 0) {
1355 			if (hammer2_debug & 0x40000) {
1356 				kprintf("DEDUP SUCCESS %016jx\n",
1357 					(intmax_t)off);
1358 			}
1359 			hammer2_io_putblk(&dio);
1360 			*datap = NULL;
1361 			dedup[i].ticks = ticks;	/* update use */
1362 			++hammer2_iod_file_wdedup;
1363 			return off;		/* RETURN */
1364 		}
1365 		if (dio)
1366 			hammer2_io_putblk(&dio);
1367 	}
1368 	return 0;
1369 }
1370 
1371 /*
1372  * Poof.  Races are ok, if someone gets in and reuses a dedup offset
1373  * before or while we are clearing it they will also recover the freemap
1374  * entry (set it to fully allocated), so a bulkfree race can only set it
1375  * to a possibly-free state.
1376  *
1377  * XXX ok, well, not really sure races are ok but going to run with it
1378  *     for the moment.
1379  */
1380 void
1381 hammer2_dedup_clear(hammer2_dev_t *hmp)
1382 {
1383 	int i;
1384 
1385 	for (i = 0; i < HAMMER2_DEDUP_HEUR_SIZE; ++i) {
1386 		hmp->heur_dedup[i].data_off = 0;
1387 		hmp->heur_dedup[i].ticks = ticks - 1;
1388 	}
1389 }
1390