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