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(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: Fatar 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(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, 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(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(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 	hammer2_off_t bio_offset;
555 	char *bio_data;
556 
557 	/*
558 	 * We can only access the bp/bio if the frontend has not yet
559 	 * completed.
560 	 */
561 	if (xop->finished)
562 		return;
563 	hammer2_mtx_sh(&xop->lock);
564 	if (xop->finished) {
565 		hammer2_mtx_unlock(&xop->lock);
566 		return;
567 	}
568 
569 	lbase = xop->lbase;
570 	bio = xop->bio;			/* ephermal */
571 	bp = bio->bio_buf;		/* ephermal */
572 	ip = xop->head.ip1;		/* retained by ref */
573 	bio_offset = bio->bio_offset;
574 	bio_data = scratch;
575 
576 	/* hammer2_trans_init(parent->hmp->spmp, HAMMER2_TRANS_BUFCACHE); */
577 
578 	lblksize = hammer2_calc_logical(ip, bio->bio_offset, &lbase, NULL);
579 	pblksize = hammer2_calc_physical(ip, lbase);
580 	bkvasync(bp);
581 	KKASSERT(lblksize <= MAXPHYS);
582 	bcopy(bp->b_data, bio_data, lblksize);
583 
584 	hammer2_mtx_unlock(&xop->lock);
585 	bp = NULL;	/* safety, illegal to access after unlock */
586 	bio = NULL;	/* safety, illegal to access after unlock */
587 
588 	/*
589 	 * Actual operation
590 	 */
591 	parent = hammer2_inode_chain(ip, clindex, HAMMER2_RESOLVE_ALWAYS);
592 	hammer2_write_file_core(bio_data, ip, &parent,
593 				lbase, IO_ASYNC, pblksize,
594 				xop->head.mtid, &error);
595 	if (parent) {
596 		hammer2_chain_unlock(parent);
597 		hammer2_chain_drop(parent);
598 		parent = NULL;	/* safety */
599 	}
600 	hammer2_xop_feed(&xop->head, NULL, clindex, error);
601 
602 	/*
603 	 * Try to complete the operation on behalf of the front-end.
604 	 */
605 	if (xop->finished)
606 		return;
607 	hammer2_mtx_ex(&xop->lock);
608 	if (xop->finished) {
609 		hammer2_mtx_unlock(&xop->lock);
610 		return;
611 	}
612 
613 	/*
614 	 * Async operation has not completed and we now own the lock.
615 	 * Determine if we can complete the operation by issuing the
616 	 * frontend collection non-blocking.
617 	 *
618 	 * H2 double-buffers the data, setting B_NOTMETA on the logical
619 	 * buffer hints to the OS that the logical buffer should not be
620 	 * swapcached (since the device buffer can be).
621 	 */
622 	error = hammer2_xop_collect(&xop->head, HAMMER2_XOP_COLLECT_NOWAIT);
623 
624 	if (error == HAMMER2_ERROR_EINPROGRESS) {
625 		hammer2_mtx_unlock(&xop->lock);
626 		return;
627 	}
628 
629 	/*
630 	 * Async operation has completed.
631 	 */
632 	xop->finished = 1;
633 	hammer2_mtx_unlock(&xop->lock);
634 
635 	bio = xop->bio;		/* now owned by us */
636 	bp = bio->bio_buf;	/* now owned by us */
637 
638 	if (error == HAMMER2_ERROR_ENOENT || error == 0) {
639 		bp->b_flags |= B_NOTMETA;
640 		bp->b_resid = 0;
641 		bp->b_error = 0;
642 		biodone(bio);
643 	} else {
644 		kprintf("xop_strategy_write: error %d loff=%016jx\n",
645 			error, bp->b_loffset);
646 		bp->b_flags |= B_ERROR;
647 		bp->b_error = EIO;
648 		biodone(bio);
649 	}
650 	hammer2_xop_retire(&xop->head, HAMMER2_XOPMASK_VOP);
651 	hammer2_trans_assert_strategy(ip->pmp);
652 	hammer2_lwinprog_drop(ip->pmp);
653 	hammer2_trans_done(ip->pmp, HAMMER2_TRANS_BUFCACHE);
654 }
655 
656 /*
657  * Wait for pending I/O to complete
658  */
659 void
660 hammer2_bioq_sync(hammer2_pfs_t *pmp)
661 {
662 	hammer2_lwinprog_wait(pmp, 0);
663 }
664 
665 /*
666  * Assign physical storage at (cparent, lbase), returning a suitable chain
667  * and setting *errorp appropriately.
668  *
669  * If no error occurs, the returned chain will be in a modified state.
670  *
671  * If an error occurs, the returned chain may or may not be NULL.  If
672  * not-null any chain->error (if not 0) will also be rolled up into *errorp.
673  * So the caller only needs to test *errorp.
674  *
675  * cparent can wind up being anything.
676  *
677  * If datap is not NULL, *datap points to the real data we intend to write.
678  * If we can dedup the storage location we set *datap to NULL to indicate
679  * to the caller that a dedup occurred.
680  *
681  * NOTE: Special case for data embedded in inode.
682  */
683 static
684 hammer2_chain_t *
685 hammer2_assign_physical(hammer2_inode_t *ip, hammer2_chain_t **parentp,
686 			hammer2_key_t lbase, int pblksize,
687 			hammer2_tid_t mtid, char **datap, int *errorp)
688 {
689 	hammer2_chain_t *chain;
690 	hammer2_key_t key_dummy;
691 	hammer2_off_t dedup_off;
692 	int pradix = hammer2_getradix(pblksize);
693 
694 	/*
695 	 * Locate the chain associated with lbase, return a locked chain.
696 	 * However, do not instantiate any data reference (which utilizes a
697 	 * device buffer) because we will be using direct IO via the
698 	 * logical buffer cache buffer.
699 	 */
700 	KKASSERT(pblksize >= HAMMER2_ALLOC_MIN);
701 
702 	chain = hammer2_chain_lookup(parentp, &key_dummy,
703 				     lbase, lbase,
704 				     errorp,
705 				     HAMMER2_LOOKUP_NODATA);
706 
707 	/*
708 	 * The lookup code should not return a DELETED chain to us, unless
709 	 * its a short-file embedded in the inode.  Then it is possible for
710 	 * the lookup to return a deleted inode.
711 	 */
712 	if (chain && (chain->flags & HAMMER2_CHAIN_DELETED) &&
713 	    chain->bref.type != HAMMER2_BREF_TYPE_INODE) {
714 		kprintf("assign physical deleted chain @ "
715 			"%016jx (%016jx.%02x) ip %016jx\n",
716 			lbase, chain->bref.data_off, chain->bref.type,
717 			ip->meta.inum);
718 		Debugger("bleh");
719 	}
720 
721 	if (chain == NULL) {
722 		/*
723 		 * We found a hole, create a new chain entry.
724 		 *
725 		 * NOTE: DATA chains are created without device backing
726 		 *	 store (nor do we want any).
727 		 */
728 		dedup_off = hammer2_dedup_lookup((*parentp)->hmp, datap,
729 						 pblksize);
730 		*errorp |= hammer2_chain_create(parentp, &chain, NULL, ip->pmp,
731 				       HAMMER2_ENC_CHECK(ip->meta.check_algo) |
732 				       HAMMER2_ENC_COMP(HAMMER2_COMP_NONE),
733 					        lbase, HAMMER2_PBUFRADIX,
734 					        HAMMER2_BREF_TYPE_DATA,
735 					        pblksize, mtid,
736 					        dedup_off, 0);
737 		if (chain == NULL)
738 			goto failed;
739 		/*ip->delta_dcount += pblksize;*/
740 	} else if (chain->error == 0) {
741 		switch (chain->bref.type) {
742 		case HAMMER2_BREF_TYPE_INODE:
743 			/*
744 			 * The data is embedded in the inode, which requires
745 			 * a bit more finess.
746 			 */
747 			*errorp |= hammer2_chain_modify_ip(ip, chain, mtid, 0);
748 			break;
749 		case HAMMER2_BREF_TYPE_DATA:
750 			dedup_off = hammer2_dedup_lookup(chain->hmp, datap,
751 							 pblksize);
752 			if (chain->bytes != pblksize) {
753 				*errorp |= hammer2_chain_resize(chain,
754 						     mtid, dedup_off,
755 						     pradix,
756 						     HAMMER2_MODIFY_OPTDATA);
757 				if (*errorp)
758 					break;
759 			}
760 
761 			/*
762 			 * DATA buffers must be marked modified whether the
763 			 * data is in a logical buffer or not.  We also have
764 			 * to make this call to fixup the chain data pointers
765 			 * after resizing in case this is an encrypted or
766 			 * compressed buffer.
767 			 */
768 			*errorp |= hammer2_chain_modify(chain, mtid, dedup_off,
769 						        HAMMER2_MODIFY_OPTDATA);
770 			break;
771 		default:
772 			panic("hammer2_assign_physical: bad type");
773 			/* NOT REACHED */
774 			break;
775 		}
776 	} else {
777 		*errorp = chain->error;
778 	}
779 	atomic_set_int(&ip->flags, HAMMER2_INODE_DIRTYDATA);
780 failed:
781 	return (chain);
782 }
783 
784 /*
785  * hammer2_write_file_core()
786  *
787  * The core write function which determines which path to take
788  * depending on compression settings.  We also have to locate the
789  * related chains so we can calculate and set the check data for
790  * the blockref.
791  */
792 static
793 void
794 hammer2_write_file_core(char *data, hammer2_inode_t *ip,
795 			hammer2_chain_t **parentp,
796 			hammer2_key_t lbase, int ioflag, int pblksize,
797 			hammer2_tid_t mtid, int *errorp)
798 {
799 	hammer2_chain_t *chain;
800 	char *bdata;
801 
802 	*errorp = 0;
803 
804 	switch(HAMMER2_DEC_ALGO(ip->meta.comp_algo)) {
805 	case HAMMER2_COMP_NONE:
806 		/*
807 		 * We have to assign physical storage to the buffer
808 		 * we intend to dirty or write now to avoid deadlocks
809 		 * in the strategy code later.
810 		 *
811 		 * This can return NOOFFSET for inode-embedded data.
812 		 * The strategy code will take care of it in that case.
813 		 */
814 		bdata = data;
815 		chain = hammer2_assign_physical(ip, parentp, lbase, pblksize,
816 						mtid, &bdata, errorp);
817 		if (*errorp) {
818 			/* skip modifications */
819 		} else if (chain->bref.type == HAMMER2_BREF_TYPE_INODE) {
820 			hammer2_inode_data_t *wipdata;
821 
822 			wipdata = &chain->data->ipdata;
823 			KKASSERT(wipdata->meta.op_flags &
824 				 HAMMER2_OPFLAG_DIRECTDATA);
825 			bcopy(data, wipdata->u.data, HAMMER2_EMBEDDED_BYTES);
826 			++hammer2_iod_file_wembed;
827 		} else if (bdata == NULL) {
828 			/*
829 			 * Copy of data already present on-media.
830 			 */
831 			chain->bref.methods =
832 				HAMMER2_ENC_COMP(HAMMER2_COMP_NONE) +
833 				HAMMER2_ENC_CHECK(ip->meta.check_algo);
834 			hammer2_chain_setcheck(chain, data);
835 			atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
836 		} else {
837 			hammer2_write_bp(chain, data, ioflag, pblksize,
838 					 mtid, errorp, ip->meta.check_algo);
839 		}
840 		if (chain) {
841 			hammer2_chain_unlock(chain);
842 			hammer2_chain_drop(chain);
843 		}
844 		break;
845 	case HAMMER2_COMP_AUTOZERO:
846 		/*
847 		 * Check for zero-fill only
848 		 */
849 		hammer2_zero_check_and_write(data, ip, parentp,
850 					     lbase, ioflag, pblksize,
851 					     mtid, errorp,
852 					     ip->meta.check_algo);
853 		break;
854 	case HAMMER2_COMP_LZ4:
855 	case HAMMER2_COMP_ZLIB:
856 	default:
857 		/*
858 		 * Check for zero-fill and attempt compression.
859 		 */
860 		hammer2_compress_and_write(data, ip, parentp,
861 					   lbase, ioflag, pblksize,
862 					   mtid, errorp,
863 					   ip->meta.comp_algo,
864 					   ip->meta.check_algo);
865 		break;
866 	}
867 }
868 
869 /*
870  * Helper
871  *
872  * Generic function that will perform the compression in compression
873  * write path. The compression algorithm is determined by the settings
874  * obtained from inode.
875  */
876 static
877 void
878 hammer2_compress_and_write(char *data, hammer2_inode_t *ip,
879 	hammer2_chain_t **parentp,
880 	hammer2_key_t lbase, int ioflag, int pblksize,
881 	hammer2_tid_t mtid, int *errorp, int comp_algo, int check_algo)
882 {
883 	hammer2_chain_t *chain;
884 	int comp_size;
885 	int comp_block_size;
886 	char *comp_buffer;
887 	char *bdata;
888 
889 	/*
890 	 * An all-zeros write creates a hole unless the check code
891 	 * is disabled.  When the check code is disabled all writes
892 	 * are done in-place, including any all-zeros writes.
893 	 *
894 	 * NOTE: A snapshot will still force a copy-on-write
895 	 *	 (see the HAMMER2_CHECK_NONE in hammer2_chain.c).
896 	 */
897 	if (check_algo != HAMMER2_CHECK_NONE &&
898 	    test_block_zeros(data, pblksize)) {
899 		zero_write(data, ip, parentp, lbase, mtid, errorp);
900 		return;
901 	}
902 
903 	/*
904 	 * Compression requested.  Try to compress the block.  We store
905 	 * the data normally if we cannot sufficiently compress it.
906 	 *
907 	 * We have a heuristic to detect files which are mostly
908 	 * uncompressable and avoid the compression attempt in that
909 	 * case.  If the compression heuristic is turned off, we always
910 	 * try to compress.
911 	 */
912 	comp_size = 0;
913 	comp_buffer = NULL;
914 
915 	KKASSERT(pblksize / 2 <= 32768);
916 
917 	if (ip->comp_heuristic < 8 || (ip->comp_heuristic & 7) == 0 ||
918 	    hammer2_always_compress) {
919 		z_stream strm_compress;
920 		int comp_level;
921 		int ret;
922 
923 		switch(HAMMER2_DEC_ALGO(comp_algo)) {
924 		case HAMMER2_COMP_LZ4:
925 			/*
926 			 * We need to prefix with the size, LZ4
927 			 * doesn't do it for us.  Add the related
928 			 * overhead.
929 			 *
930 			 * NOTE: The LZ4 code seems to assume at least an
931 			 *	 8-byte buffer size granularity and may
932 			 *	 overrun the buffer if given a 4-byte
933 			 *	 granularity.
934 			 */
935 			comp_buffer = objcache_get(cache_buffer_write,
936 						   M_INTWAIT);
937 			comp_size = LZ4_compress_limitedOutput(
938 					data,
939 					&comp_buffer[sizeof(int)],
940 					pblksize,
941 					pblksize / 2 - sizeof(int64_t));
942 			*(int *)comp_buffer = comp_size;
943 			if (comp_size)
944 				comp_size += sizeof(int);
945 			break;
946 		case HAMMER2_COMP_ZLIB:
947 			comp_level = HAMMER2_DEC_LEVEL(comp_algo);
948 			if (comp_level == 0)
949 				comp_level = 6;	/* default zlib compression */
950 			else if (comp_level < 6)
951 				comp_level = 6;
952 			else if (comp_level > 9)
953 				comp_level = 9;
954 			ret = deflateInit(&strm_compress, comp_level);
955 			if (ret != Z_OK) {
956 				kprintf("HAMMER2 ZLIB: fatal error "
957 					"on deflateInit.\n");
958 			}
959 
960 			comp_buffer = objcache_get(cache_buffer_write,
961 						   M_INTWAIT);
962 			strm_compress.next_in = data;
963 			strm_compress.avail_in = pblksize;
964 			strm_compress.next_out = comp_buffer;
965 			strm_compress.avail_out = pblksize / 2;
966 			ret = deflate(&strm_compress, Z_FINISH);
967 			if (ret == Z_STREAM_END) {
968 				comp_size = pblksize / 2 -
969 					    strm_compress.avail_out;
970 			} else {
971 				comp_size = 0;
972 			}
973 			ret = deflateEnd(&strm_compress);
974 			break;
975 		default:
976 			kprintf("Error: Unknown compression method.\n");
977 			kprintf("Comp_method = %d.\n", comp_algo);
978 			break;
979 		}
980 	}
981 
982 	if (comp_size == 0) {
983 		/*
984 		 * compression failed or turned off
985 		 */
986 		comp_block_size = pblksize;	/* safety */
987 		if (++ip->comp_heuristic > 128)
988 			ip->comp_heuristic = 8;
989 	} else {
990 		/*
991 		 * compression succeeded
992 		 */
993 		ip->comp_heuristic = 0;
994 		if (comp_size <= 1024) {
995 			comp_block_size = 1024;
996 		} else if (comp_size <= 2048) {
997 			comp_block_size = 2048;
998 		} else if (comp_size <= 4096) {
999 			comp_block_size = 4096;
1000 		} else if (comp_size <= 8192) {
1001 			comp_block_size = 8192;
1002 		} else if (comp_size <= 16384) {
1003 			comp_block_size = 16384;
1004 		} else if (comp_size <= 32768) {
1005 			comp_block_size = 32768;
1006 		} else {
1007 			panic("hammer2: WRITE PATH: "
1008 			      "Weird comp_size value.");
1009 			/* NOT REACHED */
1010 			comp_block_size = pblksize;
1011 		}
1012 
1013 		/*
1014 		 * Must zero the remainder or dedup (which operates on a
1015 		 * physical block basis) will not find matches.
1016 		 */
1017 		if (comp_size < comp_block_size) {
1018 			bzero(comp_buffer + comp_size,
1019 			      comp_block_size - comp_size);
1020 		}
1021 	}
1022 
1023 	/*
1024 	 * Assign physical storage, bdata will be set to NULL if a live-dedup
1025 	 * was successful.
1026 	 */
1027 	bdata = comp_size ? comp_buffer : data;
1028 	chain = hammer2_assign_physical(ip, parentp, lbase, comp_block_size,
1029 					mtid, &bdata, errorp);
1030 
1031 	if (*errorp) {
1032 		goto done;
1033 	}
1034 
1035 	if (chain->bref.type == HAMMER2_BREF_TYPE_INODE) {
1036 		hammer2_inode_data_t *wipdata;
1037 
1038 		*errorp = hammer2_chain_modify_ip(ip, chain, mtid, 0);
1039 		if (*errorp == 0) {
1040 			wipdata = &chain->data->ipdata;
1041 			KKASSERT(wipdata->meta.op_flags &
1042 				 HAMMER2_OPFLAG_DIRECTDATA);
1043 			bcopy(data, wipdata->u.data, HAMMER2_EMBEDDED_BYTES);
1044 			++hammer2_iod_file_wembed;
1045 		}
1046 	} else if (bdata == NULL) {
1047 		/*
1048 		 * Live deduplication, a copy of the data is already present
1049 		 * on the media.
1050 		 */
1051 		if (comp_size) {
1052 			chain->bref.methods =
1053 				HAMMER2_ENC_COMP(comp_algo) +
1054 				HAMMER2_ENC_CHECK(check_algo);
1055 		} else {
1056 			chain->bref.methods =
1057 				HAMMER2_ENC_COMP(
1058 					HAMMER2_COMP_NONE) +
1059 				HAMMER2_ENC_CHECK(check_algo);
1060 		}
1061 		bdata = comp_size ? comp_buffer : data;
1062 		hammer2_chain_setcheck(chain, bdata);
1063 		atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
1064 	} else {
1065 		hammer2_io_t *dio;
1066 
1067 		KKASSERT(chain->flags & HAMMER2_CHAIN_MODIFIED);
1068 
1069 		switch(chain->bref.type) {
1070 		case HAMMER2_BREF_TYPE_INODE:
1071 			panic("hammer2_compress_and_write: unexpected inode\n");
1072 			break;
1073 		case HAMMER2_BREF_TYPE_DATA:
1074 			/*
1075 			 * Optimize out the read-before-write
1076 			 * if possible.
1077 			 */
1078 			*errorp = hammer2_io_newnz(chain->hmp,
1079 						   chain->bref.type,
1080 						   chain->bref.data_off,
1081 						   chain->bytes,
1082 						   &dio);
1083 			if (*errorp) {
1084 				hammer2_io_brelse(&dio);
1085 				kprintf("hammer2: WRITE PATH: "
1086 					"dbp bread error\n");
1087 				break;
1088 			}
1089 			bdata = hammer2_io_data(dio, chain->bref.data_off);
1090 
1091 			/*
1092 			 * When loading the block make sure we don't
1093 			 * leave garbage after the compressed data.
1094 			 */
1095 			if (comp_size) {
1096 				chain->bref.methods =
1097 					HAMMER2_ENC_COMP(comp_algo) +
1098 					HAMMER2_ENC_CHECK(check_algo);
1099 				bcopy(comp_buffer, bdata, comp_block_size);
1100 			} else {
1101 				chain->bref.methods =
1102 					HAMMER2_ENC_COMP(
1103 						HAMMER2_COMP_NONE) +
1104 					HAMMER2_ENC_CHECK(check_algo);
1105 				bcopy(data, bdata, pblksize);
1106 			}
1107 
1108 			/*
1109 			 * The flush code doesn't calculate check codes for
1110 			 * file data (doing so can result in excessive I/O),
1111 			 * so we do it here.
1112 			 */
1113 			hammer2_chain_setcheck(chain, bdata);
1114 
1115 			/*
1116 			 * Device buffer is now valid, chain is no longer in
1117 			 * the initial state.
1118 			 *
1119 			 * (No blockref table worries with file data)
1120 			 */
1121 			atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
1122 			hammer2_dedup_record(chain, dio, bdata);
1123 
1124 			/* Now write the related bdp. */
1125 			if (ioflag & IO_SYNC) {
1126 				/*
1127 				 * Synchronous I/O requested.
1128 				 */
1129 				hammer2_io_bwrite(&dio);
1130 			/*
1131 			} else if ((ioflag & IO_DIRECT) &&
1132 				   loff + n == pblksize) {
1133 				hammer2_io_bdwrite(&dio);
1134 			*/
1135 			} else if (ioflag & IO_ASYNC) {
1136 				hammer2_io_bawrite(&dio);
1137 			} else {
1138 				hammer2_io_bdwrite(&dio);
1139 			}
1140 			break;
1141 		default:
1142 			panic("hammer2_compress_and_write: bad chain type %d\n",
1143 				chain->bref.type);
1144 			/* NOT REACHED */
1145 			break;
1146 		}
1147 	}
1148 done:
1149 	if (chain) {
1150 		hammer2_chain_unlock(chain);
1151 		hammer2_chain_drop(chain);
1152 	}
1153 	if (comp_buffer)
1154 		objcache_put(cache_buffer_write, comp_buffer);
1155 }
1156 
1157 /*
1158  * Helper
1159  *
1160  * Function that performs zero-checking and writing without compression,
1161  * it corresponds to default zero-checking path.
1162  */
1163 static
1164 void
1165 hammer2_zero_check_and_write(char *data, hammer2_inode_t *ip,
1166 	hammer2_chain_t **parentp,
1167 	hammer2_key_t lbase, int ioflag, int pblksize,
1168 	hammer2_tid_t mtid, int *errorp,
1169 	int check_algo)
1170 {
1171 	hammer2_chain_t *chain;
1172 	char *bdata;
1173 
1174 	if (check_algo != HAMMER2_CHECK_NONE &&
1175 	    test_block_zeros(data, pblksize)) {
1176 		/*
1177 		 * An all-zeros write creates a hole unless the check code
1178 		 * is disabled.  When the check code is disabled all writes
1179 		 * are done in-place, including any all-zeros writes.
1180 		 *
1181 		 * NOTE: A snapshot will still force a copy-on-write
1182 		 *	 (see the HAMMER2_CHECK_NONE in hammer2_chain.c).
1183 		 */
1184 		zero_write(data, ip, parentp, lbase, mtid, errorp);
1185 	} else {
1186 		/*
1187 		 * Normal write (bdata set to NULL if de-duplicated)
1188 		 */
1189 		bdata = data;
1190 		chain = hammer2_assign_physical(ip, parentp, lbase, pblksize,
1191 						mtid, &bdata, errorp);
1192 		if (*errorp) {
1193 			/* do nothing */
1194 		} else if (bdata) {
1195 			hammer2_write_bp(chain, data, ioflag, pblksize,
1196 					 mtid, errorp, check_algo);
1197 		} else {
1198 			/* dedup occurred */
1199 			chain->bref.methods =
1200 				HAMMER2_ENC_COMP(HAMMER2_COMP_NONE) +
1201 				HAMMER2_ENC_CHECK(check_algo);
1202 			hammer2_chain_setcheck(chain, data);
1203 			atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
1204 		}
1205 		if (chain) {
1206 			hammer2_chain_unlock(chain);
1207 			hammer2_chain_drop(chain);
1208 		}
1209 	}
1210 }
1211 
1212 /*
1213  * Helper
1214  *
1215  * A function to test whether a block of data contains only zeros,
1216  * returns TRUE (non-zero) if the block is all zeros.
1217  */
1218 static
1219 int
1220 test_block_zeros(const char *buf, size_t bytes)
1221 {
1222 	size_t i;
1223 
1224 	for (i = 0; i < bytes; i += sizeof(long)) {
1225 		if (*(const long *)(buf + i) != 0)
1226 			return (0);
1227 	}
1228 	return (1);
1229 }
1230 
1231 /*
1232  * Helper
1233  *
1234  * Function to "write" a block that contains only zeros.
1235  */
1236 static
1237 void
1238 zero_write(char *data, hammer2_inode_t *ip,
1239 	   hammer2_chain_t **parentp,
1240 	   hammer2_key_t lbase, hammer2_tid_t mtid, int *errorp)
1241 {
1242 	hammer2_chain_t *chain;
1243 	hammer2_key_t key_dummy;
1244 
1245 	chain = hammer2_chain_lookup(parentp, &key_dummy,
1246 				     lbase, lbase,
1247 				     errorp,
1248 				     HAMMER2_LOOKUP_NODATA);
1249 	if (chain) {
1250 		if (chain->bref.type == HAMMER2_BREF_TYPE_INODE) {
1251 			hammer2_inode_data_t *wipdata;
1252 
1253 			if (*errorp == 0) {
1254 				*errorp = hammer2_chain_modify_ip(ip, chain,
1255 								  mtid, 0);
1256 			}
1257 			if (*errorp == 0) {
1258 				wipdata = &chain->data->ipdata;
1259 				KKASSERT(wipdata->meta.op_flags &
1260 					 HAMMER2_OPFLAG_DIRECTDATA);
1261 				bzero(wipdata->u.data, HAMMER2_EMBEDDED_BYTES);
1262 				++hammer2_iod_file_wembed;
1263 			}
1264 		} else {
1265 			/* chain->error ok for deletion */
1266 			hammer2_chain_delete(*parentp, chain,
1267 					     mtid, HAMMER2_DELETE_PERMANENT);
1268 			++hammer2_iod_file_wzero;
1269 		}
1270 		atomic_set_int(&ip->flags, HAMMER2_INODE_DIRTYDATA);
1271 		hammer2_chain_unlock(chain);
1272 		hammer2_chain_drop(chain);
1273 	} else {
1274 		++hammer2_iod_file_wzero;
1275 	}
1276 }
1277 
1278 /*
1279  * Helper
1280  *
1281  * Function to write the data as it is, without performing any sort of
1282  * compression. This function is used in path without compression and
1283  * default zero-checking path.
1284  */
1285 static
1286 void
1287 hammer2_write_bp(hammer2_chain_t *chain, char *data, int ioflag,
1288 		 int pblksize,
1289 		 hammer2_tid_t mtid, int *errorp, int check_algo)
1290 {
1291 	hammer2_inode_data_t *wipdata;
1292 	hammer2_io_t *dio;
1293 	char *bdata;
1294 	int error;
1295 
1296 	error = 0;	/* XXX TODO below */
1297 
1298 	KKASSERT(chain->flags & HAMMER2_CHAIN_MODIFIED);
1299 
1300 	switch(chain->bref.type) {
1301 	case HAMMER2_BREF_TYPE_INODE:
1302 		wipdata = &chain->data->ipdata;
1303 		KKASSERT(wipdata->meta.op_flags & HAMMER2_OPFLAG_DIRECTDATA);
1304 		bcopy(data, wipdata->u.data, HAMMER2_EMBEDDED_BYTES);
1305 		error = 0;
1306 		++hammer2_iod_file_wembed;
1307 		break;
1308 	case HAMMER2_BREF_TYPE_DATA:
1309 		error = hammer2_io_newnz(chain->hmp,
1310 					 chain->bref.type,
1311 					 chain->bref.data_off,
1312 					 chain->bytes, &dio);
1313 		if (error) {
1314 			hammer2_io_bqrelse(&dio);
1315 			kprintf("hammer2: WRITE PATH: "
1316 				"dbp bread error\n");
1317 			break;
1318 		}
1319 		bdata = hammer2_io_data(dio, chain->bref.data_off);
1320 
1321 		chain->bref.methods = HAMMER2_ENC_COMP(HAMMER2_COMP_NONE) +
1322 				      HAMMER2_ENC_CHECK(check_algo);
1323 		bcopy(data, bdata, chain->bytes);
1324 
1325 		/*
1326 		 * The flush code doesn't calculate check codes for
1327 		 * file data (doing so can result in excessive I/O),
1328 		 * so we do it here.
1329 		 */
1330 		hammer2_chain_setcheck(chain, bdata);
1331 
1332 		/*
1333 		 * Device buffer is now valid, chain is no longer in
1334 		 * the initial state.
1335 		 *
1336 		 * (No blockref table worries with file data)
1337 		 */
1338 		atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
1339 		hammer2_dedup_record(chain, dio, bdata);
1340 
1341 		if (ioflag & IO_SYNC) {
1342 			/*
1343 			 * Synchronous I/O requested.
1344 			 */
1345 			hammer2_io_bwrite(&dio);
1346 		/*
1347 		} else if ((ioflag & IO_DIRECT) &&
1348 			   loff + n == pblksize) {
1349 			hammer2_io_bdwrite(&dio);
1350 		*/
1351 		} else if (ioflag & IO_ASYNC) {
1352 			hammer2_io_bawrite(&dio);
1353 		} else {
1354 			hammer2_io_bdwrite(&dio);
1355 		}
1356 		break;
1357 	default:
1358 		panic("hammer2_write_bp: bad chain type %d\n",
1359 		      chain->bref.type);
1360 		/* NOT REACHED */
1361 		error = 0;
1362 		break;
1363 	}
1364 	*errorp = error;
1365 }
1366 
1367 /*
1368  * LIVE DEDUP HEURISTICS
1369  *
1370  * Record media and crc information for possible dedup operation.  Note
1371  * that the dedup mask bits must also be set in the related DIO for a dedup
1372  * to be fully validated (which is handled in the freemap allocation code).
1373  *
1374  * WARNING! This code is SMP safe but the heuristic allows SMP collisions.
1375  *	    All fields must be loaded into locals and validated.
1376  *
1377  * WARNING! Should only be used for file data and directory entries,
1378  *	    hammer2_chain_modify() only checks for the dedup case on data
1379  *	    chains.  Also, dedup data can only be recorded for committed
1380  *	    chains (so NOT strategy writes which can undergo further
1381  *	    modification after the fact!).
1382  */
1383 void
1384 hammer2_dedup_record(hammer2_chain_t *chain, hammer2_io_t *dio,
1385 		     const char *data)
1386 {
1387 	hammer2_dev_t *hmp;
1388 	hammer2_dedup_t *dedup;
1389 	uint64_t crc;
1390 	uint64_t mask;
1391 	int best = 0;
1392 	int i;
1393 	int dticks;
1394 
1395 	/*
1396 	 * We can only record a dedup if we have media data to test against.
1397 	 * If dedup is not enabled, return early, which allows a chain to
1398 	 * remain marked MODIFIED (which might have benefits in special
1399 	 * situations, though typically it does not).
1400 	 */
1401 	if (hammer2_dedup_enable == 0)
1402 		return;
1403 	if (dio == NULL) {
1404 		dio = chain->dio;
1405 		if (dio == NULL)
1406 			return;
1407 	}
1408 
1409 	hmp = chain->hmp;
1410 
1411 	switch(HAMMER2_DEC_CHECK(chain->bref.methods)) {
1412 	case HAMMER2_CHECK_ISCSI32:
1413 		/*
1414 		 * XXX use the built-in crc (the dedup lookup sequencing
1415 		 * needs to be fixed so the check code is already present
1416 		 * when dedup_lookup is called)
1417 		 */
1418 #if 0
1419 		crc = (uint64_t)(uint32_t)chain->bref.check.iscsi32.value;
1420 #endif
1421 		crc = XXH64(data, chain->bytes, XXH_HAMMER2_SEED);
1422 		break;
1423 	case HAMMER2_CHECK_XXHASH64:
1424 		crc = chain->bref.check.xxhash64.value;
1425 		break;
1426 	case HAMMER2_CHECK_SHA192:
1427 		/*
1428 		 * XXX use the built-in crc (the dedup lookup sequencing
1429 		 * needs to be fixed so the check code is already present
1430 		 * when dedup_lookup is called)
1431 		 */
1432 #if 0
1433 		crc = ((uint64_t *)chain->bref.check.sha192.data)[0] ^
1434 		      ((uint64_t *)chain->bref.check.sha192.data)[1] ^
1435 		      ((uint64_t *)chain->bref.check.sha192.data)[2];
1436 #endif
1437 		crc = XXH64(data, chain->bytes, XXH_HAMMER2_SEED);
1438 		break;
1439 	default:
1440 		/*
1441 		 * Cannot dedup without a check code
1442 		 *
1443 		 * NOTE: In particular, CHECK_NONE allows a sector to be
1444 		 *	 overwritten without copy-on-write, recording
1445 		 *	 a dedup block for a CHECK_NONE object would be
1446 		 *	 a disaster!
1447 		 */
1448 		return;
1449 	}
1450 
1451 	atomic_set_int(&chain->flags, HAMMER2_CHAIN_DEDUPABLE);
1452 
1453 	dedup = &hmp->heur_dedup[crc & (HAMMER2_DEDUP_HEUR_MASK & ~3)];
1454 	for (i = 0; i < 4; ++i) {
1455 		if (dedup[i].data_crc == crc) {
1456 			best = i;
1457 			break;
1458 		}
1459 		dticks = (int)(dedup[i].ticks - dedup[best].ticks);
1460 		if (dticks < 0 || dticks > hz * 60 * 30)
1461 			best = i;
1462 	}
1463 	dedup += best;
1464 	if (hammer2_debug & 0x40000) {
1465 		kprintf("REC %04x %016jx %016jx\n",
1466 			(int)(dedup - hmp->heur_dedup),
1467 			crc,
1468 			chain->bref.data_off);
1469 	}
1470 	dedup->ticks = ticks;
1471 	dedup->data_off = chain->bref.data_off;
1472 	dedup->data_crc = crc;
1473 
1474 	/*
1475 	 * Set the valid bits for the dedup only after we know the data
1476 	 * buffer has been updated.  The alloc bits were set (and the valid
1477 	 * bits cleared) when the media was allocated.
1478 	 *
1479 	 * This is done in two stages becuase the bulkfree code can race
1480 	 * the gap between allocation and data population.  Both masks must
1481 	 * be set before a bcmp/dedup operation is able to use the block.
1482 	 */
1483 	mask = hammer2_dedup_mask(dio, chain->bref.data_off, chain->bytes);
1484 	atomic_set_64(&dio->dedup_valid, mask);
1485 
1486 #if 0
1487 	/*
1488 	 * XXX removed. MODIFIED is an integral part of the flush code,
1489 	 * lets not just clear it
1490 	 */
1491 	/*
1492 	 * Once we record the dedup the chain must be marked clean to
1493 	 * prevent reuse of the underlying block.   Remember that this
1494 	 * write occurs when the buffer cache is flushed (i.e. on sync(),
1495 	 * fsync(), filesystem periodic sync, or when the kernel needs to
1496 	 * flush a buffer), and not whenever the user write()s.
1497 	 */
1498 	if (chain->flags & HAMMER2_CHAIN_MODIFIED) {
1499 		atomic_clear_int(&chain->flags, HAMMER2_CHAIN_MODIFIED);
1500 		atomic_add_long(&hammer2_count_modified_chains, -1);
1501 		if (chain->pmp)
1502 			hammer2_pfs_memory_wakeup(chain->pmp, -1);
1503 	}
1504 #endif
1505 }
1506 
1507 static
1508 hammer2_off_t
1509 hammer2_dedup_lookup(hammer2_dev_t *hmp, char **datap, int pblksize)
1510 {
1511 	hammer2_dedup_t *dedup;
1512 	hammer2_io_t *dio;
1513 	hammer2_off_t off;
1514 	uint64_t crc;
1515 	uint64_t mask;
1516 	char *data;
1517 	char *dtmp;
1518 	int i;
1519 
1520 	if (hammer2_dedup_enable == 0)
1521 		return 0;
1522 	data = *datap;
1523 	if (data == NULL)
1524 		return 0;
1525 
1526 	/*
1527 	 * XXX use the built-in crc (the dedup lookup sequencing
1528 	 * needs to be fixed so the check code is already present
1529 	 * when dedup_lookup is called)
1530 	 */
1531 	crc = XXH64(data, pblksize, XXH_HAMMER2_SEED);
1532 	dedup = &hmp->heur_dedup[crc & (HAMMER2_DEDUP_HEUR_MASK & ~3)];
1533 
1534 	if (hammer2_debug & 0x40000) {
1535 		kprintf("LOC %04x/4 %016jx\n",
1536 			(int)(dedup - hmp->heur_dedup),
1537 			crc);
1538 	}
1539 
1540 	for (i = 0; i < 4; ++i) {
1541 		off = dedup[i].data_off;
1542 		cpu_ccfence();
1543 		if (dedup[i].data_crc != crc)
1544 			continue;
1545 		if ((1 << (int)(off & HAMMER2_OFF_MASK_RADIX)) != pblksize)
1546 			continue;
1547 		dio = hammer2_io_getquick(hmp, off, pblksize);
1548 		if (dio) {
1549 			dtmp = hammer2_io_data(dio, off),
1550 			mask = hammer2_dedup_mask(dio, off, pblksize);
1551 			if ((dio->dedup_alloc & mask) == mask &&
1552 			    (dio->dedup_valid & mask) == mask &&
1553 			    bcmp(data, dtmp, pblksize) == 0) {
1554 				if (hammer2_debug & 0x40000) {
1555 					kprintf("DEDUP SUCCESS %016jx\n",
1556 						(intmax_t)off);
1557 				}
1558 				hammer2_io_putblk(&dio);
1559 				*datap = NULL;
1560 				dedup[i].ticks = ticks;   /* update use */
1561 				atomic_add_long(&hammer2_iod_file_wdedup,
1562 						pblksize);
1563 
1564 				return off;		/* RETURN */
1565 			}
1566 			hammer2_io_putblk(&dio);
1567 		}
1568 	}
1569 	return 0;
1570 }
1571 
1572 /*
1573  * Poof.  Races are ok, if someone gets in and reuses a dedup offset
1574  * before or while we are clearing it they will also recover the freemap
1575  * entry (set it to fully allocated), so a bulkfree race can only set it
1576  * to a possibly-free state.
1577  *
1578  * XXX ok, well, not really sure races are ok but going to run with it
1579  *     for the moment.
1580  */
1581 void
1582 hammer2_dedup_clear(hammer2_dev_t *hmp)
1583 {
1584 	int i;
1585 
1586 	for (i = 0; i < HAMMER2_DEDUP_HEUR_SIZE; ++i) {
1587 		hmp->heur_dedup[i].data_off = 0;
1588 		hmp->heur_dedup[i].ticks = ticks - 1;
1589 	}
1590 }
1591