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