xref: /titanic_51/usr/src/uts/common/fs/zfs/zfs_znode.c (revision 63251bc7f1ca38259078c48e316fee4ed66d4e93)
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 2009 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 /* Portions Copyright 2007 Jeremy Teo */
27 
28 #ifdef _KERNEL
29 #include <sys/types.h>
30 #include <sys/param.h>
31 #include <sys/time.h>
32 #include <sys/systm.h>
33 #include <sys/sysmacros.h>
34 #include <sys/resource.h>
35 #include <sys/mntent.h>
36 #include <sys/mkdev.h>
37 #include <sys/u8_textprep.h>
38 #include <sys/dsl_dataset.h>
39 #include <sys/vfs.h>
40 #include <sys/vfs_opreg.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/mode.h>
47 #include <sys/atomic.h>
48 #include <vm/pvn.h>
49 #include "fs/fs_subr.h"
50 #include <sys/zfs_dir.h>
51 #include <sys/zfs_acl.h>
52 #include <sys/zfs_ioctl.h>
53 #include <sys/zfs_rlock.h>
54 #include <sys/zfs_fuid.h>
55 #include <sys/fs/zfs.h>
56 #include <sys/kidmap.h>
57 #endif /* _KERNEL */
58 
59 #include <sys/dmu.h>
60 #include <sys/refcount.h>
61 #include <sys/stat.h>
62 #include <sys/zap.h>
63 #include <sys/zfs_znode.h>
64 
65 #include "zfs_prop.h"
66 
67 /*
68  * Define ZNODE_STATS to turn on statistic gathering. By default, it is only
69  * turned on when DEBUG is also defined.
70  */
71 #ifdef	DEBUG
72 #define	ZNODE_STATS
73 #endif	/* DEBUG */
74 
75 #ifdef	ZNODE_STATS
76 #define	ZNODE_STAT_ADD(stat)			((stat)++)
77 #else
78 #define	ZNODE_STAT_ADD(stat)			/* nothing */
79 #endif	/* ZNODE_STATS */
80 
81 #define	POINTER_IS_VALID(p)	(!((uintptr_t)(p) & 0x3))
82 #define	POINTER_INVALIDATE(pp)	(*(pp) = (void *)((uintptr_t)(*(pp)) | 0x1))
83 
84 /*
85  * Functions needed for userland (ie: libzpool) are not put under
86  * #ifdef_KERNEL; the rest of the functions have dependencies
87  * (such as VFS logic) that will not compile easily in userland.
88  */
89 #ifdef _KERNEL
90 static kmem_cache_t *znode_cache = NULL;
91 
92 /*ARGSUSED*/
93 static void
94 znode_evict_error(dmu_buf_t *dbuf, void *user_ptr)
95 {
96 	/*
97 	 * We should never drop all dbuf refs without first clearing
98 	 * the eviction callback.
99 	 */
100 	panic("evicting znode %p\n", user_ptr);
101 }
102 
103 /*ARGSUSED*/
104 static int
105 zfs_znode_cache_constructor(void *buf, void *arg, int kmflags)
106 {
107 	znode_t *zp = buf;
108 
109 	ASSERT(!POINTER_IS_VALID(zp->z_zfsvfs));
110 
111 	zp->z_vnode = vn_alloc(kmflags);
112 	if (zp->z_vnode == NULL) {
113 		return (-1);
114 	}
115 	ZTOV(zp)->v_data = zp;
116 
117 	list_link_init(&zp->z_link_node);
118 
119 	mutex_init(&zp->z_lock, NULL, MUTEX_DEFAULT, NULL);
120 	rw_init(&zp->z_parent_lock, NULL, RW_DEFAULT, NULL);
121 	rw_init(&zp->z_name_lock, NULL, RW_DEFAULT, NULL);
122 	mutex_init(&zp->z_acl_lock, NULL, MUTEX_DEFAULT, NULL);
123 
124 	mutex_init(&zp->z_range_lock, NULL, MUTEX_DEFAULT, NULL);
125 	avl_create(&zp->z_range_avl, zfs_range_compare,
126 	    sizeof (rl_t), offsetof(rl_t, r_node));
127 
128 	zp->z_dbuf = NULL;
129 	zp->z_dirlocks = NULL;
130 	return (0);
131 }
132 
133 /*ARGSUSED*/
134 static void
135 zfs_znode_cache_destructor(void *buf, void *arg)
136 {
137 	znode_t *zp = buf;
138 
139 	ASSERT(!POINTER_IS_VALID(zp->z_zfsvfs));
140 	ASSERT(ZTOV(zp)->v_data == zp);
141 	vn_free(ZTOV(zp));
142 	ASSERT(!list_link_active(&zp->z_link_node));
143 	mutex_destroy(&zp->z_lock);
144 	rw_destroy(&zp->z_parent_lock);
145 	rw_destroy(&zp->z_name_lock);
146 	mutex_destroy(&zp->z_acl_lock);
147 	avl_destroy(&zp->z_range_avl);
148 	mutex_destroy(&zp->z_range_lock);
149 
150 	ASSERT(zp->z_dbuf == NULL);
151 	ASSERT(zp->z_dirlocks == NULL);
152 }
153 
154 #ifdef	ZNODE_STATS
155 static struct {
156 	uint64_t zms_zfsvfs_invalid;
157 	uint64_t zms_zfsvfs_unmounted;
158 	uint64_t zms_zfsvfs_recheck_invalid;
159 	uint64_t zms_obj_held;
160 	uint64_t zms_vnode_locked;
161 	uint64_t zms_not_only_dnlc;
162 } znode_move_stats;
163 #endif	/* ZNODE_STATS */
164 
165 static void
166 zfs_znode_move_impl(znode_t *ozp, znode_t *nzp)
167 {
168 	vnode_t *vp;
169 
170 	/* Copy fields. */
171 	nzp->z_zfsvfs = ozp->z_zfsvfs;
172 
173 	/* Swap vnodes. */
174 	vp = nzp->z_vnode;
175 	nzp->z_vnode = ozp->z_vnode;
176 	ozp->z_vnode = vp; /* let destructor free the overwritten vnode */
177 	ZTOV(ozp)->v_data = ozp;
178 	ZTOV(nzp)->v_data = nzp;
179 
180 	nzp->z_id = ozp->z_id;
181 	ASSERT(ozp->z_dirlocks == NULL); /* znode not in use */
182 	ASSERT(avl_numnodes(&ozp->z_range_avl) == 0);
183 	nzp->z_unlinked = ozp->z_unlinked;
184 	nzp->z_atime_dirty = ozp->z_atime_dirty;
185 	nzp->z_zn_prefetch = ozp->z_zn_prefetch;
186 	nzp->z_blksz = ozp->z_blksz;
187 	nzp->z_seq = ozp->z_seq;
188 	nzp->z_mapcnt = ozp->z_mapcnt;
189 	nzp->z_last_itx = ozp->z_last_itx;
190 	nzp->z_gen = ozp->z_gen;
191 	nzp->z_sync_cnt = ozp->z_sync_cnt;
192 	nzp->z_phys = ozp->z_phys;
193 	nzp->z_dbuf = ozp->z_dbuf;
194 
195 	/* Update back pointers. */
196 	(void) dmu_buf_update_user(nzp->z_dbuf, ozp, nzp, &nzp->z_phys,
197 	    znode_evict_error);
198 
199 	/*
200 	 * Invalidate the original znode by clearing fields that provide a
201 	 * pointer back to the znode. Set the low bit of the vfs pointer to
202 	 * ensure that zfs_znode_move() recognizes the znode as invalid in any
203 	 * subsequent callback.
204 	 */
205 	ozp->z_dbuf = NULL;
206 	POINTER_INVALIDATE(&ozp->z_zfsvfs);
207 }
208 
209 /*
210  * Wrapper function for ZFS_ENTER that returns 0 if successful and otherwise
211  * returns a non-zero error code.
212  */
213 static int
214 zfs_enter(zfsvfs_t *zfsvfs)
215 {
216 	ZFS_ENTER(zfsvfs);
217 	return (0);
218 }
219 
220 /*ARGSUSED*/
221 static kmem_cbrc_t
222 zfs_znode_move(void *buf, void *newbuf, size_t size, void *arg)
223 {
224 	znode_t *ozp = buf, *nzp = newbuf;
225 	zfsvfs_t *zfsvfs;
226 	vnode_t *vp;
227 
228 	/*
229 	 * The znode is on the file system's list of known znodes if the vfs
230 	 * pointer is valid. We set the low bit of the vfs pointer when freeing
231 	 * the znode to invalidate it, and the memory patterns written by kmem
232 	 * (baddcafe and deadbeef) set at least one of the two low bits. A newly
233 	 * created znode sets the vfs pointer last of all to indicate that the
234 	 * znode is known and in a valid state to be moved by this function.
235 	 */
236 	zfsvfs = ozp->z_zfsvfs;
237 	if (!POINTER_IS_VALID(zfsvfs)) {
238 		ZNODE_STAT_ADD(znode_move_stats.zms_zfsvfs_invalid);
239 		return (KMEM_CBRC_DONT_KNOW);
240 	}
241 
242 	/*
243 	 * Ensure that the filesystem is not unmounted during the move.
244 	 */
245 	if (zfs_enter(zfsvfs) != 0) {		/* ZFS_ENTER */
246 		ZNODE_STAT_ADD(znode_move_stats.zms_zfsvfs_unmounted);
247 		return (KMEM_CBRC_DONT_KNOW);
248 	}
249 
250 	mutex_enter(&zfsvfs->z_znodes_lock);
251 	/*
252 	 * Recheck the vfs pointer in case the znode was removed just before
253 	 * acquiring the lock.
254 	 */
255 	if (zfsvfs != ozp->z_zfsvfs) {
256 		mutex_exit(&zfsvfs->z_znodes_lock);
257 		ZFS_EXIT(zfsvfs);
258 		ZNODE_STAT_ADD(znode_move_stats.zms_zfsvfs_recheck_invalid);
259 		return (KMEM_CBRC_DONT_KNOW);
260 	}
261 
262 	/*
263 	 * At this point we know that as long as we hold z_znodes_lock, the
264 	 * znode cannot be freed and fields within the znode can be safely
265 	 * accessed. Now, prevent a race with zfs_zget().
266 	 */
267 	if (ZFS_OBJ_HOLD_TRYENTER(zfsvfs, ozp->z_id) == 0) {
268 		mutex_exit(&zfsvfs->z_znodes_lock);
269 		ZFS_EXIT(zfsvfs);
270 		ZNODE_STAT_ADD(znode_move_stats.zms_obj_held);
271 		return (KMEM_CBRC_LATER);
272 	}
273 
274 	vp = ZTOV(ozp);
275 	if (mutex_tryenter(&vp->v_lock) == 0) {
276 		ZFS_OBJ_HOLD_EXIT(zfsvfs, ozp->z_id);
277 		mutex_exit(&zfsvfs->z_znodes_lock);
278 		ZFS_EXIT(zfsvfs);
279 		ZNODE_STAT_ADD(znode_move_stats.zms_vnode_locked);
280 		return (KMEM_CBRC_LATER);
281 	}
282 
283 	/* Only move znodes that are referenced _only_ by the DNLC. */
284 	if (vp->v_count != 1 || !vn_in_dnlc(vp)) {
285 		mutex_exit(&vp->v_lock);
286 		ZFS_OBJ_HOLD_EXIT(zfsvfs, ozp->z_id);
287 		mutex_exit(&zfsvfs->z_znodes_lock);
288 		ZFS_EXIT(zfsvfs);
289 		ZNODE_STAT_ADD(znode_move_stats.zms_not_only_dnlc);
290 		return (KMEM_CBRC_LATER);
291 	}
292 
293 	/*
294 	 * The znode is known and in a valid state to move. We're holding the
295 	 * locks needed to execute the critical section.
296 	 */
297 	zfs_znode_move_impl(ozp, nzp);
298 	mutex_exit(&vp->v_lock);
299 	ZFS_OBJ_HOLD_EXIT(zfsvfs, ozp->z_id);
300 
301 	list_link_replace(&ozp->z_link_node, &nzp->z_link_node);
302 	mutex_exit(&zfsvfs->z_znodes_lock);
303 	ZFS_EXIT(zfsvfs);
304 
305 	return (KMEM_CBRC_YES);
306 }
307 
308 void
309 zfs_znode_init(void)
310 {
311 	/*
312 	 * Initialize zcache
313 	 */
314 	ASSERT(znode_cache == NULL);
315 	znode_cache = kmem_cache_create("zfs_znode_cache",
316 	    sizeof (znode_t), 0, zfs_znode_cache_constructor,
317 	    zfs_znode_cache_destructor, NULL, NULL, NULL, 0);
318 	kmem_cache_set_move(znode_cache, zfs_znode_move);
319 }
320 
321 void
322 zfs_znode_fini(void)
323 {
324 	/*
325 	 * Cleanup vfs & vnode ops
326 	 */
327 	zfs_remove_op_tables();
328 
329 	/*
330 	 * Cleanup zcache
331 	 */
332 	if (znode_cache)
333 		kmem_cache_destroy(znode_cache);
334 	znode_cache = NULL;
335 }
336 
337 struct vnodeops *zfs_dvnodeops;
338 struct vnodeops *zfs_fvnodeops;
339 struct vnodeops *zfs_symvnodeops;
340 struct vnodeops *zfs_xdvnodeops;
341 struct vnodeops *zfs_evnodeops;
342 struct vnodeops *zfs_sharevnodeops;
343 
344 void
345 zfs_remove_op_tables()
346 {
347 	/*
348 	 * Remove vfs ops
349 	 */
350 	ASSERT(zfsfstype);
351 	(void) vfs_freevfsops_by_type(zfsfstype);
352 	zfsfstype = 0;
353 
354 	/*
355 	 * Remove vnode ops
356 	 */
357 	if (zfs_dvnodeops)
358 		vn_freevnodeops(zfs_dvnodeops);
359 	if (zfs_fvnodeops)
360 		vn_freevnodeops(zfs_fvnodeops);
361 	if (zfs_symvnodeops)
362 		vn_freevnodeops(zfs_symvnodeops);
363 	if (zfs_xdvnodeops)
364 		vn_freevnodeops(zfs_xdvnodeops);
365 	if (zfs_evnodeops)
366 		vn_freevnodeops(zfs_evnodeops);
367 	if (zfs_sharevnodeops)
368 		vn_freevnodeops(zfs_sharevnodeops);
369 
370 	zfs_dvnodeops = NULL;
371 	zfs_fvnodeops = NULL;
372 	zfs_symvnodeops = NULL;
373 	zfs_xdvnodeops = NULL;
374 	zfs_evnodeops = NULL;
375 	zfs_sharevnodeops = NULL;
376 }
377 
378 extern const fs_operation_def_t zfs_dvnodeops_template[];
379 extern const fs_operation_def_t zfs_fvnodeops_template[];
380 extern const fs_operation_def_t zfs_xdvnodeops_template[];
381 extern const fs_operation_def_t zfs_symvnodeops_template[];
382 extern const fs_operation_def_t zfs_evnodeops_template[];
383 extern const fs_operation_def_t zfs_sharevnodeops_template[];
384 
385 int
386 zfs_create_op_tables()
387 {
388 	int error;
389 
390 	/*
391 	 * zfs_dvnodeops can be set if mod_remove() calls mod_installfs()
392 	 * due to a failure to remove the the 2nd modlinkage (zfs_modldrv).
393 	 * In this case we just return as the ops vectors are already set up.
394 	 */
395 	if (zfs_dvnodeops)
396 		return (0);
397 
398 	error = vn_make_ops(MNTTYPE_ZFS, zfs_dvnodeops_template,
399 	    &zfs_dvnodeops);
400 	if (error)
401 		return (error);
402 
403 	error = vn_make_ops(MNTTYPE_ZFS, zfs_fvnodeops_template,
404 	    &zfs_fvnodeops);
405 	if (error)
406 		return (error);
407 
408 	error = vn_make_ops(MNTTYPE_ZFS, zfs_symvnodeops_template,
409 	    &zfs_symvnodeops);
410 	if (error)
411 		return (error);
412 
413 	error = vn_make_ops(MNTTYPE_ZFS, zfs_xdvnodeops_template,
414 	    &zfs_xdvnodeops);
415 	if (error)
416 		return (error);
417 
418 	error = vn_make_ops(MNTTYPE_ZFS, zfs_evnodeops_template,
419 	    &zfs_evnodeops);
420 	if (error)
421 		return (error);
422 
423 	error = vn_make_ops(MNTTYPE_ZFS, zfs_sharevnodeops_template,
424 	    &zfs_sharevnodeops);
425 
426 	return (error);
427 }
428 
429 static int
430 zfs_create_share_dir(zfsvfs_t *zfsvfs, dmu_tx_t *tx)
431 {
432 	vattr_t vattr;
433 	znode_t *sharezp;
434 	vnode_t *vp;
435 	znode_t *zp;
436 	int error;
437 
438 	vattr.va_mask = AT_MODE|AT_UID|AT_GID|AT_TYPE;
439 	vattr.va_type = VDIR;
440 	vattr.va_mode = S_IFDIR|0555;
441 	vattr.va_uid = crgetuid(kcred);
442 	vattr.va_gid = crgetgid(kcred);
443 
444 	sharezp = kmem_cache_alloc(znode_cache, KM_SLEEP);
445 	sharezp->z_unlinked = 0;
446 	sharezp->z_atime_dirty = 0;
447 	sharezp->z_zfsvfs = zfsvfs;
448 
449 	vp = ZTOV(sharezp);
450 	vn_reinit(vp);
451 	vp->v_type = VDIR;
452 
453 	zfs_mknode(sharezp, &vattr, tx, kcred, IS_ROOT_NODE,
454 	    &zp, 0, NULL, NULL);
455 	ASSERT3P(zp, ==, sharezp);
456 	ASSERT(!vn_in_dnlc(ZTOV(sharezp))); /* not valid to move */
457 	POINTER_INVALIDATE(&sharezp->z_zfsvfs);
458 	error = zap_add(zfsvfs->z_os, MASTER_NODE_OBJ,
459 	    ZFS_SHARES_DIR, 8, 1, &sharezp->z_id, tx);
460 	zfsvfs->z_shares_dir = sharezp->z_id;
461 
462 	ZTOV(sharezp)->v_count = 0;
463 	dmu_buf_rele(sharezp->z_dbuf, NULL);
464 	sharezp->z_dbuf = NULL;
465 	kmem_cache_free(znode_cache, sharezp);
466 
467 	return (error);
468 }
469 
470 /*
471  * zfs_init_fs - Initialize the zfsvfs struct and the file system
472  *	incore "master" object.  Verify version compatibility.
473  */
474 int
475 zfs_init_fs(zfsvfs_t *zfsvfs, znode_t **zpp)
476 {
477 	extern int zfsfstype;
478 
479 	objset_t	*os = zfsvfs->z_os;
480 	int		i, error;
481 	uint64_t fsid_guid;
482 	uint64_t zval;
483 
484 	*zpp = NULL;
485 
486 	error = zfs_get_zplprop(os, ZFS_PROP_VERSION, &zfsvfs->z_version);
487 	if (error) {
488 		return (error);
489 	} else if (zfsvfs->z_version > ZPL_VERSION) {
490 		(void) printf("Mismatched versions:  File system "
491 		    "is version %llu on-disk format, which is "
492 		    "incompatible with this software version %lld!",
493 		    (u_longlong_t)zfsvfs->z_version, ZPL_VERSION);
494 		return (ENOTSUP);
495 	}
496 
497 	if ((error = zfs_get_zplprop(os, ZFS_PROP_NORMALIZE, &zval)) != 0)
498 		return (error);
499 	zfsvfs->z_norm = (int)zval;
500 	if ((error = zfs_get_zplprop(os, ZFS_PROP_UTF8ONLY, &zval)) != 0)
501 		return (error);
502 	zfsvfs->z_utf8 = (zval != 0);
503 	if ((error = zfs_get_zplprop(os, ZFS_PROP_CASE, &zval)) != 0)
504 		return (error);
505 	zfsvfs->z_case = (uint_t)zval;
506 	/*
507 	 * Fold case on file systems that are always or sometimes case
508 	 * insensitive.
509 	 */
510 	if (zfsvfs->z_case == ZFS_CASE_INSENSITIVE ||
511 	    zfsvfs->z_case == ZFS_CASE_MIXED)
512 		zfsvfs->z_norm |= U8_TEXTPREP_TOUPPER;
513 
514 	/*
515 	 * The fsid is 64 bits, composed of an 8-bit fs type, which
516 	 * separates our fsid from any other filesystem types, and a
517 	 * 56-bit objset unique ID.  The objset unique ID is unique to
518 	 * all objsets open on this system, provided by unique_create().
519 	 * The 8-bit fs type must be put in the low bits of fsid[1]
520 	 * because that's where other Solaris filesystems put it.
521 	 */
522 	fsid_guid = dmu_objset_fsid_guid(os);
523 	ASSERT((fsid_guid & ~((1ULL<<56)-1)) == 0);
524 	zfsvfs->z_vfs->vfs_fsid.val[0] = fsid_guid;
525 	zfsvfs->z_vfs->vfs_fsid.val[1] = ((fsid_guid>>32) << 8) |
526 	    zfsfstype & 0xFF;
527 
528 	error = zap_lookup(os, MASTER_NODE_OBJ, ZFS_ROOT_OBJ, 8, 1,
529 	    &zfsvfs->z_root);
530 	if (error)
531 		return (error);
532 	ASSERT(zfsvfs->z_root != 0);
533 
534 	error = zap_lookup(os, MASTER_NODE_OBJ, ZFS_UNLINKED_SET, 8, 1,
535 	    &zfsvfs->z_unlinkedobj);
536 	if (error)
537 		return (error);
538 
539 	/*
540 	 * Initialize zget mutex's
541 	 */
542 	for (i = 0; i != ZFS_OBJ_MTX_SZ; i++)
543 		mutex_init(&zfsvfs->z_hold_mtx[i], NULL, MUTEX_DEFAULT, NULL);
544 
545 	error = zfs_zget(zfsvfs, zfsvfs->z_root, zpp);
546 	if (error) {
547 		/*
548 		 * On error, we destroy the mutexes here since it's not
549 		 * possible for the caller to determine if the mutexes were
550 		 * initialized properly.
551 		 */
552 		for (i = 0; i != ZFS_OBJ_MTX_SZ; i++)
553 			mutex_destroy(&zfsvfs->z_hold_mtx[i]);
554 		return (error);
555 	}
556 	ASSERT3U((*zpp)->z_id, ==, zfsvfs->z_root);
557 	error = zap_lookup(os, MASTER_NODE_OBJ, ZFS_FUID_TABLES, 8, 1,
558 	    &zfsvfs->z_fuid_obj);
559 	if (error == ENOENT)
560 		error = 0;
561 
562 	error = zap_lookup(os, MASTER_NODE_OBJ, ZFS_SHARES_DIR, 8, 1,
563 	    &zfsvfs->z_shares_dir);
564 	if (error == ENOENT) {
565 		dmu_tx_t *tx;
566 
567 		if (!dmu_objset_is_snapshot(zfsvfs->z_os)) {
568 			tx = dmu_tx_create(zfsvfs->z_os);
569 			dmu_tx_hold_zap(tx, MASTER_NODE_OBJ, TRUE,
570 			    ZFS_SHARES_DIR);
571 			dmu_tx_hold_zap(tx, DMU_NEW_OBJECT, FALSE, NULL);
572 			error = dmu_tx_assign(tx, TXG_WAIT);
573 			if (error) {
574 				dmu_tx_abort(tx);
575 			} else {
576 				error = zfs_create_share_dir(zfsvfs, tx);
577 				dmu_tx_commit(tx);
578 			}
579 		} else { /* Don't create directory on older snapshots */
580 			error = 0;
581 		}
582 	}
583 	return (error);
584 }
585 
586 /*
587  * define a couple of values we need available
588  * for both 64 and 32 bit environments.
589  */
590 #ifndef NBITSMINOR64
591 #define	NBITSMINOR64	32
592 #endif
593 #ifndef MAXMAJ64
594 #define	MAXMAJ64	0xffffffffUL
595 #endif
596 #ifndef	MAXMIN64
597 #define	MAXMIN64	0xffffffffUL
598 #endif
599 
600 /*
601  * Create special expldev for ZFS private use.
602  * Can't use standard expldev since it doesn't do
603  * what we want.  The standard expldev() takes a
604  * dev32_t in LP64 and expands it to a long dev_t.
605  * We need an interface that takes a dev32_t in ILP32
606  * and expands it to a long dev_t.
607  */
608 static uint64_t
609 zfs_expldev(dev_t dev)
610 {
611 #ifndef _LP64
612 	major_t major = (major_t)dev >> NBITSMINOR32 & MAXMAJ32;
613 	return (((uint64_t)major << NBITSMINOR64) |
614 	    ((minor_t)dev & MAXMIN32));
615 #else
616 	return (dev);
617 #endif
618 }
619 
620 /*
621  * Special cmpldev for ZFS private use.
622  * Can't use standard cmpldev since it takes
623  * a long dev_t and compresses it to dev32_t in
624  * LP64.  We need to do a compaction of a long dev_t
625  * to a dev32_t in ILP32.
626  */
627 dev_t
628 zfs_cmpldev(uint64_t dev)
629 {
630 #ifndef _LP64
631 	minor_t minor = (minor_t)dev & MAXMIN64;
632 	major_t major = (major_t)(dev >> NBITSMINOR64) & MAXMAJ64;
633 
634 	if (major > MAXMAJ32 || minor > MAXMIN32)
635 		return (NODEV32);
636 
637 	return (((dev32_t)major << NBITSMINOR32) | minor);
638 #else
639 	return (dev);
640 #endif
641 }
642 
643 static void
644 zfs_znode_dmu_init(zfsvfs_t *zfsvfs, znode_t *zp, dmu_buf_t *db)
645 {
646 	znode_t		*nzp;
647 
648 	ASSERT(!POINTER_IS_VALID(zp->z_zfsvfs) || (zfsvfs == zp->z_zfsvfs));
649 	ASSERT(MUTEX_HELD(ZFS_OBJ_MUTEX(zfsvfs, zp->z_id)));
650 
651 	mutex_enter(&zp->z_lock);
652 
653 	ASSERT(zp->z_dbuf == NULL);
654 	zp->z_dbuf = db;
655 	nzp = dmu_buf_set_user_ie(db, zp, &zp->z_phys, znode_evict_error);
656 
657 	/*
658 	 * there should be no
659 	 * concurrent zgets on this object.
660 	 */
661 	if (nzp != NULL)
662 		panic("existing znode %p for dbuf %p", (void *)nzp, (void *)db);
663 
664 	/*
665 	 * Slap on VROOT if we are the root znode
666 	 */
667 	if (zp->z_id == zfsvfs->z_root)
668 		ZTOV(zp)->v_flag |= VROOT;
669 
670 	mutex_exit(&zp->z_lock);
671 	vn_exists(ZTOV(zp));
672 }
673 
674 void
675 zfs_znode_dmu_fini(znode_t *zp)
676 {
677 	dmu_buf_t *db = zp->z_dbuf;
678 	ASSERT(MUTEX_HELD(ZFS_OBJ_MUTEX(zp->z_zfsvfs, zp->z_id)) ||
679 	    zp->z_unlinked ||
680 	    RW_WRITE_HELD(&zp->z_zfsvfs->z_teardown_inactive_lock));
681 	ASSERT(zp->z_dbuf != NULL);
682 	zp->z_dbuf = NULL;
683 	VERIFY(zp == dmu_buf_update_user(db, zp, NULL, NULL, NULL));
684 	dmu_buf_rele(db, NULL);
685 }
686 
687 /*
688  * Construct a new znode/vnode and intialize.
689  *
690  * This does not do a call to dmu_set_user() that is
691  * up to the caller to do, in case you don't want to
692  * return the znode
693  */
694 static znode_t *
695 zfs_znode_alloc(zfsvfs_t *zfsvfs, dmu_buf_t *db, int blksz)
696 {
697 	znode_t	*zp;
698 	vnode_t *vp;
699 
700 	zp = kmem_cache_alloc(znode_cache, KM_SLEEP);
701 
702 	ASSERT(zp->z_dirlocks == NULL);
703 	ASSERT(zp->z_dbuf == NULL);
704 	ASSERT(!POINTER_IS_VALID(zp->z_zfsvfs));
705 
706 	/*
707 	 * Defer setting z_zfsvfs until the znode is ready to be a candidate for
708 	 * the zfs_znode_move() callback.
709 	 */
710 	zp->z_phys = NULL;
711 	zp->z_unlinked = 0;
712 	zp->z_atime_dirty = 0;
713 	zp->z_mapcnt = 0;
714 	zp->z_last_itx = 0;
715 	zp->z_id = db->db_object;
716 	zp->z_blksz = blksz;
717 	zp->z_seq = 0x7A4653;
718 	zp->z_sync_cnt = 0;
719 
720 	vp = ZTOV(zp);
721 	vn_reinit(vp);
722 
723 	zfs_znode_dmu_init(zfsvfs, zp, db);
724 
725 	zp->z_gen = zp->z_phys->zp_gen;
726 
727 	vp->v_vfsp = zfsvfs->z_parent->z_vfs;
728 	vp->v_type = IFTOVT((mode_t)zp->z_phys->zp_mode);
729 
730 	switch (vp->v_type) {
731 	case VDIR:
732 		if (zp->z_phys->zp_flags & ZFS_XATTR) {
733 			vn_setops(vp, zfs_xdvnodeops);
734 			vp->v_flag |= V_XATTRDIR;
735 		} else {
736 			vn_setops(vp, zfs_dvnodeops);
737 		}
738 		zp->z_zn_prefetch = B_TRUE; /* z_prefetch default is enabled */
739 		break;
740 	case VBLK:
741 	case VCHR:
742 		vp->v_rdev = zfs_cmpldev(zp->z_phys->zp_rdev);
743 		/*FALLTHROUGH*/
744 	case VFIFO:
745 	case VSOCK:
746 	case VDOOR:
747 		vn_setops(vp, zfs_fvnodeops);
748 		break;
749 	case VREG:
750 		vp->v_flag |= VMODSORT;
751 		if (zp->z_phys->zp_parent == zfsvfs->z_shares_dir)
752 			vn_setops(vp, zfs_sharevnodeops);
753 		else
754 			vn_setops(vp, zfs_fvnodeops);
755 		break;
756 	case VLNK:
757 		vn_setops(vp, zfs_symvnodeops);
758 		break;
759 	default:
760 		vn_setops(vp, zfs_evnodeops);
761 		break;
762 	}
763 
764 	mutex_enter(&zfsvfs->z_znodes_lock);
765 	list_insert_tail(&zfsvfs->z_all_znodes, zp);
766 	membar_producer();
767 	/*
768 	 * Everything else must be valid before assigning z_zfsvfs makes the
769 	 * znode eligible for zfs_znode_move().
770 	 */
771 	zp->z_zfsvfs = zfsvfs;
772 	mutex_exit(&zfsvfs->z_znodes_lock);
773 
774 	VFS_HOLD(zfsvfs->z_vfs);
775 	return (zp);
776 }
777 
778 /*
779  * Create a new DMU object to hold a zfs znode.
780  *
781  *	IN:	dzp	- parent directory for new znode
782  *		vap	- file attributes for new znode
783  *		tx	- dmu transaction id for zap operations
784  *		cr	- credentials of caller
785  *		flag	- flags:
786  *			  IS_ROOT_NODE	- new object will be root
787  *			  IS_XATTR	- new object is an attribute
788  *			  IS_REPLAY	- intent log replay
789  *		bonuslen - length of bonus buffer
790  *		setaclp  - File/Dir initial ACL
791  *		fuidp	 - Tracks fuid allocation.
792  *
793  *	OUT:	zpp	- allocated znode
794  *
795  */
796 void
797 zfs_mknode(znode_t *dzp, vattr_t *vap, dmu_tx_t *tx, cred_t *cr,
798     uint_t flag, znode_t **zpp, int bonuslen, zfs_acl_t *setaclp,
799     zfs_fuid_info_t **fuidp)
800 {
801 	dmu_buf_t	*db;
802 	znode_phys_t	*pzp;
803 	zfsvfs_t	*zfsvfs = dzp->z_zfsvfs;
804 	timestruc_t	now;
805 	uint64_t	gen, obj;
806 	int		err;
807 
808 	ASSERT(vap && (vap->va_mask & (AT_TYPE|AT_MODE)) == (AT_TYPE|AT_MODE));
809 
810 	if (zfsvfs->z_replay) {
811 		obj = vap->va_nodeid;
812 		flag |= IS_REPLAY;
813 		now = vap->va_ctime;		/* see zfs_replay_create() */
814 		gen = vap->va_nblocks;		/* ditto */
815 	} else {
816 		obj = 0;
817 		gethrestime(&now);
818 		gen = dmu_tx_get_txg(tx);
819 	}
820 
821 	/*
822 	 * Create a new DMU object.
823 	 */
824 	/*
825 	 * There's currently no mechanism for pre-reading the blocks that will
826 	 * be to needed allocate a new object, so we accept the small chance
827 	 * that there will be an i/o error and we will fail one of the
828 	 * assertions below.
829 	 */
830 	if (vap->va_type == VDIR) {
831 		if (flag & IS_REPLAY) {
832 			err = zap_create_claim_norm(zfsvfs->z_os, obj,
833 			    zfsvfs->z_norm, DMU_OT_DIRECTORY_CONTENTS,
834 			    DMU_OT_ZNODE, sizeof (znode_phys_t) + bonuslen, tx);
835 			ASSERT3U(err, ==, 0);
836 		} else {
837 			obj = zap_create_norm(zfsvfs->z_os,
838 			    zfsvfs->z_norm, DMU_OT_DIRECTORY_CONTENTS,
839 			    DMU_OT_ZNODE, sizeof (znode_phys_t) + bonuslen, tx);
840 		}
841 	} else {
842 		if (flag & IS_REPLAY) {
843 			err = dmu_object_claim(zfsvfs->z_os, obj,
844 			    DMU_OT_PLAIN_FILE_CONTENTS, 0,
845 			    DMU_OT_ZNODE, sizeof (znode_phys_t) + bonuslen, tx);
846 			ASSERT3U(err, ==, 0);
847 		} else {
848 			obj = dmu_object_alloc(zfsvfs->z_os,
849 			    DMU_OT_PLAIN_FILE_CONTENTS, 0,
850 			    DMU_OT_ZNODE, sizeof (znode_phys_t) + bonuslen, tx);
851 		}
852 	}
853 	VERIFY(0 == dmu_bonus_hold(zfsvfs->z_os, obj, NULL, &db));
854 	dmu_buf_will_dirty(db, tx);
855 
856 	/*
857 	 * Initialize the znode physical data to zero.
858 	 */
859 	ASSERT(db->db_size >= sizeof (znode_phys_t));
860 	bzero(db->db_data, db->db_size);
861 	pzp = db->db_data;
862 
863 	/*
864 	 * If this is the root, fix up the half-initialized parent pointer
865 	 * to reference the just-allocated physical data area.
866 	 */
867 	if (flag & IS_ROOT_NODE) {
868 		dzp->z_dbuf = db;
869 		dzp->z_phys = pzp;
870 		dzp->z_id = obj;
871 	}
872 
873 	/*
874 	 * If parent is an xattr, so am I.
875 	 */
876 	if (dzp->z_phys->zp_flags & ZFS_XATTR)
877 		flag |= IS_XATTR;
878 
879 	if (vap->va_type == VBLK || vap->va_type == VCHR) {
880 		pzp->zp_rdev = zfs_expldev(vap->va_rdev);
881 	}
882 
883 	if (zfsvfs->z_use_fuids)
884 		pzp->zp_flags = ZFS_ARCHIVE | ZFS_AV_MODIFIED;
885 
886 	if (vap->va_type == VDIR) {
887 		pzp->zp_size = 2;		/* contents ("." and "..") */
888 		pzp->zp_links = (flag & (IS_ROOT_NODE | IS_XATTR)) ? 2 : 1;
889 	}
890 
891 	pzp->zp_parent = dzp->z_id;
892 	if (flag & IS_XATTR)
893 		pzp->zp_flags |= ZFS_XATTR;
894 
895 	pzp->zp_gen = gen;
896 
897 	ZFS_TIME_ENCODE(&now, pzp->zp_crtime);
898 	ZFS_TIME_ENCODE(&now, pzp->zp_ctime);
899 
900 	if (vap->va_mask & AT_ATIME) {
901 		ZFS_TIME_ENCODE(&vap->va_atime, pzp->zp_atime);
902 	} else {
903 		ZFS_TIME_ENCODE(&now, pzp->zp_atime);
904 	}
905 
906 	if (vap->va_mask & AT_MTIME) {
907 		ZFS_TIME_ENCODE(&vap->va_mtime, pzp->zp_mtime);
908 	} else {
909 		ZFS_TIME_ENCODE(&now, pzp->zp_mtime);
910 	}
911 
912 	pzp->zp_mode = MAKEIMODE(vap->va_type, vap->va_mode);
913 	if (!(flag & IS_ROOT_NODE)) {
914 		ZFS_OBJ_HOLD_ENTER(zfsvfs, obj);
915 		*zpp = zfs_znode_alloc(zfsvfs, db, 0);
916 		ZFS_OBJ_HOLD_EXIT(zfsvfs, obj);
917 	} else {
918 		/*
919 		 * If we are creating the root node, the "parent" we
920 		 * passed in is the znode for the root.
921 		 */
922 		*zpp = dzp;
923 	}
924 	zfs_perm_init(*zpp, dzp, flag, vap, tx, cr, setaclp, fuidp);
925 }
926 
927 void
928 zfs_xvattr_set(znode_t *zp, xvattr_t *xvap)
929 {
930 	xoptattr_t *xoap;
931 
932 	xoap = xva_getxoptattr(xvap);
933 	ASSERT(xoap);
934 
935 	if (XVA_ISSET_REQ(xvap, XAT_CREATETIME)) {
936 		ZFS_TIME_ENCODE(&xoap->xoa_createtime, zp->z_phys->zp_crtime);
937 		XVA_SET_RTN(xvap, XAT_CREATETIME);
938 	}
939 	if (XVA_ISSET_REQ(xvap, XAT_READONLY)) {
940 		ZFS_ATTR_SET(zp, ZFS_READONLY, xoap->xoa_readonly);
941 		XVA_SET_RTN(xvap, XAT_READONLY);
942 	}
943 	if (XVA_ISSET_REQ(xvap, XAT_HIDDEN)) {
944 		ZFS_ATTR_SET(zp, ZFS_HIDDEN, xoap->xoa_hidden);
945 		XVA_SET_RTN(xvap, XAT_HIDDEN);
946 	}
947 	if (XVA_ISSET_REQ(xvap, XAT_SYSTEM)) {
948 		ZFS_ATTR_SET(zp, ZFS_SYSTEM, xoap->xoa_system);
949 		XVA_SET_RTN(xvap, XAT_SYSTEM);
950 	}
951 	if (XVA_ISSET_REQ(xvap, XAT_ARCHIVE)) {
952 		ZFS_ATTR_SET(zp, ZFS_ARCHIVE, xoap->xoa_archive);
953 		XVA_SET_RTN(xvap, XAT_ARCHIVE);
954 	}
955 	if (XVA_ISSET_REQ(xvap, XAT_IMMUTABLE)) {
956 		ZFS_ATTR_SET(zp, ZFS_IMMUTABLE, xoap->xoa_immutable);
957 		XVA_SET_RTN(xvap, XAT_IMMUTABLE);
958 	}
959 	if (XVA_ISSET_REQ(xvap, XAT_NOUNLINK)) {
960 		ZFS_ATTR_SET(zp, ZFS_NOUNLINK, xoap->xoa_nounlink);
961 		XVA_SET_RTN(xvap, XAT_NOUNLINK);
962 	}
963 	if (XVA_ISSET_REQ(xvap, XAT_APPENDONLY)) {
964 		ZFS_ATTR_SET(zp, ZFS_APPENDONLY, xoap->xoa_appendonly);
965 		XVA_SET_RTN(xvap, XAT_APPENDONLY);
966 	}
967 	if (XVA_ISSET_REQ(xvap, XAT_NODUMP)) {
968 		ZFS_ATTR_SET(zp, ZFS_NODUMP, xoap->xoa_nodump);
969 		XVA_SET_RTN(xvap, XAT_NODUMP);
970 	}
971 	if (XVA_ISSET_REQ(xvap, XAT_OPAQUE)) {
972 		ZFS_ATTR_SET(zp, ZFS_OPAQUE, xoap->xoa_opaque);
973 		XVA_SET_RTN(xvap, XAT_OPAQUE);
974 	}
975 	if (XVA_ISSET_REQ(xvap, XAT_AV_QUARANTINED)) {
976 		ZFS_ATTR_SET(zp, ZFS_AV_QUARANTINED,
977 		    xoap->xoa_av_quarantined);
978 		XVA_SET_RTN(xvap, XAT_AV_QUARANTINED);
979 	}
980 	if (XVA_ISSET_REQ(xvap, XAT_AV_MODIFIED)) {
981 		ZFS_ATTR_SET(zp, ZFS_AV_MODIFIED, xoap->xoa_av_modified);
982 		XVA_SET_RTN(xvap, XAT_AV_MODIFIED);
983 	}
984 	if (XVA_ISSET_REQ(xvap, XAT_AV_SCANSTAMP)) {
985 		(void) memcpy(zp->z_phys + 1, xoap->xoa_av_scanstamp,
986 		    sizeof (xoap->xoa_av_scanstamp));
987 		zp->z_phys->zp_flags |= ZFS_BONUS_SCANSTAMP;
988 		XVA_SET_RTN(xvap, XAT_AV_SCANSTAMP);
989 	}
990 }
991 
992 int
993 zfs_zget(zfsvfs_t *zfsvfs, uint64_t obj_num, znode_t **zpp)
994 {
995 	dmu_object_info_t doi;
996 	dmu_buf_t	*db;
997 	znode_t		*zp;
998 	int err;
999 
1000 	*zpp = NULL;
1001 
1002 	ZFS_OBJ_HOLD_ENTER(zfsvfs, obj_num);
1003 
1004 	err = dmu_bonus_hold(zfsvfs->z_os, obj_num, NULL, &db);
1005 	if (err) {
1006 		ZFS_OBJ_HOLD_EXIT(zfsvfs, obj_num);
1007 		return (err);
1008 	}
1009 
1010 	dmu_object_info_from_db(db, &doi);
1011 	if (doi.doi_bonus_type != DMU_OT_ZNODE ||
1012 	    doi.doi_bonus_size < sizeof (znode_phys_t)) {
1013 		dmu_buf_rele(db, NULL);
1014 		ZFS_OBJ_HOLD_EXIT(zfsvfs, obj_num);
1015 		return (EINVAL);
1016 	}
1017 
1018 	zp = dmu_buf_get_user(db);
1019 	if (zp != NULL) {
1020 		mutex_enter(&zp->z_lock);
1021 
1022 		/*
1023 		 * Since we do immediate eviction of the z_dbuf, we
1024 		 * should never find a dbuf with a znode that doesn't
1025 		 * know about the dbuf.
1026 		 */
1027 		ASSERT3P(zp->z_dbuf, ==, db);
1028 		ASSERT3U(zp->z_id, ==, obj_num);
1029 		if (zp->z_unlinked) {
1030 			err = ENOENT;
1031 		} else {
1032 			VN_HOLD(ZTOV(zp));
1033 			*zpp = zp;
1034 			err = 0;
1035 		}
1036 		dmu_buf_rele(db, NULL);
1037 		mutex_exit(&zp->z_lock);
1038 		ZFS_OBJ_HOLD_EXIT(zfsvfs, obj_num);
1039 		return (err);
1040 	}
1041 
1042 	/*
1043 	 * Not found create new znode/vnode
1044 	 */
1045 	zp = zfs_znode_alloc(zfsvfs, db, doi.doi_data_block_size);
1046 	ZFS_OBJ_HOLD_EXIT(zfsvfs, obj_num);
1047 	*zpp = zp;
1048 	return (0);
1049 }
1050 
1051 int
1052 zfs_rezget(znode_t *zp)
1053 {
1054 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
1055 	dmu_object_info_t doi;
1056 	dmu_buf_t *db;
1057 	uint64_t obj_num = zp->z_id;
1058 	int err;
1059 
1060 	ZFS_OBJ_HOLD_ENTER(zfsvfs, obj_num);
1061 
1062 	err = dmu_bonus_hold(zfsvfs->z_os, obj_num, NULL, &db);
1063 	if (err) {
1064 		ZFS_OBJ_HOLD_EXIT(zfsvfs, obj_num);
1065 		return (err);
1066 	}
1067 
1068 	dmu_object_info_from_db(db, &doi);
1069 	if (doi.doi_bonus_type != DMU_OT_ZNODE ||
1070 	    doi.doi_bonus_size < sizeof (znode_phys_t)) {
1071 		dmu_buf_rele(db, NULL);
1072 		ZFS_OBJ_HOLD_EXIT(zfsvfs, obj_num);
1073 		return (EINVAL);
1074 	}
1075 
1076 	if (((znode_phys_t *)db->db_data)->zp_gen != zp->z_gen) {
1077 		dmu_buf_rele(db, NULL);
1078 		ZFS_OBJ_HOLD_EXIT(zfsvfs, obj_num);
1079 		return (EIO);
1080 	}
1081 
1082 	zfs_znode_dmu_init(zfsvfs, zp, db);
1083 	zp->z_unlinked = (zp->z_phys->zp_links == 0);
1084 	zp->z_blksz = doi.doi_data_block_size;
1085 
1086 	ZFS_OBJ_HOLD_EXIT(zfsvfs, obj_num);
1087 
1088 	return (0);
1089 }
1090 
1091 void
1092 zfs_znode_delete(znode_t *zp, dmu_tx_t *tx)
1093 {
1094 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
1095 	objset_t *os = zfsvfs->z_os;
1096 	uint64_t obj = zp->z_id;
1097 	uint64_t acl_obj = zp->z_phys->zp_acl.z_acl_extern_obj;
1098 
1099 	ZFS_OBJ_HOLD_ENTER(zfsvfs, obj);
1100 	if (acl_obj)
1101 		VERIFY(0 == dmu_object_free(os, acl_obj, tx));
1102 	VERIFY(0 == dmu_object_free(os, obj, tx));
1103 	zfs_znode_dmu_fini(zp);
1104 	ZFS_OBJ_HOLD_EXIT(zfsvfs, obj);
1105 	zfs_znode_free(zp);
1106 }
1107 
1108 void
1109 zfs_zinactive(znode_t *zp)
1110 {
1111 	vnode_t	*vp = ZTOV(zp);
1112 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
1113 	uint64_t z_id = zp->z_id;
1114 
1115 	ASSERT(zp->z_dbuf && zp->z_phys);
1116 
1117 	/*
1118 	 * Don't allow a zfs_zget() while were trying to release this znode
1119 	 */
1120 	ZFS_OBJ_HOLD_ENTER(zfsvfs, z_id);
1121 
1122 	mutex_enter(&zp->z_lock);
1123 	mutex_enter(&vp->v_lock);
1124 	vp->v_count--;
1125 	if (vp->v_count > 0 || vn_has_cached_data(vp)) {
1126 		/*
1127 		 * If the hold count is greater than zero, somebody has
1128 		 * obtained a new reference on this znode while we were
1129 		 * processing it here, so we are done.  If we still have
1130 		 * mapped pages then we are also done, since we don't
1131 		 * want to inactivate the znode until the pages get pushed.
1132 		 *
1133 		 * XXX - if vn_has_cached_data(vp) is true, but count == 0,
1134 		 * this seems like it would leave the znode hanging with
1135 		 * no chance to go inactive...
1136 		 */
1137 		mutex_exit(&vp->v_lock);
1138 		mutex_exit(&zp->z_lock);
1139 		ZFS_OBJ_HOLD_EXIT(zfsvfs, z_id);
1140 		return;
1141 	}
1142 	mutex_exit(&vp->v_lock);
1143 
1144 	/*
1145 	 * If this was the last reference to a file with no links,
1146 	 * remove the file from the file system.
1147 	 */
1148 	if (zp->z_unlinked) {
1149 		mutex_exit(&zp->z_lock);
1150 		ZFS_OBJ_HOLD_EXIT(zfsvfs, z_id);
1151 		zfs_rmnode(zp);
1152 		return;
1153 	}
1154 	mutex_exit(&zp->z_lock);
1155 	zfs_znode_dmu_fini(zp);
1156 	ZFS_OBJ_HOLD_EXIT(zfsvfs, z_id);
1157 	zfs_znode_free(zp);
1158 }
1159 
1160 void
1161 zfs_znode_free(znode_t *zp)
1162 {
1163 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
1164 
1165 	vn_invalid(ZTOV(zp));
1166 
1167 	ASSERT(ZTOV(zp)->v_count == 0);
1168 
1169 	mutex_enter(&zfsvfs->z_znodes_lock);
1170 	POINTER_INVALIDATE(&zp->z_zfsvfs);
1171 	list_remove(&zfsvfs->z_all_znodes, zp);
1172 	mutex_exit(&zfsvfs->z_znodes_lock);
1173 
1174 	kmem_cache_free(znode_cache, zp);
1175 
1176 	VFS_RELE(zfsvfs->z_vfs);
1177 }
1178 
1179 void
1180 zfs_time_stamper_locked(znode_t *zp, uint_t flag, dmu_tx_t *tx)
1181 {
1182 	timestruc_t	now;
1183 
1184 	ASSERT(MUTEX_HELD(&zp->z_lock));
1185 
1186 	gethrestime(&now);
1187 
1188 	if (tx) {
1189 		dmu_buf_will_dirty(zp->z_dbuf, tx);
1190 		zp->z_atime_dirty = 0;
1191 		zp->z_seq++;
1192 	} else {
1193 		zp->z_atime_dirty = 1;
1194 	}
1195 
1196 	if (flag & AT_ATIME)
1197 		ZFS_TIME_ENCODE(&now, zp->z_phys->zp_atime);
1198 
1199 	if (flag & AT_MTIME) {
1200 		ZFS_TIME_ENCODE(&now, zp->z_phys->zp_mtime);
1201 		if (zp->z_zfsvfs->z_use_fuids)
1202 			zp->z_phys->zp_flags |= (ZFS_ARCHIVE | ZFS_AV_MODIFIED);
1203 	}
1204 
1205 	if (flag & AT_CTIME) {
1206 		ZFS_TIME_ENCODE(&now, zp->z_phys->zp_ctime);
1207 		if (zp->z_zfsvfs->z_use_fuids)
1208 			zp->z_phys->zp_flags |= ZFS_ARCHIVE;
1209 	}
1210 }
1211 
1212 /*
1213  * Update the requested znode timestamps with the current time.
1214  * If we are in a transaction, then go ahead and mark the znode
1215  * dirty in the transaction so the timestamps will go to disk.
1216  * Otherwise, we will get pushed next time the znode is updated
1217  * in a transaction, or when this znode eventually goes inactive.
1218  *
1219  * Why is this OK?
1220  *  1 - Only the ACCESS time is ever updated outside of a transaction.
1221  *  2 - Multiple consecutive updates will be collapsed into a single
1222  *	znode update by the transaction grouping semantics of the DMU.
1223  */
1224 void
1225 zfs_time_stamper(znode_t *zp, uint_t flag, dmu_tx_t *tx)
1226 {
1227 	mutex_enter(&zp->z_lock);
1228 	zfs_time_stamper_locked(zp, flag, tx);
1229 	mutex_exit(&zp->z_lock);
1230 }
1231 
1232 /*
1233  * Grow the block size for a file.
1234  *
1235  *	IN:	zp	- znode of file to free data in.
1236  *		size	- requested block size
1237  *		tx	- open transaction.
1238  *
1239  * NOTE: this function assumes that the znode is write locked.
1240  */
1241 void
1242 zfs_grow_blocksize(znode_t *zp, uint64_t size, dmu_tx_t *tx)
1243 {
1244 	int		error;
1245 	u_longlong_t	dummy;
1246 
1247 	if (size <= zp->z_blksz)
1248 		return;
1249 	/*
1250 	 * If the file size is already greater than the current blocksize,
1251 	 * we will not grow.  If there is more than one block in a file,
1252 	 * the blocksize cannot change.
1253 	 */
1254 	if (zp->z_blksz && zp->z_phys->zp_size > zp->z_blksz)
1255 		return;
1256 
1257 	error = dmu_object_set_blocksize(zp->z_zfsvfs->z_os, zp->z_id,
1258 	    size, 0, tx);
1259 	if (error == ENOTSUP)
1260 		return;
1261 	ASSERT3U(error, ==, 0);
1262 
1263 	/* What blocksize did we actually get? */
1264 	dmu_object_size_from_db(zp->z_dbuf, &zp->z_blksz, &dummy);
1265 }
1266 
1267 /*
1268  * This is a dummy interface used when pvn_vplist_dirty() should *not*
1269  * be calling back into the fs for a putpage().  E.g.: when truncating
1270  * a file, the pages being "thrown away* don't need to be written out.
1271  */
1272 /* ARGSUSED */
1273 static int
1274 zfs_no_putpage(vnode_t *vp, page_t *pp, u_offset_t *offp, size_t *lenp,
1275     int flags, cred_t *cr)
1276 {
1277 	ASSERT(0);
1278 	return (0);
1279 }
1280 
1281 /*
1282  * Increase the file length
1283  *
1284  *	IN:	zp	- znode of file to free data in.
1285  *		end	- new end-of-file
1286  *
1287  * 	RETURN:	0 if success
1288  *		error code if failure
1289  */
1290 static int
1291 zfs_extend(znode_t *zp, uint64_t end)
1292 {
1293 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
1294 	dmu_tx_t *tx;
1295 	rl_t *rl;
1296 	uint64_t newblksz;
1297 	int error;
1298 
1299 	/*
1300 	 * We will change zp_size, lock the whole file.
1301 	 */
1302 	rl = zfs_range_lock(zp, 0, UINT64_MAX, RL_WRITER);
1303 
1304 	/*
1305 	 * Nothing to do if file already at desired length.
1306 	 */
1307 	if (end <= zp->z_phys->zp_size) {
1308 		zfs_range_unlock(rl);
1309 		return (0);
1310 	}
1311 top:
1312 	tx = dmu_tx_create(zfsvfs->z_os);
1313 	dmu_tx_hold_bonus(tx, zp->z_id);
1314 	if (end > zp->z_blksz &&
1315 	    (!ISP2(zp->z_blksz) || zp->z_blksz < zfsvfs->z_max_blksz)) {
1316 		/*
1317 		 * We are growing the file past the current block size.
1318 		 */
1319 		if (zp->z_blksz > zp->z_zfsvfs->z_max_blksz) {
1320 			ASSERT(!ISP2(zp->z_blksz));
1321 			newblksz = MIN(end, SPA_MAXBLOCKSIZE);
1322 		} else {
1323 			newblksz = MIN(end, zp->z_zfsvfs->z_max_blksz);
1324 		}
1325 		dmu_tx_hold_write(tx, zp->z_id, 0, newblksz);
1326 	} else {
1327 		newblksz = 0;
1328 	}
1329 
1330 	error = dmu_tx_assign(tx, TXG_NOWAIT);
1331 	if (error) {
1332 		if (error == ERESTART) {
1333 			dmu_tx_wait(tx);
1334 			dmu_tx_abort(tx);
1335 			goto top;
1336 		}
1337 		dmu_tx_abort(tx);
1338 		zfs_range_unlock(rl);
1339 		return (error);
1340 	}
1341 	dmu_buf_will_dirty(zp->z_dbuf, tx);
1342 
1343 	if (newblksz)
1344 		zfs_grow_blocksize(zp, newblksz, tx);
1345 
1346 	zp->z_phys->zp_size = end;
1347 
1348 	zfs_range_unlock(rl);
1349 
1350 	dmu_tx_commit(tx);
1351 
1352 	return (0);
1353 }
1354 
1355 /*
1356  * Free space in a file.
1357  *
1358  *	IN:	zp	- znode of file to free data in.
1359  *		off	- start of section to free.
1360  *		len	- length of section to free.
1361  *
1362  * 	RETURN:	0 if success
1363  *		error code if failure
1364  */
1365 static int
1366 zfs_free_range(znode_t *zp, uint64_t off, uint64_t len)
1367 {
1368 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
1369 	rl_t *rl;
1370 	int error;
1371 
1372 	/*
1373 	 * Lock the range being freed.
1374 	 */
1375 	rl = zfs_range_lock(zp, off, len, RL_WRITER);
1376 
1377 	/*
1378 	 * Nothing to do if file already at desired length.
1379 	 */
1380 	if (off >= zp->z_phys->zp_size) {
1381 		zfs_range_unlock(rl);
1382 		return (0);
1383 	}
1384 
1385 	if (off + len > zp->z_phys->zp_size)
1386 		len = zp->z_phys->zp_size - off;
1387 
1388 	error = dmu_free_long_range(zfsvfs->z_os, zp->z_id, off, len);
1389 
1390 	zfs_range_unlock(rl);
1391 
1392 	return (error);
1393 }
1394 
1395 /*
1396  * Truncate a file
1397  *
1398  *	IN:	zp	- znode of file to free data in.
1399  *		end	- new end-of-file.
1400  *
1401  * 	RETURN:	0 if success
1402  *		error code if failure
1403  */
1404 static int
1405 zfs_trunc(znode_t *zp, uint64_t end)
1406 {
1407 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
1408 	vnode_t *vp = ZTOV(zp);
1409 	dmu_tx_t *tx;
1410 	rl_t *rl;
1411 	int error;
1412 
1413 	/*
1414 	 * We will change zp_size, lock the whole file.
1415 	 */
1416 	rl = zfs_range_lock(zp, 0, UINT64_MAX, RL_WRITER);
1417 
1418 	/*
1419 	 * Nothing to do if file already at desired length.
1420 	 */
1421 	if (end >= zp->z_phys->zp_size) {
1422 		zfs_range_unlock(rl);
1423 		return (0);
1424 	}
1425 
1426 	error = dmu_free_long_range(zfsvfs->z_os, zp->z_id, end,  -1);
1427 	if (error) {
1428 		zfs_range_unlock(rl);
1429 		return (error);
1430 	}
1431 top:
1432 	tx = dmu_tx_create(zfsvfs->z_os);
1433 	dmu_tx_hold_bonus(tx, zp->z_id);
1434 	error = dmu_tx_assign(tx, TXG_NOWAIT);
1435 	if (error) {
1436 		if (error == ERESTART) {
1437 			dmu_tx_wait(tx);
1438 			dmu_tx_abort(tx);
1439 			goto top;
1440 		}
1441 		dmu_tx_abort(tx);
1442 		zfs_range_unlock(rl);
1443 		return (error);
1444 	}
1445 	dmu_buf_will_dirty(zp->z_dbuf, tx);
1446 
1447 	zp->z_phys->zp_size = end;
1448 
1449 	dmu_tx_commit(tx);
1450 
1451 	/*
1452 	 * Clear any mapped pages in the truncated region.  This has to
1453 	 * happen outside of the transaction to avoid the possibility of
1454 	 * a deadlock with someone trying to push a page that we are
1455 	 * about to invalidate.
1456 	 */
1457 	if (vn_has_cached_data(vp)) {
1458 		page_t *pp;
1459 		uint64_t start = end & PAGEMASK;
1460 		int poff = end & PAGEOFFSET;
1461 
1462 		if (poff != 0 && (pp = page_lookup(vp, start, SE_SHARED))) {
1463 			/*
1464 			 * We need to zero a partial page.
1465 			 */
1466 			pagezero(pp, poff, PAGESIZE - poff);
1467 			start += PAGESIZE;
1468 			page_unlock(pp);
1469 		}
1470 		error = pvn_vplist_dirty(vp, start, zfs_no_putpage,
1471 		    B_INVAL | B_TRUNC, NULL);
1472 		ASSERT(error == 0);
1473 	}
1474 
1475 	zfs_range_unlock(rl);
1476 
1477 	return (0);
1478 }
1479 
1480 /*
1481  * Free space in a file
1482  *
1483  *	IN:	zp	- znode of file to free data in.
1484  *		off	- start of range
1485  *		len	- end of range (0 => EOF)
1486  *		flag	- current file open mode flags.
1487  *		log	- TRUE if this action should be logged
1488  *
1489  * 	RETURN:	0 if success
1490  *		error code if failure
1491  */
1492 int
1493 zfs_freesp(znode_t *zp, uint64_t off, uint64_t len, int flag, boolean_t log)
1494 {
1495 	vnode_t *vp = ZTOV(zp);
1496 	dmu_tx_t *tx;
1497 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
1498 	zilog_t *zilog = zfsvfs->z_log;
1499 	int error;
1500 
1501 	if (off > zp->z_phys->zp_size) {
1502 		error =  zfs_extend(zp, off+len);
1503 		if (error == 0 && log)
1504 			goto log;
1505 		else
1506 			return (error);
1507 	}
1508 
1509 	/*
1510 	 * Check for any locks in the region to be freed.
1511 	 */
1512 	if (MANDLOCK(vp, (mode_t)zp->z_phys->zp_mode)) {
1513 		uint64_t length = (len ? len : zp->z_phys->zp_size - off);
1514 		if (error = chklock(vp, FWRITE, off, length, flag, NULL))
1515 			return (error);
1516 	}
1517 
1518 	if (len == 0) {
1519 		error = zfs_trunc(zp, off);
1520 	} else {
1521 		if ((error = zfs_free_range(zp, off, len)) == 0 &&
1522 		    off + len > zp->z_phys->zp_size)
1523 			error = zfs_extend(zp, off+len);
1524 	}
1525 	if (error || !log)
1526 		return (error);
1527 log:
1528 	tx = dmu_tx_create(zfsvfs->z_os);
1529 	dmu_tx_hold_bonus(tx, zp->z_id);
1530 	error = dmu_tx_assign(tx, TXG_NOWAIT);
1531 	if (error) {
1532 		if (error == ERESTART) {
1533 			dmu_tx_wait(tx);
1534 			dmu_tx_abort(tx);
1535 			goto log;
1536 		}
1537 		dmu_tx_abort(tx);
1538 		return (error);
1539 	}
1540 
1541 	zfs_time_stamper(zp, CONTENT_MODIFIED, tx);
1542 	zfs_log_truncate(zilog, tx, TX_TRUNCATE, zp, off, len);
1543 
1544 	dmu_tx_commit(tx);
1545 	return (0);
1546 }
1547 
1548 void
1549 zfs_create_fs(objset_t *os, cred_t *cr, nvlist_t *zplprops, dmu_tx_t *tx)
1550 {
1551 	zfsvfs_t	zfsvfs;
1552 	uint64_t	moid, doid, version;
1553 	uint64_t	sense = ZFS_CASE_SENSITIVE;
1554 	uint64_t	norm = 0;
1555 	nvpair_t	*elem;
1556 	int		error;
1557 	znode_t		*rootzp = NULL;
1558 	vnode_t		*vp;
1559 	vattr_t		vattr;
1560 	znode_t		*zp;
1561 
1562 	/*
1563 	 * First attempt to create master node.
1564 	 */
1565 	/*
1566 	 * In an empty objset, there are no blocks to read and thus
1567 	 * there can be no i/o errors (which we assert below).
1568 	 */
1569 	moid = MASTER_NODE_OBJ;
1570 	error = zap_create_claim(os, moid, DMU_OT_MASTER_NODE,
1571 	    DMU_OT_NONE, 0, tx);
1572 	ASSERT(error == 0);
1573 
1574 	/*
1575 	 * Set starting attributes.
1576 	 */
1577 	if (spa_version(dmu_objset_spa(os)) >= SPA_VERSION_FUID)
1578 		version = ZPL_VERSION;
1579 	else
1580 		version = ZPL_VERSION_FUID - 1;
1581 	error = zap_update(os, moid, ZPL_VERSION_STR,
1582 	    8, 1, &version, tx);
1583 	elem = NULL;
1584 	while ((elem = nvlist_next_nvpair(zplprops, elem)) != NULL) {
1585 		/* For the moment we expect all zpl props to be uint64_ts */
1586 		uint64_t val;
1587 		char *name;
1588 
1589 		ASSERT(nvpair_type(elem) == DATA_TYPE_UINT64);
1590 		VERIFY(nvpair_value_uint64(elem, &val) == 0);
1591 		name = nvpair_name(elem);
1592 		if (strcmp(name, zfs_prop_to_name(ZFS_PROP_VERSION)) == 0) {
1593 			version = val;
1594 			error = zap_update(os, moid, ZPL_VERSION_STR,
1595 			    8, 1, &version, tx);
1596 		} else {
1597 			error = zap_update(os, moid, name, 8, 1, &val, tx);
1598 		}
1599 		ASSERT(error == 0);
1600 		if (strcmp(name, zfs_prop_to_name(ZFS_PROP_NORMALIZE)) == 0)
1601 			norm = val;
1602 		else if (strcmp(name, zfs_prop_to_name(ZFS_PROP_CASE)) == 0)
1603 			sense = val;
1604 	}
1605 	ASSERT(version != 0);
1606 
1607 	/*
1608 	 * Create a delete queue.
1609 	 */
1610 	doid = zap_create(os, DMU_OT_UNLINKED_SET, DMU_OT_NONE, 0, tx);
1611 
1612 	error = zap_add(os, moid, ZFS_UNLINKED_SET, 8, 1, &doid, tx);
1613 	ASSERT(error == 0);
1614 
1615 	/*
1616 	 * Create root znode.  Create minimal znode/vnode/zfsvfs
1617 	 * to allow zfs_mknode to work.
1618 	 */
1619 	vattr.va_mask = AT_MODE|AT_UID|AT_GID|AT_TYPE;
1620 	vattr.va_type = VDIR;
1621 	vattr.va_mode = S_IFDIR|0755;
1622 	vattr.va_uid = crgetuid(cr);
1623 	vattr.va_gid = crgetgid(cr);
1624 
1625 	rootzp = kmem_cache_alloc(znode_cache, KM_SLEEP);
1626 	rootzp->z_unlinked = 0;
1627 	rootzp->z_atime_dirty = 0;
1628 
1629 	vp = ZTOV(rootzp);
1630 	vn_reinit(vp);
1631 	vp->v_type = VDIR;
1632 
1633 	bzero(&zfsvfs, sizeof (zfsvfs_t));
1634 
1635 	zfsvfs.z_os = os;
1636 	zfsvfs.z_parent = &zfsvfs;
1637 	zfsvfs.z_version = version;
1638 	zfsvfs.z_use_fuids = USE_FUIDS(version, os);
1639 	zfsvfs.z_norm = norm;
1640 	/*
1641 	 * Fold case on file systems that are always or sometimes case
1642 	 * insensitive.
1643 	 */
1644 	if (sense == ZFS_CASE_INSENSITIVE || sense == ZFS_CASE_MIXED)
1645 		zfsvfs.z_norm |= U8_TEXTPREP_TOUPPER;
1646 
1647 	mutex_init(&zfsvfs.z_znodes_lock, NULL, MUTEX_DEFAULT, NULL);
1648 	list_create(&zfsvfs.z_all_znodes, sizeof (znode_t),
1649 	    offsetof(znode_t, z_link_node));
1650 
1651 	ASSERT(!POINTER_IS_VALID(rootzp->z_zfsvfs));
1652 	rootzp->z_zfsvfs = &zfsvfs;
1653 	zfs_mknode(rootzp, &vattr, tx, cr, IS_ROOT_NODE, &zp, 0, NULL, NULL);
1654 	ASSERT3P(zp, ==, rootzp);
1655 	ASSERT(!vn_in_dnlc(ZTOV(rootzp))); /* not valid to move */
1656 	error = zap_add(os, moid, ZFS_ROOT_OBJ, 8, 1, &rootzp->z_id, tx);
1657 	ASSERT(error == 0);
1658 	POINTER_INVALIDATE(&rootzp->z_zfsvfs);
1659 
1660 	ZTOV(rootzp)->v_count = 0;
1661 	dmu_buf_rele(rootzp->z_dbuf, NULL);
1662 	rootzp->z_dbuf = NULL;
1663 	kmem_cache_free(znode_cache, rootzp);
1664 
1665 	/*
1666 	 * Create shares directory
1667 	 */
1668 
1669 	error = zfs_create_share_dir(&zfsvfs, tx);
1670 	ASSERT(error == 0);
1671 }
1672 
1673 #endif /* _KERNEL */
1674 /*
1675  * Given an object number, return its parent object number and whether
1676  * or not the object is an extended attribute directory.
1677  */
1678 static int
1679 zfs_obj_to_pobj(objset_t *osp, uint64_t obj, uint64_t *pobjp, int *is_xattrdir)
1680 {
1681 	dmu_buf_t *db;
1682 	dmu_object_info_t doi;
1683 	znode_phys_t *zp;
1684 	int error;
1685 
1686 	if ((error = dmu_bonus_hold(osp, obj, FTAG, &db)) != 0)
1687 		return (error);
1688 
1689 	dmu_object_info_from_db(db, &doi);
1690 	if (doi.doi_bonus_type != DMU_OT_ZNODE ||
1691 	    doi.doi_bonus_size < sizeof (znode_phys_t)) {
1692 		dmu_buf_rele(db, FTAG);
1693 		return (EINVAL);
1694 	}
1695 
1696 	zp = db->db_data;
1697 	*pobjp = zp->zp_parent;
1698 	*is_xattrdir = ((zp->zp_flags & ZFS_XATTR) != 0) &&
1699 	    S_ISDIR(zp->zp_mode);
1700 	dmu_buf_rele(db, FTAG);
1701 
1702 	return (0);
1703 }
1704 
1705 int
1706 zfs_obj_to_path(objset_t *osp, uint64_t obj, char *buf, int len)
1707 {
1708 	char *path = buf + len - 1;
1709 	int error;
1710 
1711 	*path = '\0';
1712 
1713 	for (;;) {
1714 		uint64_t pobj;
1715 		char component[MAXNAMELEN + 2];
1716 		size_t complen;
1717 		int is_xattrdir;
1718 
1719 		if ((error = zfs_obj_to_pobj(osp, obj, &pobj,
1720 		    &is_xattrdir)) != 0)
1721 			break;
1722 
1723 		if (pobj == obj) {
1724 			if (path[0] != '/')
1725 				*--path = '/';
1726 			break;
1727 		}
1728 
1729 		component[0] = '/';
1730 		if (is_xattrdir) {
1731 			(void) sprintf(component + 1, "<xattrdir>");
1732 		} else {
1733 			error = zap_value_search(osp, pobj, obj,
1734 			    ZFS_DIRENT_OBJ(-1ULL), component + 1);
1735 			if (error != 0)
1736 				break;
1737 		}
1738 
1739 		complen = strlen(component);
1740 		path -= complen;
1741 		ASSERT(path >= buf);
1742 		bcopy(component, path, complen);
1743 		obj = pobj;
1744 	}
1745 
1746 	if (error == 0)
1747 		(void) memmove(buf, path, buf + len - path);
1748 	return (error);
1749 }
1750