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