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