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