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