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