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