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