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