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