xref: /titanic_41/usr/src/uts/common/fs/zfs/zfs_znode.c (revision c3c82186300a3bf11cfdda43b1cca3cd6b333629)
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 int
430 zfs_create_share_dir(zfsvfs_t *zfsvfs, dmu_tx_t *tx)
431 {
432 	zfs_acl_ids_t acl_ids;
433 	vattr_t vattr;
434 	znode_t *sharezp;
435 	vnode_t *vp;
436 	znode_t *zp;
437 	int error;
438 
439 	vattr.va_mask = AT_MODE|AT_UID|AT_GID|AT_TYPE;
440 	vattr.va_type = VDIR;
441 	vattr.va_mode = S_IFDIR|0555;
442 	vattr.va_uid = crgetuid(kcred);
443 	vattr.va_gid = crgetgid(kcred);
444 
445 	sharezp = kmem_cache_alloc(znode_cache, KM_SLEEP);
446 	sharezp->z_unlinked = 0;
447 	sharezp->z_atime_dirty = 0;
448 	sharezp->z_zfsvfs = zfsvfs;
449 
450 	vp = ZTOV(sharezp);
451 	vn_reinit(vp);
452 	vp->v_type = VDIR;
453 
454 	VERIFY(0 == zfs_acl_ids_create(sharezp, IS_ROOT_NODE, &vattr,
455 	    kcred, NULL, &acl_ids));
456 	zfs_mknode(sharezp, &vattr, tx, kcred, IS_ROOT_NODE,
457 	    &zp, 0, &acl_ids);
458 	ASSERT3P(zp, ==, sharezp);
459 	ASSERT(!vn_in_dnlc(ZTOV(sharezp))); /* not valid to move */
460 	POINTER_INVALIDATE(&sharezp->z_zfsvfs);
461 	error = zap_add(zfsvfs->z_os, MASTER_NODE_OBJ,
462 	    ZFS_SHARES_DIR, 8, 1, &sharezp->z_id, tx);
463 	zfsvfs->z_shares_dir = sharezp->z_id;
464 
465 	zfs_acl_ids_free(&acl_ids);
466 	ZTOV(sharezp)->v_count = 0;
467 	dmu_buf_rele(sharezp->z_dbuf, NULL);
468 	sharezp->z_dbuf = NULL;
469 	kmem_cache_free(znode_cache, sharezp);
470 
471 	return (error);
472 }
473 
474 /*
475  * zfs_init_fs - Initialize the zfsvfs struct and the file system
476  *	incore "master" object.  Verify version compatibility.
477  */
478 int
479 zfs_init_fs(zfsvfs_t *zfsvfs, znode_t **zpp)
480 {
481 	extern int zfsfstype;
482 
483 	objset_t	*os = zfsvfs->z_os;
484 	int		i, error;
485 	uint64_t fsid_guid;
486 	uint64_t zval;
487 
488 	*zpp = NULL;
489 
490 	error = zfs_get_zplprop(os, ZFS_PROP_VERSION, &zfsvfs->z_version);
491 	if (error) {
492 		return (error);
493 	} else if (zfsvfs->z_version > ZPL_VERSION) {
494 		(void) printf("Mismatched versions:  File system "
495 		    "is version %llu on-disk format, which is "
496 		    "incompatible with this software version %lld!",
497 		    (u_longlong_t)zfsvfs->z_version, ZPL_VERSION);
498 		return (ENOTSUP);
499 	}
500 
501 	if ((error = zfs_get_zplprop(os, ZFS_PROP_NORMALIZE, &zval)) != 0)
502 		return (error);
503 	zfsvfs->z_norm = (int)zval;
504 	if ((error = zfs_get_zplprop(os, ZFS_PROP_UTF8ONLY, &zval)) != 0)
505 		return (error);
506 	zfsvfs->z_utf8 = (zval != 0);
507 	if ((error = zfs_get_zplprop(os, ZFS_PROP_CASE, &zval)) != 0)
508 		return (error);
509 	zfsvfs->z_case = (uint_t)zval;
510 	/*
511 	 * Fold case on file systems that are always or sometimes case
512 	 * insensitive.
513 	 */
514 	if (zfsvfs->z_case == ZFS_CASE_INSENSITIVE ||
515 	    zfsvfs->z_case == ZFS_CASE_MIXED)
516 		zfsvfs->z_norm |= U8_TEXTPREP_TOUPPER;
517 
518 	/*
519 	 * The fsid is 64 bits, composed of an 8-bit fs type, which
520 	 * separates our fsid from any other filesystem types, and a
521 	 * 56-bit objset unique ID.  The objset unique ID is unique to
522 	 * all objsets open on this system, provided by unique_create().
523 	 * The 8-bit fs type must be put in the low bits of fsid[1]
524 	 * because that's where other Solaris filesystems put it.
525 	 */
526 	fsid_guid = dmu_objset_fsid_guid(os);
527 	ASSERT((fsid_guid & ~((1ULL<<56)-1)) == 0);
528 	zfsvfs->z_vfs->vfs_fsid.val[0] = fsid_guid;
529 	zfsvfs->z_vfs->vfs_fsid.val[1] = ((fsid_guid>>32) << 8) |
530 	    zfsfstype & 0xFF;
531 
532 	error = zap_lookup(os, MASTER_NODE_OBJ, ZFS_ROOT_OBJ, 8, 1,
533 	    &zfsvfs->z_root);
534 	if (error)
535 		return (error);
536 	ASSERT(zfsvfs->z_root != 0);
537 
538 	error = zap_lookup(os, MASTER_NODE_OBJ, ZFS_UNLINKED_SET, 8, 1,
539 	    &zfsvfs->z_unlinkedobj);
540 	if (error)
541 		return (error);
542 
543 	error = zap_lookup(os, MASTER_NODE_OBJ, ZFS_FUID_TABLES, 8, 1,
544 	    &zfsvfs->z_fuid_obj);
545 	if (error == ENOENT)
546 		error = 0;
547 
548 	error = zap_lookup(os, MASTER_NODE_OBJ, ZFS_SHARES_DIR, 8, 1,
549 	    &zfsvfs->z_shares_dir);
550 	if (error && error != ENOENT)
551 		return (error);
552 
553 	/*
554 	 * Initialize zget mutex's
555 	 */
556 	for (i = 0; i != ZFS_OBJ_MTX_SZ; i++)
557 		mutex_init(&zfsvfs->z_hold_mtx[i], NULL, MUTEX_DEFAULT, NULL);
558 
559 	error = zfs_zget(zfsvfs, zfsvfs->z_root, zpp);
560 	if (error) {
561 		/*
562 		 * On error, we destroy the mutexes here since it's not
563 		 * possible for the caller to determine if the mutexes were
564 		 * initialized properly.
565 		 */
566 		for (i = 0; i != ZFS_OBJ_MTX_SZ; i++)
567 			mutex_destroy(&zfsvfs->z_hold_mtx[i]);
568 		return (error);
569 	}
570 	ASSERT3U((*zpp)->z_id, ==, zfsvfs->z_root);
571 
572 	return (error);
573 }
574 
575 /*
576  * define a couple of values we need available
577  * for both 64 and 32 bit environments.
578  */
579 #ifndef NBITSMINOR64
580 #define	NBITSMINOR64	32
581 #endif
582 #ifndef MAXMAJ64
583 #define	MAXMAJ64	0xffffffffUL
584 #endif
585 #ifndef	MAXMIN64
586 #define	MAXMIN64	0xffffffffUL
587 #endif
588 
589 /*
590  * Create special expldev for ZFS private use.
591  * Can't use standard expldev since it doesn't do
592  * what we want.  The standard expldev() takes a
593  * dev32_t in LP64 and expands it to a long dev_t.
594  * We need an interface that takes a dev32_t in ILP32
595  * and expands it to a long dev_t.
596  */
597 static uint64_t
598 zfs_expldev(dev_t dev)
599 {
600 #ifndef _LP64
601 	major_t major = (major_t)dev >> NBITSMINOR32 & MAXMAJ32;
602 	return (((uint64_t)major << NBITSMINOR64) |
603 	    ((minor_t)dev & MAXMIN32));
604 #else
605 	return (dev);
606 #endif
607 }
608 
609 /*
610  * Special cmpldev for ZFS private use.
611  * Can't use standard cmpldev since it takes
612  * a long dev_t and compresses it to dev32_t in
613  * LP64.  We need to do a compaction of a long dev_t
614  * to a dev32_t in ILP32.
615  */
616 dev_t
617 zfs_cmpldev(uint64_t dev)
618 {
619 #ifndef _LP64
620 	minor_t minor = (minor_t)dev & MAXMIN64;
621 	major_t major = (major_t)(dev >> NBITSMINOR64) & MAXMAJ64;
622 
623 	if (major > MAXMAJ32 || minor > MAXMIN32)
624 		return (NODEV32);
625 
626 	return (((dev32_t)major << NBITSMINOR32) | minor);
627 #else
628 	return (dev);
629 #endif
630 }
631 
632 static void
633 zfs_znode_dmu_init(zfsvfs_t *zfsvfs, znode_t *zp, dmu_buf_t *db)
634 {
635 	znode_t		*nzp;
636 
637 	ASSERT(!POINTER_IS_VALID(zp->z_zfsvfs) || (zfsvfs == zp->z_zfsvfs));
638 	ASSERT(MUTEX_HELD(ZFS_OBJ_MUTEX(zfsvfs, zp->z_id)));
639 
640 	mutex_enter(&zp->z_lock);
641 
642 	ASSERT(zp->z_dbuf == NULL);
643 	zp->z_dbuf = db;
644 	nzp = dmu_buf_set_user_ie(db, zp, &zp->z_phys, znode_evict_error);
645 
646 	/*
647 	 * there should be no
648 	 * concurrent zgets on this object.
649 	 */
650 	if (nzp != NULL)
651 		panic("existing znode %p for dbuf %p", (void *)nzp, (void *)db);
652 
653 	/*
654 	 * Slap on VROOT if we are the root znode
655 	 */
656 	if (zp->z_id == zfsvfs->z_root)
657 		ZTOV(zp)->v_flag |= VROOT;
658 
659 	mutex_exit(&zp->z_lock);
660 	vn_exists(ZTOV(zp));
661 }
662 
663 void
664 zfs_znode_dmu_fini(znode_t *zp)
665 {
666 	dmu_buf_t *db = zp->z_dbuf;
667 	ASSERT(MUTEX_HELD(ZFS_OBJ_MUTEX(zp->z_zfsvfs, zp->z_id)) ||
668 	    zp->z_unlinked ||
669 	    RW_WRITE_HELD(&zp->z_zfsvfs->z_teardown_inactive_lock));
670 	ASSERT(zp->z_dbuf != NULL);
671 	zp->z_dbuf = NULL;
672 	VERIFY(zp == dmu_buf_update_user(db, zp, NULL, NULL, NULL));
673 	dmu_buf_rele(db, NULL);
674 }
675 
676 /*
677  * Construct a new znode/vnode and intialize.
678  *
679  * This does not do a call to dmu_set_user() that is
680  * up to the caller to do, in case you don't want to
681  * return the znode
682  */
683 static znode_t *
684 zfs_znode_alloc(zfsvfs_t *zfsvfs, dmu_buf_t *db, int blksz)
685 {
686 	znode_t	*zp;
687 	vnode_t *vp;
688 
689 	zp = kmem_cache_alloc(znode_cache, KM_SLEEP);
690 
691 	ASSERT(zp->z_dirlocks == NULL);
692 	ASSERT(zp->z_dbuf == NULL);
693 	ASSERT(!POINTER_IS_VALID(zp->z_zfsvfs));
694 
695 	/*
696 	 * Defer setting z_zfsvfs until the znode is ready to be a candidate for
697 	 * the zfs_znode_move() callback.
698 	 */
699 	zp->z_phys = NULL;
700 	zp->z_unlinked = 0;
701 	zp->z_atime_dirty = 0;
702 	zp->z_mapcnt = 0;
703 	zp->z_last_itx = 0;
704 	zp->z_id = db->db_object;
705 	zp->z_blksz = blksz;
706 	zp->z_seq = 0x7A4653;
707 	zp->z_sync_cnt = 0;
708 
709 	vp = ZTOV(zp);
710 	vn_reinit(vp);
711 
712 	zfs_znode_dmu_init(zfsvfs, zp, db);
713 
714 	zp->z_gen = zp->z_phys->zp_gen;
715 
716 	vp->v_vfsp = zfsvfs->z_parent->z_vfs;
717 	vp->v_type = IFTOVT((mode_t)zp->z_phys->zp_mode);
718 
719 	switch (vp->v_type) {
720 	case VDIR:
721 		if (zp->z_phys->zp_flags & ZFS_XATTR) {
722 			vn_setops(vp, zfs_xdvnodeops);
723 			vp->v_flag |= V_XATTRDIR;
724 		} else {
725 			vn_setops(vp, zfs_dvnodeops);
726 		}
727 		zp->z_zn_prefetch = B_TRUE; /* z_prefetch default is enabled */
728 		break;
729 	case VBLK:
730 	case VCHR:
731 		vp->v_rdev = zfs_cmpldev(zp->z_phys->zp_rdev);
732 		/*FALLTHROUGH*/
733 	case VFIFO:
734 	case VSOCK:
735 	case VDOOR:
736 		vn_setops(vp, zfs_fvnodeops);
737 		break;
738 	case VREG:
739 		vp->v_flag |= VMODSORT;
740 		if (zp->z_phys->zp_parent == zfsvfs->z_shares_dir)
741 			vn_setops(vp, zfs_sharevnodeops);
742 		else
743 			vn_setops(vp, zfs_fvnodeops);
744 		break;
745 	case VLNK:
746 		vn_setops(vp, zfs_symvnodeops);
747 		break;
748 	default:
749 		vn_setops(vp, zfs_evnodeops);
750 		break;
751 	}
752 
753 	mutex_enter(&zfsvfs->z_znodes_lock);
754 	list_insert_tail(&zfsvfs->z_all_znodes, zp);
755 	membar_producer();
756 	/*
757 	 * Everything else must be valid before assigning z_zfsvfs makes the
758 	 * znode eligible for zfs_znode_move().
759 	 */
760 	zp->z_zfsvfs = zfsvfs;
761 	mutex_exit(&zfsvfs->z_znodes_lock);
762 
763 	VFS_HOLD(zfsvfs->z_vfs);
764 	return (zp);
765 }
766 
767 /*
768  * Create a new DMU object to hold a zfs znode.
769  *
770  *	IN:	dzp	- parent directory for new znode
771  *		vap	- file attributes for new znode
772  *		tx	- dmu transaction id for zap operations
773  *		cr	- credentials of caller
774  *		flag	- flags:
775  *			  IS_ROOT_NODE	- new object will be root
776  *			  IS_XATTR	- new object is an attribute
777  *			  IS_REPLAY	- intent log replay
778  *		bonuslen - length of bonus buffer
779  *		setaclp  - File/Dir initial ACL
780  *		fuidp	 - Tracks fuid allocation.
781  *
782  *	OUT:	zpp	- allocated znode
783  *
784  */
785 void
786 zfs_mknode(znode_t *dzp, vattr_t *vap, dmu_tx_t *tx, cred_t *cr,
787     uint_t flag, znode_t **zpp, int bonuslen, zfs_acl_ids_t *acl_ids)
788 {
789 	dmu_buf_t	*db;
790 	znode_phys_t	*pzp;
791 	zfsvfs_t	*zfsvfs = dzp->z_zfsvfs;
792 	timestruc_t	now;
793 	uint64_t	gen, obj;
794 	int		err;
795 
796 	ASSERT(vap && (vap->va_mask & (AT_TYPE|AT_MODE)) == (AT_TYPE|AT_MODE));
797 
798 	if (zfsvfs->z_replay) {
799 		obj = vap->va_nodeid;
800 		flag |= IS_REPLAY;
801 		now = vap->va_ctime;		/* see zfs_replay_create() */
802 		gen = vap->va_nblocks;		/* ditto */
803 	} else {
804 		obj = 0;
805 		gethrestime(&now);
806 		gen = dmu_tx_get_txg(tx);
807 	}
808 
809 	/*
810 	 * Create a new DMU object.
811 	 */
812 	/*
813 	 * There's currently no mechanism for pre-reading the blocks that will
814 	 * be to needed allocate a new object, so we accept the small chance
815 	 * that there will be an i/o error and we will fail one of the
816 	 * assertions below.
817 	 */
818 	if (vap->va_type == VDIR) {
819 		if (flag & IS_REPLAY) {
820 			err = zap_create_claim_norm(zfsvfs->z_os, obj,
821 			    zfsvfs->z_norm, DMU_OT_DIRECTORY_CONTENTS,
822 			    DMU_OT_ZNODE, sizeof (znode_phys_t) + bonuslen, tx);
823 			ASSERT3U(err, ==, 0);
824 		} else {
825 			obj = zap_create_norm(zfsvfs->z_os,
826 			    zfsvfs->z_norm, DMU_OT_DIRECTORY_CONTENTS,
827 			    DMU_OT_ZNODE, sizeof (znode_phys_t) + bonuslen, tx);
828 		}
829 	} else {
830 		if (flag & IS_REPLAY) {
831 			err = dmu_object_claim(zfsvfs->z_os, obj,
832 			    DMU_OT_PLAIN_FILE_CONTENTS, 0,
833 			    DMU_OT_ZNODE, sizeof (znode_phys_t) + bonuslen, tx);
834 			ASSERT3U(err, ==, 0);
835 		} else {
836 			obj = dmu_object_alloc(zfsvfs->z_os,
837 			    DMU_OT_PLAIN_FILE_CONTENTS, 0,
838 			    DMU_OT_ZNODE, sizeof (znode_phys_t) + bonuslen, tx);
839 		}
840 	}
841 	VERIFY(0 == dmu_bonus_hold(zfsvfs->z_os, obj, NULL, &db));
842 	dmu_buf_will_dirty(db, tx);
843 
844 	/*
845 	 * Initialize the znode physical data to zero.
846 	 */
847 	ASSERT(db->db_size >= sizeof (znode_phys_t));
848 	bzero(db->db_data, db->db_size);
849 	pzp = db->db_data;
850 
851 	/*
852 	 * If this is the root, fix up the half-initialized parent pointer
853 	 * to reference the just-allocated physical data area.
854 	 */
855 	if (flag & IS_ROOT_NODE) {
856 		dzp->z_dbuf = db;
857 		dzp->z_phys = pzp;
858 		dzp->z_id = obj;
859 	}
860 
861 	/*
862 	 * If parent is an xattr, so am I.
863 	 */
864 	if (dzp->z_phys->zp_flags & ZFS_XATTR)
865 		flag |= IS_XATTR;
866 
867 	if (vap->va_type == VBLK || vap->va_type == VCHR) {
868 		pzp->zp_rdev = zfs_expldev(vap->va_rdev);
869 	}
870 
871 	if (zfsvfs->z_use_fuids)
872 		pzp->zp_flags = ZFS_ARCHIVE | ZFS_AV_MODIFIED;
873 
874 	if (vap->va_type == VDIR) {
875 		pzp->zp_size = 2;		/* contents ("." and "..") */
876 		pzp->zp_links = (flag & (IS_ROOT_NODE | IS_XATTR)) ? 2 : 1;
877 	}
878 
879 	pzp->zp_parent = dzp->z_id;
880 	if (flag & IS_XATTR)
881 		pzp->zp_flags |= ZFS_XATTR;
882 
883 	pzp->zp_gen = gen;
884 
885 	ZFS_TIME_ENCODE(&now, pzp->zp_crtime);
886 	ZFS_TIME_ENCODE(&now, pzp->zp_ctime);
887 
888 	if (vap->va_mask & AT_ATIME) {
889 		ZFS_TIME_ENCODE(&vap->va_atime, pzp->zp_atime);
890 	} else {
891 		ZFS_TIME_ENCODE(&now, pzp->zp_atime);
892 	}
893 
894 	if (vap->va_mask & AT_MTIME) {
895 		ZFS_TIME_ENCODE(&vap->va_mtime, pzp->zp_mtime);
896 	} else {
897 		ZFS_TIME_ENCODE(&now, pzp->zp_mtime);
898 	}
899 
900 	pzp->zp_mode = MAKEIMODE(vap->va_type, vap->va_mode);
901 	if (!(flag & IS_ROOT_NODE)) {
902 		ZFS_OBJ_HOLD_ENTER(zfsvfs, obj);
903 		*zpp = zfs_znode_alloc(zfsvfs, db, 0);
904 		ZFS_OBJ_HOLD_EXIT(zfsvfs, obj);
905 	} else {
906 		/*
907 		 * If we are creating the root node, the "parent" we
908 		 * passed in is the znode for the root.
909 		 */
910 		*zpp = dzp;
911 	}
912 	pzp->zp_uid = acl_ids->z_fuid;
913 	pzp->zp_gid = acl_ids->z_fgid;
914 	pzp->zp_mode = acl_ids->z_mode;
915 	VERIFY(0 == zfs_aclset_common(*zpp, acl_ids->z_aclp, cr, tx));
916 	if (vap->va_mask & AT_XVATTR)
917 		zfs_xvattr_set(*zpp, (xvattr_t *)vap);
918 }
919 
920 void
921 zfs_xvattr_set(znode_t *zp, xvattr_t *xvap)
922 {
923 	xoptattr_t *xoap;
924 
925 	xoap = xva_getxoptattr(xvap);
926 	ASSERT(xoap);
927 
928 	if (XVA_ISSET_REQ(xvap, XAT_CREATETIME)) {
929 		ZFS_TIME_ENCODE(&xoap->xoa_createtime, zp->z_phys->zp_crtime);
930 		XVA_SET_RTN(xvap, XAT_CREATETIME);
931 	}
932 	if (XVA_ISSET_REQ(xvap, XAT_READONLY)) {
933 		ZFS_ATTR_SET(zp, ZFS_READONLY, xoap->xoa_readonly);
934 		XVA_SET_RTN(xvap, XAT_READONLY);
935 	}
936 	if (XVA_ISSET_REQ(xvap, XAT_HIDDEN)) {
937 		ZFS_ATTR_SET(zp, ZFS_HIDDEN, xoap->xoa_hidden);
938 		XVA_SET_RTN(xvap, XAT_HIDDEN);
939 	}
940 	if (XVA_ISSET_REQ(xvap, XAT_SYSTEM)) {
941 		ZFS_ATTR_SET(zp, ZFS_SYSTEM, xoap->xoa_system);
942 		XVA_SET_RTN(xvap, XAT_SYSTEM);
943 	}
944 	if (XVA_ISSET_REQ(xvap, XAT_ARCHIVE)) {
945 		ZFS_ATTR_SET(zp, ZFS_ARCHIVE, xoap->xoa_archive);
946 		XVA_SET_RTN(xvap, XAT_ARCHIVE);
947 	}
948 	if (XVA_ISSET_REQ(xvap, XAT_IMMUTABLE)) {
949 		ZFS_ATTR_SET(zp, ZFS_IMMUTABLE, xoap->xoa_immutable);
950 		XVA_SET_RTN(xvap, XAT_IMMUTABLE);
951 	}
952 	if (XVA_ISSET_REQ(xvap, XAT_NOUNLINK)) {
953 		ZFS_ATTR_SET(zp, ZFS_NOUNLINK, xoap->xoa_nounlink);
954 		XVA_SET_RTN(xvap, XAT_NOUNLINK);
955 	}
956 	if (XVA_ISSET_REQ(xvap, XAT_APPENDONLY)) {
957 		ZFS_ATTR_SET(zp, ZFS_APPENDONLY, xoap->xoa_appendonly);
958 		XVA_SET_RTN(xvap, XAT_APPENDONLY);
959 	}
960 	if (XVA_ISSET_REQ(xvap, XAT_NODUMP)) {
961 		ZFS_ATTR_SET(zp, ZFS_NODUMP, xoap->xoa_nodump);
962 		XVA_SET_RTN(xvap, XAT_NODUMP);
963 	}
964 	if (XVA_ISSET_REQ(xvap, XAT_OPAQUE)) {
965 		ZFS_ATTR_SET(zp, ZFS_OPAQUE, xoap->xoa_opaque);
966 		XVA_SET_RTN(xvap, XAT_OPAQUE);
967 	}
968 	if (XVA_ISSET_REQ(xvap, XAT_AV_QUARANTINED)) {
969 		ZFS_ATTR_SET(zp, ZFS_AV_QUARANTINED,
970 		    xoap->xoa_av_quarantined);
971 		XVA_SET_RTN(xvap, XAT_AV_QUARANTINED);
972 	}
973 	if (XVA_ISSET_REQ(xvap, XAT_AV_MODIFIED)) {
974 		ZFS_ATTR_SET(zp, ZFS_AV_MODIFIED, xoap->xoa_av_modified);
975 		XVA_SET_RTN(xvap, XAT_AV_MODIFIED);
976 	}
977 	if (XVA_ISSET_REQ(xvap, XAT_AV_SCANSTAMP)) {
978 		(void) memcpy(zp->z_phys + 1, xoap->xoa_av_scanstamp,
979 		    sizeof (xoap->xoa_av_scanstamp));
980 		zp->z_phys->zp_flags |= ZFS_BONUS_SCANSTAMP;
981 		XVA_SET_RTN(xvap, XAT_AV_SCANSTAMP);
982 	}
983 }
984 
985 int
986 zfs_zget(zfsvfs_t *zfsvfs, uint64_t obj_num, znode_t **zpp)
987 {
988 	dmu_object_info_t doi;
989 	dmu_buf_t	*db;
990 	znode_t		*zp;
991 	int err;
992 
993 	*zpp = NULL;
994 
995 	ZFS_OBJ_HOLD_ENTER(zfsvfs, obj_num);
996 
997 	err = dmu_bonus_hold(zfsvfs->z_os, obj_num, NULL, &db);
998 	if (err) {
999 		ZFS_OBJ_HOLD_EXIT(zfsvfs, obj_num);
1000 		return (err);
1001 	}
1002 
1003 	dmu_object_info_from_db(db, &doi);
1004 	if (doi.doi_bonus_type != DMU_OT_ZNODE ||
1005 	    doi.doi_bonus_size < sizeof (znode_phys_t)) {
1006 		dmu_buf_rele(db, NULL);
1007 		ZFS_OBJ_HOLD_EXIT(zfsvfs, obj_num);
1008 		return (EINVAL);
1009 	}
1010 
1011 	zp = dmu_buf_get_user(db);
1012 	if (zp != NULL) {
1013 		mutex_enter(&zp->z_lock);
1014 
1015 		/*
1016 		 * Since we do immediate eviction of the z_dbuf, we
1017 		 * should never find a dbuf with a znode that doesn't
1018 		 * know about the dbuf.
1019 		 */
1020 		ASSERT3P(zp->z_dbuf, ==, db);
1021 		ASSERT3U(zp->z_id, ==, obj_num);
1022 		if (zp->z_unlinked) {
1023 			err = ENOENT;
1024 		} else {
1025 			VN_HOLD(ZTOV(zp));
1026 			*zpp = zp;
1027 			err = 0;
1028 		}
1029 		dmu_buf_rele(db, NULL);
1030 		mutex_exit(&zp->z_lock);
1031 		ZFS_OBJ_HOLD_EXIT(zfsvfs, obj_num);
1032 		return (err);
1033 	}
1034 
1035 	/*
1036 	 * Not found create new znode/vnode
1037 	 */
1038 	zp = zfs_znode_alloc(zfsvfs, db, doi.doi_data_block_size);
1039 	ZFS_OBJ_HOLD_EXIT(zfsvfs, obj_num);
1040 	*zpp = zp;
1041 	return (0);
1042 }
1043 
1044 int
1045 zfs_rezget(znode_t *zp)
1046 {
1047 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
1048 	dmu_object_info_t doi;
1049 	dmu_buf_t *db;
1050 	uint64_t obj_num = zp->z_id;
1051 	int err;
1052 
1053 	ZFS_OBJ_HOLD_ENTER(zfsvfs, obj_num);
1054 
1055 	err = dmu_bonus_hold(zfsvfs->z_os, obj_num, NULL, &db);
1056 	if (err) {
1057 		ZFS_OBJ_HOLD_EXIT(zfsvfs, obj_num);
1058 		return (err);
1059 	}
1060 
1061 	dmu_object_info_from_db(db, &doi);
1062 	if (doi.doi_bonus_type != DMU_OT_ZNODE ||
1063 	    doi.doi_bonus_size < sizeof (znode_phys_t)) {
1064 		dmu_buf_rele(db, NULL);
1065 		ZFS_OBJ_HOLD_EXIT(zfsvfs, obj_num);
1066 		return (EINVAL);
1067 	}
1068 
1069 	if (((znode_phys_t *)db->db_data)->zp_gen != zp->z_gen) {
1070 		dmu_buf_rele(db, NULL);
1071 		ZFS_OBJ_HOLD_EXIT(zfsvfs, obj_num);
1072 		return (EIO);
1073 	}
1074 
1075 	zfs_znode_dmu_init(zfsvfs, zp, db);
1076 	zp->z_unlinked = (zp->z_phys->zp_links == 0);
1077 	zp->z_blksz = doi.doi_data_block_size;
1078 
1079 	ZFS_OBJ_HOLD_EXIT(zfsvfs, obj_num);
1080 
1081 	return (0);
1082 }
1083 
1084 void
1085 zfs_znode_delete(znode_t *zp, dmu_tx_t *tx)
1086 {
1087 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
1088 	objset_t *os = zfsvfs->z_os;
1089 	uint64_t obj = zp->z_id;
1090 	uint64_t acl_obj = zp->z_phys->zp_acl.z_acl_extern_obj;
1091 
1092 	ZFS_OBJ_HOLD_ENTER(zfsvfs, obj);
1093 	if (acl_obj)
1094 		VERIFY(0 == dmu_object_free(os, acl_obj, tx));
1095 	VERIFY(0 == dmu_object_free(os, obj, tx));
1096 	zfs_znode_dmu_fini(zp);
1097 	ZFS_OBJ_HOLD_EXIT(zfsvfs, obj);
1098 	zfs_znode_free(zp);
1099 }
1100 
1101 void
1102 zfs_zinactive(znode_t *zp)
1103 {
1104 	vnode_t	*vp = ZTOV(zp);
1105 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
1106 	uint64_t z_id = zp->z_id;
1107 
1108 	ASSERT(zp->z_dbuf && zp->z_phys);
1109 
1110 	/*
1111 	 * Don't allow a zfs_zget() while were trying to release this znode
1112 	 */
1113 	ZFS_OBJ_HOLD_ENTER(zfsvfs, z_id);
1114 
1115 	mutex_enter(&zp->z_lock);
1116 	mutex_enter(&vp->v_lock);
1117 	vp->v_count--;
1118 	if (vp->v_count > 0 || vn_has_cached_data(vp)) {
1119 		/*
1120 		 * If the hold count is greater than zero, somebody has
1121 		 * obtained a new reference on this znode while we were
1122 		 * processing it here, so we are done.  If we still have
1123 		 * mapped pages then we are also done, since we don't
1124 		 * want to inactivate the znode until the pages get pushed.
1125 		 *
1126 		 * XXX - if vn_has_cached_data(vp) is true, but count == 0,
1127 		 * this seems like it would leave the znode hanging with
1128 		 * no chance to go inactive...
1129 		 */
1130 		mutex_exit(&vp->v_lock);
1131 		mutex_exit(&zp->z_lock);
1132 		ZFS_OBJ_HOLD_EXIT(zfsvfs, z_id);
1133 		return;
1134 	}
1135 	mutex_exit(&vp->v_lock);
1136 
1137 	/*
1138 	 * If this was the last reference to a file with no links,
1139 	 * remove the file from the file system.
1140 	 */
1141 	if (zp->z_unlinked) {
1142 		mutex_exit(&zp->z_lock);
1143 		ZFS_OBJ_HOLD_EXIT(zfsvfs, z_id);
1144 		zfs_rmnode(zp);
1145 		return;
1146 	}
1147 	mutex_exit(&zp->z_lock);
1148 	zfs_znode_dmu_fini(zp);
1149 	ZFS_OBJ_HOLD_EXIT(zfsvfs, z_id);
1150 	zfs_znode_free(zp);
1151 }
1152 
1153 void
1154 zfs_znode_free(znode_t *zp)
1155 {
1156 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
1157 
1158 	vn_invalid(ZTOV(zp));
1159 
1160 	ASSERT(ZTOV(zp)->v_count == 0);
1161 
1162 	mutex_enter(&zfsvfs->z_znodes_lock);
1163 	POINTER_INVALIDATE(&zp->z_zfsvfs);
1164 	list_remove(&zfsvfs->z_all_znodes, zp);
1165 	mutex_exit(&zfsvfs->z_znodes_lock);
1166 
1167 	kmem_cache_free(znode_cache, zp);
1168 
1169 	VFS_RELE(zfsvfs->z_vfs);
1170 }
1171 
1172 void
1173 zfs_time_stamper_locked(znode_t *zp, uint_t flag, dmu_tx_t *tx)
1174 {
1175 	timestruc_t	now;
1176 
1177 	ASSERT(MUTEX_HELD(&zp->z_lock));
1178 
1179 	gethrestime(&now);
1180 
1181 	if (tx) {
1182 		dmu_buf_will_dirty(zp->z_dbuf, tx);
1183 		zp->z_atime_dirty = 0;
1184 		zp->z_seq++;
1185 	} else {
1186 		zp->z_atime_dirty = 1;
1187 	}
1188 
1189 	if (flag & AT_ATIME)
1190 		ZFS_TIME_ENCODE(&now, zp->z_phys->zp_atime);
1191 
1192 	if (flag & AT_MTIME) {
1193 		ZFS_TIME_ENCODE(&now, zp->z_phys->zp_mtime);
1194 		if (zp->z_zfsvfs->z_use_fuids)
1195 			zp->z_phys->zp_flags |= (ZFS_ARCHIVE | ZFS_AV_MODIFIED);
1196 	}
1197 
1198 	if (flag & AT_CTIME) {
1199 		ZFS_TIME_ENCODE(&now, zp->z_phys->zp_ctime);
1200 		if (zp->z_zfsvfs->z_use_fuids)
1201 			zp->z_phys->zp_flags |= ZFS_ARCHIVE;
1202 	}
1203 }
1204 
1205 /*
1206  * Update the requested znode timestamps with the current time.
1207  * If we are in a transaction, then go ahead and mark the znode
1208  * dirty in the transaction so the timestamps will go to disk.
1209  * Otherwise, we will get pushed next time the znode is updated
1210  * in a transaction, or when this znode eventually goes inactive.
1211  *
1212  * Why is this OK?
1213  *  1 - Only the ACCESS time is ever updated outside of a transaction.
1214  *  2 - Multiple consecutive updates will be collapsed into a single
1215  *	znode update by the transaction grouping semantics of the DMU.
1216  */
1217 void
1218 zfs_time_stamper(znode_t *zp, uint_t flag, dmu_tx_t *tx)
1219 {
1220 	mutex_enter(&zp->z_lock);
1221 	zfs_time_stamper_locked(zp, flag, tx);
1222 	mutex_exit(&zp->z_lock);
1223 }
1224 
1225 /*
1226  * Grow the block size for a file.
1227  *
1228  *	IN:	zp	- znode of file to free data in.
1229  *		size	- requested block size
1230  *		tx	- open transaction.
1231  *
1232  * NOTE: this function assumes that the znode is write locked.
1233  */
1234 void
1235 zfs_grow_blocksize(znode_t *zp, uint64_t size, dmu_tx_t *tx)
1236 {
1237 	int		error;
1238 	u_longlong_t	dummy;
1239 
1240 	if (size <= zp->z_blksz)
1241 		return;
1242 	/*
1243 	 * If the file size is already greater than the current blocksize,
1244 	 * we will not grow.  If there is more than one block in a file,
1245 	 * the blocksize cannot change.
1246 	 */
1247 	if (zp->z_blksz && zp->z_phys->zp_size > zp->z_blksz)
1248 		return;
1249 
1250 	error = dmu_object_set_blocksize(zp->z_zfsvfs->z_os, zp->z_id,
1251 	    size, 0, tx);
1252 	if (error == ENOTSUP)
1253 		return;
1254 	ASSERT3U(error, ==, 0);
1255 
1256 	/* What blocksize did we actually get? */
1257 	dmu_object_size_from_db(zp->z_dbuf, &zp->z_blksz, &dummy);
1258 }
1259 
1260 /*
1261  * This is a dummy interface used when pvn_vplist_dirty() should *not*
1262  * be calling back into the fs for a putpage().  E.g.: when truncating
1263  * a file, the pages being "thrown away* don't need to be written out.
1264  */
1265 /* ARGSUSED */
1266 static int
1267 zfs_no_putpage(vnode_t *vp, page_t *pp, u_offset_t *offp, size_t *lenp,
1268     int flags, cred_t *cr)
1269 {
1270 	ASSERT(0);
1271 	return (0);
1272 }
1273 
1274 /*
1275  * Increase the file length
1276  *
1277  *	IN:	zp	- znode of file to free data in.
1278  *		end	- new end-of-file
1279  *
1280  * 	RETURN:	0 if success
1281  *		error code if failure
1282  */
1283 static int
1284 zfs_extend(znode_t *zp, uint64_t end)
1285 {
1286 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
1287 	dmu_tx_t *tx;
1288 	rl_t *rl;
1289 	uint64_t newblksz;
1290 	int error;
1291 
1292 	/*
1293 	 * We will change zp_size, lock the whole file.
1294 	 */
1295 	rl = zfs_range_lock(zp, 0, UINT64_MAX, RL_WRITER);
1296 
1297 	/*
1298 	 * Nothing to do if file already at desired length.
1299 	 */
1300 	if (end <= zp->z_phys->zp_size) {
1301 		zfs_range_unlock(rl);
1302 		return (0);
1303 	}
1304 top:
1305 	tx = dmu_tx_create(zfsvfs->z_os);
1306 	dmu_tx_hold_bonus(tx, zp->z_id);
1307 	if (end > zp->z_blksz &&
1308 	    (!ISP2(zp->z_blksz) || zp->z_blksz < zfsvfs->z_max_blksz)) {
1309 		/*
1310 		 * We are growing the file past the current block size.
1311 		 */
1312 		if (zp->z_blksz > zp->z_zfsvfs->z_max_blksz) {
1313 			ASSERT(!ISP2(zp->z_blksz));
1314 			newblksz = MIN(end, SPA_MAXBLOCKSIZE);
1315 		} else {
1316 			newblksz = MIN(end, zp->z_zfsvfs->z_max_blksz);
1317 		}
1318 		dmu_tx_hold_write(tx, zp->z_id, 0, newblksz);
1319 	} else {
1320 		newblksz = 0;
1321 	}
1322 
1323 	error = dmu_tx_assign(tx, TXG_NOWAIT);
1324 	if (error) {
1325 		if (error == ERESTART) {
1326 			dmu_tx_wait(tx);
1327 			dmu_tx_abort(tx);
1328 			goto top;
1329 		}
1330 		dmu_tx_abort(tx);
1331 		zfs_range_unlock(rl);
1332 		return (error);
1333 	}
1334 	dmu_buf_will_dirty(zp->z_dbuf, tx);
1335 
1336 	if (newblksz)
1337 		zfs_grow_blocksize(zp, newblksz, tx);
1338 
1339 	zp->z_phys->zp_size = end;
1340 
1341 	zfs_range_unlock(rl);
1342 
1343 	dmu_tx_commit(tx);
1344 
1345 	return (0);
1346 }
1347 
1348 /*
1349  * Free space in a file.
1350  *
1351  *	IN:	zp	- znode of file to free data in.
1352  *		off	- start of section to free.
1353  *		len	- length of section to free.
1354  *
1355  * 	RETURN:	0 if success
1356  *		error code if failure
1357  */
1358 static int
1359 zfs_free_range(znode_t *zp, uint64_t off, uint64_t len)
1360 {
1361 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
1362 	rl_t *rl;
1363 	int error;
1364 
1365 	/*
1366 	 * Lock the range being freed.
1367 	 */
1368 	rl = zfs_range_lock(zp, off, len, RL_WRITER);
1369 
1370 	/*
1371 	 * Nothing to do if file already at desired length.
1372 	 */
1373 	if (off >= zp->z_phys->zp_size) {
1374 		zfs_range_unlock(rl);
1375 		return (0);
1376 	}
1377 
1378 	if (off + len > zp->z_phys->zp_size)
1379 		len = zp->z_phys->zp_size - off;
1380 
1381 	error = dmu_free_long_range(zfsvfs->z_os, zp->z_id, off, len);
1382 
1383 	zfs_range_unlock(rl);
1384 
1385 	return (error);
1386 }
1387 
1388 /*
1389  * Truncate a file
1390  *
1391  *	IN:	zp	- znode of file to free data in.
1392  *		end	- new end-of-file.
1393  *
1394  * 	RETURN:	0 if success
1395  *		error code if failure
1396  */
1397 static int
1398 zfs_trunc(znode_t *zp, uint64_t end)
1399 {
1400 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
1401 	vnode_t *vp = ZTOV(zp);
1402 	dmu_tx_t *tx;
1403 	rl_t *rl;
1404 	int error;
1405 
1406 	/*
1407 	 * We will change zp_size, lock the whole file.
1408 	 */
1409 	rl = zfs_range_lock(zp, 0, UINT64_MAX, RL_WRITER);
1410 
1411 	/*
1412 	 * Nothing to do if file already at desired length.
1413 	 */
1414 	if (end >= zp->z_phys->zp_size) {
1415 		zfs_range_unlock(rl);
1416 		return (0);
1417 	}
1418 
1419 	error = dmu_free_long_range(zfsvfs->z_os, zp->z_id, end,  -1);
1420 	if (error) {
1421 		zfs_range_unlock(rl);
1422 		return (error);
1423 	}
1424 top:
1425 	tx = dmu_tx_create(zfsvfs->z_os);
1426 	dmu_tx_hold_bonus(tx, zp->z_id);
1427 	error = dmu_tx_assign(tx, TXG_NOWAIT);
1428 	if (error) {
1429 		if (error == ERESTART) {
1430 			dmu_tx_wait(tx);
1431 			dmu_tx_abort(tx);
1432 			goto top;
1433 		}
1434 		dmu_tx_abort(tx);
1435 		zfs_range_unlock(rl);
1436 		return (error);
1437 	}
1438 	dmu_buf_will_dirty(zp->z_dbuf, tx);
1439 
1440 	zp->z_phys->zp_size = end;
1441 
1442 	dmu_tx_commit(tx);
1443 
1444 	/*
1445 	 * Clear any mapped pages in the truncated region.  This has to
1446 	 * happen outside of the transaction to avoid the possibility of
1447 	 * a deadlock with someone trying to push a page that we are
1448 	 * about to invalidate.
1449 	 */
1450 	if (vn_has_cached_data(vp)) {
1451 		page_t *pp;
1452 		uint64_t start = end & PAGEMASK;
1453 		int poff = end & PAGEOFFSET;
1454 
1455 		if (poff != 0 && (pp = page_lookup(vp, start, SE_SHARED))) {
1456 			/*
1457 			 * We need to zero a partial page.
1458 			 */
1459 			pagezero(pp, poff, PAGESIZE - poff);
1460 			start += PAGESIZE;
1461 			page_unlock(pp);
1462 		}
1463 		error = pvn_vplist_dirty(vp, start, zfs_no_putpage,
1464 		    B_INVAL | B_TRUNC, NULL);
1465 		ASSERT(error == 0);
1466 	}
1467 
1468 	zfs_range_unlock(rl);
1469 
1470 	return (0);
1471 }
1472 
1473 /*
1474  * Free space in a file
1475  *
1476  *	IN:	zp	- znode of file to free data in.
1477  *		off	- start of range
1478  *		len	- end of range (0 => EOF)
1479  *		flag	- current file open mode flags.
1480  *		log	- TRUE if this action should be logged
1481  *
1482  * 	RETURN:	0 if success
1483  *		error code if failure
1484  */
1485 int
1486 zfs_freesp(znode_t *zp, uint64_t off, uint64_t len, int flag, boolean_t log)
1487 {
1488 	vnode_t *vp = ZTOV(zp);
1489 	dmu_tx_t *tx;
1490 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
1491 	zilog_t *zilog = zfsvfs->z_log;
1492 	int error;
1493 
1494 	if (off > zp->z_phys->zp_size) {
1495 		error =  zfs_extend(zp, off+len);
1496 		if (error == 0 && log)
1497 			goto log;
1498 		else
1499 			return (error);
1500 	}
1501 
1502 	/*
1503 	 * Check for any locks in the region to be freed.
1504 	 */
1505 	if (MANDLOCK(vp, (mode_t)zp->z_phys->zp_mode)) {
1506 		uint64_t length = (len ? len : zp->z_phys->zp_size - off);
1507 		if (error = chklock(vp, FWRITE, off, length, flag, NULL))
1508 			return (error);
1509 	}
1510 
1511 	if (len == 0) {
1512 		error = zfs_trunc(zp, off);
1513 	} else {
1514 		if ((error = zfs_free_range(zp, off, len)) == 0 &&
1515 		    off + len > zp->z_phys->zp_size)
1516 			error = zfs_extend(zp, off+len);
1517 	}
1518 	if (error || !log)
1519 		return (error);
1520 log:
1521 	tx = dmu_tx_create(zfsvfs->z_os);
1522 	dmu_tx_hold_bonus(tx, zp->z_id);
1523 	error = dmu_tx_assign(tx, TXG_NOWAIT);
1524 	if (error) {
1525 		if (error == ERESTART) {
1526 			dmu_tx_wait(tx);
1527 			dmu_tx_abort(tx);
1528 			goto log;
1529 		}
1530 		dmu_tx_abort(tx);
1531 		return (error);
1532 	}
1533 
1534 	zfs_time_stamper(zp, CONTENT_MODIFIED, tx);
1535 	zfs_log_truncate(zilog, tx, TX_TRUNCATE, zp, off, len);
1536 
1537 	dmu_tx_commit(tx);
1538 	return (0);
1539 }
1540 
1541 void
1542 zfs_create_fs(objset_t *os, cred_t *cr, nvlist_t *zplprops, dmu_tx_t *tx)
1543 {
1544 	zfsvfs_t	zfsvfs;
1545 	uint64_t	moid, doid, version;
1546 	uint64_t	sense = ZFS_CASE_SENSITIVE;
1547 	uint64_t	norm = 0;
1548 	nvpair_t	*elem;
1549 	int		error;
1550 	znode_t		*rootzp = NULL;
1551 	vnode_t		*vp;
1552 	vattr_t		vattr;
1553 	znode_t		*zp;
1554 	zfs_acl_ids_t	acl_ids;
1555 
1556 	/*
1557 	 * First attempt to create master node.
1558 	 */
1559 	/*
1560 	 * In an empty objset, there are no blocks to read and thus
1561 	 * there can be no i/o errors (which we assert below).
1562 	 */
1563 	moid = MASTER_NODE_OBJ;
1564 	error = zap_create_claim(os, moid, DMU_OT_MASTER_NODE,
1565 	    DMU_OT_NONE, 0, tx);
1566 	ASSERT(error == 0);
1567 
1568 	/*
1569 	 * Set starting attributes.
1570 	 */
1571 	if (spa_version(dmu_objset_spa(os)) >= SPA_VERSION_FUID)
1572 		version = ZPL_VERSION;
1573 	else
1574 		version = ZPL_VERSION_FUID - 1;
1575 	error = zap_update(os, moid, ZPL_VERSION_STR,
1576 	    8, 1, &version, tx);
1577 	elem = NULL;
1578 	while ((elem = nvlist_next_nvpair(zplprops, elem)) != NULL) {
1579 		/* For the moment we expect all zpl props to be uint64_ts */
1580 		uint64_t val;
1581 		char *name;
1582 
1583 		ASSERT(nvpair_type(elem) == DATA_TYPE_UINT64);
1584 		VERIFY(nvpair_value_uint64(elem, &val) == 0);
1585 		name = nvpair_name(elem);
1586 		if (strcmp(name, zfs_prop_to_name(ZFS_PROP_VERSION)) == 0) {
1587 			version = val;
1588 			error = zap_update(os, moid, ZPL_VERSION_STR,
1589 			    8, 1, &version, tx);
1590 		} else {
1591 			error = zap_update(os, moid, name, 8, 1, &val, tx);
1592 		}
1593 		ASSERT(error == 0);
1594 		if (strcmp(name, zfs_prop_to_name(ZFS_PROP_NORMALIZE)) == 0)
1595 			norm = val;
1596 		else if (strcmp(name, zfs_prop_to_name(ZFS_PROP_CASE)) == 0)
1597 			sense = val;
1598 	}
1599 	ASSERT(version != 0);
1600 
1601 	/*
1602 	 * Create a delete queue.
1603 	 */
1604 	doid = zap_create(os, DMU_OT_UNLINKED_SET, DMU_OT_NONE, 0, tx);
1605 
1606 	error = zap_add(os, moid, ZFS_UNLINKED_SET, 8, 1, &doid, tx);
1607 	ASSERT(error == 0);
1608 
1609 	/*
1610 	 * Create root znode.  Create minimal znode/vnode/zfsvfs
1611 	 * to allow zfs_mknode to work.
1612 	 */
1613 	vattr.va_mask = AT_MODE|AT_UID|AT_GID|AT_TYPE;
1614 	vattr.va_type = VDIR;
1615 	vattr.va_mode = S_IFDIR|0755;
1616 	vattr.va_uid = crgetuid(cr);
1617 	vattr.va_gid = crgetgid(cr);
1618 
1619 	rootzp = kmem_cache_alloc(znode_cache, KM_SLEEP);
1620 	rootzp->z_unlinked = 0;
1621 	rootzp->z_atime_dirty = 0;
1622 
1623 	vp = ZTOV(rootzp);
1624 	vn_reinit(vp);
1625 	vp->v_type = VDIR;
1626 
1627 	bzero(&zfsvfs, sizeof (zfsvfs_t));
1628 
1629 	zfsvfs.z_os = os;
1630 	zfsvfs.z_parent = &zfsvfs;
1631 	zfsvfs.z_version = version;
1632 	zfsvfs.z_use_fuids = USE_FUIDS(version, os);
1633 	zfsvfs.z_norm = norm;
1634 	/*
1635 	 * Fold case on file systems that are always or sometimes case
1636 	 * insensitive.
1637 	 */
1638 	if (sense == ZFS_CASE_INSENSITIVE || sense == ZFS_CASE_MIXED)
1639 		zfsvfs.z_norm |= U8_TEXTPREP_TOUPPER;
1640 
1641 	mutex_init(&zfsvfs.z_znodes_lock, NULL, MUTEX_DEFAULT, NULL);
1642 	list_create(&zfsvfs.z_all_znodes, sizeof (znode_t),
1643 	    offsetof(znode_t, z_link_node));
1644 
1645 	ASSERT(!POINTER_IS_VALID(rootzp->z_zfsvfs));
1646 	rootzp->z_zfsvfs = &zfsvfs;
1647 	VERIFY(0 == zfs_acl_ids_create(rootzp, IS_ROOT_NODE, &vattr,
1648 	    cr, NULL, &acl_ids));
1649 	zfs_mknode(rootzp, &vattr, tx, cr, IS_ROOT_NODE, &zp, 0, &acl_ids);
1650 	ASSERT3P(zp, ==, rootzp);
1651 	ASSERT(!vn_in_dnlc(ZTOV(rootzp))); /* not valid to move */
1652 	error = zap_add(os, moid, ZFS_ROOT_OBJ, 8, 1, &rootzp->z_id, tx);
1653 	ASSERT(error == 0);
1654 	zfs_acl_ids_free(&acl_ids);
1655 	POINTER_INVALIDATE(&rootzp->z_zfsvfs);
1656 
1657 	ZTOV(rootzp)->v_count = 0;
1658 	dmu_buf_rele(rootzp->z_dbuf, NULL);
1659 	rootzp->z_dbuf = NULL;
1660 	kmem_cache_free(znode_cache, rootzp);
1661 
1662 	/*
1663 	 * Create shares directory
1664 	 */
1665 
1666 	error = zfs_create_share_dir(&zfsvfs, tx);
1667 
1668 	ASSERT(error == 0);
1669 }
1670 
1671 #endif /* _KERNEL */
1672 /*
1673  * Given an object number, return its parent object number and whether
1674  * or not the object is an extended attribute directory.
1675  */
1676 static int
1677 zfs_obj_to_pobj(objset_t *osp, uint64_t obj, uint64_t *pobjp, int *is_xattrdir)
1678 {
1679 	dmu_buf_t *db;
1680 	dmu_object_info_t doi;
1681 	znode_phys_t *zp;
1682 	int error;
1683 
1684 	if ((error = dmu_bonus_hold(osp, obj, FTAG, &db)) != 0)
1685 		return (error);
1686 
1687 	dmu_object_info_from_db(db, &doi);
1688 	if (doi.doi_bonus_type != DMU_OT_ZNODE ||
1689 	    doi.doi_bonus_size < sizeof (znode_phys_t)) {
1690 		dmu_buf_rele(db, FTAG);
1691 		return (EINVAL);
1692 	}
1693 
1694 	zp = db->db_data;
1695 	*pobjp = zp->zp_parent;
1696 	*is_xattrdir = ((zp->zp_flags & ZFS_XATTR) != 0) &&
1697 	    S_ISDIR(zp->zp_mode);
1698 	dmu_buf_rele(db, FTAG);
1699 
1700 	return (0);
1701 }
1702 
1703 int
1704 zfs_obj_to_path(objset_t *osp, uint64_t obj, char *buf, int len)
1705 {
1706 	char *path = buf + len - 1;
1707 	int error;
1708 
1709 	*path = '\0';
1710 
1711 	for (;;) {
1712 		uint64_t pobj;
1713 		char component[MAXNAMELEN + 2];
1714 		size_t complen;
1715 		int is_xattrdir;
1716 
1717 		if ((error = zfs_obj_to_pobj(osp, obj, &pobj,
1718 		    &is_xattrdir)) != 0)
1719 			break;
1720 
1721 		if (pobj == obj) {
1722 			if (path[0] != '/')
1723 				*--path = '/';
1724 			break;
1725 		}
1726 
1727 		component[0] = '/';
1728 		if (is_xattrdir) {
1729 			(void) sprintf(component + 1, "<xattrdir>");
1730 		} else {
1731 			error = zap_value_search(osp, pobj, obj,
1732 			    ZFS_DIRENT_OBJ(-1ULL), component + 1);
1733 			if (error != 0)
1734 				break;
1735 		}
1736 
1737 		complen = strlen(component);
1738 		path -= complen;
1739 		ASSERT(path >= buf);
1740 		bcopy(component, path, complen);
1741 		obj = pobj;
1742 	}
1743 
1744 	if (error == 0)
1745 		(void) memmove(buf, path, buf + len - path);
1746 	return (error);
1747 }
1748