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