zfs_znode.c revision 240955
1295016Sjkim/*
2110010Smarkm * CDDL HEADER START
3110010Smarkm *
4160819Ssimon * The contents of this file are subject to the terms of the
5110010Smarkm * Common Development and Distribution License (the "License").
6110010Smarkm * You may not use this file except in compliance with the License.
7110010Smarkm *
8110010Smarkm * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9110010Smarkm * or http://www.opensolaris.org/os/licensing.
10110010Smarkm * See the License for the specific language governing permissions
11110010Smarkm * and limitations under the License.
12110010Smarkm *
13110010Smarkm * When distributing Covered Code, include this CDDL HEADER in each
14110010Smarkm * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15110010Smarkm * If applicable, add the following below this CDDL HEADER, with the
16110010Smarkm * fields enclosed by brackets "[]" replaced with your own identifying
17110010Smarkm * information: Portions Copyright [yyyy] [name of copyright owner]
18110010Smarkm *
19110010Smarkm * CDDL HEADER END
20215698Ssimon */
21215698Ssimon/*
22215698Ssimon * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
23215698Ssimon * Copyright (c) 2012 by Delphix. All rights reserved.
24215698Ssimon */
25110010Smarkm
26110010Smarkm/* Portions Copyright 2007 Jeremy Teo */
27110010Smarkm/* Portions Copyright 2011 Martin Matuska <mm@FreeBSD.org> */
28110010Smarkm
29110010Smarkm#ifdef _KERNEL
30110010Smarkm#include <sys/types.h>
31110010Smarkm#include <sys/param.h>
32110010Smarkm#include <sys/time.h>
33110010Smarkm#include <sys/systm.h>
34110010Smarkm#include <sys/sysmacros.h>
35110010Smarkm#include <sys/resource.h>
36110010Smarkm#include <sys/mntent.h>
37110010Smarkm#include <sys/u8_textprep.h>
38110010Smarkm#include <sys/dsl_dataset.h>
39110010Smarkm#include <sys/vfs.h>
40110010Smarkm#include <sys/vnode.h>
41276864Sjkim#include <sys/file.h>
42276864Sjkim#include <sys/kmem.h>
43110010Smarkm#include <sys/errno.h>
44110010Smarkm#include <sys/unistd.h>
45215698Ssimon#include <sys/atomic.h>
46215698Ssimon#include <sys/zfs_dir.h>
47215698Ssimon#include <sys/zfs_acl.h>
48215698Ssimon#include <sys/zfs_ioctl.h>
49160819Ssimon#include <sys/zfs_rlock.h>
50215698Ssimon#include <sys/zfs_fuid.h>
51160819Ssimon#include <sys/dnode.h>
52160819Ssimon#include <sys/fs/zfs.h>
53276864Sjkim#include <sys/kidmap.h>
54276864Sjkim#endif /* _KERNEL */
55276864Sjkim
56110010Smarkm#include <sys/dmu.h>
57276864Sjkim#include <sys/refcount.h>
58276864Sjkim#include <sys/stat.h>
59276864Sjkim#include <sys/zap.h>
60276864Sjkim#include <sys/zfs_znode.h>
61276864Sjkim#include <sys/sa.h>
62276864Sjkim#include <sys/zfs_sa.h>
63215698Ssimon#include <sys/zfs_stat.h>
64276864Sjkim#include <sys/refcount.h>
65276864Sjkim
66276864Sjkim#include "zfs_prop.h"
67276864Sjkim#include "zfs_comutil.h"
68276864Sjkim
69215698Ssimon/* Used by fstat(1). */
70276864SjkimSYSCTL_INT(_debug_sizeof, OID_AUTO, znode, CTLFLAG_RD, 0, sizeof(znode_t),
71110010Smarkm    "sizeof(znode_t)");
72110010Smarkm
73110010Smarkm/*
74110010Smarkm * Define ZNODE_STATS to turn on statistic gathering. By default, it is only
75110010Smarkm * turned on when DEBUG is also defined.
76110010Smarkm */
77110010Smarkm#ifdef	DEBUG
78110010Smarkm#define	ZNODE_STATS
79110010Smarkm#endif	/* DEBUG */
80110010Smarkm
81110010Smarkm#ifdef	ZNODE_STATS
82110010Smarkm#define	ZNODE_STAT_ADD(stat)			((stat)++)
83110010Smarkm#else
84110010Smarkm#define	ZNODE_STAT_ADD(stat)			/* nothing */
85110010Smarkm#endif	/* ZNODE_STATS */
86110010Smarkm
87110010Smarkm/*
88110010Smarkm * Functions needed for userland (ie: libzpool) are not put under
89110010Smarkm * #ifdef_KERNEL; the rest of the functions have dependencies
90110010Smarkm * (such as VFS logic) that will not compile easily in userland.
91110010Smarkm */
92110010Smarkm#ifdef _KERNEL
93110010Smarkm/*
94110010Smarkm * Needed to close a small window in zfs_znode_move() that allows the zfsvfs to
95110010Smarkm * be freed before it can be safely accessed.
96110010Smarkm */
97110010Smarkmkrwlock_t zfsvfs_lock;
98110010Smarkm
99110010Smarkmstatic kmem_cache_t *znode_cache = NULL;
100110010Smarkm
101110010Smarkm/*ARGSUSED*/
102110010Smarkmstatic void
103110010Smarkmznode_evict_error(dmu_buf_t *dbuf, void *user_ptr)
104110010Smarkm{
105110010Smarkm	/*
106110010Smarkm	 * We should never drop all dbuf refs without first clearing
107110010Smarkm	 * the eviction callback.
108110010Smarkm	 */
109110010Smarkm	panic("evicting znode %p\n", user_ptr);
110110010Smarkm}
111110010Smarkm
112110010Smarkmextern struct vop_vector zfs_vnodeops;
113110010Smarkmextern struct vop_vector zfs_fifoops;
114110010Smarkmextern struct vop_vector zfs_shareops;
115110010Smarkm
116110010Smarkm/*
117110010Smarkm * XXX: We cannot use this function as a cache constructor, because
118110010Smarkm *      there is one global cache for all file systems and we need
119110010Smarkm *      to pass vfsp here, which is not possible, because argument
120110010Smarkm *      'cdrarg' is defined at kmem_cache_create() time.
121110010Smarkm */
122110010Smarkm/*ARGSUSED*/
123110010Smarkmstatic int
124110010Smarkmzfs_znode_cache_constructor(void *buf, void *arg, int kmflags)
125110010Smarkm{
126110010Smarkm	znode_t *zp = buf;
127110010Smarkm	vnode_t *vp;
128110010Smarkm	vfs_t *vfsp = arg;
129110010Smarkm	int error;
130110010Smarkm
131110010Smarkm	POINTER_INVALIDATE(&zp->z_zfsvfs);
132110010Smarkm	ASSERT(!POINTER_IS_VALID(zp->z_zfsvfs));
133160819Ssimon
134110010Smarkm	if (vfsp != NULL) {
135110010Smarkm		error = getnewvnode("zfs", vfsp, &zfs_vnodeops, &vp);
136296317Sdelphij		if (error != 0 && (kmflags & KM_NOSLEEP))
137215698Ssimon			return (-1);
138215698Ssimon		ASSERT(error == 0);
139215698Ssimon		vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
140215698Ssimon		zp->z_vnode = vp;
141110010Smarkm		vp->v_data = (caddr_t)zp;
142160819Ssimon		VN_LOCK_AREC(vp);
143110010Smarkm		VN_LOCK_ASHARE(vp);
144110010Smarkm	} else {
145110010Smarkm		zp->z_vnode = NULL;
146110010Smarkm	}
147215698Ssimon
148110010Smarkm	list_link_init(&zp->z_link_node);
149110010Smarkm
150110010Smarkm	mutex_init(&zp->z_lock, NULL, MUTEX_DEFAULT, NULL);
151110010Smarkm	rw_init(&zp->z_parent_lock, NULL, RW_DEFAULT, NULL);
152110010Smarkm	rw_init(&zp->z_name_lock, NULL, RW_DEFAULT, NULL);
153110010Smarkm	mutex_init(&zp->z_acl_lock, NULL, MUTEX_DEFAULT, NULL);
154110010Smarkm
155110010Smarkm	mutex_init(&zp->z_range_lock, NULL, MUTEX_DEFAULT, NULL);
156110010Smarkm	avl_create(&zp->z_range_avl, zfs_range_compare,
157110010Smarkm	    sizeof (rl_t), offsetof(rl_t, r_node));
158110010Smarkm
159276864Sjkim	zp->z_dirlocks = NULL;
160160819Ssimon	zp->z_acl_cached = NULL;
161160819Ssimon	zp->z_moved = 0;
162110010Smarkm	return (0);
163110010Smarkm}
164110010Smarkm
165110010Smarkm/*ARGSUSED*/
166110010Smarkmstatic void
167110010Smarkmzfs_znode_cache_destructor(void *buf, void *arg)
168110010Smarkm{
169110010Smarkm	znode_t *zp = buf;
170160819Ssimon
171110010Smarkm	ASSERT(!POINTER_IS_VALID(zp->z_zfsvfs));
172110010Smarkm	ASSERT(ZTOV(zp) == NULL);
173110010Smarkm	vn_free(ZTOV(zp));
174110010Smarkm	ASSERT(!list_link_active(&zp->z_link_node));
175110010Smarkm	mutex_destroy(&zp->z_lock);
176110010Smarkm	rw_destroy(&zp->z_parent_lock);
177237657Sjkim	rw_destroy(&zp->z_name_lock);
178237657Sjkim	mutex_destroy(&zp->z_acl_lock);
179237657Sjkim	avl_destroy(&zp->z_range_avl);
180237657Sjkim	mutex_destroy(&zp->z_range_lock);
181237657Sjkim
182237657Sjkim	ASSERT(zp->z_dirlocks == NULL);
183237657Sjkim	ASSERT(zp->z_acl_cached == NULL);
184237657Sjkim}
185237657Sjkim
186237657Sjkim#ifdef	ZNODE_STATS
187110010Smarkmstatic struct {
188110010Smarkm	uint64_t zms_zfsvfs_invalid;
189110010Smarkm	uint64_t zms_zfsvfs_recheck1;
190160819Ssimon	uint64_t zms_zfsvfs_unmounted;
191110010Smarkm	uint64_t zms_zfsvfs_recheck2;
192110010Smarkm	uint64_t zms_obj_held;
193160819Ssimon	uint64_t zms_vnode_locked;
194110010Smarkm	uint64_t zms_not_only_dnlc;
195110010Smarkm} znode_move_stats;
196110010Smarkm#endif	/* ZNODE_STATS */
197160819Ssimon
198160819Ssimon#ifdef sun
199160819Ssimonstatic void
200160819Ssimonzfs_znode_move_impl(znode_t *ozp, znode_t *nzp)
201{
202	vnode_t *vp;
203
204	/* Copy fields. */
205	nzp->z_zfsvfs = ozp->z_zfsvfs;
206
207	/* Swap vnodes. */
208	vp = nzp->z_vnode;
209	nzp->z_vnode = ozp->z_vnode;
210	ozp->z_vnode = vp; /* let destructor free the overwritten vnode */
211	ZTOV(ozp)->v_data = ozp;
212	ZTOV(nzp)->v_data = nzp;
213
214	nzp->z_id = ozp->z_id;
215	ASSERT(ozp->z_dirlocks == NULL); /* znode not in use */
216	ASSERT(avl_numnodes(&ozp->z_range_avl) == 0);
217	nzp->z_unlinked = ozp->z_unlinked;
218	nzp->z_atime_dirty = ozp->z_atime_dirty;
219	nzp->z_zn_prefetch = ozp->z_zn_prefetch;
220	nzp->z_blksz = ozp->z_blksz;
221	nzp->z_seq = ozp->z_seq;
222	nzp->z_mapcnt = ozp->z_mapcnt;
223	nzp->z_gen = ozp->z_gen;
224	nzp->z_sync_cnt = ozp->z_sync_cnt;
225	nzp->z_is_sa = ozp->z_is_sa;
226	nzp->z_sa_hdl = ozp->z_sa_hdl;
227	bcopy(ozp->z_atime, nzp->z_atime, sizeof (uint64_t) * 2);
228	nzp->z_links = ozp->z_links;
229	nzp->z_size = ozp->z_size;
230	nzp->z_pflags = ozp->z_pflags;
231	nzp->z_uid = ozp->z_uid;
232	nzp->z_gid = ozp->z_gid;
233	nzp->z_mode = ozp->z_mode;
234
235	/*
236	 * Since this is just an idle znode and kmem is already dealing with
237	 * memory pressure, release any cached ACL.
238	 */
239	if (ozp->z_acl_cached) {
240		zfs_acl_free(ozp->z_acl_cached);
241		ozp->z_acl_cached = NULL;
242	}
243
244	sa_set_userp(nzp->z_sa_hdl, nzp);
245
246	/*
247	 * Invalidate the original znode by clearing fields that provide a
248	 * pointer back to the znode. Set the low bit of the vfs pointer to
249	 * ensure that zfs_znode_move() recognizes the znode as invalid in any
250	 * subsequent callback.
251	 */
252	ozp->z_sa_hdl = NULL;
253	POINTER_INVALIDATE(&ozp->z_zfsvfs);
254
255	/*
256	 * Mark the znode.
257	 */
258	nzp->z_moved = 1;
259	ozp->z_moved = (uint8_t)-1;
260}
261
262/*ARGSUSED*/
263static kmem_cbrc_t
264zfs_znode_move(void *buf, void *newbuf, size_t size, void *arg)
265{
266	znode_t *ozp = buf, *nzp = newbuf;
267	zfsvfs_t *zfsvfs;
268	vnode_t *vp;
269
270	/*
271	 * The znode is on the file system's list of known znodes if the vfs
272	 * pointer is valid. We set the low bit of the vfs pointer when freeing
273	 * the znode to invalidate it, and the memory patterns written by kmem
274	 * (baddcafe and deadbeef) set at least one of the two low bits. A newly
275	 * created znode sets the vfs pointer last of all to indicate that the
276	 * znode is known and in a valid state to be moved by this function.
277	 */
278	zfsvfs = ozp->z_zfsvfs;
279	if (!POINTER_IS_VALID(zfsvfs)) {
280		ZNODE_STAT_ADD(znode_move_stats.zms_zfsvfs_invalid);
281		return (KMEM_CBRC_DONT_KNOW);
282	}
283
284	/*
285	 * Close a small window in which it's possible that the filesystem could
286	 * be unmounted and freed, and zfsvfs, though valid in the previous
287	 * statement, could point to unrelated memory by the time we try to
288	 * prevent the filesystem from being unmounted.
289	 */
290	rw_enter(&zfsvfs_lock, RW_WRITER);
291	if (zfsvfs != ozp->z_zfsvfs) {
292		rw_exit(&zfsvfs_lock);
293		ZNODE_STAT_ADD(znode_move_stats.zms_zfsvfs_recheck1);
294		return (KMEM_CBRC_DONT_KNOW);
295	}
296
297	/*
298	 * If the znode is still valid, then so is the file system. We know that
299	 * no valid file system can be freed while we hold zfsvfs_lock, so we
300	 * can safely ensure that the filesystem is not and will not be
301	 * unmounted. The next statement is equivalent to ZFS_ENTER().
302	 */
303	rrw_enter(&zfsvfs->z_teardown_lock, RW_READER, FTAG);
304	if (zfsvfs->z_unmounted) {
305		ZFS_EXIT(zfsvfs);
306		rw_exit(&zfsvfs_lock);
307		ZNODE_STAT_ADD(znode_move_stats.zms_zfsvfs_unmounted);
308		return (KMEM_CBRC_DONT_KNOW);
309	}
310	rw_exit(&zfsvfs_lock);
311
312	mutex_enter(&zfsvfs->z_znodes_lock);
313	/*
314	 * Recheck the vfs pointer in case the znode was removed just before
315	 * acquiring the lock.
316	 */
317	if (zfsvfs != ozp->z_zfsvfs) {
318		mutex_exit(&zfsvfs->z_znodes_lock);
319		ZFS_EXIT(zfsvfs);
320		ZNODE_STAT_ADD(znode_move_stats.zms_zfsvfs_recheck2);
321		return (KMEM_CBRC_DONT_KNOW);
322	}
323
324	/*
325	 * At this point we know that as long as we hold z_znodes_lock, the
326	 * znode cannot be freed and fields within the znode can be safely
327	 * accessed. Now, prevent a race with zfs_zget().
328	 */
329	if (ZFS_OBJ_HOLD_TRYENTER(zfsvfs, ozp->z_id) == 0) {
330		mutex_exit(&zfsvfs->z_znodes_lock);
331		ZFS_EXIT(zfsvfs);
332		ZNODE_STAT_ADD(znode_move_stats.zms_obj_held);
333		return (KMEM_CBRC_LATER);
334	}
335
336	vp = ZTOV(ozp);
337	if (mutex_tryenter(&vp->v_lock) == 0) {
338		ZFS_OBJ_HOLD_EXIT(zfsvfs, ozp->z_id);
339		mutex_exit(&zfsvfs->z_znodes_lock);
340		ZFS_EXIT(zfsvfs);
341		ZNODE_STAT_ADD(znode_move_stats.zms_vnode_locked);
342		return (KMEM_CBRC_LATER);
343	}
344
345	/* Only move znodes that are referenced _only_ by the DNLC. */
346	if (vp->v_count != 1 || !vn_in_dnlc(vp)) {
347		mutex_exit(&vp->v_lock);
348		ZFS_OBJ_HOLD_EXIT(zfsvfs, ozp->z_id);
349		mutex_exit(&zfsvfs->z_znodes_lock);
350		ZFS_EXIT(zfsvfs);
351		ZNODE_STAT_ADD(znode_move_stats.zms_not_only_dnlc);
352		return (KMEM_CBRC_LATER);
353	}
354
355	/*
356	 * The znode is known and in a valid state to move. We're holding the
357	 * locks needed to execute the critical section.
358	 */
359	zfs_znode_move_impl(ozp, nzp);
360	mutex_exit(&vp->v_lock);
361	ZFS_OBJ_HOLD_EXIT(zfsvfs, ozp->z_id);
362
363	list_link_replace(&ozp->z_link_node, &nzp->z_link_node);
364	mutex_exit(&zfsvfs->z_znodes_lock);
365	ZFS_EXIT(zfsvfs);
366
367	return (KMEM_CBRC_YES);
368}
369#endif /* sun */
370
371void
372zfs_znode_init(void)
373{
374	/*
375	 * Initialize zcache
376	 */
377	rw_init(&zfsvfs_lock, NULL, RW_DEFAULT, NULL);
378	ASSERT(znode_cache == NULL);
379	znode_cache = kmem_cache_create("zfs_znode_cache",
380	    sizeof (znode_t), 0, /* zfs_znode_cache_constructor */ NULL,
381	    zfs_znode_cache_destructor, NULL, NULL, NULL, 0);
382	kmem_cache_set_move(znode_cache, zfs_znode_move);
383}
384
385void
386zfs_znode_fini(void)
387{
388#ifdef sun
389	/*
390	 * Cleanup vfs & vnode ops
391	 */
392	zfs_remove_op_tables();
393#endif	/* sun */
394
395	/*
396	 * Cleanup zcache
397	 */
398	if (znode_cache)
399		kmem_cache_destroy(znode_cache);
400	znode_cache = NULL;
401	rw_destroy(&zfsvfs_lock);
402}
403
404#ifdef sun
405struct vnodeops *zfs_dvnodeops;
406struct vnodeops *zfs_fvnodeops;
407struct vnodeops *zfs_symvnodeops;
408struct vnodeops *zfs_xdvnodeops;
409struct vnodeops *zfs_evnodeops;
410struct vnodeops *zfs_sharevnodeops;
411
412void
413zfs_remove_op_tables()
414{
415	/*
416	 * Remove vfs ops
417	 */
418	ASSERT(zfsfstype);
419	(void) vfs_freevfsops_by_type(zfsfstype);
420	zfsfstype = 0;
421
422	/*
423	 * Remove vnode ops
424	 */
425	if (zfs_dvnodeops)
426		vn_freevnodeops(zfs_dvnodeops);
427	if (zfs_fvnodeops)
428		vn_freevnodeops(zfs_fvnodeops);
429	if (zfs_symvnodeops)
430		vn_freevnodeops(zfs_symvnodeops);
431	if (zfs_xdvnodeops)
432		vn_freevnodeops(zfs_xdvnodeops);
433	if (zfs_evnodeops)
434		vn_freevnodeops(zfs_evnodeops);
435	if (zfs_sharevnodeops)
436		vn_freevnodeops(zfs_sharevnodeops);
437
438	zfs_dvnodeops = NULL;
439	zfs_fvnodeops = NULL;
440	zfs_symvnodeops = NULL;
441	zfs_xdvnodeops = NULL;
442	zfs_evnodeops = NULL;
443	zfs_sharevnodeops = NULL;
444}
445
446extern const fs_operation_def_t zfs_dvnodeops_template[];
447extern const fs_operation_def_t zfs_fvnodeops_template[];
448extern const fs_operation_def_t zfs_xdvnodeops_template[];
449extern const fs_operation_def_t zfs_symvnodeops_template[];
450extern const fs_operation_def_t zfs_evnodeops_template[];
451extern const fs_operation_def_t zfs_sharevnodeops_template[];
452
453int
454zfs_create_op_tables()
455{
456	int error;
457
458	/*
459	 * zfs_dvnodeops can be set if mod_remove() calls mod_installfs()
460	 * due to a failure to remove the the 2nd modlinkage (zfs_modldrv).
461	 * In this case we just return as the ops vectors are already set up.
462	 */
463	if (zfs_dvnodeops)
464		return (0);
465
466	error = vn_make_ops(MNTTYPE_ZFS, zfs_dvnodeops_template,
467	    &zfs_dvnodeops);
468	if (error)
469		return (error);
470
471	error = vn_make_ops(MNTTYPE_ZFS, zfs_fvnodeops_template,
472	    &zfs_fvnodeops);
473	if (error)
474		return (error);
475
476	error = vn_make_ops(MNTTYPE_ZFS, zfs_symvnodeops_template,
477	    &zfs_symvnodeops);
478	if (error)
479		return (error);
480
481	error = vn_make_ops(MNTTYPE_ZFS, zfs_xdvnodeops_template,
482	    &zfs_xdvnodeops);
483	if (error)
484		return (error);
485
486	error = vn_make_ops(MNTTYPE_ZFS, zfs_evnodeops_template,
487	    &zfs_evnodeops);
488	if (error)
489		return (error);
490
491	error = vn_make_ops(MNTTYPE_ZFS, zfs_sharevnodeops_template,
492	    &zfs_sharevnodeops);
493
494	return (error);
495}
496#endif	/* sun */
497
498int
499zfs_create_share_dir(zfsvfs_t *zfsvfs, dmu_tx_t *tx)
500{
501	zfs_acl_ids_t acl_ids;
502	vattr_t vattr;
503	znode_t *sharezp;
504	vnode_t *vp, vnode;
505	znode_t *zp;
506	int error;
507
508	vattr.va_mask = AT_MODE|AT_UID|AT_GID|AT_TYPE;
509	vattr.va_type = VDIR;
510	vattr.va_mode = S_IFDIR|0555;
511	vattr.va_uid = crgetuid(kcred);
512	vattr.va_gid = crgetgid(kcred);
513
514	sharezp = kmem_cache_alloc(znode_cache, KM_SLEEP);
515	zfs_znode_cache_constructor(sharezp, zfsvfs->z_parent->z_vfs, 0);
516	ASSERT(!POINTER_IS_VALID(sharezp->z_zfsvfs));
517	sharezp->z_moved = 0;
518	sharezp->z_unlinked = 0;
519	sharezp->z_atime_dirty = 0;
520	sharezp->z_zfsvfs = zfsvfs;
521	sharezp->z_is_sa = zfsvfs->z_use_sa;
522
523	sharezp->z_vnode = &vnode;
524	vnode.v_data = sharezp;
525
526	vp = ZTOV(sharezp);
527	vp->v_type = VDIR;
528
529	VERIFY(0 == zfs_acl_ids_create(sharezp, IS_ROOT_NODE, &vattr,
530	    kcred, NULL, &acl_ids));
531	zfs_mknode(sharezp, &vattr, tx, kcred, IS_ROOT_NODE, &zp, &acl_ids);
532	ASSERT3P(zp, ==, sharezp);
533	POINTER_INVALIDATE(&sharezp->z_zfsvfs);
534	error = zap_add(zfsvfs->z_os, MASTER_NODE_OBJ,
535	    ZFS_SHARES_DIR, 8, 1, &sharezp->z_id, tx);
536	zfsvfs->z_shares_dir = sharezp->z_id;
537
538	zfs_acl_ids_free(&acl_ids);
539	ZTOV(sharezp)->v_data = NULL;
540	ZTOV(sharezp)->v_count = 0;
541	ZTOV(sharezp)->v_holdcnt = 0;
542	zp->z_vnode = NULL;
543	sa_handle_destroy(sharezp->z_sa_hdl);
544	sharezp->z_vnode = NULL;
545	kmem_cache_free(znode_cache, sharezp);
546
547	return (error);
548}
549
550/*
551 * define a couple of values we need available
552 * for both 64 and 32 bit environments.
553 */
554#ifndef NBITSMINOR64
555#define	NBITSMINOR64	32
556#endif
557#ifndef MAXMAJ64
558#define	MAXMAJ64	0xffffffffUL
559#endif
560#ifndef	MAXMIN64
561#define	MAXMIN64	0xffffffffUL
562#endif
563
564/*
565 * Create special expldev for ZFS private use.
566 * Can't use standard expldev since it doesn't do
567 * what we want.  The standard expldev() takes a
568 * dev32_t in LP64 and expands it to a long dev_t.
569 * We need an interface that takes a dev32_t in ILP32
570 * and expands it to a long dev_t.
571 */
572static uint64_t
573zfs_expldev(dev_t dev)
574{
575	return (((uint64_t)major(dev) << NBITSMINOR64) | minor(dev));
576}
577/*
578 * Special cmpldev for ZFS private use.
579 * Can't use standard cmpldev since it takes
580 * a long dev_t and compresses it to dev32_t in
581 * LP64.  We need to do a compaction of a long dev_t
582 * to a dev32_t in ILP32.
583 */
584dev_t
585zfs_cmpldev(uint64_t dev)
586{
587	return (makedev((dev >> NBITSMINOR64), (dev & MAXMIN64)));
588}
589
590static void
591zfs_znode_sa_init(zfsvfs_t *zfsvfs, znode_t *zp,
592    dmu_buf_t *db, dmu_object_type_t obj_type, sa_handle_t *sa_hdl)
593{
594	ASSERT(!POINTER_IS_VALID(zp->z_zfsvfs) || (zfsvfs == zp->z_zfsvfs));
595	ASSERT(MUTEX_HELD(ZFS_OBJ_MUTEX(zfsvfs, zp->z_id)));
596
597	mutex_enter(&zp->z_lock);
598
599	ASSERT(zp->z_sa_hdl == NULL);
600	ASSERT(zp->z_acl_cached == NULL);
601	if (sa_hdl == NULL) {
602		VERIFY(0 == sa_handle_get_from_db(zfsvfs->z_os, db, zp,
603		    SA_HDL_SHARED, &zp->z_sa_hdl));
604	} else {
605		zp->z_sa_hdl = sa_hdl;
606		sa_set_userp(sa_hdl, zp);
607	}
608
609	zp->z_is_sa = (obj_type == DMU_OT_SA) ? B_TRUE : B_FALSE;
610
611	/*
612	 * Slap on VROOT if we are the root znode
613	 */
614	if (zp->z_id == zfsvfs->z_root)
615		ZTOV(zp)->v_flag |= VROOT;
616
617	mutex_exit(&zp->z_lock);
618	vn_exists(ZTOV(zp));
619}
620
621void
622zfs_znode_dmu_fini(znode_t *zp)
623{
624	ASSERT(MUTEX_HELD(ZFS_OBJ_MUTEX(zp->z_zfsvfs, zp->z_id)) ||
625	    zp->z_unlinked ||
626	    RW_WRITE_HELD(&zp->z_zfsvfs->z_teardown_inactive_lock));
627
628	sa_handle_destroy(zp->z_sa_hdl);
629	zp->z_sa_hdl = NULL;
630}
631
632static void
633zfs_vnode_forget(vnode_t *vp)
634{
635
636	VOP_UNLOCK(vp, 0);
637	VI_LOCK(vp);
638	vp->v_usecount--;
639	vp->v_iflag |= VI_DOOMED;
640	vp->v_data = NULL;
641	vdropl(vp);
642}
643
644/*
645 * Construct a new znode/vnode and intialize.
646 *
647 * This does not do a call to dmu_set_user() that is
648 * up to the caller to do, in case you don't want to
649 * return the znode
650 */
651static znode_t *
652zfs_znode_alloc(zfsvfs_t *zfsvfs, dmu_buf_t *db, int blksz,
653    dmu_object_type_t obj_type, sa_handle_t *hdl)
654{
655	znode_t	*zp;
656	vnode_t *vp;
657	uint64_t mode;
658	uint64_t parent;
659	sa_bulk_attr_t bulk[9];
660	int count = 0;
661
662	zp = kmem_cache_alloc(znode_cache, KM_SLEEP);
663	zfs_znode_cache_constructor(zp, zfsvfs->z_parent->z_vfs, 0);
664
665	ASSERT(zp->z_dirlocks == NULL);
666	ASSERT(!POINTER_IS_VALID(zp->z_zfsvfs));
667	zp->z_moved = 0;
668
669	/*
670	 * Defer setting z_zfsvfs until the znode is ready to be a candidate for
671	 * the zfs_znode_move() callback.
672	 */
673	zp->z_sa_hdl = NULL;
674	zp->z_unlinked = 0;
675	zp->z_atime_dirty = 0;
676	zp->z_mapcnt = 0;
677	zp->z_id = db->db_object;
678	zp->z_blksz = blksz;
679	zp->z_seq = 0x7A4653;
680	zp->z_sync_cnt = 0;
681
682	vp = ZTOV(zp);
683
684	zfs_znode_sa_init(zfsvfs, zp, db, obj_type, hdl);
685
686	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MODE(zfsvfs), NULL, &mode, 8);
687	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_GEN(zfsvfs), NULL, &zp->z_gen, 8);
688	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_SIZE(zfsvfs), NULL,
689	    &zp->z_size, 8);
690	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_LINKS(zfsvfs), NULL,
691	    &zp->z_links, 8);
692	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_FLAGS(zfsvfs), NULL,
693	    &zp->z_pflags, 8);
694	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_PARENT(zfsvfs), NULL, &parent, 8);
695	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_ATIME(zfsvfs), NULL,
696	    &zp->z_atime, 16);
697	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_UID(zfsvfs), NULL,
698	    &zp->z_uid, 8);
699	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_GID(zfsvfs), NULL,
700	    &zp->z_gid, 8);
701
702	if (sa_bulk_lookup(zp->z_sa_hdl, bulk, count) != 0 || zp->z_gen == 0) {
703		if (hdl == NULL)
704			sa_handle_destroy(zp->z_sa_hdl);
705		zfs_vnode_forget(vp);
706		zp->z_vnode = NULL;
707		kmem_cache_free(znode_cache, zp);
708		return (NULL);
709	}
710
711	zp->z_mode = mode;
712
713	vp->v_type = IFTOVT((mode_t)mode);
714
715	switch (vp->v_type) {
716	case VDIR:
717		zp->z_zn_prefetch = B_TRUE; /* z_prefetch default is enabled */
718		break;
719#ifdef sun
720	case VBLK:
721	case VCHR:
722		{
723			uint64_t rdev;
724			VERIFY(sa_lookup(zp->z_sa_hdl, SA_ZPL_RDEV(zfsvfs),
725			    &rdev, sizeof (rdev)) == 0);
726
727			vp->v_rdev = zfs_cmpldev(rdev);
728		}
729		break;
730#endif	/* sun */
731	case VFIFO:
732#ifdef sun
733	case VSOCK:
734	case VDOOR:
735#endif	/* sun */
736		vp->v_op = &zfs_fifoops;
737		break;
738	case VREG:
739		if (parent == zfsvfs->z_shares_dir) {
740			ASSERT(zp->z_uid == 0 && zp->z_gid == 0);
741			vp->v_op = &zfs_shareops;
742		}
743		break;
744#ifdef sun
745	case VLNK:
746		vn_setops(vp, zfs_symvnodeops);
747		break;
748	default:
749		vn_setops(vp, zfs_evnodeops);
750		break;
751#endif	/* sun */
752	}
753	if (vp->v_type != VFIFO)
754		VN_LOCK_ASHARE(vp);
755
756	mutex_enter(&zfsvfs->z_znodes_lock);
757	list_insert_tail(&zfsvfs->z_all_znodes, zp);
758	membar_producer();
759	/*
760	 * Everything else must be valid before assigning z_zfsvfs makes the
761	 * znode eligible for zfs_znode_move().
762	 */
763	zp->z_zfsvfs = zfsvfs;
764	mutex_exit(&zfsvfs->z_znodes_lock);
765
766	VFS_HOLD(zfsvfs->z_vfs);
767	return (zp);
768}
769
770static uint64_t empty_xattr;
771static uint64_t pad[4];
772static zfs_acl_phys_t acl_phys;
773/*
774 * Create a new DMU object to hold a zfs znode.
775 *
776 *	IN:	dzp	- parent directory for new znode
777 *		vap	- file attributes for new znode
778 *		tx	- dmu transaction id for zap operations
779 *		cr	- credentials of caller
780 *		flag	- flags:
781 *			  IS_ROOT_NODE	- new object will be root
782 *			  IS_XATTR	- new object is an attribute
783 *		bonuslen - length of bonus buffer
784 *		setaclp  - File/Dir initial ACL
785 *		fuidp	 - Tracks fuid allocation.
786 *
787 *	OUT:	zpp	- allocated znode
788 *
789 */
790void
791zfs_mknode(znode_t *dzp, vattr_t *vap, dmu_tx_t *tx, cred_t *cr,
792    uint_t flag, znode_t **zpp, zfs_acl_ids_t *acl_ids)
793{
794	uint64_t	crtime[2], atime[2], mtime[2], ctime[2];
795	uint64_t	mode, size, links, parent, pflags;
796	uint64_t	dzp_pflags = 0;
797	uint64_t	rdev = 0;
798	zfsvfs_t	*zfsvfs = dzp->z_zfsvfs;
799	dmu_buf_t	*db;
800	timestruc_t	now;
801	uint64_t	gen, obj;
802	int		err;
803	int		bonuslen;
804	sa_handle_t	*sa_hdl;
805	dmu_object_type_t obj_type;
806	sa_bulk_attr_t	sa_attrs[ZPL_END];
807	int		cnt = 0;
808	zfs_acl_locator_cb_t locate = { 0 };
809
810	ASSERT(vap && (vap->va_mask & (AT_TYPE|AT_MODE)) == (AT_TYPE|AT_MODE));
811
812	if (zfsvfs->z_replay) {
813		obj = vap->va_nodeid;
814		now = vap->va_ctime;		/* see zfs_replay_create() */
815		gen = vap->va_nblocks;		/* ditto */
816	} else {
817		obj = 0;
818		gethrestime(&now);
819		gen = dmu_tx_get_txg(tx);
820	}
821
822	obj_type = zfsvfs->z_use_sa ? DMU_OT_SA : DMU_OT_ZNODE;
823	bonuslen = (obj_type == DMU_OT_SA) ?
824	    DN_MAX_BONUSLEN : ZFS_OLD_ZNODE_PHYS_SIZE;
825
826	/*
827	 * Create a new DMU object.
828	 */
829	/*
830	 * There's currently no mechanism for pre-reading the blocks that will
831	 * be needed to allocate a new object, so we accept the small chance
832	 * that there will be an i/o error and we will fail one of the
833	 * assertions below.
834	 */
835	if (vap->va_type == VDIR) {
836		if (zfsvfs->z_replay) {
837			err = zap_create_claim_norm(zfsvfs->z_os, obj,
838			    zfsvfs->z_norm, DMU_OT_DIRECTORY_CONTENTS,
839			    obj_type, bonuslen, tx);
840			ASSERT0(err);
841		} else {
842			obj = zap_create_norm(zfsvfs->z_os,
843			    zfsvfs->z_norm, DMU_OT_DIRECTORY_CONTENTS,
844			    obj_type, bonuslen, tx);
845		}
846	} else {
847		if (zfsvfs->z_replay) {
848			err = dmu_object_claim(zfsvfs->z_os, obj,
849			    DMU_OT_PLAIN_FILE_CONTENTS, 0,
850			    obj_type, bonuslen, tx);
851			ASSERT0(err);
852		} else {
853			obj = dmu_object_alloc(zfsvfs->z_os,
854			    DMU_OT_PLAIN_FILE_CONTENTS, 0,
855			    obj_type, bonuslen, tx);
856		}
857	}
858
859	ZFS_OBJ_HOLD_ENTER(zfsvfs, obj);
860	VERIFY(0 == sa_buf_hold(zfsvfs->z_os, obj, NULL, &db));
861
862	/*
863	 * If this is the root, fix up the half-initialized parent pointer
864	 * to reference the just-allocated physical data area.
865	 */
866	if (flag & IS_ROOT_NODE) {
867		dzp->z_id = obj;
868	} else {
869		dzp_pflags = dzp->z_pflags;
870	}
871
872	/*
873	 * If parent is an xattr, so am I.
874	 */
875	if (dzp_pflags & ZFS_XATTR) {
876		flag |= IS_XATTR;
877	}
878
879	if (zfsvfs->z_use_fuids)
880		pflags = ZFS_ARCHIVE | ZFS_AV_MODIFIED;
881	else
882		pflags = 0;
883
884	if (vap->va_type == VDIR) {
885		size = 2;		/* contents ("." and "..") */
886		links = (flag & (IS_ROOT_NODE | IS_XATTR)) ? 2 : 1;
887	} else {
888		size = links = 0;
889	}
890
891	if (vap->va_type == VBLK || vap->va_type == VCHR) {
892		rdev = zfs_expldev(vap->va_rdev);
893	}
894
895	parent = dzp->z_id;
896	mode = acl_ids->z_mode;
897	if (flag & IS_XATTR)
898		pflags |= ZFS_XATTR;
899
900	/*
901	 * No execs denied will be deterimed when zfs_mode_compute() is called.
902	 */
903	pflags |= acl_ids->z_aclp->z_hints &
904	    (ZFS_ACL_TRIVIAL|ZFS_INHERIT_ACE|ZFS_ACL_AUTO_INHERIT|
905	    ZFS_ACL_DEFAULTED|ZFS_ACL_PROTECTED);
906
907	ZFS_TIME_ENCODE(&now, crtime);
908	ZFS_TIME_ENCODE(&now, ctime);
909
910	if (vap->va_mask & AT_ATIME) {
911		ZFS_TIME_ENCODE(&vap->va_atime, atime);
912	} else {
913		ZFS_TIME_ENCODE(&now, atime);
914	}
915
916	if (vap->va_mask & AT_MTIME) {
917		ZFS_TIME_ENCODE(&vap->va_mtime, mtime);
918	} else {
919		ZFS_TIME_ENCODE(&now, mtime);
920	}
921
922	/* Now add in all of the "SA" attributes */
923	VERIFY(0 == sa_handle_get_from_db(zfsvfs->z_os, db, NULL, SA_HDL_SHARED,
924	    &sa_hdl));
925
926	/*
927	 * Setup the array of attributes to be replaced/set on the new file
928	 *
929	 * order for  DMU_OT_ZNODE is critical since it needs to be constructed
930	 * in the old znode_phys_t format.  Don't change this ordering
931	 */
932
933	if (obj_type == DMU_OT_ZNODE) {
934		SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_ATIME(zfsvfs),
935		    NULL, &atime, 16);
936		SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_MTIME(zfsvfs),
937		    NULL, &mtime, 16);
938		SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_CTIME(zfsvfs),
939		    NULL, &ctime, 16);
940		SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_CRTIME(zfsvfs),
941		    NULL, &crtime, 16);
942		SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_GEN(zfsvfs),
943		    NULL, &gen, 8);
944		SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_MODE(zfsvfs),
945		    NULL, &mode, 8);
946		SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_SIZE(zfsvfs),
947		    NULL, &size, 8);
948		SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_PARENT(zfsvfs),
949		    NULL, &parent, 8);
950	} else {
951		SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_MODE(zfsvfs),
952		    NULL, &mode, 8);
953		SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_SIZE(zfsvfs),
954		    NULL, &size, 8);
955		SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_GEN(zfsvfs),
956		    NULL, &gen, 8);
957		SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_UID(zfsvfs), NULL,
958		    &acl_ids->z_fuid, 8);
959		SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_GID(zfsvfs), NULL,
960		    &acl_ids->z_fgid, 8);
961		SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_PARENT(zfsvfs),
962		    NULL, &parent, 8);
963		SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_FLAGS(zfsvfs),
964		    NULL, &pflags, 8);
965		SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_ATIME(zfsvfs),
966		    NULL, &atime, 16);
967		SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_MTIME(zfsvfs),
968		    NULL, &mtime, 16);
969		SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_CTIME(zfsvfs),
970		    NULL, &ctime, 16);
971		SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_CRTIME(zfsvfs),
972		    NULL, &crtime, 16);
973	}
974
975	SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_LINKS(zfsvfs), NULL, &links, 8);
976
977	if (obj_type == DMU_OT_ZNODE) {
978		SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_XATTR(zfsvfs), NULL,
979		    &empty_xattr, 8);
980	}
981	if (obj_type == DMU_OT_ZNODE ||
982	    (vap->va_type == VBLK || vap->va_type == VCHR)) {
983		SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_RDEV(zfsvfs),
984		    NULL, &rdev, 8);
985
986	}
987	if (obj_type == DMU_OT_ZNODE) {
988		SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_FLAGS(zfsvfs),
989		    NULL, &pflags, 8);
990		SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_UID(zfsvfs), NULL,
991		    &acl_ids->z_fuid, 8);
992		SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_GID(zfsvfs), NULL,
993		    &acl_ids->z_fgid, 8);
994		SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_PAD(zfsvfs), NULL, pad,
995		    sizeof (uint64_t) * 4);
996		SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_ZNODE_ACL(zfsvfs), NULL,
997		    &acl_phys, sizeof (zfs_acl_phys_t));
998	} else if (acl_ids->z_aclp->z_version >= ZFS_ACL_VERSION_FUID) {
999		SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_DACL_COUNT(zfsvfs), NULL,
1000		    &acl_ids->z_aclp->z_acl_count, 8);
1001		locate.cb_aclp = acl_ids->z_aclp;
1002		SA_ADD_BULK_ATTR(sa_attrs, cnt, SA_ZPL_DACL_ACES(zfsvfs),
1003		    zfs_acl_data_locator, &locate,
1004		    acl_ids->z_aclp->z_acl_bytes);
1005		mode = zfs_mode_compute(mode, acl_ids->z_aclp, &pflags,
1006		    acl_ids->z_fuid, acl_ids->z_fgid);
1007	}
1008
1009	VERIFY(sa_replace_all_by_template(sa_hdl, sa_attrs, cnt, tx) == 0);
1010
1011	if (!(flag & IS_ROOT_NODE)) {
1012		*zpp = zfs_znode_alloc(zfsvfs, db, 0, obj_type, sa_hdl);
1013		ASSERT(*zpp != NULL);
1014	} else {
1015		/*
1016		 * If we are creating the root node, the "parent" we
1017		 * passed in is the znode for the root.
1018		 */
1019		*zpp = dzp;
1020
1021		(*zpp)->z_sa_hdl = sa_hdl;
1022	}
1023
1024	(*zpp)->z_pflags = pflags;
1025	(*zpp)->z_mode = mode;
1026
1027	if (vap->va_mask & AT_XVATTR)
1028		zfs_xvattr_set(*zpp, (xvattr_t *)vap, tx);
1029
1030	if (obj_type == DMU_OT_ZNODE ||
1031	    acl_ids->z_aclp->z_version < ZFS_ACL_VERSION_FUID) {
1032		err = zfs_aclset_common(*zpp, acl_ids->z_aclp, cr, tx);
1033		ASSERT0(err);
1034	}
1035	if (!(flag & IS_ROOT_NODE)) {
1036		vnode_t *vp;
1037
1038		vp = ZTOV(*zpp);
1039		vp->v_vflag |= VV_FORCEINSMQ;
1040		err = insmntque(vp, zfsvfs->z_vfs);
1041		vp->v_vflag &= ~VV_FORCEINSMQ;
1042		KASSERT(err == 0, ("insmntque() failed: error %d", err));
1043	}
1044	ZFS_OBJ_HOLD_EXIT(zfsvfs, obj);
1045}
1046
1047/*
1048 * zfs_xvattr_set only updates the in-core attributes
1049 * it is assumed the caller will be doing an sa_bulk_update
1050 * to push the changes out
1051 */
1052void
1053zfs_xvattr_set(znode_t *zp, xvattr_t *xvap, dmu_tx_t *tx)
1054{
1055	xoptattr_t *xoap;
1056
1057	xoap = xva_getxoptattr(xvap);
1058	ASSERT(xoap);
1059
1060	if (XVA_ISSET_REQ(xvap, XAT_CREATETIME)) {
1061		uint64_t times[2];
1062		ZFS_TIME_ENCODE(&xoap->xoa_createtime, times);
1063		(void) sa_update(zp->z_sa_hdl, SA_ZPL_CRTIME(zp->z_zfsvfs),
1064		    &times, sizeof (times), tx);
1065		XVA_SET_RTN(xvap, XAT_CREATETIME);
1066	}
1067	if (XVA_ISSET_REQ(xvap, XAT_READONLY)) {
1068		ZFS_ATTR_SET(zp, ZFS_READONLY, xoap->xoa_readonly,
1069		    zp->z_pflags, tx);
1070		XVA_SET_RTN(xvap, XAT_READONLY);
1071	}
1072	if (XVA_ISSET_REQ(xvap, XAT_HIDDEN)) {
1073		ZFS_ATTR_SET(zp, ZFS_HIDDEN, xoap->xoa_hidden,
1074		    zp->z_pflags, tx);
1075		XVA_SET_RTN(xvap, XAT_HIDDEN);
1076	}
1077	if (XVA_ISSET_REQ(xvap, XAT_SYSTEM)) {
1078		ZFS_ATTR_SET(zp, ZFS_SYSTEM, xoap->xoa_system,
1079		    zp->z_pflags, tx);
1080		XVA_SET_RTN(xvap, XAT_SYSTEM);
1081	}
1082	if (XVA_ISSET_REQ(xvap, XAT_ARCHIVE)) {
1083		ZFS_ATTR_SET(zp, ZFS_ARCHIVE, xoap->xoa_archive,
1084		    zp->z_pflags, tx);
1085		XVA_SET_RTN(xvap, XAT_ARCHIVE);
1086	}
1087	if (XVA_ISSET_REQ(xvap, XAT_IMMUTABLE)) {
1088		ZFS_ATTR_SET(zp, ZFS_IMMUTABLE, xoap->xoa_immutable,
1089		    zp->z_pflags, tx);
1090		XVA_SET_RTN(xvap, XAT_IMMUTABLE);
1091	}
1092	if (XVA_ISSET_REQ(xvap, XAT_NOUNLINK)) {
1093		ZFS_ATTR_SET(zp, ZFS_NOUNLINK, xoap->xoa_nounlink,
1094		    zp->z_pflags, tx);
1095		XVA_SET_RTN(xvap, XAT_NOUNLINK);
1096	}
1097	if (XVA_ISSET_REQ(xvap, XAT_APPENDONLY)) {
1098		ZFS_ATTR_SET(zp, ZFS_APPENDONLY, xoap->xoa_appendonly,
1099		    zp->z_pflags, tx);
1100		XVA_SET_RTN(xvap, XAT_APPENDONLY);
1101	}
1102	if (XVA_ISSET_REQ(xvap, XAT_NODUMP)) {
1103		ZFS_ATTR_SET(zp, ZFS_NODUMP, xoap->xoa_nodump,
1104		    zp->z_pflags, tx);
1105		XVA_SET_RTN(xvap, XAT_NODUMP);
1106	}
1107	if (XVA_ISSET_REQ(xvap, XAT_OPAQUE)) {
1108		ZFS_ATTR_SET(zp, ZFS_OPAQUE, xoap->xoa_opaque,
1109		    zp->z_pflags, tx);
1110		XVA_SET_RTN(xvap, XAT_OPAQUE);
1111	}
1112	if (XVA_ISSET_REQ(xvap, XAT_AV_QUARANTINED)) {
1113		ZFS_ATTR_SET(zp, ZFS_AV_QUARANTINED,
1114		    xoap->xoa_av_quarantined, zp->z_pflags, tx);
1115		XVA_SET_RTN(xvap, XAT_AV_QUARANTINED);
1116	}
1117	if (XVA_ISSET_REQ(xvap, XAT_AV_MODIFIED)) {
1118		ZFS_ATTR_SET(zp, ZFS_AV_MODIFIED, xoap->xoa_av_modified,
1119		    zp->z_pflags, tx);
1120		XVA_SET_RTN(xvap, XAT_AV_MODIFIED);
1121	}
1122	if (XVA_ISSET_REQ(xvap, XAT_AV_SCANSTAMP)) {
1123		zfs_sa_set_scanstamp(zp, xvap, tx);
1124		XVA_SET_RTN(xvap, XAT_AV_SCANSTAMP);
1125	}
1126	if (XVA_ISSET_REQ(xvap, XAT_REPARSE)) {
1127		ZFS_ATTR_SET(zp, ZFS_REPARSE, xoap->xoa_reparse,
1128		    zp->z_pflags, tx);
1129		XVA_SET_RTN(xvap, XAT_REPARSE);
1130	}
1131	if (XVA_ISSET_REQ(xvap, XAT_OFFLINE)) {
1132		ZFS_ATTR_SET(zp, ZFS_OFFLINE, xoap->xoa_offline,
1133		    zp->z_pflags, tx);
1134		XVA_SET_RTN(xvap, XAT_OFFLINE);
1135	}
1136	if (XVA_ISSET_REQ(xvap, XAT_SPARSE)) {
1137		ZFS_ATTR_SET(zp, ZFS_SPARSE, xoap->xoa_sparse,
1138		    zp->z_pflags, tx);
1139		XVA_SET_RTN(xvap, XAT_SPARSE);
1140	}
1141}
1142
1143int
1144zfs_zget(zfsvfs_t *zfsvfs, uint64_t obj_num, znode_t **zpp)
1145{
1146	dmu_object_info_t doi;
1147	dmu_buf_t	*db;
1148	znode_t		*zp;
1149	int err;
1150	sa_handle_t	*hdl;
1151	int first = 1;
1152
1153	*zpp = NULL;
1154
1155again:
1156	ZFS_OBJ_HOLD_ENTER(zfsvfs, obj_num);
1157
1158	err = sa_buf_hold(zfsvfs->z_os, obj_num, NULL, &db);
1159	if (err) {
1160		ZFS_OBJ_HOLD_EXIT(zfsvfs, obj_num);
1161		return (err);
1162	}
1163
1164	dmu_object_info_from_db(db, &doi);
1165	if (doi.doi_bonus_type != DMU_OT_SA &&
1166	    (doi.doi_bonus_type != DMU_OT_ZNODE ||
1167	    (doi.doi_bonus_type == DMU_OT_ZNODE &&
1168	    doi.doi_bonus_size < sizeof (znode_phys_t)))) {
1169		sa_buf_rele(db, NULL);
1170		ZFS_OBJ_HOLD_EXIT(zfsvfs, obj_num);
1171		return (EINVAL);
1172	}
1173
1174	hdl = dmu_buf_get_user(db);
1175	if (hdl != NULL) {
1176		zp  = sa_get_userdata(hdl);
1177
1178
1179		/*
1180		 * Since "SA" does immediate eviction we
1181		 * should never find a sa handle that doesn't
1182		 * know about the znode.
1183		 */
1184
1185		ASSERT3P(zp, !=, NULL);
1186
1187		mutex_enter(&zp->z_lock);
1188		ASSERT3U(zp->z_id, ==, obj_num);
1189		if (zp->z_unlinked) {
1190			err = ENOENT;
1191		} else {
1192			vnode_t *vp;
1193			int dying = 0;
1194
1195			vp = ZTOV(zp);
1196			if (vp == NULL)
1197				dying = 1;
1198			else {
1199				VN_HOLD(vp);
1200				if ((vp->v_iflag & VI_DOOMED) != 0) {
1201					dying = 1;
1202					/*
1203					 * Don't VN_RELE() vnode here, because
1204					 * it can call vn_lock() which creates
1205					 * LOR between vnode lock and znode
1206					 * lock. We will VN_RELE() the vnode
1207					 * after droping znode lock.
1208					 */
1209				}
1210			}
1211			if (dying) {
1212				if (first) {
1213					ZFS_LOG(1, "dying znode detected (zp=%p)", zp);
1214					first = 0;
1215				}
1216				/*
1217				 * znode is dying so we can't reuse it, we must
1218				 * wait until destruction is completed.
1219				 */
1220				sa_buf_rele(db, NULL);
1221				mutex_exit(&zp->z_lock);
1222				ZFS_OBJ_HOLD_EXIT(zfsvfs, obj_num);
1223				if (vp != NULL)
1224					VN_RELE(vp);
1225				tsleep(zp, 0, "zcollide", 1);
1226				goto again;
1227			}
1228			*zpp = zp;
1229			err = 0;
1230		}
1231		sa_buf_rele(db, NULL);
1232		mutex_exit(&zp->z_lock);
1233		ZFS_OBJ_HOLD_EXIT(zfsvfs, obj_num);
1234		return (err);
1235	}
1236
1237	/*
1238	 * Not found create new znode/vnode
1239	 * but only if file exists.
1240	 *
1241	 * There is a small window where zfs_vget() could
1242	 * find this object while a file create is still in
1243	 * progress.  This is checked for in zfs_znode_alloc()
1244	 *
1245	 * if zfs_znode_alloc() fails it will drop the hold on the
1246	 * bonus buffer.
1247	 */
1248	zp = zfs_znode_alloc(zfsvfs, db, doi.doi_data_block_size,
1249	    doi.doi_bonus_type, NULL);
1250	if (zp == NULL) {
1251		err = ENOENT;
1252	} else {
1253		*zpp = zp;
1254	}
1255	if (err == 0) {
1256		vnode_t *vp = ZTOV(zp);
1257
1258		err = insmntque(vp, zfsvfs->z_vfs);
1259		if (err == 0)
1260			VOP_UNLOCK(vp, 0);
1261		else {
1262			zp->z_vnode = NULL;
1263			zfs_znode_dmu_fini(zp);
1264			zfs_znode_free(zp);
1265			*zpp = NULL;
1266		}
1267	}
1268	ZFS_OBJ_HOLD_EXIT(zfsvfs, obj_num);
1269	return (err);
1270}
1271
1272int
1273zfs_rezget(znode_t *zp)
1274{
1275	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
1276	dmu_object_info_t doi;
1277	dmu_buf_t *db;
1278	vnode_t *vp;
1279	uint64_t obj_num = zp->z_id;
1280	uint64_t mode, size;
1281	sa_bulk_attr_t bulk[8];
1282	int err;
1283	int count = 0;
1284	uint64_t gen;
1285
1286	ZFS_OBJ_HOLD_ENTER(zfsvfs, obj_num);
1287
1288	mutex_enter(&zp->z_acl_lock);
1289	if (zp->z_acl_cached) {
1290		zfs_acl_free(zp->z_acl_cached);
1291		zp->z_acl_cached = NULL;
1292	}
1293
1294	mutex_exit(&zp->z_acl_lock);
1295	ASSERT(zp->z_sa_hdl == NULL);
1296	err = sa_buf_hold(zfsvfs->z_os, obj_num, NULL, &db);
1297	if (err) {
1298		ZFS_OBJ_HOLD_EXIT(zfsvfs, obj_num);
1299		return (err);
1300	}
1301
1302	dmu_object_info_from_db(db, &doi);
1303	if (doi.doi_bonus_type != DMU_OT_SA &&
1304	    (doi.doi_bonus_type != DMU_OT_ZNODE ||
1305	    (doi.doi_bonus_type == DMU_OT_ZNODE &&
1306	    doi.doi_bonus_size < sizeof (znode_phys_t)))) {
1307		sa_buf_rele(db, NULL);
1308		ZFS_OBJ_HOLD_EXIT(zfsvfs, obj_num);
1309		return (EINVAL);
1310	}
1311
1312	zfs_znode_sa_init(zfsvfs, zp, db, doi.doi_bonus_type, NULL);
1313	size = zp->z_size;
1314
1315	/* reload cached values */
1316	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_GEN(zfsvfs), NULL,
1317	    &gen, sizeof (gen));
1318	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_SIZE(zfsvfs), NULL,
1319	    &zp->z_size, sizeof (zp->z_size));
1320	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_LINKS(zfsvfs), NULL,
1321	    &zp->z_links, sizeof (zp->z_links));
1322	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_FLAGS(zfsvfs), NULL,
1323	    &zp->z_pflags, sizeof (zp->z_pflags));
1324	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_ATIME(zfsvfs), NULL,
1325	    &zp->z_atime, sizeof (zp->z_atime));
1326	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_UID(zfsvfs), NULL,
1327	    &zp->z_uid, sizeof (zp->z_uid));
1328	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_GID(zfsvfs), NULL,
1329	    &zp->z_gid, sizeof (zp->z_gid));
1330	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MODE(zfsvfs), NULL,
1331	    &mode, sizeof (mode));
1332
1333	if (sa_bulk_lookup(zp->z_sa_hdl, bulk, count)) {
1334		zfs_znode_dmu_fini(zp);
1335		ZFS_OBJ_HOLD_EXIT(zfsvfs, obj_num);
1336		return (EIO);
1337	}
1338
1339	zp->z_mode = mode;
1340
1341	if (gen != zp->z_gen) {
1342		zfs_znode_dmu_fini(zp);
1343		ZFS_OBJ_HOLD_EXIT(zfsvfs, obj_num);
1344		return (EIO);
1345	}
1346
1347	/*
1348	 * XXXPJD: Not sure how is that possible, but under heavy
1349	 * zfs recv -F load it happens that z_gen is the same, but
1350	 * vnode type is different than znode type. This would mean
1351	 * that for example regular file was replaced with directory
1352	 * which has the same object number.
1353	 */
1354	vp = ZTOV(zp);
1355	if (vp != NULL &&
1356	    vp->v_type != IFTOVT((mode_t)zp->z_mode)) {
1357		zfs_znode_dmu_fini(zp);
1358		ZFS_OBJ_HOLD_EXIT(zfsvfs, obj_num);
1359		return (EIO);
1360	}
1361
1362	zp->z_unlinked = (zp->z_links == 0);
1363	zp->z_blksz = doi.doi_data_block_size;
1364	if (vp != NULL) {
1365		vn_pages_remove(vp, 0, 0);
1366		if (zp->z_size != size)
1367			vnode_pager_setsize(vp, zp->z_size);
1368	}
1369
1370	ZFS_OBJ_HOLD_EXIT(zfsvfs, obj_num);
1371
1372	return (0);
1373}
1374
1375void
1376zfs_znode_delete(znode_t *zp, dmu_tx_t *tx)
1377{
1378	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
1379	objset_t *os = zfsvfs->z_os;
1380	uint64_t obj = zp->z_id;
1381	uint64_t acl_obj = zfs_external_acl(zp);
1382
1383	ZFS_OBJ_HOLD_ENTER(zfsvfs, obj);
1384	if (acl_obj) {
1385		VERIFY(!zp->z_is_sa);
1386		VERIFY(0 == dmu_object_free(os, acl_obj, tx));
1387	}
1388	VERIFY(0 == dmu_object_free(os, obj, tx));
1389	zfs_znode_dmu_fini(zp);
1390	ZFS_OBJ_HOLD_EXIT(zfsvfs, obj);
1391	zfs_znode_free(zp);
1392}
1393
1394void
1395zfs_zinactive(znode_t *zp)
1396{
1397	vnode_t	*vp = ZTOV(zp);
1398	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
1399	uint64_t z_id = zp->z_id;
1400	int vfslocked;
1401
1402	ASSERT(zp->z_sa_hdl);
1403
1404	/*
1405	 * Don't allow a zfs_zget() while were trying to release this znode
1406	 */
1407	ZFS_OBJ_HOLD_ENTER(zfsvfs, z_id);
1408
1409	mutex_enter(&zp->z_lock);
1410	VI_LOCK(vp);
1411	if (vp->v_count > 0) {
1412		/*
1413		 * If the hold count is greater than zero, somebody has
1414		 * obtained a new reference on this znode while we were
1415		 * processing it here, so we are done.
1416		 */
1417		VI_UNLOCK(vp);
1418		mutex_exit(&zp->z_lock);
1419		ZFS_OBJ_HOLD_EXIT(zfsvfs, z_id);
1420		return;
1421	}
1422	VI_UNLOCK(vp);
1423
1424	/*
1425	 * If this was the last reference to a file with no links,
1426	 * remove the file from the file system.
1427	 */
1428	if (zp->z_unlinked) {
1429		mutex_exit(&zp->z_lock);
1430		ZFS_OBJ_HOLD_EXIT(zfsvfs, z_id);
1431		ASSERT(vp->v_count == 0);
1432		vrecycle(vp);
1433		vfslocked = VFS_LOCK_GIANT(zfsvfs->z_vfs);
1434		zfs_rmnode(zp);
1435		VFS_UNLOCK_GIANT(vfslocked);
1436		return;
1437	}
1438
1439	mutex_exit(&zp->z_lock);
1440	ZFS_OBJ_HOLD_EXIT(zfsvfs, z_id);
1441}
1442
1443void
1444zfs_znode_free(znode_t *zp)
1445{
1446	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
1447
1448	ASSERT(ZTOV(zp) == NULL);
1449	ASSERT(zp->z_sa_hdl == NULL);
1450	mutex_enter(&zfsvfs->z_znodes_lock);
1451	POINTER_INVALIDATE(&zp->z_zfsvfs);
1452	list_remove(&zfsvfs->z_all_znodes, zp);
1453	mutex_exit(&zfsvfs->z_znodes_lock);
1454
1455	if (zp->z_acl_cached) {
1456		zfs_acl_free(zp->z_acl_cached);
1457		zp->z_acl_cached = NULL;
1458	}
1459
1460	kmem_cache_free(znode_cache, zp);
1461
1462	VFS_RELE(zfsvfs->z_vfs);
1463}
1464
1465void
1466zfs_tstamp_update_setup(znode_t *zp, uint_t flag, uint64_t mtime[2],
1467    uint64_t ctime[2], boolean_t have_tx)
1468{
1469	timestruc_t	now;
1470
1471	gethrestime(&now);
1472
1473	if (have_tx) {	/* will sa_bulk_update happen really soon? */
1474		zp->z_atime_dirty = 0;
1475		zp->z_seq++;
1476	} else {
1477		zp->z_atime_dirty = 1;
1478	}
1479
1480	if (flag & AT_ATIME) {
1481		ZFS_TIME_ENCODE(&now, zp->z_atime);
1482	}
1483
1484	if (flag & AT_MTIME) {
1485		ZFS_TIME_ENCODE(&now, mtime);
1486		if (zp->z_zfsvfs->z_use_fuids) {
1487			zp->z_pflags |= (ZFS_ARCHIVE |
1488			    ZFS_AV_MODIFIED);
1489		}
1490	}
1491
1492	if (flag & AT_CTIME) {
1493		ZFS_TIME_ENCODE(&now, ctime);
1494		if (zp->z_zfsvfs->z_use_fuids)
1495			zp->z_pflags |= ZFS_ARCHIVE;
1496	}
1497}
1498
1499/*
1500 * Grow the block size for a file.
1501 *
1502 *	IN:	zp	- znode of file to free data in.
1503 *		size	- requested block size
1504 *		tx	- open transaction.
1505 *
1506 * NOTE: this function assumes that the znode is write locked.
1507 */
1508void
1509zfs_grow_blocksize(znode_t *zp, uint64_t size, dmu_tx_t *tx)
1510{
1511	int		error;
1512	u_longlong_t	dummy;
1513
1514	if (size <= zp->z_blksz)
1515		return;
1516	/*
1517	 * If the file size is already greater than the current blocksize,
1518	 * we will not grow.  If there is more than one block in a file,
1519	 * the blocksize cannot change.
1520	 */
1521	if (zp->z_blksz && zp->z_size > zp->z_blksz)
1522		return;
1523
1524	error = dmu_object_set_blocksize(zp->z_zfsvfs->z_os, zp->z_id,
1525	    size, 0, tx);
1526
1527	if (error == ENOTSUP)
1528		return;
1529	ASSERT0(error);
1530
1531	/* What blocksize did we actually get? */
1532	dmu_object_size_from_db(sa_get_db(zp->z_sa_hdl), &zp->z_blksz, &dummy);
1533}
1534
1535#ifdef sun
1536/*
1537 * This is a dummy interface used when pvn_vplist_dirty() should *not*
1538 * be calling back into the fs for a putpage().  E.g.: when truncating
1539 * a file, the pages being "thrown away* don't need to be written out.
1540 */
1541/* ARGSUSED */
1542static int
1543zfs_no_putpage(vnode_t *vp, page_t *pp, u_offset_t *offp, size_t *lenp,
1544    int flags, cred_t *cr)
1545{
1546	ASSERT(0);
1547	return (0);
1548}
1549#endif	/* sun */
1550
1551/*
1552 * Increase the file length
1553 *
1554 *	IN:	zp	- znode of file to free data in.
1555 *		end	- new end-of-file
1556 *
1557 * 	RETURN:	0 if success
1558 *		error code if failure
1559 */
1560static int
1561zfs_extend(znode_t *zp, uint64_t end)
1562{
1563	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
1564	dmu_tx_t *tx;
1565	rl_t *rl;
1566	uint64_t newblksz;
1567	int error;
1568
1569	/*
1570	 * We will change zp_size, lock the whole file.
1571	 */
1572	rl = zfs_range_lock(zp, 0, UINT64_MAX, RL_WRITER);
1573
1574	/*
1575	 * Nothing to do if file already at desired length.
1576	 */
1577	if (end <= zp->z_size) {
1578		zfs_range_unlock(rl);
1579		return (0);
1580	}
1581top:
1582	tx = dmu_tx_create(zfsvfs->z_os);
1583	dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE);
1584	zfs_sa_upgrade_txholds(tx, zp);
1585	if (end > zp->z_blksz &&
1586	    (!ISP2(zp->z_blksz) || zp->z_blksz < zfsvfs->z_max_blksz)) {
1587		/*
1588		 * We are growing the file past the current block size.
1589		 */
1590		if (zp->z_blksz > zp->z_zfsvfs->z_max_blksz) {
1591			ASSERT(!ISP2(zp->z_blksz));
1592			newblksz = MIN(end, SPA_MAXBLOCKSIZE);
1593		} else {
1594			newblksz = MIN(end, zp->z_zfsvfs->z_max_blksz);
1595		}
1596		dmu_tx_hold_write(tx, zp->z_id, 0, newblksz);
1597	} else {
1598		newblksz = 0;
1599	}
1600
1601	error = dmu_tx_assign(tx, TXG_NOWAIT);
1602	if (error) {
1603		if (error == ERESTART) {
1604			dmu_tx_wait(tx);
1605			dmu_tx_abort(tx);
1606			goto top;
1607		}
1608		dmu_tx_abort(tx);
1609		zfs_range_unlock(rl);
1610		return (error);
1611	}
1612
1613	if (newblksz)
1614		zfs_grow_blocksize(zp, newblksz, tx);
1615
1616	zp->z_size = end;
1617
1618	VERIFY(0 == sa_update(zp->z_sa_hdl, SA_ZPL_SIZE(zp->z_zfsvfs),
1619	    &zp->z_size, sizeof (zp->z_size), tx));
1620
1621	vnode_pager_setsize(ZTOV(zp), end);
1622
1623	zfs_range_unlock(rl);
1624
1625	dmu_tx_commit(tx);
1626
1627	return (0);
1628}
1629
1630/*
1631 * Free space in a file.
1632 *
1633 *	IN:	zp	- znode of file to free data in.
1634 *		off	- start of section to free.
1635 *		len	- length of section to free.
1636 *
1637 * 	RETURN:	0 if success
1638 *		error code if failure
1639 */
1640static int
1641zfs_free_range(znode_t *zp, uint64_t off, uint64_t len)
1642{
1643	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
1644	rl_t *rl;
1645	int error;
1646
1647	/*
1648	 * Lock the range being freed.
1649	 */
1650	rl = zfs_range_lock(zp, off, len, RL_WRITER);
1651
1652	/*
1653	 * Nothing to do if file already at desired length.
1654	 */
1655	if (off >= zp->z_size) {
1656		zfs_range_unlock(rl);
1657		return (0);
1658	}
1659
1660	if (off + len > zp->z_size)
1661		len = zp->z_size - off;
1662
1663	error = dmu_free_long_range(zfsvfs->z_os, zp->z_id, off, len);
1664
1665	if (error == 0) {
1666		/*
1667		 * In FreeBSD we cannot free block in the middle of a file,
1668		 * but only at the end of a file, so this code path should
1669		 * never happen.
1670		 */
1671		vnode_pager_setsize(ZTOV(zp), off);
1672	}
1673
1674	zfs_range_unlock(rl);
1675
1676	return (error);
1677}
1678
1679/*
1680 * Truncate a file
1681 *
1682 *	IN:	zp	- znode of file to free data in.
1683 *		end	- new end-of-file.
1684 *
1685 * 	RETURN:	0 if success
1686 *		error code if failure
1687 */
1688static int
1689zfs_trunc(znode_t *zp, uint64_t end)
1690{
1691	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
1692	vnode_t *vp = ZTOV(zp);
1693	dmu_tx_t *tx;
1694	rl_t *rl;
1695	int error;
1696	sa_bulk_attr_t bulk[2];
1697	int count = 0;
1698
1699	/*
1700	 * We will change zp_size, lock the whole file.
1701	 */
1702	rl = zfs_range_lock(zp, 0, UINT64_MAX, RL_WRITER);
1703
1704	/*
1705	 * Nothing to do if file already at desired length.
1706	 */
1707	if (end >= zp->z_size) {
1708		zfs_range_unlock(rl);
1709		return (0);
1710	}
1711
1712	error = dmu_free_long_range(zfsvfs->z_os, zp->z_id, end,  -1);
1713	if (error) {
1714		zfs_range_unlock(rl);
1715		return (error);
1716	}
1717top:
1718	tx = dmu_tx_create(zfsvfs->z_os);
1719	dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE);
1720	zfs_sa_upgrade_txholds(tx, zp);
1721	error = dmu_tx_assign(tx, TXG_NOWAIT);
1722	if (error) {
1723		if (error == ERESTART) {
1724			dmu_tx_wait(tx);
1725			dmu_tx_abort(tx);
1726			goto top;
1727		}
1728		dmu_tx_abort(tx);
1729		zfs_range_unlock(rl);
1730		return (error);
1731	}
1732
1733	zp->z_size = end;
1734	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_SIZE(zfsvfs),
1735	    NULL, &zp->z_size, sizeof (zp->z_size));
1736
1737	if (end == 0) {
1738		zp->z_pflags &= ~ZFS_SPARSE;
1739		SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_FLAGS(zfsvfs),
1740		    NULL, &zp->z_pflags, 8);
1741	}
1742	VERIFY(sa_bulk_update(zp->z_sa_hdl, bulk, count, tx) == 0);
1743
1744	dmu_tx_commit(tx);
1745
1746	/*
1747	 * Clear any mapped pages in the truncated region.  This has to
1748	 * happen outside of the transaction to avoid the possibility of
1749	 * a deadlock with someone trying to push a page that we are
1750	 * about to invalidate.
1751	 */
1752	vnode_pager_setsize(vp, end);
1753
1754	zfs_range_unlock(rl);
1755
1756	return (0);
1757}
1758
1759/*
1760 * Free space in a file
1761 *
1762 *	IN:	zp	- znode of file to free data in.
1763 *		off	- start of range
1764 *		len	- end of range (0 => EOF)
1765 *		flag	- current file open mode flags.
1766 *		log	- TRUE if this action should be logged
1767 *
1768 * 	RETURN:	0 if success
1769 *		error code if failure
1770 */
1771int
1772zfs_freesp(znode_t *zp, uint64_t off, uint64_t len, int flag, boolean_t log)
1773{
1774	vnode_t *vp = ZTOV(zp);
1775	dmu_tx_t *tx;
1776	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
1777	zilog_t *zilog = zfsvfs->z_log;
1778	uint64_t mode;
1779	uint64_t mtime[2], ctime[2];
1780	sa_bulk_attr_t bulk[3];
1781	int count = 0;
1782	int error;
1783
1784	if ((error = sa_lookup(zp->z_sa_hdl, SA_ZPL_MODE(zfsvfs), &mode,
1785	    sizeof (mode))) != 0)
1786		return (error);
1787
1788	if (off > zp->z_size) {
1789		error =  zfs_extend(zp, off+len);
1790		if (error == 0 && log)
1791			goto log;
1792		else
1793			return (error);
1794	}
1795
1796	/*
1797	 * Check for any locks in the region to be freed.
1798	 */
1799
1800	if (MANDLOCK(vp, (mode_t)mode)) {
1801		uint64_t length = (len ? len : zp->z_size - off);
1802		if (error = chklock(vp, FWRITE, off, length, flag, NULL))
1803			return (error);
1804	}
1805
1806	if (len == 0) {
1807		error = zfs_trunc(zp, off);
1808	} else {
1809		if ((error = zfs_free_range(zp, off, len)) == 0 &&
1810		    off + len > zp->z_size)
1811			error = zfs_extend(zp, off+len);
1812	}
1813	if (error || !log)
1814		return (error);
1815log:
1816	tx = dmu_tx_create(zfsvfs->z_os);
1817	dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE);
1818	zfs_sa_upgrade_txholds(tx, zp);
1819	error = dmu_tx_assign(tx, TXG_NOWAIT);
1820	if (error) {
1821		if (error == ERESTART) {
1822			dmu_tx_wait(tx);
1823			dmu_tx_abort(tx);
1824			goto log;
1825		}
1826		dmu_tx_abort(tx);
1827		return (error);
1828	}
1829
1830	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zfsvfs), NULL, mtime, 16);
1831	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs), NULL, ctime, 16);
1832	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_FLAGS(zfsvfs),
1833	    NULL, &zp->z_pflags, 8);
1834	zfs_tstamp_update_setup(zp, CONTENT_MODIFIED, mtime, ctime, B_TRUE);
1835	error = sa_bulk_update(zp->z_sa_hdl, bulk, count, tx);
1836	ASSERT(error == 0);
1837
1838	zfs_log_truncate(zilog, tx, TX_TRUNCATE, zp, off, len);
1839
1840	dmu_tx_commit(tx);
1841	return (0);
1842}
1843
1844void
1845zfs_create_fs(objset_t *os, cred_t *cr, nvlist_t *zplprops, dmu_tx_t *tx)
1846{
1847	zfsvfs_t	zfsvfs;
1848	uint64_t	moid, obj, sa_obj, version;
1849	uint64_t	sense = ZFS_CASE_SENSITIVE;
1850	uint64_t	norm = 0;
1851	nvpair_t	*elem;
1852	int		error;
1853	int		i;
1854	znode_t		*rootzp = NULL;
1855	vnode_t		vnode;
1856	vattr_t		vattr;
1857	znode_t		*zp;
1858	zfs_acl_ids_t	acl_ids;
1859
1860	/*
1861	 * First attempt to create master node.
1862	 */
1863	/*
1864	 * In an empty objset, there are no blocks to read and thus
1865	 * there can be no i/o errors (which we assert below).
1866	 */
1867	moid = MASTER_NODE_OBJ;
1868	error = zap_create_claim(os, moid, DMU_OT_MASTER_NODE,
1869	    DMU_OT_NONE, 0, tx);
1870	ASSERT(error == 0);
1871
1872	/*
1873	 * Set starting attributes.
1874	 */
1875	version = zfs_zpl_version_map(spa_version(dmu_objset_spa(os)));
1876	elem = NULL;
1877	while ((elem = nvlist_next_nvpair(zplprops, elem)) != NULL) {
1878		/* For the moment we expect all zpl props to be uint64_ts */
1879		uint64_t val;
1880		char *name;
1881
1882		ASSERT(nvpair_type(elem) == DATA_TYPE_UINT64);
1883		VERIFY(nvpair_value_uint64(elem, &val) == 0);
1884		name = nvpair_name(elem);
1885		if (strcmp(name, zfs_prop_to_name(ZFS_PROP_VERSION)) == 0) {
1886			if (val < version)
1887				version = val;
1888		} else {
1889			error = zap_update(os, moid, name, 8, 1, &val, tx);
1890		}
1891		ASSERT(error == 0);
1892		if (strcmp(name, zfs_prop_to_name(ZFS_PROP_NORMALIZE)) == 0)
1893			norm = val;
1894		else if (strcmp(name, zfs_prop_to_name(ZFS_PROP_CASE)) == 0)
1895			sense = val;
1896	}
1897	ASSERT(version != 0);
1898	error = zap_update(os, moid, ZPL_VERSION_STR, 8, 1, &version, tx);
1899
1900	/*
1901	 * Create zap object used for SA attribute registration
1902	 */
1903
1904	if (version >= ZPL_VERSION_SA) {
1905		sa_obj = zap_create(os, DMU_OT_SA_MASTER_NODE,
1906		    DMU_OT_NONE, 0, tx);
1907		error = zap_add(os, moid, ZFS_SA_ATTRS, 8, 1, &sa_obj, tx);
1908		ASSERT(error == 0);
1909	} else {
1910		sa_obj = 0;
1911	}
1912	/*
1913	 * Create a delete queue.
1914	 */
1915	obj = zap_create(os, DMU_OT_UNLINKED_SET, DMU_OT_NONE, 0, tx);
1916
1917	error = zap_add(os, moid, ZFS_UNLINKED_SET, 8, 1, &obj, tx);
1918	ASSERT(error == 0);
1919
1920	/*
1921	 * Create root znode.  Create minimal znode/vnode/zfsvfs
1922	 * to allow zfs_mknode to work.
1923	 */
1924	VATTR_NULL(&vattr);
1925	vattr.va_mask = AT_MODE|AT_UID|AT_GID|AT_TYPE;
1926	vattr.va_type = VDIR;
1927	vattr.va_mode = S_IFDIR|0755;
1928	vattr.va_uid = crgetuid(cr);
1929	vattr.va_gid = crgetgid(cr);
1930
1931	bzero(&zfsvfs, sizeof (zfsvfs_t));
1932
1933	rootzp = kmem_cache_alloc(znode_cache, KM_SLEEP);
1934	zfs_znode_cache_constructor(rootzp, NULL, 0);
1935	ASSERT(!POINTER_IS_VALID(rootzp->z_zfsvfs));
1936	rootzp->z_moved = 0;
1937	rootzp->z_unlinked = 0;
1938	rootzp->z_atime_dirty = 0;
1939	rootzp->z_is_sa = USE_SA(version, os);
1940
1941	vnode.v_type = VDIR;
1942	vnode.v_data = rootzp;
1943	rootzp->z_vnode = &vnode;
1944
1945	zfsvfs.z_os = os;
1946	zfsvfs.z_parent = &zfsvfs;
1947	zfsvfs.z_version = version;
1948	zfsvfs.z_use_fuids = USE_FUIDS(version, os);
1949	zfsvfs.z_use_sa = USE_SA(version, os);
1950	zfsvfs.z_norm = norm;
1951
1952	error = sa_setup(os, sa_obj, zfs_attr_table, ZPL_END,
1953	    &zfsvfs.z_attr_table);
1954
1955	ASSERT(error == 0);
1956
1957	/*
1958	 * Fold case on file systems that are always or sometimes case
1959	 * insensitive.
1960	 */
1961	if (sense == ZFS_CASE_INSENSITIVE || sense == ZFS_CASE_MIXED)
1962		zfsvfs.z_norm |= U8_TEXTPREP_TOUPPER;
1963
1964	mutex_init(&zfsvfs.z_znodes_lock, NULL, MUTEX_DEFAULT, NULL);
1965	list_create(&zfsvfs.z_all_znodes, sizeof (znode_t),
1966	    offsetof(znode_t, z_link_node));
1967
1968	for (i = 0; i != ZFS_OBJ_MTX_SZ; i++)
1969		mutex_init(&zfsvfs.z_hold_mtx[i], NULL, MUTEX_DEFAULT, NULL);
1970
1971	rootzp->z_zfsvfs = &zfsvfs;
1972	VERIFY(0 == zfs_acl_ids_create(rootzp, IS_ROOT_NODE, &vattr,
1973	    cr, NULL, &acl_ids));
1974	zfs_mknode(rootzp, &vattr, tx, cr, IS_ROOT_NODE, &zp, &acl_ids);
1975	ASSERT3P(zp, ==, rootzp);
1976	error = zap_add(os, moid, ZFS_ROOT_OBJ, 8, 1, &rootzp->z_id, tx);
1977	ASSERT(error == 0);
1978	zfs_acl_ids_free(&acl_ids);
1979	POINTER_INVALIDATE(&rootzp->z_zfsvfs);
1980
1981	sa_handle_destroy(rootzp->z_sa_hdl);
1982	rootzp->z_vnode = NULL;
1983	kmem_cache_free(znode_cache, rootzp);
1984
1985	/*
1986	 * Create shares directory
1987	 */
1988
1989	error = zfs_create_share_dir(&zfsvfs, tx);
1990
1991	ASSERT(error == 0);
1992
1993	for (i = 0; i != ZFS_OBJ_MTX_SZ; i++)
1994		mutex_destroy(&zfsvfs.z_hold_mtx[i]);
1995}
1996
1997#endif /* _KERNEL */
1998
1999static int
2000zfs_sa_setup(objset_t *osp, sa_attr_type_t **sa_table)
2001{
2002	uint64_t sa_obj = 0;
2003	int error;
2004
2005	error = zap_lookup(osp, MASTER_NODE_OBJ, ZFS_SA_ATTRS, 8, 1, &sa_obj);
2006	if (error != 0 && error != ENOENT)
2007		return (error);
2008
2009	error = sa_setup(osp, sa_obj, zfs_attr_table, ZPL_END, sa_table);
2010	return (error);
2011}
2012
2013static int
2014zfs_grab_sa_handle(objset_t *osp, uint64_t obj, sa_handle_t **hdlp,
2015    dmu_buf_t **db, void *tag)
2016{
2017	dmu_object_info_t doi;
2018	int error;
2019
2020	if ((error = sa_buf_hold(osp, obj, tag, db)) != 0)
2021		return (error);
2022
2023	dmu_object_info_from_db(*db, &doi);
2024	if ((doi.doi_bonus_type != DMU_OT_SA &&
2025	    doi.doi_bonus_type != DMU_OT_ZNODE) ||
2026	    doi.doi_bonus_type == DMU_OT_ZNODE &&
2027	    doi.doi_bonus_size < sizeof (znode_phys_t)) {
2028		sa_buf_rele(*db, tag);
2029		return (ENOTSUP);
2030	}
2031
2032	error = sa_handle_get(osp, obj, NULL, SA_HDL_PRIVATE, hdlp);
2033	if (error != 0) {
2034		sa_buf_rele(*db, tag);
2035		return (error);
2036	}
2037
2038	return (0);
2039}
2040
2041void
2042zfs_release_sa_handle(sa_handle_t *hdl, dmu_buf_t *db, void *tag)
2043{
2044	sa_handle_destroy(hdl);
2045	sa_buf_rele(db, tag);
2046}
2047
2048/*
2049 * Given an object number, return its parent object number and whether
2050 * or not the object is an extended attribute directory.
2051 */
2052static int
2053zfs_obj_to_pobj(objset_t *osp, sa_handle_t *hdl, sa_attr_type_t *sa_table,
2054    uint64_t *pobjp, int *is_xattrdir)
2055{
2056	uint64_t parent;
2057	uint64_t pflags;
2058	uint64_t mode;
2059	uint64_t parent_mode;
2060	sa_bulk_attr_t bulk[3];
2061	sa_handle_t *sa_hdl;
2062	dmu_buf_t *sa_db;
2063	int count = 0;
2064	int error;
2065
2066	SA_ADD_BULK_ATTR(bulk, count, sa_table[ZPL_PARENT], NULL,
2067	    &parent, sizeof (parent));
2068	SA_ADD_BULK_ATTR(bulk, count, sa_table[ZPL_FLAGS], NULL,
2069	    &pflags, sizeof (pflags));
2070	SA_ADD_BULK_ATTR(bulk, count, sa_table[ZPL_MODE], NULL,
2071	    &mode, sizeof (mode));
2072
2073	if ((error = sa_bulk_lookup(hdl, bulk, count)) != 0)
2074		return (error);
2075
2076	/*
2077	 * When a link is removed its parent pointer is not changed and will
2078	 * be invalid.  There are two cases where a link is removed but the
2079	 * file stays around, when it goes to the delete queue and when there
2080	 * are additional links.
2081	 */
2082	error = zfs_grab_sa_handle(osp, parent, &sa_hdl, &sa_db, FTAG);
2083	if (error != 0)
2084		return (error);
2085
2086	error = sa_lookup(sa_hdl, ZPL_MODE, &parent_mode, sizeof (parent_mode));
2087	zfs_release_sa_handle(sa_hdl, sa_db, FTAG);
2088	if (error != 0)
2089		return (error);
2090
2091	*is_xattrdir = ((pflags & ZFS_XATTR) != 0) && S_ISDIR(mode);
2092
2093	/*
2094	 * Extended attributes can be applied to files, directories, etc.
2095	 * Otherwise the parent must be a directory.
2096	 */
2097	if (!*is_xattrdir && !S_ISDIR(parent_mode))
2098		return (EINVAL);
2099
2100	*pobjp = parent;
2101
2102	return (0);
2103}
2104
2105/*
2106 * Given an object number, return some zpl level statistics
2107 */
2108static int
2109zfs_obj_to_stats_impl(sa_handle_t *hdl, sa_attr_type_t *sa_table,
2110    zfs_stat_t *sb)
2111{
2112	sa_bulk_attr_t bulk[4];
2113	int count = 0;
2114
2115	SA_ADD_BULK_ATTR(bulk, count, sa_table[ZPL_MODE], NULL,
2116	    &sb->zs_mode, sizeof (sb->zs_mode));
2117	SA_ADD_BULK_ATTR(bulk, count, sa_table[ZPL_GEN], NULL,
2118	    &sb->zs_gen, sizeof (sb->zs_gen));
2119	SA_ADD_BULK_ATTR(bulk, count, sa_table[ZPL_LINKS], NULL,
2120	    &sb->zs_links, sizeof (sb->zs_links));
2121	SA_ADD_BULK_ATTR(bulk, count, sa_table[ZPL_CTIME], NULL,
2122	    &sb->zs_ctime, sizeof (sb->zs_ctime));
2123
2124	return (sa_bulk_lookup(hdl, bulk, count));
2125}
2126
2127static int
2128zfs_obj_to_path_impl(objset_t *osp, uint64_t obj, sa_handle_t *hdl,
2129    sa_attr_type_t *sa_table, char *buf, int len)
2130{
2131	sa_handle_t *sa_hdl;
2132	sa_handle_t *prevhdl = NULL;
2133	dmu_buf_t *prevdb = NULL;
2134	dmu_buf_t *sa_db = NULL;
2135	char *path = buf + len - 1;
2136	int error;
2137
2138	*path = '\0';
2139	sa_hdl = hdl;
2140
2141	for (;;) {
2142		uint64_t pobj;
2143		char component[MAXNAMELEN + 2];
2144		size_t complen;
2145		int is_xattrdir;
2146
2147		if (prevdb)
2148			zfs_release_sa_handle(prevhdl, prevdb, FTAG);
2149
2150		if ((error = zfs_obj_to_pobj(osp, sa_hdl, sa_table, &pobj,
2151		    &is_xattrdir)) != 0)
2152			break;
2153
2154		if (pobj == obj) {
2155			if (path[0] != '/')
2156				*--path = '/';
2157			break;
2158		}
2159
2160		component[0] = '/';
2161		if (is_xattrdir) {
2162			(void) sprintf(component + 1, "<xattrdir>");
2163		} else {
2164			error = zap_value_search(osp, pobj, obj,
2165			    ZFS_DIRENT_OBJ(-1ULL), component + 1);
2166			if (error != 0)
2167				break;
2168		}
2169
2170		complen = strlen(component);
2171		path -= complen;
2172		ASSERT(path >= buf);
2173		bcopy(component, path, complen);
2174		obj = pobj;
2175
2176		if (sa_hdl != hdl) {
2177			prevhdl = sa_hdl;
2178			prevdb = sa_db;
2179		}
2180		error = zfs_grab_sa_handle(osp, obj, &sa_hdl, &sa_db, FTAG);
2181		if (error != 0) {
2182			sa_hdl = prevhdl;
2183			sa_db = prevdb;
2184			break;
2185		}
2186	}
2187
2188	if (sa_hdl != NULL && sa_hdl != hdl) {
2189		ASSERT(sa_db != NULL);
2190		zfs_release_sa_handle(sa_hdl, sa_db, FTAG);
2191	}
2192
2193	if (error == 0)
2194		(void) memmove(buf, path, buf + len - path);
2195
2196	return (error);
2197}
2198
2199int
2200zfs_obj_to_path(objset_t *osp, uint64_t obj, char *buf, int len)
2201{
2202	sa_attr_type_t *sa_table;
2203	sa_handle_t *hdl;
2204	dmu_buf_t *db;
2205	int error;
2206
2207	error = zfs_sa_setup(osp, &sa_table);
2208	if (error != 0)
2209		return (error);
2210
2211	error = zfs_grab_sa_handle(osp, obj, &hdl, &db, FTAG);
2212	if (error != 0)
2213		return (error);
2214
2215	error = zfs_obj_to_path_impl(osp, obj, hdl, sa_table, buf, len);
2216
2217	zfs_release_sa_handle(hdl, db, FTAG);
2218	return (error);
2219}
2220
2221int
2222zfs_obj_to_stats(objset_t *osp, uint64_t obj, zfs_stat_t *sb,
2223    char *buf, int len)
2224{
2225	char *path = buf + len - 1;
2226	sa_attr_type_t *sa_table;
2227	sa_handle_t *hdl;
2228	dmu_buf_t *db;
2229	int error;
2230
2231	*path = '\0';
2232
2233	error = zfs_sa_setup(osp, &sa_table);
2234	if (error != 0)
2235		return (error);
2236
2237	error = zfs_grab_sa_handle(osp, obj, &hdl, &db, FTAG);
2238	if (error != 0)
2239		return (error);
2240
2241	error = zfs_obj_to_stats_impl(hdl, sa_table, sb);
2242	if (error != 0) {
2243		zfs_release_sa_handle(hdl, db, FTAG);
2244		return (error);
2245	}
2246
2247	error = zfs_obj_to_path_impl(osp, obj, hdl, sa_table, buf, len);
2248
2249	zfs_release_sa_handle(hdl, db, FTAG);
2250	return (error);
2251}
2252