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