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