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