]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_znode.c
MFS11 r341828: Resolve a hang in ZFS during vnode reclaimation
[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                 if (zp->z_unlinked) {
1159                         err = SET_ERROR(ENOENT);
1160                 } else {
1161                         vp = ZTOV(zp);
1162                         /*
1163                          * Don't let the vnode disappear after
1164                          * ZFS_OBJ_HOLD_EXIT.
1165                          */
1166                         VN_HOLD(vp);
1167                         *zpp = zp;
1168                         err = 0;
1169                 }
1170
1171                 sa_buf_rele(db, NULL);
1172                 ZFS_OBJ_HOLD_EXIT(zfsvfs, obj_num);
1173
1174                 if (err) {
1175                         getnewvnode_drop_reserve();
1176                         return (err);
1177                 }
1178
1179                 locked = VOP_ISLOCKED(vp);
1180                 VI_LOCK(vp);
1181                 if ((vp->v_iflag & VI_DOOMED) != 0 &&
1182                     locked != LK_EXCLUSIVE) {
1183                         /*
1184                          * The vnode is doomed and this thread doesn't
1185                          * hold the exclusive lock on it, so the vnode
1186                          * must be being reclaimed by another thread.
1187                          * Otherwise the doomed vnode is being reclaimed
1188                          * by this thread and zfs_zget is called from
1189                          * ZIL internals.
1190                          */
1191                         VI_UNLOCK(vp);
1192
1193                         /*
1194                          * XXX vrele() locks the vnode when the last reference
1195                          * is dropped.  Although in this case the vnode is
1196                          * doomed / dead and so no inactivation is required,
1197                          * the vnode lock is still acquired.  That could result
1198                          * in a LOR with z_teardown_lock if another thread holds
1199                          * the vnode's lock and tries to take z_teardown_lock.
1200                          * But that is only possible if the other thread peforms
1201                          * a ZFS vnode operation on the vnode.  That either
1202                          * should not happen if the vnode is dead or the thread
1203                          * should also have a refrence to the vnode and thus
1204                          * our reference is not last.
1205                          */
1206                         VN_RELE(vp);
1207                         goto again;
1208                 }
1209                 VI_UNLOCK(vp);
1210                 getnewvnode_drop_reserve();
1211                 return (err);
1212         }
1213
1214         /*
1215          * Not found create new znode/vnode
1216          * but only if file exists.
1217          *
1218          * There is a small window where zfs_vget() could
1219          * find this object while a file create is still in
1220          * progress.  This is checked for in zfs_znode_alloc()
1221          *
1222          * if zfs_znode_alloc() fails it will drop the hold on the
1223          * bonus buffer.
1224          */
1225         zp = zfs_znode_alloc(zfsvfs, db, doi.doi_data_block_size,
1226             doi.doi_bonus_type, NULL);
1227         if (zp == NULL) {
1228                 err = SET_ERROR(ENOENT);
1229         } else {
1230                 *zpp = zp;
1231         }
1232         if (err == 0) {
1233                 vnode_t *vp = ZTOV(zp);
1234
1235                 err = insmntque(vp, zfsvfs->z_vfs);
1236                 if (err == 0) {
1237                         vp->v_hash = obj_num;
1238                         VOP_UNLOCK(vp, 0);
1239                 } else {
1240                         zp->z_vnode = NULL;
1241                         zfs_znode_dmu_fini(zp);
1242                         zfs_znode_free(zp);
1243                         *zpp = NULL;
1244                 }
1245         }
1246         ZFS_OBJ_HOLD_EXIT(zfsvfs, obj_num);
1247         getnewvnode_drop_reserve();
1248         return (err);
1249 }
1250
1251 int
1252 zfs_rezget(znode_t *zp)
1253 {
1254         zfsvfs_t *zfsvfs = zp->z_zfsvfs;
1255         dmu_object_info_t doi;
1256         dmu_buf_t *db;
1257         vnode_t *vp;
1258         uint64_t obj_num = zp->z_id;
1259         uint64_t mode, size;
1260         sa_bulk_attr_t bulk[8];
1261         int err;
1262         int count = 0;
1263         uint64_t gen;
1264
1265         /*
1266          * Remove cached pages before reloading the znode, so that they are not
1267          * lingering after we run into any error.  Ideally, we should vgone()
1268          * the vnode in case of error, but currently we cannot do that
1269          * because of the LOR between the vnode lock and z_teardown_lock.
1270          * So, instead, we have to "doom" the znode in the illumos style.
1271          */
1272         vp = ZTOV(zp);
1273         vn_pages_remove(vp, 0, 0);
1274
1275         ZFS_OBJ_HOLD_ENTER(zfsvfs, obj_num);
1276
1277         mutex_enter(&zp->z_acl_lock);
1278         if (zp->z_acl_cached) {
1279                 zfs_acl_free(zp->z_acl_cached);
1280                 zp->z_acl_cached = NULL;
1281         }
1282
1283         mutex_exit(&zp->z_acl_lock);
1284         ASSERT(zp->z_sa_hdl == NULL);
1285         err = sa_buf_hold(zfsvfs->z_os, obj_num, NULL, &db);
1286         if (err) {
1287                 ZFS_OBJ_HOLD_EXIT(zfsvfs, obj_num);
1288                 return (err);
1289         }
1290
1291         dmu_object_info_from_db(db, &doi);
1292         if (doi.doi_bonus_type != DMU_OT_SA &&
1293             (doi.doi_bonus_type != DMU_OT_ZNODE ||
1294             (doi.doi_bonus_type == DMU_OT_ZNODE &&
1295             doi.doi_bonus_size < sizeof (znode_phys_t)))) {
1296                 sa_buf_rele(db, NULL);
1297                 ZFS_OBJ_HOLD_EXIT(zfsvfs, obj_num);
1298                 return (SET_ERROR(EINVAL));
1299         }
1300
1301         zfs_znode_sa_init(zfsvfs, zp, db, doi.doi_bonus_type, NULL);
1302         size = zp->z_size;
1303
1304         /* reload cached values */
1305         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_GEN(zfsvfs), NULL,
1306             &gen, sizeof (gen));
1307         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_SIZE(zfsvfs), NULL,
1308             &zp->z_size, sizeof (zp->z_size));
1309         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_LINKS(zfsvfs), NULL,
1310             &zp->z_links, sizeof (zp->z_links));
1311         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_FLAGS(zfsvfs), NULL,
1312             &zp->z_pflags, sizeof (zp->z_pflags));
1313         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_ATIME(zfsvfs), NULL,
1314             &zp->z_atime, sizeof (zp->z_atime));
1315         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_UID(zfsvfs), NULL,
1316             &zp->z_uid, sizeof (zp->z_uid));
1317         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_GID(zfsvfs), NULL,
1318             &zp->z_gid, sizeof (zp->z_gid));
1319         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MODE(zfsvfs), NULL,
1320             &mode, sizeof (mode));
1321
1322         if (sa_bulk_lookup(zp->z_sa_hdl, bulk, count)) {
1323                 zfs_znode_dmu_fini(zp);
1324                 ZFS_OBJ_HOLD_EXIT(zfsvfs, obj_num);
1325                 return (SET_ERROR(EIO));
1326         }
1327
1328         zp->z_mode = mode;
1329
1330         if (gen != zp->z_gen) {
1331                 zfs_znode_dmu_fini(zp);
1332                 ZFS_OBJ_HOLD_EXIT(zfsvfs, obj_num);
1333                 return (SET_ERROR(EIO));
1334         }
1335
1336         /*
1337          * It is highly improbable but still quite possible that two
1338          * objects in different datasets are created with the same
1339          * object numbers and in transaction groups with the same
1340          * numbers.  znodes corresponding to those objects would
1341          * have the same z_id and z_gen, but their other attributes
1342          * may be different.
1343          * zfs recv -F may replace one of such objects with the other.
1344          * As a result file properties recorded in the replaced
1345          * object's vnode may no longer match the received object's
1346          * properties.  At present the only cached property is the
1347          * files type recorded in v_type.
1348          * So, handle this case by leaving the old vnode and znode
1349          * disassociated from the actual object.  A new vnode and a
1350          * znode will be created if the object is accessed
1351          * (e.g. via a look-up).  The old vnode and znode will be
1352          * recycled when the last vnode reference is dropped.
1353          */
1354         if (vp->v_type != IFTOVT((mode_t)zp->z_mode)) {
1355                 zfs_znode_dmu_fini(zp);
1356                 ZFS_OBJ_HOLD_EXIT(zfsvfs, obj_num);
1357                 return (SET_ERROR(EIO));
1358         }
1359
1360         /*
1361          * If the file has zero links, then it has been unlinked on the send
1362          * side and it must be in the received unlinked set.
1363          * We call zfs_znode_dmu_fini() now to prevent any accesses to the
1364          * stale data and to prevent automatical removal of the file in
1365          * zfs_zinactive().  The file will be removed either when it is removed
1366          * on the send side and the next incremental stream is received or
1367          * when the unlinked set gets processed.
1368          */
1369         zp->z_unlinked = (zp->z_links == 0);
1370         if (zp->z_unlinked) {
1371                 zfs_znode_dmu_fini(zp);
1372                 ZFS_OBJ_HOLD_EXIT(zfsvfs, obj_num);
1373                 return (0);
1374         }
1375
1376         zp->z_blksz = doi.doi_data_block_size;
1377         if (zp->z_size != size)
1378                 vnode_pager_setsize(vp, zp->z_size);
1379
1380         ZFS_OBJ_HOLD_EXIT(zfsvfs, obj_num);
1381
1382         return (0);
1383 }
1384
1385 void
1386 zfs_znode_delete(znode_t *zp, dmu_tx_t *tx)
1387 {
1388         zfsvfs_t *zfsvfs = zp->z_zfsvfs;
1389         objset_t *os = zfsvfs->z_os;
1390         uint64_t obj = zp->z_id;
1391         uint64_t acl_obj = zfs_external_acl(zp);
1392
1393         ZFS_OBJ_HOLD_ENTER(zfsvfs, obj);
1394         if (acl_obj) {
1395                 VERIFY(!zp->z_is_sa);
1396                 VERIFY(0 == dmu_object_free(os, acl_obj, tx));
1397         }
1398         VERIFY(0 == dmu_object_free(os, obj, tx));
1399         zfs_znode_dmu_fini(zp);
1400         ZFS_OBJ_HOLD_EXIT(zfsvfs, obj);
1401         zfs_znode_free(zp);
1402 }
1403
1404 void
1405 zfs_zinactive(znode_t *zp)
1406 {
1407         zfsvfs_t *zfsvfs = zp->z_zfsvfs;
1408         uint64_t z_id = zp->z_id;
1409
1410         ASSERT(zp->z_sa_hdl);
1411
1412         /*
1413          * Don't allow a zfs_zget() while were trying to release this znode
1414          */
1415         ZFS_OBJ_HOLD_ENTER(zfsvfs, z_id);
1416
1417         /*
1418          * If this was the last reference to a file with no links, remove
1419          * the file from the file system unless the file system is mounted
1420          * read-only.  That can happen, for example, if the file system was
1421          * originally read-write, the file was opened, then unlinked and
1422          * the file system was made read-only before the file was finally
1423          * closed.  The file will remain in the unlinked set.
1424          */
1425         if (zp->z_unlinked) {
1426                 ASSERT(!zfsvfs->z_issnap);
1427                 if ((zfsvfs->z_vfs->vfs_flag & VFS_RDONLY) == 0) {
1428                         ZFS_OBJ_HOLD_EXIT(zfsvfs, z_id);
1429                         zfs_rmnode(zp);
1430                         return;
1431                 }
1432         }
1433
1434         zfs_znode_dmu_fini(zp);
1435         ZFS_OBJ_HOLD_EXIT(zfsvfs, z_id);
1436         zfs_znode_free(zp);
1437 }
1438
1439 void
1440 zfs_znode_free(znode_t *zp)
1441 {
1442         zfsvfs_t *zfsvfs = zp->z_zfsvfs;
1443
1444         ASSERT(zp->z_sa_hdl == NULL);
1445         zp->z_vnode = NULL;
1446         mutex_enter(&zfsvfs->z_znodes_lock);
1447         POINTER_INVALIDATE(&zp->z_zfsvfs);
1448         list_remove(&zfsvfs->z_all_znodes, zp);
1449         mutex_exit(&zfsvfs->z_znodes_lock);
1450
1451         if (zp->z_acl_cached) {
1452                 zfs_acl_free(zp->z_acl_cached);
1453                 zp->z_acl_cached = NULL;
1454         }
1455
1456         kmem_cache_free(znode_cache, zp);
1457
1458 #ifdef illumos
1459         VFS_RELE(zfsvfs->z_vfs);
1460 #endif
1461 }
1462
1463 void
1464 zfs_tstamp_update_setup(znode_t *zp, uint_t flag, uint64_t mtime[2],
1465     uint64_t ctime[2], boolean_t have_tx)
1466 {
1467         timestruc_t     now;
1468
1469         vfs_timestamp(&now);
1470
1471         if (have_tx) {  /* will sa_bulk_update happen really soon? */
1472                 zp->z_atime_dirty = 0;
1473                 zp->z_seq++;
1474         } else {
1475                 zp->z_atime_dirty = 1;
1476         }
1477
1478         if (flag & AT_ATIME) {
1479                 ZFS_TIME_ENCODE(&now, zp->z_atime);
1480         }
1481
1482         if (flag & AT_MTIME) {
1483                 ZFS_TIME_ENCODE(&now, mtime);
1484                 if (zp->z_zfsvfs->z_use_fuids) {
1485                         zp->z_pflags |= (ZFS_ARCHIVE |
1486                             ZFS_AV_MODIFIED);
1487                 }
1488         }
1489
1490         if (flag & AT_CTIME) {
1491                 ZFS_TIME_ENCODE(&now, ctime);
1492                 if (zp->z_zfsvfs->z_use_fuids)
1493                         zp->z_pflags |= ZFS_ARCHIVE;
1494         }
1495 }
1496
1497 /*
1498  * Grow the block size for a file.
1499  *
1500  *      IN:     zp      - znode of file to free data in.
1501  *              size    - requested block size
1502  *              tx      - open transaction.
1503  *
1504  * NOTE: this function assumes that the znode is write locked.
1505  */
1506 void
1507 zfs_grow_blocksize(znode_t *zp, uint64_t size, dmu_tx_t *tx)
1508 {
1509         int             error;
1510         u_longlong_t    dummy;
1511
1512         if (size <= zp->z_blksz)
1513                 return;
1514         /*
1515          * If the file size is already greater than the current blocksize,
1516          * we will not grow.  If there is more than one block in a file,
1517          * the blocksize cannot change.
1518          */
1519         if (zp->z_blksz && zp->z_size > zp->z_blksz)
1520                 return;
1521
1522         error = dmu_object_set_blocksize(zp->z_zfsvfs->z_os, zp->z_id,
1523             size, 0, tx);
1524
1525         if (error == ENOTSUP)
1526                 return;
1527         ASSERT0(error);
1528
1529         /* What blocksize did we actually get? */
1530         dmu_object_size_from_db(sa_get_db(zp->z_sa_hdl), &zp->z_blksz, &dummy);
1531 }
1532
1533 #ifdef illumos
1534 /*
1535  * This is a dummy interface used when pvn_vplist_dirty() should *not*
1536  * be calling back into the fs for a putpage().  E.g.: when truncating
1537  * a file, the pages being "thrown away* don't need to be written out.
1538  */
1539 /* ARGSUSED */
1540 static int
1541 zfs_no_putpage(vnode_t *vp, page_t *pp, u_offset_t *offp, size_t *lenp,
1542     int flags, cred_t *cr)
1543 {
1544         ASSERT(0);
1545         return (0);
1546 }
1547 #endif
1548
1549 /*
1550  * Increase the file length
1551  *
1552  *      IN:     zp      - znode of file to free data in.
1553  *              end     - new end-of-file
1554  *
1555  *      RETURN: 0 on success, error code on failure
1556  */
1557 static int
1558 zfs_extend(znode_t *zp, uint64_t end)
1559 {
1560         zfsvfs_t *zfsvfs = zp->z_zfsvfs;
1561         dmu_tx_t *tx;
1562         rl_t *rl;
1563         uint64_t newblksz;
1564         int error;
1565
1566         /*
1567          * We will change zp_size, lock the whole file.
1568          */
1569         rl = zfs_range_lock(zp, 0, UINT64_MAX, RL_WRITER);
1570
1571         /*
1572          * Nothing to do if file already at desired length.
1573          */
1574         if (end <= zp->z_size) {
1575                 zfs_range_unlock(rl);
1576                 return (0);
1577         }
1578         tx = dmu_tx_create(zfsvfs->z_os);
1579         dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE);
1580         zfs_sa_upgrade_txholds(tx, zp);
1581         if (end > zp->z_blksz &&
1582             (!ISP2(zp->z_blksz) || zp->z_blksz < zfsvfs->z_max_blksz)) {
1583                 /*
1584                  * We are growing the file past the current block size.
1585                  */
1586                 if (zp->z_blksz > zp->z_zfsvfs->z_max_blksz) {
1587                         /*
1588                          * File's blocksize is already larger than the
1589                          * "recordsize" property.  Only let it grow to
1590                          * the next power of 2.
1591                          */
1592                         ASSERT(!ISP2(zp->z_blksz));
1593                         newblksz = MIN(end, 1 << highbit64(zp->z_blksz));
1594                 } else {
1595                         newblksz = MIN(end, zp->z_zfsvfs->z_max_blksz);
1596                 }
1597                 dmu_tx_hold_write(tx, zp->z_id, 0, newblksz);
1598         } else {
1599                 newblksz = 0;
1600         }
1601
1602         error = dmu_tx_assign(tx, TXG_WAIT);
1603         if (error) {
1604                 dmu_tx_abort(tx);
1605                 zfs_range_unlock(rl);
1606                 return (error);
1607         }
1608
1609         if (newblksz)
1610                 zfs_grow_blocksize(zp, newblksz, tx);
1611
1612         zp->z_size = end;
1613
1614         VERIFY(0 == sa_update(zp->z_sa_hdl, SA_ZPL_SIZE(zp->z_zfsvfs),
1615             &zp->z_size, sizeof (zp->z_size), tx));
1616
1617         vnode_pager_setsize(ZTOV(zp), end);
1618
1619         zfs_range_unlock(rl);
1620
1621         dmu_tx_commit(tx);
1622
1623         return (0);
1624 }
1625
1626 /*
1627  * Free space in a file.
1628  *
1629  *      IN:     zp      - znode of file to free data in.
1630  *              off     - start of section to free.
1631  *              len     - length of section to free.
1632  *
1633  *      RETURN: 0 on success, error code on failure
1634  */
1635 static int
1636 zfs_free_range(znode_t *zp, uint64_t off, uint64_t len)
1637 {
1638         zfsvfs_t *zfsvfs = zp->z_zfsvfs;
1639         rl_t *rl;
1640         int error;
1641
1642         /*
1643          * Lock the range being freed.
1644          */
1645         rl = zfs_range_lock(zp, off, len, RL_WRITER);
1646
1647         /*
1648          * Nothing to do if file already at desired length.
1649          */
1650         if (off >= zp->z_size) {
1651                 zfs_range_unlock(rl);
1652                 return (0);
1653         }
1654
1655         if (off + len > zp->z_size)
1656                 len = zp->z_size - off;
1657
1658         error = dmu_free_long_range(zfsvfs->z_os, zp->z_id, off, len);
1659
1660         if (error == 0) {
1661                 /*
1662                  * In FreeBSD we cannot free block in the middle of a file,
1663                  * but only at the end of a file, so this code path should
1664                  * never happen.
1665                  */
1666                 vnode_pager_setsize(ZTOV(zp), off);
1667         }
1668
1669         zfs_range_unlock(rl);
1670
1671         return (error);
1672 }
1673
1674 /*
1675  * Truncate a file
1676  *
1677  *      IN:     zp      - znode of file to free data in.
1678  *              end     - new end-of-file.
1679  *
1680  *      RETURN: 0 on success, error code on failure
1681  */
1682 static int
1683 zfs_trunc(znode_t *zp, uint64_t end)
1684 {
1685         zfsvfs_t *zfsvfs = zp->z_zfsvfs;
1686         vnode_t *vp = ZTOV(zp);
1687         dmu_tx_t *tx;
1688         rl_t *rl;
1689         int error;
1690         sa_bulk_attr_t bulk[2];
1691         int count = 0;
1692
1693         /*
1694          * We will change zp_size, lock the whole file.
1695          */
1696         rl = zfs_range_lock(zp, 0, UINT64_MAX, RL_WRITER);
1697
1698         /*
1699          * Nothing to do if file already at desired length.
1700          */
1701         if (end >= zp->z_size) {
1702                 zfs_range_unlock(rl);
1703                 return (0);
1704         }
1705
1706         error = dmu_free_long_range(zfsvfs->z_os, zp->z_id, end,  -1);
1707         if (error) {
1708                 zfs_range_unlock(rl);
1709                 return (error);
1710         }
1711         tx = dmu_tx_create(zfsvfs->z_os);
1712         dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE);
1713         zfs_sa_upgrade_txholds(tx, zp);
1714         dmu_tx_mark_netfree(tx);
1715         error = dmu_tx_assign(tx, TXG_WAIT);
1716         if (error) {
1717                 dmu_tx_abort(tx);
1718                 zfs_range_unlock(rl);
1719                 return (error);
1720         }
1721
1722         zp->z_size = end;
1723         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_SIZE(zfsvfs),
1724             NULL, &zp->z_size, sizeof (zp->z_size));
1725
1726         if (end == 0) {
1727                 zp->z_pflags &= ~ZFS_SPARSE;
1728                 SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_FLAGS(zfsvfs),
1729                     NULL, &zp->z_pflags, 8);
1730         }
1731         VERIFY(sa_bulk_update(zp->z_sa_hdl, bulk, count, tx) == 0);
1732
1733         dmu_tx_commit(tx);
1734
1735         /*
1736          * Clear any mapped pages in the truncated region.  This has to
1737          * happen outside of the transaction to avoid the possibility of
1738          * a deadlock with someone trying to push a page that we are
1739          * about to invalidate.
1740          */
1741         vnode_pager_setsize(vp, end);
1742
1743         zfs_range_unlock(rl);
1744
1745         return (0);
1746 }
1747
1748 /*
1749  * Free space in a file
1750  *
1751  *      IN:     zp      - znode of file to free data in.
1752  *              off     - start of range
1753  *              len     - end of range (0 => EOF)
1754  *              flag    - current file open mode flags.
1755  *              log     - TRUE if this action should be logged
1756  *
1757  *      RETURN: 0 on success, error code on failure
1758  */
1759 int
1760 zfs_freesp(znode_t *zp, uint64_t off, uint64_t len, int flag, boolean_t log)
1761 {
1762         vnode_t *vp = ZTOV(zp);
1763         dmu_tx_t *tx;
1764         zfsvfs_t *zfsvfs = zp->z_zfsvfs;
1765         zilog_t *zilog = zfsvfs->z_log;
1766         uint64_t mode;
1767         uint64_t mtime[2], ctime[2];
1768         sa_bulk_attr_t bulk[3];
1769         int count = 0;
1770         int error;
1771
1772         if ((error = sa_lookup(zp->z_sa_hdl, SA_ZPL_MODE(zfsvfs), &mode,
1773             sizeof (mode))) != 0)
1774                 return (error);
1775
1776         if (off > zp->z_size) {
1777                 error =  zfs_extend(zp, off+len);
1778                 if (error == 0 && log)
1779                         goto log;
1780                 else
1781                         return (error);
1782         }
1783
1784         /*
1785          * Check for any locks in the region to be freed.
1786          */
1787
1788         if (MANDLOCK(vp, (mode_t)mode)) {
1789                 uint64_t length = (len ? len : zp->z_size - off);
1790                 if (error = chklock(vp, FWRITE, off, length, flag, NULL))
1791                         return (error);
1792         }
1793
1794         if (len == 0) {
1795                 error = zfs_trunc(zp, off);
1796         } else {
1797                 if ((error = zfs_free_range(zp, off, len)) == 0 &&
1798                     off + len > zp->z_size)
1799                         error = zfs_extend(zp, off+len);
1800         }
1801         if (error || !log)
1802                 return (error);
1803 log:
1804         tx = dmu_tx_create(zfsvfs->z_os);
1805         dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE);
1806         zfs_sa_upgrade_txholds(tx, zp);
1807         error = dmu_tx_assign(tx, TXG_WAIT);
1808         if (error) {
1809                 dmu_tx_abort(tx);
1810                 return (error);
1811         }
1812
1813         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zfsvfs), NULL, mtime, 16);
1814         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs), NULL, ctime, 16);
1815         SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_FLAGS(zfsvfs),
1816             NULL, &zp->z_pflags, 8);
1817         zfs_tstamp_update_setup(zp, CONTENT_MODIFIED, mtime, ctime, B_TRUE);
1818         error = sa_bulk_update(zp->z_sa_hdl, bulk, count, tx);
1819         ASSERT(error == 0);
1820
1821         zfs_log_truncate(zilog, tx, TX_TRUNCATE, zp, off, len);
1822
1823         dmu_tx_commit(tx);
1824         return (0);
1825 }
1826
1827 void
1828 zfs_create_fs(objset_t *os, cred_t *cr, nvlist_t *zplprops, dmu_tx_t *tx)
1829 {
1830         uint64_t        moid, obj, sa_obj, version;
1831         uint64_t        sense = ZFS_CASE_SENSITIVE;
1832         uint64_t        norm = 0;
1833         nvpair_t        *elem;
1834         int             error;
1835         int             i;
1836         znode_t         *rootzp = NULL;
1837         zfsvfs_t        *zfsvfs;
1838         vattr_t         vattr;
1839         znode_t         *zp;
1840         zfs_acl_ids_t   acl_ids;
1841
1842         /*
1843          * First attempt to create master node.
1844          */
1845         /*
1846          * In an empty objset, there are no blocks to read and thus
1847          * there can be no i/o errors (which we assert below).
1848          */
1849         moid = MASTER_NODE_OBJ;
1850         error = zap_create_claim(os, moid, DMU_OT_MASTER_NODE,
1851             DMU_OT_NONE, 0, tx);
1852         ASSERT(error == 0);
1853
1854         /*
1855          * Set starting attributes.
1856          */
1857         version = zfs_zpl_version_map(spa_version(dmu_objset_spa(os)));
1858         elem = NULL;
1859         while ((elem = nvlist_next_nvpair(zplprops, elem)) != NULL) {
1860                 /* For the moment we expect all zpl props to be uint64_ts */
1861                 uint64_t val;
1862                 char *name;
1863
1864                 ASSERT(nvpair_type(elem) == DATA_TYPE_UINT64);
1865                 VERIFY(nvpair_value_uint64(elem, &val) == 0);
1866                 name = nvpair_name(elem);
1867                 if (strcmp(name, zfs_prop_to_name(ZFS_PROP_VERSION)) == 0) {
1868                         if (val < version)
1869                                 version = val;
1870                 } else {
1871                         error = zap_update(os, moid, name, 8, 1, &val, tx);
1872                 }
1873                 ASSERT(error == 0);
1874                 if (strcmp(name, zfs_prop_to_name(ZFS_PROP_NORMALIZE)) == 0)
1875                         norm = val;
1876                 else if (strcmp(name, zfs_prop_to_name(ZFS_PROP_CASE)) == 0)
1877                         sense = val;
1878         }
1879         ASSERT(version != 0);
1880         error = zap_update(os, moid, ZPL_VERSION_STR, 8, 1, &version, tx);
1881
1882         /*
1883          * Create zap object used for SA attribute registration
1884          */
1885
1886         if (version >= ZPL_VERSION_SA) {
1887                 sa_obj = zap_create(os, DMU_OT_SA_MASTER_NODE,
1888                     DMU_OT_NONE, 0, tx);
1889                 error = zap_add(os, moid, ZFS_SA_ATTRS, 8, 1, &sa_obj, tx);
1890                 ASSERT(error == 0);
1891         } else {
1892                 sa_obj = 0;
1893         }
1894         /*
1895          * Create a delete queue.
1896          */
1897         obj = zap_create(os, DMU_OT_UNLINKED_SET, DMU_OT_NONE, 0, tx);
1898
1899         error = zap_add(os, moid, ZFS_UNLINKED_SET, 8, 1, &obj, tx);
1900         ASSERT(error == 0);
1901
1902         /*
1903          * Create root znode.  Create minimal znode/vnode/zfsvfs
1904          * to allow zfs_mknode to work.
1905          */
1906         VATTR_NULL(&vattr);
1907         vattr.va_mask = AT_MODE|AT_UID|AT_GID|AT_TYPE;
1908         vattr.va_type = VDIR;
1909         vattr.va_mode = S_IFDIR|0755;
1910         vattr.va_uid = crgetuid(cr);
1911         vattr.va_gid = crgetgid(cr);
1912
1913         zfsvfs = kmem_zalloc(sizeof (zfsvfs_t), KM_SLEEP);
1914
1915         rootzp = kmem_cache_alloc(znode_cache, KM_SLEEP);
1916         ASSERT(!POINTER_IS_VALID(rootzp->z_zfsvfs));
1917         rootzp->z_moved = 0;
1918         rootzp->z_unlinked = 0;
1919         rootzp->z_atime_dirty = 0;
1920         rootzp->z_is_sa = USE_SA(version, os);
1921
1922         zfsvfs->z_os = os;
1923         zfsvfs->z_parent = zfsvfs;
1924         zfsvfs->z_version = version;
1925         zfsvfs->z_use_fuids = USE_FUIDS(version, os);
1926         zfsvfs->z_use_sa = USE_SA(version, os);
1927         zfsvfs->z_norm = norm;
1928
1929         error = sa_setup(os, sa_obj, zfs_attr_table, ZPL_END,
1930             &zfsvfs->z_attr_table);
1931
1932         ASSERT(error == 0);
1933
1934         /*
1935          * Fold case on file systems that are always or sometimes case
1936          * insensitive.
1937          */
1938         if (sense == ZFS_CASE_INSENSITIVE || sense == ZFS_CASE_MIXED)
1939                 zfsvfs->z_norm |= U8_TEXTPREP_TOUPPER;
1940
1941         mutex_init(&zfsvfs->z_znodes_lock, NULL, MUTEX_DEFAULT, NULL);
1942         list_create(&zfsvfs->z_all_znodes, sizeof (znode_t),
1943             offsetof(znode_t, z_link_node));
1944
1945         for (i = 0; i != ZFS_OBJ_MTX_SZ; i++)
1946                 mutex_init(&zfsvfs->z_hold_mtx[i], NULL, MUTEX_DEFAULT, NULL);
1947
1948         rootzp->z_zfsvfs = zfsvfs;
1949         VERIFY(0 == zfs_acl_ids_create(rootzp, IS_ROOT_NODE, &vattr,
1950             cr, NULL, &acl_ids));
1951         zfs_mknode(rootzp, &vattr, tx, cr, IS_ROOT_NODE, &zp, &acl_ids);
1952         ASSERT3P(zp, ==, rootzp);
1953         error = zap_add(os, moid, ZFS_ROOT_OBJ, 8, 1, &rootzp->z_id, tx);
1954         ASSERT(error == 0);
1955         zfs_acl_ids_free(&acl_ids);
1956         POINTER_INVALIDATE(&rootzp->z_zfsvfs);
1957
1958         sa_handle_destroy(rootzp->z_sa_hdl);
1959         kmem_cache_free(znode_cache, rootzp);
1960
1961         /*
1962          * Create shares directory
1963          */
1964
1965         error = zfs_create_share_dir(zfsvfs, tx);
1966
1967         ASSERT(error == 0);
1968
1969         for (i = 0; i != ZFS_OBJ_MTX_SZ; i++)
1970                 mutex_destroy(&zfsvfs->z_hold_mtx[i]);
1971         kmem_free(zfsvfs, sizeof (zfsvfs_t));
1972 }
1973 #endif /* _KERNEL */
1974
1975 static int
1976 zfs_sa_setup(objset_t *osp, sa_attr_type_t **sa_table)
1977 {
1978         uint64_t sa_obj = 0;
1979         int error;
1980
1981         error = zap_lookup(osp, MASTER_NODE_OBJ, ZFS_SA_ATTRS, 8, 1, &sa_obj);
1982         if (error != 0 && error != ENOENT)
1983                 return (error);
1984
1985         error = sa_setup(osp, sa_obj, zfs_attr_table, ZPL_END, sa_table);
1986         return (error);
1987 }
1988
1989 static int
1990 zfs_grab_sa_handle(objset_t *osp, uint64_t obj, sa_handle_t **hdlp,
1991     dmu_buf_t **db, void *tag)
1992 {
1993         dmu_object_info_t doi;
1994         int error;
1995
1996         if ((error = sa_buf_hold(osp, obj, tag, db)) != 0)
1997                 return (error);
1998
1999         dmu_object_info_from_db(*db, &doi);
2000         if ((doi.doi_bonus_type != DMU_OT_SA &&
2001             doi.doi_bonus_type != DMU_OT_ZNODE) ||
2002             doi.doi_bonus_type == DMU_OT_ZNODE &&
2003             doi.doi_bonus_size < sizeof (znode_phys_t)) {
2004                 sa_buf_rele(*db, tag);
2005                 return (SET_ERROR(ENOTSUP));
2006         }
2007
2008         error = sa_handle_get(osp, obj, NULL, SA_HDL_PRIVATE, hdlp);
2009         if (error != 0) {
2010                 sa_buf_rele(*db, tag);
2011                 return (error);
2012         }
2013
2014         return (0);
2015 }
2016
2017 void
2018 zfs_release_sa_handle(sa_handle_t *hdl, dmu_buf_t *db, void *tag)
2019 {
2020         sa_handle_destroy(hdl);
2021         sa_buf_rele(db, tag);
2022 }
2023
2024 /*
2025  * Given an object number, return its parent object number and whether
2026  * or not the object is an extended attribute directory.
2027  */
2028 static int
2029 zfs_obj_to_pobj(objset_t *osp, sa_handle_t *hdl, sa_attr_type_t *sa_table,
2030     uint64_t *pobjp, int *is_xattrdir)
2031 {
2032         uint64_t parent;
2033         uint64_t pflags;
2034         uint64_t mode;
2035         uint64_t parent_mode;
2036         sa_bulk_attr_t bulk[3];
2037         sa_handle_t *sa_hdl;
2038         dmu_buf_t *sa_db;
2039         int count = 0;
2040         int error;
2041
2042         SA_ADD_BULK_ATTR(bulk, count, sa_table[ZPL_PARENT], NULL,
2043             &parent, sizeof (parent));
2044         SA_ADD_BULK_ATTR(bulk, count, sa_table[ZPL_FLAGS], NULL,
2045             &pflags, sizeof (pflags));
2046         SA_ADD_BULK_ATTR(bulk, count, sa_table[ZPL_MODE], NULL,
2047             &mode, sizeof (mode));
2048
2049         if ((error = sa_bulk_lookup(hdl, bulk, count)) != 0)
2050                 return (error);
2051
2052         /*
2053          * When a link is removed its parent pointer is not changed and will
2054          * be invalid.  There are two cases where a link is removed but the
2055          * file stays around, when it goes to the delete queue and when there
2056          * are additional links.
2057          */
2058         error = zfs_grab_sa_handle(osp, parent, &sa_hdl, &sa_db, FTAG);
2059         if (error != 0)
2060                 return (error);
2061
2062         error = sa_lookup(sa_hdl, ZPL_MODE, &parent_mode, sizeof (parent_mode));
2063         zfs_release_sa_handle(sa_hdl, sa_db, FTAG);
2064         if (error != 0)
2065                 return (error);
2066
2067         *is_xattrdir = ((pflags & ZFS_XATTR) != 0) && S_ISDIR(mode);
2068
2069         /*
2070          * Extended attributes can be applied to files, directories, etc.
2071          * Otherwise the parent must be a directory.
2072          */
2073         if (!*is_xattrdir && !S_ISDIR(parent_mode))
2074                 return (SET_ERROR(EINVAL));
2075
2076         *pobjp = parent;
2077
2078         return (0);
2079 }
2080
2081 /*
2082  * Given an object number, return some zpl level statistics
2083  */
2084 static int
2085 zfs_obj_to_stats_impl(sa_handle_t *hdl, sa_attr_type_t *sa_table,
2086     zfs_stat_t *sb)
2087 {
2088         sa_bulk_attr_t bulk[4];
2089         int count = 0;
2090
2091         SA_ADD_BULK_ATTR(bulk, count, sa_table[ZPL_MODE], NULL,
2092             &sb->zs_mode, sizeof (sb->zs_mode));
2093         SA_ADD_BULK_ATTR(bulk, count, sa_table[ZPL_GEN], NULL,
2094             &sb->zs_gen, sizeof (sb->zs_gen));
2095         SA_ADD_BULK_ATTR(bulk, count, sa_table[ZPL_LINKS], NULL,
2096             &sb->zs_links, sizeof (sb->zs_links));
2097         SA_ADD_BULK_ATTR(bulk, count, sa_table[ZPL_CTIME], NULL,
2098             &sb->zs_ctime, sizeof (sb->zs_ctime));
2099
2100         return (sa_bulk_lookup(hdl, bulk, count));
2101 }
2102
2103 static int
2104 zfs_obj_to_path_impl(objset_t *osp, uint64_t obj, sa_handle_t *hdl,
2105     sa_attr_type_t *sa_table, char *buf, int len)
2106 {
2107         sa_handle_t *sa_hdl;
2108         sa_handle_t *prevhdl = NULL;
2109         dmu_buf_t *prevdb = NULL;
2110         dmu_buf_t *sa_db = NULL;
2111         char *path = buf + len - 1;
2112         int error;
2113
2114         *path = '\0';
2115         sa_hdl = hdl;
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 */