]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_vfsops.c
zfs: add an option to the bootloader to rewind the ZFS checkpoint
[FreeBSD/FreeBSD.git] / sys / cddl / contrib / opensolaris / uts / common / fs / zfs / zfs_vfsops.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) 2011 Pawel Jakub Dawidek <pawel@dawidek.net>.
24  * All rights reserved.
25  * Copyright (c) 2012, 2015 by Delphix. All rights reserved.
26  * Copyright (c) 2014 Integros [integros.com]
27  * Copyright 2016 Nexenta Systems, Inc. All rights reserved.
28  */
29
30 /* Portions Copyright 2010 Robert Milkowski */
31
32 #include <sys/types.h>
33 #include <sys/param.h>
34 #include <sys/systm.h>
35 #include <sys/kernel.h>
36 #include <sys/sysmacros.h>
37 #include <sys/kmem.h>
38 #include <sys/acl.h>
39 #include <sys/vnode.h>
40 #include <sys/vfs.h>
41 #include <sys/mntent.h>
42 #include <sys/mount.h>
43 #include <sys/cmn_err.h>
44 #include <sys/zfs_znode.h>
45 #include <sys/zfs_dir.h>
46 #include <sys/zil.h>
47 #include <sys/fs/zfs.h>
48 #include <sys/dmu.h>
49 #include <sys/dsl_prop.h>
50 #include <sys/dsl_dataset.h>
51 #include <sys/dsl_deleg.h>
52 #include <sys/spa.h>
53 #include <sys/zap.h>
54 #include <sys/sa.h>
55 #include <sys/sa_impl.h>
56 #include <sys/varargs.h>
57 #include <sys/policy.h>
58 #include <sys/atomic.h>
59 #include <sys/zfs_ioctl.h>
60 #include <sys/zfs_ctldir.h>
61 #include <sys/zfs_fuid.h>
62 #include <sys/sunddi.h>
63 #include <sys/dnlc.h>
64 #include <sys/dmu_objset.h>
65 #include <sys/spa_boot.h>
66 #include <sys/jail.h>
67 #include <ufs/ufs/quota.h>
68
69 #include "zfs_comutil.h"
70
71 struct mtx zfs_debug_mtx;
72 MTX_SYSINIT(zfs_debug_mtx, &zfs_debug_mtx, "zfs_debug", MTX_DEF);
73
74 SYSCTL_NODE(_vfs, OID_AUTO, zfs, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
75     "ZFS file system");
76
77 int zfs_super_owner;
78 SYSCTL_INT(_vfs_zfs, OID_AUTO, super_owner, CTLFLAG_RW, &zfs_super_owner, 0,
79     "File system owner can perform privileged operation on his file systems");
80
81 int zfs_debug_level;
82 SYSCTL_INT(_vfs_zfs, OID_AUTO, debug, CTLFLAG_RWTUN, &zfs_debug_level, 0,
83     "Debug level");
84
85 SYSCTL_NODE(_vfs_zfs, OID_AUTO, version, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
86     "ZFS versions");
87 static int zfs_version_acl = ZFS_ACL_VERSION;
88 SYSCTL_INT(_vfs_zfs_version, OID_AUTO, acl, CTLFLAG_RD, &zfs_version_acl, 0,
89     "ZFS_ACL_VERSION");
90 static int zfs_version_spa = SPA_VERSION;
91 SYSCTL_INT(_vfs_zfs_version, OID_AUTO, spa, CTLFLAG_RD, &zfs_version_spa, 0,
92     "SPA_VERSION");
93 static int zfs_version_zpl = ZPL_VERSION;
94 SYSCTL_INT(_vfs_zfs_version, OID_AUTO, zpl, CTLFLAG_RD, &zfs_version_zpl, 0,
95     "ZPL_VERSION");
96
97 static int zfs_quotactl(vfs_t *vfsp, int cmds, uid_t id, void *arg);
98 static int zfs_mount(vfs_t *vfsp);
99 static int zfs_umount(vfs_t *vfsp, int fflag);
100 static int zfs_root(vfs_t *vfsp, int flags, vnode_t **vpp);
101 static int zfs_statfs(vfs_t *vfsp, struct statfs *statp);
102 static int zfs_vget(vfs_t *vfsp, ino_t ino, int flags, vnode_t **vpp);
103 static int zfs_sync(vfs_t *vfsp, int waitfor);
104 static int zfs_checkexp(vfs_t *vfsp, struct sockaddr *nam, uint64_t *extflagsp,
105     struct ucred **credanonp, int *numsecflavors, int *secflavors);
106 static int zfs_fhtovp(vfs_t *vfsp, fid_t *fidp, int flags, vnode_t **vpp);
107 static void zfs_objset_close(zfsvfs_t *zfsvfs);
108 static void zfs_freevfs(vfs_t *vfsp);
109
110 struct vfsops zfs_vfsops = {
111         .vfs_mount =            zfs_mount,
112         .vfs_unmount =          zfs_umount,
113         .vfs_root =             vfs_cache_root,
114         .vfs_cachedroot =       zfs_root,
115         .vfs_statfs =           zfs_statfs,
116         .vfs_vget =             zfs_vget,
117         .vfs_sync =             zfs_sync,
118         .vfs_checkexp =         zfs_checkexp,
119         .vfs_fhtovp =           zfs_fhtovp,
120         .vfs_quotactl =         zfs_quotactl,
121 };
122
123 VFS_SET(zfs_vfsops, zfs, VFCF_JAIL | VFCF_DELEGADMIN);
124
125 /*
126  * We need to keep a count of active fs's.
127  * This is necessary to prevent our module
128  * from being unloaded after a umount -f
129  */
130 static uint32_t zfs_active_fs_count = 0;
131
132 static int
133 zfs_getquota(zfsvfs_t *zfsvfs, uid_t id, int isgroup, struct dqblk64 *dqp)
134 {
135         int error = 0;
136         char buf[32];
137         int err;
138         uint64_t usedobj, quotaobj;
139         uint64_t quota, used = 0;
140         timespec_t now;
141         
142         usedobj = isgroup ? DMU_GROUPUSED_OBJECT : DMU_USERUSED_OBJECT;
143         quotaobj = isgroup ? zfsvfs->z_groupquota_obj : zfsvfs->z_userquota_obj;
144
145         if (quotaobj == 0 || zfsvfs->z_replay) {
146                 error = EINVAL;
147                 goto done;
148         }
149         (void)sprintf(buf, "%llx", (longlong_t)id);
150         if ((error = zap_lookup(zfsvfs->z_os, quotaobj,
151                                 buf, sizeof(quota), 1, &quota)) != 0) {
152                 dprintf("%s(%d): quotaobj lookup failed\n", __FUNCTION__, __LINE__);
153                 goto done;
154         }
155         /*
156          * quota(8) uses bsoftlimit as "quoota", and hardlimit as "limit".
157          * So we set them to be the same.
158          */
159         dqp->dqb_bsoftlimit = dqp->dqb_bhardlimit = btodb(quota);
160         error = zap_lookup(zfsvfs->z_os, usedobj, buf, sizeof(used), 1, &used);
161         if (error && error != ENOENT) {
162                 dprintf("%s(%d):  usedobj failed; %d\n", __FUNCTION__, __LINE__, error);
163                 goto done;
164         }
165         dqp->dqb_curblocks = btodb(used);
166         dqp->dqb_ihardlimit = dqp->dqb_isoftlimit = 0;
167         vfs_timestamp(&now);
168         /*
169          * Setting this to 0 causes FreeBSD quota(8) to print
170          * the number of days since the epoch, which isn't
171          * particularly useful.
172          */
173         dqp->dqb_btime = dqp->dqb_itime = now.tv_sec;
174 done:
175         return (error);
176 }
177
178 static int
179 zfs_quotactl(vfs_t *vfsp, int cmds, uid_t id, void *arg)
180 {
181         zfsvfs_t *zfsvfs = vfsp->vfs_data;
182         struct thread *td;
183         int cmd, type, error = 0;
184         int bitsize;
185         uint64_t fuid;
186         zfs_userquota_prop_t quota_type;
187         struct dqblk64 dqblk = { 0 };
188         
189         td = curthread;
190         cmd = cmds >> SUBCMDSHIFT;
191         type = cmds & SUBCMDMASK;
192
193         ZFS_ENTER(zfsvfs);
194         if (id == -1) {
195                 switch (type) {
196                 case USRQUOTA:
197                         id = td->td_ucred->cr_ruid;
198                         break;
199                 case GRPQUOTA:
200                         id = td->td_ucred->cr_rgid;
201                         break;
202                 default:
203                         error = EINVAL;
204                         if (cmd == Q_QUOTAON || cmd == Q_QUOTAOFF)
205                                 vfs_unbusy(vfsp);
206                         goto done;
207                 }
208         }
209         /*
210          * Map BSD type to:
211          * ZFS_PROP_USERUSED,
212          * ZFS_PROP_USERQUOTA,
213          * ZFS_PROP_GROUPUSED,
214          * ZFS_PROP_GROUPQUOTA
215          */
216         switch (cmd) {
217         case Q_SETQUOTA:
218         case Q_SETQUOTA32:
219                 if (type == USRQUOTA)
220                         quota_type = ZFS_PROP_USERQUOTA;
221                 else if (type == GRPQUOTA)
222                         quota_type = ZFS_PROP_GROUPQUOTA;
223                 else
224                         error = EINVAL;
225                 break;
226         case Q_GETQUOTA:
227         case Q_GETQUOTA32:
228                 if (type == USRQUOTA)
229                         quota_type = ZFS_PROP_USERUSED;
230                 else if (type == GRPQUOTA)
231                         quota_type = ZFS_PROP_GROUPUSED;
232                 else
233                         error = EINVAL;
234                 break;
235         }
236
237         /*
238          * Depending on the cmd, we may need to get
239          * the ruid and domain (see fuidstr_to_sid?),
240          * the fuid (how?), or other information.
241          * Create fuid using zfs_fuid_create(zfsvfs, id,
242          * ZFS_OWNER or ZFS_GROUP, cr, &fuidp)?
243          * I think I can use just the id?
244          *
245          * Look at zfs_fuid_overquota() to look up a quota.
246          * zap_lookup(something, quotaobj, fuidstring, sizeof(long long), 1, &quota)
247          *
248          * See zfs_set_userquota() to set a quota.
249          */
250         if ((u_int)type >= MAXQUOTAS) {
251                 error = EINVAL;
252                 goto done;
253         }
254
255         switch (cmd) {
256         case Q_GETQUOTASIZE:
257                 bitsize = 64;
258                 error = copyout(&bitsize, arg, sizeof(int));
259                 break;
260         case Q_QUOTAON:
261                 // As far as I can tell, you can't turn quotas on or off on zfs
262                 error = 0;
263                 vfs_unbusy(vfsp);
264                 break;
265         case Q_QUOTAOFF:
266                 error = ENOTSUP;
267                 vfs_unbusy(vfsp);
268                 break;
269         case Q_SETQUOTA:
270                 error = copyin(arg, &dqblk, sizeof(dqblk));
271                 if (error == 0)
272                         error = zfs_set_userquota(zfsvfs, quota_type,
273                                                   "", id, dbtob(dqblk.dqb_bhardlimit));
274                 break;
275         case Q_GETQUOTA:
276                 error = zfs_getquota(zfsvfs, id, type == GRPQUOTA, &dqblk);
277                 if (error == 0)
278                         error = copyout(&dqblk, arg, sizeof(dqblk));
279                 break;
280         default:
281                 error = EINVAL;
282                 break;
283         }
284 done:
285         ZFS_EXIT(zfsvfs);
286         return (error);
287 }
288
289 /*ARGSUSED*/
290 static int
291 zfs_sync(vfs_t *vfsp, int waitfor)
292 {
293
294         /*
295          * Data integrity is job one.  We don't want a compromised kernel
296          * writing to the storage pool, so we never sync during panic.
297          */
298         if (KERNEL_PANICKED())
299                 return (0);
300
301         /*
302          * Ignore the system syncher.  ZFS already commits async data
303          * at zfs_txg_timeout intervals.
304          */
305         if (waitfor == MNT_LAZY)
306                 return (0);
307
308         if (vfsp != NULL) {
309                 /*
310                  * Sync a specific filesystem.
311                  */
312                 zfsvfs_t *zfsvfs = vfsp->vfs_data;
313                 dsl_pool_t *dp;
314                 int error;
315
316                 error = vfs_stdsync(vfsp, waitfor);
317                 if (error != 0)
318                         return (error);
319
320                 ZFS_ENTER(zfsvfs);
321                 dp = dmu_objset_pool(zfsvfs->z_os);
322
323                 /*
324                  * If the system is shutting down, then skip any
325                  * filesystems which may exist on a suspended pool.
326                  */
327                 if (sys_shutdown && spa_suspended(dp->dp_spa)) {
328                         ZFS_EXIT(zfsvfs);
329                         return (0);
330                 }
331
332                 if (zfsvfs->z_log != NULL)
333                         zil_commit(zfsvfs->z_log, 0);
334
335                 ZFS_EXIT(zfsvfs);
336         } else {
337                 /*
338                  * Sync all ZFS filesystems.  This is what happens when you
339                  * run sync(1M).  Unlike other filesystems, ZFS honors the
340                  * request by waiting for all pools to commit all dirty data.
341                  */
342                 spa_sync_allpools();
343         }
344
345         return (0);
346 }
347
348 #ifndef __FreeBSD_kernel__
349 static int
350 zfs_create_unique_device(dev_t *dev)
351 {
352         major_t new_major;
353
354         do {
355                 ASSERT3U(zfs_minor, <=, MAXMIN32);
356                 minor_t start = zfs_minor;
357                 do {
358                         mutex_enter(&zfs_dev_mtx);
359                         if (zfs_minor >= MAXMIN32) {
360                                 /*
361                                  * If we're still using the real major
362                                  * keep out of /dev/zfs and /dev/zvol minor
363                                  * number space.  If we're using a getudev()'ed
364                                  * major number, we can use all of its minors.
365                                  */
366                                 if (zfs_major == ddi_name_to_major(ZFS_DRIVER))
367                                         zfs_minor = ZFS_MIN_MINOR;
368                                 else
369                                         zfs_minor = 0;
370                         } else {
371                                 zfs_minor++;
372                         }
373                         *dev = makedevice(zfs_major, zfs_minor);
374                         mutex_exit(&zfs_dev_mtx);
375                 } while (vfs_devismounted(*dev) && zfs_minor != start);
376                 if (zfs_minor == start) {
377                         /*
378                          * We are using all ~262,000 minor numbers for the
379                          * current major number.  Create a new major number.
380                          */
381                         if ((new_major = getudev()) == (major_t)-1) {
382                                 cmn_err(CE_WARN,
383                                     "zfs_mount: Can't get unique major "
384                                     "device number.");
385                                 return (-1);
386                         }
387                         mutex_enter(&zfs_dev_mtx);
388                         zfs_major = new_major;
389                         zfs_minor = 0;
390
391                         mutex_exit(&zfs_dev_mtx);
392                 } else {
393                         break;
394                 }
395                 /* CONSTANTCONDITION */
396         } while (1);
397
398         return (0);
399 }
400 #endif  /* !__FreeBSD_kernel__ */
401
402 static void
403 atime_changed_cb(void *arg, uint64_t newval)
404 {
405         zfsvfs_t *zfsvfs = arg;
406
407         if (newval == TRUE) {
408                 zfsvfs->z_atime = TRUE;
409                 zfsvfs->z_vfs->vfs_flag &= ~MNT_NOATIME;
410                 vfs_clearmntopt(zfsvfs->z_vfs, MNTOPT_NOATIME);
411                 vfs_setmntopt(zfsvfs->z_vfs, MNTOPT_ATIME, NULL, 0);
412         } else {
413                 zfsvfs->z_atime = FALSE;
414                 zfsvfs->z_vfs->vfs_flag |= MNT_NOATIME;
415                 vfs_clearmntopt(zfsvfs->z_vfs, MNTOPT_ATIME);
416                 vfs_setmntopt(zfsvfs->z_vfs, MNTOPT_NOATIME, NULL, 0);
417         }
418 }
419
420 static void
421 xattr_changed_cb(void *arg, uint64_t newval)
422 {
423         zfsvfs_t *zfsvfs = arg;
424
425         if (newval == TRUE) {
426                 /* XXX locking on vfs_flag? */
427 #ifdef TODO
428                 zfsvfs->z_vfs->vfs_flag |= VFS_XATTR;
429 #endif
430                 vfs_clearmntopt(zfsvfs->z_vfs, MNTOPT_NOXATTR);
431                 vfs_setmntopt(zfsvfs->z_vfs, MNTOPT_XATTR, NULL, 0);
432         } else {
433                 /* XXX locking on vfs_flag? */
434 #ifdef TODO
435                 zfsvfs->z_vfs->vfs_flag &= ~VFS_XATTR;
436 #endif
437                 vfs_clearmntopt(zfsvfs->z_vfs, MNTOPT_XATTR);
438                 vfs_setmntopt(zfsvfs->z_vfs, MNTOPT_NOXATTR, NULL, 0);
439         }
440 }
441
442 static void
443 blksz_changed_cb(void *arg, uint64_t newval)
444 {
445         zfsvfs_t *zfsvfs = arg;
446         ASSERT3U(newval, <=, spa_maxblocksize(dmu_objset_spa(zfsvfs->z_os)));
447         ASSERT3U(newval, >=, SPA_MINBLOCKSIZE);
448         ASSERT(ISP2(newval));
449
450         zfsvfs->z_max_blksz = newval;
451         zfsvfs->z_vfs->mnt_stat.f_iosize = newval;
452 }
453
454 static void
455 readonly_changed_cb(void *arg, uint64_t newval)
456 {
457         zfsvfs_t *zfsvfs = arg;
458
459         if (newval) {
460                 /* XXX locking on vfs_flag? */
461                 zfsvfs->z_vfs->vfs_flag |= VFS_RDONLY;
462                 vfs_clearmntopt(zfsvfs->z_vfs, MNTOPT_RW);
463                 vfs_setmntopt(zfsvfs->z_vfs, MNTOPT_RO, NULL, 0);
464         } else {
465                 /* XXX locking on vfs_flag? */
466                 zfsvfs->z_vfs->vfs_flag &= ~VFS_RDONLY;
467                 vfs_clearmntopt(zfsvfs->z_vfs, MNTOPT_RO);
468                 vfs_setmntopt(zfsvfs->z_vfs, MNTOPT_RW, NULL, 0);
469         }
470 }
471
472 static void
473 setuid_changed_cb(void *arg, uint64_t newval)
474 {
475         zfsvfs_t *zfsvfs = arg;
476
477         if (newval == FALSE) {
478                 zfsvfs->z_vfs->vfs_flag |= VFS_NOSETUID;
479                 vfs_clearmntopt(zfsvfs->z_vfs, MNTOPT_SETUID);
480                 vfs_setmntopt(zfsvfs->z_vfs, MNTOPT_NOSETUID, NULL, 0);
481         } else {
482                 zfsvfs->z_vfs->vfs_flag &= ~VFS_NOSETUID;
483                 vfs_clearmntopt(zfsvfs->z_vfs, MNTOPT_NOSETUID);
484                 vfs_setmntopt(zfsvfs->z_vfs, MNTOPT_SETUID, NULL, 0);
485         }
486 }
487
488 static void
489 exec_changed_cb(void *arg, uint64_t newval)
490 {
491         zfsvfs_t *zfsvfs = arg;
492
493         if (newval == FALSE) {
494                 zfsvfs->z_vfs->vfs_flag |= VFS_NOEXEC;
495                 vfs_clearmntopt(zfsvfs->z_vfs, MNTOPT_EXEC);
496                 vfs_setmntopt(zfsvfs->z_vfs, MNTOPT_NOEXEC, NULL, 0);
497         } else {
498                 zfsvfs->z_vfs->vfs_flag &= ~VFS_NOEXEC;
499                 vfs_clearmntopt(zfsvfs->z_vfs, MNTOPT_NOEXEC);
500                 vfs_setmntopt(zfsvfs->z_vfs, MNTOPT_EXEC, NULL, 0);
501         }
502 }
503
504 /*
505  * The nbmand mount option can be changed at mount time.
506  * We can't allow it to be toggled on live file systems or incorrect
507  * behavior may be seen from cifs clients
508  *
509  * This property isn't registered via dsl_prop_register(), but this callback
510  * will be called when a file system is first mounted
511  */
512 static void
513 nbmand_changed_cb(void *arg, uint64_t newval)
514 {
515         zfsvfs_t *zfsvfs = arg;
516         if (newval == FALSE) {
517                 vfs_clearmntopt(zfsvfs->z_vfs, MNTOPT_NBMAND);
518                 vfs_setmntopt(zfsvfs->z_vfs, MNTOPT_NONBMAND, NULL, 0);
519         } else {
520                 vfs_clearmntopt(zfsvfs->z_vfs, MNTOPT_NONBMAND);
521                 vfs_setmntopt(zfsvfs->z_vfs, MNTOPT_NBMAND, NULL, 0);
522         }
523 }
524
525 static void
526 snapdir_changed_cb(void *arg, uint64_t newval)
527 {
528         zfsvfs_t *zfsvfs = arg;
529
530         zfsvfs->z_show_ctldir = newval;
531 }
532
533 static void
534 vscan_changed_cb(void *arg, uint64_t newval)
535 {
536         zfsvfs_t *zfsvfs = arg;
537
538         zfsvfs->z_vscan = newval;
539 }
540
541 static void
542 acl_mode_changed_cb(void *arg, uint64_t newval)
543 {
544         zfsvfs_t *zfsvfs = arg;
545
546         zfsvfs->z_acl_mode = newval;
547 }
548
549 static void
550 acl_inherit_changed_cb(void *arg, uint64_t newval)
551 {
552         zfsvfs_t *zfsvfs = arg;
553
554         zfsvfs->z_acl_inherit = newval;
555 }
556
557 static int
558 zfs_register_callbacks(vfs_t *vfsp)
559 {
560         struct dsl_dataset *ds = NULL;
561         objset_t *os = NULL;
562         zfsvfs_t *zfsvfs = NULL;
563         uint64_t nbmand;
564         boolean_t readonly = B_FALSE;
565         boolean_t do_readonly = B_FALSE;
566         boolean_t setuid = B_FALSE;
567         boolean_t do_setuid = B_FALSE;
568         boolean_t exec = B_FALSE;
569         boolean_t do_exec = B_FALSE;
570 #ifdef illumos
571         boolean_t devices = B_FALSE;
572         boolean_t do_devices = B_FALSE;
573 #endif
574         boolean_t xattr = B_FALSE;
575         boolean_t do_xattr = B_FALSE;
576         boolean_t atime = B_FALSE;
577         boolean_t do_atime = B_FALSE;
578         int error = 0;
579
580         ASSERT(vfsp);
581         zfsvfs = vfsp->vfs_data;
582         ASSERT(zfsvfs);
583         os = zfsvfs->z_os;
584
585         /*
586          * This function can be called for a snapshot when we update snapshot's
587          * mount point, which isn't really supported.
588          */
589         if (dmu_objset_is_snapshot(os))
590                 return (EOPNOTSUPP);
591
592         /*
593          * The act of registering our callbacks will destroy any mount
594          * options we may have.  In order to enable temporary overrides
595          * of mount options, we stash away the current values and
596          * restore them after we register the callbacks.
597          */
598         if (vfs_optionisset(vfsp, MNTOPT_RO, NULL) ||
599             !spa_writeable(dmu_objset_spa(os))) {
600                 readonly = B_TRUE;
601                 do_readonly = B_TRUE;
602         } else if (vfs_optionisset(vfsp, MNTOPT_RW, NULL)) {
603                 readonly = B_FALSE;
604                 do_readonly = B_TRUE;
605         }
606         if (vfs_optionisset(vfsp, MNTOPT_NOSUID, NULL)) {
607                 setuid = B_FALSE;
608                 do_setuid = B_TRUE;
609         } else {
610                 if (vfs_optionisset(vfsp, MNTOPT_NOSETUID, NULL)) {
611                         setuid = B_FALSE;
612                         do_setuid = B_TRUE;
613                 } else if (vfs_optionisset(vfsp, MNTOPT_SETUID, NULL)) {
614                         setuid = B_TRUE;
615                         do_setuid = B_TRUE;
616                 }
617         }
618         if (vfs_optionisset(vfsp, MNTOPT_NOEXEC, NULL)) {
619                 exec = B_FALSE;
620                 do_exec = B_TRUE;
621         } else if (vfs_optionisset(vfsp, MNTOPT_EXEC, NULL)) {
622                 exec = B_TRUE;
623                 do_exec = B_TRUE;
624         }
625         if (vfs_optionisset(vfsp, MNTOPT_NOXATTR, NULL)) {
626                 xattr = B_FALSE;
627                 do_xattr = B_TRUE;
628         } else if (vfs_optionisset(vfsp, MNTOPT_XATTR, NULL)) {
629                 xattr = B_TRUE;
630                 do_xattr = B_TRUE;
631         }
632         if (vfs_optionisset(vfsp, MNTOPT_NOATIME, NULL)) {
633                 atime = B_FALSE;
634                 do_atime = B_TRUE;
635         } else if (vfs_optionisset(vfsp, MNTOPT_ATIME, NULL)) {
636                 atime = B_TRUE;
637                 do_atime = B_TRUE;
638         }
639
640         /*
641          * We need to enter pool configuration here, so that we can use
642          * dsl_prop_get_int_ds() to handle the special nbmand property below.
643          * dsl_prop_get_integer() can not be used, because it has to acquire
644          * spa_namespace_lock and we can not do that because we already hold
645          * z_teardown_lock.  The problem is that spa_write_cachefile() is called
646          * with spa_namespace_lock held and the function calls ZFS vnode
647          * operations to write the cache file and thus z_teardown_lock is
648          * acquired after spa_namespace_lock.
649          */
650         ds = dmu_objset_ds(os);
651         dsl_pool_config_enter(dmu_objset_pool(os), FTAG);
652
653         /*
654          * nbmand is a special property.  It can only be changed at
655          * mount time.
656          *
657          * This is weird, but it is documented to only be changeable
658          * at mount time.
659          */
660         if (vfs_optionisset(vfsp, MNTOPT_NONBMAND, NULL)) {
661                 nbmand = B_FALSE;
662         } else if (vfs_optionisset(vfsp, MNTOPT_NBMAND, NULL)) {
663                 nbmand = B_TRUE;
664         } else if (error = dsl_prop_get_int_ds(ds, "nbmand", &nbmand) != 0) {
665                 dsl_pool_config_exit(dmu_objset_pool(os), FTAG);
666                 return (error);
667         }
668
669         /*
670          * Register property callbacks.
671          *
672          * It would probably be fine to just check for i/o error from
673          * the first prop_register(), but I guess I like to go
674          * overboard...
675          */
676         error = dsl_prop_register(ds,
677             zfs_prop_to_name(ZFS_PROP_ATIME), atime_changed_cb, zfsvfs);
678         error = error ? error : dsl_prop_register(ds,
679             zfs_prop_to_name(ZFS_PROP_XATTR), xattr_changed_cb, zfsvfs);
680         error = error ? error : dsl_prop_register(ds,
681             zfs_prop_to_name(ZFS_PROP_RECORDSIZE), blksz_changed_cb, zfsvfs);
682         error = error ? error : dsl_prop_register(ds,
683             zfs_prop_to_name(ZFS_PROP_READONLY), readonly_changed_cb, zfsvfs);
684 #ifdef illumos
685         error = error ? error : dsl_prop_register(ds,
686             zfs_prop_to_name(ZFS_PROP_DEVICES), devices_changed_cb, zfsvfs);
687 #endif
688         error = error ? error : dsl_prop_register(ds,
689             zfs_prop_to_name(ZFS_PROP_SETUID), setuid_changed_cb, zfsvfs);
690         error = error ? error : dsl_prop_register(ds,
691             zfs_prop_to_name(ZFS_PROP_EXEC), exec_changed_cb, zfsvfs);
692         error = error ? error : dsl_prop_register(ds,
693             zfs_prop_to_name(ZFS_PROP_SNAPDIR), snapdir_changed_cb, zfsvfs);
694         error = error ? error : dsl_prop_register(ds,
695             zfs_prop_to_name(ZFS_PROP_ACLMODE), acl_mode_changed_cb, zfsvfs);
696         error = error ? error : dsl_prop_register(ds,
697             zfs_prop_to_name(ZFS_PROP_ACLINHERIT), acl_inherit_changed_cb,
698             zfsvfs);
699         error = error ? error : dsl_prop_register(ds,
700             zfs_prop_to_name(ZFS_PROP_VSCAN), vscan_changed_cb, zfsvfs);
701         dsl_pool_config_exit(dmu_objset_pool(os), FTAG);
702         if (error)
703                 goto unregister;
704
705         /*
706          * Invoke our callbacks to restore temporary mount options.
707          */
708         if (do_readonly)
709                 readonly_changed_cb(zfsvfs, readonly);
710         if (do_setuid)
711                 setuid_changed_cb(zfsvfs, setuid);
712         if (do_exec)
713                 exec_changed_cb(zfsvfs, exec);
714         if (do_xattr)
715                 xattr_changed_cb(zfsvfs, xattr);
716         if (do_atime)
717                 atime_changed_cb(zfsvfs, atime);
718
719         nbmand_changed_cb(zfsvfs, nbmand);
720
721         return (0);
722
723 unregister:
724         dsl_prop_unregister_all(ds, zfsvfs);
725         return (error);
726 }
727
728 static int
729 zfs_space_delta_cb(dmu_object_type_t bonustype, void *data,
730     uint64_t *userp, uint64_t *groupp)
731 {
732         /*
733          * Is it a valid type of object to track?
734          */
735         if (bonustype != DMU_OT_ZNODE && bonustype != DMU_OT_SA)
736                 return (SET_ERROR(ENOENT));
737
738         /*
739          * If we have a NULL data pointer
740          * then assume the id's aren't changing and
741          * return EEXIST to the dmu to let it know to
742          * use the same ids
743          */
744         if (data == NULL)
745                 return (SET_ERROR(EEXIST));
746
747         if (bonustype == DMU_OT_ZNODE) {
748                 znode_phys_t *znp = data;
749                 *userp = znp->zp_uid;
750                 *groupp = znp->zp_gid;
751         } else {
752                 int hdrsize;
753                 sa_hdr_phys_t *sap = data;
754                 sa_hdr_phys_t sa = *sap;
755                 boolean_t swap = B_FALSE;
756
757                 ASSERT(bonustype == DMU_OT_SA);
758
759                 if (sa.sa_magic == 0) {
760                         /*
761                          * This should only happen for newly created
762                          * files that haven't had the znode data filled
763                          * in yet.
764                          */
765                         *userp = 0;
766                         *groupp = 0;
767                         return (0);
768                 }
769                 if (sa.sa_magic == BSWAP_32(SA_MAGIC)) {
770                         sa.sa_magic = SA_MAGIC;
771                         sa.sa_layout_info = BSWAP_16(sa.sa_layout_info);
772                         swap = B_TRUE;
773                 } else {
774                         VERIFY3U(sa.sa_magic, ==, SA_MAGIC);
775                 }
776
777                 hdrsize = sa_hdrsize(&sa);
778                 VERIFY3U(hdrsize, >=, sizeof (sa_hdr_phys_t));
779                 *userp = *((uint64_t *)((uintptr_t)data + hdrsize +
780                     SA_UID_OFFSET));
781                 *groupp = *((uint64_t *)((uintptr_t)data + hdrsize +
782                     SA_GID_OFFSET));
783                 if (swap) {
784                         *userp = BSWAP_64(*userp);
785                         *groupp = BSWAP_64(*groupp);
786                 }
787         }
788         return (0);
789 }
790
791 static void
792 fuidstr_to_sid(zfsvfs_t *zfsvfs, const char *fuidstr,
793     char *domainbuf, int buflen, uid_t *ridp)
794 {
795         uint64_t fuid;
796         const char *domain;
797
798         fuid = zfs_strtonum(fuidstr, NULL);
799
800         domain = zfs_fuid_find_by_idx(zfsvfs, FUID_INDEX(fuid));
801         if (domain)
802                 (void) strlcpy(domainbuf, domain, buflen);
803         else
804                 domainbuf[0] = '\0';
805         *ridp = FUID_RID(fuid);
806 }
807
808 static uint64_t
809 zfs_userquota_prop_to_obj(zfsvfs_t *zfsvfs, zfs_userquota_prop_t type)
810 {
811         switch (type) {
812         case ZFS_PROP_USERUSED:
813                 return (DMU_USERUSED_OBJECT);
814         case ZFS_PROP_GROUPUSED:
815                 return (DMU_GROUPUSED_OBJECT);
816         case ZFS_PROP_USERQUOTA:
817                 return (zfsvfs->z_userquota_obj);
818         case ZFS_PROP_GROUPQUOTA:
819                 return (zfsvfs->z_groupquota_obj);
820         }
821         return (0);
822 }
823
824 int
825 zfs_userspace_many(zfsvfs_t *zfsvfs, zfs_userquota_prop_t type,
826     uint64_t *cookiep, void *vbuf, uint64_t *bufsizep)
827 {
828         int error;
829         zap_cursor_t zc;
830         zap_attribute_t za;
831         zfs_useracct_t *buf = vbuf;
832         uint64_t obj;
833
834         if (!dmu_objset_userspace_present(zfsvfs->z_os))
835                 return (SET_ERROR(ENOTSUP));
836
837         obj = zfs_userquota_prop_to_obj(zfsvfs, type);
838         if (obj == 0) {
839                 *bufsizep = 0;
840                 return (0);
841         }
842
843         for (zap_cursor_init_serialized(&zc, zfsvfs->z_os, obj, *cookiep);
844             (error = zap_cursor_retrieve(&zc, &za)) == 0;
845             zap_cursor_advance(&zc)) {
846                 if ((uintptr_t)buf - (uintptr_t)vbuf + sizeof (zfs_useracct_t) >
847                     *bufsizep)
848                         break;
849
850                 fuidstr_to_sid(zfsvfs, za.za_name,
851                     buf->zu_domain, sizeof (buf->zu_domain), &buf->zu_rid);
852
853                 buf->zu_space = za.za_first_integer;
854                 buf++;
855         }
856         if (error == ENOENT)
857                 error = 0;
858
859         ASSERT3U((uintptr_t)buf - (uintptr_t)vbuf, <=, *bufsizep);
860         *bufsizep = (uintptr_t)buf - (uintptr_t)vbuf;
861         *cookiep = zap_cursor_serialize(&zc);
862         zap_cursor_fini(&zc);
863         return (error);
864 }
865
866 /*
867  * buf must be big enough (eg, 32 bytes)
868  */
869 static int
870 id_to_fuidstr(zfsvfs_t *zfsvfs, const char *domain, uid_t rid,
871     char *buf, boolean_t addok)
872 {
873         uint64_t fuid;
874         int domainid = 0;
875
876         if (domain && domain[0]) {
877                 domainid = zfs_fuid_find_by_domain(zfsvfs, domain, NULL, addok);
878                 if (domainid == -1)
879                         return (SET_ERROR(ENOENT));
880         }
881         fuid = FUID_ENCODE(domainid, rid);
882         (void) sprintf(buf, "%llx", (longlong_t)fuid);
883         return (0);
884 }
885
886 int
887 zfs_userspace_one(zfsvfs_t *zfsvfs, zfs_userquota_prop_t type,
888     const char *domain, uint64_t rid, uint64_t *valp)
889 {
890         char buf[32];
891         int err;
892         uint64_t obj;
893
894         *valp = 0;
895
896         if (!dmu_objset_userspace_present(zfsvfs->z_os))
897                 return (SET_ERROR(ENOTSUP));
898
899         obj = zfs_userquota_prop_to_obj(zfsvfs, type);
900         if (obj == 0)
901                 return (0);
902
903         err = id_to_fuidstr(zfsvfs, domain, rid, buf, B_FALSE);
904         if (err)
905                 return (err);
906
907         err = zap_lookup(zfsvfs->z_os, obj, buf, 8, 1, valp);
908         if (err == ENOENT)
909                 err = 0;
910         return (err);
911 }
912
913 int
914 zfs_set_userquota(zfsvfs_t *zfsvfs, zfs_userquota_prop_t type,
915     const char *domain, uint64_t rid, uint64_t quota)
916 {
917         char buf[32];
918         int err;
919         dmu_tx_t *tx;
920         uint64_t *objp;
921         boolean_t fuid_dirtied;
922
923         if (type != ZFS_PROP_USERQUOTA && type != ZFS_PROP_GROUPQUOTA)
924                 return (SET_ERROR(EINVAL));
925
926         if (zfsvfs->z_version < ZPL_VERSION_USERSPACE)
927                 return (SET_ERROR(ENOTSUP));
928
929         objp = (type == ZFS_PROP_USERQUOTA) ? &zfsvfs->z_userquota_obj :
930             &zfsvfs->z_groupquota_obj;
931
932         err = id_to_fuidstr(zfsvfs, domain, rid, buf, B_TRUE);
933         if (err)
934                 return (err);
935         fuid_dirtied = zfsvfs->z_fuid_dirty;
936
937         tx = dmu_tx_create(zfsvfs->z_os);
938         dmu_tx_hold_zap(tx, *objp ? *objp : DMU_NEW_OBJECT, B_TRUE, NULL);
939         if (*objp == 0) {
940                 dmu_tx_hold_zap(tx, MASTER_NODE_OBJ, B_TRUE,
941                     zfs_userquota_prop_prefixes[type]);
942         }
943         if (fuid_dirtied)
944                 zfs_fuid_txhold(zfsvfs, tx);
945         err = dmu_tx_assign(tx, TXG_WAIT);
946         if (err) {
947                 dmu_tx_abort(tx);
948                 return (err);
949         }
950
951         mutex_enter(&zfsvfs->z_lock);
952         if (*objp == 0) {
953                 *objp = zap_create(zfsvfs->z_os, DMU_OT_USERGROUP_QUOTA,
954                     DMU_OT_NONE, 0, tx);
955                 VERIFY(0 == zap_add(zfsvfs->z_os, MASTER_NODE_OBJ,
956                     zfs_userquota_prop_prefixes[type], 8, 1, objp, tx));
957         }
958         mutex_exit(&zfsvfs->z_lock);
959
960         if (quota == 0) {
961                 err = zap_remove(zfsvfs->z_os, *objp, buf, tx);
962                 if (err == ENOENT)
963                         err = 0;
964         } else {
965                 err = zap_update(zfsvfs->z_os, *objp, buf, 8, 1, &quota, tx);
966         }
967         ASSERT(err == 0);
968         if (fuid_dirtied)
969                 zfs_fuid_sync(zfsvfs, tx);
970         dmu_tx_commit(tx);
971         return (err);
972 }
973
974 boolean_t
975 zfs_fuid_overquota(zfsvfs_t *zfsvfs, boolean_t isgroup, uint64_t fuid)
976 {
977         char buf[32];
978         uint64_t used, quota, usedobj, quotaobj;
979         int err;
980
981         usedobj = isgroup ? DMU_GROUPUSED_OBJECT : DMU_USERUSED_OBJECT;
982         quotaobj = isgroup ? zfsvfs->z_groupquota_obj : zfsvfs->z_userquota_obj;
983
984         if (quotaobj == 0 || zfsvfs->z_replay)
985                 return (B_FALSE);
986
987         (void) sprintf(buf, "%llx", (longlong_t)fuid);
988         err = zap_lookup(zfsvfs->z_os, quotaobj, buf, 8, 1, &quota);
989         if (err != 0)
990                 return (B_FALSE);
991
992         err = zap_lookup(zfsvfs->z_os, usedobj, buf, 8, 1, &used);
993         if (err != 0)
994                 return (B_FALSE);
995         return (used >= quota);
996 }
997
998 boolean_t
999 zfs_owner_overquota(zfsvfs_t *zfsvfs, znode_t *zp, boolean_t isgroup)
1000 {
1001         uint64_t fuid;
1002         uint64_t quotaobj;
1003
1004         quotaobj = isgroup ? zfsvfs->z_groupquota_obj : zfsvfs->z_userquota_obj;
1005
1006         fuid = isgroup ? zp->z_gid : zp->z_uid;
1007
1008         if (quotaobj == 0 || zfsvfs->z_replay)
1009                 return (B_FALSE);
1010
1011         return (zfs_fuid_overquota(zfsvfs, isgroup, fuid));
1012 }
1013
1014 /*
1015  * Associate this zfsvfs with the given objset, which must be owned.
1016  * This will cache a bunch of on-disk state from the objset in the
1017  * zfsvfs.
1018  */
1019 static int
1020 zfsvfs_init(zfsvfs_t *zfsvfs, objset_t *os)
1021 {
1022         int error;
1023         uint64_t val;
1024
1025         zfsvfs->z_max_blksz = SPA_OLD_MAXBLOCKSIZE;
1026         zfsvfs->z_show_ctldir = ZFS_SNAPDIR_VISIBLE;
1027         zfsvfs->z_os = os;
1028
1029         error = zfs_get_zplprop(os, ZFS_PROP_VERSION, &zfsvfs->z_version);
1030         if (error != 0)
1031                 return (error);
1032         if (zfsvfs->z_version >
1033             zfs_zpl_version_map(spa_version(dmu_objset_spa(os)))) {
1034                 (void) printf("Can't mount a version %lld file system "
1035                     "on a version %lld pool\n. Pool must be upgraded to mount "
1036                     "this file system.", (u_longlong_t)zfsvfs->z_version,
1037                     (u_longlong_t)spa_version(dmu_objset_spa(os)));
1038                 return (SET_ERROR(ENOTSUP));
1039         }
1040         error = zfs_get_zplprop(os, ZFS_PROP_NORMALIZE, &val);
1041         if (error != 0)
1042                 return (error);
1043         zfsvfs->z_norm = (int)val;
1044
1045         error = zfs_get_zplprop(os, ZFS_PROP_UTF8ONLY, &val);
1046         if (error != 0)
1047                 return (error);
1048         zfsvfs->z_utf8 = (val != 0);
1049
1050         error = zfs_get_zplprop(os, ZFS_PROP_CASE, &val);
1051         if (error != 0)
1052                 return (error);
1053         zfsvfs->z_case = (uint_t)val;
1054
1055         /*
1056          * Fold case on file systems that are always or sometimes case
1057          * insensitive.
1058          */
1059         if (zfsvfs->z_case == ZFS_CASE_INSENSITIVE ||
1060             zfsvfs->z_case == ZFS_CASE_MIXED)
1061                 zfsvfs->z_norm |= U8_TEXTPREP_TOUPPER;
1062
1063         zfsvfs->z_use_fuids = USE_FUIDS(zfsvfs->z_version, zfsvfs->z_os);
1064         zfsvfs->z_use_sa = USE_SA(zfsvfs->z_version, zfsvfs->z_os);
1065
1066         uint64_t sa_obj = 0;
1067         if (zfsvfs->z_use_sa) {
1068                 /* should either have both of these objects or none */
1069                 error = zap_lookup(os, MASTER_NODE_OBJ, ZFS_SA_ATTRS, 8, 1,
1070                     &sa_obj);
1071                 if (error != 0)
1072                         return (error);
1073         }
1074
1075         error = sa_setup(os, sa_obj, zfs_attr_table, ZPL_END,
1076             &zfsvfs->z_attr_table);
1077         if (error != 0)
1078                 return (error);
1079
1080         if (zfsvfs->z_version >= ZPL_VERSION_SA)
1081                 sa_register_update_callback(os, zfs_sa_upgrade);
1082
1083         error = zap_lookup(os, MASTER_NODE_OBJ, ZFS_ROOT_OBJ, 8, 1,
1084             &zfsvfs->z_root);
1085         if (error != 0)
1086                 return (error);
1087         ASSERT(zfsvfs->z_root != 0);
1088
1089         error = zap_lookup(os, MASTER_NODE_OBJ, ZFS_UNLINKED_SET, 8, 1,
1090             &zfsvfs->z_unlinkedobj);
1091         if (error != 0)
1092                 return (error);
1093
1094         error = zap_lookup(os, MASTER_NODE_OBJ,
1095             zfs_userquota_prop_prefixes[ZFS_PROP_USERQUOTA],
1096             8, 1, &zfsvfs->z_userquota_obj);
1097         if (error == ENOENT)
1098                 zfsvfs->z_userquota_obj = 0;
1099         else if (error != 0)
1100                 return (error);
1101
1102         error = zap_lookup(os, MASTER_NODE_OBJ,
1103             zfs_userquota_prop_prefixes[ZFS_PROP_GROUPQUOTA],
1104             8, 1, &zfsvfs->z_groupquota_obj);
1105         if (error == ENOENT)
1106                 zfsvfs->z_groupquota_obj = 0;
1107         else if (error != 0)
1108                 return (error);
1109
1110         error = zap_lookup(os, MASTER_NODE_OBJ, ZFS_FUID_TABLES, 8, 1,
1111             &zfsvfs->z_fuid_obj);
1112         if (error == ENOENT)
1113                 zfsvfs->z_fuid_obj = 0;
1114         else if (error != 0)
1115                 return (error);
1116
1117         error = zap_lookup(os, MASTER_NODE_OBJ, ZFS_SHARES_DIR, 8, 1,
1118             &zfsvfs->z_shares_dir);
1119         if (error == ENOENT)
1120                 zfsvfs->z_shares_dir = 0;
1121         else if (error != 0)
1122                 return (error);
1123
1124         /*
1125          * Only use the name cache if we are looking for a
1126          * name on a file system that does not require normalization
1127          * or case folding.  We can also look there if we happen to be
1128          * on a non-normalizing, mixed sensitivity file system IF we
1129          * are looking for the exact name (which is always the case on
1130          * FreeBSD).
1131          */
1132         zfsvfs->z_use_namecache = !zfsvfs->z_norm ||
1133             ((zfsvfs->z_case == ZFS_CASE_MIXED) &&
1134             !(zfsvfs->z_norm & ~U8_TEXTPREP_TOUPPER));
1135
1136         return (0);
1137 }
1138
1139 #if defined(__FreeBSD__)
1140 taskq_t *zfsvfs_taskq;
1141
1142 static void
1143 zfsvfs_task_unlinked_drain(void *context, int pending __unused)
1144 {
1145
1146         zfs_unlinked_drain((zfsvfs_t *)context);
1147 }
1148 #endif
1149
1150 int
1151 zfsvfs_create(const char *osname, zfsvfs_t **zfvp)
1152 {
1153         objset_t *os;
1154         zfsvfs_t *zfsvfs;
1155         int error;
1156
1157         /*
1158          * XXX: Fix struct statfs so this isn't necessary!
1159          *
1160          * The 'osname' is used as the filesystem's special node, which means
1161          * it must fit in statfs.f_mntfromname, or else it can't be
1162          * enumerated, so libzfs_mnttab_find() returns NULL, which causes
1163          * 'zfs unmount' to think it's not mounted when it is.
1164          */
1165         if (strlen(osname) >= MNAMELEN)
1166                 return (SET_ERROR(ENAMETOOLONG));
1167
1168         zfsvfs = kmem_zalloc(sizeof (zfsvfs_t), KM_SLEEP);
1169
1170         /*
1171          * We claim to always be readonly so we can open snapshots;
1172          * other ZPL code will prevent us from writing to snapshots.
1173          */
1174
1175         error = dmu_objset_own(osname, DMU_OST_ZFS, B_TRUE, zfsvfs, &os);
1176         if (error != 0) {
1177                 kmem_free(zfsvfs, sizeof (zfsvfs_t));
1178                 return (error);
1179         }
1180
1181         error = zfsvfs_create_impl(zfvp, zfsvfs, os);
1182         if (error != 0) {
1183                 dmu_objset_disown(os, zfsvfs);
1184         }
1185         return (error);
1186 }
1187
1188
1189 int
1190 zfsvfs_create_impl(zfsvfs_t **zfvp, zfsvfs_t *zfsvfs, objset_t *os)
1191 {
1192         int error;
1193
1194         zfsvfs->z_vfs = NULL;
1195         zfsvfs->z_parent = zfsvfs;
1196
1197         mutex_init(&zfsvfs->z_znodes_lock, NULL, MUTEX_DEFAULT, NULL);
1198         mutex_init(&zfsvfs->z_lock, NULL, MUTEX_DEFAULT, NULL);
1199         list_create(&zfsvfs->z_all_znodes, sizeof (znode_t),
1200             offsetof(znode_t, z_link_node));
1201 #if defined(__FreeBSD__)
1202         TASK_INIT(&zfsvfs->z_unlinked_drain_task, 0,
1203             zfsvfs_task_unlinked_drain, zfsvfs);
1204 #endif
1205 #ifdef DIAGNOSTIC
1206         rrm_init(&zfsvfs->z_teardown_lock, B_TRUE);
1207 #else
1208         rrm_init(&zfsvfs->z_teardown_lock, B_FALSE);
1209 #endif
1210         rms_init(&zfsvfs->z_teardown_inactive_lock, "zfs teardown inactive");
1211         rw_init(&zfsvfs->z_fuid_lock, NULL, RW_DEFAULT, NULL);
1212         for (int i = 0; i != ZFS_OBJ_MTX_SZ; i++)
1213                 mutex_init(&zfsvfs->z_hold_mtx[i], NULL, MUTEX_DEFAULT, NULL);
1214
1215         error = zfsvfs_init(zfsvfs, os);
1216         if (error != 0) {
1217                 *zfvp = NULL;
1218                 kmem_free(zfsvfs, sizeof (zfsvfs_t));
1219                 return (error);
1220         }
1221
1222         *zfvp = zfsvfs;
1223         return (0);
1224 }
1225
1226 static int
1227 zfsvfs_setup(zfsvfs_t *zfsvfs, boolean_t mounting)
1228 {
1229         int error;
1230
1231         error = zfs_register_callbacks(zfsvfs->z_vfs);
1232         if (error)
1233                 return (error);
1234
1235         zfsvfs->z_log = zil_open(zfsvfs->z_os, zfs_get_data);
1236
1237         /*
1238          * If we are not mounting (ie: online recv), then we don't
1239          * have to worry about replaying the log as we blocked all
1240          * operations out since we closed the ZIL.
1241          */
1242         if (mounting) {
1243                 boolean_t readonly;
1244
1245                 /*
1246                  * During replay we remove the read only flag to
1247                  * allow replays to succeed.
1248                  */
1249                 readonly = zfsvfs->z_vfs->vfs_flag & VFS_RDONLY;
1250                 if (readonly != 0)
1251                         zfsvfs->z_vfs->vfs_flag &= ~VFS_RDONLY;
1252                 else
1253                         zfs_unlinked_drain(zfsvfs);
1254
1255                 /*
1256                  * Parse and replay the intent log.
1257                  *
1258                  * Because of ziltest, this must be done after
1259                  * zfs_unlinked_drain().  (Further note: ziltest
1260                  * doesn't use readonly mounts, where
1261                  * zfs_unlinked_drain() isn't called.)  This is because
1262                  * ziltest causes spa_sync() to think it's committed,
1263                  * but actually it is not, so the intent log contains
1264                  * many txg's worth of changes.
1265                  *
1266                  * In particular, if object N is in the unlinked set in
1267                  * the last txg to actually sync, then it could be
1268                  * actually freed in a later txg and then reallocated
1269                  * in a yet later txg.  This would write a "create
1270                  * object N" record to the intent log.  Normally, this
1271                  * would be fine because the spa_sync() would have
1272                  * written out the fact that object N is free, before
1273                  * we could write the "create object N" intent log
1274                  * record.
1275                  *
1276                  * But when we are in ziltest mode, we advance the "open
1277                  * txg" without actually spa_sync()-ing the changes to
1278                  * disk.  So we would see that object N is still
1279                  * allocated and in the unlinked set, and there is an
1280                  * intent log record saying to allocate it.
1281                  */
1282                 if (spa_writeable(dmu_objset_spa(zfsvfs->z_os))) {
1283                         if (zil_replay_disable) {
1284                                 zil_destroy(zfsvfs->z_log, B_FALSE);
1285                         } else {
1286                                 zfsvfs->z_replay = B_TRUE;
1287                                 zil_replay(zfsvfs->z_os, zfsvfs,
1288                                     zfs_replay_vector);
1289                                 zfsvfs->z_replay = B_FALSE;
1290                         }
1291                 }
1292                 zfsvfs->z_vfs->vfs_flag |= readonly; /* restore readonly bit */
1293         }
1294
1295         /*
1296          * Set the objset user_ptr to track its zfsvfs.
1297          */
1298         mutex_enter(&zfsvfs->z_os->os_user_ptr_lock);
1299         dmu_objset_set_user(zfsvfs->z_os, zfsvfs);
1300         mutex_exit(&zfsvfs->z_os->os_user_ptr_lock);
1301
1302         return (0);
1303 }
1304
1305 extern krwlock_t zfsvfs_lock; /* in zfs_znode.c */
1306
1307 void
1308 zfsvfs_free(zfsvfs_t *zfsvfs)
1309 {
1310         int i;
1311
1312         /*
1313          * This is a barrier to prevent the filesystem from going away in
1314          * zfs_znode_move() until we can safely ensure that the filesystem is
1315          * not unmounted. We consider the filesystem valid before the barrier
1316          * and invalid after the barrier.
1317          */
1318         rw_enter(&zfsvfs_lock, RW_READER);
1319         rw_exit(&zfsvfs_lock);
1320
1321         zfs_fuid_destroy(zfsvfs);
1322
1323         mutex_destroy(&zfsvfs->z_znodes_lock);
1324         mutex_destroy(&zfsvfs->z_lock);
1325         list_destroy(&zfsvfs->z_all_znodes);
1326         rrm_destroy(&zfsvfs->z_teardown_lock);
1327         rms_destroy(&zfsvfs->z_teardown_inactive_lock);
1328         rw_destroy(&zfsvfs->z_fuid_lock);
1329         for (i = 0; i != ZFS_OBJ_MTX_SZ; i++)
1330                 mutex_destroy(&zfsvfs->z_hold_mtx[i]);
1331         kmem_free(zfsvfs, sizeof (zfsvfs_t));
1332 }
1333
1334 static void
1335 zfs_set_fuid_feature(zfsvfs_t *zfsvfs)
1336 {
1337         zfsvfs->z_use_fuids = USE_FUIDS(zfsvfs->z_version, zfsvfs->z_os);
1338         if (zfsvfs->z_vfs) {
1339                 if (zfsvfs->z_use_fuids) {
1340                         vfs_set_feature(zfsvfs->z_vfs, VFSFT_XVATTR);
1341                         vfs_set_feature(zfsvfs->z_vfs, VFSFT_SYSATTR_VIEWS);
1342                         vfs_set_feature(zfsvfs->z_vfs, VFSFT_ACEMASKONACCESS);
1343                         vfs_set_feature(zfsvfs->z_vfs, VFSFT_ACLONCREATE);
1344                         vfs_set_feature(zfsvfs->z_vfs, VFSFT_ACCESS_FILTER);
1345                         vfs_set_feature(zfsvfs->z_vfs, VFSFT_REPARSE);
1346                 } else {
1347                         vfs_clear_feature(zfsvfs->z_vfs, VFSFT_XVATTR);
1348                         vfs_clear_feature(zfsvfs->z_vfs, VFSFT_SYSATTR_VIEWS);
1349                         vfs_clear_feature(zfsvfs->z_vfs, VFSFT_ACEMASKONACCESS);
1350                         vfs_clear_feature(zfsvfs->z_vfs, VFSFT_ACLONCREATE);
1351                         vfs_clear_feature(zfsvfs->z_vfs, VFSFT_ACCESS_FILTER);
1352                         vfs_clear_feature(zfsvfs->z_vfs, VFSFT_REPARSE);
1353                 }
1354         }
1355         zfsvfs->z_use_sa = USE_SA(zfsvfs->z_version, zfsvfs->z_os);
1356 }
1357
1358 static int
1359 zfs_domount(vfs_t *vfsp, char *osname)
1360 {
1361         uint64_t recordsize, fsid_guid;
1362         int error = 0;
1363         zfsvfs_t *zfsvfs;
1364         vnode_t *vp;
1365
1366         ASSERT(vfsp);
1367         ASSERT(osname);
1368
1369         error = zfsvfs_create(osname, &zfsvfs);
1370         if (error)
1371                 return (error);
1372         zfsvfs->z_vfs = vfsp;
1373
1374 #ifdef illumos
1375         /* Initialize the generic filesystem structure. */
1376         vfsp->vfs_bcount = 0;
1377         vfsp->vfs_data = NULL;
1378
1379         if (zfs_create_unique_device(&mount_dev) == -1) {
1380                 error = SET_ERROR(ENODEV);
1381                 goto out;
1382         }
1383         ASSERT(vfs_devismounted(mount_dev) == 0);
1384 #endif
1385
1386         if (error = dsl_prop_get_integer(osname, "recordsize", &recordsize,
1387             NULL))
1388                 goto out;
1389         zfsvfs->z_vfs->vfs_bsize = SPA_MINBLOCKSIZE;
1390         zfsvfs->z_vfs->mnt_stat.f_iosize = recordsize;
1391
1392         vfsp->vfs_data = zfsvfs;
1393         vfsp->mnt_flag |= MNT_LOCAL;
1394 #if defined(_KERNEL) && !defined(KMEM_DEBUG)
1395         vfsp->mnt_kern_flag |= MNTK_FPLOOKUP;
1396 #endif
1397         vfsp->mnt_kern_flag |= MNTK_LOOKUP_SHARED;
1398         vfsp->mnt_kern_flag |= MNTK_SHARED_WRITES;
1399         vfsp->mnt_kern_flag |= MNTK_EXTENDED_SHARED;
1400         vfsp->mnt_kern_flag |= MNTK_NO_IOPF;    /* vn_io_fault can be used */
1401         vfsp->mnt_kern_flag |= MNTK_NOMSYNC;
1402         vfsp->mnt_kern_flag |= MNTK_VMSETSIZE_BUG;
1403
1404         /*
1405          * The fsid is 64 bits, composed of an 8-bit fs type, which
1406          * separates our fsid from any other filesystem types, and a
1407          * 56-bit objset unique ID.  The objset unique ID is unique to
1408          * all objsets open on this system, provided by unique_create().
1409          * The 8-bit fs type must be put in the low bits of fsid[1]
1410          * because that's where other Solaris filesystems put it.
1411          */
1412         fsid_guid = dmu_objset_fsid_guid(zfsvfs->z_os);
1413         ASSERT((fsid_guid & ~((1ULL<<56)-1)) == 0);
1414         vfsp->vfs_fsid.val[0] = fsid_guid;
1415         vfsp->vfs_fsid.val[1] = ((fsid_guid>>32) << 8) |
1416             vfsp->mnt_vfc->vfc_typenum & 0xFF;
1417
1418         /*
1419          * Set features for file system.
1420          */
1421         zfs_set_fuid_feature(zfsvfs);
1422         if (zfsvfs->z_case == ZFS_CASE_INSENSITIVE) {
1423                 vfs_set_feature(vfsp, VFSFT_DIRENTFLAGS);
1424                 vfs_set_feature(vfsp, VFSFT_CASEINSENSITIVE);
1425                 vfs_set_feature(vfsp, VFSFT_NOCASESENSITIVE);
1426         } else if (zfsvfs->z_case == ZFS_CASE_MIXED) {
1427                 vfs_set_feature(vfsp, VFSFT_DIRENTFLAGS);
1428                 vfs_set_feature(vfsp, VFSFT_CASEINSENSITIVE);
1429         }
1430         vfs_set_feature(vfsp, VFSFT_ZEROCOPY_SUPPORTED);
1431
1432         if (dmu_objset_is_snapshot(zfsvfs->z_os)) {
1433                 uint64_t pval;
1434
1435                 atime_changed_cb(zfsvfs, B_FALSE);
1436                 readonly_changed_cb(zfsvfs, B_TRUE);
1437                 if (error = dsl_prop_get_integer(osname, "xattr", &pval, NULL))
1438                         goto out;
1439                 xattr_changed_cb(zfsvfs, pval);
1440                 zfsvfs->z_issnap = B_TRUE;
1441                 zfsvfs->z_os->os_sync = ZFS_SYNC_DISABLED;
1442
1443                 mutex_enter(&zfsvfs->z_os->os_user_ptr_lock);
1444                 dmu_objset_set_user(zfsvfs->z_os, zfsvfs);
1445                 mutex_exit(&zfsvfs->z_os->os_user_ptr_lock);
1446         } else {
1447                 error = zfsvfs_setup(zfsvfs, B_TRUE);
1448         }
1449
1450         vfs_mountedfrom(vfsp, osname);
1451
1452         if (!zfsvfs->z_issnap)
1453                 zfsctl_create(zfsvfs);
1454 out:
1455         if (error) {
1456                 dmu_objset_disown(zfsvfs->z_os, zfsvfs);
1457                 zfsvfs_free(zfsvfs);
1458         } else {
1459                 atomic_inc_32(&zfs_active_fs_count);
1460         }
1461
1462         return (error);
1463 }
1464
1465 void
1466 zfs_unregister_callbacks(zfsvfs_t *zfsvfs)
1467 {
1468         objset_t *os = zfsvfs->z_os;
1469
1470         if (!dmu_objset_is_snapshot(os))
1471                 dsl_prop_unregister_all(dmu_objset_ds(os), zfsvfs);
1472 }
1473
1474 #ifdef SECLABEL
1475 /*
1476  * Convert a decimal digit string to a uint64_t integer.
1477  */
1478 static int
1479 str_to_uint64(char *str, uint64_t *objnum)
1480 {
1481         uint64_t num = 0;
1482
1483         while (*str) {
1484                 if (*str < '0' || *str > '9')
1485                         return (SET_ERROR(EINVAL));
1486
1487                 num = num*10 + *str++ - '0';
1488         }
1489
1490         *objnum = num;
1491         return (0);
1492 }
1493
1494 /*
1495  * The boot path passed from the boot loader is in the form of
1496  * "rootpool-name/root-filesystem-object-number'. Convert this
1497  * string to a dataset name: "rootpool-name/root-filesystem-name".
1498  */
1499 static int
1500 zfs_parse_bootfs(char *bpath, char *outpath)
1501 {
1502         char *slashp;
1503         uint64_t objnum;
1504         int error;
1505
1506         if (*bpath == 0 || *bpath == '/')
1507                 return (SET_ERROR(EINVAL));
1508
1509         (void) strcpy(outpath, bpath);
1510
1511         slashp = strchr(bpath, '/');
1512
1513         /* if no '/', just return the pool name */
1514         if (slashp == NULL) {
1515                 return (0);
1516         }
1517
1518         /* if not a number, just return the root dataset name */
1519         if (str_to_uint64(slashp+1, &objnum)) {
1520                 return (0);
1521         }
1522
1523         *slashp = '\0';
1524         error = dsl_dsobj_to_dsname(bpath, objnum, outpath);
1525         *slashp = '/';
1526
1527         return (error);
1528 }
1529
1530 /*
1531  * Check that the hex label string is appropriate for the dataset being
1532  * mounted into the global_zone proper.
1533  *
1534  * Return an error if the hex label string is not default or
1535  * admin_low/admin_high.  For admin_low labels, the corresponding
1536  * dataset must be readonly.
1537  */
1538 int
1539 zfs_check_global_label(const char *dsname, const char *hexsl)
1540 {
1541         if (strcasecmp(hexsl, ZFS_MLSLABEL_DEFAULT) == 0)
1542                 return (0);
1543         if (strcasecmp(hexsl, ADMIN_HIGH) == 0)
1544                 return (0);
1545         if (strcasecmp(hexsl, ADMIN_LOW) == 0) {
1546                 /* must be readonly */
1547                 uint64_t rdonly;
1548
1549                 if (dsl_prop_get_integer(dsname,
1550                     zfs_prop_to_name(ZFS_PROP_READONLY), &rdonly, NULL))
1551                         return (SET_ERROR(EACCES));
1552                 return (rdonly ? 0 : EACCES);
1553         }
1554         return (SET_ERROR(EACCES));
1555 }
1556
1557 /*
1558  * Determine whether the mount is allowed according to MAC check.
1559  * by comparing (where appropriate) label of the dataset against
1560  * the label of the zone being mounted into.  If the dataset has
1561  * no label, create one.
1562  *
1563  * Returns 0 if access allowed, error otherwise (e.g. EACCES)
1564  */
1565 static int
1566 zfs_mount_label_policy(vfs_t *vfsp, char *osname)
1567 {
1568         int             error, retv;
1569         zone_t          *mntzone = NULL;
1570         ts_label_t      *mnt_tsl;
1571         bslabel_t       *mnt_sl;
1572         bslabel_t       ds_sl;
1573         char            ds_hexsl[MAXNAMELEN];
1574
1575         retv = EACCES;                          /* assume the worst */
1576
1577         /*
1578          * Start by getting the dataset label if it exists.
1579          */
1580         error = dsl_prop_get(osname, zfs_prop_to_name(ZFS_PROP_MLSLABEL),
1581             1, sizeof (ds_hexsl), &ds_hexsl, NULL);
1582         if (error)
1583                 return (SET_ERROR(EACCES));
1584
1585         /*
1586          * If labeling is NOT enabled, then disallow the mount of datasets
1587          * which have a non-default label already.  No other label checks
1588          * are needed.
1589          */
1590         if (!is_system_labeled()) {
1591                 if (strcasecmp(ds_hexsl, ZFS_MLSLABEL_DEFAULT) == 0)
1592                         return (0);
1593                 return (SET_ERROR(EACCES));
1594         }
1595
1596         /*
1597          * Get the label of the mountpoint.  If mounting into the global
1598          * zone (i.e. mountpoint is not within an active zone and the
1599          * zoned property is off), the label must be default or
1600          * admin_low/admin_high only; no other checks are needed.
1601          */
1602         mntzone = zone_find_by_any_path(refstr_value(vfsp->vfs_mntpt), B_FALSE);
1603         if (mntzone->zone_id == GLOBAL_ZONEID) {
1604                 uint64_t zoned;
1605
1606                 zone_rele(mntzone);
1607
1608                 if (dsl_prop_get_integer(osname,
1609                     zfs_prop_to_name(ZFS_PROP_ZONED), &zoned, NULL))
1610                         return (SET_ERROR(EACCES));
1611                 if (!zoned)
1612                         return (zfs_check_global_label(osname, ds_hexsl));
1613                 else
1614                         /*
1615                          * This is the case of a zone dataset being mounted
1616                          * initially, before the zone has been fully created;
1617                          * allow this mount into global zone.
1618                          */
1619                         return (0);
1620         }
1621
1622         mnt_tsl = mntzone->zone_slabel;
1623         ASSERT(mnt_tsl != NULL);
1624         label_hold(mnt_tsl);
1625         mnt_sl = label2bslabel(mnt_tsl);
1626
1627         if (strcasecmp(ds_hexsl, ZFS_MLSLABEL_DEFAULT) == 0) {
1628                 /*
1629                  * The dataset doesn't have a real label, so fabricate one.
1630                  */
1631                 char *str = NULL;
1632
1633                 if (l_to_str_internal(mnt_sl, &str) == 0 &&
1634                     dsl_prop_set_string(osname,
1635                     zfs_prop_to_name(ZFS_PROP_MLSLABEL),
1636                     ZPROP_SRC_LOCAL, str) == 0)
1637                         retv = 0;
1638                 if (str != NULL)
1639                         kmem_free(str, strlen(str) + 1);
1640         } else if (hexstr_to_label(ds_hexsl, &ds_sl) == 0) {
1641                 /*
1642                  * Now compare labels to complete the MAC check.  If the
1643                  * labels are equal then allow access.  If the mountpoint
1644                  * label dominates the dataset label, allow readonly access.
1645                  * Otherwise, access is denied.
1646                  */
1647                 if (blequal(mnt_sl, &ds_sl))
1648                         retv = 0;
1649                 else if (bldominates(mnt_sl, &ds_sl)) {
1650                         vfs_setmntopt(vfsp, MNTOPT_RO, NULL, 0);
1651                         retv = 0;
1652                 }
1653         }
1654
1655         label_rele(mnt_tsl);
1656         zone_rele(mntzone);
1657         return (retv);
1658 }
1659 #endif  /* SECLABEL */
1660
1661 #ifdef OPENSOLARIS_MOUNTROOT
1662 static int
1663 zfs_mountroot(vfs_t *vfsp, enum whymountroot why)
1664 {
1665         int error = 0;
1666         static int zfsrootdone = 0;
1667         zfsvfs_t *zfsvfs = NULL;
1668         znode_t *zp = NULL;
1669         vnode_t *vp = NULL;
1670         char *zfs_bootfs;
1671         char *zfs_devid;
1672
1673         ASSERT(vfsp);
1674
1675         /*
1676          * The filesystem that we mount as root is defined in the
1677          * boot property "zfs-bootfs" with a format of
1678          * "poolname/root-dataset-objnum".
1679          */
1680         if (why == ROOT_INIT) {
1681                 if (zfsrootdone++)
1682                         return (SET_ERROR(EBUSY));
1683                 /*
1684                  * the process of doing a spa_load will require the
1685                  * clock to be set before we could (for example) do
1686                  * something better by looking at the timestamp on
1687                  * an uberblock, so just set it to -1.
1688                  */
1689                 clkset(-1);
1690
1691                 if ((zfs_bootfs = spa_get_bootprop("zfs-bootfs")) == NULL) {
1692                         cmn_err(CE_NOTE, "spa_get_bootfs: can not get "
1693                             "bootfs name");
1694                         return (SET_ERROR(EINVAL));
1695                 }
1696                 zfs_devid = spa_get_bootprop("diskdevid");
1697                 error = spa_import_rootpool(rootfs.bo_name, zfs_devid);
1698                 if (zfs_devid)
1699                         spa_free_bootprop(zfs_devid);
1700                 if (error) {
1701                         spa_free_bootprop(zfs_bootfs);
1702                         cmn_err(CE_NOTE, "spa_import_rootpool: error %d",
1703                             error);
1704                         return (error);
1705                 }
1706                 if (error = zfs_parse_bootfs(zfs_bootfs, rootfs.bo_name)) {
1707                         spa_free_bootprop(zfs_bootfs);
1708                         cmn_err(CE_NOTE, "zfs_parse_bootfs: error %d",
1709                             error);
1710                         return (error);
1711                 }
1712
1713                 spa_free_bootprop(zfs_bootfs);
1714
1715                 if (error = vfs_lock(vfsp))
1716                         return (error);
1717
1718                 if (error = zfs_domount(vfsp, rootfs.bo_name)) {
1719                         cmn_err(CE_NOTE, "zfs_domount: error %d", error);
1720                         goto out;
1721                 }
1722
1723                 zfsvfs = (zfsvfs_t *)vfsp->vfs_data;
1724                 ASSERT(zfsvfs);
1725                 if (error = zfs_zget(zfsvfs, zfsvfs->z_root, &zp)) {
1726                         cmn_err(CE_NOTE, "zfs_zget: error %d", error);
1727                         goto out;
1728                 }
1729
1730                 vp = ZTOV(zp);
1731                 mutex_enter(&vp->v_lock);
1732                 vp->v_flag |= VROOT;
1733                 mutex_exit(&vp->v_lock);
1734                 rootvp = vp;
1735
1736                 /*
1737                  * Leave rootvp held.  The root file system is never unmounted.
1738                  */
1739
1740                 vfs_add((struct vnode *)0, vfsp,
1741                     (vfsp->vfs_flag & VFS_RDONLY) ? MS_RDONLY : 0);
1742 out:
1743                 vfs_unlock(vfsp);
1744                 return (error);
1745         } else if (why == ROOT_REMOUNT) {
1746                 readonly_changed_cb(vfsp->vfs_data, B_FALSE);
1747                 vfsp->vfs_flag |= VFS_REMOUNT;
1748
1749                 /* refresh mount options */
1750                 zfs_unregister_callbacks(vfsp->vfs_data);
1751                 return (zfs_register_callbacks(vfsp));
1752
1753         } else if (why == ROOT_UNMOUNT) {
1754                 zfs_unregister_callbacks((zfsvfs_t *)vfsp->vfs_data);
1755                 (void) zfs_sync(vfsp, 0, 0);
1756                 return (0);
1757         }
1758
1759         /*
1760          * if "why" is equal to anything else other than ROOT_INIT,
1761          * ROOT_REMOUNT, or ROOT_UNMOUNT, we do not support it.
1762          */
1763         return (SET_ERROR(ENOTSUP));
1764 }
1765 #endif  /* OPENSOLARIS_MOUNTROOT */
1766
1767 static int
1768 getpoolname(const char *osname, char *poolname)
1769 {
1770         char *p;
1771
1772         p = strchr(osname, '/');
1773         if (p == NULL) {
1774                 if (strlen(osname) >= MAXNAMELEN)
1775                         return (ENAMETOOLONG);
1776                 (void) strcpy(poolname, osname);
1777         } else {
1778                 if (p - osname >= MAXNAMELEN)
1779                         return (ENAMETOOLONG);
1780                 (void) strncpy(poolname, osname, p - osname);
1781                 poolname[p - osname] = '\0';
1782         }
1783         return (0);
1784 }
1785
1786 static void
1787 fetch_osname_options(char *name, bool *checkpointrewind)
1788 {
1789
1790         if (name[0] == '!') {
1791                 *checkpointrewind = true;
1792                 memmove(name, name + 1, strlen(name));
1793         } else {
1794                 *checkpointrewind = false;
1795         }
1796 }
1797
1798 /*ARGSUSED*/
1799 static int
1800 zfs_mount(vfs_t *vfsp)
1801 {
1802         kthread_t       *td = curthread;
1803         vnode_t         *mvp = vfsp->mnt_vnodecovered;
1804         cred_t          *cr = td->td_ucred;
1805         char            *osname;
1806         int             error = 0;
1807         int             canwrite;
1808         bool            checkpointrewind;
1809
1810 #ifdef illumos
1811         if (mvp->v_type != VDIR)
1812                 return (SET_ERROR(ENOTDIR));
1813
1814         mutex_enter(&mvp->v_lock);
1815         if ((uap->flags & MS_REMOUNT) == 0 &&
1816             (uap->flags & MS_OVERLAY) == 0 &&
1817             (mvp->v_count != 1 || (mvp->v_flag & VROOT))) {
1818                 mutex_exit(&mvp->v_lock);
1819                 return (SET_ERROR(EBUSY));
1820         }
1821         mutex_exit(&mvp->v_lock);
1822
1823         /*
1824          * ZFS does not support passing unparsed data in via MS_DATA.
1825          * Users should use the MS_OPTIONSTR interface; this means
1826          * that all option parsing is already done and the options struct
1827          * can be interrogated.
1828          */
1829         if ((uap->flags & MS_DATA) && uap->datalen > 0)
1830                 return (SET_ERROR(EINVAL));
1831
1832         /*
1833          * Get the objset name (the "special" mount argument).
1834          */
1835         if (error = pn_get(uap->spec, fromspace, &spn))
1836                 return (error);
1837
1838         osname = spn.pn_path;
1839 #else   /* !illumos */
1840         if (vfs_getopt(vfsp->mnt_optnew, "from", (void **)&osname, NULL))
1841                 return (SET_ERROR(EINVAL));
1842
1843         /*
1844          * If full-owner-access is enabled and delegated administration is
1845          * turned on, we must set nosuid.
1846          */
1847         if (zfs_super_owner &&
1848             dsl_deleg_access(osname, ZFS_DELEG_PERM_MOUNT, cr) != ECANCELED) {
1849                 secpolicy_fs_mount_clearopts(cr, vfsp);
1850         }
1851 #endif  /* illumos */
1852         fetch_osname_options(osname, &checkpointrewind);
1853
1854         /*
1855          * Check for mount privilege?
1856          *
1857          * If we don't have privilege then see if
1858          * we have local permission to allow it
1859          */
1860         error = secpolicy_fs_mount(cr, mvp, vfsp);
1861         if (error) {
1862                 if (dsl_deleg_access(osname, ZFS_DELEG_PERM_MOUNT, cr) != 0)
1863                         goto out;
1864
1865                 if (!(vfsp->vfs_flag & MS_REMOUNT)) {
1866                         vattr_t         vattr;
1867
1868                         /*
1869                          * Make sure user is the owner of the mount point
1870                          * or has sufficient privileges.
1871                          */
1872
1873                         vattr.va_mask = AT_UID;
1874
1875                         vn_lock(mvp, LK_SHARED | LK_RETRY);
1876                         if (VOP_GETATTR(mvp, &vattr, cr)) {
1877                                 VOP_UNLOCK(mvp);
1878                                 goto out;
1879                         }
1880
1881                         if (secpolicy_vnode_owner(mvp, cr, vattr.va_uid) != 0 &&
1882                             VOP_ACCESS(mvp, VWRITE, cr, td) != 0) {
1883                                 VOP_UNLOCK(mvp);
1884                                 goto out;
1885                         }
1886                         VOP_UNLOCK(mvp);
1887                 }
1888
1889                 secpolicy_fs_mount_clearopts(cr, vfsp);
1890         }
1891
1892         /*
1893          * Refuse to mount a filesystem if we are in a local zone and the
1894          * dataset is not visible.
1895          */
1896         if (!INGLOBALZONE(curthread) &&
1897             (!zone_dataset_visible(osname, &canwrite) || !canwrite)) {
1898                 error = SET_ERROR(EPERM);
1899                 goto out;
1900         }
1901
1902 #ifdef SECLABEL
1903         error = zfs_mount_label_policy(vfsp, osname);
1904         if (error)
1905                 goto out;
1906 #endif
1907
1908         vfsp->vfs_flag |= MNT_NFS4ACLS;
1909
1910         /*
1911          * When doing a remount, we simply refresh our temporary properties
1912          * according to those options set in the current VFS options.
1913          */
1914         if (vfsp->vfs_flag & MS_REMOUNT) {
1915                 zfsvfs_t *zfsvfs = vfsp->vfs_data;
1916
1917                 /*
1918                  * Refresh mount options with z_teardown_lock blocking I/O while
1919                  * the filesystem is in an inconsistent state.
1920                  * The lock also serializes this code with filesystem
1921                  * manipulations between entry to zfs_suspend_fs() and return
1922                  * from zfs_resume_fs().
1923                  */
1924                 rrm_enter(&zfsvfs->z_teardown_lock, RW_WRITER, FTAG);
1925                 zfs_unregister_callbacks(zfsvfs);
1926                 error = zfs_register_callbacks(vfsp);
1927                 rrm_exit(&zfsvfs->z_teardown_lock, FTAG);
1928                 goto out;
1929         }
1930
1931         /* Initial root mount: try hard to import the requested root pool. */
1932         if ((vfsp->vfs_flag & MNT_ROOTFS) != 0 &&
1933             (vfsp->vfs_flag & MNT_UPDATE) == 0) {
1934                 char pname[MAXNAMELEN];
1935
1936                 error = getpoolname(osname, pname);
1937                 if (error == 0)
1938                         error = spa_import_rootpool(pname, checkpointrewind);
1939                 if (error)
1940                         goto out;
1941         }
1942         DROP_GIANT();
1943         error = zfs_domount(vfsp, osname);
1944         PICKUP_GIANT();
1945
1946 #ifdef illumos
1947         /*
1948          * Add an extra VFS_HOLD on our parent vfs so that it can't
1949          * disappear due to a forced unmount.
1950          */
1951         if (error == 0 && ((zfsvfs_t *)vfsp->vfs_data)->z_issnap)
1952                 VFS_HOLD(mvp->v_vfsp);
1953 #endif
1954
1955 out:
1956         return (error);
1957 }
1958
1959 static int
1960 zfs_statfs(vfs_t *vfsp, struct statfs *statp)
1961 {
1962         zfsvfs_t *zfsvfs = vfsp->vfs_data;
1963         uint64_t refdbytes, availbytes, usedobjs, availobjs;
1964
1965         statp->f_version = STATFS_VERSION;
1966
1967         ZFS_ENTER(zfsvfs);
1968
1969         dmu_objset_space(zfsvfs->z_os,
1970             &refdbytes, &availbytes, &usedobjs, &availobjs);
1971
1972         /*
1973          * The underlying storage pool actually uses multiple block sizes.
1974          * We report the fragsize as the smallest block size we support,
1975          * and we report our blocksize as the filesystem's maximum blocksize.
1976          */
1977         statp->f_bsize = SPA_MINBLOCKSIZE;
1978         statp->f_iosize = zfsvfs->z_vfs->mnt_stat.f_iosize;
1979
1980         /*
1981          * The following report "total" blocks of various kinds in the
1982          * file system, but reported in terms of f_frsize - the
1983          * "fragment" size.
1984          */
1985
1986         statp->f_blocks = (refdbytes + availbytes) >> SPA_MINBLOCKSHIFT;
1987         statp->f_bfree = availbytes / statp->f_bsize;
1988         statp->f_bavail = statp->f_bfree; /* no root reservation */
1989
1990         /*
1991          * statvfs() should really be called statufs(), because it assumes
1992          * static metadata.  ZFS doesn't preallocate files, so the best
1993          * we can do is report the max that could possibly fit in f_files,
1994          * and that minus the number actually used in f_ffree.
1995          * For f_ffree, report the smaller of the number of object available
1996          * and the number of blocks (each object will take at least a block).
1997          */
1998         statp->f_ffree = MIN(availobjs, statp->f_bfree);
1999         statp->f_files = statp->f_ffree + usedobjs;
2000
2001         /*
2002          * We're a zfs filesystem.
2003          */
2004         (void) strlcpy(statp->f_fstypename, "zfs", sizeof(statp->f_fstypename));
2005
2006         strlcpy(statp->f_mntfromname, vfsp->mnt_stat.f_mntfromname,
2007             sizeof(statp->f_mntfromname));
2008         strlcpy(statp->f_mntonname, vfsp->mnt_stat.f_mntonname,
2009             sizeof(statp->f_mntonname));
2010
2011         statp->f_namemax = MAXNAMELEN - 1;
2012
2013         ZFS_EXIT(zfsvfs);
2014         return (0);
2015 }
2016
2017 static int
2018 zfs_root(vfs_t *vfsp, int flags, vnode_t **vpp)
2019 {
2020         zfsvfs_t *zfsvfs = vfsp->vfs_data;
2021         znode_t *rootzp;
2022         int error;
2023
2024         ZFS_ENTER(zfsvfs);
2025
2026         error = zfs_zget(zfsvfs, zfsvfs->z_root, &rootzp);
2027         if (error == 0)
2028                 *vpp = ZTOV(rootzp);
2029
2030         ZFS_EXIT(zfsvfs);
2031
2032         if (error == 0) {
2033                 error = vn_lock(*vpp, flags);
2034                 if (error != 0) {
2035                         VN_RELE(*vpp);
2036                         *vpp = NULL;
2037                 }
2038         }
2039         return (error);
2040 }
2041
2042 /*
2043  * Teardown the zfsvfs::z_os.
2044  *
2045  * Note, if 'unmounting' is FALSE, we return with the 'z_teardown_lock'
2046  * and 'z_teardown_inactive_lock' held.
2047  */
2048 static int
2049 zfsvfs_teardown(zfsvfs_t *zfsvfs, boolean_t unmounting)
2050 {
2051         znode_t *zp;
2052
2053         rrm_enter(&zfsvfs->z_teardown_lock, RW_WRITER, FTAG);
2054
2055         if (!unmounting) {
2056                 /*
2057                  * We purge the parent filesystem's vfsp as the parent
2058                  * filesystem and all of its snapshots have their vnode's
2059                  * v_vfsp set to the parent's filesystem's vfsp.  Note,
2060                  * 'z_parent' is self referential for non-snapshots.
2061                  */
2062                 (void) dnlc_purge_vfsp(zfsvfs->z_parent->z_vfs, 0);
2063 #ifdef FREEBSD_NAMECACHE
2064                 cache_purgevfs(zfsvfs->z_parent->z_vfs, true);
2065 #endif
2066         }
2067
2068         /*
2069          * Close the zil. NB: Can't close the zil while zfs_inactive
2070          * threads are blocked as zil_close can call zfs_inactive.
2071          */
2072         if (zfsvfs->z_log) {
2073                 zil_close(zfsvfs->z_log);
2074                 zfsvfs->z_log = NULL;
2075         }
2076
2077         ZFS_WLOCK_TEARDOWN_INACTIVE(zfsvfs);
2078
2079         /*
2080          * If we are not unmounting (ie: online recv) and someone already
2081          * unmounted this file system while we were doing the switcheroo,
2082          * or a reopen of z_os failed then just bail out now.
2083          */
2084         if (!unmounting && (zfsvfs->z_unmounted || zfsvfs->z_os == NULL)) {
2085                 ZFS_WUNLOCK_TEARDOWN_INACTIVE(zfsvfs);
2086                 rrm_exit(&zfsvfs->z_teardown_lock, FTAG);
2087                 return (SET_ERROR(EIO));
2088         }
2089
2090         /*
2091          * At this point there are no vops active, and any new vops will
2092          * fail with EIO since we have z_teardown_lock for writer (only
2093          * relavent for forced unmount).
2094          *
2095          * Release all holds on dbufs.
2096          */
2097         mutex_enter(&zfsvfs->z_znodes_lock);
2098         for (zp = list_head(&zfsvfs->z_all_znodes); zp != NULL;
2099             zp = list_next(&zfsvfs->z_all_znodes, zp))
2100                 if (zp->z_sa_hdl) {
2101                         ASSERT(ZTOV(zp)->v_count >= 0);
2102                         zfs_znode_dmu_fini(zp);
2103                 }
2104         mutex_exit(&zfsvfs->z_znodes_lock);
2105
2106         /*
2107          * If we are unmounting, set the unmounted flag and let new vops
2108          * unblock.  zfs_inactive will have the unmounted behavior, and all
2109          * other vops will fail with EIO.
2110          */
2111         if (unmounting) {
2112                 zfsvfs->z_unmounted = B_TRUE;
2113                 ZFS_WUNLOCK_TEARDOWN_INACTIVE(zfsvfs);
2114                 rrm_exit(&zfsvfs->z_teardown_lock, FTAG);
2115         }
2116
2117         /*
2118          * z_os will be NULL if there was an error in attempting to reopen
2119          * zfsvfs, so just return as the properties had already been
2120          * unregistered and cached data had been evicted before.
2121          */
2122         if (zfsvfs->z_os == NULL)
2123                 return (0);
2124
2125         /*
2126          * Unregister properties.
2127          */
2128         zfs_unregister_callbacks(zfsvfs);
2129
2130         /*
2131          * Evict cached data
2132          */
2133         if (dsl_dataset_is_dirty(dmu_objset_ds(zfsvfs->z_os)) &&
2134             !(zfsvfs->z_vfs->vfs_flag & VFS_RDONLY))
2135                 txg_wait_synced(dmu_objset_pool(zfsvfs->z_os), 0);
2136         dmu_objset_evict_dbufs(zfsvfs->z_os);
2137
2138         return (0);
2139 }
2140
2141 /*ARGSUSED*/
2142 static int
2143 zfs_umount(vfs_t *vfsp, int fflag)
2144 {
2145         kthread_t *td = curthread;
2146         zfsvfs_t *zfsvfs = vfsp->vfs_data;
2147         objset_t *os;
2148         cred_t *cr = td->td_ucred;
2149         int ret;
2150
2151         ret = secpolicy_fs_unmount(cr, vfsp);
2152         if (ret) {
2153                 if (dsl_deleg_access((char *)refstr_value(vfsp->vfs_resource),
2154                     ZFS_DELEG_PERM_MOUNT, cr))
2155                         return (ret);
2156         }
2157
2158         /*
2159          * We purge the parent filesystem's vfsp as the parent filesystem
2160          * and all of its snapshots have their vnode's v_vfsp set to the
2161          * parent's filesystem's vfsp.  Note, 'z_parent' is self
2162          * referential for non-snapshots.
2163          */
2164         (void) dnlc_purge_vfsp(zfsvfs->z_parent->z_vfs, 0);
2165
2166         /*
2167          * Unmount any snapshots mounted under .zfs before unmounting the
2168          * dataset itself.
2169          */
2170         if (zfsvfs->z_ctldir != NULL) {
2171                 if ((ret = zfsctl_umount_snapshots(vfsp, fflag, cr)) != 0)
2172                         return (ret);
2173         }
2174
2175         if (fflag & MS_FORCE) {
2176                 /*
2177                  * Mark file system as unmounted before calling
2178                  * vflush(FORCECLOSE). This way we ensure no future vnops
2179                  * will be called and risk operating on DOOMED vnodes.
2180                  */
2181                 rrm_enter(&zfsvfs->z_teardown_lock, RW_WRITER, FTAG);
2182                 zfsvfs->z_unmounted = B_TRUE;
2183                 rrm_exit(&zfsvfs->z_teardown_lock, FTAG);
2184         }
2185
2186         /*
2187          * Flush all the files.
2188          */
2189         ret = vflush(vfsp, 0, (fflag & MS_FORCE) ? FORCECLOSE : 0, td);
2190         if (ret != 0)
2191                 return (ret);
2192
2193 #ifdef illumos
2194         if (!(fflag & MS_FORCE)) {
2195                 /*
2196                  * Check the number of active vnodes in the file system.
2197                  * Our count is maintained in the vfs structure, but the
2198                  * number is off by 1 to indicate a hold on the vfs
2199                  * structure itself.
2200                  *
2201                  * The '.zfs' directory maintains a reference of its
2202                  * own, and any active references underneath are
2203                  * reflected in the vnode count.
2204                  */
2205                 if (zfsvfs->z_ctldir == NULL) {
2206                         if (vfsp->vfs_count > 1)
2207                                 return (SET_ERROR(EBUSY));
2208                 } else {
2209                         if (vfsp->vfs_count > 2 ||
2210                             zfsvfs->z_ctldir->v_count > 1)
2211                                 return (SET_ERROR(EBUSY));
2212                 }
2213         }
2214 #endif
2215
2216         while (taskqueue_cancel(zfsvfs_taskq->tq_queue,
2217             &zfsvfs->z_unlinked_drain_task, NULL) != 0)
2218                 taskqueue_drain(zfsvfs_taskq->tq_queue,
2219                     &zfsvfs->z_unlinked_drain_task);
2220
2221         VERIFY(zfsvfs_teardown(zfsvfs, B_TRUE) == 0);
2222         os = zfsvfs->z_os;
2223
2224         /*
2225          * z_os will be NULL if there was an error in
2226          * attempting to reopen zfsvfs.
2227          */
2228         if (os != NULL) {
2229                 /*
2230                  * Unset the objset user_ptr.
2231                  */
2232                 mutex_enter(&os->os_user_ptr_lock);
2233                 dmu_objset_set_user(os, NULL);
2234                 mutex_exit(&os->os_user_ptr_lock);
2235
2236                 /*
2237                  * Finally release the objset
2238                  */
2239                 dmu_objset_disown(os, zfsvfs);
2240         }
2241
2242         /*
2243          * We can now safely destroy the '.zfs' directory node.
2244          */
2245         if (zfsvfs->z_ctldir != NULL)
2246                 zfsctl_destroy(zfsvfs);
2247         zfs_freevfs(vfsp);
2248
2249         return (0);
2250 }
2251
2252 static int
2253 zfs_vget(vfs_t *vfsp, ino_t ino, int flags, vnode_t **vpp)
2254 {
2255         zfsvfs_t        *zfsvfs = vfsp->vfs_data;
2256         znode_t         *zp;
2257         int             err;
2258
2259         /*
2260          * zfs_zget() can't operate on virtual entries like .zfs/ or
2261          * .zfs/snapshot/ directories, that's why we return EOPNOTSUPP.
2262          * This will make NFS to switch to LOOKUP instead of using VGET.
2263          */
2264         if (ino == ZFSCTL_INO_ROOT || ino == ZFSCTL_INO_SNAPDIR ||
2265             (zfsvfs->z_shares_dir != 0 && ino == zfsvfs->z_shares_dir))
2266                 return (EOPNOTSUPP);
2267
2268         ZFS_ENTER(zfsvfs);
2269         err = zfs_zget(zfsvfs, ino, &zp);
2270         if (err == 0 && zp->z_unlinked) {
2271                 vrele(ZTOV(zp));
2272                 err = EINVAL;
2273         }
2274         if (err == 0)
2275                 *vpp = ZTOV(zp);
2276         ZFS_EXIT(zfsvfs);
2277         if (err == 0) {
2278                 err = vn_lock(*vpp, flags);
2279                 if (err != 0)
2280                         vrele(*vpp);
2281         }
2282         if (err != 0)
2283                 *vpp = NULL;
2284         return (err);
2285 }
2286
2287 static int
2288 zfs_checkexp(vfs_t *vfsp, struct sockaddr *nam, uint64_t *extflagsp,
2289     struct ucred **credanonp, int *numsecflavors, int *secflavors)
2290 {
2291         zfsvfs_t *zfsvfs = vfsp->vfs_data;
2292
2293         /*
2294          * If this is regular file system vfsp is the same as
2295          * zfsvfs->z_parent->z_vfs, but if it is snapshot,
2296          * zfsvfs->z_parent->z_vfs represents parent file system
2297          * which we have to use here, because only this file system
2298          * has mnt_export configured.
2299          */
2300         return (vfs_stdcheckexp(zfsvfs->z_parent->z_vfs, nam, extflagsp,
2301             credanonp, numsecflavors, secflavors));
2302 }
2303
2304 CTASSERT(SHORT_FID_LEN <= sizeof(struct fid));
2305 CTASSERT(LONG_FID_LEN <= sizeof(struct fid));
2306
2307 static int
2308 zfs_fhtovp(vfs_t *vfsp, fid_t *fidp, int flags, vnode_t **vpp)
2309 {
2310         struct componentname cn;
2311         zfsvfs_t        *zfsvfs = vfsp->vfs_data;
2312         znode_t         *zp;
2313         vnode_t         *dvp;
2314         uint64_t        object = 0;
2315         uint64_t        fid_gen = 0;
2316         uint64_t        gen_mask;
2317         uint64_t        zp_gen;
2318         int             i, err;
2319
2320         *vpp = NULL;
2321
2322         ZFS_ENTER(zfsvfs);
2323
2324         /*
2325          * On FreeBSD we can get snapshot's mount point or its parent file
2326          * system mount point depending if snapshot is already mounted or not.
2327          */
2328         if (zfsvfs->z_parent == zfsvfs && fidp->fid_len == LONG_FID_LEN) {
2329                 zfid_long_t     *zlfid = (zfid_long_t *)fidp;
2330                 uint64_t        objsetid = 0;
2331                 uint64_t        setgen = 0;
2332
2333                 for (i = 0; i < sizeof (zlfid->zf_setid); i++)
2334                         objsetid |= ((uint64_t)zlfid->zf_setid[i]) << (8 * i);
2335
2336                 for (i = 0; i < sizeof (zlfid->zf_setgen); i++)
2337                         setgen |= ((uint64_t)zlfid->zf_setgen[i]) << (8 * i);
2338
2339                 ZFS_EXIT(zfsvfs);
2340
2341                 err = zfsctl_lookup_objset(vfsp, objsetid, &zfsvfs);
2342                 if (err)
2343                         return (SET_ERROR(EINVAL));
2344                 ZFS_ENTER(zfsvfs);
2345         }
2346
2347         if (fidp->fid_len == SHORT_FID_LEN || fidp->fid_len == LONG_FID_LEN) {
2348                 zfid_short_t    *zfid = (zfid_short_t *)fidp;
2349
2350                 for (i = 0; i < sizeof (zfid->zf_object); i++)
2351                         object |= ((uint64_t)zfid->zf_object[i]) << (8 * i);
2352
2353                 for (i = 0; i < sizeof (zfid->zf_gen); i++)
2354                         fid_gen |= ((uint64_t)zfid->zf_gen[i]) << (8 * i);
2355         } else {
2356                 ZFS_EXIT(zfsvfs);
2357                 return (SET_ERROR(EINVAL));
2358         }
2359
2360         /*
2361          * A zero fid_gen means we are in .zfs or the .zfs/snapshot
2362          * directory tree. If the object == zfsvfs->z_shares_dir, then
2363          * we are in the .zfs/shares directory tree.
2364          */
2365         if ((fid_gen == 0 &&
2366              (object == ZFSCTL_INO_ROOT || object == ZFSCTL_INO_SNAPDIR)) ||
2367             (zfsvfs->z_shares_dir != 0 && object == zfsvfs->z_shares_dir)) {
2368                 ZFS_EXIT(zfsvfs);
2369                 VERIFY0(zfsctl_root(zfsvfs, LK_SHARED, &dvp));
2370                 if (object == ZFSCTL_INO_SNAPDIR) {
2371                         cn.cn_nameptr = "snapshot";
2372                         cn.cn_namelen = strlen(cn.cn_nameptr);
2373                         cn.cn_nameiop = LOOKUP;
2374                         cn.cn_flags = ISLASTCN | LOCKLEAF;
2375                         cn.cn_lkflags = flags;
2376                         VERIFY0(VOP_LOOKUP(dvp, vpp, &cn));
2377                         vput(dvp);
2378                 } else if (object == zfsvfs->z_shares_dir) {
2379                         /*
2380                          * XXX This branch must not be taken,
2381                          * if it is, then the lookup below will
2382                          * explode.
2383                          */
2384                         cn.cn_nameptr = "shares";
2385                         cn.cn_namelen = strlen(cn.cn_nameptr);
2386                         cn.cn_nameiop = LOOKUP;
2387                         cn.cn_flags = ISLASTCN;
2388                         cn.cn_lkflags = flags;
2389                         VERIFY0(VOP_LOOKUP(dvp, vpp, &cn));
2390                         vput(dvp);
2391                 } else {
2392                         *vpp = dvp;
2393                 }
2394                 return (err);
2395         }
2396
2397         gen_mask = -1ULL >> (64 - 8 * i);
2398
2399         dprintf("getting %llu [%u mask %llx]\n", object, fid_gen, gen_mask);
2400         if (err = zfs_zget(zfsvfs, object, &zp)) {
2401                 ZFS_EXIT(zfsvfs);
2402                 return (err);
2403         }
2404         (void) sa_lookup(zp->z_sa_hdl, SA_ZPL_GEN(zfsvfs), &zp_gen,
2405             sizeof (uint64_t));
2406         zp_gen = zp_gen & gen_mask;
2407         if (zp_gen == 0)
2408                 zp_gen = 1;
2409         if (zp->z_unlinked || zp_gen != fid_gen) {
2410                 dprintf("znode gen (%u) != fid gen (%u)\n", zp_gen, fid_gen);
2411                 vrele(ZTOV(zp));
2412                 ZFS_EXIT(zfsvfs);
2413                 return (SET_ERROR(EINVAL));
2414         }
2415
2416         *vpp = ZTOV(zp);
2417         ZFS_EXIT(zfsvfs);
2418         err = vn_lock(*vpp, flags);
2419         if (err == 0)
2420                 vnode_create_vobject(*vpp, zp->z_size, curthread);
2421         else
2422                 *vpp = NULL;
2423         return (err);
2424 }
2425
2426 /*
2427  * Block out VOPs and close zfsvfs_t::z_os
2428  *
2429  * Note, if successful, then we return with the 'z_teardown_lock' and
2430  * 'z_teardown_inactive_lock' write held.  We leave ownership of the underlying
2431  * dataset and objset intact so that they can be atomically handed off during
2432  * a subsequent rollback or recv operation and the resume thereafter.
2433  */
2434 int
2435 zfs_suspend_fs(zfsvfs_t *zfsvfs)
2436 {
2437         int error;
2438
2439         if ((error = zfsvfs_teardown(zfsvfs, B_FALSE)) != 0)
2440                 return (error);
2441
2442         return (0);
2443 }
2444
2445 /*
2446  * Rebuild SA and release VOPs.  Note that ownership of the underlying dataset
2447  * is an invariant across any of the operations that can be performed while the
2448  * filesystem was suspended.  Whether it succeeded or failed, the preconditions
2449  * are the same: the relevant objset and associated dataset are owned by
2450  * zfsvfs, held, and long held on entry.
2451  */
2452 int
2453 zfs_resume_fs(zfsvfs_t *zfsvfs, dsl_dataset_t *ds)
2454 {
2455         int err;
2456         znode_t *zp;
2457
2458         ASSERT(RRM_WRITE_HELD(&zfsvfs->z_teardown_lock));
2459         ASSERT(ZFS_TEARDOWN_INACTIVE_WLOCKED(zfsvfs));
2460
2461         /*
2462          * We already own this, so just update the objset_t, as the one we
2463          * had before may have been evicted.
2464          */
2465         objset_t *os;
2466         VERIFY3P(ds->ds_owner, ==, zfsvfs);
2467         VERIFY(dsl_dataset_long_held(ds));
2468         VERIFY0(dmu_objset_from_ds(ds, &os));
2469
2470         err = zfsvfs_init(zfsvfs, os);
2471         if (err != 0)
2472                 goto bail;
2473
2474         VERIFY(zfsvfs_setup(zfsvfs, B_FALSE) == 0);
2475
2476         zfs_set_fuid_feature(zfsvfs);
2477
2478         /*
2479          * Attempt to re-establish all the active znodes with
2480          * their dbufs.  If a zfs_rezget() fails, then we'll let
2481          * any potential callers discover that via ZFS_ENTER_VERIFY_VP
2482          * when they try to use their znode.
2483          */
2484         mutex_enter(&zfsvfs->z_znodes_lock);
2485         for (zp = list_head(&zfsvfs->z_all_znodes); zp;
2486             zp = list_next(&zfsvfs->z_all_znodes, zp)) {
2487                 (void) zfs_rezget(zp);
2488         }
2489         mutex_exit(&zfsvfs->z_znodes_lock);
2490
2491 bail:
2492         /* release the VOPs */
2493         ZFS_WUNLOCK_TEARDOWN_INACTIVE(zfsvfs);
2494         rrm_exit(&zfsvfs->z_teardown_lock, FTAG);
2495
2496         if (err) {
2497                 /*
2498                  * Since we couldn't setup the sa framework, try to force
2499                  * unmount this file system.
2500                  */
2501                 if (vn_vfswlock(zfsvfs->z_vfs->vfs_vnodecovered) == 0) {
2502                         vfs_ref(zfsvfs->z_vfs);
2503                         (void) dounmount(zfsvfs->z_vfs, MS_FORCE, curthread);
2504                 }
2505         }
2506         return (err);
2507 }
2508
2509 static void
2510 zfs_freevfs(vfs_t *vfsp)
2511 {
2512         zfsvfs_t *zfsvfs = vfsp->vfs_data;
2513
2514 #ifdef illumos
2515         /*
2516          * If this is a snapshot, we have an extra VFS_HOLD on our parent
2517          * from zfs_mount().  Release it here.  If we came through
2518          * zfs_mountroot() instead, we didn't grab an extra hold, so
2519          * skip the VFS_RELE for rootvfs.
2520          */
2521         if (zfsvfs->z_issnap && (vfsp != rootvfs))
2522                 VFS_RELE(zfsvfs->z_parent->z_vfs);
2523 #endif
2524
2525         zfsvfs_free(zfsvfs);
2526
2527         atomic_dec_32(&zfs_active_fs_count);
2528 }
2529
2530 #ifdef __i386__
2531 static int desiredvnodes_backup;
2532 #endif
2533
2534 static void
2535 zfs_vnodes_adjust(void)
2536 {
2537 #ifdef __i386__
2538         int newdesiredvnodes;
2539
2540         desiredvnodes_backup = desiredvnodes;
2541
2542         /*
2543          * We calculate newdesiredvnodes the same way it is done in
2544          * vntblinit(). If it is equal to desiredvnodes, it means that
2545          * it wasn't tuned by the administrator and we can tune it down.
2546          */
2547         newdesiredvnodes = min(maxproc + vm_cnt.v_page_count / 4, 2 *
2548             vm_kmem_size / (5 * (sizeof(struct vm_object) +
2549             sizeof(struct vnode))));
2550         if (newdesiredvnodes == desiredvnodes)
2551                 desiredvnodes = (3 * newdesiredvnodes) / 4;
2552 #endif
2553 }
2554
2555 static void
2556 zfs_vnodes_adjust_back(void)
2557 {
2558
2559 #ifdef __i386__
2560         desiredvnodes = desiredvnodes_backup;
2561 #endif
2562 }
2563
2564 void
2565 zfs_init(void)
2566 {
2567
2568         printf("ZFS filesystem version: " ZPL_VERSION_STRING "\n");
2569
2570         /*
2571          * Initialize .zfs directory structures
2572          */
2573         zfsctl_init();
2574
2575         /*
2576          * Initialize znode cache, vnode ops, etc...
2577          */
2578         zfs_znode_init();
2579
2580         /*
2581          * Reduce number of vnodes. Originally number of vnodes is calculated
2582          * with UFS inode in mind. We reduce it here, because it's too big for
2583          * ZFS/i386.
2584          */
2585         zfs_vnodes_adjust();
2586
2587         dmu_objset_register_type(DMU_OST_ZFS, zfs_space_delta_cb);
2588 #if defined(__FreeBSD__)
2589         zfsvfs_taskq = taskq_create("zfsvfs", 1, minclsyspri, 0, 0, 0);
2590 #endif
2591 }
2592
2593 void
2594 zfs_fini(void)
2595 {
2596 #if defined(__FreeBSD__)
2597         taskq_destroy(zfsvfs_taskq);
2598 #endif
2599         zfsctl_fini();
2600         zfs_znode_fini();
2601         zfs_vnodes_adjust_back();
2602 }
2603
2604 int
2605 zfs_busy(void)
2606 {
2607         return (zfs_active_fs_count != 0);
2608 }
2609
2610 int
2611 zfs_set_version(zfsvfs_t *zfsvfs, uint64_t newvers)
2612 {
2613         int error;
2614         objset_t *os = zfsvfs->z_os;
2615         dmu_tx_t *tx;
2616
2617         if (newvers < ZPL_VERSION_INITIAL || newvers > ZPL_VERSION)
2618                 return (SET_ERROR(EINVAL));
2619
2620         if (newvers < zfsvfs->z_version)
2621                 return (SET_ERROR(EINVAL));
2622
2623         if (zfs_spa_version_map(newvers) >
2624             spa_version(dmu_objset_spa(zfsvfs->z_os)))
2625                 return (SET_ERROR(ENOTSUP));
2626
2627         tx = dmu_tx_create(os);
2628         dmu_tx_hold_zap(tx, MASTER_NODE_OBJ, B_FALSE, ZPL_VERSION_STR);
2629         if (newvers >= ZPL_VERSION_SA && !zfsvfs->z_use_sa) {
2630                 dmu_tx_hold_zap(tx, MASTER_NODE_OBJ, B_TRUE,
2631                     ZFS_SA_ATTRS);
2632                 dmu_tx_hold_zap(tx, DMU_NEW_OBJECT, FALSE, NULL);
2633         }
2634         error = dmu_tx_assign(tx, TXG_WAIT);
2635         if (error) {
2636                 dmu_tx_abort(tx);
2637                 return (error);
2638         }
2639
2640         error = zap_update(os, MASTER_NODE_OBJ, ZPL_VERSION_STR,
2641             8, 1, &newvers, tx);
2642
2643         if (error) {
2644                 dmu_tx_commit(tx);
2645                 return (error);
2646         }
2647
2648         if (newvers >= ZPL_VERSION_SA && !zfsvfs->z_use_sa) {
2649                 uint64_t sa_obj;
2650
2651                 ASSERT3U(spa_version(dmu_objset_spa(zfsvfs->z_os)), >=,
2652                     SPA_VERSION_SA);
2653                 sa_obj = zap_create(os, DMU_OT_SA_MASTER_NODE,
2654                     DMU_OT_NONE, 0, tx);
2655
2656                 error = zap_add(os, MASTER_NODE_OBJ,
2657                     ZFS_SA_ATTRS, 8, 1, &sa_obj, tx);
2658                 ASSERT0(error);
2659
2660                 VERIFY(0 == sa_set_sa_object(os, sa_obj));
2661                 sa_register_update_callback(os, zfs_sa_upgrade);
2662         }
2663
2664         spa_history_log_internal_ds(dmu_objset_ds(os), "upgrade", tx,
2665             "from %llu to %llu", zfsvfs->z_version, newvers);
2666
2667         dmu_tx_commit(tx);
2668
2669         zfsvfs->z_version = newvers;
2670         os->os_version = newvers;
2671
2672         zfs_set_fuid_feature(zfsvfs);
2673
2674         return (0);
2675 }
2676
2677 /*
2678  * Read a property stored within the master node.
2679  */
2680 int
2681 zfs_get_zplprop(objset_t *os, zfs_prop_t prop, uint64_t *value)
2682 {
2683         uint64_t *cached_copy = NULL;
2684
2685         /*
2686          * Figure out where in the objset_t the cached copy would live, if it
2687          * is available for the requested property.
2688          */
2689         if (os != NULL) {
2690                 switch (prop) {
2691                 case ZFS_PROP_VERSION:
2692                         cached_copy = &os->os_version;
2693                         break;
2694                 case ZFS_PROP_NORMALIZE:
2695                         cached_copy = &os->os_normalization;
2696                         break;
2697                 case ZFS_PROP_UTF8ONLY:
2698                         cached_copy = &os->os_utf8only;
2699                         break;
2700                 case ZFS_PROP_CASE:
2701                         cached_copy = &os->os_casesensitivity;
2702                         break;
2703                 default:
2704                         break;
2705                 }
2706         }
2707         if (cached_copy != NULL && *cached_copy != OBJSET_PROP_UNINITIALIZED) {
2708                 *value = *cached_copy;
2709                 return (0);
2710         }
2711
2712         /*
2713          * If the property wasn't cached, look up the file system's value for
2714          * the property. For the version property, we look up a slightly
2715          * different string.
2716          */
2717         const char *pname;
2718         int error = ENOENT;
2719         if (prop == ZFS_PROP_VERSION) {
2720                 pname = ZPL_VERSION_STR;
2721         } else {
2722                 pname = zfs_prop_to_name(prop);
2723         }
2724
2725         if (os != NULL) {
2726                 ASSERT3U(os->os_phys->os_type, ==, DMU_OST_ZFS);
2727                 error = zap_lookup(os, MASTER_NODE_OBJ, pname, 8, 1, value);
2728         }
2729
2730         if (error == ENOENT) {
2731                 /* No value set, use the default value */
2732                 switch (prop) {
2733                 case ZFS_PROP_VERSION:
2734                         *value = ZPL_VERSION;
2735                         break;
2736                 case ZFS_PROP_NORMALIZE:
2737                 case ZFS_PROP_UTF8ONLY:
2738                         *value = 0;
2739                         break;
2740                 case ZFS_PROP_CASE:
2741                         *value = ZFS_CASE_SENSITIVE;
2742                         break;
2743                 default:
2744                         return (error);
2745                 }
2746                 error = 0;
2747         }
2748
2749         /*
2750          * If one of the methods for getting the property value above worked,
2751          * copy it into the objset_t's cache.
2752          */
2753         if (error == 0 && cached_copy != NULL) {
2754                 *cached_copy = *value;
2755         }
2756
2757         return (error);
2758 }
2759
2760 /*
2761  * Return true if the coresponding vfs's unmounted flag is set.
2762  * Otherwise return false.
2763  * If this function returns true we know VFS unmount has been initiated.
2764  */
2765 boolean_t
2766 zfs_get_vfs_flag_unmounted(objset_t *os)
2767 {
2768         zfsvfs_t *zfvp;
2769         boolean_t unmounted = B_FALSE;
2770
2771         ASSERT(dmu_objset_type(os) == DMU_OST_ZFS);
2772
2773         mutex_enter(&os->os_user_ptr_lock);
2774         zfvp = dmu_objset_get_user(os);
2775         if (zfvp != NULL && zfvp->z_vfs != NULL &&
2776             (zfvp->z_vfs->mnt_kern_flag & MNTK_UNMOUNT))
2777                 unmounted = B_TRUE;
2778         mutex_exit(&os->os_user_ptr_lock);
2779
2780         return (unmounted);
2781 }
2782
2783 #ifdef _KERNEL
2784 void
2785 zfsvfs_update_fromname(const char *oldname, const char *newname)
2786 {
2787         char tmpbuf[MAXPATHLEN];
2788         struct mount *mp;
2789         char *fromname;
2790         size_t oldlen;
2791
2792         oldlen = strlen(oldname);
2793
2794         mtx_lock(&mountlist_mtx);
2795         TAILQ_FOREACH(mp, &mountlist, mnt_list) {
2796                 fromname = mp->mnt_stat.f_mntfromname;
2797                 if (strcmp(fromname, oldname) == 0) {
2798                         (void)strlcpy(fromname, newname,
2799                             sizeof(mp->mnt_stat.f_mntfromname));
2800                         continue;
2801                 }
2802                 if (strncmp(fromname, oldname, oldlen) == 0 &&
2803                     (fromname[oldlen] == '/' || fromname[oldlen] == '@')) {
2804                         (void)snprintf(tmpbuf, sizeof(tmpbuf), "%s%s",
2805                             newname, fromname + oldlen);
2806                         (void)strlcpy(fromname, tmpbuf,
2807                             sizeof(mp->mnt_stat.f_mntfromname));
2808                         continue;
2809                 }
2810         }
2811         mtx_unlock(&mountlist_mtx);
2812 }
2813 #endif