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