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