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