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