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