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