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