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