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