xref: /dflybsd-src/sys/vfs/hammer2/hammer2_vnops.c (revision f1e3af6c0d9fb009456c1ad7a10c323acbf7022f)
1 /*
2  * Copyright (c) 2011-2013 The DragonFly Project.  All rights reserved.
3  *
4  * This code is derived from software contributed to The DragonFly Project
5  * by Matthew Dillon <dillon@dragonflybsd.org>
6  * by Venkatesh Srinivas <vsrinivas@dragonflybsd.org>
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in
16  *    the documentation and/or other materials provided with the
17  *    distribution.
18  * 3. Neither the name of The DragonFly Project nor the names of its
19  *    contributors may be used to endorse or promote products derived
20  *    from this software without specific, prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
25  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
26  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
27  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
28  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
29  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
30  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
31  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
32  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  */
35 /*
36  * Kernel Filesystem interface
37  *
38  * NOTE! local ipdata pointers must be reloaded on any modifying operation
39  *	 to the inode as its underlying chain may have changed.
40  */
41 
42 #include <sys/param.h>
43 #include <sys/systm.h>
44 #include <sys/kernel.h>
45 #include <sys/fcntl.h>
46 #include <sys/buf.h>
47 #include <sys/proc.h>
48 #include <sys/namei.h>
49 #include <sys/mount.h>
50 #include <sys/vnode.h>
51 #include <sys/mountctl.h>
52 #include <sys/dirent.h>
53 #include <sys/uio.h>
54 
55 #include "hammer2.h"
56 
57 #define ZFOFFSET	(-2LL)
58 
59 static int hammer2_read_file(hammer2_inode_t *ip, struct uio *uio,
60 				int seqcount);
61 static int hammer2_write_file(hammer2_trans_t *trans, hammer2_inode_t *ip,
62 				hammer2_chain_t **parentp,
63 				struct uio *uio, int ioflag, int seqcount);
64 static hammer2_off_t hammer2_assign_physical(hammer2_trans_t *trans,
65 				hammer2_inode_t *ip, hammer2_chain_t **parentp,
66 				hammer2_key_t lbase, int lblksize,
67 				int *errorp);
68 static void hammer2_extend_file(hammer2_trans_t *trans, hammer2_inode_t *ip,
69 				hammer2_chain_t **parentp, hammer2_key_t nsize);
70 static void hammer2_truncate_file(hammer2_trans_t *trans, hammer2_inode_t *ip,
71 				hammer2_chain_t **parentp, hammer2_key_t nsize);
72 
73 static __inline
74 void
75 hammer2_knote(struct vnode *vp, int flags)
76 {
77 	if (flags)
78 		KNOTE(&vp->v_pollinfo.vpi_kqinfo.ki_note, flags);
79 }
80 
81 /*
82  * Last reference to a vnode is going away but it is still cached.
83  */
84 static
85 int
86 hammer2_vop_inactive(struct vop_inactive_args *ap)
87 {
88 	hammer2_inode_t *ip;
89 	hammer2_chain_t *parent;
90 	struct vnode *vp;
91 
92 	vp = ap->a_vp;
93 	ip = VTOI(vp);
94 
95 	/*
96 	 * Degenerate case
97 	 */
98 	if (ip == NULL) {
99 		vrecycle(vp);
100 		return (0);
101 	}
102 
103 	/*
104 	 * Detect updates to the embedded data which may be synchronized by
105 	 * the strategy code.  Simply mark the inode modified so it gets
106 	 * picked up by our normal flush.
107 	 */
108 	parent = hammer2_inode_lock_ex(ip);
109 	KKASSERT(parent);
110 
111 	/*
112 	 * Check for deleted inodes and recycle immediately.
113 	 */
114 	if (parent->flags & HAMMER2_CHAIN_DELETED) {
115 		hammer2_inode_unlock_ex(ip, parent);
116 		vrecycle(vp);
117 	} else {
118 		hammer2_inode_unlock_ex(ip, parent);
119 	}
120 	return (0);
121 }
122 
123 /*
124  * Reclaim a vnode so that it can be reused; after the inode is
125  * disassociated, the filesystem must manage it alone.
126  */
127 static
128 int
129 hammer2_vop_reclaim(struct vop_reclaim_args *ap)
130 {
131 	hammer2_chain_t *chain;
132 	hammer2_inode_t *ip;
133 	hammer2_mount_t *hmp;
134 #if 0
135 	hammer2_trans_t trans;
136 #endif
137 	struct vnode *vp;
138 
139 	vp = ap->a_vp;
140 	ip = VTOI(vp);
141 	if (ip == NULL)
142 		return(0);
143 	hmp = ip->hmp;
144 
145 	/*
146 	 * Set SUBMODIFIED so we can detect and propagate the DESTROYED
147 	 * bit in the flush code.
148 	 *
149 	 * ip->chain might be stale, correct it before checking as older
150 	 * versions of the chain are likely marked deleted even if the
151 	 * file hasn't been.  XXX ip->chain should never be stale on
152 	 * reclaim.
153 	 */
154 	chain = hammer2_inode_lock_ex(ip);
155 #if 0
156 	if (chain->next_parent)
157 		kprintf("RECLAIM DUPLINKED IP: %p ip->ch=%p ch=%p np=%p\n",
158 			ip, ip->chain, chain, chain->next_parent);
159 #endif
160 
161 	/*
162 	 * The final close of a deleted file or directory marks it for
163 	 * destruction.  The DESTROYED flag allows the flusher to shortcut
164 	 * any modified blocks still unflushed (that is, just ignore them).
165 	 *
166 	 * HAMMER2 usually does not try to optimize the freemap by returning
167 	 * deleted blocks to it as it does not usually know how many snapshots
168 	 * might be referencing portions of the file/dir.  XXX TODO.
169 	 *
170 	 * XXX TODO - However, any modified file as-of when a snapshot is made
171 	 *	      cannot use this optimization as some of the modifications
172 	 *	      may wind up being part of the snapshot.
173 	 */
174 	vp->v_data = NULL;
175 	ip->vp = NULL;
176 	if (chain->flags & HAMMER2_CHAIN_DELETED) {
177 		KKASSERT(chain->flags & HAMMER2_CHAIN_DELETED);
178 		atomic_set_int(&chain->flags, HAMMER2_CHAIN_DESTROYED |
179 					      HAMMER2_CHAIN_SUBMODIFIED);
180 	}
181 #if 0
182 	/*
183 	 * XXX chains will be flushed on sync, no need to do it here.
184 	 */
185 	if (chain->flags & (HAMMER2_CHAIN_MODIFIED |
186 			    HAMMER2_CHAIN_DELETED |
187 			    HAMMER2_CHAIN_SUBMODIFIED)) {
188 		hammer2_trans_init(ip->hmp, &trans, HAMMER2_TRANS_ISFLUSH);
189 		hammer2_chain_flush(&trans, chain);
190 		hammer2_trans_done(&trans);
191 	}
192 #endif
193 	hammer2_inode_unlock_ex(ip, chain);		/* unlock */
194 	hammer2_inode_drop(ip);				/* vp ref */
195 	/* chain no longer referenced */
196 	/* chain = NULL; not needed */
197 
198 	/*
199 	 * XXX handle background sync when ip dirty, kernel will no longer
200 	 * notify us regarding this inode because there is no longer a
201 	 * vnode attached to it.
202 	 */
203 
204 	return (0);
205 }
206 
207 static
208 int
209 hammer2_vop_fsync(struct vop_fsync_args *ap)
210 {
211 	hammer2_mount_t *hmp;
212 	hammer2_inode_t *ip;
213 	hammer2_trans_t trans;
214 	hammer2_chain_t *chain;
215 	struct vnode *vp;
216 
217 	vp = ap->a_vp;
218 	ip = VTOI(vp);
219 	hmp = ip->hmp;
220 
221 	hammer2_trans_init(hmp, &trans, HAMMER2_TRANS_ISFLUSH);
222 	chain = hammer2_inode_lock_ex(ip);
223 
224 	vfsync(vp, ap->a_waitfor, 1, NULL, NULL);
225 
226 	/*
227 	 * Calling chain_flush here creates a lot of duplicative
228 	 * COW operations due to non-optimal vnode ordering.
229 	 *
230 	 * Only do it for an actual fsync() syscall.  The other forms
231 	 * which call this function will eventually call chain_flush
232 	 * on the volume root as a catch-all, which is far more optimal.
233 	 */
234 	atomic_clear_int(&ip->flags, HAMMER2_INODE_MODIFIED);
235 	if (ap->a_flags & VOP_FSYNC_SYSCALL) {
236 		hammer2_chain_flush(&trans, chain);
237 	}
238 	hammer2_inode_unlock_ex(ip, chain);
239 	hammer2_trans_done(&trans);
240 
241 	return (0);
242 }
243 
244 static
245 int
246 hammer2_vop_access(struct vop_access_args *ap)
247 {
248 	hammer2_inode_t *ip = VTOI(ap->a_vp);
249 	hammer2_inode_data_t *ipdata;
250 	hammer2_chain_t *chain;
251 	uid_t uid;
252 	gid_t gid;
253 	int error;
254 
255 	chain = hammer2_inode_lock_sh(ip);
256 	ipdata = &chain->data->ipdata;
257 	uid = hammer2_to_unix_xid(&ipdata->uid);
258 	gid = hammer2_to_unix_xid(&ipdata->gid);
259 	error = vop_helper_access(ap, uid, gid, ipdata->mode, ipdata->uflags);
260 	hammer2_inode_unlock_sh(ip, chain);
261 
262 	return (error);
263 }
264 
265 static
266 int
267 hammer2_vop_getattr(struct vop_getattr_args *ap)
268 {
269 	hammer2_inode_data_t *ipdata;
270 	hammer2_chain_t *chain;
271 	hammer2_pfsmount_t *pmp;
272 	hammer2_inode_t *ip;
273 	struct vnode *vp;
274 	struct vattr *vap;
275 
276 	vp = ap->a_vp;
277 	vap = ap->a_vap;
278 
279 	ip = VTOI(vp);
280 	pmp = ip->pmp;
281 
282 	chain = hammer2_inode_lock_sh(ip);
283 	ipdata = &chain->data->ipdata;
284 
285 	vap->va_fsid = pmp->mp->mnt_stat.f_fsid.val[0];
286 	vap->va_fileid = ipdata->inum;
287 	vap->va_mode = ipdata->mode;
288 	vap->va_nlink = ipdata->nlinks;
289 	vap->va_uid = hammer2_to_unix_xid(&ipdata->uid);
290 	vap->va_gid = hammer2_to_unix_xid(&ipdata->gid);
291 	vap->va_rmajor = 0;
292 	vap->va_rminor = 0;
293 	vap->va_size = ipdata->size;
294 	vap->va_blocksize = HAMMER2_PBUFSIZE;
295 	vap->va_flags = ipdata->uflags;
296 	hammer2_time_to_timespec(ipdata->ctime, &vap->va_ctime);
297 	hammer2_time_to_timespec(ipdata->mtime, &vap->va_mtime);
298 	hammer2_time_to_timespec(ipdata->mtime, &vap->va_atime);
299 	vap->va_gen = 1;
300 	vap->va_bytes = vap->va_size;	/* XXX */
301 	vap->va_type = hammer2_get_vtype(chain);
302 	vap->va_filerev = 0;
303 	vap->va_uid_uuid = ipdata->uid;
304 	vap->va_gid_uuid = ipdata->gid;
305 	vap->va_vaflags = VA_UID_UUID_VALID | VA_GID_UUID_VALID |
306 			  VA_FSID_UUID_VALID;
307 
308 	hammer2_inode_unlock_sh(ip, chain);
309 
310 	return (0);
311 }
312 
313 static
314 int
315 hammer2_vop_setattr(struct vop_setattr_args *ap)
316 {
317 	hammer2_inode_data_t *ipdata;
318 	hammer2_inode_t *ip;
319 	hammer2_mount_t *hmp;
320 	hammer2_chain_t *chain;
321 	hammer2_trans_t trans;
322 	struct vnode *vp;
323 	struct vattr *vap;
324 	int error;
325 	int kflags = 0;
326 	int domtime = 0;
327 	uint64_t ctime;
328 
329 	vp = ap->a_vp;
330 	vap = ap->a_vap;
331 	hammer2_update_time(&ctime);
332 
333 	ip = VTOI(vp);
334 	hmp = ip->hmp;
335 
336 	if (hmp->ronly)
337 		return(EROFS);
338 
339 	hammer2_trans_init(hmp, &trans, 0);
340 	chain = hammer2_inode_lock_ex(ip);
341 	ipdata = &chain->data->ipdata;
342 	error = 0;
343 
344 	if (vap->va_flags != VNOVAL) {
345 		u_int32_t flags;
346 
347 		flags = ipdata->uflags;
348 		error = vop_helper_setattr_flags(&flags, vap->va_flags,
349 					 hammer2_to_unix_xid(&ipdata->uid),
350 					 ap->a_cred);
351 		if (error == 0) {
352 			if (ipdata->uflags != flags) {
353 				ipdata = hammer2_chain_modify_ip(&trans, ip,
354 								 &chain, 0);
355 				ipdata->uflags = flags;
356 				ipdata->ctime = ctime;
357 				kflags |= NOTE_ATTRIB;
358 			}
359 			if (ipdata->uflags & (IMMUTABLE | APPEND)) {
360 				error = 0;
361 				goto done;
362 			}
363 		}
364 		goto done;
365 	}
366 	if (ipdata->uflags & (IMMUTABLE | APPEND)) {
367 		error = EPERM;
368 		goto done;
369 	}
370 	if (vap->va_uid != (uid_t)VNOVAL || vap->va_gid != (gid_t)VNOVAL) {
371 		mode_t cur_mode = ipdata->mode;
372 		uid_t cur_uid = hammer2_to_unix_xid(&ipdata->uid);
373 		gid_t cur_gid = hammer2_to_unix_xid(&ipdata->gid);
374 		uuid_t uuid_uid;
375 		uuid_t uuid_gid;
376 
377 		error = vop_helper_chown(ap->a_vp, vap->va_uid, vap->va_gid,
378 					 ap->a_cred,
379 					 &cur_uid, &cur_gid, &cur_mode);
380 		if (error == 0) {
381 			hammer2_guid_to_uuid(&uuid_uid, cur_uid);
382 			hammer2_guid_to_uuid(&uuid_gid, cur_gid);
383 			if (bcmp(&uuid_uid, &ipdata->uid, sizeof(uuid_uid)) ||
384 			    bcmp(&uuid_gid, &ipdata->gid, sizeof(uuid_gid)) ||
385 			    ipdata->mode != cur_mode
386 			) {
387 				ipdata = hammer2_chain_modify_ip(&trans, ip,
388 								 &chain, 0);
389 				ipdata->uid = uuid_uid;
390 				ipdata->gid = uuid_gid;
391 				ipdata->mode = cur_mode;
392 				ipdata->ctime = ctime;
393 			}
394 			kflags |= NOTE_ATTRIB;
395 		}
396 	}
397 
398 	/*
399 	 * Resize the file
400 	 */
401 	if (vap->va_size != VNOVAL && ipdata->size != vap->va_size) {
402 		switch(vp->v_type) {
403 		case VREG:
404 			if (vap->va_size == ipdata->size)
405 				break;
406 			if (vap->va_size < ipdata->size) {
407 				hammer2_truncate_file(&trans, ip,
408 						      &chain, vap->va_size);
409 			} else {
410 				hammer2_extend_file(&trans, ip,
411 						    &chain, vap->va_size);
412 			}
413 			ipdata = &chain->data->ipdata; /* RELOAD */
414 			domtime = 1;
415 			break;
416 		default:
417 			error = EINVAL;
418 			goto done;
419 		}
420 	}
421 #if 0
422 	/* atime not supported */
423 	if (vap->va_atime.tv_sec != VNOVAL) {
424 		ipdata = hammer2_chain_modify_ip(&trans, ip, &chain, 0);
425 		ipdata->atime = hammer2_timespec_to_time(&vap->va_atime);
426 		kflags |= NOTE_ATTRIB;
427 	}
428 #endif
429 	if (vap->va_mtime.tv_sec != VNOVAL) {
430 		ipdata = hammer2_chain_modify_ip(&trans, ip, &chain, 0);
431 		ipdata->mtime = hammer2_timespec_to_time(&vap->va_mtime);
432 		kflags |= NOTE_ATTRIB;
433 	}
434 	if (vap->va_mode != (mode_t)VNOVAL) {
435 		mode_t cur_mode = ipdata->mode;
436 		uid_t cur_uid = hammer2_to_unix_xid(&ipdata->uid);
437 		gid_t cur_gid = hammer2_to_unix_xid(&ipdata->gid);
438 
439 		error = vop_helper_chmod(ap->a_vp, vap->va_mode, ap->a_cred,
440 					 cur_uid, cur_gid, &cur_mode);
441 		if (error == 0 && ipdata->mode != cur_mode) {
442 			ipdata = hammer2_chain_modify_ip(&trans, ip, &chain, 0);
443 			ipdata->mode = cur_mode;
444 			ipdata->ctime = ctime;
445 			kflags |= NOTE_ATTRIB;
446 		}
447 	}
448 done:
449 	hammer2_inode_unlock_ex(ip, chain);
450 	hammer2_trans_done(&trans);
451 	return (error);
452 }
453 
454 static
455 int
456 hammer2_vop_readdir(struct vop_readdir_args *ap)
457 {
458 	hammer2_inode_data_t *ipdata;
459 	hammer2_mount_t *hmp;
460 	hammer2_inode_t *ip;
461 	hammer2_inode_t *xip;
462 	hammer2_chain_t *parent;
463 	hammer2_chain_t *chain;
464 	hammer2_chain_t *xchain;
465 	hammer2_tid_t inum;
466 	hammer2_key_t lkey;
467 	struct uio *uio;
468 	off_t *cookies;
469 	off_t saveoff;
470 	int cookie_index;
471 	int ncookies;
472 	int error;
473 	int dtype;
474 	int r;
475 
476 	ip = VTOI(ap->a_vp);
477 	hmp = ip->hmp;
478 	uio = ap->a_uio;
479 	saveoff = uio->uio_offset;
480 
481 	/*
482 	 * Setup cookies directory entry cookies if requested
483 	 */
484 	if (ap->a_ncookies) {
485 		ncookies = uio->uio_resid / 16 + 1;
486 		if (ncookies > 1024)
487 			ncookies = 1024;
488 		cookies = kmalloc(ncookies * sizeof(off_t), M_TEMP, M_WAITOK);
489 	} else {
490 		ncookies = -1;
491 		cookies = NULL;
492 	}
493 	cookie_index = 0;
494 
495 	parent = hammer2_inode_lock_sh(ip);
496 	ipdata = &parent->data->ipdata;
497 
498 	/*
499 	 * Handle artificial entries.  To ensure that only positive 64 bit
500 	 * quantities are returned to userland we always strip off bit 63.
501 	 * The hash code is designed such that codes 0x0000-0x7FFF are not
502 	 * used, allowing us to use these codes for articial entries.
503 	 *
504 	 * Entry 0 is used for '.' and entry 1 is used for '..'.  Do not
505 	 * allow '..' to cross the mount point into (e.g.) the super-root.
506 	 */
507 	error = 0;
508 	chain = (void *)(intptr_t)-1;	/* non-NULL for early goto done case */
509 
510 	if (saveoff == 0) {
511 		inum = ipdata->inum & HAMMER2_DIRHASH_USERMSK;
512 		r = vop_write_dirent(&error, uio, inum, DT_DIR, 1, ".");
513 		if (r)
514 			goto done;
515 		if (cookies)
516 			cookies[cookie_index] = saveoff;
517 		++saveoff;
518 		++cookie_index;
519 		if (cookie_index == ncookies)
520 			goto done;
521 	}
522 
523 	if (saveoff == 1) {
524 		/*
525 		 * Be careful with lockorder when accessing ".."
526 		 *
527 		 * (ip is the current dir. xip is the parent dir).
528 		 */
529 		inum = ipdata->inum & HAMMER2_DIRHASH_USERMSK;
530 		while (ip->pip != NULL && ip != ip->pmp->iroot) {
531 			xip = ip->pip;
532 			hammer2_inode_ref(xip);
533 			hammer2_inode_unlock_sh(ip, parent);
534 			xchain = hammer2_inode_lock_sh(xip);
535 			parent = hammer2_inode_lock_sh(ip);
536 			hammer2_inode_drop(xip);
537 			if (xip == ip->pip) {
538 				inum = xip->chain->data->ipdata.inum &
539 				       HAMMER2_DIRHASH_USERMSK;
540 				hammer2_inode_unlock_sh(xip, xchain);
541 				break;
542 			}
543 			hammer2_inode_unlock_sh(xip, xchain);
544 		}
545 		r = vop_write_dirent(&error, uio, inum, DT_DIR, 2, "..");
546 		if (r)
547 			goto done;
548 		if (cookies)
549 			cookies[cookie_index] = saveoff;
550 		++saveoff;
551 		++cookie_index;
552 		if (cookie_index == ncookies)
553 			goto done;
554 	}
555 
556 	lkey = saveoff | HAMMER2_DIRHASH_VISIBLE;
557 
558 	/*
559 	 * parent is the inode chain, already locked for us.  Don't
560 	 * double lock shared locks as this will screw up upgrades.
561 	 */
562 	if (error) {
563 		goto done;
564 	}
565 	chain = hammer2_chain_lookup(&parent, lkey, lkey,
566 				     HAMMER2_LOOKUP_SHARED);
567 	if (chain == NULL) {
568 		chain = hammer2_chain_lookup(&parent,
569 					     lkey, (hammer2_key_t)-1,
570 					     HAMMER2_LOOKUP_SHARED);
571 	}
572 	while (chain) {
573 		if (chain->bref.type == HAMMER2_BREF_TYPE_INODE) {
574 			dtype = hammer2_get_dtype(chain);
575 			saveoff = chain->bref.key & HAMMER2_DIRHASH_USERMSK;
576 			r = vop_write_dirent(&error, uio,
577 					     chain->data->ipdata.inum &
578 					      HAMMER2_DIRHASH_USERMSK,
579 					     dtype,
580 					     chain->data->ipdata.name_len,
581 					     chain->data->ipdata.filename);
582 			if (r)
583 				break;
584 			if (cookies)
585 				cookies[cookie_index] = saveoff;
586 			++cookie_index;
587 		} else {
588 			/* XXX chain error */
589 			kprintf("bad chain type readdir %d\n",
590 				chain->bref.type);
591 		}
592 
593 		/*
594 		 * Keys may not be returned in order so once we have a
595 		 * placemarker (chain) the scan must allow the full range
596 		 * or some entries will be missed.
597 		 */
598 		chain = hammer2_chain_next(&parent, chain,
599 					   HAMMER2_DIRHASH_VISIBLE,
600 					   (hammer2_key_t)-1,
601 					   HAMMER2_LOOKUP_SHARED);
602 		if (chain) {
603 			saveoff = (chain->bref.key &
604 				   HAMMER2_DIRHASH_USERMSK) + 1;
605 		} else {
606 			saveoff = (hammer2_key_t)-1;
607 		}
608 		if (cookie_index == ncookies)
609 			break;
610 	}
611 	if (chain)
612 		hammer2_chain_unlock(chain);
613 done:
614 	hammer2_inode_unlock_sh(ip, parent);
615 	if (ap->a_eofflag)
616 		*ap->a_eofflag = (chain == NULL);
617 	uio->uio_offset = saveoff & ~HAMMER2_DIRHASH_VISIBLE;
618 	if (error && cookie_index == 0) {
619 		if (cookies) {
620 			kfree(cookies, M_TEMP);
621 			*ap->a_ncookies = 0;
622 			*ap->a_cookies = NULL;
623 		}
624 	} else {
625 		if (cookies) {
626 			*ap->a_ncookies = cookie_index;
627 			*ap->a_cookies = cookies;
628 		}
629 	}
630 	return (error);
631 }
632 
633 /*
634  * hammer2_vop_readlink { vp, uio, cred }
635  */
636 static
637 int
638 hammer2_vop_readlink(struct vop_readlink_args *ap)
639 {
640 	struct vnode *vp;
641 	hammer2_mount_t *hmp;
642 	hammer2_inode_t *ip;
643 	int error;
644 
645 	vp = ap->a_vp;
646 	if (vp->v_type != VLNK)
647 		return (EINVAL);
648 	ip = VTOI(vp);
649 	hmp = ip->hmp;
650 
651 	error = hammer2_read_file(ip, ap->a_uio, 0);
652 	return (error);
653 }
654 
655 static
656 int
657 hammer2_vop_read(struct vop_read_args *ap)
658 {
659 	struct vnode *vp;
660 	hammer2_mount_t *hmp;
661 	hammer2_inode_t *ip;
662 	struct uio *uio;
663 	int error;
664 	int seqcount;
665 	int bigread;
666 
667 	/*
668 	 * Read operations supported on this vnode?
669 	 */
670 	vp = ap->a_vp;
671 	if (vp->v_type != VREG)
672 		return (EINVAL);
673 
674 	/*
675 	 * Misc
676 	 */
677 	ip = VTOI(vp);
678 	hmp = ip->hmp;
679 	uio = ap->a_uio;
680 	error = 0;
681 
682 	seqcount = ap->a_ioflag >> 16;
683 	bigread = (uio->uio_resid > 100 * 1024 * 1024);
684 
685 	error = hammer2_read_file(ip, uio, seqcount);
686 	return (error);
687 }
688 
689 static
690 int
691 hammer2_vop_write(struct vop_write_args *ap)
692 {
693 	hammer2_mount_t *hmp;
694 	hammer2_inode_t *ip;
695 	hammer2_trans_t trans;
696 	hammer2_chain_t *parent;
697 	thread_t td;
698 	struct vnode *vp;
699 	struct uio *uio;
700 	int error;
701 	int seqcount;
702 	int bigwrite;
703 
704 	/*
705 	 * Read operations supported on this vnode?
706 	 */
707 	vp = ap->a_vp;
708 	if (vp->v_type != VREG)
709 		return (EINVAL);
710 
711 	/*
712 	 * Misc
713 	 */
714 	ip = VTOI(vp);
715 	hmp = ip->hmp;
716 	uio = ap->a_uio;
717 	error = 0;
718 	if (hmp->ronly)
719 		return (EROFS);
720 
721 	seqcount = ap->a_ioflag >> 16;
722 	bigwrite = (uio->uio_resid > 100 * 1024 * 1024);
723 
724 	/*
725 	 * Check resource limit
726 	 */
727 	if (uio->uio_resid > 0 && (td = uio->uio_td) != NULL && td->td_proc &&
728 	    uio->uio_offset + uio->uio_resid >
729 	     td->td_proc->p_rlimit[RLIMIT_FSIZE].rlim_cur) {
730 		lwpsignal(td->td_proc, td->td_lwp, SIGXFSZ);
731 		return (EFBIG);
732 	}
733 
734 	bigwrite = (uio->uio_resid > 100 * 1024 * 1024);
735 
736 	/*
737 	 * ip must be locked if extending the file.
738 	 * ip must be locked to avoid racing a truncation.
739 	 *
740 	 * ip must be marked modified, particularly because the write
741 	 * might wind up being copied into the embedded data area.
742 	 */
743 	hammer2_trans_init(ip->hmp, &trans, 0);
744 	parent = hammer2_inode_lock_ex(ip);
745 	error = hammer2_write_file(&trans, ip, &parent,
746 				   uio, ap->a_ioflag, seqcount);
747 	hammer2_inode_unlock_ex(ip, parent);
748 	hammer2_trans_done(&trans);
749 
750 	return (error);
751 }
752 
753 /*
754  * Perform read operations on a file or symlink given an UNLOCKED
755  * inode and uio.
756  *
757  * The passed ip is not locked.
758  */
759 static
760 int
761 hammer2_read_file(hammer2_inode_t *ip, struct uio *uio, int seqcount)
762 {
763 	hammer2_off_t size;
764 	hammer2_chain_t *parent;
765 	struct buf *bp;
766 	int error;
767 
768 	error = 0;
769 
770 	/*
771 	 * UIO read loop.
772 	 */
773 	parent = hammer2_inode_lock_sh(ip);
774 	size = ip->chain->data->ipdata.size;
775 
776 	while (uio->uio_resid > 0 && uio->uio_offset < size) {
777 		hammer2_key_t lbase;
778 		hammer2_key_t leof;
779 		int lblksize;
780 		int loff;
781 		int n;
782 
783 		lblksize = hammer2_calc_logical(ip, uio->uio_offset,
784 						&lbase, &leof);
785 
786 		error = cluster_read(ip->vp, leof, lbase, lblksize,
787 				     uio->uio_resid, seqcount * BKVASIZE,
788 				     &bp);
789 
790 		if (error)
791 			break;
792 		loff = (int)(uio->uio_offset - lbase);
793 		n = lblksize - loff;
794 		if (n > uio->uio_resid)
795 			n = uio->uio_resid;
796 		if (n > size - uio->uio_offset)
797 			n = (int)(size - uio->uio_offset);
798 		bp->b_flags |= B_AGE;
799 		uiomove((char *)bp->b_data + loff, n, uio);
800 		bqrelse(bp);
801 	}
802 	hammer2_inode_unlock_sh(ip, parent);
803 	return (error);
804 }
805 
806 /*
807  * Called with a locked (ip) to do the underlying write to a file or
808  * to build the symlink target.
809  */
810 static
811 int
812 hammer2_write_file(hammer2_trans_t *trans, hammer2_inode_t *ip,
813 		   hammer2_chain_t **parentp,
814 		   struct uio *uio, int ioflag, int seqcount)
815 {
816 	hammer2_inode_data_t *ipdata;
817 	hammer2_key_t old_eof;
818 	struct buf *bp;
819 	int kflags;
820 	int error;
821 	int modified = 0;
822 
823 	/*
824 	 * Setup if append
825 	 */
826 	ipdata = &ip->chain->data->ipdata;
827 	if (ioflag & IO_APPEND)
828 		uio->uio_offset = ipdata->size;
829 	kflags = 0;
830 	error = 0;
831 
832 	/*
833 	 * vfs_sync visibility.  Interlocked by the inode ex lock so we
834 	 * shouldn't have to reassert it multiple times if the ip->chain
835 	 * is modified/flushed multiple times during the write, except
836 	 * when we release/reacquire the inode ex lock.
837 	 */
838 	atomic_set_int(&ip->flags, HAMMER2_INODE_MODIFIED);
839 
840 	/*
841 	 * Extend the file if necessary.  If the write fails at some point
842 	 * we will truncate it back down to cover as much as we were able
843 	 * to write.
844 	 *
845 	 * Doing this now makes it easier to calculate buffer sizes in
846 	 * the loop.
847 	 */
848 	KKASSERT(ipdata->type != HAMMER2_OBJTYPE_HARDLINK);
849 	old_eof = ipdata->size;
850 	if (uio->uio_offset + uio->uio_resid > ipdata->size) {
851 		modified = 1;
852 		hammer2_extend_file(trans, ip, parentp,
853 				    uio->uio_offset + uio->uio_resid);
854 		ipdata = &ip->chain->data->ipdata;	/* RELOAD */
855 		kflags |= NOTE_EXTEND;
856 	}
857 	KKASSERT(ipdata->type != HAMMER2_OBJTYPE_HARDLINK);
858 
859 	/*
860 	 * UIO write loop
861 	 */
862 	while (uio->uio_resid > 0) {
863 		hammer2_key_t lbase;
864 		hammer2_key_t leof;
865 		int trivial;
866 		int lblksize;
867 		int loff;
868 		int n;
869 
870 		/*
871 		 * Don't allow the buffer build to blow out the buffer
872 		 * cache.
873 		 */
874 		if ((ioflag & IO_RECURSE) == 0) {
875 			/*
876 			 * XXX should try to leave this unlocked through
877 			 *	the whole loop
878 			 */
879 			hammer2_inode_unlock_ex(ip, *parentp);
880 			bwillwrite(HAMMER2_PBUFSIZE);
881 			*parentp = hammer2_inode_lock_ex(ip);
882 			atomic_set_int(&ip->flags, HAMMER2_INODE_MODIFIED);
883 			ipdata = &ip->chain->data->ipdata;	/* reload */
884 		}
885 
886 		/* XXX bigwrite & signal check test */
887 
888 		/*
889 		 * This nominally tells us how much we can cluster and
890 		 * what the logical buffer size needs to be.  Currently
891 		 * we don't try to cluster the write and just handle one
892 		 * block at a time.
893 		 */
894 		lblksize = hammer2_calc_logical(ip, uio->uio_offset,
895 						&lbase, &leof);
896 		loff = (int)(uio->uio_offset - lbase);
897 
898 		/*
899 		 * Calculate bytes to copy this transfer and whether the
900 		 * copy completely covers the buffer or not.
901 		 */
902 		trivial = 0;
903 		n = lblksize - loff;
904 		if (n > uio->uio_resid) {
905 			n = uio->uio_resid;
906 			if (loff == lbase &&
907 			    uio->uio_offset + n == ipdata->size)
908 				trivial = 1;
909 		} else if (loff == 0) {
910 			trivial = 1;
911 		}
912 
913 		/*
914 		 * Get the buffer
915 		 */
916 		if (uio->uio_segflg == UIO_NOCOPY) {
917 			/*
918 			 * Issuing a write with the same data backing the
919 			 * buffer.  Instantiate the buffer to collect the
920 			 * backing vm pages, then read-in any missing bits.
921 			 *
922 			 * This case is used by vop_stdputpages().
923 			 */
924 			bp = getblk(ip->vp, lbase, lblksize, GETBLK_BHEAVY, 0);
925 			if ((bp->b_flags & B_CACHE) == 0) {
926 				bqrelse(bp);
927 				error = bread(ip->vp, lbase, lblksize, &bp);
928 			}
929 		} else if (trivial) {
930 			/*
931 			 * Even though we are entirely overwriting the buffer
932 			 * we may still have to zero it out to avoid a
933 			 * mmap/write visibility issue.
934 			 */
935 			bp = getblk(ip->vp, lbase, lblksize, GETBLK_BHEAVY, 0);
936 			if ((bp->b_flags & B_CACHE) == 0)
937 				vfs_bio_clrbuf(bp);
938 		} else {
939 			/*
940 			 * Partial overwrite, read in any missing bits then
941 			 * replace the portion being written.
942 			 *
943 			 * (The strategy code will detect zero-fill physical
944 			 * blocks for this case).
945 			 */
946 			error = bread(ip->vp, lbase, lblksize, &bp);
947 			if (error == 0)
948 				bheavy(bp);
949 		}
950 
951 		if (error) {
952 			brelse(bp);
953 			break;
954 		}
955 
956 		/*
957 		 * We have to assign physical storage to the buffer we intend
958 		 * to dirty or write now to avoid deadlocks in the strategy
959 		 * code later.
960 		 *
961 		 * This can return NOOFFSET for inode-embedded data.  The
962 		 * strategy code will take care of it in that case.
963 		 */
964 		bp->b_bio2.bio_offset =
965 			hammer2_assign_physical(trans, ip, parentp,
966 						lbase, lblksize, &error);
967 		ipdata = &ip->chain->data->ipdata;	/* RELOAD */
968 		if (error) {
969 			brelse(bp);
970 			break;
971 		}
972 
973 		/*
974 		 * Ok, copy the data in
975 		 */
976 		hammer2_inode_unlock_ex(ip, *parentp);
977 		error = uiomove(bp->b_data + loff, n, uio);
978 		*parentp = hammer2_inode_lock_ex(ip);
979 		atomic_set_int(&ip->flags, HAMMER2_INODE_MODIFIED);
980 		ipdata = &ip->chain->data->ipdata;	/* reload */
981 		kflags |= NOTE_WRITE;
982 		modified = 1;
983 
984 		if (error) {
985 			brelse(bp);
986 			break;
987 		}
988 
989 		/* XXX update ip_data.mtime */
990 
991 		/*
992 		 * Once we dirty a buffer any cached offset becomes invalid.
993 		 *
994 		 * NOTE: For cluster_write() always use the trailing block
995 		 *	 size, which is HAMMER2_PBUFSIZE.  lblksize is the
996 		 *	 eof-straddling blocksize and is incorrect.
997 		 */
998 		bp->b_flags |= B_AGE;
999 		if (lbase == 0 && (ipdata->op_flags &
1000 				   HAMMER2_OPFLAG_DIRECTDATA)) {
1001 			/*
1002 			 * Writing to the inode's embedded data must be
1003 			 * synchronous because the strategy code isn't
1004 			 * allowed to acquire chain locks.
1005 			 *
1006 			 * Deal with chain interactions here.
1007 			 */
1008 			ipdata = hammer2_chain_modify_ip(trans, ip, parentp, 0);
1009 			bwrite(bp);
1010 		} else if (ioflag & IO_SYNC) {
1011 			/*
1012 			 * Synchronous I/O requested.
1013 			 */
1014 			bwrite(bp);
1015 		} else if ((ioflag & IO_DIRECT) && loff + n == lblksize) {
1016 			if (bp->b_bcount == HAMMER2_PBUFSIZE)
1017 				bp->b_flags |= B_CLUSTEROK;
1018 			bdwrite(bp);
1019 		} else if (ioflag & IO_ASYNC) {
1020 			bawrite(bp);
1021 		} else if (hammer2_cluster_enable) {
1022 			if (bp->b_bcount == HAMMER2_PBUFSIZE)
1023 				bp->b_flags |= B_CLUSTEROK;
1024 			cluster_write(bp, leof, HAMMER2_PBUFSIZE, seqcount);
1025 		} else {
1026 			if (bp->b_bcount == HAMMER2_PBUFSIZE)
1027 				bp->b_flags |= B_CLUSTEROK;
1028 			bdwrite(bp);
1029 		}
1030 	}
1031 
1032 	/*
1033 	 * Cleanup.  If we extended the file EOF but failed to write through
1034 	 * the entire write is a failure and we have to back-up.
1035 	 */
1036 	if (error && ipdata->size != old_eof) {
1037 		hammer2_truncate_file(trans, ip, parentp, old_eof);
1038 		ipdata = &ip->chain->data->ipdata;	/* RELOAD */
1039 	} else if (modified) {
1040 		ipdata = hammer2_chain_modify_ip(trans, ip, parentp, 0);
1041 		hammer2_update_time(&ipdata->mtime);
1042 	}
1043 	hammer2_knote(ip->vp, kflags);
1044 
1045 	return error;
1046 }
1047 
1048 /*
1049  * Assign physical storage to a logical block.  This function creates the
1050  * related meta-data chains representing the data blocks and marks them
1051  * MODIFIED.  We could mark them MOVED instead but ultimately I need to
1052  * XXX code the flusher to check that the related logical buffer is
1053  * flushed.
1054  *
1055  * NOOFFSET is returned if the data is inode-embedded.  In this case the
1056  * strategy code will simply bcopy() the data into the inode.
1057  *
1058  * The inode's delta_dcount is adjusted.
1059  */
1060 static
1061 hammer2_off_t
1062 hammer2_assign_physical(hammer2_trans_t *trans, hammer2_inode_t *ip,
1063 			hammer2_chain_t **parentp,
1064 			hammer2_key_t lbase, int lblksize, int *errorp)
1065 {
1066 	hammer2_mount_t *hmp;
1067 	hammer2_chain_t *parent;
1068 	hammer2_chain_t *chain;
1069 	hammer2_off_t pbase;
1070 
1071 	/*
1072 	 * Locate the chain associated with lbase, return a locked chain.
1073 	 * However, do not instantiate any data reference (which utilizes a
1074 	 * device buffer) because we will be using direct IO via the
1075 	 * logical buffer cache buffer.
1076 	 */
1077 	hmp = ip->hmp;
1078 	*errorp = 0;
1079 retry:
1080 	parent = *parentp;
1081 	hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS); /* extra lock */
1082 	chain = hammer2_chain_lookup(&parent,
1083 				     lbase, lbase,
1084 				     HAMMER2_LOOKUP_NODATA);
1085 
1086 	if (chain == NULL) {
1087 		/*
1088 		 * We found a hole, create a new chain entry.
1089 		 *
1090 		 * NOTE: DATA chains are created without device backing
1091 		 *	 store (nor do we want any).
1092 		 */
1093 		*errorp = hammer2_chain_create(trans, &parent, &chain,
1094 					       lbase, HAMMER2_PBUFRADIX,
1095 					       HAMMER2_BREF_TYPE_DATA,
1096 					       lblksize);
1097 		if (chain == NULL) {
1098 			hammer2_chain_lookup_done(parent);
1099 			panic("hammer2_chain_create: par=%p error=%d\n",
1100 				parent, *errorp);
1101 			goto retry;
1102 		}
1103 
1104 		pbase = chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX;
1105 		/*ip->delta_dcount += lblksize;*/
1106 	} else {
1107 		switch (chain->bref.type) {
1108 		case HAMMER2_BREF_TYPE_INODE:
1109 			/*
1110 			 * The data is embedded in the inode.  The
1111 			 * caller is responsible for marking the inode
1112 			 * modified and copying the data to the embedded
1113 			 * area.
1114 			 */
1115 			pbase = NOOFFSET;
1116 			break;
1117 		case HAMMER2_BREF_TYPE_DATA:
1118 			if (chain->bytes != lblksize) {
1119 				panic("hammer2_assign_physical: "
1120 				      "size mismatch %d/%d\n",
1121 				      lblksize, chain->bytes);
1122 			}
1123 			hammer2_chain_modify(trans, &chain,
1124 					     HAMMER2_MODIFY_OPTDATA);
1125 			pbase = chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX;
1126 			break;
1127 		default:
1128 			panic("hammer2_assign_physical: bad type");
1129 			/* NOT REACHED */
1130 			pbase = NOOFFSET;
1131 			break;
1132 		}
1133 	}
1134 
1135 	/*
1136 	 * Cleanup.  If chain wound up being the inode (i.e. DIRECTDATA),
1137 	 * we might have to replace *parentp.
1138 	 */
1139 	hammer2_chain_lookup_done(parent);
1140 	if (chain) {
1141 		if (*parentp != chain &&
1142 		    (*parentp)->core == chain->core) {
1143 			parent = *parentp;
1144 			*parentp = chain;
1145 			hammer2_chain_unlock(parent);
1146 		} else {
1147 			hammer2_chain_unlock(chain);
1148 		}
1149 	}
1150 
1151 	return (pbase);
1152 }
1153 
1154 /*
1155  * Truncate the size of a file.
1156  *
1157  * This routine adjusts ipdata->size smaller, destroying any related
1158  * data beyond the new EOF and potentially resizing the block straddling
1159  * the EOF.
1160  *
1161  * The inode must be locked.
1162  */
1163 static
1164 void
1165 hammer2_truncate_file(hammer2_trans_t *trans, hammer2_inode_t *ip,
1166 		      hammer2_chain_t **parentp, hammer2_key_t nsize)
1167 {
1168 	hammer2_inode_data_t *ipdata;
1169 	hammer2_chain_t *parent;
1170 	hammer2_chain_t *chain;
1171 	hammer2_key_t lbase;
1172 	hammer2_key_t leof;
1173 	struct buf *bp;
1174 	int loff;
1175 	int error;
1176 	int oblksize;
1177 	int nblksize;
1178 
1179 	bp = NULL;
1180 	error = 0;
1181 	ipdata = hammer2_chain_modify_ip(trans, ip, parentp, 0);
1182 
1183 	/*
1184 	 * Destroy any logical buffer cache buffers beyond the file EOF.
1185 	 *
1186 	 * We call nvtruncbuf() w/ trivial == 1 to prevent it from messing
1187 	 * around with the buffer straddling EOF, because we need to assign
1188 	 * a new physical offset to it.
1189 	 */
1190 	if (ip->vp) {
1191 		nvtruncbuf(ip->vp, nsize,
1192 			   HAMMER2_PBUFSIZE, (int)nsize & HAMMER2_PBUFMASK,
1193 			   1);
1194 	}
1195 
1196 	/*
1197 	 * Setup for lookup/search
1198 	 */
1199 	parent = hammer2_chain_lookup_init(ip->chain, 0);
1200 
1201 	/*
1202 	 * Handle the case where a chain/logical-buffer straddles the new
1203 	 * EOF.  We told nvtruncbuf() above not to mess with the logical
1204 	 * buffer straddling the EOF because we need to reassign its storage
1205 	 * and can't let the strategy code do it for us.
1206 	 */
1207 	loff = (int)nsize & HAMMER2_PBUFMASK;
1208 	if (loff && ip->vp) {
1209 		oblksize = hammer2_calc_logical(ip, nsize, &lbase, &leof);
1210 		error = bread(ip->vp, lbase, oblksize, &bp);
1211 		KKASSERT(error == 0);
1212 	}
1213 	ipdata->size = nsize;
1214 	nblksize = hammer2_calc_logical(ip, nsize, &lbase, &leof);
1215 
1216 	/*
1217 	 * Fixup the chain element.  If we have a logical buffer in-hand
1218 	 * we don't want to create a conflicting device buffer.
1219 	 */
1220 	if (loff && bp) {
1221 		chain = hammer2_chain_lookup(&parent, lbase, lbase,
1222 					     HAMMER2_LOOKUP_NODATA);
1223 		if (chain) {
1224 			switch(chain->bref.type) {
1225 			case HAMMER2_BREF_TYPE_DATA:
1226 				hammer2_chain_resize(trans, ip, bp,
1227 					     parent, &chain,
1228 					     hammer2_allocsize(nblksize),
1229 					     HAMMER2_MODIFY_OPTDATA);
1230 				allocbuf(bp, nblksize);
1231 				bzero(bp->b_data + loff, nblksize - loff);
1232 				bp->b_bio2.bio_offset = chain->bref.data_off &
1233 							HAMMER2_OFF_MASK;
1234 				break;
1235 			case HAMMER2_BREF_TYPE_INODE:
1236 				allocbuf(bp, nblksize);
1237 				bzero(bp->b_data + loff, nblksize - loff);
1238 				bp->b_bio2.bio_offset = NOOFFSET;
1239 				break;
1240 			default:
1241 				panic("hammer2_truncate_file: bad type");
1242 				break;
1243 			}
1244 			hammer2_chain_unlock(chain);
1245 			if (lbase == 0 &&
1246 			    (ipdata->op_flags & HAMMER2_OPFLAG_DIRECTDATA)) {
1247 				/*
1248 				 * Must be synchronous if writing to the
1249 				 * inode's embedded data area.
1250 				 */
1251 				bwrite(bp);
1252 			} else {
1253 				/*
1254 				 * Else a delayed-write is fine.
1255 				 */
1256 				if (bp->b_bcount == HAMMER2_PBUFSIZE)
1257 					bp->b_flags |= B_CLUSTEROK;
1258 				bdwrite(bp);
1259 			}
1260 		} else {
1261 			/*
1262 			 * Destroy clean buffer w/ wrong buffer size.  Retain
1263 			 * backing store.
1264 			 */
1265 			bp->b_flags |= B_RELBUF;
1266 			KKASSERT(bp->b_bio2.bio_offset == NOOFFSET);
1267 			KKASSERT((bp->b_flags & B_DIRTY) == 0);
1268 			bqrelse(bp);
1269 		}
1270 	} else if (loff) {
1271 		/*
1272 		 * WARNING: This utilizes a device buffer for the data.
1273 		 *
1274 		 * This case should not occur because file truncations without
1275 		 * a vnode (and hence no logical buffer cache) should only
1276 		 * always truncate to 0-length.
1277 		 */
1278 		panic("hammer2_truncate_file: non-zero truncation, no-vnode");
1279 #if 0
1280 		chain = hammer2_chain_lookup(&parent, lbase, lbase, 0);
1281 		if (chain) {
1282 			switch(chain->bref.type) {
1283 			case HAMMER2_BREF_TYPE_DATA:
1284 				chain = hammer2_chain_resize(trans, ip, bp,
1285 					     parent, chain,
1286 					     hammer2_allocsize(nblksize),
1287 					     0);
1288 				hammer2_chain_modify(hmp, &chain, 0);
1289 				bzero(chain->data->buf + loff, nblksize - loff);
1290 				break;
1291 			case HAMMER2_BREF_TYPE_INODE:
1292 				if (loff < HAMMER2_EMBEDDED_BYTES) {
1293 					hammer2_chain_modify(hmp, &chain, 0);
1294 					bzero(chain->data->ipdata.u.data + loff,
1295 					      HAMMER2_EMBEDDED_BYTES - loff);
1296 				}
1297 				break;
1298 			}
1299 			hammer2_chain_unlock(chain);
1300 		}
1301 #endif
1302 	}
1303 
1304 	/*
1305 	 * Clean up any fragmentory VM pages now that we have properly
1306 	 * resized the straddling buffer.  These pages are no longer
1307 	 * part of the buffer.
1308 	 */
1309 	if (ip->vp) {
1310 		nvtruncbuf(ip->vp, nsize,
1311 			   nblksize, (int)nsize & (nblksize - 1),
1312 			   1);
1313 	}
1314 
1315 	/*
1316 	 * Destroy any physical blocks after the new EOF point.
1317 	 */
1318 	lbase = (nsize + HAMMER2_PBUFMASK64) & ~HAMMER2_PBUFMASK64;
1319 	chain = hammer2_chain_lookup(&parent,
1320 				     lbase, (hammer2_key_t)-1,
1321 				     HAMMER2_LOOKUP_NODATA);
1322 	while (chain) {
1323 		/*
1324 		 * Degenerate embedded data case, nothing to loop on.
1325 		 */
1326 		if (chain->bref.type == HAMMER2_BREF_TYPE_INODE) {
1327 			hammer2_chain_unlock(chain);
1328 			break;
1329 		}
1330 
1331 		/*
1332 		 * Delete physical data blocks past the file EOF.
1333 		 */
1334 		if (chain->bref.type == HAMMER2_BREF_TYPE_DATA) {
1335 			/*ip->delta_dcount -= chain->bytes;*/
1336 			hammer2_chain_delete(trans, chain);
1337 		}
1338 		/* XXX check parent if empty indirect block & delete */
1339 		chain = hammer2_chain_next(&parent, chain,
1340 					   lbase, (hammer2_key_t)-1,
1341 					   HAMMER2_LOOKUP_NODATA);
1342 	}
1343 	hammer2_chain_lookup_done(parent);
1344 }
1345 
1346 /*
1347  * Extend the size of a file.  The inode must be locked.
1348  *
1349  * We may have to resize the block straddling the old EOF.
1350  */
1351 static
1352 void
1353 hammer2_extend_file(hammer2_trans_t *trans, hammer2_inode_t *ip,
1354 		    hammer2_chain_t **parentp, hammer2_key_t nsize)
1355 {
1356 	hammer2_inode_data_t *ipdata;
1357 	hammer2_mount_t *hmp;
1358 	hammer2_chain_t *parent;
1359 	hammer2_chain_t *chain;
1360 	struct buf *bp;
1361 	hammer2_key_t osize;
1362 	hammer2_key_t obase;
1363 	hammer2_key_t nbase;
1364 	hammer2_key_t leof;
1365 	int oblksize;
1366 	int nblksize;
1367 	int nradix;
1368 	int error;
1369 
1370 	KKASSERT(ip->vp);
1371 	hmp = ip->hmp;
1372 
1373 	ipdata = hammer2_chain_modify_ip(trans, ip, parentp, 0);
1374 
1375 	/*
1376 	 * Nothing to do if the direct-data case is still intact
1377 	 */
1378 	if ((ipdata->op_flags & HAMMER2_OPFLAG_DIRECTDATA) &&
1379 	    nsize <= HAMMER2_EMBEDDED_BYTES) {
1380 		ipdata->size = nsize;
1381 		nvextendbuf(ip->vp,
1382 			    ipdata->size, nsize,
1383 			    0, HAMMER2_EMBEDDED_BYTES,
1384 			    0, (int)nsize,
1385 			    1);
1386 		/* ipdata = &ip->chain->data->ipdata; RELOAD */
1387 		return;
1388 	}
1389 
1390 	/*
1391 	 * Calculate the blocksize at the original EOF and resize the block
1392 	 * if necessary.  Adjust the file size in the inode.
1393 	 */
1394 	osize = ipdata->size;
1395 	oblksize = hammer2_calc_logical(ip, osize, &obase, &leof);
1396 	ipdata->size = nsize;
1397 	nblksize = hammer2_calc_logical(ip, osize, &nbase, &leof);
1398 
1399 	/*
1400 	 * Do all required vnode operations, but do not mess with the
1401 	 * buffer straddling the orignal EOF.
1402 	 */
1403 	nvextendbuf(ip->vp,
1404 		    ipdata->size, nsize,
1405 		    0, nblksize,
1406 		    0, (int)nsize & HAMMER2_PBUFMASK,
1407 		    1);
1408 	ipdata = &ip->chain->data->ipdata;
1409 
1410 	/*
1411 	 * Early return if we have no more work to do.
1412 	 */
1413 	if (obase == nbase && oblksize == nblksize &&
1414 	    (ipdata->op_flags & HAMMER2_OPFLAG_DIRECTDATA) == 0) {
1415 		return;
1416 	}
1417 
1418 	/*
1419 	 * We have work to do, including possibly resizing the buffer
1420 	 * at the previous EOF point and turning off DIRECTDATA mode.
1421 	 */
1422 	bp = NULL;
1423 	if (((int)osize & HAMMER2_PBUFMASK)) {
1424 		error = bread(ip->vp, obase, oblksize, &bp);
1425 		KKASSERT(error == 0);
1426 	}
1427 
1428 	/*
1429 	 * Disable direct-data mode by loading up a buffer cache buffer
1430 	 * with the data, then converting the inode data area into the
1431 	 * inode indirect block array area.
1432 	 */
1433 	if (ipdata->op_flags & HAMMER2_OPFLAG_DIRECTDATA) {
1434 		ipdata->op_flags &= ~HAMMER2_OPFLAG_DIRECTDATA;
1435 		bzero(&ipdata->u.blockset, sizeof(ipdata->u.blockset));
1436 	}
1437 
1438 	/*
1439 	 * Resize the chain element at the old EOF.
1440 	 */
1441 	if (((int)osize & HAMMER2_PBUFMASK)) {
1442 retry:
1443 		error = 0;
1444 		parent = hammer2_chain_lookup_init(ip->chain, 0);
1445 		nradix = hammer2_allocsize(nblksize);
1446 
1447 		chain = hammer2_chain_lookup(&parent,
1448 					     obase, obase,
1449 					     HAMMER2_LOOKUP_NODATA);
1450 		if (chain == NULL) {
1451 			error = hammer2_chain_create(trans, &parent, &chain,
1452 						     obase, nblksize,
1453 						     HAMMER2_BREF_TYPE_DATA,
1454 						     nblksize);
1455 			if (chain == NULL) {
1456 				hammer2_chain_lookup_done(parent);
1457 				panic("hammer2_chain_create: par=%p error=%d\n",
1458 					parent, error);
1459 				goto retry;
1460 			}
1461 			/*ip->delta_dcount += nblksize;*/
1462 		} else {
1463 			KKASSERT(chain->bref.type == HAMMER2_BREF_TYPE_DATA);
1464 			hammer2_chain_resize(trans, ip, bp,
1465 					     parent, &chain,
1466 					     nradix,
1467 					     HAMMER2_MODIFY_OPTDATA);
1468 		}
1469 		if (obase != nbase) {
1470 			if (oblksize != HAMMER2_PBUFSIZE)
1471 				allocbuf(bp, HAMMER2_PBUFSIZE);
1472 		} else {
1473 			if (oblksize != nblksize)
1474 				allocbuf(bp, nblksize);
1475 		}
1476 		bp->b_bio2.bio_offset = chain->bref.data_off &
1477 					HAMMER2_OFF_MASK;
1478 		hammer2_chain_unlock(chain);
1479 		if (bp->b_bcount == HAMMER2_PBUFSIZE)
1480 			bp->b_flags |= B_CLUSTEROK;
1481 		bdwrite(bp);
1482 		hammer2_chain_lookup_done(parent);  /* must be after bdwrite */
1483 	}
1484 }
1485 
1486 static
1487 int
1488 hammer2_vop_nresolve(struct vop_nresolve_args *ap)
1489 {
1490 	hammer2_inode_t *ip;
1491 	hammer2_inode_t *dip;
1492 	hammer2_mount_t *hmp;
1493 	hammer2_chain_t *parent;
1494 	hammer2_chain_t *chain;
1495 	hammer2_chain_t *ochain;
1496 	hammer2_trans_t trans;
1497 	struct namecache *ncp;
1498 	const uint8_t *name;
1499 	size_t name_len;
1500 	hammer2_key_t lhc;
1501 	int error = 0;
1502 	struct vnode *vp;
1503 
1504 	dip = VTOI(ap->a_dvp);
1505 	hmp = dip->hmp;
1506 	ncp = ap->a_nch->ncp;
1507 	name = ncp->nc_name;
1508 	name_len = ncp->nc_nlen;
1509 	lhc = hammer2_dirhash(name, name_len);
1510 
1511 	/*
1512 	 * Note: In DragonFly the kernel handles '.' and '..'.
1513 	 */
1514 	parent = hammer2_inode_lock_sh(dip);
1515 	chain = hammer2_chain_lookup(&parent,
1516 				     lhc, lhc + HAMMER2_DIRHASH_LOMASK,
1517 				     HAMMER2_LOOKUP_SHARED);
1518 	while (chain) {
1519 		if (chain->bref.type == HAMMER2_BREF_TYPE_INODE &&
1520 		    name_len == chain->data->ipdata.name_len &&
1521 		    bcmp(name, chain->data->ipdata.filename, name_len) == 0) {
1522 			break;
1523 		}
1524 		chain = hammer2_chain_next(&parent, chain,
1525 					   lhc, lhc + HAMMER2_DIRHASH_LOMASK,
1526 					   HAMMER2_LOOKUP_SHARED);
1527 	}
1528 	hammer2_inode_unlock_sh(dip, parent);
1529 
1530 	/*
1531 	 * If the inode represents a forwarding entry for a hardlink we have
1532 	 * to locate the actual inode.  The original ip is saved for possible
1533 	 * deconsolidation.  (ip) will only be set to non-NULL when we have
1534 	 * to locate the real file via a hardlink.  ip will be referenced but
1535 	 * not locked in that situation.  chain is passed in locked and
1536 	 * returned locked.
1537 	 *
1538 	 * XXX what kind of chain lock?
1539 	 */
1540 	ochain = NULL;
1541 	if (chain && chain->data->ipdata.type == HAMMER2_OBJTYPE_HARDLINK) {
1542 		error = hammer2_hardlink_find(dip, &chain, &ochain);
1543 		if (error) {
1544 			kprintf("hammer2: unable to find hardlink\n");
1545 			if (chain) {
1546 				hammer2_chain_unlock(chain);
1547 				chain = NULL;
1548 			}
1549 			goto failed;
1550 		}
1551 	}
1552 
1553 	/*
1554 	 * Deconsolidate any hardlink whos nlinks == 1.  Ignore errors.
1555 	 * If an error occurs chain and ip are left alone.
1556 	 *
1557 	 * XXX upgrade shared lock?
1558 	 */
1559 	if (ochain && chain && chain->data->ipdata.nlinks == 1 && !hmp->ronly) {
1560 		kprintf("hammer2: need to unconsolidate hardlink for %s\n",
1561 			chain->data->ipdata.filename);
1562 		/* XXX retain shared lock on dip? (currently not held) */
1563 		hammer2_trans_init(dip->hmp, &trans, 0);
1564 		hammer2_hardlink_deconsolidate(&trans, dip, &chain, &ochain);
1565 		hammer2_trans_done(&trans);
1566 	}
1567 
1568 	/*
1569 	 * Acquire the related vnode
1570 	 *
1571 	 * NOTE: For error processing, only ENOENT resolves the namecache
1572 	 *	 entry to NULL, otherwise we just return the error and
1573 	 *	 leave the namecache unresolved.
1574 	 *
1575 	 * NOTE: multiple hammer2_inode structures can be aliased to the
1576 	 *	 same chain element, for example for hardlinks.  This
1577 	 *	 use case does not 'reattach' inode associations that
1578 	 *	 might already exist, but always allocates a new one.
1579 	 *
1580 	 * WARNING: inode structure is locked exclusively via inode_get
1581 	 *	    but chain was locked shared.  inode_unlock_ex()
1582 	 *	    will handle it properly.
1583 	 */
1584 	if (chain) {
1585 		ip = hammer2_inode_get(hmp, dip->pmp, dip, chain);
1586 		vp = hammer2_igetv(ip, &error);
1587 		if (error == 0) {
1588 			vn_unlock(vp);
1589 			cache_setvp(ap->a_nch, vp);
1590 		} else if (error == ENOENT) {
1591 			cache_setvp(ap->a_nch, NULL);
1592 		}
1593 		hammer2_inode_unlock_ex(ip, chain);
1594 
1595 		/*
1596 		 * The vp should not be released until after we've disposed
1597 		 * of our locks, because it might cause vop_inactive() to
1598 		 * be called.
1599 		 */
1600 		if (vp)
1601 			vrele(vp);
1602 	} else {
1603 		error = ENOENT;
1604 		cache_setvp(ap->a_nch, NULL);
1605 	}
1606 failed:
1607 	KASSERT(error || ap->a_nch->ncp->nc_vp != NULL,
1608 		("resolve error %d/%p chain %p ap %p\n",
1609 		 error, ap->a_nch->ncp->nc_vp, chain, ap));
1610 	if (ochain)
1611 		hammer2_chain_drop(ochain);
1612 	return error;
1613 }
1614 
1615 static
1616 int
1617 hammer2_vop_nlookupdotdot(struct vop_nlookupdotdot_args *ap)
1618 {
1619 	hammer2_inode_t *dip;
1620 	hammer2_inode_t *ip;
1621 	hammer2_mount_t *hmp;
1622 	hammer2_chain_t *parent;
1623 	int error;
1624 
1625 	dip = VTOI(ap->a_dvp);
1626 	hmp = dip->hmp;
1627 
1628 	if ((ip = dip->pip) == NULL) {
1629 		*ap->a_vpp = NULL;
1630 		return ENOENT;
1631 	}
1632 	parent = hammer2_inode_lock_ex(ip);
1633 	*ap->a_vpp = hammer2_igetv(ip, &error);
1634 	hammer2_inode_unlock_ex(ip, parent);
1635 
1636 	return error;
1637 }
1638 
1639 static
1640 int
1641 hammer2_vop_nmkdir(struct vop_nmkdir_args *ap)
1642 {
1643 	hammer2_mount_t *hmp;
1644 	hammer2_inode_t *dip;
1645 	hammer2_inode_t *nip;
1646 	hammer2_trans_t trans;
1647 	hammer2_chain_t *chain;
1648 	struct namecache *ncp;
1649 	const uint8_t *name;
1650 	size_t name_len;
1651 	int error;
1652 
1653 	dip = VTOI(ap->a_dvp);
1654 	hmp = dip->hmp;
1655 	if (hmp->ronly)
1656 		return (EROFS);
1657 
1658 	ncp = ap->a_nch->ncp;
1659 	name = ncp->nc_name;
1660 	name_len = ncp->nc_nlen;
1661 
1662 	hammer2_trans_init(hmp, &trans, 0);
1663 	nip = hammer2_inode_create(&trans, dip, ap->a_vap, ap->a_cred,
1664 				   name, name_len, &chain, &error);
1665 	if (error) {
1666 		KKASSERT(nip == NULL);
1667 		*ap->a_vpp = NULL;
1668 	} else {
1669 		*ap->a_vpp = hammer2_igetv(nip, &error);
1670 		hammer2_inode_unlock_ex(nip, chain);
1671 	}
1672 	hammer2_trans_done(&trans);
1673 
1674 	if (error == 0) {
1675 		cache_setunresolved(ap->a_nch);
1676 		cache_setvp(ap->a_nch, *ap->a_vpp);
1677 	}
1678 	return error;
1679 }
1680 
1681 /*
1682  * Return the largest contiguous physical disk range for the logical
1683  * request.
1684  *
1685  * (struct vnode *vp, off_t loffset, off_t *doffsetp, int *runp, int *runb)
1686  */
1687 static
1688 int
1689 hammer2_vop_bmap(struct vop_bmap_args *ap)
1690 {
1691 	struct vnode *vp;
1692 	hammer2_mount_t *hmp;
1693 	hammer2_inode_t *ip;
1694 	hammer2_chain_t *parent;
1695 	hammer2_chain_t *chain;
1696 	hammer2_key_t lbeg;
1697 	hammer2_key_t lend;
1698 	hammer2_off_t pbeg;
1699 	hammer2_off_t pbytes;
1700 	hammer2_off_t array[HAMMER2_BMAP_COUNT][2];
1701 	int loff;
1702 	int ai;
1703 
1704 	/*
1705 	 * Only supported on regular files
1706 	 *
1707 	 * Only supported for read operations (required for cluster_read).
1708 	 * The block allocation is delayed for write operations.
1709 	 */
1710 	vp = ap->a_vp;
1711 	if (vp->v_type != VREG)
1712 		return (EOPNOTSUPP);
1713 	if (ap->a_cmd != BUF_CMD_READ)
1714 		return (EOPNOTSUPP);
1715 
1716 	ip = VTOI(vp);
1717 	hmp = ip->hmp;
1718 	bzero(array, sizeof(array));
1719 
1720 	/*
1721 	 * Calculate logical range
1722 	 */
1723 	KKASSERT((ap->a_loffset & HAMMER2_LBUFMASK64) == 0);
1724 	lbeg = ap->a_loffset & HAMMER2_OFF_MASK_HI;
1725 	lend = lbeg + HAMMER2_BMAP_COUNT * HAMMER2_PBUFSIZE - 1;
1726 	if (lend < lbeg)
1727 		lend = lbeg;
1728 	loff = ap->a_loffset & HAMMER2_OFF_MASK_LO;
1729 
1730 	parent = hammer2_inode_lock_sh(ip);
1731 	chain = hammer2_chain_lookup(&parent,
1732 				     lbeg, lend,
1733 				     HAMMER2_LOOKUP_NODATA |
1734 				     HAMMER2_LOOKUP_SHARED);
1735 	if (chain == NULL) {
1736 		*ap->a_doffsetp = ZFOFFSET;
1737 		hammer2_inode_unlock_sh(ip, parent);
1738 		return (0);
1739 	}
1740 
1741 	while (chain) {
1742 		if (chain->bref.type == HAMMER2_BREF_TYPE_DATA) {
1743 			ai = (chain->bref.key - lbeg) / HAMMER2_PBUFSIZE;
1744 			KKASSERT(ai >= 0 && ai < HAMMER2_BMAP_COUNT);
1745 			array[ai][0] = chain->bref.data_off & HAMMER2_OFF_MASK;
1746 			array[ai][1] = chain->bytes;
1747 		}
1748 		chain = hammer2_chain_next(&parent, chain,
1749 					   lbeg, lend,
1750 					   HAMMER2_LOOKUP_NODATA |
1751 					   HAMMER2_LOOKUP_SHARED);
1752 	}
1753 	hammer2_inode_unlock_sh(ip, parent);
1754 
1755 	/*
1756 	 * If the requested loffset is not mappable physically we can't
1757 	 * bmap.  The caller will have to access the file data via a
1758 	 * device buffer.
1759 	 */
1760 	if (array[0][0] == 0 || array[0][1] < loff + HAMMER2_LBUFSIZE) {
1761 		*ap->a_doffsetp = NOOFFSET;
1762 		return (0);
1763 	}
1764 
1765 	/*
1766 	 * Calculate the physical disk offset range for array[0]
1767 	 */
1768 	pbeg = array[0][0] + loff;
1769 	pbytes = array[0][1] - loff;
1770 
1771 	for (ai = 1; ai < HAMMER2_BMAP_COUNT; ++ai) {
1772 		if (array[ai][0] != pbeg + pbytes)
1773 			break;
1774 		pbytes += array[ai][1];
1775 	}
1776 
1777 	*ap->a_doffsetp = pbeg;
1778 	if (ap->a_runp)
1779 		*ap->a_runp = pbytes;
1780 	return (0);
1781 }
1782 
1783 static
1784 int
1785 hammer2_vop_open(struct vop_open_args *ap)
1786 {
1787 	return vop_stdopen(ap);
1788 }
1789 
1790 /*
1791  * hammer2_vop_advlock { vp, id, op, fl, flags }
1792  */
1793 static
1794 int
1795 hammer2_vop_advlock(struct vop_advlock_args *ap)
1796 {
1797 	hammer2_inode_t *ip = VTOI(ap->a_vp);
1798 	hammer2_chain_t *parent;
1799 	hammer2_off_t size;
1800 
1801 	parent = hammer2_inode_lock_sh(ip);
1802 	size = parent->data->ipdata.size;
1803 	hammer2_inode_unlock_sh(ip, parent);
1804 	return (lf_advlock(ap, &ip->advlock, size));
1805 }
1806 
1807 
1808 static
1809 int
1810 hammer2_vop_close(struct vop_close_args *ap)
1811 {
1812 	return vop_stdclose(ap);
1813 }
1814 
1815 /*
1816  * hammer2_vop_nlink { nch, dvp, vp, cred }
1817  *
1818  * Create a hardlink from (vp) to {dvp, nch}.
1819  */
1820 static
1821 int
1822 hammer2_vop_nlink(struct vop_nlink_args *ap)
1823 {
1824 	hammer2_inode_t *dip;	/* target directory to create link in */
1825 	hammer2_inode_t *ip;	/* inode we are hardlinking to */
1826 	hammer2_mount_t *hmp;
1827 	hammer2_chain_t *chain;
1828 	hammer2_trans_t trans;
1829 	struct namecache *ncp;
1830 	const uint8_t *name;
1831 	size_t name_len;
1832 	int error;
1833 
1834 	dip = VTOI(ap->a_dvp);
1835 	hmp = dip->hmp;
1836 	if (hmp->ronly)
1837 		return (EROFS);
1838 
1839 	ncp = ap->a_nch->ncp;
1840 	name = ncp->nc_name;
1841 	name_len = ncp->nc_nlen;
1842 	hammer2_trans_init(hmp, &trans, 0);
1843 
1844 	/*
1845 	 * ip represents the file being hardlinked.  The file could be a
1846 	 * normal file or a hardlink target if it has already been hardlinked.
1847 	 * If ip is a hardlinked target then ip->pip represents the location
1848 	 * of the hardlinked target, NOT the location of the hardlink pointer.
1849 	 *
1850 	 * Bump nlinks and potentially also create or move the hardlink
1851 	 * target in the parent directory common to (ip) and (dip).  The
1852 	 * consolidation code can modify ip->chain and ip->pip.  The
1853 	 * returned chain is locked.
1854 	 */
1855 	ip = VTOI(ap->a_vp);
1856 	chain = hammer2_inode_lock_ex(ip);
1857 	error = hammer2_hardlink_consolidate(&trans, ip, &chain, dip, 1);
1858 	if (error)
1859 		goto done;
1860 
1861 	/*
1862 	 * Create a directory entry connected to the specified chain.
1863 	 * The hardlink consolidation code has already adjusted ip->pip
1864 	 * to the common parent directory containing the actual hardlink
1865 	 *
1866 	 * (which may be different from dip where we created our hardlink
1867 	 * entry. ip->chain always represents the actual hardlink and not
1868 	 * any of the pointers to the actual hardlink).
1869 	 */
1870 	error = hammer2_inode_connect(&trans, 1,
1871 				      dip, &chain,
1872 				      name, name_len);
1873 	if (error == 0) {
1874 		cache_setunresolved(ap->a_nch);
1875 		cache_setvp(ap->a_nch, ap->a_vp);
1876 	}
1877 done:
1878 	hammer2_inode_unlock_ex(ip, chain);
1879 	hammer2_trans_done(&trans);
1880 
1881 	return error;
1882 }
1883 
1884 /*
1885  * hammer2_vop_ncreate { nch, dvp, vpp, cred, vap }
1886  *
1887  * The operating system has already ensured that the directory entry
1888  * does not exist and done all appropriate namespace locking.
1889  */
1890 static
1891 int
1892 hammer2_vop_ncreate(struct vop_ncreate_args *ap)
1893 {
1894 	hammer2_mount_t *hmp;
1895 	hammer2_inode_t *dip;
1896 	hammer2_inode_t *nip;
1897 	hammer2_trans_t trans;
1898 	hammer2_chain_t *nchain;
1899 	struct namecache *ncp;
1900 	const uint8_t *name;
1901 	size_t name_len;
1902 	int error;
1903 
1904 	dip = VTOI(ap->a_dvp);
1905 	hmp = dip->hmp;
1906 	if (hmp->ronly)
1907 		return (EROFS);
1908 
1909 	ncp = ap->a_nch->ncp;
1910 	name = ncp->nc_name;
1911 	name_len = ncp->nc_nlen;
1912 	hammer2_trans_init(hmp, &trans, 0);
1913 
1914 	nip = hammer2_inode_create(&trans, dip, ap->a_vap, ap->a_cred,
1915 				   name, name_len, &nchain, &error);
1916 	if (error) {
1917 		KKASSERT(nip == NULL);
1918 		*ap->a_vpp = NULL;
1919 	} else {
1920 		*ap->a_vpp = hammer2_igetv(nip, &error);
1921 		hammer2_inode_unlock_ex(nip, nchain);
1922 	}
1923 	hammer2_trans_done(&trans);
1924 
1925 	if (error == 0) {
1926 		cache_setunresolved(ap->a_nch);
1927 		cache_setvp(ap->a_nch, *ap->a_vpp);
1928 	}
1929 	return error;
1930 }
1931 
1932 /*
1933  * hammer2_vop_nsymlink { nch, dvp, vpp, cred, vap, target }
1934  */
1935 static
1936 int
1937 hammer2_vop_nsymlink(struct vop_nsymlink_args *ap)
1938 {
1939 	hammer2_mount_t *hmp;
1940 	hammer2_inode_t *dip;
1941 	hammer2_inode_t *nip;
1942 	hammer2_chain_t *nparent;
1943 	hammer2_trans_t trans;
1944 	struct namecache *ncp;
1945 	const uint8_t *name;
1946 	size_t name_len;
1947 	int error;
1948 
1949 	dip = VTOI(ap->a_dvp);
1950 	hmp = dip->hmp;
1951 	if (hmp->ronly)
1952 		return (EROFS);
1953 
1954 	ncp = ap->a_nch->ncp;
1955 	name = ncp->nc_name;
1956 	name_len = ncp->nc_nlen;
1957 	hammer2_trans_init(hmp, &trans, 0);
1958 
1959 	ap->a_vap->va_type = VLNK;	/* enforce type */
1960 
1961 	nip = hammer2_inode_create(&trans, dip, ap->a_vap, ap->a_cred,
1962 				   name, name_len, &nparent, &error);
1963 	if (error) {
1964 		KKASSERT(nip == NULL);
1965 		*ap->a_vpp = NULL;
1966 		hammer2_trans_done(&trans);
1967 		return error;
1968 	}
1969 	*ap->a_vpp = hammer2_igetv(nip, &error);
1970 
1971 	/*
1972 	 * Build the softlink (~like file data) and finalize the namecache.
1973 	 */
1974 	if (error == 0) {
1975 		size_t bytes;
1976 		struct uio auio;
1977 		struct iovec aiov;
1978 		hammer2_inode_data_t *nipdata;
1979 
1980 		nipdata = &nip->chain->data->ipdata;
1981 		bytes = strlen(ap->a_target);
1982 
1983 		if (bytes <= HAMMER2_EMBEDDED_BYTES) {
1984 			KKASSERT(nipdata->op_flags &
1985 				 HAMMER2_OPFLAG_DIRECTDATA);
1986 			bcopy(ap->a_target, nipdata->u.data, bytes);
1987 			nipdata->size = bytes;
1988 		} else {
1989 			bzero(&auio, sizeof(auio));
1990 			bzero(&aiov, sizeof(aiov));
1991 			auio.uio_iov = &aiov;
1992 			auio.uio_segflg = UIO_SYSSPACE;
1993 			auio.uio_rw = UIO_WRITE;
1994 			auio.uio_resid = bytes;
1995 			auio.uio_iovcnt = 1;
1996 			auio.uio_td = curthread;
1997 			aiov.iov_base = ap->a_target;
1998 			aiov.iov_len = bytes;
1999 			error = hammer2_write_file(&trans, nip, &nparent,
2000 						   &auio, IO_APPEND, 0);
2001 			nipdata = &nip->chain->data->ipdata; /* RELOAD */
2002 			/* XXX handle error */
2003 			error = 0;
2004 		}
2005 	}
2006 	hammer2_inode_unlock_ex(nip, nparent);
2007 	hammer2_trans_done(&trans);
2008 
2009 	/*
2010 	 * Finalize namecache
2011 	 */
2012 	if (error == 0) {
2013 		cache_setunresolved(ap->a_nch);
2014 		cache_setvp(ap->a_nch, *ap->a_vpp);
2015 		/* hammer2_knote(ap->a_dvp, NOTE_WRITE); */
2016 	}
2017 	return error;
2018 }
2019 
2020 /*
2021  * hammer2_vop_nremove { nch, dvp, cred }
2022  */
2023 static
2024 int
2025 hammer2_vop_nremove(struct vop_nremove_args *ap)
2026 {
2027 	hammer2_inode_t *dip;
2028 	hammer2_mount_t *hmp;
2029 	hammer2_trans_t trans;
2030 	struct namecache *ncp;
2031 	const uint8_t *name;
2032 	size_t name_len;
2033 	int error;
2034 
2035 	dip = VTOI(ap->a_dvp);
2036 	hmp = dip->hmp;
2037 	if (hmp->ronly)
2038 		return(EROFS);
2039 
2040 	ncp = ap->a_nch->ncp;
2041 	name = ncp->nc_name;
2042 	name_len = ncp->nc_nlen;
2043 	hammer2_trans_init(hmp, &trans, 0);
2044 	error = hammer2_unlink_file(&trans, dip, name, name_len, 0, NULL);
2045 	hammer2_trans_done(&trans);
2046 	if (error == 0) {
2047 		cache_unlink(ap->a_nch);
2048 	}
2049 	return (error);
2050 }
2051 
2052 /*
2053  * hammer2_vop_nrmdir { nch, dvp, cred }
2054  */
2055 static
2056 int
2057 hammer2_vop_nrmdir(struct vop_nrmdir_args *ap)
2058 {
2059 	hammer2_inode_t *dip;
2060 	hammer2_mount_t *hmp;
2061 	hammer2_trans_t trans;
2062 	struct namecache *ncp;
2063 	const uint8_t *name;
2064 	size_t name_len;
2065 	int error;
2066 
2067 	dip = VTOI(ap->a_dvp);
2068 	hmp = dip->hmp;
2069 	if (hmp->ronly)
2070 		return(EROFS);
2071 
2072 	ncp = ap->a_nch->ncp;
2073 	name = ncp->nc_name;
2074 	name_len = ncp->nc_nlen;
2075 
2076 	hammer2_trans_init(hmp, &trans, 0);
2077 	error = hammer2_unlink_file(&trans, dip, name, name_len, 1, NULL);
2078 	hammer2_trans_done(&trans);
2079 	if (error == 0) {
2080 		cache_unlink(ap->a_nch);
2081 	}
2082 	return (error);
2083 }
2084 
2085 /*
2086  * hammer2_vop_nrename { fnch, tnch, fdvp, tdvp, cred }
2087  */
2088 static
2089 int
2090 hammer2_vop_nrename(struct vop_nrename_args *ap)
2091 {
2092 	struct namecache *fncp;
2093 	struct namecache *tncp;
2094 	hammer2_inode_t *fdip;
2095 	hammer2_inode_t *tdip;
2096 	hammer2_inode_t *ip;
2097 	hammer2_chain_t *chain;
2098 	hammer2_mount_t *hmp;
2099 	hammer2_trans_t trans;
2100 	const uint8_t *fname;
2101 	size_t fname_len;
2102 	const uint8_t *tname;
2103 	size_t tname_len;
2104 	int error;
2105 	int hlink;
2106 
2107 	if (ap->a_fdvp->v_mount != ap->a_tdvp->v_mount)
2108 		return(EXDEV);
2109 	if (ap->a_fdvp->v_mount != ap->a_fnch->ncp->nc_vp->v_mount)
2110 		return(EXDEV);
2111 
2112 	fdip = VTOI(ap->a_fdvp);	/* source directory */
2113 	tdip = VTOI(ap->a_tdvp);	/* target directory */
2114 
2115 	hmp = fdip->hmp;		/* check read-only filesystem */
2116 	if (hmp->ronly)
2117 		return(EROFS);
2118 
2119 	fncp = ap->a_fnch->ncp;		/* entry name in source */
2120 	fname = fncp->nc_name;
2121 	fname_len = fncp->nc_nlen;
2122 
2123 	tncp = ap->a_tnch->ncp;		/* entry name in target */
2124 	tname = tncp->nc_name;
2125 	tname_len = tncp->nc_nlen;
2126 
2127 	hammer2_trans_init(hmp, &trans, 0);
2128 
2129 	/*
2130 	 * ip is the inode being renamed.  If this is a hardlink then
2131 	 * ip represents the actual file and not the hardlink marker.
2132 	 */
2133 	ip = VTOI(fncp->nc_vp);
2134 	chain = NULL;
2135 
2136 	/*
2137 	 * Keep a tight grip on the inode so the temporary unlinking from
2138 	 * the source location prior to linking to the target location
2139 	 * does not cause the chain to be destroyed.
2140 	 *
2141 	 * NOTE: To avoid deadlocks we cannot lock (ip) while we are
2142 	 *	 unlinking elements from their directories.  Locking
2143 	 *	 the nlinks field does not lock the whole inode.
2144 	 */
2145 	hammer2_inode_ref(ip);
2146 
2147 	/*
2148 	 * Remove target if it exists
2149 	 */
2150 	error = hammer2_unlink_file(&trans, tdip, tname, tname_len, -1, NULL);
2151 	if (error && error != ENOENT)
2152 		goto done;
2153 	cache_setunresolved(ap->a_tnch);
2154 
2155 	/*
2156 	 * When renaming a hardlinked file we may have to re-consolidate
2157 	 * the location of the hardlink target.  Since the element is simply
2158 	 * being moved, nlinks is not modified in this case.
2159 	 *
2160 	 * If ip represents a regular file the consolidation code essentially
2161 	 * does nothing other than return the same locked chain that was
2162 	 * passed in.
2163 	 *
2164 	 * The returned chain will be locked.
2165 	 *
2166 	 * WARNING!  We do not currently have a local copy of ipdata but
2167 	 *	     we do use one later remember that it must be reloaded
2168 	 *	     on any modification to the inode, including connects.
2169 	 */
2170 	chain = hammer2_inode_lock_ex(ip);
2171 	error = hammer2_hardlink_consolidate(&trans, ip, &chain, tdip, 0);
2172 	if (error)
2173 		goto done;
2174 
2175 	/*
2176 	 * Disconnect (fdip, fname) from the source directory.  This will
2177 	 * disconnect (ip) if it represents a direct file.  If (ip) represents
2178 	 * a hardlink the HARDLINK pointer object will be removed but the
2179 	 * hardlink will stay intact.
2180 	 *
2181 	 * The target chain may be marked DELETED but will not be destroyed
2182 	 * since we retain our hold on ip and chain.
2183 	 */
2184 	error = hammer2_unlink_file(&trans, fdip, fname, fname_len, -1, &hlink);
2185 	KKASSERT(error != EAGAIN);
2186 	if (error)
2187 		goto done;
2188 
2189 	/*
2190 	 * Reconnect ip to target directory using chain.  Chains cannot
2191 	 * actually be moved, so this will duplicate the chain in the new
2192 	 * spot and assign it to the ip, replacing the old chain.
2193 	 *
2194 	 * WARNING: chain locks can lock buffer cache buffers, to avoid
2195 	 *	    deadlocks we want to unlock before issuing a cache_*()
2196 	 *	    op (that might have to lock a vnode).
2197 	 */
2198 	error = hammer2_inode_connect(&trans, hlink,
2199 				      tdip, &chain,
2200 				      tname, tname_len);
2201 	if (error == 0) {
2202 		KKASSERT(chain != NULL);
2203 		hammer2_inode_repoint(ip, (hlink ? ip->pip : tdip), chain);
2204 		cache_rename(ap->a_fnch, ap->a_tnch);
2205 	}
2206 done:
2207 	hammer2_inode_unlock_ex(ip, chain);
2208 	hammer2_inode_drop(ip);
2209 	hammer2_trans_done(&trans);
2210 
2211 	return (error);
2212 }
2213 
2214 /*
2215  * Strategy code
2216  *
2217  * WARNING: The strategy code cannot safely use hammer2 transactions
2218  *	    as this can deadlock against vfs_sync's vfsync() call
2219  *	    if multiple flushes are queued.
2220  */
2221 static int hammer2_strategy_read(struct vop_strategy_args *ap);
2222 static int hammer2_strategy_write(struct vop_strategy_args *ap);
2223 
2224 static
2225 int
2226 hammer2_vop_strategy(struct vop_strategy_args *ap)
2227 {
2228 	struct bio *biop;
2229 	struct buf *bp;
2230 	int error;
2231 
2232 	biop = ap->a_bio;
2233 	bp = biop->bio_buf;
2234 
2235 	switch(bp->b_cmd) {
2236 	case BUF_CMD_READ:
2237 		error = hammer2_strategy_read(ap);
2238 		++hammer2_iod_file_read;
2239 		break;
2240 	case BUF_CMD_WRITE:
2241 		error = hammer2_strategy_write(ap);
2242 		++hammer2_iod_file_write;
2243 		break;
2244 	default:
2245 		bp->b_error = error = EINVAL;
2246 		bp->b_flags |= B_ERROR;
2247 		biodone(biop);
2248 		break;
2249 	}
2250 
2251 	return (error);
2252 }
2253 
2254 static
2255 int
2256 hammer2_strategy_read(struct vop_strategy_args *ap)
2257 {
2258 	struct buf *bp;
2259 	struct bio *bio;
2260 	struct bio *nbio;
2261 	hammer2_mount_t *hmp;
2262 	hammer2_inode_t *ip;
2263 	hammer2_chain_t *parent;
2264 	hammer2_chain_t *chain;
2265 	hammer2_key_t lbase;
2266 
2267 	bio = ap->a_bio;
2268 	bp = bio->bio_buf;
2269 	ip = VTOI(ap->a_vp);
2270 	hmp = ip->hmp;
2271 	nbio = push_bio(bio);
2272 
2273 	lbase = bio->bio_offset;
2274 	chain = NULL;
2275 	KKASSERT(((int)lbase & HAMMER2_PBUFMASK) == 0);
2276 
2277 #if 0
2278 	kprintf("read lbase %jd cached %016jx\n",
2279 		lbase, nbio->bio_offset);
2280 #endif
2281 
2282 	/*
2283 	 * We must characterize the logical->physical translation if it
2284 	 * has not already been cached.
2285 	 *
2286 	 * Physical data references < LBUFSIZE are never cached.  This
2287 	 * includes both small-block allocations and inode-embedded data.
2288 	 */
2289 	if (nbio->bio_offset == NOOFFSET) {
2290 		parent = hammer2_inode_lock_sh(ip);
2291 
2292 		chain = hammer2_chain_lookup(&parent, lbase, lbase,
2293 					     HAMMER2_LOOKUP_NODATA |
2294 					     HAMMER2_LOOKUP_SHARED);
2295 		if (chain == NULL) {
2296 			/*
2297 			 * Data is zero-fill
2298 			 */
2299 			nbio->bio_offset = ZFOFFSET;
2300 		} else if (chain->bref.type == HAMMER2_BREF_TYPE_INODE) {
2301 			/*
2302 			 * Data is embedded in the inode (do nothing)
2303 			 */
2304 			KKASSERT(chain == parent);
2305 			hammer2_chain_unlock(chain);
2306 			nbio->bio_offset = NOOFFSET;
2307 		} else if (chain->bref.type == HAMMER2_BREF_TYPE_DATA) {
2308 			/*
2309 			 * Data is on-media
2310 			 */
2311 			KKASSERT(bp->b_bcount == chain->bytes);
2312 			nbio->bio_offset = chain->bref.data_off &
2313 					   HAMMER2_OFF_MASK;
2314 			hammer2_chain_unlock(chain);
2315 			KKASSERT(nbio->bio_offset != 0);
2316 		} else {
2317 			panic("hammer2_strategy_read: unknown bref type");
2318 		}
2319 		hammer2_inode_unlock_sh(ip, parent);
2320 	}
2321 
2322 	if (hammer2_debug & 0x0020) {
2323 		kprintf("read %016jx %016jx\n",
2324 			bio->bio_offset, nbio->bio_offset);
2325 	}
2326 
2327 	if (nbio->bio_offset == ZFOFFSET) {
2328 		/*
2329 		 * Data is zero-fill
2330 		 */
2331 		bp->b_resid = 0;
2332 		bp->b_error = 0;
2333 		bzero(bp->b_data, bp->b_bcount);
2334 		biodone(nbio);
2335 	} else if (nbio->bio_offset != NOOFFSET) {
2336 		/*
2337 		 * Forward direct IO to the device
2338 		 */
2339 		vn_strategy(hmp->devvp, nbio);
2340 	} else {
2341 		/*
2342 		 * Data is embedded in inode.
2343 		 */
2344 		bcopy(chain->data->ipdata.u.data, bp->b_data,
2345 		      HAMMER2_EMBEDDED_BYTES);
2346 		bzero(bp->b_data + HAMMER2_EMBEDDED_BYTES,
2347 		      bp->b_bcount - HAMMER2_EMBEDDED_BYTES);
2348 		bp->b_resid = 0;
2349 		bp->b_error = 0;
2350 		biodone(nbio);
2351 	}
2352 	return (0);
2353 }
2354 
2355 static
2356 int
2357 hammer2_strategy_write(struct vop_strategy_args *ap)
2358 {
2359 	struct buf *bp;
2360 	struct bio *bio;
2361 	struct bio *nbio;
2362 	hammer2_chain_t *chain;
2363 	hammer2_mount_t *hmp;
2364 	hammer2_inode_t *ip;
2365 
2366 	bio = ap->a_bio;
2367 	bp = bio->bio_buf;
2368 	ip = VTOI(ap->a_vp);
2369 	hmp = ip->hmp;
2370 	nbio = push_bio(bio);
2371 
2372 	KKASSERT((bio->bio_offset & HAMMER2_PBUFMASK64) == 0);
2373 	KKASSERT(nbio->bio_offset != 0 && nbio->bio_offset != ZFOFFSET);
2374 
2375 	if (nbio->bio_offset == NOOFFSET) {
2376 		/*
2377 		 * The data is embedded in the inode.  Note that strategy
2378 		 * calls for embedded data are synchronous in order to
2379 		 * ensure that ip->chain is stable.  Chain modification
2380 		 * status is handled by the caller.
2381 		 */
2382 		KKASSERT(ip->chain->flags & HAMMER2_CHAIN_MODIFIED);
2383 		KKASSERT(bio->bio_offset == 0);
2384 		KKASSERT(ip->chain && ip->chain->data);
2385 		chain = ip->chain;
2386 		bcopy(bp->b_data, chain->data->ipdata.u.data,
2387 		      HAMMER2_EMBEDDED_BYTES);
2388 		bp->b_resid = 0;
2389 		bp->b_error = 0;
2390 		biodone(nbio);
2391 	} else {
2392 		/*
2393 		 * Forward direct IO to the device
2394 		 */
2395 		vn_strategy(hmp->devvp, nbio);
2396 	}
2397 	return (0);
2398 }
2399 
2400 /*
2401  * hammer2_vop_ioctl { vp, command, data, fflag, cred }
2402  */
2403 static
2404 int
2405 hammer2_vop_ioctl(struct vop_ioctl_args *ap)
2406 {
2407 	hammer2_mount_t *hmp;
2408 	hammer2_inode_t *ip;
2409 	int error;
2410 
2411 	ip = VTOI(ap->a_vp);
2412 	hmp = ip->hmp;
2413 
2414 	error = hammer2_ioctl(ip, ap->a_command, (void *)ap->a_data,
2415 			      ap->a_fflag, ap->a_cred);
2416 	return (error);
2417 }
2418 
2419 static
2420 int
2421 hammer2_vop_mountctl(struct vop_mountctl_args *ap)
2422 {
2423 	struct mount *mp;
2424 	hammer2_pfsmount_t *pmp;
2425 	int rc;
2426 
2427 	switch (ap->a_op) {
2428 	case (MOUNTCTL_SET_EXPORT):
2429 		mp = ap->a_head.a_ops->head.vv_mount;
2430 		pmp = MPTOPMP(mp);
2431 
2432 		if (ap->a_ctllen != sizeof(struct export_args))
2433 			rc = (EINVAL);
2434 		else
2435 			rc = vfs_export(mp, &pmp->export,
2436 					(const struct export_args *)ap->a_ctl);
2437 		break;
2438 	default:
2439 		rc = vop_stdmountctl(ap);
2440 		break;
2441 	}
2442 	return (rc);
2443 }
2444 
2445 struct vop_ops hammer2_vnode_vops = {
2446 	.vop_default	= vop_defaultop,
2447 	.vop_fsync	= hammer2_vop_fsync,
2448 	.vop_getpages	= vop_stdgetpages,
2449 	.vop_putpages	= vop_stdputpages,
2450 	.vop_access	= hammer2_vop_access,
2451 	.vop_advlock	= hammer2_vop_advlock,
2452 	.vop_close	= hammer2_vop_close,
2453 	.vop_nlink	= hammer2_vop_nlink,
2454 	.vop_ncreate	= hammer2_vop_ncreate,
2455 	.vop_nsymlink	= hammer2_vop_nsymlink,
2456 	.vop_nremove	= hammer2_vop_nremove,
2457 	.vop_nrmdir	= hammer2_vop_nrmdir,
2458 	.vop_nrename	= hammer2_vop_nrename,
2459 	.vop_getattr	= hammer2_vop_getattr,
2460 	.vop_setattr	= hammer2_vop_setattr,
2461 	.vop_readdir	= hammer2_vop_readdir,
2462 	.vop_readlink	= hammer2_vop_readlink,
2463 	.vop_getpages	= vop_stdgetpages,
2464 	.vop_putpages	= vop_stdputpages,
2465 	.vop_read	= hammer2_vop_read,
2466 	.vop_write	= hammer2_vop_write,
2467 	.vop_open	= hammer2_vop_open,
2468 	.vop_inactive	= hammer2_vop_inactive,
2469 	.vop_reclaim 	= hammer2_vop_reclaim,
2470 	.vop_nresolve	= hammer2_vop_nresolve,
2471 	.vop_nlookupdotdot = hammer2_vop_nlookupdotdot,
2472 	.vop_nmkdir 	= hammer2_vop_nmkdir,
2473 	.vop_ioctl	= hammer2_vop_ioctl,
2474 	.vop_mountctl	= hammer2_vop_mountctl,
2475 	.vop_bmap	= hammer2_vop_bmap,
2476 	.vop_strategy	= hammer2_vop_strategy,
2477 };
2478 
2479 struct vop_ops hammer2_spec_vops = {
2480 
2481 };
2482 
2483 struct vop_ops hammer2_fifo_vops = {
2484 
2485 };
2486