hammer2 - performance, stabilization
[dragonfly.git] / sys / vfs / hammer2 / hammer2_vnops.c
1 /*
2  * Copyright (c) 2011-2013 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  * Kernel Filesystem interface
38  *
39  * NOTE! local ipdata pointers must be reloaded on any modifying operation
40  *       to the inode as its underlying chain may have changed.
41  */
42
43 #include <sys/param.h>
44 #include <sys/systm.h>
45 #include <sys/kernel.h>
46 #include <sys/fcntl.h>
47 #include <sys/buf.h>
48 #include <sys/proc.h>
49 #include <sys/namei.h>
50 #include <sys/mount.h>
51 #include <sys/vnode.h>
52 #include <sys/mountctl.h>
53 #include <sys/dirent.h>
54 #include <sys/uio.h>
55 #include <sys/objcache.h>
56 #include <sys/event.h>
57 #include <sys/file.h>
58 #include <vfs/fifofs/fifo.h>
59
60 #include "hammer2.h"
61 #include "hammer2_lz4.h"
62
63 #include "zlib/hammer2_zlib.h"
64
65 #define ZFOFFSET        (-2LL)
66
67 static int hammer2_read_file(hammer2_inode_t *ip, struct uio *uio,
68                                 int seqcount);
69 static int hammer2_write_file(hammer2_inode_t *ip, struct uio *uio,
70                                 int ioflag, int seqcount);
71 static void hammer2_extend_file(hammer2_inode_t *ip, hammer2_key_t nsize);
72 static void hammer2_truncate_file(hammer2_inode_t *ip, hammer2_key_t nsize);
73 static void hammer2_decompress_LZ4_callback(hammer2_io_t *dio,
74                                 hammer2_chain_t *arg_c,
75                                 void *arg_p, off_t arg_o);
76 static void hammer2_decompress_ZLIB_callback(hammer2_io_t *dio,
77                                 hammer2_chain_t *arg_c,
78                                 void *arg_p, off_t arg_o);
79
80 struct objcache *cache_buffer_read;
81 struct objcache *cache_buffer_write;
82
83 /* 
84  * Callback used in read path in case that a block is compressed with LZ4.
85  */
86 static
87 void
88 hammer2_decompress_LZ4_callback(hammer2_io_t *dio, hammer2_chain_t *arg_c,
89                                 void *arg_p, off_t arg_o)
90 {
91         struct buf *obp;
92         struct bio *obio = arg_p;
93         char *bdata;
94         int bytes = 1 << (int)(arg_o & HAMMER2_OFF_MASK_RADIX);
95
96         /*
97          * If BIO_DONE is already set the device buffer was already
98          * fully valid (B_CACHE).  If it is not set then I/O was issued
99          * and we have to run I/O completion as the last bio.
100          *
101          * Nobody is waiting for our device I/O to complete, we are
102          * responsible for bqrelse()ing it which means we also have to do
103          * the equivalent of biowait() and clear BIO_DONE (which breadcb()
104          * may have set).
105          *
106          * Any preexisting device buffer should match the requested size,
107          * but due to bigblock recycling and other factors there is some
108          * fragility there, so we assert that the device buffer covers
109          * the request.
110          */
111         obp = obio->bio_buf;
112
113         if (dio->bp->b_flags & B_ERROR) {
114                 obp->b_flags |= B_ERROR;
115                 obp->b_error = dio->bp->b_error;
116 #if 0
117         } else if (obio->bio_caller_info2.index &&
118                    obio->bio_caller_info1.uvalue32 !=
119                     crc32(bp->b_data, bp->b_bufsize)) {
120                 obp->b_flags |= B_ERROR;
121                 obp->b_error = EIO;
122 #endif
123         } else {
124                 char *compressed_buffer;
125                 int *compressed_size;
126                 int result;
127
128                 KKASSERT(obp->b_bufsize <= HAMMER2_PBUFSIZE);
129                 bdata = hammer2_io_data(dio, arg_o);
130                 compressed_size = (int *)bdata;
131                 compressed_buffer = objcache_get(cache_buffer_read, M_INTWAIT);
132                 KKASSERT((unsigned int)*compressed_size <= HAMMER2_PBUFSIZE);
133                 result = LZ4_decompress_safe(&bdata[sizeof(int)],
134                                              compressed_buffer,
135                                              *compressed_size,
136                                              obp->b_bufsize);
137                 if (result < 0) {
138                         kprintf("READ PATH: Error during decompression."
139                                 "bio %016jx/%d log %016jx/%d\n",
140                                 (intmax_t)dio->pbase, dio->psize,
141                                 (intmax_t)arg_o, bytes);
142                         /* make sure it isn't random garbage */
143                         bzero(compressed_buffer, obp->b_bufsize);
144                 }
145                 KKASSERT(result <= obp->b_bufsize);
146                 bcopy(compressed_buffer, obp->b_data, obp->b_bufsize);
147                 if (result < obp->b_bufsize)
148                         bzero(obp->b_data + result, obp->b_bufsize - result);
149                 objcache_put(cache_buffer_read, compressed_buffer);
150                 obp->b_resid = 0;
151                 obp->b_flags |= B_AGE;
152         }
153         biodone(obio);
154 }
155
156 /*
157  * Callback used in read path in case that a block is compressed with ZLIB.
158  * It is almost identical to LZ4 callback, so in theory they can be unified,
159  * but we didn't want to make changes in bio structure for that.
160  */
161 static
162 void
163 hammer2_decompress_ZLIB_callback(hammer2_io_t *dio, hammer2_chain_t *arg_c,
164                                  void *arg_p, off_t arg_o)
165 {
166         struct buf *obp;
167         struct bio *obio = arg_p;
168         char *bdata;
169         int bytes = 1 << (int)(arg_o & HAMMER2_OFF_MASK_RADIX);
170
171         /*
172          * If BIO_DONE is already set the device buffer was already
173          * fully valid (B_CACHE).  If it is not set then I/O was issued
174          * and we have to run I/O completion as the last bio.
175          *
176          * Nobody is waiting for our device I/O to complete, we are
177          * responsible for bqrelse()ing it which means we also have to do
178          * the equivalent of biowait() and clear BIO_DONE (which breadcb()
179          * may have set).
180          *
181          * Any preexisting device buffer should match the requested size,
182          * but due to bigblock recycling and other factors there is some
183          * fragility there, so we assert that the device buffer covers
184          * the request.
185          */
186         obp = obio->bio_buf;
187
188         if (dio->bp->b_flags & B_ERROR) {
189                 obp->b_flags |= B_ERROR;
190                 obp->b_error = dio->bp->b_error;
191 #if 0
192         } else if (obio->bio_caller_info2.index &&
193                    obio->bio_caller_info1.uvalue32 !=
194                     crc32(bp->b_data, bp->b_bufsize)) {
195                 obp->b_flags |= B_ERROR;
196                 obp->b_error = EIO;
197 #endif
198         } else {
199                 char *compressed_buffer;
200                 z_stream strm_decompress;
201                 int result;
202                 int ret;
203
204                 KKASSERT(obp->b_bufsize <= HAMMER2_PBUFSIZE);
205                 strm_decompress.avail_in = 0;
206                 strm_decompress.next_in = Z_NULL;
207                 
208                 ret = inflateInit(&strm_decompress);
209                 
210                 if (ret != Z_OK)
211                         kprintf("HAMMER2 ZLIB: Fatal error in inflateInit.\n");
212                 
213                 bdata = hammer2_io_data(dio, arg_o);
214                 compressed_buffer = objcache_get(cache_buffer_read, M_INTWAIT);
215                 strm_decompress.next_in = bdata;
216
217                 /* XXX supply proper size, subset of device bp */
218                 strm_decompress.avail_in = bytes;
219                 strm_decompress.next_out = compressed_buffer;
220                 strm_decompress.avail_out = obp->b_bufsize;
221                 
222                 ret = inflate(&strm_decompress, Z_FINISH);
223                 if (ret != Z_STREAM_END) {
224                         kprintf("HAMMER2 ZLIB: Fatar error during decompression.\n");
225                         bzero(compressed_buffer, obp->b_bufsize);
226                 }
227                 bcopy(compressed_buffer, obp->b_data, obp->b_bufsize);
228                 result = obp->b_bufsize - strm_decompress.avail_out;
229                 if (result < obp->b_bufsize)
230                         bzero(obp->b_data + result, strm_decompress.avail_out);
231                 objcache_put(cache_buffer_read, compressed_buffer);
232                 obp->b_resid = 0;
233                 obp->b_flags |= B_AGE;
234                 ret = inflateEnd(&strm_decompress);
235         }
236         biodone(obio);
237 }
238
239 static __inline
240 void
241 hammer2_knote(struct vnode *vp, int flags)
242 {
243         if (flags)
244                 KNOTE(&vp->v_pollinfo.vpi_kqinfo.ki_note, flags);
245 }
246
247 /*
248  * Last reference to a vnode is going away but it is still cached.
249  */
250 static
251 int
252 hammer2_vop_inactive(struct vop_inactive_args *ap)
253 {
254         hammer2_inode_t *ip;
255         hammer2_chain_t *parent;
256         struct vnode *vp;
257
258         vp = ap->a_vp;
259         ip = VTOI(vp);
260
261         /*
262          * Degenerate case
263          */
264         if (ip == NULL) {
265                 vrecycle(vp);
266                 return (0);
267         }
268
269         /*
270          * Detect updates to the embedded data which may be synchronized by
271          * the strategy code.  Simply mark the inode modified so it gets
272          * picked up by our normal flush.
273          */
274         parent = hammer2_inode_lock_ex(ip);
275         KKASSERT(parent);
276
277         /*
278          * Check for deleted inodes and recycle immediately.
279          */
280         if (parent->flags & HAMMER2_CHAIN_DELETED) {
281                 hammer2_inode_unlock_ex(ip, parent);
282                 vrecycle(vp);
283         } else {
284                 hammer2_inode_unlock_ex(ip, parent);
285         }
286         return (0);
287 }
288
289 /*
290  * Reclaim a vnode so that it can be reused; after the inode is
291  * disassociated, the filesystem must manage it alone.
292  */
293 static
294 int
295 hammer2_vop_reclaim(struct vop_reclaim_args *ap)
296 {
297         hammer2_chain_t *chain;
298         hammer2_inode_t *ip;
299         hammer2_trans_t trans;
300         struct vnode *vp;
301
302         vp = ap->a_vp;
303         ip = VTOI(vp);
304         if (ip == NULL)
305                 return(0);
306
307         /*
308          * Set update_hi so we can detect and propagate the DESTROYED
309          * bit in the flush code.
310          *
311          * ip->chain might be stale, correct it before checking as older
312          * versions of the chain are likely marked deleted even if the
313          * file hasn't been.  XXX ip->chain should never be stale on
314          * reclaim.
315          */
316         chain = hammer2_inode_lock_ex(ip);
317 #if 0
318         if (chain->next_parent)
319                 kprintf("RECLAIM DUPLINKED IP: %p ip->ch=%p ch=%p np=%p\n",
320                         ip, ip->chain, chain, chain->next_parent);
321 #endif
322
323         /*
324          * The final close of a deleted file or directory marks it for
325          * destruction.  The DESTROYED flag allows the flusher to shortcut
326          * any modified blocks still unflushed (that is, just ignore them).
327          *
328          * HAMMER2 usually does not try to optimize the freemap by returning
329          * deleted blocks to it as it does not usually know how many snapshots
330          * might be referencing portions of the file/dir.  XXX TODO.
331          *
332          * XXX TODO - However, any modified file as-of when a snapshot is made
333          *            cannot use this optimization as some of the modifications
334          *            may wind up being part of the snapshot.
335          */
336         vp->v_data = NULL;
337         ip->vp = NULL;
338         if (chain->flags & HAMMER2_CHAIN_DELETED) {
339                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DESTROYED);
340                 hammer2_trans_init(&trans, ip->pmp, HAMMER2_TRANS_BUFCACHE);
341                 hammer2_chain_setsubmod(&trans, chain);
342                 spin_lock(&chain->core->cst.spin);
343                 if (chain->core->update_hi < trans.sync_tid)
344                         chain->core->update_hi = trans.sync_tid; /* needed? */
345                 spin_unlock(&chain->core->cst.spin);
346                 hammer2_trans_done(&trans);
347         }
348
349         /*
350          * NOTE! We do not attempt to flush chains here, flushing is
351          *       really fragile and could also deadlock.
352          */
353         vclrisdirty(vp);
354         hammer2_inode_unlock_ex(ip, chain);             /* unlock */
355         hammer2_inode_drop(ip);                         /* vp ref */
356         /* chain no longer referenced */
357         /* chain = NULL; not needed */
358
359         /*
360          * XXX handle background sync when ip dirty, kernel will no longer
361          * notify us regarding this inode because there is no longer a
362          * vnode attached to it.
363          */
364
365         return (0);
366 }
367
368 static
369 int
370 hammer2_vop_fsync(struct vop_fsync_args *ap)
371 {
372         hammer2_inode_t *ip;
373         hammer2_trans_t trans;
374         hammer2_chain_t *chain;
375         struct vnode *vp;
376
377         vp = ap->a_vp;
378         ip = VTOI(vp);
379
380         /*
381          * WARNING: Cannot use TRANS_ISFLUSH for partial syncs.
382          */
383 #if 0
384         hammer2_trans_init(&trans, ip->pmp, HAMMER2_TRANS_ISFLUSH);
385         vfsync(vp, ap->a_waitfor, 1, NULL, NULL);
386         hammer2_trans_clear_invfsync(&trans);
387 #endif
388         hammer2_trans_init(&trans, ip->pmp, 0);
389         vfsync(vp, ap->a_waitfor, 1, NULL, NULL);
390
391         /*
392          * Calling chain_flush here creates a lot of duplicative
393          * COW operations due to non-optimal vnode ordering.
394          *
395          * Only do it for an actual fsync() syscall.  The other forms
396          * which call this function will eventually call chain_flush
397          * on the volume root as a catch-all, which is far more optimal.
398          */
399         chain = hammer2_inode_lock_ex(ip);
400         atomic_clear_int(&ip->flags, HAMMER2_INODE_MODIFIED);
401         vclrisdirty(vp);
402         if (ip->flags & (HAMMER2_INODE_RESIZED|HAMMER2_INODE_MTIME))
403                 hammer2_inode_fsync(&trans, ip, &chain);
404
405 #if 0
406         /*
407          * XXX creates discontinuity w/modify_tid
408          */
409         if (ap->a_flags & VOP_FSYNC_SYSCALL) {
410                 hammer2_chain_flush(&trans, &chain);
411         }
412 #endif
413         hammer2_inode_unlock_ex(ip, chain);
414         hammer2_trans_done(&trans);
415
416         return (0);
417 }
418
419 static
420 int
421 hammer2_vop_access(struct vop_access_args *ap)
422 {
423         hammer2_inode_t *ip = VTOI(ap->a_vp);
424         hammer2_inode_data_t *ipdata;
425         hammer2_chain_t *chain;
426         uid_t uid;
427         gid_t gid;
428         int error;
429
430         chain = hammer2_inode_lock_sh(ip);
431         ipdata = &chain->data->ipdata;
432         uid = hammer2_to_unix_xid(&ipdata->uid);
433         gid = hammer2_to_unix_xid(&ipdata->gid);
434         error = vop_helper_access(ap, uid, gid, ipdata->mode, ipdata->uflags);
435         hammer2_inode_unlock_sh(ip, chain);
436
437         return (error);
438 }
439
440 static
441 int
442 hammer2_vop_getattr(struct vop_getattr_args *ap)
443 {
444         hammer2_inode_data_t *ipdata;
445         hammer2_chain_t *chain;
446         hammer2_pfsmount_t *pmp;
447         hammer2_inode_t *ip;
448         struct vnode *vp;
449         struct vattr *vap;
450
451         vp = ap->a_vp;
452         vap = ap->a_vap;
453
454         ip = VTOI(vp);
455         pmp = ip->pmp;
456
457         chain = hammer2_inode_lock_sh(ip);
458         ipdata = &chain->data->ipdata;
459
460         vap->va_fsid = pmp->mp->mnt_stat.f_fsid.val[0];
461         vap->va_fileid = ipdata->inum;
462         vap->va_mode = ipdata->mode;
463         vap->va_nlink = ipdata->nlinks;
464         vap->va_uid = hammer2_to_unix_xid(&ipdata->uid);
465         vap->va_gid = hammer2_to_unix_xid(&ipdata->gid);
466         vap->va_rmajor = 0;
467         vap->va_rminor = 0;
468         vap->va_size = ip->size;        /* protected by shared lock */
469         vap->va_blocksize = HAMMER2_PBUFSIZE;
470         vap->va_flags = ipdata->uflags;
471         hammer2_time_to_timespec(ipdata->ctime, &vap->va_ctime);
472         hammer2_time_to_timespec(ipdata->mtime, &vap->va_mtime);
473         hammer2_time_to_timespec(ipdata->mtime, &vap->va_atime);
474         vap->va_gen = 1;
475         vap->va_bytes = vap->va_size;   /* XXX */
476         vap->va_type = hammer2_get_vtype(chain);
477         vap->va_filerev = 0;
478         vap->va_uid_uuid = ipdata->uid;
479         vap->va_gid_uuid = ipdata->gid;
480         vap->va_vaflags = VA_UID_UUID_VALID | VA_GID_UUID_VALID |
481                           VA_FSID_UUID_VALID;
482
483         hammer2_inode_unlock_sh(ip, chain);
484
485         return (0);
486 }
487
488 static
489 int
490 hammer2_vop_setattr(struct vop_setattr_args *ap)
491 {
492         hammer2_inode_data_t *ipdata;
493         hammer2_inode_t *ip;
494         hammer2_chain_t *chain;
495         hammer2_trans_t trans;
496         struct vnode *vp;
497         struct vattr *vap;
498         int error;
499         int kflags = 0;
500         int domtime = 0;
501         uint64_t ctime;
502
503         vp = ap->a_vp;
504         vap = ap->a_vap;
505         hammer2_update_time(&ctime);
506
507         ip = VTOI(vp);
508
509         if (ip->pmp->ronly)
510                 return(EROFS);
511
512         hammer2_chain_memory_wait(ip->pmp);
513         hammer2_trans_init(&trans, ip->pmp, 0);
514         chain = hammer2_inode_lock_ex(ip);
515         ipdata = &chain->data->ipdata;
516         error = 0;
517
518         if (vap->va_flags != VNOVAL) {
519                 u_int32_t flags;
520
521                 flags = ipdata->uflags;
522                 error = vop_helper_setattr_flags(&flags, vap->va_flags,
523                                          hammer2_to_unix_xid(&ipdata->uid),
524                                          ap->a_cred);
525                 if (error == 0) {
526                         if (ipdata->uflags != flags) {
527                                 ipdata = hammer2_chain_modify_ip(&trans, ip,
528                                                                  &chain, 0);
529                                 ipdata->uflags = flags;
530                                 ipdata->ctime = ctime;
531                                 kflags |= NOTE_ATTRIB;
532                         }
533                         if (ipdata->uflags & (IMMUTABLE | APPEND)) {
534                                 error = 0;
535                                 goto done;
536                         }
537                 }
538                 goto done;
539         }
540         if (ipdata->uflags & (IMMUTABLE | APPEND)) {
541                 error = EPERM;
542                 goto done;
543         }
544         if (vap->va_uid != (uid_t)VNOVAL || vap->va_gid != (gid_t)VNOVAL) {
545                 mode_t cur_mode = ipdata->mode;
546                 uid_t cur_uid = hammer2_to_unix_xid(&ipdata->uid);
547                 gid_t cur_gid = hammer2_to_unix_xid(&ipdata->gid);
548                 uuid_t uuid_uid;
549                 uuid_t uuid_gid;
550
551                 error = vop_helper_chown(ap->a_vp, vap->va_uid, vap->va_gid,
552                                          ap->a_cred,
553                                          &cur_uid, &cur_gid, &cur_mode);
554                 if (error == 0) {
555                         hammer2_guid_to_uuid(&uuid_uid, cur_uid);
556                         hammer2_guid_to_uuid(&uuid_gid, cur_gid);
557                         if (bcmp(&uuid_uid, &ipdata->uid, sizeof(uuid_uid)) ||
558                             bcmp(&uuid_gid, &ipdata->gid, sizeof(uuid_gid)) ||
559                             ipdata->mode != cur_mode
560                         ) {
561                                 ipdata = hammer2_chain_modify_ip(&trans, ip,
562                                                                  &chain, 0);
563                                 ipdata->uid = uuid_uid;
564                                 ipdata->gid = uuid_gid;
565                                 ipdata->mode = cur_mode;
566                                 ipdata->ctime = ctime;
567                         }
568                         kflags |= NOTE_ATTRIB;
569                 }
570         }
571
572         /*
573          * Resize the file
574          */
575         if (vap->va_size != VNOVAL && ip->size != vap->va_size) {
576                 switch(vp->v_type) {
577                 case VREG:
578                         if (vap->va_size == ip->size)
579                                 break;
580                         hammer2_inode_unlock_ex(ip, chain);
581                         if (vap->va_size < ip->size) {
582                                 hammer2_truncate_file(ip, vap->va_size);
583                         } else {
584                                 hammer2_extend_file(ip, vap->va_size);
585                         }
586                         chain = hammer2_inode_lock_ex(ip);
587                         ipdata = &chain->data->ipdata; /* RELOAD */
588                         domtime = 1;
589                         break;
590                 default:
591                         error = EINVAL;
592                         goto done;
593                 }
594         }
595 #if 0
596         /* atime not supported */
597         if (vap->va_atime.tv_sec != VNOVAL) {
598                 ipdata = hammer2_chain_modify_ip(&trans, ip, &chain, 0);
599                 ipdata->atime = hammer2_timespec_to_time(&vap->va_atime);
600                 kflags |= NOTE_ATTRIB;
601         }
602 #endif
603         if (vap->va_mtime.tv_sec != VNOVAL) {
604                 ipdata = hammer2_chain_modify_ip(&trans, ip, &chain, 0);
605                 ipdata->mtime = hammer2_timespec_to_time(&vap->va_mtime);
606                 kflags |= NOTE_ATTRIB;
607                 domtime = 0;
608         }
609         if (vap->va_mode != (mode_t)VNOVAL) {
610                 mode_t cur_mode = ipdata->mode;
611                 uid_t cur_uid = hammer2_to_unix_xid(&ipdata->uid);
612                 gid_t cur_gid = hammer2_to_unix_xid(&ipdata->gid);
613
614                 error = vop_helper_chmod(ap->a_vp, vap->va_mode, ap->a_cred,
615                                          cur_uid, cur_gid, &cur_mode);
616                 if (error == 0 && ipdata->mode != cur_mode) {
617                         ipdata = hammer2_chain_modify_ip(&trans, ip, &chain, 0);
618                         ipdata->mode = cur_mode;
619                         ipdata->ctime = ctime;
620                         kflags |= NOTE_ATTRIB;
621                 }
622         }
623
624         /*
625          * If a truncation occurred we must call inode_fsync() now in order
626          * to trim the related data chains, otherwise a later expansion can
627          * cause havoc.
628          */
629         hammer2_inode_fsync(&trans, ip, &chain);
630
631         /*
632          * Cleanup.  If domtime is set an additional inode modification
633          * must be flagged.  All other modifications will have already
634          * set INODE_MODIFIED and called vsetisdirty().
635          */
636 done:
637         if (domtime) {
638                 atomic_set_int(&ip->flags, HAMMER2_INODE_MODIFIED |
639                                            HAMMER2_INODE_MTIME);
640                 vsetisdirty(ip->vp);
641         }
642         hammer2_inode_unlock_ex(ip, chain);
643         hammer2_trans_done(&trans);
644         hammer2_knote(ip->vp, kflags);
645
646         return (error);
647 }
648
649 static
650 int
651 hammer2_vop_readdir(struct vop_readdir_args *ap)
652 {
653         hammer2_inode_data_t *ipdata;
654         hammer2_inode_t *ip;
655         hammer2_inode_t *xip;
656         hammer2_chain_t *parent;
657         hammer2_chain_t *chain;
658         hammer2_chain_t *xchain;
659         hammer2_tid_t inum;
660         hammer2_key_t key_next;
661         hammer2_key_t lkey;
662         struct uio *uio;
663         off_t *cookies;
664         off_t saveoff;
665         int cookie_index;
666         int cache_index = -1;
667         int ncookies;
668         int error;
669         int dtype;
670         int r;
671
672         ip = VTOI(ap->a_vp);
673         uio = ap->a_uio;
674         saveoff = uio->uio_offset;
675
676         /*
677          * Setup cookies directory entry cookies if requested
678          */
679         if (ap->a_ncookies) {
680                 ncookies = uio->uio_resid / 16 + 1;
681                 if (ncookies > 1024)
682                         ncookies = 1024;
683                 cookies = kmalloc(ncookies * sizeof(off_t), M_TEMP, M_WAITOK);
684         } else {
685                 ncookies = -1;
686                 cookies = NULL;
687         }
688         cookie_index = 0;
689
690         parent = hammer2_inode_lock_sh(ip);
691         ipdata = &parent->data->ipdata;
692
693         /*
694          * Handle artificial entries.  To ensure that only positive 64 bit
695          * quantities are returned to userland we always strip off bit 63.
696          * The hash code is designed such that codes 0x0000-0x7FFF are not
697          * used, allowing us to use these codes for articial entries.
698          *
699          * Entry 0 is used for '.' and entry 1 is used for '..'.  Do not
700          * allow '..' to cross the mount point into (e.g.) the super-root.
701          */
702         error = 0;
703         chain = (void *)(intptr_t)-1;   /* non-NULL for early goto done case */
704
705         if (saveoff == 0) {
706                 inum = ipdata->inum & HAMMER2_DIRHASH_USERMSK;
707                 r = vop_write_dirent(&error, uio, inum, DT_DIR, 1, ".");
708                 if (r)
709                         goto done;
710                 if (cookies)
711                         cookies[cookie_index] = saveoff;
712                 ++saveoff;
713                 ++cookie_index;
714                 if (cookie_index == ncookies)
715                         goto done;
716         }
717
718         if (saveoff == 1) {
719                 /*
720                  * Be careful with lockorder when accessing ".."
721                  *
722                  * (ip is the current dir. xip is the parent dir).
723                  */
724                 inum = ipdata->inum & HAMMER2_DIRHASH_USERMSK;
725                 while (ip->pip != NULL && ip != ip->pmp->iroot) {
726                         xip = ip->pip;
727                         hammer2_inode_ref(xip);
728                         hammer2_inode_unlock_sh(ip, parent);
729                         xchain = hammer2_inode_lock_sh(xip);
730                         parent = hammer2_inode_lock_sh(ip);
731                         hammer2_inode_drop(xip);
732                         if (xip == ip->pip) {
733                                 inum = xchain->data->ipdata.inum &
734                                        HAMMER2_DIRHASH_USERMSK;
735                                 hammer2_inode_unlock_sh(xip, xchain);
736                                 break;
737                         }
738                         hammer2_inode_unlock_sh(xip, xchain);
739                 }
740                 r = vop_write_dirent(&error, uio, inum, DT_DIR, 2, "..");
741                 if (r)
742                         goto done;
743                 if (cookies)
744                         cookies[cookie_index] = saveoff;
745                 ++saveoff;
746                 ++cookie_index;
747                 if (cookie_index == ncookies)
748                         goto done;
749         }
750
751         lkey = saveoff | HAMMER2_DIRHASH_VISIBLE;
752
753         /*
754          * parent is the inode chain, already locked for us.  Don't
755          * double lock shared locks as this will screw up upgrades.
756          */
757         if (error) {
758                 goto done;
759         }
760         chain = hammer2_chain_lookup(&parent, &key_next, lkey, lkey,
761                                      &cache_index, HAMMER2_LOOKUP_SHARED);
762         if (chain == NULL) {
763                 chain = hammer2_chain_lookup(&parent, &key_next,
764                                              lkey, (hammer2_key_t)-1,
765                                              &cache_index,
766                                              HAMMER2_LOOKUP_SHARED);
767         }
768         while (chain) {
769                 if (chain->bref.type == HAMMER2_BREF_TYPE_INODE) {
770                         dtype = hammer2_get_dtype(chain);
771                         saveoff = chain->bref.key & HAMMER2_DIRHASH_USERMSK;
772                         r = vop_write_dirent(&error, uio,
773                                              chain->data->ipdata.inum &
774                                               HAMMER2_DIRHASH_USERMSK,
775                                              dtype,
776                                              chain->data->ipdata.name_len,
777                                              chain->data->ipdata.filename);
778                         if (r)
779                                 break;
780                         if (cookies)
781                                 cookies[cookie_index] = saveoff;
782                         ++cookie_index;
783                 } else {
784                         /* XXX chain error */
785                         kprintf("bad chain type readdir %d\n",
786                                 chain->bref.type);
787                 }
788
789                 /*
790                  * Keys may not be returned in order so once we have a
791                  * placemarker (chain) the scan must allow the full range
792                  * or some entries will be missed.
793                  */
794                 chain = hammer2_chain_next(&parent, chain, &key_next,
795                                            key_next, (hammer2_key_t)-1,
796                                            &cache_index, HAMMER2_LOOKUP_SHARED);
797                 if (chain) {
798                         saveoff = (chain->bref.key &
799                                    HAMMER2_DIRHASH_USERMSK) + 1;
800                 } else {
801                         saveoff = (hammer2_key_t)-1;
802                 }
803                 if (cookie_index == ncookies)
804                         break;
805         }
806         if (chain)
807                 hammer2_chain_unlock(chain);
808 done:
809         hammer2_inode_unlock_sh(ip, parent);
810         if (ap->a_eofflag)
811                 *ap->a_eofflag = (chain == NULL);
812         uio->uio_offset = saveoff & ~HAMMER2_DIRHASH_VISIBLE;
813         if (error && cookie_index == 0) {
814                 if (cookies) {
815                         kfree(cookies, M_TEMP);
816                         *ap->a_ncookies = 0;
817                         *ap->a_cookies = NULL;
818                 }
819         } else {
820                 if (cookies) {
821                         *ap->a_ncookies = cookie_index;
822                         *ap->a_cookies = cookies;
823                 }
824         }
825         return (error);
826 }
827
828 /*
829  * hammer2_vop_readlink { vp, uio, cred }
830  */
831 static
832 int
833 hammer2_vop_readlink(struct vop_readlink_args *ap)
834 {
835         struct vnode *vp;
836         hammer2_inode_t *ip;
837         int error;
838
839         vp = ap->a_vp;
840         if (vp->v_type != VLNK)
841                 return (EINVAL);
842         ip = VTOI(vp);
843
844         error = hammer2_read_file(ip, ap->a_uio, 0);
845         return (error);
846 }
847
848 static
849 int
850 hammer2_vop_read(struct vop_read_args *ap)
851 {
852         struct vnode *vp;
853         hammer2_inode_t *ip;
854         struct uio *uio;
855         int error;
856         int seqcount;
857         int bigread;
858
859         /*
860          * Read operations supported on this vnode?
861          */
862         vp = ap->a_vp;
863         if (vp->v_type != VREG)
864                 return (EINVAL);
865
866         /*
867          * Misc
868          */
869         ip = VTOI(vp);
870         uio = ap->a_uio;
871         error = 0;
872
873         seqcount = ap->a_ioflag >> 16;
874         bigread = (uio->uio_resid > 100 * 1024 * 1024);
875
876         error = hammer2_read_file(ip, uio, seqcount);
877         return (error);
878 }
879
880 static
881 int
882 hammer2_vop_write(struct vop_write_args *ap)
883 {
884         hammer2_inode_t *ip;
885         hammer2_trans_t trans;
886         thread_t td;
887         struct vnode *vp;
888         struct uio *uio;
889         int error;
890         int seqcount;
891         int bigwrite;
892
893         /*
894          * Read operations supported on this vnode?
895          */
896         vp = ap->a_vp;
897         if (vp->v_type != VREG)
898                 return (EINVAL);
899
900         /*
901          * Misc
902          */
903         ip = VTOI(vp);
904         uio = ap->a_uio;
905         error = 0;
906         if (ip->pmp->ronly)
907                 return (EROFS);
908
909         seqcount = ap->a_ioflag >> 16;
910         bigwrite = (uio->uio_resid > 100 * 1024 * 1024);
911
912         /*
913          * Check resource limit
914          */
915         if (uio->uio_resid > 0 && (td = uio->uio_td) != NULL && td->td_proc &&
916             uio->uio_offset + uio->uio_resid >
917              td->td_proc->p_rlimit[RLIMIT_FSIZE].rlim_cur) {
918                 lwpsignal(td->td_proc, td->td_lwp, SIGXFSZ);
919                 return (EFBIG);
920         }
921
922         bigwrite = (uio->uio_resid > 100 * 1024 * 1024);
923
924         /*
925          * The transaction interlocks against flushes initiations
926          * (note: but will run concurrently with the actual flush).
927          */
928         hammer2_trans_init(&trans, ip->pmp, 0);
929         error = hammer2_write_file(ip, uio, ap->a_ioflag, seqcount);
930         hammer2_trans_done(&trans);
931
932         return (error);
933 }
934
935 /*
936  * Perform read operations on a file or symlink given an UNLOCKED
937  * inode and uio.
938  *
939  * The passed ip is not locked.
940  */
941 static
942 int
943 hammer2_read_file(hammer2_inode_t *ip, struct uio *uio, int seqcount)
944 {
945         hammer2_off_t size;
946         struct buf *bp;
947         int error;
948
949         error = 0;
950
951         /*
952          * UIO read loop.
953          */
954         ccms_thread_lock(&ip->topo_cst, CCMS_STATE_EXCLUSIVE);
955         size = ip->size;
956         ccms_thread_unlock(&ip->topo_cst);
957
958         while (uio->uio_resid > 0 && uio->uio_offset < size) {
959                 hammer2_key_t lbase;
960                 hammer2_key_t leof;
961                 int lblksize;
962                 int loff;
963                 int n;
964
965                 lblksize = hammer2_calc_logical(ip, uio->uio_offset,
966                                                 &lbase, &leof);
967
968                 error = cluster_read(ip->vp, leof, lbase, lblksize,
969                                      uio->uio_resid, seqcount * BKVASIZE,
970                                      &bp);
971
972                 if (error)
973                         break;
974                 loff = (int)(uio->uio_offset - lbase);
975                 n = lblksize - loff;
976                 if (n > uio->uio_resid)
977                         n = uio->uio_resid;
978                 if (n > size - uio->uio_offset)
979                         n = (int)(size - uio->uio_offset);
980                 bp->b_flags |= B_AGE;
981                 uiomove((char *)bp->b_data + loff, n, uio);
982                 bqrelse(bp);
983         }
984         return (error);
985 }
986
987 /*
988  * Write to the file represented by the inode via the logical buffer cache.
989  * The inode may represent a regular file or a symlink.
990  *
991  * The inode must not be locked.
992  */
993 static
994 int
995 hammer2_write_file(hammer2_inode_t *ip,
996                    struct uio *uio, int ioflag, int seqcount)
997 {
998         hammer2_key_t old_eof;
999         hammer2_key_t new_eof;
1000         struct buf *bp;
1001         int kflags;
1002         int error;
1003         int modified;
1004
1005         /*
1006          * Setup if append
1007          */
1008         ccms_thread_lock(&ip->topo_cst, CCMS_STATE_EXCLUSIVE);
1009         if (ioflag & IO_APPEND)
1010                 uio->uio_offset = ip->size;
1011         old_eof = ip->size;
1012         ccms_thread_unlock(&ip->topo_cst);
1013
1014         /*
1015          * Extend the file if necessary.  If the write fails at some point
1016          * we will truncate it back down to cover as much as we were able
1017          * to write.
1018          *
1019          * Doing this now makes it easier to calculate buffer sizes in
1020          * the loop.
1021          */
1022         kflags = 0;
1023         error = 0;
1024         modified = 0;
1025
1026         if (uio->uio_offset + uio->uio_resid > old_eof) {
1027                 new_eof = uio->uio_offset + uio->uio_resid;
1028                 modified = 1;
1029                 hammer2_extend_file(ip, new_eof);
1030                 kflags |= NOTE_EXTEND;
1031         } else {
1032                 new_eof = old_eof;
1033         }
1034         
1035         /*
1036          * UIO write loop
1037          */
1038         while (uio->uio_resid > 0) {
1039                 hammer2_key_t lbase;
1040                 int trivial;
1041                 int endofblk;
1042                 int lblksize;
1043                 int loff;
1044                 int n;
1045
1046                 /*
1047                  * Don't allow the buffer build to blow out the buffer
1048                  * cache.
1049                  */
1050                 if ((ioflag & IO_RECURSE) == 0)
1051                         bwillwrite(HAMMER2_PBUFSIZE);
1052
1053                 /*
1054                  * This nominally tells us how much we can cluster and
1055                  * what the logical buffer size needs to be.  Currently
1056                  * we don't try to cluster the write and just handle one
1057                  * block at a time.
1058                  */
1059                 lblksize = hammer2_calc_logical(ip, uio->uio_offset,
1060                                                 &lbase, NULL);
1061                 loff = (int)(uio->uio_offset - lbase);
1062                 
1063                 KKASSERT(lblksize <= 65536);
1064
1065                 /*
1066                  * Calculate bytes to copy this transfer and whether the
1067                  * copy completely covers the buffer or not.
1068                  */
1069                 trivial = 0;
1070                 n = lblksize - loff;
1071                 if (n > uio->uio_resid) {
1072                         n = uio->uio_resid;
1073                         if (loff == lbase && uio->uio_offset + n == new_eof)
1074                                 trivial = 1;
1075                         endofblk = 0;
1076                 } else {
1077                         if (loff == 0)
1078                                 trivial = 1;
1079                         endofblk = 1;
1080                 }
1081
1082                 /*
1083                  * Get the buffer
1084                  */
1085                 if (uio->uio_segflg == UIO_NOCOPY) {
1086                         /*
1087                          * Issuing a write with the same data backing the
1088                          * buffer.  Instantiate the buffer to collect the
1089                          * backing vm pages, then read-in any missing bits.
1090                          *
1091                          * This case is used by vop_stdputpages().
1092                          */
1093                         bp = getblk(ip->vp, lbase, lblksize, GETBLK_BHEAVY, 0);
1094                         if ((bp->b_flags & B_CACHE) == 0) {
1095                                 bqrelse(bp);
1096                                 error = bread(ip->vp, lbase, lblksize, &bp);
1097                         }
1098                 } else if (trivial) {
1099                         /*
1100                          * Even though we are entirely overwriting the buffer
1101                          * we may still have to zero it out to avoid a
1102                          * mmap/write visibility issue.
1103                          */
1104                         bp = getblk(ip->vp, lbase, lblksize, GETBLK_BHEAVY, 0);
1105                         if ((bp->b_flags & B_CACHE) == 0)
1106                                 vfs_bio_clrbuf(bp);
1107                 } else {
1108                         /*
1109                          * Partial overwrite, read in any missing bits then
1110                          * replace the portion being written.
1111                          *
1112                          * (The strategy code will detect zero-fill physical
1113                          * blocks for this case).
1114                          */
1115                         error = bread(ip->vp, lbase, lblksize, &bp);
1116                         if (error == 0)
1117                                 bheavy(bp);
1118                 }
1119
1120                 if (error) {
1121                         brelse(bp);
1122                         break;
1123                 }
1124
1125                 /*
1126                  * Ok, copy the data in
1127                  */
1128                 error = uiomove(bp->b_data + loff, n, uio);
1129                 kflags |= NOTE_WRITE;
1130                 modified = 1;
1131                 if (error) {
1132                         brelse(bp);
1133                         break;
1134                 }
1135
1136                 /*
1137                  * WARNING: Pageout daemon will issue UIO_NOCOPY writes
1138                  *          with IO_SYNC or IO_ASYNC set.  These writes
1139                  *          must be handled as the pageout daemon expects.
1140                  */
1141                 if (ioflag & IO_SYNC) {
1142                         bwrite(bp);
1143                 } else if ((ioflag & IO_DIRECT) && endofblk) {
1144                         bawrite(bp);
1145                 } else if (ioflag & IO_ASYNC) {
1146                         bawrite(bp);
1147                 } else {
1148                         bdwrite(bp);
1149                 }
1150         }
1151
1152         /*
1153          * Cleanup.  If we extended the file EOF but failed to write through
1154          * the entire write is a failure and we have to back-up.
1155          */
1156         if (error && new_eof != old_eof) {
1157                 hammer2_truncate_file(ip, old_eof);
1158         } else if (modified) {
1159                 ccms_thread_lock(&ip->topo_cst, CCMS_STATE_EXCLUSIVE);
1160                 hammer2_update_time(&ip->mtime);
1161                 atomic_set_int(&ip->flags, HAMMER2_INODE_MTIME);
1162                 ccms_thread_unlock(&ip->topo_cst);
1163         }
1164         atomic_set_int(&ip->flags, HAMMER2_INODE_MODIFIED);
1165         hammer2_knote(ip->vp, kflags);
1166         vsetisdirty(ip->vp);
1167
1168         return error;
1169 }
1170
1171 /*
1172  * Truncate the size of a file.  The inode must not be locked.
1173  *
1174  * NOTE: Caller handles setting HAMMER2_INODE_MODIFIED
1175  */
1176 static
1177 void
1178 hammer2_truncate_file(hammer2_inode_t *ip, hammer2_key_t nsize)
1179 {
1180         hammer2_key_t lbase;
1181         int nblksize;
1182
1183         if (ip->vp) {
1184                 nblksize = hammer2_calc_logical(ip, nsize, &lbase, NULL);
1185                 nvtruncbuf(ip->vp, nsize,
1186                            nblksize, (int)nsize & (nblksize - 1),
1187                            0);
1188         }
1189         ccms_thread_lock(&ip->topo_cst, CCMS_STATE_EXCLUSIVE);
1190         ip->size = nsize;
1191         atomic_set_int(&ip->flags, HAMMER2_INODE_RESIZED);
1192         ccms_thread_unlock(&ip->topo_cst);
1193 }
1194
1195 /*
1196  * Extend the size of a file.  The inode must not be locked.
1197  *
1198  * NOTE: Caller handles setting HAMMER2_INODE_MODIFIED
1199  */
1200 static
1201 void
1202 hammer2_extend_file(hammer2_inode_t *ip, hammer2_key_t nsize)
1203 {
1204         hammer2_key_t lbase;
1205         hammer2_key_t osize;
1206         int oblksize;
1207         int nblksize;
1208
1209         ccms_thread_lock(&ip->topo_cst, CCMS_STATE_EXCLUSIVE);
1210         osize = ip->size;
1211         ip->size = nsize;
1212         ccms_thread_unlock(&ip->topo_cst);
1213
1214         if (ip->vp) {
1215                 oblksize = hammer2_calc_logical(ip, osize, &lbase, NULL);
1216                 nblksize = hammer2_calc_logical(ip, nsize, &lbase, NULL);
1217                 nvextendbuf(ip->vp,
1218                             osize, nsize,
1219                             oblksize, nblksize,
1220                             -1, -1, 0);
1221         }
1222         atomic_set_int(&ip->flags, HAMMER2_INODE_RESIZED);
1223 }
1224
1225 static
1226 int
1227 hammer2_vop_nresolve(struct vop_nresolve_args *ap)
1228 {
1229         hammer2_inode_t *ip;
1230         hammer2_inode_t *dip;
1231         hammer2_chain_t *parent;
1232         hammer2_chain_t *chain;
1233         hammer2_chain_t *ochain;
1234         hammer2_trans_t trans;
1235         hammer2_key_t key_next;
1236         hammer2_key_t lhc;
1237         struct namecache *ncp;
1238         const uint8_t *name;
1239         size_t name_len;
1240         int error = 0;
1241         int cache_index = -1;
1242         struct vnode *vp;
1243
1244         dip = VTOI(ap->a_dvp);
1245         ncp = ap->a_nch->ncp;
1246         name = ncp->nc_name;
1247         name_len = ncp->nc_nlen;
1248         lhc = hammer2_dirhash(name, name_len);
1249
1250         /*
1251          * Note: In DragonFly the kernel handles '.' and '..'.
1252          */
1253         parent = hammer2_inode_lock_sh(dip);
1254         chain = hammer2_chain_lookup(&parent, &key_next,
1255                                      lhc, lhc + HAMMER2_DIRHASH_LOMASK,
1256                                      &cache_index, HAMMER2_LOOKUP_SHARED);
1257         while (chain) {
1258                 if (chain->bref.type == HAMMER2_BREF_TYPE_INODE &&
1259                     name_len == chain->data->ipdata.name_len &&
1260                     bcmp(name, chain->data->ipdata.filename, name_len) == 0) {
1261                         break;
1262                 }
1263                 chain = hammer2_chain_next(&parent, chain, &key_next,
1264                                            key_next,
1265                                            lhc + HAMMER2_DIRHASH_LOMASK,
1266                                            &cache_index, HAMMER2_LOOKUP_SHARED);
1267         }
1268         hammer2_inode_unlock_sh(dip, parent);
1269
1270         /*
1271          * If the inode represents a forwarding entry for a hardlink we have
1272          * to locate the actual inode.  The original ip is saved for possible
1273          * deconsolidation.  (ip) will only be set to non-NULL when we have
1274          * to locate the real file via a hardlink.  ip will be referenced but
1275          * not locked in that situation.  chain is passed in locked and
1276          * returned locked.
1277          *
1278          * XXX what kind of chain lock?
1279          */
1280         ochain = NULL;
1281         if (chain && chain->data->ipdata.type == HAMMER2_OBJTYPE_HARDLINK) {
1282                 error = hammer2_hardlink_find(dip, &chain, &ochain);
1283                 if (error) {
1284                         kprintf("hammer2: unable to find hardlink\n");
1285                         if (chain) {
1286                                 hammer2_chain_unlock(chain);
1287                                 chain = NULL;
1288                         }
1289                         goto failed;
1290                 }
1291         }
1292
1293         /*
1294          * Deconsolidate any hardlink whos nlinks == 1.  Ignore errors.
1295          * If an error occurs chain and ip are left alone.
1296          *
1297          * XXX upgrade shared lock?
1298          */
1299         if (ochain && chain &&
1300             chain->data->ipdata.nlinks == 1 && !dip->pmp->ronly) {
1301                 kprintf("hammer2: need to unconsolidate hardlink for %s\n",
1302                         chain->data->ipdata.filename);
1303                 /* XXX retain shared lock on dip? (currently not held) */
1304                 hammer2_trans_init(&trans, dip->pmp, 0);
1305                 hammer2_hardlink_deconsolidate(&trans, dip, &chain, &ochain);
1306                 hammer2_trans_done(&trans);
1307         }
1308
1309         /*
1310          * Acquire the related vnode
1311          *
1312          * NOTE: For error processing, only ENOENT resolves the namecache
1313          *       entry to NULL, otherwise we just return the error and
1314          *       leave the namecache unresolved.
1315          *
1316          * NOTE: multiple hammer2_inode structures can be aliased to the
1317          *       same chain element, for example for hardlinks.  This
1318          *       use case does not 'reattach' inode associations that
1319          *       might already exist, but always allocates a new one.
1320          *
1321          * WARNING: inode structure is locked exclusively via inode_get
1322          *          but chain was locked shared.  inode_unlock_ex()
1323          *          will handle it properly.
1324          */
1325         if (chain) {
1326                 ip = hammer2_inode_get(dip->pmp, dip, chain);
1327                 vp = hammer2_igetv(ip, &error);
1328                 if (error == 0) {
1329                         vn_unlock(vp);
1330                         cache_setvp(ap->a_nch, vp);
1331                 } else if (error == ENOENT) {
1332                         cache_setvp(ap->a_nch, NULL);
1333                 }
1334                 hammer2_inode_unlock_ex(ip, chain);
1335
1336                 /*
1337                  * The vp should not be released until after we've disposed
1338                  * of our locks, because it might cause vop_inactive() to
1339                  * be called.
1340                  */
1341                 if (vp)
1342                         vrele(vp);
1343         } else {
1344                 error = ENOENT;
1345                 cache_setvp(ap->a_nch, NULL);
1346         }
1347 failed:
1348         KASSERT(error || ap->a_nch->ncp->nc_vp != NULL,
1349                 ("resolve error %d/%p chain %p ap %p\n",
1350                  error, ap->a_nch->ncp->nc_vp, chain, ap));
1351         if (ochain)
1352                 hammer2_chain_drop(ochain);
1353         return error;
1354 }
1355
1356 static
1357 int
1358 hammer2_vop_nlookupdotdot(struct vop_nlookupdotdot_args *ap)
1359 {
1360         hammer2_inode_t *dip;
1361         hammer2_inode_t *ip;
1362         hammer2_chain_t *parent;
1363         int error;
1364
1365         dip = VTOI(ap->a_dvp);
1366
1367         if ((ip = dip->pip) == NULL) {
1368                 *ap->a_vpp = NULL;
1369                 return ENOENT;
1370         }
1371         parent = hammer2_inode_lock_ex(ip);
1372         *ap->a_vpp = hammer2_igetv(ip, &error);
1373         hammer2_inode_unlock_ex(ip, parent);
1374
1375         return error;
1376 }
1377
1378 static
1379 int
1380 hammer2_vop_nmkdir(struct vop_nmkdir_args *ap)
1381 {
1382         hammer2_inode_t *dip;
1383         hammer2_inode_t *nip;
1384         hammer2_trans_t trans;
1385         hammer2_chain_t *chain;
1386         struct namecache *ncp;
1387         const uint8_t *name;
1388         size_t name_len;
1389         int error;
1390
1391         dip = VTOI(ap->a_dvp);
1392         if (dip->pmp->ronly)
1393                 return (EROFS);
1394
1395         ncp = ap->a_nch->ncp;
1396         name = ncp->nc_name;
1397         name_len = ncp->nc_nlen;
1398
1399         hammer2_chain_memory_wait(dip->pmp);
1400         hammer2_trans_init(&trans, dip->pmp, HAMMER2_TRANS_NEWINODE);
1401         nip = hammer2_inode_create(&trans, dip, ap->a_vap, ap->a_cred,
1402                                    name, name_len, &chain, &error);
1403         if (error) {
1404                 KKASSERT(nip == NULL);
1405                 *ap->a_vpp = NULL;
1406         } else {
1407                 *ap->a_vpp = hammer2_igetv(nip, &error);
1408                 hammer2_inode_unlock_ex(nip, chain);
1409         }
1410         hammer2_trans_done(&trans);
1411
1412         if (error == 0) {
1413                 cache_setunresolved(ap->a_nch);
1414                 cache_setvp(ap->a_nch, *ap->a_vpp);
1415         }
1416         return error;
1417 }
1418
1419 /*
1420  * Return the largest contiguous physical disk range for the logical
1421  * request, in bytes.
1422  *
1423  * (struct vnode *vp, off_t loffset, off_t *doffsetp, int *runp, int *runb)
1424  *
1425  * Basically disabled, the logical buffer write thread has to deal with
1426  * buffers one-at-a-time.
1427  */
1428 static
1429 int
1430 hammer2_vop_bmap(struct vop_bmap_args *ap)
1431 {
1432         *ap->a_doffsetp = NOOFFSET;
1433         if (ap->a_runp)
1434                 *ap->a_runp = 0;
1435         if (ap->a_runb)
1436                 *ap->a_runb = 0;
1437         return (EOPNOTSUPP);
1438 }
1439
1440 static
1441 int
1442 hammer2_vop_open(struct vop_open_args *ap)
1443 {
1444         return vop_stdopen(ap);
1445 }
1446
1447 /*
1448  * hammer2_vop_advlock { vp, id, op, fl, flags }
1449  */
1450 static
1451 int
1452 hammer2_vop_advlock(struct vop_advlock_args *ap)
1453 {
1454         hammer2_inode_t *ip = VTOI(ap->a_vp);
1455         hammer2_chain_t *parent;
1456         hammer2_off_t size;
1457
1458         parent = hammer2_inode_lock_sh(ip);
1459         size = parent->data->ipdata.size;
1460         hammer2_inode_unlock_sh(ip, parent);
1461         return (lf_advlock(ap, &ip->advlock, size));
1462 }
1463
1464
1465 static
1466 int
1467 hammer2_vop_close(struct vop_close_args *ap)
1468 {
1469         return vop_stdclose(ap);
1470 }
1471
1472 /*
1473  * hammer2_vop_nlink { nch, dvp, vp, cred }
1474  *
1475  * Create a hardlink from (vp) to {dvp, nch}.
1476  */
1477 static
1478 int
1479 hammer2_vop_nlink(struct vop_nlink_args *ap)
1480 {
1481         hammer2_inode_t *dip;   /* target directory to create link in */
1482         hammer2_inode_t *ip;    /* inode we are hardlinking to */
1483         hammer2_chain_t *chain;
1484         hammer2_trans_t trans;
1485         struct namecache *ncp;
1486         const uint8_t *name;
1487         size_t name_len;
1488         int error;
1489
1490         dip = VTOI(ap->a_dvp);
1491         if (dip->pmp->ronly)
1492                 return (EROFS);
1493
1494         ncp = ap->a_nch->ncp;
1495         name = ncp->nc_name;
1496         name_len = ncp->nc_nlen;
1497
1498         /*
1499          * ip represents the file being hardlinked.  The file could be a
1500          * normal file or a hardlink target if it has already been hardlinked.
1501          * If ip is a hardlinked target then ip->pip represents the location
1502          * of the hardlinked target, NOT the location of the hardlink pointer.
1503          *
1504          * Bump nlinks and potentially also create or move the hardlink
1505          * target in the parent directory common to (ip) and (dip).  The
1506          * consolidation code can modify ip->chain and ip->pip.  The
1507          * returned chain is locked.
1508          */
1509         ip = VTOI(ap->a_vp);
1510         hammer2_chain_memory_wait(ip->pmp);
1511         hammer2_trans_init(&trans, ip->pmp, HAMMER2_TRANS_NEWINODE);
1512
1513         chain = hammer2_inode_lock_ex(ip);
1514         error = hammer2_hardlink_consolidate(&trans, ip, &chain, dip, 1);
1515         if (error)
1516                 goto done;
1517
1518         /*
1519          * Create a directory entry connected to the specified chain.
1520          * The hardlink consolidation code has already adjusted ip->pip
1521          * to the common parent directory containing the actual hardlink
1522          *
1523          * (which may be different from dip where we created our hardlink
1524          * entry. ip->chain always represents the actual hardlink and not
1525          * any of the pointers to the actual hardlink).
1526          */
1527         error = hammer2_inode_connect(&trans, 1,
1528                                       dip, &chain,
1529                                       name, name_len);
1530         if (error == 0) {
1531                 cache_setunresolved(ap->a_nch);
1532                 cache_setvp(ap->a_nch, ap->a_vp);
1533         }
1534 done:
1535         hammer2_inode_unlock_ex(ip, chain);
1536         hammer2_trans_done(&trans);
1537
1538         return error;
1539 }
1540
1541 /*
1542  * hammer2_vop_ncreate { nch, dvp, vpp, cred, vap }
1543  *
1544  * The operating system has already ensured that the directory entry
1545  * does not exist and done all appropriate namespace locking.
1546  */
1547 static
1548 int
1549 hammer2_vop_ncreate(struct vop_ncreate_args *ap)
1550 {
1551         hammer2_inode_t *dip;
1552         hammer2_inode_t *nip;
1553         hammer2_trans_t trans;
1554         hammer2_chain_t *nchain;
1555         struct namecache *ncp;
1556         const uint8_t *name;
1557         size_t name_len;
1558         int error;
1559
1560         dip = VTOI(ap->a_dvp);
1561         if (dip->pmp->ronly)
1562                 return (EROFS);
1563
1564         ncp = ap->a_nch->ncp;
1565         name = ncp->nc_name;
1566         name_len = ncp->nc_nlen;
1567         hammer2_chain_memory_wait(dip->pmp);
1568         hammer2_trans_init(&trans, dip->pmp, HAMMER2_TRANS_NEWINODE);
1569
1570         nip = hammer2_inode_create(&trans, dip, ap->a_vap, ap->a_cred,
1571                                    name, name_len, &nchain, &error);
1572         if (error) {
1573                 KKASSERT(nip == NULL);
1574                 *ap->a_vpp = NULL;
1575         } else {
1576                 *ap->a_vpp = hammer2_igetv(nip, &error);
1577                 hammer2_inode_unlock_ex(nip, nchain);
1578         }
1579         hammer2_trans_done(&trans);
1580
1581         if (error == 0) {
1582                 cache_setunresolved(ap->a_nch);
1583                 cache_setvp(ap->a_nch, *ap->a_vpp);
1584         }
1585         return error;
1586 }
1587
1588 /*
1589  *
1590  */
1591 static
1592 int
1593 hammer2_vop_nmknod(struct vop_nmknod_args *ap)
1594 {
1595         hammer2_inode_t *dip;
1596         hammer2_inode_t *nip;
1597         hammer2_trans_t trans;
1598         hammer2_chain_t *nchain;
1599         struct namecache *ncp;
1600         const uint8_t *name;
1601         size_t name_len;
1602         int error;
1603
1604         dip = VTOI(ap->a_dvp);
1605         if (dip->pmp->ronly)
1606                 return (EROFS);
1607
1608         ncp = ap->a_nch->ncp;
1609         name = ncp->nc_name;
1610         name_len = ncp->nc_nlen;
1611         hammer2_chain_memory_wait(dip->pmp);
1612         hammer2_trans_init(&trans, dip->pmp, HAMMER2_TRANS_NEWINODE);
1613
1614         nip = hammer2_inode_create(&trans, dip, ap->a_vap, ap->a_cred,
1615                                    name, name_len, &nchain, &error);
1616         if (error) {
1617                 KKASSERT(nip == NULL);
1618                 *ap->a_vpp = NULL;
1619         } else {
1620                 *ap->a_vpp = hammer2_igetv(nip, &error);
1621                 hammer2_inode_unlock_ex(nip, nchain);
1622         }
1623         hammer2_trans_done(&trans);
1624
1625         if (error == 0) {
1626                 cache_setunresolved(ap->a_nch);
1627                 cache_setvp(ap->a_nch, *ap->a_vpp);
1628         }
1629         return error;
1630 }
1631
1632 /*
1633  * hammer2_vop_nsymlink { nch, dvp, vpp, cred, vap, target }
1634  */
1635 static
1636 int
1637 hammer2_vop_nsymlink(struct vop_nsymlink_args *ap)
1638 {
1639         hammer2_inode_t *dip;
1640         hammer2_inode_t *nip;
1641         hammer2_chain_t *nparent;
1642         hammer2_trans_t trans;
1643         struct namecache *ncp;
1644         const uint8_t *name;
1645         size_t name_len;
1646         int error;
1647         
1648         dip = VTOI(ap->a_dvp);
1649         if (dip->pmp->ronly)
1650                 return (EROFS);
1651
1652         ncp = ap->a_nch->ncp;
1653         name = ncp->nc_name;
1654         name_len = ncp->nc_nlen;
1655         hammer2_chain_memory_wait(dip->pmp);
1656         hammer2_trans_init(&trans, dip->pmp, HAMMER2_TRANS_NEWINODE);
1657
1658         ap->a_vap->va_type = VLNK;      /* enforce type */
1659
1660         nip = hammer2_inode_create(&trans, dip, ap->a_vap, ap->a_cred,
1661                                    name, name_len, &nparent, &error);
1662         if (error) {
1663                 KKASSERT(nip == NULL);
1664                 *ap->a_vpp = NULL;
1665                 hammer2_trans_done(&trans);
1666                 return error;
1667         }
1668         *ap->a_vpp = hammer2_igetv(nip, &error);
1669
1670         /*
1671          * Build the softlink (~like file data) and finalize the namecache.
1672          */
1673         if (error == 0) {
1674                 size_t bytes;
1675                 struct uio auio;
1676                 struct iovec aiov;
1677                 hammer2_inode_data_t *nipdata;
1678
1679                 nipdata = &nip->chain->data->ipdata;
1680                 bytes = strlen(ap->a_target);
1681
1682                 if (bytes <= HAMMER2_EMBEDDED_BYTES) {
1683                         KKASSERT(nipdata->op_flags &
1684                                  HAMMER2_OPFLAG_DIRECTDATA);
1685                         bcopy(ap->a_target, nipdata->u.data, bytes);
1686                         nipdata->size = bytes;
1687                         nip->size = bytes;
1688                         hammer2_inode_unlock_ex(nip, nparent);
1689                 } else {
1690                         hammer2_inode_unlock_ex(nip, nparent);
1691                         bzero(&auio, sizeof(auio));
1692                         bzero(&aiov, sizeof(aiov));
1693                         auio.uio_iov = &aiov;
1694                         auio.uio_segflg = UIO_SYSSPACE;
1695                         auio.uio_rw = UIO_WRITE;
1696                         auio.uio_resid = bytes;
1697                         auio.uio_iovcnt = 1;
1698                         auio.uio_td = curthread;
1699                         aiov.iov_base = ap->a_target;
1700                         aiov.iov_len = bytes;
1701                         error = hammer2_write_file(nip, &auio, IO_APPEND, 0);
1702                         nipdata = &nip->chain->data->ipdata; /* RELOAD */
1703                         /* XXX handle error */
1704                         error = 0;
1705                 }
1706         } else {
1707                 hammer2_inode_unlock_ex(nip, nparent);
1708         }
1709         hammer2_trans_done(&trans);
1710
1711         /*
1712          * Finalize namecache
1713          */
1714         if (error == 0) {
1715                 cache_setunresolved(ap->a_nch);
1716                 cache_setvp(ap->a_nch, *ap->a_vpp);
1717                 /* hammer2_knote(ap->a_dvp, NOTE_WRITE); */
1718         }
1719         return error;
1720 }
1721
1722 /*
1723  * hammer2_vop_nremove { nch, dvp, cred }
1724  */
1725 static
1726 int
1727 hammer2_vop_nremove(struct vop_nremove_args *ap)
1728 {
1729         hammer2_inode_t *dip;
1730         hammer2_trans_t trans;
1731         struct namecache *ncp;
1732         const uint8_t *name;
1733         size_t name_len;
1734         int error;
1735
1736         dip = VTOI(ap->a_dvp);
1737         if (dip->pmp->ronly)
1738                 return(EROFS);
1739
1740         ncp = ap->a_nch->ncp;
1741         name = ncp->nc_name;
1742         name_len = ncp->nc_nlen;
1743         hammer2_chain_memory_wait(dip->pmp);
1744         hammer2_trans_init(&trans, dip->pmp, 0);
1745         error = hammer2_unlink_file(&trans, dip, name, name_len, 0, NULL);
1746         hammer2_trans_done(&trans);
1747         if (error == 0) {
1748                 cache_unlink(ap->a_nch);
1749         }
1750         return (error);
1751 }
1752
1753 /*
1754  * hammer2_vop_nrmdir { nch, dvp, cred }
1755  */
1756 static
1757 int
1758 hammer2_vop_nrmdir(struct vop_nrmdir_args *ap)
1759 {
1760         hammer2_inode_t *dip;
1761         hammer2_trans_t trans;
1762         struct namecache *ncp;
1763         const uint8_t *name;
1764         size_t name_len;
1765         int error;
1766
1767         dip = VTOI(ap->a_dvp);
1768         if (dip->pmp->ronly)
1769                 return(EROFS);
1770
1771         ncp = ap->a_nch->ncp;
1772         name = ncp->nc_name;
1773         name_len = ncp->nc_nlen;
1774
1775         hammer2_chain_memory_wait(dip->pmp);
1776         hammer2_trans_init(&trans, dip->pmp, 0);
1777         error = hammer2_unlink_file(&trans, dip, name, name_len, 1, NULL);
1778         hammer2_trans_done(&trans);
1779         if (error == 0) {
1780                 cache_unlink(ap->a_nch);
1781         }
1782         return (error);
1783 }
1784
1785 /*
1786  * hammer2_vop_nrename { fnch, tnch, fdvp, tdvp, cred }
1787  */
1788 static
1789 int
1790 hammer2_vop_nrename(struct vop_nrename_args *ap)
1791 {
1792         struct namecache *fncp;
1793         struct namecache *tncp;
1794         hammer2_inode_t *fdip;
1795         hammer2_inode_t *tdip;
1796         hammer2_inode_t *ip;
1797         hammer2_chain_t *chain;
1798         hammer2_trans_t trans;
1799         const uint8_t *fname;
1800         size_t fname_len;
1801         const uint8_t *tname;
1802         size_t tname_len;
1803         int error;
1804         int hlink;
1805
1806         if (ap->a_fdvp->v_mount != ap->a_tdvp->v_mount)
1807                 return(EXDEV);
1808         if (ap->a_fdvp->v_mount != ap->a_fnch->ncp->nc_vp->v_mount)
1809                 return(EXDEV);
1810
1811         fdip = VTOI(ap->a_fdvp);        /* source directory */
1812         tdip = VTOI(ap->a_tdvp);        /* target directory */
1813
1814         if (fdip->pmp->ronly)
1815                 return(EROFS);
1816
1817         fncp = ap->a_fnch->ncp;         /* entry name in source */
1818         fname = fncp->nc_name;
1819         fname_len = fncp->nc_nlen;
1820
1821         tncp = ap->a_tnch->ncp;         /* entry name in target */
1822         tname = tncp->nc_name;
1823         tname_len = tncp->nc_nlen;
1824
1825         hammer2_chain_memory_wait(tdip->pmp);
1826         hammer2_trans_init(&trans, tdip->pmp, 0);
1827
1828         /*
1829          * ip is the inode being renamed.  If this is a hardlink then
1830          * ip represents the actual file and not the hardlink marker.
1831          */
1832         ip = VTOI(fncp->nc_vp);
1833         chain = NULL;
1834
1835         /*
1836          * Keep a tight grip on the inode so the temporary unlinking from
1837          * the source location prior to linking to the target location
1838          * does not cause the chain to be destroyed.
1839          *
1840          * NOTE: To avoid deadlocks we cannot lock (ip) while we are
1841          *       unlinking elements from their directories.  Locking
1842          *       the nlinks field does not lock the whole inode.
1843          */
1844         hammer2_inode_ref(ip);
1845
1846         /*
1847          * Remove target if it exists
1848          */
1849         error = hammer2_unlink_file(&trans, tdip, tname, tname_len, -1, NULL);
1850         if (error && error != ENOENT)
1851                 goto done;
1852         cache_setunresolved(ap->a_tnch);
1853
1854         /*
1855          * When renaming a hardlinked file we may have to re-consolidate
1856          * the location of the hardlink target.  Since the element is simply
1857          * being moved, nlinks is not modified in this case.
1858          *
1859          * If ip represents a regular file the consolidation code essentially
1860          * does nothing other than return the same locked chain that was
1861          * passed in.
1862          *
1863          * The returned chain will be locked.
1864          *
1865          * WARNING!  We do not currently have a local copy of ipdata but
1866          *           we do use one later remember that it must be reloaded
1867          *           on any modification to the inode, including connects.
1868          */
1869         chain = hammer2_inode_lock_ex(ip);
1870         error = hammer2_hardlink_consolidate(&trans, ip, &chain, tdip, 0);
1871         if (error)
1872                 goto done;
1873
1874         /*
1875          * Disconnect (fdip, fname) from the source directory.  This will
1876          * disconnect (ip) if it represents a direct file.  If (ip) represents
1877          * a hardlink the HARDLINK pointer object will be removed but the
1878          * hardlink will stay intact.
1879          *
1880          * The target chain may be marked DELETED but will not be destroyed
1881          * since we retain our hold on ip and chain.
1882          */
1883         error = hammer2_unlink_file(&trans, fdip, fname, fname_len, -1, &hlink);
1884         KKASSERT(error != EAGAIN);
1885         if (error)
1886                 goto done;
1887
1888         /*
1889          * Reconnect ip to target directory using chain.  Chains cannot
1890          * actually be moved, so this will duplicate the chain in the new
1891          * spot and assign it to the ip, replacing the old chain.
1892          *
1893          * WARNING: Because recursive locks are allowed and we unlinked the
1894          *          file that we have a chain-in-hand for just above, the
1895          *          chain might have been delete-duplicated.  We must refactor
1896          *          the chain.
1897          *
1898          * WARNING: Chain locks can lock buffer cache buffers, to avoid
1899          *          deadlocks we want to unlock before issuing a cache_*()
1900          *          op (that might have to lock a vnode).
1901          */
1902         hammer2_chain_refactor(&chain);
1903         error = hammer2_inode_connect(&trans, hlink,
1904                                       tdip, &chain,
1905                                       tname, tname_len);
1906         if (error == 0) {
1907                 KKASSERT(chain != NULL);
1908                 hammer2_inode_repoint(ip, (hlink ? ip->pip : tdip), chain);
1909                 cache_rename(ap->a_fnch, ap->a_tnch);
1910         }
1911 done:
1912         hammer2_inode_unlock_ex(ip, chain);
1913         hammer2_inode_drop(ip);
1914         hammer2_trans_done(&trans);
1915
1916         return (error);
1917 }
1918
1919 /*
1920  * Strategy code
1921  *
1922  * WARNING: The strategy code cannot safely use hammer2 transactions
1923  *          as this can deadlock against vfs_sync's vfsync() call
1924  *          if multiple flushes are queued.
1925  */
1926 static int hammer2_strategy_read(struct vop_strategy_args *ap);
1927 static int hammer2_strategy_write(struct vop_strategy_args *ap);
1928 static void hammer2_strategy_read_callback(hammer2_io_t *dio,
1929                                 hammer2_chain_t *chain,
1930                                 void *arg_p, off_t arg_o);
1931
1932 static
1933 int
1934 hammer2_vop_strategy(struct vop_strategy_args *ap)
1935 {
1936         struct bio *biop;
1937         struct buf *bp;
1938         int error;
1939
1940         biop = ap->a_bio;
1941         bp = biop->bio_buf;
1942
1943         switch(bp->b_cmd) {
1944         case BUF_CMD_READ:
1945                 error = hammer2_strategy_read(ap);
1946                 ++hammer2_iod_file_read;
1947                 break;
1948         case BUF_CMD_WRITE:
1949                 error = hammer2_strategy_write(ap);
1950                 ++hammer2_iod_file_write;
1951                 break;
1952         default:
1953                 bp->b_error = error = EINVAL;
1954                 bp->b_flags |= B_ERROR;
1955                 biodone(biop);
1956                 break;
1957         }
1958
1959         return (error);
1960 }
1961
1962 static
1963 int
1964 hammer2_strategy_read(struct vop_strategy_args *ap)
1965 {
1966         struct buf *bp;
1967         struct bio *bio;
1968         struct bio *nbio;
1969         hammer2_inode_t *ip;
1970         hammer2_chain_t *parent;
1971         hammer2_chain_t *chain;
1972         hammer2_key_t key_dummy;
1973         hammer2_key_t lbase;
1974         int cache_index = -1;
1975
1976         bio = ap->a_bio;
1977         bp = bio->bio_buf;
1978         ip = VTOI(ap->a_vp);
1979         nbio = push_bio(bio);
1980
1981         lbase = bio->bio_offset;
1982         chain = NULL;
1983         KKASSERT(((int)lbase & HAMMER2_PBUFMASK) == 0);
1984
1985         parent = hammer2_inode_lock_sh(ip);
1986         chain = hammer2_chain_lookup(&parent, &key_dummy,
1987                                      lbase, lbase,
1988                                      &cache_index,
1989                                      HAMMER2_LOOKUP_NODATA |
1990                                      HAMMER2_LOOKUP_SHARED);
1991
1992         if (chain == NULL) {
1993                 /*
1994                  * Data is zero-fill
1995                  */
1996                 bp->b_resid = 0;
1997                 bp->b_error = 0;
1998                 bzero(bp->b_data, bp->b_bcount);
1999                 biodone(nbio);
2000         } else if (chain->bref.type == HAMMER2_BREF_TYPE_INODE) {
2001                 /*
2002                  * Data is embedded in the inode (copy from inode).
2003                  */
2004                 hammer2_chain_load_async(chain,
2005                                          hammer2_strategy_read_callback,
2006                                          nbio, 0);
2007         } else if (chain->bref.type == HAMMER2_BREF_TYPE_DATA) {
2008                 /*
2009                  * Data is on-media, issue device I/O and copy.
2010                  *
2011                  * XXX direct-IO shortcut could go here XXX.
2012                  */
2013                 if (HAMMER2_DEC_COMP(chain->bref.methods) == HAMMER2_COMP_LZ4) {
2014                         /*
2015                          * Block compression is determined by bref.methods
2016                          */
2017                         hammer2_blockref_t *bref;
2018                                 
2019                         bref = &chain->bref;
2020                         hammer2_io_breadcb(chain->hmp, bref->data_off,
2021                                            chain->bytes,
2022                                            hammer2_decompress_LZ4_callback,
2023                                            NULL, nbio, bref->data_off);
2024                         /* XXX async read dev blk not protected by chain lk */
2025                         hammer2_chain_unlock(chain);
2026                 } else if (HAMMER2_DEC_COMP(chain->bref.methods) ==
2027                            HAMMER2_COMP_ZLIB) {
2028                         hammer2_blockref_t *bref;
2029                                 
2030                         bref = &chain->bref;
2031                         hammer2_io_breadcb(chain->hmp, bref->data_off,
2032                                            chain->bytes,
2033                                            hammer2_decompress_ZLIB_callback,
2034                                            NULL, nbio, bref->data_off);
2035                         /* XXX async read dev blk not protected by chain lk */
2036                         hammer2_chain_unlock(chain);
2037                 } else {
2038                         hammer2_chain_load_async(chain,
2039                                                  hammer2_strategy_read_callback,
2040                                                  nbio, 0);
2041                 }
2042         } else {
2043                 panic("READ PATH: hammer2_strategy_read: unknown bref type");
2044                 chain = NULL;
2045         }
2046         hammer2_inode_unlock_sh(ip, parent);
2047         return (0);
2048 }
2049
2050 /*
2051  * Read callback for block that is not compressed.
2052  */
2053 static
2054 void
2055 hammer2_strategy_read_callback(hammer2_io_t *dio, hammer2_chain_t *chain,
2056                                void *arg_p, off_t arg_o __unused)
2057 {
2058         struct bio *nbio = arg_p;
2059         struct buf *bp = nbio->bio_buf;
2060         char *data;
2061
2062         if (dio)
2063                 data = hammer2_io_data(dio, chain->bref.data_off);
2064         else
2065                 data = (void *)chain->data;
2066
2067         if (chain->bref.type == HAMMER2_BREF_TYPE_INODE) {
2068                 /*
2069                  * Data is embedded in the inode (copy from inode).
2070                  */
2071                 bcopy(((hammer2_inode_data_t *)data)->u.data,
2072                       bp->b_data, HAMMER2_EMBEDDED_BYTES);
2073                 bzero(bp->b_data + HAMMER2_EMBEDDED_BYTES,
2074                       bp->b_bcount - HAMMER2_EMBEDDED_BYTES);
2075                 bp->b_resid = 0;
2076                 bp->b_error = 0;
2077                 hammer2_chain_unlock(chain);
2078                 biodone(nbio);
2079         } else if (chain->bref.type == HAMMER2_BREF_TYPE_DATA) {
2080                 /*
2081                  * Data is on-media, issue device I/O and copy.
2082                  *
2083                  * XXX direct-IO shortcut could go here XXX.
2084                  */
2085                 KKASSERT(chain->bytes <= bp->b_bcount);
2086                 bcopy(data, bp->b_data, chain->bytes);
2087                 if (chain->bytes < bp->b_bcount); {
2088                         bzero(bp->b_data + chain->bytes,
2089                               bp->b_bcount - chain->bytes);
2090                 }
2091                 bp->b_flags |= B_NOTMETA;
2092                 bp->b_resid = 0;
2093                 bp->b_error = 0;
2094                 hammer2_chain_unlock(chain);
2095                 biodone(nbio);
2096         } else {
2097                 /* bqrelse the dio to help stabilize the call to panic() */
2098                 if (dio)
2099                         hammer2_io_bqrelse(&dio);
2100                 panic("hammer2_strategy_read: unknown bref type");
2101                 /*hammer2_chain_unlock(chain);*/
2102                 /*chain = NULL;*/
2103         }
2104 }
2105
2106 static
2107 int
2108 hammer2_strategy_write(struct vop_strategy_args *ap)
2109 {       
2110         hammer2_pfsmount_t *pmp;
2111         struct bio *bio;
2112         struct buf *bp;
2113         hammer2_inode_t *ip;
2114         
2115         bio = ap->a_bio;
2116         bp = bio->bio_buf;
2117         ip = VTOI(ap->a_vp);
2118         pmp = ip->pmp;
2119         
2120         hammer2_lwinprog_ref(pmp);
2121         mtx_lock(&pmp->wthread_mtx);
2122         if (TAILQ_EMPTY(&pmp->wthread_bioq.queue)) {
2123                 bioq_insert_tail(&pmp->wthread_bioq, ap->a_bio);
2124                 mtx_unlock(&pmp->wthread_mtx);
2125                 wakeup(&pmp->wthread_bioq);
2126         } else {
2127                 bioq_insert_tail(&pmp->wthread_bioq, ap->a_bio);
2128                 mtx_unlock(&pmp->wthread_mtx);
2129         }
2130         hammer2_lwinprog_wait(pmp);
2131
2132         return(0);
2133 }
2134
2135 /*
2136  * hammer2_vop_ioctl { vp, command, data, fflag, cred }
2137  */
2138 static
2139 int
2140 hammer2_vop_ioctl(struct vop_ioctl_args *ap)
2141 {
2142         hammer2_inode_t *ip;
2143         int error;
2144
2145         ip = VTOI(ap->a_vp);
2146
2147         error = hammer2_ioctl(ip, ap->a_command, (void *)ap->a_data,
2148                               ap->a_fflag, ap->a_cred);
2149         return (error);
2150 }
2151
2152 static
2153 int 
2154 hammer2_vop_mountctl(struct vop_mountctl_args *ap)
2155 {
2156         struct mount *mp;
2157         hammer2_pfsmount_t *pmp;
2158         int rc;
2159
2160         switch (ap->a_op) {
2161         case (MOUNTCTL_SET_EXPORT):
2162                 mp = ap->a_head.a_ops->head.vv_mount;
2163                 pmp = MPTOPMP(mp);
2164
2165                 if (ap->a_ctllen != sizeof(struct export_args))
2166                         rc = (EINVAL);
2167                 else
2168                         rc = vfs_export(mp, &pmp->export,
2169                                         (const struct export_args *)ap->a_ctl);
2170                 break;
2171         default:
2172                 rc = vop_stdmountctl(ap);
2173                 break;
2174         }
2175         return (rc);
2176 }
2177
2178 /*
2179  * KQFILTER
2180  */
2181 static void filt_hammer2detach(struct knote *kn);
2182 static int filt_hammer2read(struct knote *kn, long hint);
2183 static int filt_hammer2write(struct knote *kn, long hint);
2184 static int filt_hammer2vnode(struct knote *kn, long hint);
2185
2186 static struct filterops hammer2read_filtops =
2187         { FILTEROP_ISFD | FILTEROP_MPSAFE,
2188           NULL, filt_hammer2detach, filt_hammer2read };
2189 static struct filterops hammer2write_filtops =
2190         { FILTEROP_ISFD | FILTEROP_MPSAFE,
2191           NULL, filt_hammer2detach, filt_hammer2write };
2192 static struct filterops hammer2vnode_filtops =
2193         { FILTEROP_ISFD | FILTEROP_MPSAFE,
2194           NULL, filt_hammer2detach, filt_hammer2vnode };
2195
2196 static
2197 int
2198 hammer2_vop_kqfilter(struct vop_kqfilter_args *ap)
2199 {
2200         struct vnode *vp = ap->a_vp;
2201         struct knote *kn = ap->a_kn;
2202
2203         switch (kn->kn_filter) {
2204         case EVFILT_READ:
2205                 kn->kn_fop = &hammer2read_filtops;
2206                 break;
2207         case EVFILT_WRITE:
2208                 kn->kn_fop = &hammer2write_filtops;
2209                 break;
2210         case EVFILT_VNODE:
2211                 kn->kn_fop = &hammer2vnode_filtops;
2212                 break;
2213         default:
2214                 return (EOPNOTSUPP);
2215         }
2216
2217         kn->kn_hook = (caddr_t)vp;
2218
2219         knote_insert(&vp->v_pollinfo.vpi_kqinfo.ki_note, kn);
2220
2221         return(0);
2222 }
2223
2224 static void
2225 filt_hammer2detach(struct knote *kn)
2226 {
2227         struct vnode *vp = (void *)kn->kn_hook;
2228
2229         knote_remove(&vp->v_pollinfo.vpi_kqinfo.ki_note, kn);
2230 }
2231
2232 static int
2233 filt_hammer2read(struct knote *kn, long hint)
2234 {
2235         struct vnode *vp = (void *)kn->kn_hook;
2236         hammer2_inode_t *ip = VTOI(vp);
2237         off_t off;
2238
2239         if (hint == NOTE_REVOKE) {
2240                 kn->kn_flags |= (EV_EOF | EV_NODATA | EV_ONESHOT);
2241                 return(1);
2242         }
2243         off = ip->size - kn->kn_fp->f_offset;
2244         kn->kn_data = (off < INTPTR_MAX) ? off : INTPTR_MAX;
2245         if (kn->kn_sfflags & NOTE_OLDAPI)
2246                 return(1);
2247         return (kn->kn_data != 0);
2248 }
2249
2250
2251 static int
2252 filt_hammer2write(struct knote *kn, long hint)
2253 {
2254         if (hint == NOTE_REVOKE)
2255                 kn->kn_flags |= (EV_EOF | EV_NODATA | EV_ONESHOT);
2256         kn->kn_data = 0;
2257         return (1);
2258 }
2259
2260 static int
2261 filt_hammer2vnode(struct knote *kn, long hint)
2262 {
2263         if (kn->kn_sfflags & hint)
2264                 kn->kn_fflags |= hint;
2265         if (hint == NOTE_REVOKE) {
2266                 kn->kn_flags |= (EV_EOF | EV_NODATA);
2267                 return (1);
2268         }
2269         return (kn->kn_fflags != 0);
2270 }
2271
2272 /*
2273  * FIFO VOPS
2274  */
2275 static
2276 int
2277 hammer2_vop_markatime(struct vop_markatime_args *ap)
2278 {
2279         hammer2_inode_t *ip;
2280         struct vnode *vp;
2281
2282         vp = ap->a_vp;
2283         ip = VTOI(vp);
2284
2285         if (ip->pmp->ronly)
2286                 return(EROFS);
2287         return(0);
2288 }
2289
2290 static
2291 int
2292 hammer2_vop_fifokqfilter(struct vop_kqfilter_args *ap)
2293 {
2294         int error;
2295
2296         error = VOCALL(&fifo_vnode_vops, &ap->a_head);
2297         if (error)
2298                 error = hammer2_vop_kqfilter(ap);
2299         return(error);
2300 }
2301
2302 /*
2303  * VOPS vector
2304  */
2305 struct vop_ops hammer2_vnode_vops = {
2306         .vop_default    = vop_defaultop,
2307         .vop_fsync      = hammer2_vop_fsync,
2308         .vop_getpages   = vop_stdgetpages,
2309         .vop_putpages   = vop_stdputpages,
2310         .vop_access     = hammer2_vop_access,
2311         .vop_advlock    = hammer2_vop_advlock,
2312         .vop_close      = hammer2_vop_close,
2313         .vop_nlink      = hammer2_vop_nlink,
2314         .vop_ncreate    = hammer2_vop_ncreate,
2315         .vop_nsymlink   = hammer2_vop_nsymlink,
2316         .vop_nremove    = hammer2_vop_nremove,
2317         .vop_nrmdir     = hammer2_vop_nrmdir,
2318         .vop_nrename    = hammer2_vop_nrename,
2319         .vop_getattr    = hammer2_vop_getattr,
2320         .vop_setattr    = hammer2_vop_setattr,
2321         .vop_readdir    = hammer2_vop_readdir,
2322         .vop_readlink   = hammer2_vop_readlink,
2323         .vop_getpages   = vop_stdgetpages,
2324         .vop_putpages   = vop_stdputpages,
2325         .vop_read       = hammer2_vop_read,
2326         .vop_write      = hammer2_vop_write,
2327         .vop_open       = hammer2_vop_open,
2328         .vop_inactive   = hammer2_vop_inactive,
2329         .vop_reclaim    = hammer2_vop_reclaim,
2330         .vop_nresolve   = hammer2_vop_nresolve,
2331         .vop_nlookupdotdot = hammer2_vop_nlookupdotdot,
2332         .vop_nmkdir     = hammer2_vop_nmkdir,
2333         .vop_nmknod     = hammer2_vop_nmknod,
2334         .vop_ioctl      = hammer2_vop_ioctl,
2335         .vop_mountctl   = hammer2_vop_mountctl,
2336         .vop_bmap       = hammer2_vop_bmap,
2337         .vop_strategy   = hammer2_vop_strategy,
2338         .vop_kqfilter   = hammer2_vop_kqfilter
2339 };
2340
2341 struct vop_ops hammer2_spec_vops = {
2342         .vop_default =          vop_defaultop,
2343         .vop_fsync =            hammer2_vop_fsync,
2344         .vop_read =             vop_stdnoread,
2345         .vop_write =            vop_stdnowrite,
2346         .vop_access =           hammer2_vop_access,
2347         .vop_close =            hammer2_vop_close,
2348         .vop_markatime =        hammer2_vop_markatime,
2349         .vop_getattr =          hammer2_vop_getattr,
2350         .vop_inactive =         hammer2_vop_inactive,
2351         .vop_reclaim =          hammer2_vop_reclaim,
2352         .vop_setattr =          hammer2_vop_setattr
2353 };
2354
2355 struct vop_ops hammer2_fifo_vops = {
2356         .vop_default =          fifo_vnoperate,
2357         .vop_fsync =            hammer2_vop_fsync,
2358 #if 0
2359         .vop_read =             hammer2_vop_fiforead,
2360         .vop_write =            hammer2_vop_fifowrite,
2361 #endif
2362         .vop_access =           hammer2_vop_access,
2363 #if 0
2364         .vop_close =            hammer2_vop_fifoclose,
2365 #endif
2366         .vop_markatime =        hammer2_vop_markatime,
2367         .vop_getattr =          hammer2_vop_getattr,
2368         .vop_inactive =         hammer2_vop_inactive,
2369         .vop_reclaim =          hammer2_vop_reclaim,
2370         .vop_setattr =          hammer2_vop_setattr,
2371         .vop_kqfilter =         hammer2_vop_fifokqfilter
2372 };
2373