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