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