sys/vfs/hammer: Remove obsolete code and comments
[dragonfly.git] / sys / vfs / hammer / hammer_vnops.c
1 /*
2  * Copyright (c) 2007-2008 The DragonFly Project.  All rights reserved.
3  *
4  * This code is derived from software contributed to The DragonFly Project
5  * by Matthew Dillon <dillon@backplane.com>
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in
15  *    the documentation and/or other materials provided with the
16  *    distribution.
17  * 3. Neither the name of The DragonFly Project nor the names of its
18  *    contributors may be used to endorse or promote products derived
19  *    from this software without specific, prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
24  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
25  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
26  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
27  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
28  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
29  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
30  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
31  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34
35 #include <sys/fcntl.h>
36 #include <sys/namecache.h>
37 #include <sys/event.h>
38 #include <sys/dirent.h>
39 #include <sys/file.h>
40 #include <vm/swap_pager.h>
41 #include <vfs/fifofs/fifo.h>
42
43 #include "hammer.h"
44
45 /*
46  * USERFS VNOPS
47  */
48 static int hammer_vop_fsync(struct vop_fsync_args *);
49 static int hammer_vop_read(struct vop_read_args *);
50 static int hammer_vop_write(struct vop_write_args *);
51 static int hammer_vop_access(struct vop_access_args *);
52 static int hammer_vop_advlock(struct vop_advlock_args *);
53 static int hammer_vop_close(struct vop_close_args *);
54 static int hammer_vop_ncreate(struct vop_ncreate_args *);
55 static int hammer_vop_getattr(struct vop_getattr_args *);
56 static int hammer_vop_nresolve(struct vop_nresolve_args *);
57 static int hammer_vop_nlookupdotdot(struct vop_nlookupdotdot_args *);
58 static int hammer_vop_nlink(struct vop_nlink_args *);
59 static int hammer_vop_nmkdir(struct vop_nmkdir_args *);
60 static int hammer_vop_nmknod(struct vop_nmknod_args *);
61 static int hammer_vop_open(struct vop_open_args *);
62 static int hammer_vop_print(struct vop_print_args *);
63 static int hammer_vop_readdir(struct vop_readdir_args *);
64 static int hammer_vop_readlink(struct vop_readlink_args *);
65 static int hammer_vop_nremove(struct vop_nremove_args *);
66 static int hammer_vop_nrename(struct vop_nrename_args *);
67 static int hammer_vop_nrmdir(struct vop_nrmdir_args *);
68 static int hammer_vop_markatime(struct vop_markatime_args *);
69 static int hammer_vop_setattr(struct vop_setattr_args *);
70 static int hammer_vop_strategy(struct vop_strategy_args *);
71 static int hammer_vop_bmap(struct vop_bmap_args *ap);
72 static int hammer_vop_nsymlink(struct vop_nsymlink_args *);
73 static int hammer_vop_nwhiteout(struct vop_nwhiteout_args *);
74 static int hammer_vop_ioctl(struct vop_ioctl_args *);
75 static int hammer_vop_mountctl(struct vop_mountctl_args *);
76 static int hammer_vop_kqfilter (struct vop_kqfilter_args *);
77
78 static int hammer_vop_fifoclose (struct vop_close_args *);
79 static int hammer_vop_fiforead (struct vop_read_args *);
80 static int hammer_vop_fifowrite (struct vop_write_args *);
81 static int hammer_vop_fifokqfilter (struct vop_kqfilter_args *);
82
83 struct vop_ops hammer_vnode_vops = {
84         .vop_default =          vop_defaultop,
85         .vop_fsync =            hammer_vop_fsync,
86         .vop_getpages =         vop_stdgetpages,
87         .vop_putpages =         vop_stdputpages,
88         .vop_read =             hammer_vop_read,
89         .vop_write =            hammer_vop_write,
90         .vop_access =           hammer_vop_access,
91         .vop_advlock =          hammer_vop_advlock,
92         .vop_close =            hammer_vop_close,
93         .vop_ncreate =          hammer_vop_ncreate,
94         .vop_getattr =          hammer_vop_getattr,
95         .vop_inactive =         hammer_vop_inactive,
96         .vop_reclaim =          hammer_vop_reclaim,
97         .vop_nresolve =         hammer_vop_nresolve,
98         .vop_nlookupdotdot =    hammer_vop_nlookupdotdot,
99         .vop_nlink =            hammer_vop_nlink,
100         .vop_nmkdir =           hammer_vop_nmkdir,
101         .vop_nmknod =           hammer_vop_nmknod,
102         .vop_open =             hammer_vop_open,
103         .vop_pathconf =         vop_stdpathconf,
104         .vop_print =            hammer_vop_print,
105         .vop_readdir =          hammer_vop_readdir,
106         .vop_readlink =         hammer_vop_readlink,
107         .vop_nremove =          hammer_vop_nremove,
108         .vop_nrename =          hammer_vop_nrename,
109         .vop_nrmdir =           hammer_vop_nrmdir,
110         .vop_markatime =        hammer_vop_markatime,
111         .vop_setattr =          hammer_vop_setattr,
112         .vop_bmap =             hammer_vop_bmap,
113         .vop_strategy =         hammer_vop_strategy,
114         .vop_nsymlink =         hammer_vop_nsymlink,
115         .vop_nwhiteout =        hammer_vop_nwhiteout,
116         .vop_ioctl =            hammer_vop_ioctl,
117         .vop_mountctl =         hammer_vop_mountctl,
118         .vop_kqfilter =         hammer_vop_kqfilter
119 };
120
121 struct vop_ops hammer_spec_vops = {
122         .vop_default =          vop_defaultop,
123         .vop_fsync =            hammer_vop_fsync,
124         .vop_read =             vop_stdnoread,
125         .vop_write =            vop_stdnowrite,
126         .vop_access =           hammer_vop_access,
127         .vop_close =            hammer_vop_close,
128         .vop_markatime =        hammer_vop_markatime,
129         .vop_getattr =          hammer_vop_getattr,
130         .vop_inactive =         hammer_vop_inactive,
131         .vop_reclaim =          hammer_vop_reclaim,
132         .vop_setattr =          hammer_vop_setattr
133 };
134
135 struct vop_ops hammer_fifo_vops = {
136         .vop_default =          fifo_vnoperate,
137         .vop_fsync =            hammer_vop_fsync,
138         .vop_read =             hammer_vop_fiforead,
139         .vop_write =            hammer_vop_fifowrite,
140         .vop_access =           hammer_vop_access,
141         .vop_close =            hammer_vop_fifoclose,
142         .vop_markatime =        hammer_vop_markatime,
143         .vop_getattr =          hammer_vop_getattr,
144         .vop_inactive =         hammer_vop_inactive,
145         .vop_reclaim =          hammer_vop_reclaim,
146         .vop_setattr =          hammer_vop_setattr,
147         .vop_kqfilter =         hammer_vop_fifokqfilter
148 };
149
150 static __inline
151 void
152 hammer_knote(struct vnode *vp, int flags)
153 {
154         if (flags)
155                 KNOTE(&vp->v_pollinfo.vpi_kqinfo.ki_note, flags);
156 }
157
158 #ifdef DEBUG_TRUNCATE
159 struct hammer_inode *HammerTruncIp;
160 #endif
161
162 static int hammer_dounlink(hammer_transaction_t trans, struct nchandle *nch,
163                            struct vnode *dvp, struct ucred *cred,
164                            int flags, int isdir);
165 static int hammer_vop_strategy_read(struct vop_strategy_args *ap);
166 static int hammer_vop_strategy_write(struct vop_strategy_args *ap);
167
168 /*
169  * hammer_vop_fsync { vp, waitfor }
170  *
171  * fsync() an inode to disk and wait for it to be completely committed
172  * such that the information would not be undone if a crash occured after
173  * return.
174  *
175  * NOTE: HAMMER's fsync()'s are going to remain expensive until we implement
176  *       a REDO log.  A sysctl is provided to relax HAMMER's fsync()
177  *       operation.
178  *
179  *       Ultimately the combination of a REDO log and use of fast storage
180  *       to front-end cluster caches will make fsync fast, but it aint
181  *       here yet.  And, in anycase, we need real transactional
182  *       all-or-nothing features which are not restricted to a single file.
183  */
184 static
185 int
186 hammer_vop_fsync(struct vop_fsync_args *ap)
187 {
188         hammer_inode_t ip = VTOI(ap->a_vp);
189         hammer_mount_t hmp = ip->hmp;
190         int waitfor = ap->a_waitfor;
191         int mode;
192
193         lwkt_gettoken(&hmp->fs_token);
194
195         /*
196          * Fsync rule relaxation (default is either full synchronous flush
197          * or REDO semantics with synchronous flush).
198          */
199         if (ap->a_flags & VOP_FSYNC_SYSCALL) {
200                 switch(hammer_fsync_mode) {
201                 case 0:
202 mode0:
203                         /* no REDO, full synchronous flush */
204                         goto skip;
205                 case 1:
206 mode1:
207                         /* no REDO, full asynchronous flush */
208                         if (waitfor == MNT_WAIT)
209                                 waitfor = MNT_NOWAIT;
210                         goto skip;
211                 case 2:
212                         /* REDO semantics, synchronous flush */
213                         if (hmp->version < HAMMER_VOL_VERSION_FOUR)
214                                 goto mode0;
215                         mode = HAMMER_FLUSH_UNDOS_AUTO;
216                         break;
217                 case 3:
218                         /* REDO semantics, relaxed asynchronous flush */
219                         if (hmp->version < HAMMER_VOL_VERSION_FOUR)
220                                 goto mode1;
221                         mode = HAMMER_FLUSH_UNDOS_RELAXED;
222                         if (waitfor == MNT_WAIT)
223                                 waitfor = MNT_NOWAIT;
224                         break;
225                 case 4:
226                         /* ignore the fsync() system call */
227                         lwkt_reltoken(&hmp->fs_token);
228                         return(0);
229                 default:
230                         /* we have to do something */
231                         mode = HAMMER_FLUSH_UNDOS_RELAXED;
232                         if (waitfor == MNT_WAIT)
233                                 waitfor = MNT_NOWAIT;
234                         break;
235                 }
236
237                 /*
238                  * Fast fsync only needs to flush the UNDO/REDO fifo if
239                  * HAMMER_INODE_REDO is non-zero and the only modifications
240                  * made to the file are write or write-extends.
241                  */
242                 if ((ip->flags & HAMMER_INODE_REDO) &&
243                     (ip->flags & HAMMER_INODE_MODMASK_NOREDO) == 0) {
244                         ++hammer_count_fsyncs;
245                         hammer_flusher_flush_undos(hmp, mode);
246                         ip->redo_count = 0;
247                         if (ip->vp && (ip->flags & HAMMER_INODE_MODMASK) == 0)
248                                 vclrisdirty(ip->vp);
249                         lwkt_reltoken(&hmp->fs_token);
250                         return(0);
251                 }
252
253                 /*
254                  * REDO is enabled by fsync(), the idea being we really only
255                  * want to lay down REDO records when programs are using
256                  * fsync() heavily.  The first fsync() on the file starts
257                  * the gravy train going and later fsync()s keep it hot by
258                  * resetting the redo_count.
259                  *
260                  * We weren't running REDOs before now so we have to fall
261                  * through and do a full fsync of what we have.
262                  */
263                 if (hmp->version >= HAMMER_VOL_VERSION_FOUR &&
264                     (hmp->flags & HAMMER_MOUNT_REDO_RECOVERY_RUN) == 0) {
265                         ip->flags |= HAMMER_INODE_REDO;
266                         ip->redo_count = 0;
267                 }
268         }
269 skip:
270
271         /*
272          * Do a full flush sequence.
273          *
274          * Attempt to release the vnode while waiting for the inode to
275          * finish flushing.  This can really mess up inactive->reclaim
276          * sequences so only do it if the vnode is active.
277          *
278          * WARNING! The VX lock functions must be used.  vn_lock() will
279          *          fail when this is part of a VOP_RECLAIM sequence.
280          */
281         ++hammer_count_fsyncs;
282         vfsync(ap->a_vp, waitfor, 1, NULL, NULL);
283         hammer_flush_inode(ip, HAMMER_FLUSH_SIGNAL);
284         if (waitfor == MNT_WAIT) {
285                 int dorelock;
286
287                 if ((ap->a_vp->v_flag & VRECLAIMED) == 0) {
288                         vx_unlock(ap->a_vp);
289                         dorelock = 1;
290                 } else {
291                         dorelock = 0;
292                 }
293                 hammer_wait_inode(ip);
294                 if (dorelock)
295                         vx_lock(ap->a_vp);
296         }
297         if (ip->vp && (ip->flags & HAMMER_INODE_MODMASK) == 0)
298                 vclrisdirty(ip->vp);
299         lwkt_reltoken(&hmp->fs_token);
300         return (ip->error);
301 }
302
303 /*
304  * hammer_vop_read { vp, uio, ioflag, cred }
305  *
306  * MPSAFE (for the cache safe does not require fs_token)
307  */
308 static
309 int
310 hammer_vop_read(struct vop_read_args *ap)
311 {
312         struct hammer_transaction trans;
313         hammer_inode_t ip;
314         hammer_mount_t hmp;
315         off_t offset;
316         struct buf *bp;
317         struct uio *uio;
318         int error;
319         int n;
320         int seqcount;
321         int ioseqcount;
322         int blksize;
323         int bigread;
324         int got_trans;
325         size_t resid;
326
327         if (ap->a_vp->v_type != VREG)
328                 return (EINVAL);
329         ip = VTOI(ap->a_vp);
330         hmp = ip->hmp;
331         error = 0;
332         got_trans = 0;
333         uio = ap->a_uio;
334
335         /*
336          * Attempt to shortcut directly to the VM object using lwbufs.
337          * This is much faster than instantiating buffer cache buffers.
338          */
339         resid = uio->uio_resid;
340         error = vop_helper_read_shortcut(ap);
341         hammer_stats_file_read += resid - uio->uio_resid;
342         if (error)
343                 return (error);
344         if (uio->uio_resid == 0)
345                 goto finished;
346
347         /*
348          * Allow the UIO's size to override the sequential heuristic.
349          */
350         blksize = hammer_blocksize(uio->uio_offset);
351         seqcount = (uio->uio_resid + (BKVASIZE - 1)) / BKVASIZE;
352         ioseqcount = (ap->a_ioflag >> 16);
353         if (seqcount < ioseqcount)
354                 seqcount = ioseqcount;
355
356         /*
357          * If reading or writing a huge amount of data we have to break
358          * atomicy and allow the operation to be interrupted by a signal
359          * or it can DOS the machine.
360          */
361         bigread = (uio->uio_resid > 100 * 1024 * 1024);
362
363         /*
364          * Access the data typically in HAMMER_BUFSIZE blocks via the
365          * buffer cache, but HAMMER may use a variable block size based
366          * on the offset.
367          *
368          * XXX Temporary hack, delay the start transaction while we remain
369          *     MPSAFE.  NOTE: ino_data.size cannot change while vnode is
370          *     locked-shared.
371          */
372         while (uio->uio_resid > 0 && uio->uio_offset < ip->ino_data.size) {
373                 int64_t base_offset;
374                 int64_t file_limit;
375
376                 blksize = hammer_blocksize(uio->uio_offset);
377                 offset = (int)uio->uio_offset & (blksize - 1);
378                 base_offset = uio->uio_offset - offset;
379
380                 if (bigread && (error = hammer_signal_check(ip->hmp)) != 0)
381                         break;
382
383                 /*
384                  * MPSAFE
385                  */
386                 bp = getblk(ap->a_vp, base_offset, blksize, 0, 0);
387                 if ((bp->b_flags & (B_INVAL | B_CACHE | B_RAM)) == B_CACHE) {
388                         bp->b_flags &= ~B_AGE;
389                         error = 0;
390                         goto skip;
391                 }
392                 if (ap->a_ioflag & IO_NRDELAY) {
393                         bqrelse(bp);
394                         return (EWOULDBLOCK);
395                 }
396
397                 /*
398                  * MPUNSAFE
399                  */
400                 if (got_trans == 0) {
401                         hammer_start_transaction(&trans, ip->hmp);
402                         got_trans = 1;
403                 }
404
405                 /*
406                  * NOTE: A valid bp has already been acquired, but was not
407                  *       B_CACHE.
408                  */
409                 if (hammer_cluster_enable) {
410                         /*
411                          * Use file_limit to prevent cluster_read() from
412                          * creating buffers of the wrong block size past
413                          * the demarc.
414                          */
415                         file_limit = ip->ino_data.size;
416                         if (base_offset < HAMMER_XDEMARC &&
417                             file_limit > HAMMER_XDEMARC) {
418                                 file_limit = HAMMER_XDEMARC;
419                         }
420                         error = cluster_readx(ap->a_vp,
421                                              file_limit, base_offset,
422                                              blksize, uio->uio_resid,
423                                              seqcount * BKVASIZE, &bp);
424                 } else {
425                         error = breadnx(ap->a_vp, base_offset, blksize,
426                                         NULL, NULL, 0, &bp);
427                 }
428                 if (error) {
429                         brelse(bp);
430                         break;
431                 }
432 skip:
433                 if ((hammer_debug_io & 0x0001) && (bp->b_flags & B_IODEBUG)) {
434                         kprintf("doff %016jx read file %016jx@%016jx\n",
435                                 (intmax_t)bp->b_bio2.bio_offset,
436                                 (intmax_t)ip->obj_id,
437                                 (intmax_t)bp->b_loffset);
438                 }
439                 bp->b_flags &= ~B_IODEBUG;
440                 if (blksize == HAMMER_XBUFSIZE)
441                         bp->b_flags |= B_CLUSTEROK;
442
443                 n = blksize - offset;
444                 if (n > uio->uio_resid)
445                         n = uio->uio_resid;
446                 if (n > ip->ino_data.size - uio->uio_offset)
447                         n = (int)(ip->ino_data.size - uio->uio_offset);
448
449                 /*
450                  * Set B_AGE, data has a lower priority than meta-data.
451                  *
452                  * Use a hold/unlock/drop sequence to run the uiomove
453                  * with the buffer unlocked, avoiding deadlocks against
454                  * read()s on mmap()'d spaces.
455                  */
456                 bp->b_flags |= B_AGE;
457                 error = uiomovebp(bp, (char *)bp->b_data + offset, n, uio);
458                 bqrelse(bp);
459
460                 if (error)
461                         break;
462                 hammer_stats_file_read += n;
463         }
464
465 finished:
466
467         /*
468          * Try to update the atime with just the inode lock for maximum
469          * concurrency.  If we can't shortcut it we have to get the full
470          * blown transaction.
471          */
472         if (got_trans == 0 && hammer_update_atime_quick(ip) < 0) {
473                 hammer_start_transaction(&trans, ip->hmp);
474                 got_trans = 1;
475         }
476
477         if (got_trans) {
478                 if ((ip->flags & HAMMER_INODE_RO) == 0 &&
479                     (ip->hmp->mp->mnt_flag & MNT_NOATIME) == 0) {
480                         lwkt_gettoken(&hmp->fs_token);
481                         ip->ino_data.atime = trans.time;
482                         hammer_modify_inode(&trans, ip, HAMMER_INODE_ATIME);
483                         hammer_done_transaction(&trans);
484                         lwkt_reltoken(&hmp->fs_token);
485                 } else {
486                         hammer_done_transaction(&trans);
487                 }
488         }
489         return (error);
490 }
491
492 /*
493  * hammer_vop_write { vp, uio, ioflag, cred }
494  */
495 static
496 int
497 hammer_vop_write(struct vop_write_args *ap)
498 {
499         struct hammer_transaction trans;
500         struct hammer_inode *ip;
501         hammer_mount_t hmp;
502         thread_t td;
503         struct uio *uio;
504         int offset;
505         off_t base_offset;
506         int64_t cluster_eof;
507         struct buf *bp;
508         int kflags;
509         int error;
510         int n;
511         int flags;
512         int seqcount;
513         int bigwrite;
514
515         if (ap->a_vp->v_type != VREG)
516                 return (EINVAL);
517         ip = VTOI(ap->a_vp);
518         hmp = ip->hmp;
519         error = 0;
520         kflags = 0;
521         seqcount = ap->a_ioflag >> 16;
522
523         if (ip->flags & HAMMER_INODE_RO)
524                 return (EROFS);
525
526         /*
527          * Create a transaction to cover the operations we perform.
528          */
529         hammer_start_transaction(&trans, hmp);
530         uio = ap->a_uio;
531
532         /*
533          * Check append mode
534          */
535         if (ap->a_ioflag & IO_APPEND)
536                 uio->uio_offset = ip->ino_data.size;
537
538         /*
539          * Check for illegal write offsets.  Valid range is 0...2^63-1.
540          *
541          * NOTE: the base_off assignment is required to work around what
542          * I consider to be a GCC-4 optimization bug.
543          */
544         if (uio->uio_offset < 0) {
545                 hammer_done_transaction(&trans);
546                 return (EFBIG);
547         }
548         base_offset = uio->uio_offset + uio->uio_resid; /* work around gcc-4 */
549         if (uio->uio_resid > 0 && base_offset <= uio->uio_offset) {
550                 hammer_done_transaction(&trans);
551                 return (EFBIG);
552         }
553
554         if (uio->uio_resid > 0 && (td = uio->uio_td) != NULL && td->td_proc &&
555             base_offset > td->td_proc->p_rlimit[RLIMIT_FSIZE].rlim_cur) {
556                 hammer_done_transaction(&trans);
557                 lwpsignal(td->td_proc, td->td_lwp, SIGXFSZ);
558                 return (EFBIG);
559         }
560
561         /*
562          * If reading or writing a huge amount of data we have to break
563          * atomicy and allow the operation to be interrupted by a signal
564          * or it can DOS the machine.
565          *
566          * Preset redo_count so we stop generating REDOs earlier if the
567          * limit is exceeded.
568          *
569          * redo_count is heuristical, SMP races are ok
570          */
571         bigwrite = (uio->uio_resid > 100 * 1024 * 1024);
572         if ((ip->flags & HAMMER_INODE_REDO) &&
573             ip->redo_count < hammer_limit_redo) {
574                 ip->redo_count += uio->uio_resid;
575         }
576
577         /*
578          * Access the data typically in HAMMER_BUFSIZE blocks via the
579          * buffer cache, but HAMMER may use a variable block size based
580          * on the offset.
581          */
582         while (uio->uio_resid > 0) {
583                 int fixsize = 0;
584                 int blksize;
585                 int blkmask;
586                 int trivial;
587                 int endofblk;
588                 off_t nsize;
589
590                 if ((error = hammer_checkspace(hmp, HAMMER_CHKSPC_WRITE)) != 0)
591                         break;
592                 if (bigwrite && (error = hammer_signal_check(hmp)) != 0)
593                         break;
594
595                 blksize = hammer_blocksize(uio->uio_offset);
596
597                 /*
598                  * Control the number of pending records associated with
599                  * this inode.  If too many have accumulated start a
600                  * flush.  Try to maintain a pipeline with the flusher.
601                  *
602                  * NOTE: It is possible for other sources to grow the
603                  *       records but not necessarily issue another flush,
604                  *       so use a timeout and ensure that a re-flush occurs.
605                  */
606                 if (ip->rsv_recs >= hammer_limit_inode_recs) {
607                         lwkt_gettoken(&hmp->fs_token);
608                         hammer_flush_inode(ip, HAMMER_FLUSH_SIGNAL);
609                         while (ip->rsv_recs >= hammer_limit_inode_recs * 2) {
610                                 ip->flags |= HAMMER_INODE_RECSW;
611                                 tsleep(&ip->rsv_recs, 0, "hmrwww", hz);
612                                 hammer_flush_inode(ip, HAMMER_FLUSH_SIGNAL);
613                         }
614                         lwkt_reltoken(&hmp->fs_token);
615                 }
616
617                 /*
618                  * Do not allow HAMMER to blow out the buffer cache.  Very
619                  * large UIOs can lockout other processes due to bwillwrite()
620                  * mechanics.
621                  *
622                  * The hammer inode is not locked during these operations.
623                  * The vnode is locked which can interfere with the pageout
624                  * daemon for non-UIO_NOCOPY writes but should not interfere
625                  * with the buffer cache.  Even so, we cannot afford to
626                  * allow the pageout daemon to build up too many dirty buffer
627                  * cache buffers.
628                  *
629                  * Only call this if we aren't being recursively called from
630                  * a virtual disk device (vn), else we may deadlock.
631                  */
632                 if ((ap->a_ioflag & IO_RECURSE) == 0)
633                         bwillwrite(blksize);
634
635                 /*
636                  * Calculate the blocksize at the current offset and figure
637                  * out how much we can actually write.
638                  */
639                 blkmask = blksize - 1;
640                 offset = (int)uio->uio_offset & blkmask;
641                 base_offset = uio->uio_offset & ~(int64_t)blkmask;
642                 n = blksize - offset;
643                 if (n > uio->uio_resid) {
644                         n = uio->uio_resid;
645                         endofblk = 0;
646                 } else {
647                         endofblk = 1;
648                 }
649                 nsize = uio->uio_offset + n;
650                 if (nsize > ip->ino_data.size) {
651                         if (uio->uio_offset > ip->ino_data.size)
652                                 trivial = 0;
653                         else
654                                 trivial = 1;
655                         nvextendbuf(ap->a_vp,
656                                     ip->ino_data.size,
657                                     nsize,
658                                     hammer_blocksize(ip->ino_data.size),
659                                     hammer_blocksize(nsize),
660                                     hammer_blockoff(ip->ino_data.size),
661                                     hammer_blockoff(nsize),
662                                     trivial);
663                         fixsize = 1;
664                         kflags |= NOTE_EXTEND;
665                 }
666
667                 if (uio->uio_segflg == UIO_NOCOPY) {
668                         /*
669                          * Issuing a write with the same data backing the
670                          * buffer.  Instantiate the buffer to collect the
671                          * backing vm pages, then read-in any missing bits.
672                          *
673                          * This case is used by vop_stdputpages().
674                          */
675                         bp = getblk(ap->a_vp, base_offset,
676                                     blksize, GETBLK_BHEAVY, 0);
677                         if ((bp->b_flags & B_CACHE) == 0) {
678                                 bqrelse(bp);
679                                 error = bread(ap->a_vp, base_offset,
680                                               blksize, &bp);
681                         }
682                 } else if (offset == 0 && uio->uio_resid >= blksize) {
683                         /*
684                          * Even though we are entirely overwriting the buffer
685                          * we may still have to zero it out to avoid a
686                          * mmap/write visibility issue.
687                          */
688                         bp = getblk(ap->a_vp, base_offset, blksize, GETBLK_BHEAVY, 0);
689                         if ((bp->b_flags & B_CACHE) == 0)
690                                 vfs_bio_clrbuf(bp);
691                 } else if (base_offset >= ip->ino_data.size) {
692                         /*
693                          * If the base offset of the buffer is beyond the
694                          * file EOF, we don't have to issue a read.
695                          */
696                         bp = getblk(ap->a_vp, base_offset,
697                                     blksize, GETBLK_BHEAVY, 0);
698                         vfs_bio_clrbuf(bp);
699                 } else {
700                         /*
701                          * Partial overwrite, read in any missing bits then
702                          * replace the portion being written.
703                          */
704                         error = bread(ap->a_vp, base_offset, blksize, &bp);
705                         if (error == 0)
706                                 bheavy(bp);
707                 }
708                 if (error == 0)
709                         error = uiomovebp(bp, bp->b_data + offset, n, uio);
710
711                 lwkt_gettoken(&hmp->fs_token);
712
713                 /*
714                  * Generate REDO records if enabled and redo_count will not
715                  * exceeded the limit.
716                  *
717                  * If redo_count exceeds the limit we stop generating records
718                  * and clear HAMMER_INODE_REDO.  This will cause the next
719                  * fsync() to do a full meta-data sync instead of just an
720                  * UNDO/REDO fifo update.
721                  *
722                  * When clearing HAMMER_INODE_REDO any pre-existing REDOs
723                  * will still be tracked.  The tracks will be terminated
724                  * when the related meta-data (including possible data
725                  * modifications which are not tracked via REDO) is
726                  * flushed.
727                  */
728                 if ((ip->flags & HAMMER_INODE_REDO) && error == 0) {
729                         if (ip->redo_count < hammer_limit_redo) {
730                                 bp->b_flags |= B_VFSFLAG1;
731                                 error = hammer_generate_redo(&trans, ip,
732                                                      base_offset + offset,
733                                                      HAMMER_REDO_WRITE,
734                                                      bp->b_data + offset,
735                                                      (size_t)n);
736                         } else {
737                                 ip->flags &= ~HAMMER_INODE_REDO;
738                         }
739                 }
740
741                 /*
742                  * If we screwed up we have to undo any VM size changes we
743                  * made.
744                  */
745                 if (error) {
746                         brelse(bp);
747                         if (fixsize) {
748                                 nvtruncbuf(ap->a_vp, ip->ino_data.size,
749                                           hammer_blocksize(ip->ino_data.size),
750                                           hammer_blockoff(ip->ino_data.size),
751                                           0);
752                         }
753                         lwkt_reltoken(&hmp->fs_token);
754                         break;
755                 }
756                 kflags |= NOTE_WRITE;
757                 hammer_stats_file_write += n;
758                 if (blksize == HAMMER_XBUFSIZE)
759                         bp->b_flags |= B_CLUSTEROK;
760                 if (ip->ino_data.size < uio->uio_offset) {
761                         ip->ino_data.size = uio->uio_offset;
762                         flags = HAMMER_INODE_SDIRTY;
763                 } else {
764                         flags = 0;
765                 }
766                 ip->ino_data.mtime = trans.time;
767                 flags |= HAMMER_INODE_MTIME | HAMMER_INODE_BUFS;
768                 hammer_modify_inode(&trans, ip, flags);
769
770                 /*
771                  * Once we dirty the buffer any cached zone-X offset
772                  * becomes invalid.  HAMMER NOTE: no-history mode cannot
773                  * allow overwriting over the same data sector unless
774                  * we provide UNDOs for the old data, which we don't.
775                  */
776                 bp->b_bio2.bio_offset = NOOFFSET;
777
778                 lwkt_reltoken(&hmp->fs_token);
779
780                 /*
781                  * Final buffer disposition.
782                  *
783                  * Because meta-data updates are deferred, HAMMER is
784                  * especially sensitive to excessive bdwrite()s because
785                  * the I/O stream is not broken up by disk reads.  So the
786                  * buffer cache simply cannot keep up.
787                  *
788                  * WARNING!  blksize is variable.  cluster_write() is
789                  *           expected to not blow up if it encounters
790                  *           buffers that do not match the passed blksize.
791                  *
792                  * NOTE!  Hammer shouldn't need to bawrite()/cluster_write().
793                  *        The ip->rsv_recs check should burst-flush the data.
794                  *        If we queue it immediately the buf could be left
795                  *        locked on the device queue for a very long time.
796                  *
797                  *        However, failing to flush a dirty buffer out when
798                  *        issued from the pageout daemon can result in a low
799                  *        memory deadlock against bio_page_alloc(), so we
800                  *        have to bawrite() on IO_ASYNC as well.
801                  *
802                  * NOTE!  To avoid degenerate stalls due to mismatched block
803                  *        sizes we only honor IO_DIRECT on the write which
804                  *        abuts the end of the buffer.  However, we must
805                  *        honor IO_SYNC in case someone is silly enough to
806                  *        configure a HAMMER file as swap, or when HAMMER
807                  *        is serving NFS (for commits).  Ick ick.
808                  */
809                 bp->b_flags |= B_AGE;
810                 if (blksize == HAMMER_XBUFSIZE)
811                         bp->b_flags |= B_CLUSTEROK;
812
813                 if (ap->a_ioflag & IO_SYNC) {
814                         bwrite(bp);
815                 } else if ((ap->a_ioflag & IO_DIRECT) && endofblk) {
816                         bawrite(bp);
817                 } else if (ap->a_ioflag & IO_ASYNC) {
818                         bawrite(bp);
819                 } else if (hammer_cluster_enable &&
820                            !(ap->a_vp->v_mount->mnt_flag & MNT_NOCLUSTERW)) {
821                         if (base_offset < HAMMER_XDEMARC)
822                                 cluster_eof = hammer_blockdemarc(base_offset,
823                                                          ip->ino_data.size);
824                         else
825                                 cluster_eof = ip->ino_data.size;
826                         cluster_write(bp, cluster_eof, blksize, seqcount);
827                 } else {
828                         bdwrite(bp);
829                 }
830         }
831         hammer_done_transaction(&trans);
832         hammer_knote(ap->a_vp, kflags);
833
834         return (error);
835 }
836
837 /*
838  * hammer_vop_access { vp, mode, cred }
839  *
840  * MPSAFE - does not require fs_token
841  */
842 static
843 int
844 hammer_vop_access(struct vop_access_args *ap)
845 {
846         struct hammer_inode *ip = VTOI(ap->a_vp);
847         uid_t uid;
848         gid_t gid;
849         int error;
850
851         ++hammer_stats_file_iopsr;
852         uid = hammer_to_unix_xid(&ip->ino_data.uid);
853         gid = hammer_to_unix_xid(&ip->ino_data.gid);
854
855         error = vop_helper_access(ap, uid, gid, ip->ino_data.mode,
856                                   ip->ino_data.uflags);
857         return (error);
858 }
859
860 /*
861  * hammer_vop_advlock { vp, id, op, fl, flags }
862  *
863  * MPSAFE - does not require fs_token
864  */
865 static
866 int
867 hammer_vop_advlock(struct vop_advlock_args *ap)
868 {
869         hammer_inode_t ip = VTOI(ap->a_vp);
870
871         return (lf_advlock(ap, &ip->advlock, ip->ino_data.size));
872 }
873
874 /*
875  * hammer_vop_close { vp, fflag }
876  *
877  * We can only sync-on-close for normal closes.  XXX disabled for now.
878  */
879 static
880 int
881 hammer_vop_close(struct vop_close_args *ap)
882 {
883 #if 0
884         struct vnode *vp = ap->a_vp;
885         hammer_inode_t ip = VTOI(vp);
886         int waitfor;
887         if (ip->flags & (HAMMER_INODE_CLOSESYNC|HAMMER_INODE_CLOSEASYNC)) {
888                 if (vn_islocked(vp) == LK_EXCLUSIVE &&
889                     (vp->v_flag & (VINACTIVE|VRECLAIMED)) == 0) {
890                         if (ip->flags & HAMMER_INODE_CLOSESYNC)
891                                 waitfor = MNT_WAIT;
892                         else
893                                 waitfor = MNT_NOWAIT;
894                         ip->flags &= ~(HAMMER_INODE_CLOSESYNC |
895                                        HAMMER_INODE_CLOSEASYNC);
896                         VOP_FSYNC(vp, MNT_NOWAIT, waitfor);
897                 }
898         }
899 #endif
900         return (vop_stdclose(ap));
901 }
902
903 /*
904  * hammer_vop_ncreate { nch, dvp, vpp, cred, vap }
905  *
906  * The operating system has already ensured that the directory entry
907  * does not exist and done all appropriate namespace locking.
908  */
909 static
910 int
911 hammer_vop_ncreate(struct vop_ncreate_args *ap)
912 {
913         struct hammer_transaction trans;
914         struct hammer_inode *dip;
915         struct hammer_inode *nip;
916         struct nchandle *nch;
917         hammer_mount_t hmp;
918         int error;
919
920         nch = ap->a_nch;
921         dip = VTOI(ap->a_dvp);
922         hmp = dip->hmp;
923
924         if (dip->flags & HAMMER_INODE_RO)
925                 return (EROFS);
926         if ((error = hammer_checkspace(hmp, HAMMER_CHKSPC_CREATE)) != 0)
927                 return (error);
928
929         /*
930          * Create a transaction to cover the operations we perform.
931          */
932         lwkt_gettoken(&hmp->fs_token);
933         hammer_start_transaction(&trans, hmp);
934         ++hammer_stats_file_iopsw;
935
936         /*
937          * Create a new filesystem object of the requested type.  The
938          * returned inode will be referenced and shared-locked to prevent
939          * it from being moved to the flusher.
940          */
941         error = hammer_create_inode(&trans, ap->a_vap, ap->a_cred,
942                                     dip, nch->ncp->nc_name, nch->ncp->nc_nlen,
943                                     NULL, &nip);
944         if (error) {
945                 hkprintf("hammer_create_inode error %d\n", error);
946                 hammer_done_transaction(&trans);
947                 *ap->a_vpp = NULL;
948                 lwkt_reltoken(&hmp->fs_token);
949                 return (error);
950         }
951
952         /*
953          * Add the new filesystem object to the directory.  This will also
954          * bump the inode's link count.
955          */
956         error = hammer_ip_add_directory(&trans, dip,
957                                         nch->ncp->nc_name, nch->ncp->nc_nlen,
958                                         nip);
959         if (error)
960                 hkprintf("hammer_ip_add_directory error %d\n", error);
961
962         /*
963          * Finish up.
964          */
965         if (error) {
966                 hammer_rel_inode(nip, 0);
967                 hammer_done_transaction(&trans);
968                 *ap->a_vpp = NULL;
969         } else {
970                 error = hammer_get_vnode(nip, ap->a_vpp);
971                 hammer_done_transaction(&trans);
972                 hammer_rel_inode(nip, 0);
973                 if (error == 0) {
974                         cache_setunresolved(ap->a_nch);
975                         cache_setvp(ap->a_nch, *ap->a_vpp);
976                 }
977                 hammer_knote(ap->a_dvp, NOTE_WRITE);
978         }
979         lwkt_reltoken(&hmp->fs_token);
980         return (error);
981 }
982
983 /*
984  * hammer_vop_getattr { vp, vap }
985  *
986  * Retrieve an inode's attribute information.  When accessing inodes
987  * historically we fake the atime field to ensure consistent results.
988  * The atime field is stored in the B-Tree element and allowed to be
989  * updated without cycling the element.
990  *
991  * MPSAFE - does not require fs_token
992  */
993 static
994 int
995 hammer_vop_getattr(struct vop_getattr_args *ap)
996 {
997         struct hammer_inode *ip = VTOI(ap->a_vp);
998         struct vattr *vap = ap->a_vap;
999
1000         /*
1001          * We want the fsid to be different when accessing a filesystem
1002          * with different as-of's so programs like diff don't think
1003          * the files are the same.
1004          *
1005          * We also want the fsid to be the same when comparing snapshots,
1006          * or when comparing mirrors (which might be backed by different
1007          * physical devices).  HAMMER fsids are based on the PFS's
1008          * shared_uuid field.
1009          *
1010          * XXX there is a chance of collision here.  The va_fsid reported
1011          * by stat is different from the more involved fsid used in the
1012          * mount structure.
1013          */
1014         ++hammer_stats_file_iopsr;
1015         hammer_lock_sh(&ip->lock);
1016         vap->va_fsid = ip->pfsm->fsid_udev ^ (u_int32_t)ip->obj_asof ^
1017                        (u_int32_t)(ip->obj_asof >> 32);
1018
1019         vap->va_fileid = ip->ino_leaf.base.obj_id;
1020         vap->va_mode = ip->ino_data.mode;
1021         vap->va_nlink = ip->ino_data.nlinks;
1022         vap->va_uid = hammer_to_unix_xid(&ip->ino_data.uid);
1023         vap->va_gid = hammer_to_unix_xid(&ip->ino_data.gid);
1024         vap->va_rmajor = 0;
1025         vap->va_rminor = 0;
1026         vap->va_size = ip->ino_data.size;
1027
1028         /*
1029          * Special case for @@PFS softlinks.  The actual size of the
1030          * expanded softlink is "@@0x%016llx:%05d" == 26 bytes.
1031          * or for MAX_TID is    "@@-1:%05d" == 10 bytes.
1032          *
1033          * Note that userspace hammer command does not allow users to
1034          * create a @@PFS softlink under an existing other PFS (id!=0)
1035          * so the ip localization here for @@PFS softlink is always 0.
1036          */
1037         if (ip->ino_data.obj_type == HAMMER_OBJTYPE_SOFTLINK &&
1038             ip->ino_data.size == 10 &&
1039             ip->obj_asof == HAMMER_MAX_TID &&
1040             ip->obj_localization == 0 &&
1041             strncmp(ip->ino_data.ext.symlink, "@@PFS", 5) == 0) {
1042                     if (ip->pfsm->pfsd.mirror_flags & HAMMER_PFSD_SLAVE)
1043                             vap->va_size = 26;
1044                     else
1045                             vap->va_size = 10;
1046         }
1047
1048         /*
1049          * We must provide a consistent atime and mtime for snapshots
1050          * so people can do a 'tar cf - ... | md5' on them and get
1051          * consistent results.
1052          */
1053         if (ip->flags & HAMMER_INODE_RO) {
1054                 hammer_time_to_timespec(ip->ino_data.ctime, &vap->va_atime);
1055                 hammer_time_to_timespec(ip->ino_data.ctime, &vap->va_mtime);
1056         } else {
1057                 hammer_time_to_timespec(ip->ino_data.atime, &vap->va_atime);
1058                 hammer_time_to_timespec(ip->ino_data.mtime, &vap->va_mtime);
1059         }
1060         hammer_time_to_timespec(ip->ino_data.ctime, &vap->va_ctime);
1061         vap->va_flags = ip->ino_data.uflags;
1062         vap->va_gen = 1;        /* hammer inums are unique for all time */
1063         vap->va_blocksize = HAMMER_BUFSIZE;
1064         if (ip->ino_data.size >= HAMMER_XDEMARC) {
1065                 vap->va_bytes = (ip->ino_data.size + HAMMER_XBUFMASK64) &
1066                                 ~HAMMER_XBUFMASK64;
1067         } else if (ip->ino_data.size > HAMMER_BUFSIZE / 2) {
1068                 vap->va_bytes = (ip->ino_data.size + HAMMER_BUFMASK64) &
1069                                 ~HAMMER_BUFMASK64;
1070         } else {
1071                 vap->va_bytes = (ip->ino_data.size + 15) & ~15;
1072         }
1073
1074         vap->va_type = hammer_get_vnode_type(ip->ino_data.obj_type);
1075         vap->va_filerev = 0;    /* XXX */
1076         vap->va_uid_uuid = ip->ino_data.uid;
1077         vap->va_gid_uuid = ip->ino_data.gid;
1078         vap->va_fsid_uuid = ip->hmp->fsid;
1079         vap->va_vaflags = VA_UID_UUID_VALID | VA_GID_UUID_VALID |
1080                           VA_FSID_UUID_VALID;
1081
1082         switch (ip->ino_data.obj_type) {
1083         case HAMMER_OBJTYPE_CDEV:
1084         case HAMMER_OBJTYPE_BDEV:
1085                 vap->va_rmajor = ip->ino_data.rmajor;
1086                 vap->va_rminor = ip->ino_data.rminor;
1087                 break;
1088         default:
1089                 break;
1090         }
1091         hammer_unlock(&ip->lock);
1092         return(0);
1093 }
1094
1095 /*
1096  * hammer_vop_nresolve { nch, dvp, cred }
1097  *
1098  * Locate the requested directory entry.
1099  */
1100 static
1101 int
1102 hammer_vop_nresolve(struct vop_nresolve_args *ap)
1103 {
1104         struct hammer_transaction trans;
1105         struct namecache *ncp;
1106         hammer_mount_t hmp;
1107         hammer_inode_t dip;
1108         hammer_inode_t ip;
1109         hammer_tid_t asof;
1110         struct hammer_cursor cursor;
1111         struct vnode *vp;
1112         int64_t namekey;
1113         int error;
1114         int i;
1115         int nlen;
1116         int flags;
1117         int ispfs;
1118         int64_t obj_id;
1119         u_int32_t localization;
1120         u_int32_t max_iterations;
1121
1122         /*
1123          * Misc initialization, plus handle as-of name extensions.  Look for
1124          * the '@@' extension.  Note that as-of files and directories cannot
1125          * be modified.
1126          */
1127         dip = VTOI(ap->a_dvp);
1128         ncp = ap->a_nch->ncp;
1129         asof = dip->obj_asof;
1130         localization = dip->obj_localization;   /* for code consistency */
1131         nlen = ncp->nc_nlen;
1132         flags = dip->flags & HAMMER_INODE_RO;
1133         ispfs = 0;
1134         hmp = dip->hmp;
1135
1136         lwkt_gettoken(&hmp->fs_token);
1137         hammer_simple_transaction(&trans, hmp);
1138         ++hammer_stats_file_iopsr;
1139
1140         for (i = 0; i < nlen; ++i) {
1141                 if (ncp->nc_name[i] == '@' && ncp->nc_name[i+1] == '@') {
1142                         error = hammer_str_to_tid(ncp->nc_name + i + 2,
1143                                                   &ispfs, &asof, &localization);
1144                         if (error != 0) {
1145                                 i = nlen;
1146                                 break;
1147                         }
1148                         if (asof != HAMMER_MAX_TID)
1149                                 flags |= HAMMER_INODE_RO;
1150                         break;
1151                 }
1152         }
1153         nlen = i;
1154
1155         /*
1156          * If this is a PFS softlink we dive into the PFS
1157          */
1158         if (ispfs && nlen == 0) {
1159                 ip = hammer_get_inode(&trans, dip, HAMMER_OBJID_ROOT,
1160                                       asof, localization,
1161                                       flags, &error);
1162                 if (error == 0) {
1163                         error = hammer_get_vnode(ip, &vp);
1164                         hammer_rel_inode(ip, 0);
1165                 } else {
1166                         vp = NULL;
1167                 }
1168                 if (error == 0) {
1169                         vn_unlock(vp);
1170                         cache_setvp(ap->a_nch, vp);
1171                         vrele(vp);
1172                 }
1173                 goto done;
1174         }
1175
1176         /*
1177          * If there is no path component the time extension is relative to dip.
1178          * e.g. "fubar/@@<snapshot>"
1179          *
1180          * "." is handled by the kernel, but ".@@<snapshot>" is not.
1181          * e.g. "fubar/.@@<snapshot>"
1182          *
1183          * ".." is handled by the kernel.  We do not currently handle
1184          * "..@<snapshot>".
1185          */
1186         if (nlen == 0 || (nlen == 1 && ncp->nc_name[0] == '.')) {
1187                 ip = hammer_get_inode(&trans, dip, dip->obj_id,
1188                                       asof, dip->obj_localization,
1189                                       flags, &error);
1190                 if (error == 0) {
1191                         error = hammer_get_vnode(ip, &vp);
1192                         hammer_rel_inode(ip, 0);
1193                 } else {
1194                         vp = NULL;
1195                 }
1196                 if (error == 0) {
1197                         vn_unlock(vp);
1198                         cache_setvp(ap->a_nch, vp);
1199                         vrele(vp);
1200                 }
1201                 goto done;
1202         }
1203
1204         /*
1205          * Calculate the namekey and setup the key range for the scan.  This
1206          * works kinda like a chained hash table where the lower 32 bits
1207          * of the namekey synthesize the chain.
1208          *
1209          * The key range is inclusive of both key_beg and key_end.
1210          */
1211         namekey = hammer_directory_namekey(dip, ncp->nc_name, nlen,
1212                                            &max_iterations);
1213
1214         error = hammer_init_cursor(&trans, &cursor, &dip->cache[1], dip);
1215         cursor.key_beg.localization = dip->obj_localization +
1216                                       hammer_dir_localization(dip);
1217         cursor.key_beg.obj_id = dip->obj_id;
1218         cursor.key_beg.key = namekey;
1219         cursor.key_beg.create_tid = 0;
1220         cursor.key_beg.delete_tid = 0;
1221         cursor.key_beg.rec_type = HAMMER_RECTYPE_DIRENTRY;
1222         cursor.key_beg.obj_type = 0;
1223
1224         cursor.key_end = cursor.key_beg;
1225         cursor.key_end.key += max_iterations;
1226         cursor.asof = asof;
1227         cursor.flags |= HAMMER_CURSOR_END_INCLUSIVE | HAMMER_CURSOR_ASOF;
1228
1229         /*
1230          * Scan all matching records (the chain), locate the one matching
1231          * the requested path component.
1232          *
1233          * The hammer_ip_*() functions merge in-memory records with on-disk
1234          * records for the purposes of the search.
1235          */
1236         obj_id = 0;
1237         localization = HAMMER_DEF_LOCALIZATION;
1238
1239         if (error == 0) {
1240                 error = hammer_ip_first(&cursor);
1241                 while (error == 0) {
1242                         error = hammer_ip_resolve_data(&cursor);
1243                         if (error)
1244                                 break;
1245                         if (nlen == cursor.leaf->data_len - HAMMER_ENTRY_NAME_OFF &&
1246                             bcmp(ncp->nc_name, cursor.data->entry.name, nlen) == 0) {
1247                                 obj_id = cursor.data->entry.obj_id;
1248                                 localization = cursor.data->entry.localization;
1249                                 break;
1250                         }
1251                         error = hammer_ip_next(&cursor);
1252                 }
1253         }
1254         hammer_done_cursor(&cursor);
1255
1256         /*
1257          * Lookup the obj_id.  This should always succeed.  If it does not
1258          * the filesystem may be damaged and we return a dummy inode.
1259          */
1260         if (error == 0) {
1261                 ip = hammer_get_inode(&trans, dip, obj_id,
1262                                       asof, localization,
1263                                       flags, &error);
1264                 if (error == ENOENT) {
1265                         kprintf("HAMMER: WARNING: Missing "
1266                                 "inode for dirent \"%s\"\n"
1267                                 "\tobj_id = %016llx, asof=%016llx, lo=%08x\n",
1268                                 ncp->nc_name,
1269                                 (long long)obj_id, (long long)asof,
1270                                 localization);
1271                         error = 0;
1272                         ip = hammer_get_dummy_inode(&trans, dip, obj_id,
1273                                                     asof, localization,
1274                                                     flags, &error);
1275                 }
1276                 if (error == 0) {
1277                         error = hammer_get_vnode(ip, &vp);
1278                         hammer_rel_inode(ip, 0);
1279                 } else {
1280                         vp = NULL;
1281                 }
1282                 if (error == 0) {
1283                         vn_unlock(vp);
1284                         cache_setvp(ap->a_nch, vp);
1285                         vrele(vp);
1286                 }
1287         } else if (error == ENOENT) {
1288                 cache_setvp(ap->a_nch, NULL);
1289         }
1290 done:
1291         hammer_done_transaction(&trans);
1292         lwkt_reltoken(&hmp->fs_token);
1293         return (error);
1294 }
1295
1296 /*
1297  * hammer_vop_nlookupdotdot { dvp, vpp, cred }
1298  *
1299  * Locate the parent directory of a directory vnode.
1300  *
1301  * dvp is referenced but not locked.  *vpp must be returned referenced and
1302  * locked.  A parent_obj_id of 0 does not necessarily indicate that we are
1303  * at the root, instead it could indicate that the directory we were in was
1304  * removed.
1305  *
1306  * NOTE: as-of sequences are not linked into the directory structure.  If
1307  * we are at the root with a different asof then the mount point, reload
1308  * the same directory with the mount point's asof.   I'm not sure what this
1309  * will do to NFS.  We encode ASOF stamps in NFS file handles so it might not
1310  * get confused, but it hasn't been tested.
1311  */
1312 static
1313 int
1314 hammer_vop_nlookupdotdot(struct vop_nlookupdotdot_args *ap)
1315 {
1316         struct hammer_transaction trans;
1317         struct hammer_inode *dip;
1318         struct hammer_inode *ip;
1319         hammer_mount_t hmp;
1320         int64_t parent_obj_id;
1321         u_int32_t parent_obj_localization;
1322         hammer_tid_t asof;
1323         int error;
1324
1325         dip = VTOI(ap->a_dvp);
1326         asof = dip->obj_asof;
1327         hmp = dip->hmp;
1328
1329         /*
1330          * Whos are parent?  This could be the root of a pseudo-filesystem
1331          * whos parent is in another localization domain.
1332          */
1333         lwkt_gettoken(&hmp->fs_token);
1334         parent_obj_id = dip->ino_data.parent_obj_id;
1335         if (dip->obj_id == HAMMER_OBJID_ROOT)
1336                 parent_obj_localization = dip->ino_data.ext.obj.parent_obj_localization;
1337         else
1338                 parent_obj_localization = dip->obj_localization;
1339
1340         /*
1341          * It's probably a PFS root when dip->ino_data.parent_obj_id is 0.
1342          */
1343         if (parent_obj_id == 0) {
1344                 if (dip->obj_id == HAMMER_OBJID_ROOT &&
1345                    asof != hmp->asof) {
1346                         parent_obj_id = dip->obj_id;
1347                         asof = hmp->asof;
1348                         *ap->a_fakename = kmalloc(19, M_TEMP, M_WAITOK);
1349                         ksnprintf(*ap->a_fakename, 19, "0x%016llx",
1350                                   (long long)dip->obj_asof);
1351                 } else {
1352                         *ap->a_vpp = NULL;
1353                         lwkt_reltoken(&hmp->fs_token);
1354                         return ENOENT;
1355                 }
1356         }
1357
1358         hammer_simple_transaction(&trans, hmp);
1359         ++hammer_stats_file_iopsr;
1360
1361         ip = hammer_get_inode(&trans, dip, parent_obj_id,
1362                               asof, parent_obj_localization,
1363                               dip->flags, &error);
1364         if (ip) {
1365                 error = hammer_get_vnode(ip, ap->a_vpp);
1366                 hammer_rel_inode(ip, 0);
1367         } else {
1368                 *ap->a_vpp = NULL;
1369         }
1370         hammer_done_transaction(&trans);
1371         lwkt_reltoken(&hmp->fs_token);
1372         return (error);
1373 }
1374
1375 /*
1376  * hammer_vop_nlink { nch, dvp, vp, cred }
1377  */
1378 static
1379 int
1380 hammer_vop_nlink(struct vop_nlink_args *ap)
1381 {
1382         struct hammer_transaction trans;
1383         struct hammer_inode *dip;
1384         struct hammer_inode *ip;
1385         struct nchandle *nch;
1386         hammer_mount_t hmp;
1387         int error;
1388
1389         if (ap->a_dvp->v_mount != ap->a_vp->v_mount)
1390                 return(EXDEV);
1391
1392         nch = ap->a_nch;
1393         dip = VTOI(ap->a_dvp);
1394         ip = VTOI(ap->a_vp);
1395         hmp = dip->hmp;
1396
1397         if (dip->obj_localization != ip->obj_localization)
1398                 return(EXDEV);
1399
1400         if (dip->flags & HAMMER_INODE_RO)
1401                 return (EROFS);
1402         if (ip->flags & HAMMER_INODE_RO)
1403                 return (EROFS);
1404         if ((error = hammer_checkspace(hmp, HAMMER_CHKSPC_CREATE)) != 0)
1405                 return (error);
1406
1407         /*
1408          * Create a transaction to cover the operations we perform.
1409          */
1410         lwkt_gettoken(&hmp->fs_token);
1411         hammer_start_transaction(&trans, hmp);
1412         ++hammer_stats_file_iopsw;
1413
1414         /*
1415          * Add the filesystem object to the directory.  Note that neither
1416          * dip nor ip are referenced or locked, but their vnodes are
1417          * referenced.  This function will bump the inode's link count.
1418          */
1419         error = hammer_ip_add_directory(&trans, dip,
1420                                         nch->ncp->nc_name, nch->ncp->nc_nlen,
1421                                         ip);
1422
1423         /*
1424          * Finish up.
1425          */
1426         if (error == 0) {
1427                 cache_setunresolved(nch);
1428                 cache_setvp(nch, ap->a_vp);
1429         }
1430         hammer_done_transaction(&trans);
1431         hammer_knote(ap->a_vp, NOTE_LINK);
1432         hammer_knote(ap->a_dvp, NOTE_WRITE);
1433         lwkt_reltoken(&hmp->fs_token);
1434         return (error);
1435 }
1436
1437 /*
1438  * hammer_vop_nmkdir { nch, dvp, vpp, cred, vap }
1439  *
1440  * The operating system has already ensured that the directory entry
1441  * does not exist and done all appropriate namespace locking.
1442  */
1443 static
1444 int
1445 hammer_vop_nmkdir(struct vop_nmkdir_args *ap)
1446 {
1447         struct hammer_transaction trans;
1448         struct hammer_inode *dip;
1449         struct hammer_inode *nip;
1450         struct nchandle *nch;
1451         hammer_mount_t hmp;
1452         int error;
1453
1454         nch = ap->a_nch;
1455         dip = VTOI(ap->a_dvp);
1456         hmp = dip->hmp;
1457
1458         if (dip->flags & HAMMER_INODE_RO)
1459                 return (EROFS);
1460         if ((error = hammer_checkspace(hmp, HAMMER_CHKSPC_CREATE)) != 0)
1461                 return (error);
1462
1463         /*
1464          * Create a transaction to cover the operations we perform.
1465          */
1466         lwkt_gettoken(&hmp->fs_token);
1467         hammer_start_transaction(&trans, hmp);
1468         ++hammer_stats_file_iopsw;
1469
1470         /*
1471          * Create a new filesystem object of the requested type.  The
1472          * returned inode will be referenced but not locked.
1473          */
1474         error = hammer_create_inode(&trans, ap->a_vap, ap->a_cred,
1475                                     dip, nch->ncp->nc_name, nch->ncp->nc_nlen,
1476                                     NULL, &nip);
1477         if (error) {
1478                 hkprintf("hammer_mkdir error %d\n", error);
1479                 hammer_done_transaction(&trans);
1480                 *ap->a_vpp = NULL;
1481                 lwkt_reltoken(&hmp->fs_token);
1482                 return (error);
1483         }
1484         /*
1485          * Add the new filesystem object to the directory.  This will also
1486          * bump the inode's link count.
1487          */
1488         error = hammer_ip_add_directory(&trans, dip,
1489                                         nch->ncp->nc_name, nch->ncp->nc_nlen,
1490                                         nip);
1491         if (error)
1492                 hkprintf("hammer_mkdir (add) error %d\n", error);
1493
1494         /*
1495          * Finish up.
1496          */
1497         if (error) {
1498                 hammer_rel_inode(nip, 0);
1499                 *ap->a_vpp = NULL;
1500         } else {
1501                 error = hammer_get_vnode(nip, ap->a_vpp);
1502                 hammer_rel_inode(nip, 0);
1503                 if (error == 0) {
1504                         cache_setunresolved(ap->a_nch);
1505                         cache_setvp(ap->a_nch, *ap->a_vpp);
1506                 }
1507         }
1508         hammer_done_transaction(&trans);
1509         if (error == 0)
1510                 hammer_knote(ap->a_dvp, NOTE_WRITE | NOTE_LINK);
1511         lwkt_reltoken(&hmp->fs_token);
1512         return (error);
1513 }
1514
1515 /*
1516  * hammer_vop_nmknod { nch, dvp, vpp, cred, vap }
1517  *
1518  * The operating system has already ensured that the directory entry
1519  * does not exist and done all appropriate namespace locking.
1520  */
1521 static
1522 int
1523 hammer_vop_nmknod(struct vop_nmknod_args *ap)
1524 {
1525         struct hammer_transaction trans;
1526         struct hammer_inode *dip;
1527         struct hammer_inode *nip;
1528         struct nchandle *nch;
1529         hammer_mount_t hmp;
1530         int error;
1531
1532         nch = ap->a_nch;
1533         dip = VTOI(ap->a_dvp);
1534         hmp = dip->hmp;
1535
1536         if (dip->flags & HAMMER_INODE_RO)
1537                 return (EROFS);
1538         if ((error = hammer_checkspace(hmp, HAMMER_CHKSPC_CREATE)) != 0)
1539                 return (error);
1540
1541         /*
1542          * Create a transaction to cover the operations we perform.
1543          */
1544         lwkt_gettoken(&hmp->fs_token);
1545         hammer_start_transaction(&trans, hmp);
1546         ++hammer_stats_file_iopsw;
1547
1548         /*
1549          * Create a new filesystem object of the requested type.  The
1550          * returned inode will be referenced but not locked.
1551          *
1552          * If mknod specifies a directory a pseudo-fs is created.
1553          */
1554         error = hammer_create_inode(&trans, ap->a_vap, ap->a_cred,
1555                                     dip, nch->ncp->nc_name, nch->ncp->nc_nlen,
1556                                     NULL, &nip);
1557         if (error) {
1558                 hammer_done_transaction(&trans);
1559                 *ap->a_vpp = NULL;
1560                 lwkt_reltoken(&hmp->fs_token);
1561                 return (error);
1562         }
1563
1564         /*
1565          * Add the new filesystem object to the directory.  This will also
1566          * bump the inode's link count.
1567          */
1568         error = hammer_ip_add_directory(&trans, dip,
1569                                         nch->ncp->nc_name, nch->ncp->nc_nlen,
1570                                         nip);
1571
1572         /*
1573          * Finish up.
1574          */
1575         if (error) {
1576                 hammer_rel_inode(nip, 0);
1577                 *ap->a_vpp = NULL;
1578         } else {
1579                 error = hammer_get_vnode(nip, ap->a_vpp);
1580                 hammer_rel_inode(nip, 0);
1581                 if (error == 0) {
1582                         cache_setunresolved(ap->a_nch);
1583                         cache_setvp(ap->a_nch, *ap->a_vpp);
1584                 }
1585         }
1586         hammer_done_transaction(&trans);
1587         if (error == 0)
1588                 hammer_knote(ap->a_dvp, NOTE_WRITE);
1589         lwkt_reltoken(&hmp->fs_token);
1590         return (error);
1591 }
1592
1593 /*
1594  * hammer_vop_open { vp, mode, cred, fp }
1595  *
1596  * MPSAFE (does not require fs_token)
1597  */
1598 static
1599 int
1600 hammer_vop_open(struct vop_open_args *ap)
1601 {
1602         hammer_inode_t ip;
1603
1604         ++hammer_stats_file_iopsr;
1605         ip = VTOI(ap->a_vp);
1606
1607         if ((ap->a_mode & FWRITE) && (ip->flags & HAMMER_INODE_RO))
1608                 return (EROFS);
1609         return(vop_stdopen(ap));
1610 }
1611
1612 /*
1613  * hammer_vop_print { vp }
1614  */
1615 static
1616 int
1617 hammer_vop_print(struct vop_print_args *ap)
1618 {
1619         return EOPNOTSUPP;
1620 }
1621
1622 /*
1623  * hammer_vop_readdir { vp, uio, cred, *eofflag, *ncookies, off_t **cookies }
1624  */
1625 static
1626 int
1627 hammer_vop_readdir(struct vop_readdir_args *ap)
1628 {
1629         struct hammer_transaction trans;
1630         struct hammer_cursor cursor;
1631         struct hammer_inode *ip;
1632         hammer_mount_t hmp;
1633         struct uio *uio;
1634         hammer_base_elm_t base;
1635         int error;
1636         int cookie_index;
1637         int ncookies;
1638         off_t *cookies;
1639         off_t saveoff;
1640         int r;
1641         int dtype;
1642
1643         ++hammer_stats_file_iopsr;
1644         ip = VTOI(ap->a_vp);
1645         uio = ap->a_uio;
1646         saveoff = uio->uio_offset;
1647         hmp = ip->hmp;
1648
1649         if (ap->a_ncookies) {
1650                 ncookies = uio->uio_resid / 16 + 1;
1651                 if (ncookies > 1024)
1652                         ncookies = 1024;
1653                 cookies = kmalloc(ncookies * sizeof(off_t), M_TEMP, M_WAITOK);
1654                 cookie_index = 0;
1655         } else {
1656                 ncookies = -1;
1657                 cookies = NULL;
1658                 cookie_index = 0;
1659         }
1660
1661         lwkt_gettoken(&hmp->fs_token);
1662         hammer_simple_transaction(&trans, hmp);
1663
1664         /*
1665          * Handle artificial entries
1666          *
1667          * It should be noted that the minimum value for a directory
1668          * hash key on-media is 0x0000000100000000, so we can use anything
1669          * less then that to represent our 'special' key space.
1670          */
1671         error = 0;
1672         if (saveoff == 0) {
1673                 r = vop_write_dirent(&error, uio, ip->obj_id, DT_DIR, 1, ".");
1674                 if (r)
1675                         goto done;
1676                 if (cookies)
1677                         cookies[cookie_index] = saveoff;
1678                 ++saveoff;
1679                 ++cookie_index;
1680                 if (cookie_index == ncookies)
1681                         goto done;
1682         }
1683         if (saveoff == 1) {
1684                 if (ip->ino_data.parent_obj_id) {
1685                         r = vop_write_dirent(&error, uio,
1686                                              ip->ino_data.parent_obj_id,
1687                                              DT_DIR, 2, "..");
1688                 } else {
1689                         r = vop_write_dirent(&error, uio,
1690                                              ip->obj_id, DT_DIR, 2, "..");
1691                 }
1692                 if (r)
1693                         goto done;
1694                 if (cookies)
1695                         cookies[cookie_index] = saveoff;
1696                 ++saveoff;
1697                 ++cookie_index;
1698                 if (cookie_index == ncookies)
1699                         goto done;
1700         }
1701
1702         /*
1703          * Key range (begin and end inclusive) to scan.  Directory keys
1704          * directly translate to a 64 bit 'seek' position.
1705          */
1706         hammer_init_cursor(&trans, &cursor, &ip->cache[1], ip);
1707         cursor.key_beg.localization = ip->obj_localization +
1708                                       hammer_dir_localization(ip);
1709         cursor.key_beg.obj_id = ip->obj_id;
1710         cursor.key_beg.create_tid = 0;
1711         cursor.key_beg.delete_tid = 0;
1712         cursor.key_beg.rec_type = HAMMER_RECTYPE_DIRENTRY;
1713         cursor.key_beg.obj_type = 0;
1714         cursor.key_beg.key = saveoff;
1715
1716         cursor.key_end = cursor.key_beg;
1717         cursor.key_end.key = HAMMER_MAX_KEY;
1718         cursor.asof = ip->obj_asof;
1719         cursor.flags |= HAMMER_CURSOR_END_INCLUSIVE | HAMMER_CURSOR_ASOF;
1720
1721         error = hammer_ip_first(&cursor);
1722
1723         while (error == 0) {
1724                 error = hammer_ip_resolve_data(&cursor);
1725                 if (error)
1726                         break;
1727                 base = &cursor.leaf->base;
1728                 saveoff = base->key;
1729                 KKASSERT(cursor.leaf->data_len > HAMMER_ENTRY_NAME_OFF);
1730
1731                 if (base->obj_id != ip->obj_id)
1732                         panic("readdir: bad record at %p", cursor.node);
1733
1734                 /*
1735                  * Convert pseudo-filesystems into softlinks
1736                  */
1737                 dtype = hammer_get_dtype(cursor.leaf->base.obj_type);
1738                 r = vop_write_dirent(
1739                              &error, uio, cursor.data->entry.obj_id,
1740                              dtype,
1741                              cursor.leaf->data_len - HAMMER_ENTRY_NAME_OFF ,
1742                              (void *)cursor.data->entry.name);
1743                 if (r)
1744                         break;
1745                 ++saveoff;
1746                 if (cookies)
1747                         cookies[cookie_index] = base->key;
1748                 ++cookie_index;
1749                 if (cookie_index == ncookies)
1750                         break;
1751                 error = hammer_ip_next(&cursor);
1752         }
1753         hammer_done_cursor(&cursor);
1754
1755 done:
1756         hammer_done_transaction(&trans);
1757
1758         if (ap->a_eofflag)
1759                 *ap->a_eofflag = (error == ENOENT);
1760         uio->uio_offset = saveoff;
1761         if (error && cookie_index == 0) {
1762                 if (error == ENOENT)
1763                         error = 0;
1764                 if (cookies) {
1765                         kfree(cookies, M_TEMP);
1766                         *ap->a_ncookies = 0;
1767                         *ap->a_cookies = NULL;
1768                 }
1769         } else {
1770                 if (error == ENOENT)
1771                         error = 0;
1772                 if (cookies) {
1773                         *ap->a_ncookies = cookie_index;
1774                         *ap->a_cookies = cookies;
1775                 }
1776         }
1777         lwkt_reltoken(&hmp->fs_token);
1778         return(error);
1779 }
1780
1781 /*
1782  * hammer_vop_readlink { vp, uio, cred }
1783  */
1784 static
1785 int
1786 hammer_vop_readlink(struct vop_readlink_args *ap)
1787 {
1788         struct hammer_transaction trans;
1789         struct hammer_cursor cursor;
1790         struct hammer_inode *ip;
1791         hammer_mount_t hmp;
1792         char buf[32];
1793         u_int32_t localization;
1794         hammer_pseudofs_inmem_t pfsm;
1795         int error;
1796
1797         ip = VTOI(ap->a_vp);
1798         hmp = ip->hmp;
1799
1800         lwkt_gettoken(&hmp->fs_token);
1801
1802         /*
1803          * Shortcut if the symlink data was stuffed into ino_data.
1804          *
1805          * Also expand special "@@PFS%05d" softlinks (expansion only
1806          * occurs for non-historical (current) accesses made from the
1807          * primary filesystem).
1808          *
1809          * Note that userspace hammer command does not allow users to
1810          * create a @@PFS softlink under an existing other PFS (id!=0)
1811          * so the ip localization here for @@PFS softlink is always 0.
1812          */
1813         if (ip->ino_data.size <= HAMMER_INODE_BASESYMLEN) {
1814                 char *ptr;
1815                 int bytes;
1816
1817                 ptr = ip->ino_data.ext.symlink;
1818                 bytes = (int)ip->ino_data.size;
1819                 if (bytes == 10 &&
1820                     ip->obj_asof == HAMMER_MAX_TID &&
1821                     ip->obj_localization == 0 &&
1822                     strncmp(ptr, "@@PFS", 5) == 0) {
1823                         hammer_simple_transaction(&trans, hmp);
1824                         bcopy(ptr + 5, buf, 5);
1825                         buf[5] = 0;
1826                         localization = strtoul(buf, NULL, 10) << 16;
1827                         pfsm = hammer_load_pseudofs(&trans, localization,
1828                                                     &error);
1829                         if (error == 0) {
1830                                 if (pfsm->pfsd.mirror_flags &
1831                                     HAMMER_PFSD_SLAVE) {
1832                                         /* vap->va_size == 26 */
1833                                         ksnprintf(buf, sizeof(buf),
1834                                                   "@@0x%016llx:%05d",
1835                                                   (long long)pfsm->pfsd.sync_end_tid,
1836                                                   localization >> 16);
1837                                 } else {
1838                                         /* vap->va_size == 10 */
1839                                         ksnprintf(buf, sizeof(buf),
1840                                                   "@@-1:%05d",
1841                                                   localization >> 16);
1842 #if 0
1843                                         ksnprintf(buf, sizeof(buf),
1844                                                   "@@0x%016llx:%05d",
1845                                                   (long long)HAMMER_MAX_TID,
1846                                                   localization >> 16);
1847 #endif
1848                                 }
1849                                 ptr = buf;
1850                                 bytes = strlen(buf);
1851                         }
1852                         if (pfsm)
1853                                 hammer_rel_pseudofs(hmp, pfsm);
1854                         hammer_done_transaction(&trans);
1855                 }
1856                 error = uiomove(ptr, bytes, ap->a_uio);
1857                 lwkt_reltoken(&hmp->fs_token);
1858                 return(error);
1859         }
1860
1861         /*
1862          * Long version
1863          */
1864         hammer_simple_transaction(&trans, hmp);
1865         ++hammer_stats_file_iopsr;
1866         hammer_init_cursor(&trans, &cursor, &ip->cache[1], ip);
1867
1868         /*
1869          * Key range (begin and end inclusive) to scan.  Directory keys
1870          * directly translate to a 64 bit 'seek' position.
1871          */
1872         cursor.key_beg.localization = ip->obj_localization +
1873                                       HAMMER_LOCALIZE_MISC;
1874         cursor.key_beg.obj_id = ip->obj_id;
1875         cursor.key_beg.create_tid = 0;
1876         cursor.key_beg.delete_tid = 0;
1877         cursor.key_beg.rec_type = HAMMER_RECTYPE_FIX;
1878         cursor.key_beg.obj_type = 0;
1879         cursor.key_beg.key = HAMMER_FIXKEY_SYMLINK;
1880         cursor.asof = ip->obj_asof;
1881         cursor.flags |= HAMMER_CURSOR_ASOF;
1882
1883         error = hammer_ip_lookup(&cursor);
1884         if (error == 0) {
1885                 error = hammer_ip_resolve_data(&cursor);
1886                 if (error == 0) {
1887                         KKASSERT(cursor.leaf->data_len >=
1888                                  HAMMER_SYMLINK_NAME_OFF);
1889                         error = uiomove(cursor.data->symlink.name,
1890                                         cursor.leaf->data_len -
1891                                                 HAMMER_SYMLINK_NAME_OFF,
1892                                         ap->a_uio);
1893                 }
1894         }
1895         hammer_done_cursor(&cursor);
1896         hammer_done_transaction(&trans);
1897         lwkt_reltoken(&hmp->fs_token);
1898         return(error);
1899 }
1900
1901 /*
1902  * hammer_vop_nremove { nch, dvp, cred }
1903  */
1904 static
1905 int
1906 hammer_vop_nremove(struct vop_nremove_args *ap)
1907 {
1908         struct hammer_transaction trans;
1909         struct hammer_inode *dip;
1910         hammer_mount_t hmp;
1911         int error;
1912
1913         dip = VTOI(ap->a_dvp);
1914         hmp = dip->hmp;
1915
1916         if (hammer_nohistory(dip) == 0 &&
1917             (error = hammer_checkspace(hmp, HAMMER_CHKSPC_REMOVE)) != 0) {
1918                 return (error);
1919         }
1920
1921         lwkt_gettoken(&hmp->fs_token);
1922         hammer_start_transaction(&trans, hmp);
1923         ++hammer_stats_file_iopsw;
1924         error = hammer_dounlink(&trans, ap->a_nch, ap->a_dvp, ap->a_cred, 0, 0);
1925         hammer_done_transaction(&trans);
1926         if (error == 0)
1927                 hammer_knote(ap->a_dvp, NOTE_WRITE);
1928         lwkt_reltoken(&hmp->fs_token);
1929         return (error);
1930 }
1931
1932 /*
1933  * hammer_vop_nrename { fnch, tnch, fdvp, tdvp, cred }
1934  */
1935 static
1936 int
1937 hammer_vop_nrename(struct vop_nrename_args *ap)
1938 {
1939         struct hammer_transaction trans;
1940         struct namecache *fncp;
1941         struct namecache *tncp;
1942         struct hammer_inode *fdip;
1943         struct hammer_inode *tdip;
1944         struct hammer_inode *ip;
1945         hammer_mount_t hmp;
1946         struct hammer_cursor cursor;
1947         int64_t namekey;
1948         u_int32_t max_iterations;
1949         int nlen, error;
1950
1951         if (ap->a_fdvp->v_mount != ap->a_tdvp->v_mount)
1952                 return(EXDEV);
1953         if (ap->a_fdvp->v_mount != ap->a_fnch->ncp->nc_vp->v_mount)
1954                 return(EXDEV);
1955
1956         fdip = VTOI(ap->a_fdvp);
1957         tdip = VTOI(ap->a_tdvp);
1958         fncp = ap->a_fnch->ncp;
1959         tncp = ap->a_tnch->ncp;
1960         ip = VTOI(fncp->nc_vp);
1961         KKASSERT(ip != NULL);
1962
1963         hmp = ip->hmp;
1964
1965         if (fdip->obj_localization != tdip->obj_localization)
1966                 return(EXDEV);
1967         if (fdip->obj_localization != ip->obj_localization)
1968                 return(EXDEV);
1969
1970         if (fdip->flags & HAMMER_INODE_RO)
1971                 return (EROFS);
1972         if (tdip->flags & HAMMER_INODE_RO)
1973                 return (EROFS);
1974         if (ip->flags & HAMMER_INODE_RO)
1975                 return (EROFS);
1976         if ((error = hammer_checkspace(hmp, HAMMER_CHKSPC_CREATE)) != 0)
1977                 return (error);
1978
1979         lwkt_gettoken(&hmp->fs_token);
1980         hammer_start_transaction(&trans, hmp);
1981         ++hammer_stats_file_iopsw;
1982
1983         /*
1984          * Remove tncp from the target directory and then link ip as
1985          * tncp. XXX pass trans to dounlink
1986          *
1987          * Force the inode sync-time to match the transaction so it is
1988          * in-sync with the creation of the target directory entry.
1989          */
1990         error = hammer_dounlink(&trans, ap->a_tnch, ap->a_tdvp,
1991                                 ap->a_cred, 0, -1);
1992         if (error == 0 || error == ENOENT) {
1993                 error = hammer_ip_add_directory(&trans, tdip,
1994                                                 tncp->nc_name, tncp->nc_nlen,
1995                                                 ip);
1996                 if (error == 0) {
1997                         ip->ino_data.parent_obj_id = tdip->obj_id;
1998                         ip->ino_data.ctime = trans.time;
1999                         hammer_modify_inode(&trans, ip, HAMMER_INODE_DDIRTY);
2000                 }
2001         }
2002         if (error)
2003                 goto failed; /* XXX */
2004
2005         /*
2006          * Locate the record in the originating directory and remove it.
2007          *
2008          * Calculate the namekey and setup the key range for the scan.  This
2009          * works kinda like a chained hash table where the lower 32 bits
2010          * of the namekey synthesize the chain.
2011          *
2012          * The key range is inclusive of both key_beg and key_end.
2013          */
2014         namekey = hammer_directory_namekey(fdip, fncp->nc_name, fncp->nc_nlen,
2015                                            &max_iterations);
2016 retry:
2017         hammer_init_cursor(&trans, &cursor, &fdip->cache[1], fdip);
2018         cursor.key_beg.localization = fdip->obj_localization +
2019                                       hammer_dir_localization(fdip);
2020         cursor.key_beg.obj_id = fdip->obj_id;
2021         cursor.key_beg.key = namekey;
2022         cursor.key_beg.create_tid = 0;
2023         cursor.key_beg.delete_tid = 0;
2024         cursor.key_beg.rec_type = HAMMER_RECTYPE_DIRENTRY;
2025         cursor.key_beg.obj_type = 0;
2026
2027         cursor.key_end = cursor.key_beg;
2028         cursor.key_end.key += max_iterations;
2029         cursor.asof = fdip->obj_asof;
2030         cursor.flags |= HAMMER_CURSOR_END_INCLUSIVE | HAMMER_CURSOR_ASOF;
2031
2032         /*
2033          * Scan all matching records (the chain), locate the one matching
2034          * the requested path component.
2035          *
2036          * The hammer_ip_*() functions merge in-memory records with on-disk
2037          * records for the purposes of the search.
2038          */
2039         error = hammer_ip_first(&cursor);
2040         while (error == 0) {
2041                 if (hammer_ip_resolve_data(&cursor) != 0)
2042                         break;
2043                 nlen = cursor.leaf->data_len - HAMMER_ENTRY_NAME_OFF;
2044                 KKASSERT(nlen > 0);
2045                 if (fncp->nc_nlen == nlen &&
2046                     bcmp(fncp->nc_name, cursor.data->entry.name, nlen) == 0) {
2047                         break;
2048                 }
2049                 error = hammer_ip_next(&cursor);
2050         }
2051
2052         /*
2053          * If all is ok we have to get the inode so we can adjust nlinks.
2054          *
2055          * WARNING: hammer_ip_del_directory() may have to terminate the
2056          * cursor to avoid a recursion.  It's ok to call hammer_done_cursor()
2057          * twice.
2058          */
2059         if (error == 0)
2060                 error = hammer_ip_del_directory(&trans, &cursor, fdip, ip);
2061
2062         /*
2063          * XXX A deadlock here will break rename's atomicy for the purposes
2064          * of crash recovery.
2065          */
2066         if (error == EDEADLK) {
2067                 hammer_done_cursor(&cursor);
2068                 goto retry;
2069         }
2070
2071         /*
2072          * Cleanup and tell the kernel that the rename succeeded.
2073          *
2074          * NOTE: ip->vp, if non-NULL, cannot be directly referenced
2075          *       without formally acquiring the vp since the vp might
2076          *       have zero refs on it, or in the middle of a reclaim,
2077          *       etc.
2078          */
2079         hammer_done_cursor(&cursor);
2080         if (error == 0) {
2081                 cache_rename(ap->a_fnch, ap->a_tnch);
2082                 hammer_knote(ap->a_fdvp, NOTE_WRITE);
2083                 hammer_knote(ap->a_tdvp, NOTE_WRITE);
2084                 while (ip->vp) {
2085                         struct vnode *vp;
2086
2087                         error = hammer_get_vnode(ip, &vp);
2088                         if (error == 0 && vp) {
2089                                 vn_unlock(vp);
2090                                 hammer_knote(ip->vp, NOTE_RENAME);
2091                                 vrele(vp);
2092                                 break;
2093                         }
2094                         kprintf("Debug: HAMMER ip/vp race2 avoided\n");
2095                 }
2096         }
2097
2098 failed:
2099         hammer_done_transaction(&trans);
2100         lwkt_reltoken(&hmp->fs_token);
2101         return (error);
2102 }
2103
2104 /*
2105  * hammer_vop_nrmdir { nch, dvp, cred }
2106  */
2107 static
2108 int
2109 hammer_vop_nrmdir(struct vop_nrmdir_args *ap)
2110 {
2111         struct hammer_transaction trans;
2112         struct hammer_inode *dip;
2113         hammer_mount_t hmp;
2114         int error;
2115
2116         dip = VTOI(ap->a_dvp);
2117         hmp = dip->hmp;
2118
2119         if (hammer_nohistory(dip) == 0 &&
2120             (error = hammer_checkspace(hmp, HAMMER_CHKSPC_REMOVE)) != 0) {
2121                 return (error);
2122         }
2123
2124         lwkt_gettoken(&hmp->fs_token);
2125         hammer_start_transaction(&trans, hmp);
2126         ++hammer_stats_file_iopsw;
2127         error = hammer_dounlink(&trans, ap->a_nch, ap->a_dvp, ap->a_cred, 0, 1);
2128         hammer_done_transaction(&trans);
2129         if (error == 0)
2130                 hammer_knote(ap->a_dvp, NOTE_WRITE | NOTE_LINK);
2131         lwkt_reltoken(&hmp->fs_token);
2132         return (error);
2133 }
2134
2135 /*
2136  * hammer_vop_markatime { vp, cred }
2137  */
2138 static
2139 int
2140 hammer_vop_markatime(struct vop_markatime_args *ap)
2141 {
2142         struct hammer_transaction trans;
2143         struct hammer_inode *ip;
2144         hammer_mount_t hmp;
2145
2146         ip = VTOI(ap->a_vp);
2147         if (ap->a_vp->v_mount->mnt_flag & MNT_RDONLY)
2148                 return (EROFS);
2149         if (ip->flags & HAMMER_INODE_RO)
2150                 return (EROFS);
2151         hmp = ip->hmp;
2152         if (hmp->mp->mnt_flag & MNT_NOATIME)
2153                 return (0);
2154         lwkt_gettoken(&hmp->fs_token);
2155         hammer_start_transaction(&trans, hmp);
2156         ++hammer_stats_file_iopsw;
2157
2158         ip->ino_data.atime = trans.time;
2159         hammer_modify_inode(&trans, ip, HAMMER_INODE_ATIME);
2160         hammer_done_transaction(&trans);
2161         hammer_knote(ap->a_vp, NOTE_ATTRIB);
2162         lwkt_reltoken(&hmp->fs_token);
2163         return (0);
2164 }
2165
2166 /*
2167  * hammer_vop_setattr { vp, vap, cred }
2168  */
2169 static
2170 int
2171 hammer_vop_setattr(struct vop_setattr_args *ap)
2172 {
2173         struct hammer_transaction trans;
2174         struct hammer_inode *ip;
2175         struct vattr *vap;
2176         hammer_mount_t hmp;
2177         int modflags;
2178         int error;
2179         int truncating;
2180         int blksize;
2181         int kflags;
2182 #if 0
2183         int64_t aligned_size;
2184 #endif
2185         u_int32_t flags;
2186
2187         vap = ap->a_vap;
2188         ip = ap->a_vp->v_data;
2189         modflags = 0;
2190         kflags = 0;
2191         hmp = ip->hmp;
2192
2193         if (ap->a_vp->v_mount->mnt_flag & MNT_RDONLY)
2194                 return(EROFS);
2195         if (ip->flags & HAMMER_INODE_RO)
2196                 return (EROFS);
2197         if (hammer_nohistory(ip) == 0 &&
2198             (error = hammer_checkspace(hmp, HAMMER_CHKSPC_REMOVE)) != 0) {
2199                 return (error);
2200         }
2201
2202         lwkt_gettoken(&hmp->fs_token);
2203         hammer_start_transaction(&trans, hmp);
2204         ++hammer_stats_file_iopsw;
2205         error = 0;
2206
2207         if (vap->va_flags != VNOVAL) {
2208                 flags = ip->ino_data.uflags;
2209                 error = vop_helper_setattr_flags(&flags, vap->va_flags,
2210                                          hammer_to_unix_xid(&ip->ino_data.uid),
2211                                          ap->a_cred);
2212                 if (error == 0) {
2213                         if (ip->ino_data.uflags != flags) {
2214                                 ip->ino_data.uflags = flags;
2215                                 ip->ino_data.ctime = trans.time;
2216                                 modflags |= HAMMER_INODE_DDIRTY;
2217                                 kflags |= NOTE_ATTRIB;
2218                         }
2219                         if (ip->ino_data.uflags & (IMMUTABLE | APPEND)) {
2220                                 error = 0;
2221                                 goto done;
2222                         }
2223                 }
2224                 goto done;
2225         }
2226         if (ip->ino_data.uflags & (IMMUTABLE | APPEND)) {
2227                 error = EPERM;
2228                 goto done;
2229         }
2230         if (vap->va_uid != (uid_t)VNOVAL || vap->va_gid != (gid_t)VNOVAL) {
2231                 mode_t cur_mode = ip->ino_data.mode;
2232                 uid_t cur_uid = hammer_to_unix_xid(&ip->ino_data.uid);
2233                 gid_t cur_gid = hammer_to_unix_xid(&ip->ino_data.gid);
2234                 uuid_t uuid_uid;
2235                 uuid_t uuid_gid;
2236
2237                 error = vop_helper_chown(ap->a_vp, vap->va_uid, vap->va_gid,
2238                                          ap->a_cred,
2239                                          &cur_uid, &cur_gid, &cur_mode);
2240                 if (error == 0) {
2241                         hammer_guid_to_uuid(&uuid_uid, cur_uid);
2242                         hammer_guid_to_uuid(&uuid_gid, cur_gid);
2243                         if (bcmp(&uuid_uid, &ip->ino_data.uid,
2244                                  sizeof(uuid_uid)) ||
2245                             bcmp(&uuid_gid, &ip->ino_data.gid,
2246                                  sizeof(uuid_gid)) ||
2247                             ip->ino_data.mode != cur_mode) {
2248                                 ip->ino_data.uid = uuid_uid;
2249                                 ip->ino_data.gid = uuid_gid;
2250                                 ip->ino_data.mode = cur_mode;
2251                                 ip->ino_data.ctime = trans.time;
2252                                 modflags |= HAMMER_INODE_DDIRTY;
2253                         }
2254                         kflags |= NOTE_ATTRIB;
2255                 }
2256         }
2257         while (vap->va_size != VNOVAL && ip->ino_data.size != vap->va_size) {
2258                 switch(ap->a_vp->v_type) {
2259                 case VREG:
2260                         if (vap->va_size == ip->ino_data.size)
2261                                 break;
2262
2263                         /*
2264                          * Log the operation if in fast-fsync mode or if
2265                          * there are unterminated redo write records present.
2266                          *
2267                          * The second check is needed so the recovery code
2268                          * properly truncates write redos even if nominal
2269                          * REDO operations is turned off due to excessive
2270                          * writes, because the related records might be
2271                          * destroyed and never lay down a TERM_WRITE.
2272                          */
2273                         if ((ip->flags & HAMMER_INODE_REDO) ||
2274                             (ip->flags & HAMMER_INODE_RDIRTY)) {
2275                                 error = hammer_generate_redo(&trans, ip,
2276                                                              vap->va_size,
2277                                                              HAMMER_REDO_TRUNC,
2278                                                              NULL, 0);
2279                         }
2280                         blksize = hammer_blocksize(vap->va_size);
2281
2282                         /*
2283                          * XXX break atomicy, we can deadlock the backend
2284                          * if we do not release the lock.  Probably not a
2285                          * big deal here.
2286                          */
2287                         if (vap->va_size < ip->ino_data.size) {
2288                                 nvtruncbuf(ap->a_vp, vap->va_size,
2289                                            blksize,
2290                                            hammer_blockoff(vap->va_size),
2291                                            0);
2292                                 truncating = 1;
2293                                 kflags |= NOTE_WRITE;
2294                         } else {
2295                                 nvextendbuf(ap->a_vp,
2296                                             ip->ino_data.size,
2297                                             vap->va_size,
2298                                             hammer_blocksize(ip->ino_data.size),
2299                                             hammer_blocksize(vap->va_size),
2300                                             hammer_blockoff(ip->ino_data.size),
2301                                             hammer_blockoff(vap->va_size),
2302                                             0);
2303                                 truncating = 0;
2304                                 kflags |= NOTE_WRITE | NOTE_EXTEND;
2305                         }
2306                         ip->ino_data.size = vap->va_size;
2307                         ip->ino_data.mtime = trans.time;
2308                         /* XXX safe to use SDIRTY instead of DDIRTY here? */
2309                         modflags |= HAMMER_INODE_MTIME | HAMMER_INODE_DDIRTY;
2310
2311                         /*
2312                          * On-media truncation is cached in the inode until
2313                          * the inode is synchronized.  We must immediately
2314                          * handle any frontend records.
2315                          */
2316                         if (truncating) {
2317                                 hammer_ip_frontend_trunc(ip, vap->va_size);
2318 #ifdef DEBUG_TRUNCATE
2319                                 if (HammerTruncIp == NULL)
2320                                         HammerTruncIp = ip;
2321 #endif
2322                                 if ((ip->flags & HAMMER_INODE_TRUNCATED) == 0) {
2323                                         ip->flags |= HAMMER_INODE_TRUNCATED;
2324                                         ip->trunc_off = vap->va_size;
2325                                         hammer_inode_dirty(ip);
2326 #ifdef DEBUG_TRUNCATE
2327                                         if (ip == HammerTruncIp)
2328                                         kprintf("truncate1 %016llx\n",
2329                                                 (long long)ip->trunc_off);
2330 #endif
2331                                 } else if (ip->trunc_off > vap->va_size) {
2332                                         ip->trunc_off = vap->va_size;
2333 #ifdef DEBUG_TRUNCATE
2334                                         if (ip == HammerTruncIp)
2335                                         kprintf("truncate2 %016llx\n",
2336                                                 (long long)ip->trunc_off);
2337 #endif
2338                                 } else {
2339 #ifdef DEBUG_TRUNCATE
2340                                         if (ip == HammerTruncIp)
2341                                         kprintf("truncate3 %016llx (ignored)\n",
2342                                                 (long long)vap->va_size);
2343 #endif
2344                                 }
2345                         }
2346
2347 #if 0
2348                         /*
2349                          * When truncating, nvtruncbuf() may have cleaned out
2350                          * a portion of the last block on-disk in the buffer
2351                          * cache.  We must clean out any frontend records
2352                          * for blocks beyond the new last block.
2353                          */
2354                         aligned_size = (vap->va_size + (blksize - 1)) &
2355                                        ~(int64_t)(blksize - 1);
2356                         if (truncating && vap->va_size < aligned_size) {
2357                                 aligned_size -= blksize;
2358                                 hammer_ip_frontend_trunc(ip, aligned_size);
2359                         }
2360 #endif
2361                         break;
2362                 case VDATABASE:
2363                         if ((ip->flags & HAMMER_INODE_TRUNCATED) == 0) {
2364                                 ip->flags |= HAMMER_INODE_TRUNCATED;
2365                                 ip->trunc_off = vap->va_size;
2366                                 hammer_inode_dirty(ip);
2367                         } else if (ip->trunc_off > vap->va_size) {
2368                                 ip->trunc_off = vap->va_size;
2369                         }
2370                         hammer_ip_frontend_trunc(ip, vap->va_size);
2371                         ip->ino_data.size = vap->va_size;
2372                         ip->ino_data.mtime = trans.time;
2373                         modflags |= HAMMER_INODE_MTIME | HAMMER_INODE_DDIRTY;
2374                         kflags |= NOTE_ATTRIB;
2375                         break;
2376                 default:
2377                         error = EINVAL;
2378                         goto done;
2379                 }
2380                 break;
2381         }
2382         if (vap->va_atime.tv_sec != VNOVAL) {
2383                 ip->ino_data.atime = hammer_timespec_to_time(&vap->va_atime);
2384                 modflags |= HAMMER_INODE_ATIME;
2385                 kflags |= NOTE_ATTRIB;
2386         }
2387         if (vap->va_mtime.tv_sec != VNOVAL) {
2388                 ip->ino_data.mtime = hammer_timespec_to_time(&vap->va_mtime);
2389                 modflags |= HAMMER_INODE_MTIME;
2390                 kflags |= NOTE_ATTRIB;
2391         }
2392         if (vap->va_mode != (mode_t)VNOVAL) {
2393                 mode_t   cur_mode = ip->ino_data.mode;
2394                 uid_t cur_uid = hammer_to_unix_xid(&ip->ino_data.uid);
2395                 gid_t cur_gid = hammer_to_unix_xid(&ip->ino_data.gid);
2396
2397                 error = vop_helper_chmod(ap->a_vp, vap->va_mode, ap->a_cred,
2398                                          cur_uid, cur_gid, &cur_mode);
2399                 if (error == 0 && ip->ino_data.mode != cur_mode) {
2400                         ip->ino_data.mode = cur_mode;
2401                         ip->ino_data.ctime = trans.time;
2402                         modflags |= HAMMER_INODE_DDIRTY;
2403                         kflags |= NOTE_ATTRIB;
2404                 }
2405         }
2406 done:
2407         if (error == 0)
2408                 hammer_modify_inode(&trans, ip, modflags);
2409         hammer_done_transaction(&trans);
2410         hammer_knote(ap->a_vp, kflags);
2411         lwkt_reltoken(&hmp->fs_token);
2412         return (error);
2413 }
2414
2415 /*
2416  * hammer_vop_nsymlink { nch, dvp, vpp, cred, vap, target }
2417  */
2418 static
2419 int
2420 hammer_vop_nsymlink(struct vop_nsymlink_args *ap)
2421 {
2422         struct hammer_transaction trans;
2423         struct hammer_inode *dip;
2424         struct hammer_inode *nip;
2425         hammer_record_t record;
2426         struct nchandle *nch;
2427         hammer_mount_t hmp;
2428         int error;
2429         int bytes;
2430
2431         ap->a_vap->va_type = VLNK;
2432
2433         nch = ap->a_nch;
2434         dip = VTOI(ap->a_dvp);
2435         hmp = dip->hmp;
2436
2437         if (dip->flags & HAMMER_INODE_RO)
2438                 return (EROFS);
2439         if ((error = hammer_checkspace(hmp, HAMMER_CHKSPC_CREATE)) != 0)
2440                 return (error);
2441
2442         /*
2443          * Create a transaction to cover the operations we perform.
2444          */
2445         lwkt_gettoken(&hmp->fs_token);
2446         hammer_start_transaction(&trans, hmp);
2447         ++hammer_stats_file_iopsw;
2448
2449         /*
2450          * Create a new filesystem object of the requested type.  The
2451          * returned inode will be referenced but not locked.
2452          */
2453
2454         error = hammer_create_inode(&trans, ap->a_vap, ap->a_cred,
2455                                     dip, nch->ncp->nc_name, nch->ncp->nc_nlen,
2456                                     NULL, &nip);
2457         if (error) {
2458                 hammer_done_transaction(&trans);
2459                 *ap->a_vpp = NULL;
2460                 lwkt_reltoken(&hmp->fs_token);
2461                 return (error);
2462         }
2463
2464         /*
2465          * Add a record representing the symlink.  symlink stores the link
2466          * as pure data, not a string, and is no \0 terminated.
2467          */
2468         if (error == 0) {
2469                 bytes = strlen(ap->a_target);
2470
2471                 if (bytes <= HAMMER_INODE_BASESYMLEN) {
2472                         bcopy(ap->a_target, nip->ino_data.ext.symlink, bytes);
2473                 } else {
2474                         record = hammer_alloc_mem_record(nip, bytes);
2475                         record->type = HAMMER_MEM_RECORD_GENERAL;
2476
2477                         record->leaf.base.localization = nip->obj_localization +
2478                                                          HAMMER_LOCALIZE_MISC;
2479                         record->leaf.base.key = HAMMER_FIXKEY_SYMLINK;
2480                         record->leaf.base.rec_type = HAMMER_RECTYPE_FIX;
2481                         record->leaf.data_len = bytes;
2482                         KKASSERT(HAMMER_SYMLINK_NAME_OFF == 0);
2483                         bcopy(ap->a_target, record->data->symlink.name, bytes);
2484                         error = hammer_ip_add_record(&trans, record);
2485                 }
2486
2487                 /*
2488                  * Set the file size to the length of the link.
2489                  */
2490                 if (error == 0) {
2491                         nip->ino_data.size = bytes;
2492                         hammer_modify_inode(&trans, nip, HAMMER_INODE_DDIRTY);
2493                 }
2494         }
2495         if (error == 0)
2496                 error = hammer_ip_add_directory(&trans, dip, nch->ncp->nc_name,
2497                                                 nch->ncp->nc_nlen, nip);
2498
2499         /*
2500          * Finish up.
2501          */
2502         if (error) {
2503                 hammer_rel_inode(nip, 0);
2504                 *ap->a_vpp = NULL;
2505         } else {
2506                 error = hammer_get_vnode(nip, ap->a_vpp);
2507                 hammer_rel_inode(nip, 0);
2508                 if (error == 0) {
2509                         cache_setunresolved(ap->a_nch);
2510                         cache_setvp(ap->a_nch, *ap->a_vpp);
2511                         hammer_knote(ap->a_dvp, NOTE_WRITE);
2512                 }
2513         }
2514         hammer_done_transaction(&trans);
2515         lwkt_reltoken(&hmp->fs_token);
2516         return (error);
2517 }
2518
2519 /*
2520  * hammer_vop_nwhiteout { nch, dvp, cred, flags }
2521  */
2522 static
2523 int
2524 hammer_vop_nwhiteout(struct vop_nwhiteout_args *ap)
2525 {
2526         struct hammer_transaction trans;
2527         struct hammer_inode *dip;
2528         hammer_mount_t hmp;
2529         int error;
2530
2531         dip = VTOI(ap->a_dvp);
2532         hmp = dip->hmp;
2533
2534         if (hammer_nohistory(dip) == 0 &&
2535             (error = hammer_checkspace(hmp, HAMMER_CHKSPC_CREATE)) != 0) {
2536                 return (error);
2537         }
2538
2539         lwkt_gettoken(&hmp->fs_token);
2540         hammer_start_transaction(&trans, hmp);
2541         ++hammer_stats_file_iopsw;
2542         error = hammer_dounlink(&trans, ap->a_nch, ap->a_dvp,
2543                                 ap->a_cred, ap->a_flags, -1);
2544         hammer_done_transaction(&trans);
2545         lwkt_reltoken(&hmp->fs_token);
2546
2547         return (error);
2548 }
2549
2550 /*
2551  * hammer_vop_ioctl { vp, command, data, fflag, cred }
2552  */
2553 static
2554 int
2555 hammer_vop_ioctl(struct vop_ioctl_args *ap)
2556 {
2557         struct hammer_inode *ip = ap->a_vp->v_data;
2558         hammer_mount_t hmp = ip->hmp;
2559         int error;
2560
2561         ++hammer_stats_file_iopsr;
2562         lwkt_gettoken(&hmp->fs_token);
2563         error = hammer_ioctl(ip, ap->a_command, ap->a_data,
2564                              ap->a_fflag, ap->a_cred);
2565         lwkt_reltoken(&hmp->fs_token);
2566         return (error);
2567 }
2568
2569 static
2570 int
2571 hammer_vop_mountctl(struct vop_mountctl_args *ap)
2572 {
2573         static const struct mountctl_opt extraopt[] = {
2574                 { HMNT_NOHISTORY,       "nohistory" },
2575                 { HMNT_MASTERID,        "master" },
2576                 { 0, NULL}
2577
2578         };
2579         struct hammer_mount *hmp;
2580         struct mount *mp;
2581         int usedbytes;
2582         int error;
2583
2584         error = 0;
2585         usedbytes = 0;
2586         mp = ap->a_head.a_ops->head.vv_mount;
2587         KKASSERT(mp->mnt_data != NULL);
2588         hmp = (struct hammer_mount *)mp->mnt_data;
2589
2590         lwkt_gettoken(&hmp->fs_token);
2591
2592         switch(ap->a_op) {
2593         case MOUNTCTL_SET_EXPORT:
2594                 if (ap->a_ctllen != sizeof(struct export_args))
2595                         error = EINVAL;
2596                 else
2597                         error = hammer_vfs_export(mp, ap->a_op,
2598                                       (const struct export_args *)ap->a_ctl);
2599                 break;
2600         case MOUNTCTL_MOUNTFLAGS:
2601         {
2602                 /*
2603                  * Call standard mountctl VOP function
2604                  * so we get user mount flags.
2605                  */
2606                 error = vop_stdmountctl(ap);
2607                 if (error)
2608                         break;
2609
2610                 usedbytes = *ap->a_res;
2611
2612                 if (usedbytes > 0 && usedbytes < ap->a_buflen) {
2613                         usedbytes += vfs_flagstostr(hmp->hflags, extraopt,
2614                                                     ap->a_buf,
2615                                                     ap->a_buflen - usedbytes,
2616                                                     &error);
2617                 }
2618
2619                 *ap->a_res += usedbytes;
2620                 break;
2621         }
2622         default:
2623                 error = vop_stdmountctl(ap);
2624                 break;
2625         }
2626         lwkt_reltoken(&hmp->fs_token);
2627         return(error);
2628 }
2629
2630 /*
2631  * hammer_vop_strategy { vp, bio }
2632  *
2633  * Strategy call, used for regular file read & write only.  Note that the
2634  * bp may represent a cluster.
2635  *
2636  * To simplify operation and allow better optimizations in the future,
2637  * this code does not make any assumptions with regards to buffer alignment
2638  * or size.
2639  */
2640 static
2641 int
2642 hammer_vop_strategy(struct vop_strategy_args *ap)
2643 {
2644         struct buf *bp;
2645         int error;
2646
2647         bp = ap->a_bio->bio_buf;
2648
2649         switch(bp->b_cmd) {
2650         case BUF_CMD_READ:
2651                 error = hammer_vop_strategy_read(ap);
2652                 break;
2653         case BUF_CMD_WRITE:
2654                 error = hammer_vop_strategy_write(ap);
2655                 break;
2656         default:
2657                 bp->b_error = error = EINVAL;
2658                 bp->b_flags |= B_ERROR;
2659                 biodone(ap->a_bio);
2660                 break;
2661         }
2662
2663         /* hammer_dump_dedup_cache(((hammer_inode_t)ap->a_vp->v_data)->hmp); */
2664
2665         return (error);
2666 }
2667
2668 /*
2669  * Read from a regular file.  Iterate the related records and fill in the
2670  * BIO/BUF.  Gaps are zero-filled.
2671  *
2672  * The support code in hammer_object.c should be used to deal with mixed
2673  * in-memory and on-disk records.
2674  *
2675  * NOTE: Can be called from the cluster code with an oversized buf.
2676  *
2677  * XXX atime update
2678  */
2679 static
2680 int
2681 hammer_vop_strategy_read(struct vop_strategy_args *ap)
2682 {
2683         struct hammer_transaction trans;
2684         struct hammer_inode *ip;
2685         struct hammer_inode *dip;
2686         hammer_mount_t hmp;
2687         struct hammer_cursor cursor;
2688         hammer_base_elm_t base;
2689         hammer_off_t disk_offset;
2690         struct bio *bio;
2691         struct bio *nbio;
2692         struct buf *bp;
2693         int64_t rec_offset;
2694         int64_t ran_end;
2695         int64_t tmp64;
2696         int error;
2697         int boff;
2698         int roff;
2699         int n;
2700         int isdedupable;
2701
2702         bio = ap->a_bio;
2703         bp = bio->bio_buf;
2704         ip = ap->a_vp->v_data;
2705         hmp = ip->hmp;
2706
2707         /*
2708          * The zone-2 disk offset may have been set by the cluster code via
2709          * a BMAP operation, or else should be NOOFFSET.
2710          *
2711          * Checking the high bits for a match against zone-2 should suffice.
2712          *
2713          * In cases where a lot of data duplication is present it may be
2714          * more beneficial to drop through and doubule-buffer through the
2715          * device.
2716          */
2717         nbio = push_bio(bio);
2718         if ((nbio->bio_offset & HAMMER_OFF_ZONE_MASK) ==
2719             HAMMER_ZONE_LARGE_DATA) {
2720                 if (hammer_double_buffer == 0) {
2721                         lwkt_gettoken(&hmp->fs_token);
2722                         error = hammer_io_direct_read(hmp, nbio, NULL);
2723                         lwkt_reltoken(&hmp->fs_token);
2724                         return (error);
2725                 }
2726
2727                 /*
2728                  * Try to shortcut requests for double_buffer mode too.
2729                  * Since this mode runs through the device buffer cache
2730                  * only compatible buffer sizes (meaning those generated
2731                  * by normal filesystem buffers) are legal.
2732                  */
2733                 if (hammer_live_dedup == 0 && (bp->b_flags & B_PAGING) == 0) {
2734                         lwkt_gettoken(&hmp->fs_token);
2735                         error = hammer_io_indirect_read(hmp, nbio, NULL);
2736                         lwkt_reltoken(&hmp->fs_token);
2737                         return (error);
2738                 }
2739         }
2740
2741         /*
2742          * Well, that sucked.  Do it the hard way.  If all the stars are
2743          * aligned we may still be able to issue a direct-read.
2744          */
2745         lwkt_gettoken(&hmp->fs_token);
2746         hammer_simple_transaction(&trans, hmp);
2747         hammer_init_cursor(&trans, &cursor, &ip->cache[1], ip);
2748
2749         /*
2750          * Key range (begin and end inclusive) to scan.  Note that the key's
2751          * stored in the actual records represent BASE+LEN, not BASE.  The
2752          * first record containing bio_offset will have a key > bio_offset.
2753          */
2754         cursor.key_beg.localization = ip->obj_localization +
2755                                       HAMMER_LOCALIZE_MISC;
2756         cursor.key_beg.obj_id = ip->obj_id;
2757         cursor.key_beg.create_tid = 0;
2758         cursor.key_beg.delete_tid = 0;
2759         cursor.key_beg.obj_type = 0;
2760         cursor.key_beg.key = bio->bio_offset + 1;
2761         cursor.asof = ip->obj_asof;
2762         cursor.flags |= HAMMER_CURSOR_ASOF;
2763
2764         cursor.key_end = cursor.key_beg;
2765         KKASSERT(ip->ino_data.obj_type == HAMMER_OBJTYPE_REGFILE);
2766 #if 0
2767         if (ip->ino_data.obj_type == HAMMER_OBJTYPE_DBFILE) {
2768                 cursor.key_beg.rec_type = HAMMER_RECTYPE_DB;
2769                 cursor.key_end.rec_type = HAMMER_RECTYPE_DB;
2770                 cursor.key_end.key = 0x7FFFFFFFFFFFFFFFLL;
2771         } else
2772 #endif
2773         {
2774                 ran_end = bio->bio_offset + bp->b_bufsize;
2775                 cursor.key_beg.rec_type = HAMMER_RECTYPE_DATA;
2776                 cursor.key_end.rec_type = HAMMER_RECTYPE_DATA;
2777                 tmp64 = ran_end + MAXPHYS + 1;  /* work-around GCC-4 bug */
2778                 if (tmp64 < ran_end)
2779                         cursor.key_end.key = 0x7FFFFFFFFFFFFFFFLL;
2780                 else
2781                         cursor.key_end.key = ran_end + MAXPHYS + 1;
2782         }
2783         cursor.flags |= HAMMER_CURSOR_END_INCLUSIVE;
2784
2785         /*
2786          * Set NOSWAPCACHE for cursor data extraction if double buffering
2787          * is disabled or (if the file is not marked cacheable via chflags
2788          * and vm.swapcache_use_chflags is enabled).
2789          */
2790         if (hammer_double_buffer == 0 ||
2791             ((ap->a_vp->v_flag & VSWAPCACHE) == 0 &&
2792              vm_swapcache_use_chflags)) {
2793                 cursor.flags |= HAMMER_CURSOR_NOSWAPCACHE;
2794         }
2795
2796         error = hammer_ip_first(&cursor);
2797         boff = 0;
2798
2799         while (error == 0) {
2800                 /*
2801                  * Get the base file offset of the record.  The key for
2802                  * data records is (base + bytes) rather then (base).
2803                  */
2804                 base = &cursor.leaf->base;
2805                 rec_offset = base->key - cursor.leaf->data_len;
2806
2807                 /*
2808                  * Calculate the gap, if any, and zero-fill it.
2809                  *
2810                  * n is the offset of the start of the record verses our
2811                  * current seek offset in the bio.
2812                  */
2813                 n = (int)(rec_offset - (bio->bio_offset + boff));
2814                 if (n > 0) {
2815                         if (n > bp->b_bufsize - boff)
2816                                 n = bp->b_bufsize - boff;
2817                         bzero((char *)bp->b_data + boff, n);
2818                         boff += n;
2819                         n = 0;
2820                 }
2821
2822                 /*
2823                  * Calculate the data offset in the record and the number
2824                  * of bytes we can copy.
2825                  *
2826                  * There are two degenerate cases.  First, boff may already
2827                  * be at bp->b_bufsize.  Secondly, the data offset within
2828                  * the record may exceed the record's size.
2829                  */
2830                 roff = -n;
2831                 rec_offset += roff;
2832                 n = cursor.leaf->data_len - roff;
2833                 if (n <= 0) {
2834                         kprintf("strategy_read: bad n=%d roff=%d\n", n, roff);
2835                         n = 0;
2836                 } else if (n > bp->b_bufsize - boff) {
2837                         n = bp->b_bufsize - boff;
2838                 }
2839
2840                 /*
2841                  * Deal with cached truncations.  This cool bit of code
2842                  * allows truncate()/ftruncate() to avoid having to sync
2843                  * the file.
2844                  *
2845                  * If the frontend is truncated then all backend records are
2846                  * subject to the frontend's truncation.
2847                  *
2848                  * If the backend is truncated then backend records on-disk
2849                  * (but not in-memory) are subject to the backend's
2850                  * truncation.  In-memory records owned by the backend
2851                  * represent data written after the truncation point on the
2852                  * backend and must not be truncated.
2853                  *
2854                  * Truncate operations deal with frontend buffer cache
2855                  * buffers and frontend-owned in-memory records synchronously.
2856                  */
2857                 if (ip->flags & HAMMER_INODE_TRUNCATED) {
2858                         if (hammer_cursor_ondisk(&cursor)/* ||
2859                             cursor.iprec->flush_state == HAMMER_FST_FLUSH*/) {
2860                                 if (ip->trunc_off <= rec_offset)
2861                                         n = 0;
2862                                 else if (ip->trunc_off < rec_offset + n)
2863                                         n = (int)(ip->trunc_off - rec_offset);
2864                         }
2865                 }
2866                 if (ip->sync_flags & HAMMER_INODE_TRUNCATED) {
2867                         if (hammer_cursor_ondisk(&cursor)) {
2868                                 if (ip->sync_trunc_off <= rec_offset)
2869                                         n = 0;
2870                                 else if (ip->sync_trunc_off < rec_offset + n)
2871                                         n = (int)(ip->sync_trunc_off - rec_offset);
2872                         }
2873                 }
2874
2875                 /*
2876                  * Try to issue a direct read into our bio if possible,
2877                  * otherwise resolve the element data into a hammer_buffer
2878                  * and copy.
2879                  *
2880                  * The buffer on-disk should be zerod past any real
2881                  * truncation point, but may not be for any synthesized
2882                  * truncation point from above.
2883                  *
2884                  * NOTE: disk_offset is only valid if the cursor data is
2885                  *       on-disk.
2886                  */
2887                 disk_offset = cursor.leaf->data_offset + roff;
2888                 isdedupable = (boff == 0 && n == bp->b_bufsize &&
2889                                hammer_cursor_ondisk(&cursor) &&
2890                                ((int)disk_offset & HAMMER_BUFMASK) == 0);
2891
2892                 if (isdedupable && hammer_double_buffer == 0) {
2893                         /*
2894                          * Direct read case
2895                          */
2896                         KKASSERT((disk_offset & HAMMER_OFF_ZONE_MASK) ==
2897                                  HAMMER_ZONE_LARGE_DATA);
2898                         nbio->bio_offset = disk_offset;
2899                         error = hammer_io_direct_read(hmp, nbio, cursor.leaf);
2900                         if (hammer_live_dedup && error == 0)
2901                                 hammer_dedup_cache_add(ip, cursor.leaf);
2902                         goto done;
2903                 } else if (isdedupable) {
2904                         /*
2905                          * Async I/O case for reading from backing store
2906                          * and copying the data to the filesystem buffer.
2907                          * live-dedup has to verify the data anyway if it
2908                          * gets a hit later so we can just add the entry
2909                          * now.
2910                          */
2911                         KKASSERT((disk_offset & HAMMER_OFF_ZONE_MASK) ==
2912                                  HAMMER_ZONE_LARGE_DATA);
2913                         nbio->bio_offset = disk_offset;
2914                         if (hammer_live_dedup)
2915                                 hammer_dedup_cache_add(ip, cursor.leaf);
2916                         error = hammer_io_indirect_read(hmp, nbio, cursor.leaf);
2917                         goto done;
2918                 } else if (n) {
2919                         error = hammer_ip_resolve_data(&cursor);
2920                         if (error == 0) {
2921                                 if (hammer_live_dedup && isdedupable)
2922                                         hammer_dedup_cache_add(ip, cursor.leaf);
2923                                 bcopy((char *)cursor.data + roff,
2924                                       (char *)bp->b_data + boff, n);
2925                         }
2926                 }
2927                 if (error)
2928                         break;
2929
2930                 /*
2931                  * We have to be sure that the only elements added to the
2932                  * dedup cache are those which are already on-media.
2933                  */
2934                 if (hammer_live_dedup && hammer_cursor_ondisk(&cursor))
2935                         hammer_dedup_cache_add(ip, cursor.leaf);
2936
2937                 /*
2938                  * Iterate until we have filled the request.
2939                  */
2940                 boff += n;
2941                 if (boff == bp->b_bufsize)
2942                         break;
2943                 error = hammer_ip_next(&cursor);
2944         }
2945
2946         /*
2947          * There may have been a gap after the last record
2948          */
2949         if (error == ENOENT)
2950                 error = 0;
2951         if (error == 0 && boff != bp->b_bufsize) {
2952                 KKASSERT(boff < bp->b_bufsize);
2953                 bzero((char *)bp->b_data + boff, bp->b_bufsize - boff);
2954                 /* boff = bp->b_bufsize; */
2955         }
2956
2957         /*
2958          * Disallow swapcache operation on the vnode buffer if double
2959          * buffering is enabled, the swapcache will get the data via
2960          * the block device buffer.
2961          */
2962         if (hammer_double_buffer)
2963                 bp->b_flags |= B_NOTMETA;
2964
2965         /*
2966          * Cleanup
2967          */
2968         bp->b_resid = 0;
2969         bp->b_error = error;
2970         if (error)
2971                 bp->b_flags |= B_ERROR;
2972         biodone(ap->a_bio);
2973
2974 done:
2975         /*
2976          * Cache the b-tree node for the last data read in cache[1].
2977          *
2978          * If we hit the file EOF then also cache the node in the
2979          * governing director's cache[3], it will be used to initialize
2980          * the inode's cache[1] for any inodes looked up via the directory.
2981          *
2982          * This doesn't reduce disk accesses since the B-Tree chain is
2983          * likely cached, but it does reduce cpu overhead when looking
2984          * up file offsets for cpdup/tar/cpio style iterations.
2985          */
2986         if (cursor.node)
2987                 hammer_cache_node(&ip->cache[1], cursor.node);
2988         if (ran_end >= ip->ino_data.size) {
2989                 dip = hammer_find_inode(&trans, ip->ino_data.parent_obj_id,
2990                                         ip->obj_asof, ip->obj_localization);
2991                 if (dip) {
2992                         hammer_cache_node(&dip->cache[3], cursor.node);
2993                         hammer_rel_inode(dip, 0);
2994                 }
2995         }
2996         hammer_done_cursor(&cursor);
2997         hammer_done_transaction(&trans);
2998         lwkt_reltoken(&hmp->fs_token);
2999         return(error);
3000 }
3001
3002 /*
3003  * BMAP operation - used to support cluster_read() only.
3004  *
3005  * (struct vnode *vp, off_t loffset, off_t *doffsetp, int *runp, int *runb)
3006  *
3007  * This routine may return EOPNOTSUPP if the opration is not supported for
3008  * the specified offset.  The contents of the pointer arguments do not
3009  * need to be initialized in that case.
3010  *
3011  * If a disk address is available and properly aligned return 0 with
3012  * *doffsetp set to the zone-2 address, and *runp / *runb set appropriately
3013  * to the run-length relative to that offset.  Callers may assume that
3014  * *doffsetp is valid if 0 is returned, even if *runp is not sufficiently
3015  * large, so return EOPNOTSUPP if it is not sufficiently large.
3016  */
3017 static
3018 int
3019 hammer_vop_bmap(struct vop_bmap_args *ap)
3020 {
3021         struct hammer_transaction trans;
3022         struct hammer_inode *ip;
3023         hammer_mount_t hmp;
3024         struct hammer_cursor cursor;
3025         hammer_base_elm_t base;
3026         int64_t rec_offset;
3027         int64_t ran_end;
3028         int64_t tmp64;
3029         int64_t base_offset;
3030         int64_t base_disk_offset;
3031         int64_t last_offset;
3032         hammer_off_t last_disk_offset;
3033         hammer_off_t disk_offset;
3034         int     rec_len;
3035         int     error;
3036         int     blksize;
3037
3038         ++hammer_stats_file_iopsr;
3039         ip = ap->a_vp->v_data;
3040         hmp = ip->hmp;
3041
3042         /*
3043          * We can only BMAP regular files.  We can't BMAP database files,
3044          * directories, etc.
3045          */
3046         if (ip->ino_data.obj_type != HAMMER_OBJTYPE_REGFILE)
3047                 return(EOPNOTSUPP);
3048
3049         /*
3050          * bmap is typically called with runp/runb both NULL when used
3051          * for writing.  We do not support BMAP for writing atm.
3052          */
3053         if (ap->a_cmd != BUF_CMD_READ)
3054                 return(EOPNOTSUPP);
3055
3056         /*
3057          * Scan the B-Tree to acquire blockmap addresses, then translate
3058          * to raw addresses.
3059          */
3060         lwkt_gettoken(&hmp->fs_token);
3061         hammer_simple_transaction(&trans, hmp);
3062 #if 0
3063         kprintf("bmap_beg %016llx ip->cache %p\n",
3064                 (long long)ap->a_loffset, ip->cache[1]);
3065 #endif
3066         hammer_init_cursor(&trans, &cursor, &ip->cache[1], ip);
3067
3068         /*
3069          * Key range (begin and end inclusive) to scan.  Note that the key's
3070          * stored in the actual records represent BASE+LEN, not BASE.  The
3071          * first record containing bio_offset will have a key > bio_offset.
3072          */
3073         cursor.key_beg.localization = ip->obj_localization +
3074                                       HAMMER_LOCALIZE_MISC;
3075         cursor.key_beg.obj_id = ip->obj_id;
3076         cursor.key_beg.create_tid = 0;
3077         cursor.key_beg.delete_tid = 0;
3078         cursor.key_beg.obj_type = 0;
3079         if (ap->a_runb)
3080                 cursor.key_beg.key = ap->a_loffset - MAXPHYS + 1;
3081         else
3082                 cursor.key_beg.key = ap->a_loffset + 1;
3083         if (cursor.key_beg.key < 0)
3084                 cursor.key_beg.key = 0;
3085         cursor.asof = ip->obj_asof;
3086         cursor.flags |= HAMMER_CURSOR_ASOF;
3087
3088         cursor.key_end = cursor.key_beg;
3089         KKASSERT(ip->ino_data.obj_type == HAMMER_OBJTYPE_REGFILE);
3090
3091         ran_end = ap->a_loffset + MAXPHYS;
3092         cursor.key_beg.rec_type = HAMMER_RECTYPE_DATA;
3093         cursor.key_end.rec_type = HAMMER_RECTYPE_DATA;
3094         tmp64 = ran_end + MAXPHYS + 1;  /* work-around GCC-4 bug */
3095         if (tmp64 < ran_end)
3096                 cursor.key_end.key = 0x7FFFFFFFFFFFFFFFLL;
3097         else
3098                 cursor.key_end.key = ran_end + MAXPHYS + 1;
3099
3100         cursor.flags |= HAMMER_CURSOR_END_INCLUSIVE;
3101
3102         error = hammer_ip_first(&cursor);
3103         base_offset = last_offset = 0;
3104         base_disk_offset = last_disk_offset = 0;
3105
3106         while (error == 0) {
3107                 /*
3108                  * Get the base file offset of the record.  The key for
3109                  * data records is (base + bytes) rather then (base).
3110                  *
3111                  * NOTE: rec_offset + rec_len may exceed the end-of-file.
3112                  * The extra bytes should be zero on-disk and the BMAP op
3113                  * should still be ok.
3114                  */
3115                 base = &cursor.leaf->base;
3116                 rec_offset = base->key - cursor.leaf->data_len;
3117                 rec_len    = cursor.leaf->data_len;
3118
3119                 /*
3120                  * Incorporate any cached truncation.
3121                  *
3122                  * NOTE: Modifications to rec_len based on synthesized
3123                  * truncation points remove the guarantee that any extended
3124                  * data on disk is zero (since the truncations may not have
3125                  * taken place on-media yet).
3126                  */
3127                 if (ip->flags & HAMMER_INODE_TRUNCATED) {
3128                         if (hammer_cursor_ondisk(&cursor) ||
3129                             cursor.iprec->flush_state == HAMMER_FST_FLUSH) {
3130                                 if (ip->trunc_off <= rec_offset)
3131                                         rec_len = 0;
3132                                 else if (ip->trunc_off < rec_offset + rec_len)
3133                                         rec_len = (int)(ip->trunc_off - rec_offset);
3134                         }
3135                 }
3136                 if (ip->sync_flags & HAMMER_INODE_TRUNCATED) {
3137                         if (hammer_cursor_ondisk(&cursor)) {
3138                                 if (ip->sync_trunc_off <= rec_offset)
3139                                         rec_len = 0;
3140                                 else if (ip->sync_trunc_off < rec_offset + rec_len)
3141                                         rec_len = (int)(ip->sync_trunc_off - rec_offset);
3142                         }
3143                 }
3144
3145                 /*
3146                  * Accumulate information.  If we have hit a discontiguous
3147                  * block reset base_offset unless we are already beyond the
3148                  * requested offset.  If we are, that's it, we stop.
3149                  */
3150                 if (error)
3151                         break;
3152                 if (hammer_cursor_ondisk(&cursor)) {
3153                         disk_offset = cursor.leaf->data_offset;
3154                         if (rec_offset != last_offset ||
3155                             disk_offset != last_disk_offset) {
3156                                 if (rec_offset > ap->a_loffset)
3157                                         break;
3158                                 base_offset = rec_offset;
3159                                 base_disk_offset = disk_offset;
3160                         }
3161                         last_offset = rec_offset + rec_len;
3162                         last_disk_offset = disk_offset + rec_len;
3163
3164                         if (hammer_live_dedup)
3165                                 hammer_dedup_cache_add(ip, cursor.leaf);
3166                 }
3167
3168                 error = hammer_ip_next(&cursor);
3169         }
3170
3171 #if 0
3172         kprintf("BMAP %016llx:  %016llx - %016llx\n",
3173                 (long long)ap->a_loffset,
3174                 (long long)base_offset,
3175                 (long long)last_offset);
3176         kprintf("BMAP %16s:  %016llx - %016llx\n", "",
3177                 (long long)base_disk_offset,
3178                 (long long)last_disk_offset);
3179 #endif
3180
3181         if (cursor.node) {
3182                 hammer_cache_node(&ip->cache[1], cursor.node);
3183 #if 0
3184                 kprintf("bmap_end2 %016llx ip->cache %p\n",
3185                         (long long)ap->a_loffset, ip->cache[1]);
3186 #endif
3187         }
3188         hammer_done_cursor(&cursor);
3189         hammer_done_transaction(&trans);
3190         lwkt_reltoken(&hmp->fs_token);
3191
3192         /*
3193          * If we couldn't find any records or the records we did find were
3194          * all behind the requested offset, return failure.  A forward
3195          * truncation can leave a hole w/ no on-disk records.
3196          */
3197         if (last_offset == 0 || last_offset < ap->a_loffset)
3198                 return (EOPNOTSUPP);
3199
3200         /*
3201          * Figure out the block size at the requested offset and adjust
3202          * our limits so the cluster_read() does not create inappropriately
3203          * sized buffer cache buffers.
3204          */
3205         blksize = hammer_blocksize(ap->a_loffset);
3206         if (hammer_blocksize(base_offset) != blksize) {
3207                 base_offset = hammer_blockdemarc(base_offset, ap->a_loffset);
3208         }
3209         if (last_offset != ap->a_loffset &&
3210             hammer_blocksize(last_offset - 1) != blksize) {
3211                 last_offset = hammer_blockdemarc(ap->a_loffset,
3212                                                  last_offset - 1);
3213         }
3214
3215         /*
3216          * Returning EOPNOTSUPP simply prevents the direct-IO optimization
3217          * from occuring.
3218          */
3219         disk_offset = base_disk_offset + (ap->a_loffset - base_offset);
3220
3221         if ((disk_offset & HAMMER_OFF_ZONE_MASK) != HAMMER_ZONE_LARGE_DATA) {
3222                 /*
3223                  * Only large-data zones can be direct-IOd
3224                  */
3225                 error = EOPNOTSUPP;
3226         } else if ((disk_offset & HAMMER_BUFMASK) ||
3227                    (last_offset - ap->a_loffset) < blksize) {
3228                 /*
3229                  * doffsetp is not aligned or the forward run size does
3230                  * not cover a whole buffer, disallow the direct I/O.
3231                  */
3232                 error = EOPNOTSUPP;
3233         } else {
3234                 /*
3235                  * We're good.
3236                  */
3237                 *ap->a_doffsetp = disk_offset;
3238                 if (ap->a_runb) {
3239                         *ap->a_runb = ap->a_loffset - base_offset;
3240                         KKASSERT(*ap->a_runb >= 0);
3241                 }
3242                 if (ap->a_runp) {
3243                         *ap->a_runp = last_offset - ap->a_loffset;
3244                         KKASSERT(*ap->a_runp >= 0);
3245                 }
3246                 error = 0;
3247         }
3248         return(error);
3249 }
3250
3251 /*
3252  * Write to a regular file.   Because this is a strategy call the OS is
3253  * trying to actually get data onto the media.
3254  */
3255 static
3256 int
3257 hammer_vop_strategy_write(struct vop_strategy_args *ap)
3258 {
3259         hammer_record_t record;
3260         hammer_mount_t hmp;
3261         hammer_inode_t ip;
3262         struct bio *bio;
3263         struct buf *bp;
3264         int blksize __debugvar;
3265         int bytes;
3266         int error;
3267
3268         bio = ap->a_bio;
3269         bp = bio->bio_buf;
3270         ip = ap->a_vp->v_data;
3271         hmp = ip->hmp;
3272
3273         blksize = hammer_blocksize(bio->bio_offset);
3274         KKASSERT(bp->b_bufsize == blksize);
3275
3276         if (ip->flags & HAMMER_INODE_RO) {
3277                 bp->b_error = EROFS;
3278                 bp->b_flags |= B_ERROR;
3279                 biodone(ap->a_bio);
3280                 return(EROFS);
3281         }
3282
3283         lwkt_gettoken(&hmp->fs_token);
3284
3285         /*
3286          * Disallow swapcache operation on the vnode buffer if double
3287          * buffering is enabled, the swapcache will get the data via
3288          * the block device buffer.
3289          */
3290         if (hammer_double_buffer)
3291                 bp->b_flags |= B_NOTMETA;
3292
3293         /*
3294          * Interlock with inode destruction (no in-kernel or directory
3295          * topology visibility).  If we queue new IO while trying to
3296          * destroy the inode we can deadlock the vtrunc call in
3297          * hammer_inode_unloadable_check().
3298          *
3299          * Besides, there's no point flushing a bp associated with an
3300          * inode that is being destroyed on-media and has no kernel
3301          * references.
3302          */
3303         if ((ip->flags | ip->sync_flags) &
3304             (HAMMER_INODE_DELETING|HAMMER_INODE_DELETED)) {
3305                 bp->b_resid = 0;
3306                 biodone(ap->a_bio);
3307                 lwkt_reltoken(&hmp->fs_token);
3308                 return(0);
3309         }
3310
3311         /*
3312          * Reserve space and issue a direct-write from the front-end.
3313          * NOTE: The direct_io code will hammer_bread/bcopy smaller
3314          * allocations.
3315          *
3316          * An in-memory record will be installed to reference the storage
3317          * until the flusher can get to it.
3318          *
3319          * Since we own the high level bio the front-end will not try to
3320          * do a direct-read until the write completes.
3321          *
3322          * NOTE: The only time we do not reserve a full-sized buffers
3323          * worth of data is if the file is small.  We do not try to
3324          * allocate a fragment (from the small-data zone) at the end of
3325          * an otherwise large file as this can lead to wildly separated
3326          * data.
3327          */
3328         KKASSERT((bio->bio_offset & HAMMER_BUFMASK) == 0);
3329         KKASSERT(bio->bio_offset < ip->ino_data.size);
3330         if (bio->bio_offset || ip->ino_data.size > HAMMER_BUFSIZE / 2)
3331                 bytes = bp->b_bufsize;
3332         else
3333                 bytes = ((int)ip->ino_data.size + 15) & ~15;
3334
3335         record = hammer_ip_add_bulk(ip, bio->bio_offset, bp->b_data,
3336                                     bytes, &error);
3337
3338         /*
3339          * B_VFSFLAG1 indicates that a REDO_WRITE entry was generated
3340          * in hammer_vop_write().  We must flag the record so the proper
3341          * REDO_TERM_WRITE entry is generated during the flush.
3342          */
3343         if (record) {
3344                 if (bp->b_flags & B_VFSFLAG1) {
3345                         record->flags |= HAMMER_RECF_REDO;
3346                         bp->b_flags &= ~B_VFSFLAG1;
3347                 }
3348                 if (record->flags & HAMMER_RECF_DEDUPED) {
3349                         bp->b_resid = 0;
3350                         hammer_ip_replace_bulk(hmp, record);
3351                         biodone(ap->a_bio);
3352                 } else {
3353                         hammer_io_direct_write(hmp, bio, record);
3354                 }
3355                 if (ip->rsv_recs > 1 && hmp->rsv_recs > hammer_limit_recs)
3356                         hammer_flush_inode(ip, 0);
3357         } else {
3358                 bp->b_bio2.bio_offset = NOOFFSET;
3359                 bp->b_error = error;
3360                 bp->b_flags |= B_ERROR;
3361                 biodone(ap->a_bio);
3362         }
3363         lwkt_reltoken(&hmp->fs_token);
3364         return(error);
3365 }
3366
3367 /*
3368  * dounlink - disconnect a directory entry
3369  *
3370  * XXX whiteout support not really in yet
3371  */
3372 static int
3373 hammer_dounlink(hammer_transaction_t trans, struct nchandle *nch,
3374                 struct vnode *dvp, struct ucred *cred,
3375                 int flags, int isdir)
3376 {
3377         struct namecache *ncp;
3378         hammer_inode_t dip;
3379         hammer_inode_t ip;
3380         hammer_mount_t hmp;
3381         struct hammer_cursor cursor;
3382         int64_t namekey;
3383         u_int32_t max_iterations;
3384         int nlen, error;
3385
3386         /*
3387          * Calculate the namekey and setup the key range for the scan.  This
3388          * works kinda like a chained hash table where the lower 32 bits
3389          * of the namekey synthesize the chain.
3390          *
3391          * The key range is inclusive of both key_beg and key_end.
3392          */
3393         dip = VTOI(dvp);
3394         ncp = nch->ncp;
3395         hmp = dip->hmp;
3396
3397         if (dip->flags & HAMMER_INODE_RO)
3398                 return (EROFS);
3399
3400         namekey = hammer_directory_namekey(dip, ncp->nc_name, ncp->nc_nlen,
3401                                            &max_iterations);
3402 retry:
3403         hammer_init_cursor(trans, &cursor, &dip->cache[1], dip);
3404         cursor.key_beg.localization = dip->obj_localization +
3405                                       hammer_dir_localization(dip);
3406         cursor.key_beg.obj_id = dip->obj_id;
3407         cursor.key_beg.key = namekey;
3408         cursor.key_beg.create_tid = 0;
3409         cursor.key_beg.delete_tid = 0;
3410         cursor.key_beg.rec_type = HAMMER_RECTYPE_DIRENTRY;
3411         cursor.key_beg.obj_type = 0;
3412
3413         cursor.key_end = cursor.key_beg;
3414         cursor.key_end.key += max_iterations;
3415         cursor.asof = dip->obj_asof;
3416         cursor.flags |= HAMMER_CURSOR_END_INCLUSIVE | HAMMER_CURSOR_ASOF;
3417
3418         /*
3419          * Scan all matching records (the chain), locate the one matching
3420          * the requested path component.  info->last_error contains the
3421          * error code on search termination and could be 0, ENOENT, or
3422          * something else.
3423          *
3424          * The hammer_ip_*() functions merge in-memory records with on-disk
3425          * records for the purposes of the search.
3426          */
3427         error = hammer_ip_first(&cursor);
3428
3429         while (error == 0) {
3430                 error = hammer_ip_resolve_data(&cursor);
3431                 if (error)
3432                         break;
3433                 nlen = cursor.leaf->data_len - HAMMER_ENTRY_NAME_OFF;
3434                 KKASSERT(nlen > 0);
3435                 if (ncp->nc_nlen == nlen &&
3436                     bcmp(ncp->nc_name, cursor.data->entry.name, nlen) == 0) {
3437                         break;
3438                 }
3439                 error = hammer_ip_next(&cursor);
3440         }
3441
3442         /*
3443          * If all is ok we have to get the inode so we can adjust nlinks.
3444          * To avoid a deadlock with the flusher we must release the inode
3445          * lock on the directory when acquiring the inode for the entry.
3446          *
3447          * If the target is a directory, it must be empty.
3448          */
3449         if (error == 0) {
3450                 hammer_unlock(&cursor.ip->lock);
3451                 ip = hammer_get_inode(trans, dip, cursor.data->entry.obj_id,
3452                                       hmp->asof,
3453                                       cursor.data->entry.localization,
3454                                       0, &error);
3455                 hammer_lock_sh(&cursor.ip->lock);
3456                 if (error == ENOENT) {
3457                         kprintf("HAMMER: WARNING: Removing "
3458                                 "dirent w/missing inode \"%s\"\n"
3459                                 "\tobj_id = %016llx\n",
3460                                 ncp->nc_name,
3461                                 (long long)cursor.data->entry.obj_id);
3462                         error = 0;
3463                 }
3464
3465                 /*
3466                  * If isdir >= 0 we validate that the entry is or is not a
3467                  * directory.  If isdir < 0 we don't care.
3468                  */
3469                 if (error == 0 && isdir >= 0 && ip) {
3470                         if (isdir &&
3471                             ip->ino_data.obj_type != HAMMER_OBJTYPE_DIRECTORY) {
3472                                 error = ENOTDIR;
3473                         } else if (isdir == 0 &&
3474                             ip->ino_data.obj_type == HAMMER_OBJTYPE_DIRECTORY) {
3475                                 error = EISDIR;
3476                         }
3477                 }
3478
3479                 /*
3480                  * If we are trying to remove a directory the directory must
3481                  * be empty.
3482                  *
3483                  * The check directory code can loop and deadlock/retry.  Our
3484                  * own cursor's node locks must be released to avoid a 3-way
3485                  * deadlock with the flusher if the check directory code
3486                  * blocks.
3487                  *
3488                  * If any changes whatsoever have been made to the cursor
3489                  * set EDEADLK and retry.
3490                  *
3491                  * WARNING: See warnings in hammer_unlock_cursor()
3492                  *          function.
3493                  */
3494                 if (error == 0 && ip && ip->ino_data.obj_type ==
3495                                         HAMMER_OBJTYPE_DIRECTORY) {
3496                         hammer_unlock_cursor(&cursor);
3497                         error = hammer_ip_check_directory_empty(trans, ip);
3498                         hammer_lock_cursor(&cursor);
3499                         if (cursor.flags & HAMMER_CURSOR_RETEST) {
3500                                 kprintf("HAMMER: Warning: avoided deadlock "
3501                                         "on rmdir '%s'\n",
3502                                         ncp->nc_name);
3503                                 error = EDEADLK;
3504                         }
3505                 }
3506
3507                 /*
3508                  * Delete the directory entry.
3509                  *
3510                  * WARNING: hammer_ip_del_directory() may have to terminate
3511                  * the cursor to avoid a deadlock.  It is ok to call
3512                  * hammer_done_cursor() twice.
3513                  */
3514                 if (error == 0) {
3515                         error = hammer_ip_del_directory(trans, &cursor,
3516                                                         dip, ip);
3517                 }
3518                 hammer_done_cursor(&cursor);
3519                 if (error == 0) {
3520                         /*
3521                          * Tell the namecache that we are now unlinked.
3522                          */
3523                         cache_unlink(nch);
3524
3525                         /*
3526                          * NOTE: ip->vp, if non-NULL, cannot be directly
3527                          *       referenced without formally acquiring the
3528                          *       vp since the vp might have zero refs on it,
3529                          *       or in the middle of a reclaim, etc.
3530                          *
3531                          * NOTE: The cache_setunresolved() can rip the vp
3532                          *       out from under us since the vp may not have
3533                          *       any refs, in which case ip->vp will be NULL
3534                          *       from the outset.
3535                          */
3536                         while (ip && ip->vp) {
3537                                 struct vnode *vp;
3538
3539                                 error = hammer_get_vnode(ip, &vp);
3540                                 if (error == 0 && vp) {
3541                                         vn_unlock(vp);
3542                                         hammer_knote(ip->vp, NOTE_DELETE);
3543 #if 0
3544                                         /*
3545                                          * Don't do this, it can deadlock
3546                                          * on concurrent rm's of hardlinks.
3547                                          * Shouldn't be needed any more.
3548                                          */
3549                                         cache_inval_vp(ip->vp, CINV_DESTROY);
3550 #endif
3551                                         vrele(vp);
3552                                         break;
3553                                 }
3554                                 kprintf("Debug: HAMMER ip/vp race1 avoided\n");
3555                         }
3556                 }
3557                 if (ip)
3558                         hammer_rel_inode(ip, 0);
3559         } else {
3560                 hammer_done_cursor(&cursor);
3561         }
3562         if (error == EDEADLK)
3563                 goto retry;
3564
3565         return (error);
3566 }
3567
3568 /************************************************************************
3569  *                          FIFO AND SPECFS OPS                         *
3570  ************************************************************************
3571  *
3572  */
3573 static int
3574 hammer_vop_fifoclose (struct vop_close_args *ap)
3575 {
3576         /* XXX update itimes */
3577         return (VOCALL(&fifo_vnode_vops, &ap->a_head));
3578 }
3579
3580 static int
3581 hammer_vop_fiforead (struct vop_read_args *ap)
3582 {
3583         int error;
3584
3585         error = VOCALL(&fifo_vnode_vops, &ap->a_head);
3586         /* XXX update access time */
3587         return (error);
3588 }
3589
3590 static int
3591 hammer_vop_fifowrite (struct vop_write_args *ap)
3592 {
3593         int error;
3594
3595         error = VOCALL(&fifo_vnode_vops, &ap->a_head);
3596         /* XXX update access time */
3597         return (error);
3598 }
3599
3600 static
3601 int
3602 hammer_vop_fifokqfilter(struct vop_kqfilter_args *ap)
3603 {
3604        &nbs