1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
23  * Copyright (c) 2012, 2014 by Delphix. All rights reserved.
24  * Copyright (c) 2014 Integros [integros.com]
25  */
26 
27 /* Portions Copyright 2007 Jeremy Teo */
28 /* Portions Copyright 2011 Martin Matuska <mm@FreeBSD.org> */
29 
30 #ifdef _KERNEL
31 #include <sys/types.h>
32 #include <sys/param.h>
33 #include <sys/time.h>
34 #include <sys/systm.h>
35 #include <sys/sysmacros.h>
36 #include <sys/resource.h>
37 #include <sys/mntent.h>
38 #include <sys/u8_textprep.h>
39 #include <sys/dsl_dataset.h>
40 #include <sys/vfs.h>
41 #include <sys/vnode.h>
42 #include <sys/file.h>
43 #include <sys/kmem.h>
44 #include <sys/errno.h>
45 #include <sys/unistd.h>
46 #include <sys/atomic.h>
47 #include <sys/zfs_dir.h>
48 #include <sys/zfs_acl.h>
49 #include <sys/zfs_ioctl.h>
50 #include <sys/zfs_rlock.h>
51 #include <sys/zfs_fuid.h>
52 #include <sys/dnode.h>
53 #include <sys/fs/zfs.h>
54 #endif /* _KERNEL */
55 
56 #include <sys/dmu.h>
57 #include <sys/dmu_objset.h>
58 #include <sys/dmu_tx.h>
59 #include <sys/zfs_refcount.h>
60 #include <sys/stat.h>
61 #include <sys/zap.h>
62 #include <sys/zfs_znode.h>
63 #include <sys/sa.h>
64 #include <sys/zfs_sa.h>
65 #include <sys/zfs_stat.h>
66 
67 #include "zfs_prop.h"
68 #include "zfs_comutil.h"
69 
70 /* Used by fstat(1). */
71 SYSCTL_INT(_debug_sizeof, OID_AUTO, znode, CTLFLAG_RD,
72 	SYSCTL_NULL_INT_PTR, sizeof (znode_t), "sizeof(znode_t)");
73 
74 /*
75  * Define ZNODE_STATS to turn on statistic gathering. By default, it is only
76  * turned on when DEBUG is also defined.
77  */
78 #ifdef	ZFS_DEBUG
79 #define	ZNODE_STATS
80 #endif	/* DEBUG */
81 
82 #ifdef	ZNODE_STATS
83 #define	ZNODE_STAT_ADD(stat)			((stat)++)
84 #else
85 #define	ZNODE_STAT_ADD(stat)			/* nothing */
86 #endif	/* ZNODE_STATS */
87 
88 /*
89  * Functions needed for userland (ie: libzpool) are not put under
90  * #ifdef_KERNEL; the rest of the functions have dependencies
91  * (such as VFS logic) that will not compile easily in userland.
92  */
93 #ifdef _KERNEL
94 #if !defined(KMEM_DEBUG) && __FreeBSD_version >= 1300102
95 #define	_ZFS_USE_SMR
96 static uma_zone_t znode_uma_zone;
97 #else
98 static kmem_cache_t *znode_cache = NULL;
99 #endif
100 
101 extern struct vop_vector zfs_vnodeops;
102 extern struct vop_vector zfs_fifoops;
103 extern struct vop_vector zfs_shareops;
104 
105 
106 /*
107  * This callback is invoked when acquiring a RL_WRITER or RL_APPEND lock on
108  * z_rangelock. It will modify the offset and length of the lock to reflect
109  * znode-specific information, and convert RL_APPEND to RL_WRITER.  This is
110  * called with the rangelock_t's rl_lock held, which avoids races.
111  */
112 static void
113 zfs_rangelock_cb(zfs_locked_range_t *new, void *arg)
114 {
115 	znode_t *zp = arg;
116 
117 	/*
118 	 * If in append mode, convert to writer and lock starting at the
119 	 * current end of file.
120 	 */
121 	if (new->lr_type == RL_APPEND) {
122 		new->lr_offset = zp->z_size;
123 		new->lr_type = RL_WRITER;
124 	}
125 
126 	/*
127 	 * If we need to grow the block size then lock the whole file range.
128 	 */
129 	uint64_t end_size = MAX(zp->z_size, new->lr_offset + new->lr_length);
130 	if (end_size > zp->z_blksz && (!ISP2(zp->z_blksz) ||
131 	    zp->z_blksz < ZTOZSB(zp)->z_max_blksz)) {
132 		new->lr_offset = 0;
133 		new->lr_length = UINT64_MAX;
134 	}
135 }
136 
137 static int
138 zfs_znode_cache_constructor(void *buf, void *arg, int kmflags)
139 {
140 	znode_t *zp = buf;
141 
142 	POINTER_INVALIDATE(&zp->z_zfsvfs);
143 
144 	list_link_init(&zp->z_link_node);
145 
146 	mutex_init(&zp->z_lock, NULL, MUTEX_DEFAULT, NULL);
147 	mutex_init(&zp->z_acl_lock, NULL, MUTEX_DEFAULT, NULL);
148 	rw_init(&zp->z_xattr_lock, NULL, RW_DEFAULT, NULL);
149 
150 	zfs_rangelock_init(&zp->z_rangelock, zfs_rangelock_cb, zp);
151 
152 	zp->z_acl_cached = NULL;
153 	zp->z_xattr_cached = NULL;
154 	zp->z_xattr_parent = 0;
155 	zp->z_vnode = NULL;
156 	return (0);
157 }
158 
159 static void
160 zfs_znode_cache_destructor(void *buf, void *arg)
161 {
162 	(void) arg;
163 	znode_t *zp = buf;
164 
165 	ASSERT(!POINTER_IS_VALID(zp->z_zfsvfs));
166 	ASSERT3P(zp->z_vnode, ==, NULL);
167 	ASSERT(!list_link_active(&zp->z_link_node));
168 	mutex_destroy(&zp->z_lock);
169 	mutex_destroy(&zp->z_acl_lock);
170 	rw_destroy(&zp->z_xattr_lock);
171 	zfs_rangelock_fini(&zp->z_rangelock);
172 
173 	ASSERT3P(zp->z_acl_cached, ==, NULL);
174 	ASSERT3P(zp->z_xattr_cached, ==, NULL);
175 }
176 
177 
178 #ifdef _ZFS_USE_SMR
179 VFS_SMR_DECLARE;
180 
181 static int
182 zfs_znode_cache_constructor_smr(void *mem, int size __unused, void *private,
183     int flags)
184 {
185 	return (zfs_znode_cache_constructor(mem, private, flags));
186 }
187 
188 static void
189 zfs_znode_cache_destructor_smr(void *mem, int size __unused, void *private)
190 {
191 	zfs_znode_cache_destructor(mem, private);
192 }
193 
194 void
195 zfs_znode_init(void)
196 {
197 	/*
198 	 * Initialize zcache
199 	 */
200 	ASSERT3P(znode_uma_zone, ==, NULL);
201 	znode_uma_zone = uma_zcreate("zfs_znode_cache",
202 	    sizeof (znode_t), zfs_znode_cache_constructor_smr,
203 	    zfs_znode_cache_destructor_smr, NULL, NULL, 0, 0);
204 	VFS_SMR_ZONE_SET(znode_uma_zone);
205 }
206 
207 static znode_t *
208 zfs_znode_alloc_kmem(int flags)
209 {
210 	return (uma_zalloc_smr(znode_uma_zone, flags));
211 }
212 
213 static void
214 zfs_znode_free_kmem(znode_t *zp)
215 {
216 	if (zp->z_xattr_cached) {
217 		nvlist_free(zp->z_xattr_cached);
218 		zp->z_xattr_cached = NULL;
219 	}
220 	uma_zfree_smr(znode_uma_zone, zp);
221 }
222 #else
223 void
224 zfs_znode_init(void)
225 {
226 	/*
227 	 * Initialize zcache
228 	 */
229 	ASSERT3P(znode_cache, ==, NULL);
230 	znode_cache = kmem_cache_create("zfs_znode_cache",
231 	    sizeof (znode_t), 0, zfs_znode_cache_constructor,
232 	    zfs_znode_cache_destructor, NULL, NULL, NULL, 0);
233 }
234 
235 static znode_t *
236 zfs_znode_alloc_kmem(int flags)
237 {
238 	return (kmem_cache_alloc(znode_cache, flags));
239 }
240 
241 static void
242 zfs_znode_free_kmem(znode_t *zp)
243 {
244 	if (zp->z_xattr_cached) {
245 		nvlist_free(zp->z_xattr_cached);
246 		zp->z_xattr_cached = NULL;
247 	}
248 	kmem_cache_free(znode_cache, zp);
249 }
250 #endif
251 
252 void
253 zfs_znode_fini(void)
254 {
255 	/*
256 	 * Cleanup zcache
257 	 */
258 #ifdef _ZFS_USE_SMR
259 	if (znode_uma_zone) {
260 		uma_zdestroy(znode_uma_zone);
261 		znode_uma_zone = NULL;
262 	}
263 #else
264 	if (znode_cache) {
265 		kmem_cache_destroy(znode_cache);
266 		znode_cache = NULL;
267 	}
268 #endif
269 }
270 
271 
272 static int
273 zfs_create_share_dir(zfsvfs_t *zfsvfs, dmu_tx_t *tx)
274 {
275 	zfs_acl_ids_t acl_ids;
276 	vattr_t vattr;
277 	znode_t *sharezp;
278 	znode_t *zp;
279 	int error;
280 
281 	vattr.va_mask = AT_MODE|AT_UID|AT_GID;
282 	vattr.va_type = VDIR;
283 	vattr.va_mode = S_IFDIR|0555;
284 	vattr.va_uid = crgetuid(kcred);
285 	vattr.va_gid = crgetgid(kcred);
286 
287 	sharezp = zfs_znode_alloc_kmem(KM_SLEEP);
288 	ASSERT(!POINTER_IS_VALID(sharezp->z_zfsvfs));
289 	sharezp->z_unlinked = 0;
290 	sharezp->z_atime_dirty = 0;
291 	sharezp->z_zfsvfs = zfsvfs;
292 	sharezp->z_is_sa = zfsvfs->z_use_sa;
293 
294 	VERIFY0(zfs_acl_ids_create(sharezp, IS_ROOT_NODE, &vattr,
295 	    kcred, NULL, &acl_ids));
296 	zfs_mknode(sharezp, &vattr, tx, kcred, IS_ROOT_NODE, &zp, &acl_ids);
297 	ASSERT3P(zp, ==, sharezp);
298 	POINTER_INVALIDATE(&sharezp->z_zfsvfs);
299 	error = zap_add(zfsvfs->z_os, MASTER_NODE_OBJ,
300 	    ZFS_SHARES_DIR, 8, 1, &sharezp->z_id, tx);
301 	zfsvfs->z_shares_dir = sharezp->z_id;
302 
303 	zfs_acl_ids_free(&acl_ids);
304 	sa_handle_destroy(sharezp->z_sa_hdl);
305 	zfs_znode_free_kmem(sharezp);
306 
307 	return (error);
308 }
309 
310 /*
311  * define a couple of values we need available
312  * for both 64 and 32 bit environments.
313  */
314 #ifndef NBITSMINOR64
315 #define	NBITSMINOR64	32
316 #endif
317 #ifndef MAXMAJ64
318 #define	MAXMAJ64	0xffffffffUL
319 #endif
320 #ifndef	MAXMIN64
321 #define	MAXMIN64	0xffffffffUL
322 #endif
323 
324 /*
325  * Create special expldev for ZFS private use.
326  * Can't use standard expldev since it doesn't do
327  * what we want.  The standard expldev() takes a
328  * dev32_t in LP64 and expands it to a long dev_t.
329  * We need an interface that takes a dev32_t in ILP32
330  * and expands it to a long dev_t.
331  */
332 static uint64_t
333 zfs_expldev(dev_t dev)
334 {
335 	return (((uint64_t)major(dev) << NBITSMINOR64) | minor(dev));
336 }
337 /*
338  * Special cmpldev for ZFS private use.
339  * Can't use standard cmpldev since it takes
340  * a long dev_t and compresses it to dev32_t in
341  * LP64.  We need to do a compaction of a long dev_t
342  * to a dev32_t in ILP32.
343  */
344 dev_t
345 zfs_cmpldev(uint64_t dev)
346 {
347 	return (makedev((dev >> NBITSMINOR64), (dev & MAXMIN64)));
348 }
349 
350 static void
351 zfs_znode_sa_init(zfsvfs_t *zfsvfs, znode_t *zp,
352     dmu_buf_t *db, dmu_object_type_t obj_type, sa_handle_t *sa_hdl)
353 {
354 	ASSERT(!POINTER_IS_VALID(zp->z_zfsvfs) || (zfsvfs == zp->z_zfsvfs));
355 	ASSERT(MUTEX_HELD(ZFS_OBJ_MUTEX(zfsvfs, zp->z_id)));
356 
357 	ASSERT3P(zp->z_sa_hdl, ==, NULL);
358 	ASSERT3P(zp->z_acl_cached, ==, NULL);
359 	if (sa_hdl == NULL) {
360 		VERIFY0(sa_handle_get_from_db(zfsvfs->z_os, db, zp,
361 		    SA_HDL_SHARED, &zp->z_sa_hdl));
362 	} else {
363 		zp->z_sa_hdl = sa_hdl;
364 		sa_set_userp(sa_hdl, zp);
365 	}
366 
367 	zp->z_is_sa = (obj_type == DMU_OT_SA) ? B_TRUE : B_FALSE;
368 
369 	/*
370 	 * Slap on VROOT if we are the root znode unless we are the root
371 	 * node of a snapshot mounted under .zfs.
372 	 */
373 	if (zp->z_id == zfsvfs->z_root && zfsvfs->z_parent == zfsvfs)
374 		ZTOV(zp)->v_flag |= VROOT;
375 
376 	vn_exists(ZTOV(zp));
377 }
378 
379 void
380 zfs_znode_dmu_fini(znode_t *zp)
381 {
382 	ASSERT(MUTEX_HELD(ZFS_OBJ_MUTEX(zp->z_zfsvfs, zp->z_id)) ||
383 	    zp->z_unlinked ||
384 	    ZFS_TEARDOWN_INACTIVE_WRITE_HELD(zp->z_zfsvfs));
385 
386 	sa_handle_destroy(zp->z_sa_hdl);
387 	zp->z_sa_hdl = NULL;
388 }
389 
390 static void
391 zfs_vnode_forget(vnode_t *vp)
392 {
393 
394 	/* copied from insmntque_stddtr */
395 	vp->v_data = NULL;
396 	vp->v_op = &dead_vnodeops;
397 	vgone(vp);
398 	vput(vp);
399 }
400 
401 /*
402  * Construct a new znode/vnode and initialize.
403  *
404  * This does not do a call to dmu_set_user() that is
405  * up to the caller to do, in case you don't want to
406  * return the znode
407  */
408 static znode_t *
409 zfs_znode_alloc(zfsvfs_t *zfsvfs, dmu_buf_t *db, int blksz,
410     dmu_object_type_t obj_type, sa_handle_t *hdl)
411 {
412 	znode_t	*zp;
413 	vnode_t *vp;
414 	uint64_t mode;
415 	uint64_t parent;
416 #ifdef notyet
417 	uint64_t mtime[2], ctime[2];
418 #endif
419 	uint64_t projid = ZFS_DEFAULT_PROJID;
420 	sa_bulk_attr_t bulk[9];
421 	int count = 0;
422 	int error;
423 
424 	zp = zfs_znode_alloc_kmem(KM_SLEEP);
425 
426 #ifndef _ZFS_USE_SMR
427 	KASSERT((zfsvfs->z_parent->z_vfs->mnt_kern_flag & MNTK_FPLOOKUP) == 0,
428 	    ("%s: fast path lookup enabled without smr", __func__));
429 #endif
430 
431 #if __FreeBSD_version >= 1300076
432 	KASSERT(curthread->td_vp_reserved != NULL,
433 	    ("zfs_znode_alloc: getnewvnode without any vnodes reserved"));
434 #else
435 	KASSERT(curthread->td_vp_reserv > 0,
436 	    ("zfs_znode_alloc: getnewvnode without any vnodes reserved"));
437 #endif
438 	error = getnewvnode("zfs", zfsvfs->z_parent->z_vfs, &zfs_vnodeops, &vp);
439 	if (error != 0) {
440 		zfs_znode_free_kmem(zp);
441 		return (NULL);
442 	}
443 	zp->z_vnode = vp;
444 	vp->v_data = zp;
445 
446 	ASSERT(!POINTER_IS_VALID(zp->z_zfsvfs));
447 
448 	zp->z_sa_hdl = NULL;
449 	zp->z_unlinked = 0;
450 	zp->z_atime_dirty = 0;
451 	zp->z_mapcnt = 0;
452 	zp->z_id = db->db_object;
453 	zp->z_blksz = blksz;
454 	zp->z_seq = 0x7A4653;
455 	zp->z_sync_cnt = 0;
456 #if __FreeBSD_version >= 1300139
457 	atomic_store_ptr(&zp->z_cached_symlink, NULL);
458 #endif
459 
460 	vp = ZTOV(zp);
461 
462 	zfs_znode_sa_init(zfsvfs, zp, db, obj_type, hdl);
463 
464 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MODE(zfsvfs), NULL, &mode, 8);
465 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_GEN(zfsvfs), NULL, &zp->z_gen, 8);
466 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_SIZE(zfsvfs), NULL,
467 	    &zp->z_size, 8);
468 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_LINKS(zfsvfs), NULL,
469 	    &zp->z_links, 8);
470 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_FLAGS(zfsvfs), NULL,
471 	    &zp->z_pflags, 8);
472 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_PARENT(zfsvfs), NULL, &parent, 8);
473 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_ATIME(zfsvfs), NULL,
474 	    &zp->z_atime, 16);
475 #ifdef notyet
476 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zfsvfs), NULL,
477 	    &mtime, 16);
478 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs), NULL,
479 	    &ctime, 16);
480 #endif
481 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_UID(zfsvfs), NULL,
482 	    &zp->z_uid, 8);
483 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_GID(zfsvfs), NULL,
484 	    &zp->z_gid, 8);
485 
486 	if (sa_bulk_lookup(zp->z_sa_hdl, bulk, count) != 0 || zp->z_gen == 0 ||
487 	    (dmu_objset_projectquota_enabled(zfsvfs->z_os) &&
488 	    (zp->z_pflags & ZFS_PROJID) &&
489 	    sa_lookup(zp->z_sa_hdl, SA_ZPL_PROJID(zfsvfs), &projid, 8) != 0)) {
490 		if (hdl == NULL)
491 			sa_handle_destroy(zp->z_sa_hdl);
492 		zfs_vnode_forget(vp);
493 		zp->z_vnode = NULL;
494 		zfs_znode_free_kmem(zp);
495 		return (NULL);
496 	}
497 
498 	zp->z_projid = projid;
499 	zp->z_mode = mode;
500 
501 	/* Cache the xattr parent id */
502 	if (zp->z_pflags & ZFS_XATTR)
503 		zp->z_xattr_parent = parent;
504 
505 	vp->v_type = IFTOVT((mode_t)mode);
506 
507 	switch (vp->v_type) {
508 	case VDIR:
509 		zp->z_zn_prefetch = B_TRUE; /* z_prefetch default is enabled */
510 		break;
511 	case VFIFO:
512 		vp->v_op = &zfs_fifoops;
513 		break;
514 	case VREG:
515 		if (parent == zfsvfs->z_shares_dir) {
516 			ASSERT0(zp->z_uid);
517 			ASSERT0(zp->z_gid);
518 			vp->v_op = &zfs_shareops;
519 		}
520 		break;
521 	default:
522 			break;
523 	}
524 
525 	mutex_enter(&zfsvfs->z_znodes_lock);
526 	list_insert_tail(&zfsvfs->z_all_znodes, zp);
527 	zfsvfs->z_nr_znodes++;
528 	zp->z_zfsvfs = zfsvfs;
529 	mutex_exit(&zfsvfs->z_znodes_lock);
530 
531 	/*
532 	 * Acquire vnode lock before making it available to the world.
533 	 */
534 	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
535 	VN_LOCK_AREC(vp);
536 	if (vp->v_type != VFIFO)
537 		VN_LOCK_ASHARE(vp);
538 
539 	return (zp);
540 }
541 
542 static uint64_t empty_xattr;
543 static uint64_t pad[4];
544 static zfs_acl_phys_t acl_phys;
545 /*
546  * Create a new DMU object to hold a zfs znode.
547  *
548  *	IN:	dzp	- parent directory for new znode
549  *		vap	- file attributes for new znode
550  *		tx	- dmu transaction id for zap operations
551  *		cr	- credentials of caller
552  *		flag	- flags:
553  *			  IS_ROOT_NODE	- new object will be root
554  *			  IS_XATTR	- new object is an attribute
555  *		bonuslen - length of bonus buffer
556  *		setaclp  - File/Dir initial ACL
557  *		fuidp	 - Tracks fuid allocation.
558  *
559  *	OUT:	zpp	- allocated znode
560  *
561  */
562 void
563 zfs_mknode(znode_t *dzp, vattr_t *vap, dmu_tx_t *tx, cred_t *cr,
564     uint_t flag, znode_t **zpp, zfs_acl_ids_t *acl_ids)
565 {
566 	uint64_t	crtime[2], atime[2], mtime[2], ctime[2];
567 	uint64_t	mode, size, links, parent, pflags;
568 	uint64_t	dzp_pflags = 0;
569 	uint64_t	rdev = 0;
570 	zfsvfs_t	*zfsvfs = dzp->z_zfsvfs;
571 	dmu_buf_t	*db;
572 	timestruc_t	now;
573 	uint64_t	gen, obj;
574 	int		bonuslen;
575 	int		dnodesize;
576 	sa_handle_t	*sa_hdl;
577 	dmu_object_type_t obj_type;
578 	sa_bulk_attr_t	*sa_attrs;
579 	int		cnt = 0;
580 	zfs_acl_locator_cb_t locate = { 0 };
581 
582 	ASSERT3P(vap, !=, NULL);
583 	ASSERT3U((vap->va_mask & AT_MODE), ==, AT_MODE);
584 
585 	if (zfsvfs->z_replay) {
586 		obj = vap->va_nodeid;
587 		now = vap->va_ctime;		/* see zfs_replay_create() */
588 		gen = vap->va_nblocks;		/* ditto */
589 		dnodesize = vap->va_fsid;	/* ditto */
590 	} else {
591 		obj = 0;
592 		vfs_timestamp(&now);
593 		gen = dmu_tx_get_txg(tx);
594 		dnodesize = dmu_objset_dnodesize(zfsvfs->z_os);
595 	}
596 
597 	if (dnodesize == 0)
598 		dnodesize = DNODE_MIN_SIZE;
599 
600 	obj_type = zfsvfs->z_use_sa ? DMU_OT_SA : DMU_OT_ZNODE;
601 	bonuslen = (obj_type == DMU_OT_SA) ?
602 	    DN_BONUS_SIZE(dnodesize) : ZFS_OLD_ZNODE_PHYS_SIZE;
603 
604 	/*
605 	 * Create a new DMU object.
606 	 */
607 	/*
608 	 * There's currently no mechanism for pre-reading the blocks that will
609 	 * be needed to allocate a new object, so we accept the small chance
610 	 * that there will be an i/o error and we will fail one of the
611 	 * assertions below.
612 	 */
613 	if (vap->va_type == VDIR) {
614 		if (zfsvfs->z_replay) {
615 			VERIFY0(zap_create_claim_norm_dnsize(zfsvfs->z_os, obj,
616 			    zfsvfs->z_norm, DMU_OT_DIRECTORY_CONTENTS,
617 			    obj_type, bonuslen, dnodesize, tx));
618 		} else {
619 			obj = zap_create_norm_dnsize(zfsvfs->z_os,
620 			    zfsvfs->z_norm, DMU_OT_DIRECTORY_CONTENTS,
621 			    obj_type, bonuslen, dnodesize, tx);
622 		}
623 	} else {
624 		if (zfsvfs->z_replay) {
625 			VERIFY0(dmu_object_claim_dnsize(zfsvfs->z_os, obj,
626 			    DMU_OT_PLAIN_FILE_CONTENTS, 0,
627 			    obj_type, bonuslen, dnodesize, tx));
628 		} else {
629 			obj = dmu_object_alloc_dnsize(zfsvfs->z_os,
630 			    DMU_OT_PLAIN_FILE_CONTENTS, 0,
631 			    obj_type, bonuslen, dnodesize, tx);
632 		}
633 	}
634 
635 	ZFS_OBJ_HOLD_ENTER(zfsvfs, obj);
636 	VERIFY0(sa_buf_hold(zfsvfs->z_os, obj, NULL, &db));
637 
638 	/*
639 	 * If this is the root, fix up the half-initialized parent pointer
640 	 * to reference the just-allocated physical data area.
641 	 */
642 	if (flag & IS_ROOT_NODE) {
643 		dzp->z_id = obj;
644 	} else {
645 		dzp_pflags = dzp->z_pflags;
646 	}
647 
648 	/*
649 	 * If parent is an xattr, so am I.
650 	 */
651 	if (dzp_pflags & ZFS_XATTR) {
652 		flag |= IS_XATTR;
653 	}
654 
655 	if (zfsvfs->z_use_fuids)
656 		pflags = ZFS_ARCHIVE | ZFS_AV_MODIFIED;
657 	else
658 		pflags = 0;
659 
660 	if (vap->va_type == VDIR) {
661 		size = 2;		/* contents ("." and "..") */
662 		links = (flag & (IS_ROOT_NODE | IS_XATTR)) ? 2 : 1;
663 	} else {
664 		size = links = 0;
665 	}
666 
667 	if (vap->va_type == VBLK || vap->va_type == VCHR) {
668 		rdev = zfs_expldev(vap->va_rdev);
669 	}
670 
671 	parent = dzp->z_id;
672 	mode = acl_ids->z_mode;
673 	if (flag & IS_XATTR)
674 		pflags |= ZFS_XATTR;
675 
676 	/*
677 	 * No execs denied will be determined when zfs_mode_compute() is called.
678 	 */
679 	pflags |= acl_ids->z_aclp->z_hints &
680 	    (ZFS_ACL_TRIVIAL|ZFS_INHERIT_ACE|ZFS_ACL_AUTO_INHERIT|
681 	    ZFS_ACL_DEFAULTED|ZFS_ACL_PROTECTED);
682 
683 	ZFS_TIME_ENCODE(&now, crtime);
684 	ZFS_TIME_ENCODE(&now, ctime);
685 
686 	if (vap->va_mask & AT_ATIME) {
687 		ZFS_TIME_ENCODE(&vap->va_atime, atime);
688 	} else {
689 		ZFS_TIME_ENCODE(&now, atime);
690 	}
691 
692 	if (vap->va_mask & AT_MTIME) {
693 		ZFS_TIME_ENCODE(&vap->va_mtime, mtime);
694 	} else {
695 		ZFS_TIME_ENCODE(&now, mtime);
696 	}
697 
698 	/* Now add in all of the "SA" attributes */
699 	VERIFY0(sa_handle_get_from_db(zfsvfs->z_os, db, NULL, SA_HDL_SHARED,
700 	    &sa_hdl));
701 
702 	/*
703 	 * Setup the array of attributes to be replaced/set on the new file
704 	 *
705 	 * order for  DMU_OT_ZNODE is critical since it needs to be constructed
706 	 * in the old znode_phys_t format.  Don't change this ordering
707 	 */
708 	sa_attrs = kmem_alloc(sizeof (sa_bulk_attr_t) * ZPL_END, KM_SLEEP);
709 
710 	if (obj_type == DMU_OT_ZNODE) {
711 		SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_ATIME(zfsvfs),
712 		    NULL, &atime, 16);
713 		SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_MTIME(zfsvfs),
714 		    NULL, &mtime, 16);
715 		SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_CTIME(zfsvfs),
716 		    NULL, &ctime, 16);
717 		SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_CRTIME(zfsvfs),
718 		    NULL, &crtime, 16);
719 		SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_GEN(zfsvfs),
720 		    NULL, &gen, 8);
721 		SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_MODE(zfsvfs),
722 		    NULL, &mode, 8);
723 		SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_SIZE(zfsvfs),
724 		    NULL, &size, 8);
725 		SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_PARENT(zfsvfs),
726 		    NULL, &parent, 8);
727 	} else {
728 		SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_MODE(zfsvfs),
729 		    NULL, &mode, 8);
730 		SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_SIZE(zfsvfs),
731 		    NULL, &size, 8);
732 		SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_GEN(zfsvfs),
733 		    NULL, &gen, 8);
734 		SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_UID(zfsvfs),
735 		    NULL, &acl_ids->z_fuid, 8);
736 		SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_GID(zfsvfs),
737 		    NULL, &acl_ids->z_fgid, 8);
738 		SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_PARENT(zfsvfs),
739 		    NULL, &parent, 8);
740 		SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_FLAGS(zfsvfs),
741 		    NULL, &pflags, 8);
742 		SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_ATIME(zfsvfs),
743 		    NULL, &atime, 16);
744 		SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_MTIME(zfsvfs),
745 		    NULL, &mtime, 16);
746 		SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_CTIME(zfsvfs),
747 		    NULL, &ctime, 16);
748 		SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_CRTIME(zfsvfs),
749 		    NULL, &crtime, 16);
750 	}
751 
752 	SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_LINKS(zfsvfs), NULL, &links, 8);
753 
754 	if (obj_type == DMU_OT_ZNODE) {
755 		SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_XATTR(zfsvfs), NULL,
756 		    &empty_xattr, 8);
757 	}
758 	if (obj_type == DMU_OT_ZNODE ||
759 	    (vap->va_type == VBLK || vap->va_type == VCHR)) {
760 		SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_RDEV(zfsvfs),
761 		    NULL, &rdev, 8);
762 
763 	}
764 	if (obj_type == DMU_OT_ZNODE) {
765 		SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_FLAGS(zfsvfs),
766 		    NULL, &pflags, 8);
767 		SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_UID(zfsvfs), NULL,
768 		    &acl_ids->z_fuid, 8);
769 		SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_GID(zfsvfs), NULL,
770 		    &acl_ids->z_fgid, 8);
771 		SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_PAD(zfsvfs), NULL, pad,
772 		    sizeof (uint64_t) * 4);
773 		SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_ZNODE_ACL(zfsvfs), NULL,
774 		    &acl_phys, sizeof (zfs_acl_phys_t));
775 	} else if (acl_ids->z_aclp->z_version >= ZFS_ACL_VERSION_FUID) {
776 		SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_DACL_COUNT(zfsvfs), NULL,
777 		    &acl_ids->z_aclp->z_acl_count, 8);
778 		locate.cb_aclp = acl_ids->z_aclp;
779 		SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_DACL_ACES(zfsvfs),
780 		    zfs_acl_data_locator, &locate,
781 		    acl_ids->z_aclp->z_acl_bytes);
782 		mode = zfs_mode_compute(mode, acl_ids->z_aclp, &pflags,
783 		    acl_ids->z_fuid, acl_ids->z_fgid);
784 	}
785 
786 	VERIFY0(sa_replace_all_by_template(sa_hdl, sa_attrs, cnt, tx));
787 
788 	if (!(flag & IS_ROOT_NODE)) {
789 		*zpp = zfs_znode_alloc(zfsvfs, db, 0, obj_type, sa_hdl);
790 		ASSERT3P(*zpp, !=, NULL);
791 	} else {
792 		/*
793 		 * If we are creating the root node, the "parent" we
794 		 * passed in is the znode for the root.
795 		 */
796 		*zpp = dzp;
797 
798 		(*zpp)->z_sa_hdl = sa_hdl;
799 	}
800 
801 	(*zpp)->z_pflags = pflags;
802 	(*zpp)->z_mode = mode;
803 	(*zpp)->z_dnodesize = dnodesize;
804 
805 	if (vap->va_mask & AT_XVATTR)
806 		zfs_xvattr_set(*zpp, (xvattr_t *)vap, tx);
807 
808 	if (obj_type == DMU_OT_ZNODE ||
809 	    acl_ids->z_aclp->z_version < ZFS_ACL_VERSION_FUID) {
810 		VERIFY0(zfs_aclset_common(*zpp, acl_ids->z_aclp, cr, tx));
811 	}
812 	if (!(flag & IS_ROOT_NODE)) {
813 		vnode_t *vp = ZTOV(*zpp);
814 		vp->v_vflag |= VV_FORCEINSMQ;
815 		int err = insmntque(vp, zfsvfs->z_vfs);
816 		vp->v_vflag &= ~VV_FORCEINSMQ;
817 		(void) err;
818 		KASSERT(err == 0, ("insmntque() failed: error %d", err));
819 	}
820 	kmem_free(sa_attrs, sizeof (sa_bulk_attr_t) * ZPL_END);
821 	ZFS_OBJ_HOLD_EXIT(zfsvfs, obj);
822 }
823 
824 /*
825  * Update in-core attributes.  It is assumed the caller will be doing an
826  * sa_bulk_update to push the changes out.
827  */
828 void
829 zfs_xvattr_set(znode_t *zp, xvattr_t *xvap, dmu_tx_t *tx)
830 {
831 	xoptattr_t *xoap;
832 
833 	xoap = xva_getxoptattr(xvap);
834 	ASSERT3P(xoap, !=, NULL);
835 
836 	if (zp->z_zfsvfs->z_replay == B_FALSE) {
837 		ASSERT_VOP_IN_SEQC(ZTOV(zp));
838 	}
839 
840 	if (XVA_ISSET_REQ(xvap, XAT_CREATETIME)) {
841 		uint64_t times[2];
842 		ZFS_TIME_ENCODE(&xoap->xoa_createtime, times);
843 		(void) sa_update(zp->z_sa_hdl, SA_ZPL_CRTIME(zp->z_zfsvfs),
844 		    &times, sizeof (times), tx);
845 		XVA_SET_RTN(xvap, XAT_CREATETIME);
846 	}
847 	if (XVA_ISSET_REQ(xvap, XAT_READONLY)) {
848 		ZFS_ATTR_SET(zp, ZFS_READONLY, xoap->xoa_readonly,
849 		    zp->z_pflags, tx);
850 		XVA_SET_RTN(xvap, XAT_READONLY);
851 	}
852 	if (XVA_ISSET_REQ(xvap, XAT_HIDDEN)) {
853 		ZFS_ATTR_SET(zp, ZFS_HIDDEN, xoap->xoa_hidden,
854 		    zp->z_pflags, tx);
855 		XVA_SET_RTN(xvap, XAT_HIDDEN);
856 	}
857 	if (XVA_ISSET_REQ(xvap, XAT_SYSTEM)) {
858 		ZFS_ATTR_SET(zp, ZFS_SYSTEM, xoap->xoa_system,
859 		    zp->z_pflags, tx);
860 		XVA_SET_RTN(xvap, XAT_SYSTEM);
861 	}
862 	if (XVA_ISSET_REQ(xvap, XAT_ARCHIVE)) {
863 		ZFS_ATTR_SET(zp, ZFS_ARCHIVE, xoap->xoa_archive,
864 		    zp->z_pflags, tx);
865 		XVA_SET_RTN(xvap, XAT_ARCHIVE);
866 	}
867 	if (XVA_ISSET_REQ(xvap, XAT_IMMUTABLE)) {
868 		ZFS_ATTR_SET(zp, ZFS_IMMUTABLE, xoap->xoa_immutable,
869 		    zp->z_pflags, tx);
870 		XVA_SET_RTN(xvap, XAT_IMMUTABLE);
871 	}
872 	if (XVA_ISSET_REQ(xvap, XAT_NOUNLINK)) {
873 		ZFS_ATTR_SET(zp, ZFS_NOUNLINK, xoap->xoa_nounlink,
874 		    zp->z_pflags, tx);
875 		XVA_SET_RTN(xvap, XAT_NOUNLINK);
876 	}
877 	if (XVA_ISSET_REQ(xvap, XAT_APPENDONLY)) {
878 		ZFS_ATTR_SET(zp, ZFS_APPENDONLY, xoap->xoa_appendonly,
879 		    zp->z_pflags, tx);
880 		XVA_SET_RTN(xvap, XAT_APPENDONLY);
881 	}
882 	if (XVA_ISSET_REQ(xvap, XAT_NODUMP)) {
883 		ZFS_ATTR_SET(zp, ZFS_NODUMP, xoap->xoa_nodump,
884 		    zp->z_pflags, tx);
885 		XVA_SET_RTN(xvap, XAT_NODUMP);
886 	}
887 	if (XVA_ISSET_REQ(xvap, XAT_OPAQUE)) {
888 		ZFS_ATTR_SET(zp, ZFS_OPAQUE, xoap->xoa_opaque,
889 		    zp->z_pflags, tx);
890 		XVA_SET_RTN(xvap, XAT_OPAQUE);
891 	}
892 	if (XVA_ISSET_REQ(xvap, XAT_AV_QUARANTINED)) {
893 		ZFS_ATTR_SET(zp, ZFS_AV_QUARANTINED,
894 		    xoap->xoa_av_quarantined, zp->z_pflags, tx);
895 		XVA_SET_RTN(xvap, XAT_AV_QUARANTINED);
896 	}
897 	if (XVA_ISSET_REQ(xvap, XAT_AV_MODIFIED)) {
898 		ZFS_ATTR_SET(zp, ZFS_AV_MODIFIED, xoap->xoa_av_modified,
899 		    zp->z_pflags, tx);
900 		XVA_SET_RTN(xvap, XAT_AV_MODIFIED);
901 	}
902 	if (XVA_ISSET_REQ(xvap, XAT_AV_SCANSTAMP)) {
903 		zfs_sa_set_scanstamp(zp, xvap, tx);
904 		XVA_SET_RTN(xvap, XAT_AV_SCANSTAMP);
905 	}
906 	if (XVA_ISSET_REQ(xvap, XAT_REPARSE)) {
907 		ZFS_ATTR_SET(zp, ZFS_REPARSE, xoap->xoa_reparse,
908 		    zp->z_pflags, tx);
909 		XVA_SET_RTN(xvap, XAT_REPARSE);
910 	}
911 	if (XVA_ISSET_REQ(xvap, XAT_OFFLINE)) {
912 		ZFS_ATTR_SET(zp, ZFS_OFFLINE, xoap->xoa_offline,
913 		    zp->z_pflags, tx);
914 		XVA_SET_RTN(xvap, XAT_OFFLINE);
915 	}
916 	if (XVA_ISSET_REQ(xvap, XAT_SPARSE)) {
917 		ZFS_ATTR_SET(zp, ZFS_SPARSE, xoap->xoa_sparse,
918 		    zp->z_pflags, tx);
919 		XVA_SET_RTN(xvap, XAT_SPARSE);
920 	}
921 }
922 
923 int
924 zfs_zget(zfsvfs_t *zfsvfs, uint64_t obj_num, znode_t **zpp)
925 {
926 	dmu_object_info_t doi;
927 	dmu_buf_t	*db;
928 	znode_t		*zp;
929 	vnode_t		*vp;
930 	sa_handle_t	*hdl;
931 	int locked;
932 	int err;
933 
934 	getnewvnode_reserve_();
935 again:
936 	*zpp = NULL;
937 	ZFS_OBJ_HOLD_ENTER(zfsvfs, obj_num);
938 
939 	err = sa_buf_hold(zfsvfs->z_os, obj_num, NULL, &db);
940 	if (err) {
941 		ZFS_OBJ_HOLD_EXIT(zfsvfs, obj_num);
942 		getnewvnode_drop_reserve();
943 		return (err);
944 	}
945 
946 	dmu_object_info_from_db(db, &doi);
947 	if (doi.doi_bonus_type != DMU_OT_SA &&
948 	    (doi.doi_bonus_type != DMU_OT_ZNODE ||
949 	    (doi.doi_bonus_type == DMU_OT_ZNODE &&
950 	    doi.doi_bonus_size < sizeof (znode_phys_t)))) {
951 		sa_buf_rele(db, NULL);
952 		ZFS_OBJ_HOLD_EXIT(zfsvfs, obj_num);
953 		getnewvnode_drop_reserve();
954 		return (SET_ERROR(EINVAL));
955 	}
956 
957 	hdl = dmu_buf_get_user(db);
958 	if (hdl != NULL) {
959 		zp = sa_get_userdata(hdl);
960 
961 		/*
962 		 * Since "SA" does immediate eviction we
963 		 * should never find a sa handle that doesn't
964 		 * know about the znode.
965 		 */
966 		ASSERT3P(zp, !=, NULL);
967 		ASSERT3U(zp->z_id, ==, obj_num);
968 		if (zp->z_unlinked) {
969 			err = SET_ERROR(ENOENT);
970 		} else {
971 			vp = ZTOV(zp);
972 			/*
973 			 * Don't let the vnode disappear after
974 			 * ZFS_OBJ_HOLD_EXIT.
975 			 */
976 			VN_HOLD(vp);
977 			*zpp = zp;
978 			err = 0;
979 		}
980 
981 		sa_buf_rele(db, NULL);
982 		ZFS_OBJ_HOLD_EXIT(zfsvfs, obj_num);
983 
984 		if (err) {
985 			getnewvnode_drop_reserve();
986 			return (err);
987 		}
988 
989 		locked = VOP_ISLOCKED(vp);
990 		VI_LOCK(vp);
991 		if (VN_IS_DOOMED(vp) && locked != LK_EXCLUSIVE) {
992 			/*
993 			 * The vnode is doomed and this thread doesn't
994 			 * hold the exclusive lock on it, so the vnode
995 			 * must be being reclaimed by another thread.
996 			 * Otherwise the doomed vnode is being reclaimed
997 			 * by this thread and zfs_zget is called from
998 			 * ZIL internals.
999 			 */
1000 			VI_UNLOCK(vp);
1001 
1002 			/*
1003 			 * XXX vrele() locks the vnode when the last reference
1004 			 * is dropped.  Although in this case the vnode is
1005 			 * doomed / dead and so no inactivation is required,
1006 			 * the vnode lock is still acquired.  That could result
1007 			 * in a LOR with z_teardown_lock if another thread holds
1008 			 * the vnode's lock and tries to take z_teardown_lock.
1009 			 * But that is only possible if the other thread peforms
1010 			 * a ZFS vnode operation on the vnode.  That either
1011 			 * should not happen if the vnode is dead or the thread
1012 			 * should also have a reference to the vnode and thus
1013 			 * our reference is not last.
1014 			 */
1015 			VN_RELE(vp);
1016 			goto again;
1017 		}
1018 		VI_UNLOCK(vp);
1019 		getnewvnode_drop_reserve();
1020 		return (err);
1021 	}
1022 
1023 	/*
1024 	 * Not found create new znode/vnode
1025 	 * but only if file exists.
1026 	 *
1027 	 * There is a small window where zfs_vget() could
1028 	 * find this object while a file create is still in
1029 	 * progress.  This is checked for in zfs_znode_alloc()
1030 	 *
1031 	 * if zfs_znode_alloc() fails it will drop the hold on the
1032 	 * bonus buffer.
1033 	 */
1034 	zp = zfs_znode_alloc(zfsvfs, db, doi.doi_data_block_size,
1035 	    doi.doi_bonus_type, NULL);
1036 	if (zp == NULL) {
1037 		err = SET_ERROR(ENOENT);
1038 	} else {
1039 		*zpp = zp;
1040 	}
1041 	if (err == 0) {
1042 		vnode_t *vp = ZTOV(zp);
1043 
1044 		err = insmntque(vp, zfsvfs->z_vfs);
1045 		if (err == 0) {
1046 			vp->v_hash = obj_num;
1047 			VOP_UNLOCK1(vp);
1048 		} else {
1049 			zp->z_vnode = NULL;
1050 			zfs_znode_dmu_fini(zp);
1051 			zfs_znode_free(zp);
1052 			*zpp = NULL;
1053 		}
1054 	}
1055 	ZFS_OBJ_HOLD_EXIT(zfsvfs, obj_num);
1056 	getnewvnode_drop_reserve();
1057 	return (err);
1058 }
1059 
1060 int
1061 zfs_rezget(znode_t *zp)
1062 {
1063 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
1064 	dmu_object_info_t doi;
1065 	dmu_buf_t *db;
1066 	vnode_t *vp;
1067 	uint64_t obj_num = zp->z_id;
1068 	uint64_t mode, size;
1069 	sa_bulk_attr_t bulk[8];
1070 	int err;
1071 	int count = 0;
1072 	uint64_t gen;
1073 
1074 	/*
1075 	 * Remove cached pages before reloading the znode, so that they are not
1076 	 * lingering after we run into any error.  Ideally, we should vgone()
1077 	 * the vnode in case of error, but currently we cannot do that
1078 	 * because of the LOR between the vnode lock and z_teardown_lock.
1079 	 * So, instead, we have to "doom" the znode in the illumos style.
1080 	 *
1081 	 * Ignore invalid pages during the scan.  This is to avoid deadlocks
1082 	 * between page busying and the teardown lock, as pages are busied prior
1083 	 * to a VOP_GETPAGES operation, which acquires the teardown read lock.
1084 	 * Such pages will be invalid and can safely be skipped here.
1085 	 */
1086 	vp = ZTOV(zp);
1087 #if __FreeBSD_version >= 1400042
1088 	vn_pages_remove_valid(vp, 0, 0);
1089 #else
1090 	vn_pages_remove(vp, 0, 0);
1091 #endif
1092 
1093 	ZFS_OBJ_HOLD_ENTER(zfsvfs, obj_num);
1094 
1095 	mutex_enter(&zp->z_acl_lock);
1096 	if (zp->z_acl_cached) {
1097 		zfs_acl_free(zp->z_acl_cached);
1098 		zp->z_acl_cached = NULL;
1099 	}
1100 	mutex_exit(&zp->z_acl_lock);
1101 
1102 	rw_enter(&zp->z_xattr_lock, RW_WRITER);
1103 	if (zp->z_xattr_cached) {
1104 		nvlist_free(zp->z_xattr_cached);
1105 		zp->z_xattr_cached = NULL;
1106 	}
1107 	rw_exit(&zp->z_xattr_lock);
1108 
1109 	ASSERT3P(zp->z_sa_hdl, ==, NULL);
1110 	err = sa_buf_hold(zfsvfs->z_os, obj_num, NULL, &db);
1111 	if (err) {
1112 		ZFS_OBJ_HOLD_EXIT(zfsvfs, obj_num);
1113 		return (err);
1114 	}
1115 
1116 	dmu_object_info_from_db(db, &doi);
1117 	if (doi.doi_bonus_type != DMU_OT_SA &&
1118 	    (doi.doi_bonus_type != DMU_OT_ZNODE ||
1119 	    (doi.doi_bonus_type == DMU_OT_ZNODE &&
1120 	    doi.doi_bonus_size < sizeof (znode_phys_t)))) {
1121 		sa_buf_rele(db, NULL);
1122 		ZFS_OBJ_HOLD_EXIT(zfsvfs, obj_num);
1123 		return (SET_ERROR(EINVAL));
1124 	}
1125 
1126 	zfs_znode_sa_init(zfsvfs, zp, db, doi.doi_bonus_type, NULL);
1127 	size = zp->z_size;
1128 
1129 	/* reload cached values */
1130 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_GEN(zfsvfs), NULL,
1131 	    &gen, sizeof (gen));
1132 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_SIZE(zfsvfs), NULL,
1133 	    &zp->z_size, sizeof (zp->z_size));
1134 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_LINKS(zfsvfs), NULL,
1135 	    &zp->z_links, sizeof (zp->z_links));
1136 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_FLAGS(zfsvfs), NULL,
1137 	    &zp->z_pflags, sizeof (zp->z_pflags));
1138 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_ATIME(zfsvfs), NULL,
1139 	    &zp->z_atime, sizeof (zp->z_atime));
1140 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_UID(zfsvfs), NULL,
1141 	    &zp->z_uid, sizeof (zp->z_uid));
1142 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_GID(zfsvfs), NULL,
1143 	    &zp->z_gid, sizeof (zp->z_gid));
1144 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MODE(zfsvfs), NULL,
1145 	    &mode, sizeof (mode));
1146 
1147 	if (sa_bulk_lookup(zp->z_sa_hdl, bulk, count)) {
1148 		zfs_znode_dmu_fini(zp);
1149 		ZFS_OBJ_HOLD_EXIT(zfsvfs, obj_num);
1150 		return (SET_ERROR(EIO));
1151 	}
1152 
1153 	zp->z_mode = mode;
1154 
1155 	if (gen != zp->z_gen) {
1156 		zfs_znode_dmu_fini(zp);
1157 		ZFS_OBJ_HOLD_EXIT(zfsvfs, obj_num);
1158 		return (SET_ERROR(EIO));
1159 	}
1160 
1161 	/*
1162 	 * It is highly improbable but still quite possible that two
1163 	 * objects in different datasets are created with the same
1164 	 * object numbers and in transaction groups with the same
1165 	 * numbers.  znodes corresponding to those objects would
1166 	 * have the same z_id and z_gen, but their other attributes
1167 	 * may be different.
1168 	 * zfs recv -F may replace one of such objects with the other.
1169 	 * As a result file properties recorded in the replaced
1170 	 * object's vnode may no longer match the received object's
1171 	 * properties.  At present the only cached property is the
1172 	 * files type recorded in v_type.
1173 	 * So, handle this case by leaving the old vnode and znode
1174 	 * disassociated from the actual object.  A new vnode and a
1175 	 * znode will be created if the object is accessed
1176 	 * (e.g. via a look-up).  The old vnode and znode will be
1177 	 * recycled when the last vnode reference is dropped.
1178 	 */
1179 	if (vp->v_type != IFTOVT((mode_t)zp->z_mode)) {
1180 		zfs_znode_dmu_fini(zp);
1181 		ZFS_OBJ_HOLD_EXIT(zfsvfs, obj_num);
1182 		return (SET_ERROR(EIO));
1183 	}
1184 
1185 	/*
1186 	 * If the file has zero links, then it has been unlinked on the send
1187 	 * side and it must be in the received unlinked set.
1188 	 * We call zfs_znode_dmu_fini() now to prevent any accesses to the
1189 	 * stale data and to prevent automatically removal of the file in
1190 	 * zfs_zinactive().  The file will be removed either when it is removed
1191 	 * on the send side and the next incremental stream is received or
1192 	 * when the unlinked set gets processed.
1193 	 */
1194 	zp->z_unlinked = (zp->z_links == 0);
1195 	if (zp->z_unlinked) {
1196 		zfs_znode_dmu_fini(zp);
1197 		ZFS_OBJ_HOLD_EXIT(zfsvfs, obj_num);
1198 		return (0);
1199 	}
1200 
1201 	zp->z_blksz = doi.doi_data_block_size;
1202 	if (zp->z_size != size)
1203 		vnode_pager_setsize(vp, zp->z_size);
1204 
1205 	ZFS_OBJ_HOLD_EXIT(zfsvfs, obj_num);
1206 
1207 	return (0);
1208 }
1209 
1210 void
1211 zfs_znode_delete(znode_t *zp, dmu_tx_t *tx)
1212 {
1213 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
1214 	objset_t *os = zfsvfs->z_os;
1215 	uint64_t obj = zp->z_id;
1216 	uint64_t acl_obj = zfs_external_acl(zp);
1217 
1218 	ZFS_OBJ_HOLD_ENTER(zfsvfs, obj);
1219 	if (acl_obj) {
1220 		VERIFY(!zp->z_is_sa);
1221 		VERIFY0(dmu_object_free(os, acl_obj, tx));
1222 	}
1223 	VERIFY0(dmu_object_free(os, obj, tx));
1224 	zfs_znode_dmu_fini(zp);
1225 	ZFS_OBJ_HOLD_EXIT(zfsvfs, obj);
1226 	zfs_znode_free(zp);
1227 }
1228 
1229 void
1230 zfs_zinactive(znode_t *zp)
1231 {
1232 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
1233 	uint64_t z_id = zp->z_id;
1234 
1235 	ASSERT3P(zp->z_sa_hdl, !=, NULL);
1236 
1237 	/*
1238 	 * Don't allow a zfs_zget() while were trying to release this znode
1239 	 */
1240 	ZFS_OBJ_HOLD_ENTER(zfsvfs, z_id);
1241 
1242 	/*
1243 	 * If this was the last reference to a file with no links, remove
1244 	 * the file from the file system unless the file system is mounted
1245 	 * read-only.  That can happen, for example, if the file system was
1246 	 * originally read-write, the file was opened, then unlinked and
1247 	 * the file system was made read-only before the file was finally
1248 	 * closed.  The file will remain in the unlinked set.
1249 	 */
1250 	if (zp->z_unlinked) {
1251 		ASSERT(!zfsvfs->z_issnap);
1252 		if ((zfsvfs->z_vfs->vfs_flag & VFS_RDONLY) == 0) {
1253 			ZFS_OBJ_HOLD_EXIT(zfsvfs, z_id);
1254 			zfs_rmnode(zp);
1255 			return;
1256 		}
1257 	}
1258 
1259 	zfs_znode_dmu_fini(zp);
1260 	ZFS_OBJ_HOLD_EXIT(zfsvfs, z_id);
1261 	zfs_znode_free(zp);
1262 }
1263 
1264 void
1265 zfs_znode_free(znode_t *zp)
1266 {
1267 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
1268 #if __FreeBSD_version >= 1300139
1269 	char *symlink;
1270 #endif
1271 
1272 	ASSERT3P(zp->z_sa_hdl, ==, NULL);
1273 	zp->z_vnode = NULL;
1274 	mutex_enter(&zfsvfs->z_znodes_lock);
1275 	POINTER_INVALIDATE(&zp->z_zfsvfs);
1276 	list_remove(&zfsvfs->z_all_znodes, zp);
1277 	zfsvfs->z_nr_znodes--;
1278 	mutex_exit(&zfsvfs->z_znodes_lock);
1279 	symlink = atomic_load_ptr(&zp->z_cached_symlink);
1280 	if (symlink != NULL) {
1281 		atomic_store_rel_ptr((uintptr_t *)&zp->z_cached_symlink, (uintptr_t)NULL);
1282 		cache_symlink_free(symlink, strlen(symlink) + 1);
1283 	}
1284 
1285 #if __FreeBSD_version >= 1300139
1286 	symlink = atomic_load_ptr(&zp->z_cached_symlink);
1287 	if (symlink != NULL) {
1288 		atomic_store_rel_ptr((uintptr_t *)&zp->z_cached_symlink,
1289 		    (uintptr_t)NULL);
1290 		cache_symlink_free(symlink, strlen(symlink) + 1);
1291 	}
1292 #endif
1293 
1294 	if (zp->z_acl_cached) {
1295 		zfs_acl_free(zp->z_acl_cached);
1296 		zp->z_acl_cached = NULL;
1297 	}
1298 
1299 	zfs_znode_free_kmem(zp);
1300 }
1301 
1302 void
1303 zfs_tstamp_update_setup_ext(znode_t *zp, uint_t flag, uint64_t mtime[2],
1304     uint64_t ctime[2], boolean_t have_tx)
1305 {
1306 	timestruc_t	now;
1307 
1308 	vfs_timestamp(&now);
1309 
1310 	if (have_tx) {	/* will sa_bulk_update happen really soon? */
1311 		zp->z_atime_dirty = 0;
1312 		zp->z_seq++;
1313 	} else {
1314 		zp->z_atime_dirty = 1;
1315 	}
1316 
1317 	if (flag & AT_ATIME) {
1318 		ZFS_TIME_ENCODE(&now, zp->z_atime);
1319 	}
1320 
1321 	if (flag & AT_MTIME) {
1322 		ZFS_TIME_ENCODE(&now, mtime);
1323 		if (zp->z_zfsvfs->z_use_fuids) {
1324 			zp->z_pflags |= (ZFS_ARCHIVE |
1325 			    ZFS_AV_MODIFIED);
1326 		}
1327 	}
1328 
1329 	if (flag & AT_CTIME) {
1330 		ZFS_TIME_ENCODE(&now, ctime);
1331 		if (zp->z_zfsvfs->z_use_fuids)
1332 			zp->z_pflags |= ZFS_ARCHIVE;
1333 	}
1334 }
1335 
1336 
1337 void
1338 zfs_tstamp_update_setup(znode_t *zp, uint_t flag, uint64_t mtime[2],
1339     uint64_t ctime[2])
1340 {
1341 	zfs_tstamp_update_setup_ext(zp, flag, mtime, ctime, B_TRUE);
1342 }
1343 /*
1344  * Grow the block size for a file.
1345  *
1346  *	IN:	zp	- znode of file to free data in.
1347  *		size	- requested block size
1348  *		tx	- open transaction.
1349  *
1350  * NOTE: this function assumes that the znode is write locked.
1351  */
1352 void
1353 zfs_grow_blocksize(znode_t *zp, uint64_t size, dmu_tx_t *tx)
1354 {
1355 	int		error;
1356 	u_longlong_t	dummy;
1357 
1358 	if (size <= zp->z_blksz)
1359 		return;
1360 	/*
1361 	 * If the file size is already greater than the current blocksize,
1362 	 * we will not grow.  If there is more than one block in a file,
1363 	 * the blocksize cannot change.
1364 	 */
1365 	if (zp->z_blksz && zp->z_size > zp->z_blksz)
1366 		return;
1367 
1368 	error = dmu_object_set_blocksize(zp->z_zfsvfs->z_os, zp->z_id,
1369 	    size, 0, tx);
1370 
1371 	if (error == ENOTSUP)
1372 		return;
1373 	ASSERT0(error);
1374 
1375 	/* What blocksize did we actually get? */
1376 	dmu_object_size_from_db(sa_get_db(zp->z_sa_hdl), &zp->z_blksz, &dummy);
1377 }
1378 
1379 /*
1380  * Increase the file length
1381  *
1382  *	IN:	zp	- znode of file to free data in.
1383  *		end	- new end-of-file
1384  *
1385  *	RETURN:	0 on success, error code on failure
1386  */
1387 static int
1388 zfs_extend(znode_t *zp, uint64_t end)
1389 {
1390 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
1391 	dmu_tx_t *tx;
1392 	zfs_locked_range_t *lr;
1393 	uint64_t newblksz;
1394 	int error;
1395 
1396 	/*
1397 	 * We will change zp_size, lock the whole file.
1398 	 */
1399 	lr = zfs_rangelock_enter(&zp->z_rangelock, 0, UINT64_MAX, RL_WRITER);
1400 
1401 	/*
1402 	 * Nothing to do if file already at desired length.
1403 	 */
1404 	if (end <= zp->z_size) {
1405 		zfs_rangelock_exit(lr);
1406 		return (0);
1407 	}
1408 	tx = dmu_tx_create(zfsvfs->z_os);
1409 	dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE);
1410 	zfs_sa_upgrade_txholds(tx, zp);
1411 	if (end > zp->z_blksz &&
1412 	    (!ISP2(zp->z_blksz) || zp->z_blksz < zfsvfs->z_max_blksz)) {
1413 		/*
1414 		 * We are growing the file past the current block size.
1415 		 */
1416 		if (zp->z_blksz > zp->z_zfsvfs->z_max_blksz) {
1417 			/*
1418 			 * File's blocksize is already larger than the
1419 			 * "recordsize" property.  Only let it grow to
1420 			 * the next power of 2.
1421 			 */
1422 			ASSERT(!ISP2(zp->z_blksz));
1423 			newblksz = MIN(end, 1 << highbit64(zp->z_blksz));
1424 		} else {
1425 			newblksz = MIN(end, zp->z_zfsvfs->z_max_blksz);
1426 		}
1427 		dmu_tx_hold_write(tx, zp->z_id, 0, newblksz);
1428 	} else {
1429 		newblksz = 0;
1430 	}
1431 
1432 	error = dmu_tx_assign(tx, TXG_WAIT);
1433 	if (error) {
1434 		dmu_tx_abort(tx);
1435 		zfs_rangelock_exit(lr);
1436 		return (error);
1437 	}
1438 
1439 	if (newblksz)
1440 		zfs_grow_blocksize(zp, newblksz, tx);
1441 
1442 	zp->z_size = end;
1443 
1444 	VERIFY0(sa_update(zp->z_sa_hdl, SA_ZPL_SIZE(zp->z_zfsvfs),
1445 	    &zp->z_size, sizeof (zp->z_size), tx));
1446 
1447 	vnode_pager_setsize(ZTOV(zp), end);
1448 
1449 	zfs_rangelock_exit(lr);
1450 
1451 	dmu_tx_commit(tx);
1452 
1453 	return (0);
1454 }
1455 
1456 /*
1457  * Free space in a file.
1458  *
1459  *	IN:	zp	- znode of file to free data in.
1460  *		off	- start of section to free.
1461  *		len	- length of section to free.
1462  *
1463  *	RETURN:	0 on success, error code on failure
1464  */
1465 static int
1466 zfs_free_range(znode_t *zp, uint64_t off, uint64_t len)
1467 {
1468 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
1469 	zfs_locked_range_t *lr;
1470 	int error;
1471 
1472 	/*
1473 	 * Lock the range being freed.
1474 	 */
1475 	lr = zfs_rangelock_enter(&zp->z_rangelock, off, len, RL_WRITER);
1476 
1477 	/*
1478 	 * Nothing to do if file already at desired length.
1479 	 */
1480 	if (off >= zp->z_size) {
1481 		zfs_rangelock_exit(lr);
1482 		return (0);
1483 	}
1484 
1485 	if (off + len > zp->z_size)
1486 		len = zp->z_size - off;
1487 
1488 	error = dmu_free_long_range(zfsvfs->z_os, zp->z_id, off, len);
1489 
1490 	if (error == 0) {
1491 #if __FreeBSD_version >= 1400032
1492 		vnode_pager_purge_range(ZTOV(zp), off, off + len);
1493 #else
1494 		/*
1495 		 * Before __FreeBSD_version 1400032 we cannot free block in the
1496 		 * middle of a file, but only at the end of a file, so this code
1497 		 * path should never happen.
1498 		 */
1499 		vnode_pager_setsize(ZTOV(zp), off);
1500 #endif
1501 	}
1502 
1503 	zfs_rangelock_exit(lr);
1504 
1505 	return (error);
1506 }
1507 
1508 /*
1509  * Truncate a file
1510  *
1511  *	IN:	zp	- znode of file to free data in.
1512  *		end	- new end-of-file.
1513  *
1514  *	RETURN:	0 on success, error code on failure
1515  */
1516 static int
1517 zfs_trunc(znode_t *zp, uint64_t end)
1518 {
1519 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
1520 	vnode_t *vp = ZTOV(zp);
1521 	dmu_tx_t *tx;
1522 	zfs_locked_range_t *lr;
1523 	int error;
1524 	sa_bulk_attr_t bulk[2];
1525 	int count = 0;
1526 
1527 	/*
1528 	 * We will change zp_size, lock the whole file.
1529 	 */
1530 	lr = zfs_rangelock_enter(&zp->z_rangelock, 0, UINT64_MAX, RL_WRITER);
1531 
1532 	/*
1533 	 * Nothing to do if file already at desired length.
1534 	 */
1535 	if (end >= zp->z_size) {
1536 		zfs_rangelock_exit(lr);
1537 		return (0);
1538 	}
1539 
1540 	error = dmu_free_long_range(zfsvfs->z_os, zp->z_id, end,
1541 	    DMU_OBJECT_END);
1542 	if (error) {
1543 		zfs_rangelock_exit(lr);
1544 		return (error);
1545 	}
1546 	tx = dmu_tx_create(zfsvfs->z_os);
1547 	dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE);
1548 	zfs_sa_upgrade_txholds(tx, zp);
1549 	dmu_tx_mark_netfree(tx);
1550 	error = dmu_tx_assign(tx, TXG_WAIT);
1551 	if (error) {
1552 		dmu_tx_abort(tx);
1553 		zfs_rangelock_exit(lr);
1554 		return (error);
1555 	}
1556 
1557 	zp->z_size = end;
1558 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_SIZE(zfsvfs),
1559 	    NULL, &zp->z_size, sizeof (zp->z_size));
1560 
1561 	if (end == 0) {
1562 		zp->z_pflags &= ~ZFS_SPARSE;
1563 		SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_FLAGS(zfsvfs),
1564 		    NULL, &zp->z_pflags, 8);
1565 	}
1566 	VERIFY0(sa_bulk_update(zp->z_sa_hdl, bulk, count, tx));
1567 
1568 	dmu_tx_commit(tx);
1569 
1570 	/*
1571 	 * Clear any mapped pages in the truncated region.  This has to
1572 	 * happen outside of the transaction to avoid the possibility of
1573 	 * a deadlock with someone trying to push a page that we are
1574 	 * about to invalidate.
1575 	 */
1576 	vnode_pager_setsize(vp, end);
1577 
1578 	zfs_rangelock_exit(lr);
1579 
1580 	return (0);
1581 }
1582 
1583 /*
1584  * Free space in a file
1585  *
1586  *	IN:	zp	- znode of file to free data in.
1587  *		off	- start of range
1588  *		len	- end of range (0 => EOF)
1589  *		flag	- current file open mode flags.
1590  *		log	- TRUE if this action should be logged
1591  *
1592  *	RETURN:	0 on success, error code on failure
1593  */
1594 int
1595 zfs_freesp(znode_t *zp, uint64_t off, uint64_t len, int flag, boolean_t log)
1596 {
1597 	dmu_tx_t *tx;
1598 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
1599 	zilog_t *zilog = zfsvfs->z_log;
1600 	uint64_t mode;
1601 	uint64_t mtime[2], ctime[2];
1602 	sa_bulk_attr_t bulk[3];
1603 	int count = 0;
1604 	int error;
1605 
1606 	if ((error = sa_lookup(zp->z_sa_hdl, SA_ZPL_MODE(zfsvfs), &mode,
1607 	    sizeof (mode))) != 0)
1608 		return (error);
1609 
1610 	if (off > zp->z_size) {
1611 		error =  zfs_extend(zp, off+len);
1612 		if (error == 0 && log)
1613 			goto log;
1614 		else
1615 			return (error);
1616 	}
1617 
1618 	if (len == 0) {
1619 		error = zfs_trunc(zp, off);
1620 	} else {
1621 		if ((error = zfs_free_range(zp, off, len)) == 0 &&
1622 		    off + len > zp->z_size)
1623 			error = zfs_extend(zp, off+len);
1624 	}
1625 	if (error || !log)
1626 		return (error);
1627 log:
1628 	tx = dmu_tx_create(zfsvfs->z_os);
1629 	dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE);
1630 	zfs_sa_upgrade_txholds(tx, zp);
1631 	error = dmu_tx_assign(tx, TXG_WAIT);
1632 	if (error) {
1633 		dmu_tx_abort(tx);
1634 		return (error);
1635 	}
1636 
1637 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zfsvfs), NULL, mtime, 16);
1638 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs), NULL, ctime, 16);
1639 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_FLAGS(zfsvfs),
1640 	    NULL, &zp->z_pflags, 8);
1641 	zfs_tstamp_update_setup(zp, CONTENT_MODIFIED, mtime, ctime);
1642 	error = sa_bulk_update(zp->z_sa_hdl, bulk, count, tx);
1643 	ASSERT0(error);
1644 
1645 	zfs_log_truncate(zilog, tx, TX_TRUNCATE, zp, off, len);
1646 
1647 	dmu_tx_commit(tx);
1648 	return (0);
1649 }
1650 
1651 void
1652 zfs_create_fs(objset_t *os, cred_t *cr, nvlist_t *zplprops, dmu_tx_t *tx)
1653 {
1654 	uint64_t	moid, obj, sa_obj, version;
1655 	uint64_t	sense = ZFS_CASE_SENSITIVE;
1656 	uint64_t	norm = 0;
1657 	nvpair_t	*elem;
1658 	int		error;
1659 	int		i;
1660 	znode_t		*rootzp = NULL;
1661 	zfsvfs_t	*zfsvfs;
1662 	vattr_t		vattr;
1663 	znode_t		*zp;
1664 	zfs_acl_ids_t	acl_ids;
1665 
1666 	/*
1667 	 * First attempt to create master node.
1668 	 */
1669 	/*
1670 	 * In an empty objset, there are no blocks to read and thus
1671 	 * there can be no i/o errors (which we assert below).
1672 	 */
1673 	moid = MASTER_NODE_OBJ;
1674 	error = zap_create_claim(os, moid, DMU_OT_MASTER_NODE,
1675 	    DMU_OT_NONE, 0, tx);
1676 	ASSERT0(error);
1677 
1678 	/*
1679 	 * Set starting attributes.
1680 	 */
1681 	version = zfs_zpl_version_map(spa_version(dmu_objset_spa(os)));
1682 	elem = NULL;
1683 	while ((elem = nvlist_next_nvpair(zplprops, elem)) != NULL) {
1684 		/* For the moment we expect all zpl props to be uint64_ts */
1685 		uint64_t val;
1686 		char *name;
1687 
1688 		ASSERT3S(nvpair_type(elem), ==, DATA_TYPE_UINT64);
1689 		val = fnvpair_value_uint64(elem);
1690 		name = nvpair_name(elem);
1691 		if (strcmp(name, zfs_prop_to_name(ZFS_PROP_VERSION)) == 0) {
1692 			if (val < version)
1693 				version = val;
1694 		} else {
1695 			error = zap_update(os, moid, name, 8, 1, &val, tx);
1696 		}
1697 		ASSERT0(error);
1698 		if (strcmp(name, zfs_prop_to_name(ZFS_PROP_NORMALIZE)) == 0)
1699 			norm = val;
1700 		else if (strcmp(name, zfs_prop_to_name(ZFS_PROP_CASE)) == 0)
1701 			sense = val;
1702 	}
1703 	ASSERT3U(version, !=, 0);
1704 	error = zap_update(os, moid, ZPL_VERSION_STR, 8, 1, &version, tx);
1705 
1706 	/*
1707 	 * Create zap object used for SA attribute registration
1708 	 */
1709 
1710 	if (version >= ZPL_VERSION_SA) {
1711 		sa_obj = zap_create(os, DMU_OT_SA_MASTER_NODE,
1712 		    DMU_OT_NONE, 0, tx);
1713 		error = zap_add(os, moid, ZFS_SA_ATTRS, 8, 1, &sa_obj, tx);
1714 		ASSERT0(error);
1715 	} else {
1716 		sa_obj = 0;
1717 	}
1718 	/*
1719 	 * Create a delete queue.
1720 	 */
1721 	obj = zap_create(os, DMU_OT_UNLINKED_SET, DMU_OT_NONE, 0, tx);
1722 
1723 	error = zap_add(os, moid, ZFS_UNLINKED_SET, 8, 1, &obj, tx);
1724 	ASSERT0(error);
1725 
1726 	/*
1727 	 * Create root znode.  Create minimal znode/vnode/zfsvfs
1728 	 * to allow zfs_mknode to work.
1729 	 */
1730 	VATTR_NULL(&vattr);
1731 	vattr.va_mask = AT_MODE|AT_UID|AT_GID;
1732 	vattr.va_type = VDIR;
1733 	vattr.va_mode = S_IFDIR|0755;
1734 	vattr.va_uid = crgetuid(cr);
1735 	vattr.va_gid = crgetgid(cr);
1736 
1737 	zfsvfs = kmem_zalloc(sizeof (zfsvfs_t), KM_SLEEP);
1738 
1739 	rootzp = zfs_znode_alloc_kmem(KM_SLEEP);
1740 	ASSERT(!POINTER_IS_VALID(rootzp->z_zfsvfs));
1741 	rootzp->z_unlinked = 0;
1742 	rootzp->z_atime_dirty = 0;
1743 	rootzp->z_is_sa = USE_SA(version, os);
1744 
1745 	zfsvfs->z_os = os;
1746 	zfsvfs->z_parent = zfsvfs;
1747 	zfsvfs->z_version = version;
1748 	zfsvfs->z_use_fuids = USE_FUIDS(version, os);
1749 	zfsvfs->z_use_sa = USE_SA(version, os);
1750 	zfsvfs->z_norm = norm;
1751 
1752 	error = sa_setup(os, sa_obj, zfs_attr_table, ZPL_END,
1753 	    &zfsvfs->z_attr_table);
1754 
1755 	ASSERT0(error);
1756 
1757 	/*
1758 	 * Fold case on file systems that are always or sometimes case
1759 	 * insensitive.
1760 	 */
1761 	if (sense == ZFS_CASE_INSENSITIVE || sense == ZFS_CASE_MIXED)
1762 		zfsvfs->z_norm |= U8_TEXTPREP_TOUPPER;
1763 
1764 	mutex_init(&zfsvfs->z_znodes_lock, NULL, MUTEX_DEFAULT, NULL);
1765 	list_create(&zfsvfs->z_all_znodes, sizeof (znode_t),
1766 	    offsetof(znode_t, z_link_node));
1767 
1768 	for (i = 0; i != ZFS_OBJ_MTX_SZ; i++)
1769 		mutex_init(&zfsvfs->z_hold_mtx[i], NULL, MUTEX_DEFAULT, NULL);
1770 
1771 	rootzp->z_zfsvfs = zfsvfs;
1772 	VERIFY0(zfs_acl_ids_create(rootzp, IS_ROOT_NODE, &vattr,
1773 	    cr, NULL, &acl_ids));
1774 	zfs_mknode(rootzp, &vattr, tx, cr, IS_ROOT_NODE, &zp, &acl_ids);
1775 	ASSERT3P(zp, ==, rootzp);
1776 	error = zap_add(os, moid, ZFS_ROOT_OBJ, 8, 1, &rootzp->z_id, tx);
1777 	ASSERT0(error);
1778 	zfs_acl_ids_free(&acl_ids);
1779 	POINTER_INVALIDATE(&rootzp->z_zfsvfs);
1780 
1781 	sa_handle_destroy(rootzp->z_sa_hdl);
1782 	zfs_znode_free_kmem(rootzp);
1783 
1784 	/*
1785 	 * Create shares directory
1786 	 */
1787 
1788 	error = zfs_create_share_dir(zfsvfs, tx);
1789 
1790 	ASSERT0(error);
1791 
1792 	for (i = 0; i != ZFS_OBJ_MTX_SZ; i++)
1793 		mutex_destroy(&zfsvfs->z_hold_mtx[i]);
1794 	kmem_free(zfsvfs, sizeof (zfsvfs_t));
1795 }
1796 #endif /* _KERNEL */
1797 
1798 static int
1799 zfs_sa_setup(objset_t *osp, sa_attr_type_t **sa_table)
1800 {
1801 	uint64_t sa_obj = 0;
1802 	int error;
1803 
1804 	error = zap_lookup(osp, MASTER_NODE_OBJ, ZFS_SA_ATTRS, 8, 1, &sa_obj);
1805 	if (error != 0 && error != ENOENT)
1806 		return (error);
1807 
1808 	error = sa_setup(osp, sa_obj, zfs_attr_table, ZPL_END, sa_table);
1809 	return (error);
1810 }
1811 
1812 static int
1813 zfs_grab_sa_handle(objset_t *osp, uint64_t obj, sa_handle_t **hdlp,
1814     dmu_buf_t **db, void *tag)
1815 {
1816 	dmu_object_info_t doi;
1817 	int error;
1818 
1819 	if ((error = sa_buf_hold(osp, obj, tag, db)) != 0)
1820 		return (error);
1821 
1822 	dmu_object_info_from_db(*db, &doi);
1823 	if ((doi.doi_bonus_type != DMU_OT_SA &&
1824 	    doi.doi_bonus_type != DMU_OT_ZNODE) ||
1825 	    (doi.doi_bonus_type == DMU_OT_ZNODE &&
1826 	    doi.doi_bonus_size < sizeof (znode_phys_t))) {
1827 		sa_buf_rele(*db, tag);
1828 		return (SET_ERROR(ENOTSUP));
1829 	}
1830 
1831 	error = sa_handle_get(osp, obj, NULL, SA_HDL_PRIVATE, hdlp);
1832 	if (error != 0) {
1833 		sa_buf_rele(*db, tag);
1834 		return (error);
1835 	}
1836 
1837 	return (0);
1838 }
1839 
1840 static void
1841 zfs_release_sa_handle(sa_handle_t *hdl, dmu_buf_t *db, void *tag)
1842 {
1843 	sa_handle_destroy(hdl);
1844 	sa_buf_rele(db, tag);
1845 }
1846 
1847 /*
1848  * Given an object number, return its parent object number and whether
1849  * or not the object is an extended attribute directory.
1850  */
1851 static int
1852 zfs_obj_to_pobj(objset_t *osp, sa_handle_t *hdl, sa_attr_type_t *sa_table,
1853     uint64_t *pobjp, int *is_xattrdir)
1854 {
1855 	uint64_t parent;
1856 	uint64_t pflags;
1857 	uint64_t mode;
1858 	uint64_t parent_mode;
1859 	sa_bulk_attr_t bulk[3];
1860 	sa_handle_t *sa_hdl;
1861 	dmu_buf_t *sa_db;
1862 	int count = 0;
1863 	int error;
1864 
1865 	SA_ADD_BULK_ATTR(bulk, count, sa_table[ZPL_PARENT], NULL,
1866 	    &parent, sizeof (parent));
1867 	SA_ADD_BULK_ATTR(bulk, count, sa_table[ZPL_FLAGS], NULL,
1868 	    &pflags, sizeof (pflags));
1869 	SA_ADD_BULK_ATTR(bulk, count, sa_table[ZPL_MODE], NULL,
1870 	    &mode, sizeof (mode));
1871 
1872 	if ((error = sa_bulk_lookup(hdl, bulk, count)) != 0)
1873 		return (error);
1874 
1875 	/*
1876 	 * When a link is removed its parent pointer is not changed and will
1877 	 * be invalid.  There are two cases where a link is removed but the
1878 	 * file stays around, when it goes to the delete queue and when there
1879 	 * are additional links.
1880 	 */
1881 	error = zfs_grab_sa_handle(osp, parent, &sa_hdl, &sa_db, FTAG);
1882 	if (error != 0)
1883 		return (error);
1884 
1885 	error = sa_lookup(sa_hdl, ZPL_MODE, &parent_mode, sizeof (parent_mode));
1886 	zfs_release_sa_handle(sa_hdl, sa_db, FTAG);
1887 	if (error != 0)
1888 		return (error);
1889 
1890 	*is_xattrdir = ((pflags & ZFS_XATTR) != 0) && S_ISDIR(mode);
1891 
1892 	/*
1893 	 * Extended attributes can be applied to files, directories, etc.
1894 	 * Otherwise the parent must be a directory.
1895 	 */
1896 	if (!*is_xattrdir && !S_ISDIR(parent_mode))
1897 		return (SET_ERROR(EINVAL));
1898 
1899 	*pobjp = parent;
1900 
1901 	return (0);
1902 }
1903 
1904 /*
1905  * Given an object number, return some zpl level statistics
1906  */
1907 static int
1908 zfs_obj_to_stats_impl(sa_handle_t *hdl, sa_attr_type_t *sa_table,
1909     zfs_stat_t *sb)
1910 {
1911 	sa_bulk_attr_t bulk[4];
1912 	int count = 0;
1913 
1914 	SA_ADD_BULK_ATTR(bulk, count, sa_table[ZPL_MODE], NULL,
1915 	    &sb->zs_mode, sizeof (sb->zs_mode));
1916 	SA_ADD_BULK_ATTR(bulk, count, sa_table[ZPL_GEN], NULL,
1917 	    &sb->zs_gen, sizeof (sb->zs_gen));
1918 	SA_ADD_BULK_ATTR(bulk, count, sa_table[ZPL_LINKS], NULL,
1919 	    &sb->zs_links, sizeof (sb->zs_links));
1920 	SA_ADD_BULK_ATTR(bulk, count, sa_table[ZPL_CTIME], NULL,
1921 	    &sb->zs_ctime, sizeof (sb->zs_ctime));
1922 
1923 	return (sa_bulk_lookup(hdl, bulk, count));
1924 }
1925 
1926 static int
1927 zfs_obj_to_path_impl(objset_t *osp, uint64_t obj, sa_handle_t *hdl,
1928     sa_attr_type_t *sa_table, char *buf, int len)
1929 {
1930 	sa_handle_t *sa_hdl;
1931 	sa_handle_t *prevhdl = NULL;
1932 	dmu_buf_t *prevdb = NULL;
1933 	dmu_buf_t *sa_db = NULL;
1934 	char *path = buf + len - 1;
1935 	int error;
1936 
1937 	*path = '\0';
1938 	sa_hdl = hdl;
1939 
1940 	uint64_t deleteq_obj;
1941 	VERIFY0(zap_lookup(osp, MASTER_NODE_OBJ,
1942 	    ZFS_UNLINKED_SET, sizeof (uint64_t), 1, &deleteq_obj));
1943 	error = zap_lookup_int(osp, deleteq_obj, obj);
1944 	if (error == 0) {
1945 		return (ESTALE);
1946 	} else if (error != ENOENT) {
1947 		return (error);
1948 	}
1949 	error = 0;
1950 
1951 	for (;;) {
1952 		uint64_t pobj;
1953 		char component[MAXNAMELEN + 2];
1954 		size_t complen;
1955 		int is_xattrdir;
1956 
1957 		if (prevdb) {
1958 			ASSERT3P(prevhdl, !=, NULL);
1959 			zfs_release_sa_handle(prevhdl, prevdb, FTAG);
1960 		}
1961 
1962 		if ((error = zfs_obj_to_pobj(osp, sa_hdl, sa_table, &pobj,
1963 		    &is_xattrdir)) != 0)
1964 			break;
1965 
1966 		if (pobj == obj) {
1967 			if (path[0] != '/')
1968 				*--path = '/';
1969 			break;
1970 		}
1971 
1972 		component[0] = '/';
1973 		if (is_xattrdir) {
1974 			(void) sprintf(component + 1, "<xattrdir>");
1975 		} else {
1976 			error = zap_value_search(osp, pobj, obj,
1977 			    ZFS_DIRENT_OBJ(-1ULL), component + 1);
1978 			if (error != 0)
1979 				break;
1980 		}
1981 
1982 		complen = strlen(component);
1983 		path -= complen;
1984 		ASSERT3P(path, >=, buf);
1985 		memcpy(path, component, complen);
1986 		obj = pobj;
1987 
1988 		if (sa_hdl != hdl) {
1989 			prevhdl = sa_hdl;
1990 			prevdb = sa_db;
1991 		}
1992 		error = zfs_grab_sa_handle(osp, obj, &sa_hdl, &sa_db, FTAG);
1993 		if (error != 0) {
1994 			sa_hdl = prevhdl;
1995 			sa_db = prevdb;
1996 			break;
1997 		}
1998 	}
1999 
2000 	if (sa_hdl != NULL && sa_hdl != hdl) {
2001 		ASSERT3P(sa_db, !=, NULL);
2002 		zfs_release_sa_handle(sa_hdl, sa_db, FTAG);
2003 	}
2004 
2005 	if (error == 0)
2006 		(void) memmove(buf, path, buf + len - path);
2007 
2008 	return (error);
2009 }
2010 
2011 int
2012 zfs_obj_to_path(objset_t *osp, uint64_t obj, char *buf, int len)
2013 {
2014 	sa_attr_type_t *sa_table;
2015 	sa_handle_t *hdl;
2016 	dmu_buf_t *db;
2017 	int error;
2018 
2019 	error = zfs_sa_setup(osp, &sa_table);
2020 	if (error != 0)
2021 		return (error);
2022 
2023 	error = zfs_grab_sa_handle(osp, obj, &hdl, &db, FTAG);
2024 	if (error != 0)
2025 		return (error);
2026 
2027 	error = zfs_obj_to_path_impl(osp, obj, hdl, sa_table, buf, len);
2028 
2029 	zfs_release_sa_handle(hdl, db, FTAG);
2030 	return (error);
2031 }
2032 
2033 int
2034 zfs_obj_to_stats(objset_t *osp, uint64_t obj, zfs_stat_t *sb,
2035     char *buf, int len)
2036 {
2037 	char *path = buf + len - 1;
2038 	sa_attr_type_t *sa_table;
2039 	sa_handle_t *hdl;
2040 	dmu_buf_t *db;
2041 	int error;
2042 
2043 	*path = '\0';
2044 
2045 	error = zfs_sa_setup(osp, &sa_table);
2046 	if (error != 0)
2047 		return (error);
2048 
2049 	error = zfs_grab_sa_handle(osp, obj, &hdl, &db, FTAG);
2050 	if (error != 0)
2051 		return (error);
2052 
2053 	error = zfs_obj_to_stats_impl(hdl, sa_table, sb);
2054 	if (error != 0) {
2055 		zfs_release_sa_handle(hdl, db, FTAG);
2056 		return (error);
2057 	}
2058 
2059 	error = zfs_obj_to_path_impl(osp, obj, hdl, sa_table, buf, len);
2060 
2061 	zfs_release_sa_handle(hdl, db, FTAG);
2062 	return (error);
2063 }
2064 
2065 
2066 void
2067 zfs_znode_update_vfs(znode_t *zp)
2068 {
2069 	vm_object_t object;
2070 
2071 	if ((object = ZTOV(zp)->v_object) == NULL ||
2072 	    zp->z_size == object->un_pager.vnp.vnp_size)
2073 		return;
2074 
2075 	vnode_pager_setsize(ZTOV(zp), zp->z_size);
2076 }
2077 
2078 
2079 #ifdef _KERNEL
2080 int
2081 zfs_znode_parent_and_name(znode_t *zp, znode_t **dzpp, char *buf)
2082 {
2083 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
2084 	uint64_t parent;
2085 	int is_xattrdir;
2086 	int err;
2087 
2088 	/* Extended attributes should not be visible as regular files. */
2089 	if ((zp->z_pflags & ZFS_XATTR) != 0)
2090 		return (SET_ERROR(EINVAL));
2091 
2092 	err = zfs_obj_to_pobj(zfsvfs->z_os, zp->z_sa_hdl, zfsvfs->z_attr_table,
2093 	    &parent, &is_xattrdir);
2094 	if (err != 0)
2095 		return (err);
2096 	ASSERT0(is_xattrdir);
2097 
2098 	/* No name as this is a root object. */
2099 	if (parent == zp->z_id)
2100 		return (SET_ERROR(EINVAL));
2101 
2102 	err = zap_value_search(zfsvfs->z_os, parent, zp->z_id,
2103 	    ZFS_DIRENT_OBJ(-1ULL), buf);
2104 	if (err != 0)
2105 		return (err);
2106 	err = zfs_zget(zfsvfs, parent, dzpp);
2107 	return (err);
2108 }
2109 #endif /* _KERNEL */
2110