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