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