f68dde85f82eddebda6e63a5e367b2ae08740c4c
[zfs.git] / module / 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  */
24
25 /* Portions Copyright 2010 Robert Milkowski */
26
27 #include <sys/types.h>
28 #include <sys/param.h>
29 #include <sys/systm.h>
30 #include <sys/sysmacros.h>
31 #include <sys/kmem.h>
32 #include <sys/pathname.h>
33 #include <sys/vnode.h>
34 #include <sys/vfs.h>
35 #include <sys/vfs_opreg.h>
36 #include <sys/mntent.h>
37 #include <sys/mount.h>
38 #include <sys/cmn_err.h>
39 #include "fs/fs_subr.h"
40 #include <sys/zfs_znode.h>
41 #include <sys/zfs_dir.h>
42 #include <sys/zil.h>
43 #include <sys/fs/zfs.h>
44 #include <sys/dmu.h>
45 #include <sys/dsl_prop.h>
46 #include <sys/dsl_dataset.h>
47 #include <sys/dsl_deleg.h>
48 #include <sys/spa.h>
49 #include <sys/zap.h>
50 #include <sys/sa.h>
51 #include <sys/varargs.h>
52 #include <sys/policy.h>
53 #include <sys/atomic.h>
54 #include <sys/mkdev.h>
55 #include <sys/modctl.h>
56 #include <sys/refstr.h>
57 #include <sys/zfs_ioctl.h>
58 #include <sys/zfs_ctldir.h>
59 #include <sys/zfs_fuid.h>
60 #include <sys/bootconf.h>
61 #include <sys/sunddi.h>
62 #include <sys/dnlc.h>
63 #include <sys/dmu_objset.h>
64 #include <sys/spa_boot.h>
65 #include <sys/sa.h>
66 #include "zfs_comutil.h"
67
68 int zfsfstype;
69 vfsops_t *zfs_vfsops = NULL;
70 static major_t zfs_major;
71 static minor_t zfs_minor;
72 static kmutex_t zfs_dev_mtx;
73
74 extern int sys_shutdown;
75
76 static int zfs_mount(vfs_t *vfsp, vnode_t *mvp, struct mounta *uap, cred_t *cr);
77 static int zfs_umount(vfs_t *vfsp, int fflag, cred_t *cr);
78 static int zfs_mountroot(vfs_t *vfsp, enum whymountroot);
79 static int zfs_root(vfs_t *vfsp, vnode_t **vpp);
80 static int zfs_statvfs(vfs_t *vfsp, struct statvfs64 *statp);
81 static int zfs_vget(vfs_t *vfsp, vnode_t **vpp, fid_t *fidp);
82 static void zfs_freevfs(vfs_t *vfsp);
83
84 static const fs_operation_def_t zfs_vfsops_template[] = {
85         VFSNAME_MOUNT,          { .vfs_mount = zfs_mount },
86         VFSNAME_MOUNTROOT,      { .vfs_mountroot = zfs_mountroot },
87         VFSNAME_UNMOUNT,        { .vfs_unmount = zfs_umount },
88         VFSNAME_ROOT,           { .vfs_root = zfs_root },
89         VFSNAME_STATVFS,        { .vfs_statvfs = zfs_statvfs },
90         VFSNAME_SYNC,           { .vfs_sync = zfs_sync },
91         VFSNAME_VGET,           { .vfs_vget = zfs_vget },
92         VFSNAME_FREEVFS,        { .vfs_freevfs = zfs_freevfs },
93         NULL,                   NULL
94 };
95
96 static const fs_operation_def_t zfs_vfsops_eio_template[] = {
97         VFSNAME_FREEVFS,        { .vfs_freevfs =  zfs_freevfs },
98         NULL,                   NULL
99 };
100
101 /*
102  * We need to keep a count of active fs's.
103  * This is necessary to prevent our module
104  * from being unloaded after a umount -f
105  */
106 static uint32_t zfs_active_fs_count = 0;
107
108 static char *noatime_cancel[] = { MNTOPT_ATIME, NULL };
109 static char *atime_cancel[] = { MNTOPT_NOATIME, NULL };
110 static char *noxattr_cancel[] = { MNTOPT_XATTR, NULL };
111 static char *xattr_cancel[] = { MNTOPT_NOXATTR, NULL };
112
113 /*
114  * MO_DEFAULT is not used since the default value is determined
115  * by the equivalent property.
116  */
117 static mntopt_t mntopts[] = {
118         { MNTOPT_NOXATTR, noxattr_cancel, NULL, 0, NULL },
119         { MNTOPT_XATTR, xattr_cancel, NULL, 0, NULL },
120         { MNTOPT_NOATIME, noatime_cancel, NULL, 0, NULL },
121         { MNTOPT_ATIME, atime_cancel, NULL, 0, NULL }
122 };
123
124 static mntopts_t zfs_mntopts = {
125         sizeof (mntopts) / sizeof (mntopt_t),
126         mntopts
127 };
128
129 /*ARGSUSED*/
130 int
131 zfs_sync(vfs_t *vfsp, short flag, cred_t *cr)
132 {
133         /*
134          * Data integrity is job one.  We don't want a compromised kernel
135          * writing to the storage pool, so we never sync during panic.
136          */
137         if (panicstr)
138                 return (0);
139
140         /*
141          * SYNC_ATTR is used by fsflush() to force old filesystems like UFS
142          * to sync metadata, which they would otherwise cache indefinitely.
143          * Semantically, the only requirement is that the sync be initiated.
144          * The DMU syncs out txgs frequently, so there's nothing to do.
145          */
146         if (flag & SYNC_ATTR)
147                 return (0);
148
149         if (vfsp != NULL) {
150                 /*
151                  * Sync a specific filesystem.
152                  */
153                 zfsvfs_t *zfsvfs = vfsp->vfs_data;
154                 dsl_pool_t *dp;
155
156                 ZFS_ENTER(zfsvfs);
157                 dp = dmu_objset_pool(zfsvfs->z_os);
158
159                 /*
160                  * If the system is shutting down, then skip any
161                  * filesystems which may exist on a suspended pool.
162                  */
163                 if (sys_shutdown && spa_suspended(dp->dp_spa)) {
164                         ZFS_EXIT(zfsvfs);
165                         return (0);
166                 }
167
168                 if (zfsvfs->z_log != NULL)
169                         zil_commit(zfsvfs->z_log, UINT64_MAX, 0);
170
171                 ZFS_EXIT(zfsvfs);
172         } else {
173                 /*
174                  * Sync all ZFS filesystems.  This is what happens when you
175                  * run sync(1M).  Unlike other filesystems, ZFS honors the
176                  * request by waiting for all pools to commit all dirty data.
177                  */
178                 spa_sync_allpools();
179         }
180
181         return (0);
182 }
183
184 static int
185 zfs_create_unique_device(dev_t *dev)
186 {
187         major_t new_major;
188
189         do {
190                 ASSERT3U(zfs_minor, <=, MAXMIN32);
191                 minor_t start = zfs_minor;
192                 do {
193                         mutex_enter(&zfs_dev_mtx);
194                         if (zfs_minor >= MAXMIN32) {
195                                 /*
196                                  * If we're still using the real major
197                                  * keep out of /dev/zfs and /dev/zvol minor
198                                  * number space.  If we're using a getudev()'ed
199                                  * major number, we can use all of its minors.
200                                  */
201                                 if (zfs_major == ddi_name_to_major(ZFS_DRIVER))
202                                         zfs_minor = ZFS_MIN_MINOR;
203                                 else
204                                         zfs_minor = 0;
205                         } else {
206                                 zfs_minor++;
207                         }
208                         *dev = makedevice(zfs_major, zfs_minor);
209                         mutex_exit(&zfs_dev_mtx);
210                 } while (vfs_devismounted(*dev) && zfs_minor != start);
211                 if (zfs_minor == start) {
212                         /*
213                          * We are using all ~262,000 minor numbers for the
214                          * current major number.  Create a new major number.
215                          */
216                         if ((new_major = getudev()) == (major_t)-1) {
217                                 cmn_err(CE_WARN,
218                                     "zfs_mount: Can't get unique major "
219                                     "device number.");
220                                 return (-1);
221                         }
222                         mutex_enter(&zfs_dev_mtx);
223                         zfs_major = new_major;
224                         zfs_minor = 0;
225
226                         mutex_exit(&zfs_dev_mtx);
227                 } else {
228                         break;
229                 }
230                 /* CONSTANTCONDITION */
231         } while (1);
232
233         return (0);
234 }
235
236 static void
237 atime_changed_cb(void *arg, uint64_t newval)
238 {
239         zfsvfs_t *zfsvfs = arg;
240
241         if (newval == TRUE) {
242                 zfsvfs->z_atime = TRUE;
243                 vfs_clearmntopt(zfsvfs->z_vfs, MNTOPT_NOATIME);
244                 vfs_setmntopt(zfsvfs->z_vfs, MNTOPT_ATIME, NULL, 0);
245         } else {
246                 zfsvfs->z_atime = FALSE;
247                 vfs_clearmntopt(zfsvfs->z_vfs, MNTOPT_ATIME);
248                 vfs_setmntopt(zfsvfs->z_vfs, MNTOPT_NOATIME, NULL, 0);
249         }
250 }
251
252 static void
253 xattr_changed_cb(void *arg, uint64_t newval)
254 {
255         zfsvfs_t *zfsvfs = arg;
256
257         if (newval == TRUE) {
258                 /* XXX locking on vfs_flag? */
259                 zfsvfs->z_vfs->vfs_flag |= VFS_XATTR;
260                 vfs_clearmntopt(zfsvfs->z_vfs, MNTOPT_NOXATTR);
261                 vfs_setmntopt(zfsvfs->z_vfs, MNTOPT_XATTR, NULL, 0);
262         } else {
263                 /* XXX locking on vfs_flag? */
264                 zfsvfs->z_vfs->vfs_flag &= ~VFS_XATTR;
265                 vfs_clearmntopt(zfsvfs->z_vfs, MNTOPT_XATTR);
266                 vfs_setmntopt(zfsvfs->z_vfs, MNTOPT_NOXATTR, NULL, 0);
267         }
268 }
269
270 static void
271 blksz_changed_cb(void *arg, uint64_t newval)
272 {
273         zfsvfs_t *zfsvfs = arg;
274
275         if (newval < SPA_MINBLOCKSIZE ||
276             newval > SPA_MAXBLOCKSIZE || !ISP2(newval))
277                 newval = SPA_MAXBLOCKSIZE;
278
279         zfsvfs->z_max_blksz = newval;
280         zfsvfs->z_vfs->vfs_bsize = newval;
281 }
282
283 static void
284 readonly_changed_cb(void *arg, uint64_t newval)
285 {
286         zfsvfs_t *zfsvfs = arg;
287
288         if (newval) {
289                 /* XXX locking on vfs_flag? */
290                 zfsvfs->z_vfs->vfs_flag |= VFS_RDONLY;
291                 vfs_clearmntopt(zfsvfs->z_vfs, MNTOPT_RW);
292                 vfs_setmntopt(zfsvfs->z_vfs, MNTOPT_RO, NULL, 0);
293         } else {
294                 /* XXX locking on vfs_flag? */
295                 zfsvfs->z_vfs->vfs_flag &= ~VFS_RDONLY;
296                 vfs_clearmntopt(zfsvfs->z_vfs, MNTOPT_RO);
297                 vfs_setmntopt(zfsvfs->z_vfs, MNTOPT_RW, NULL, 0);
298         }
299 }
300
301 static void
302 devices_changed_cb(void *arg, uint64_t newval)
303 {
304         zfsvfs_t *zfsvfs = arg;
305
306         if (newval == FALSE) {
307                 zfsvfs->z_vfs->vfs_flag |= VFS_NODEVICES;
308                 vfs_clearmntopt(zfsvfs->z_vfs, MNTOPT_DEVICES);
309                 vfs_setmntopt(zfsvfs->z_vfs, MNTOPT_NODEVICES, NULL, 0);
310         } else {
311                 zfsvfs->z_vfs->vfs_flag &= ~VFS_NODEVICES;
312                 vfs_clearmntopt(zfsvfs->z_vfs, MNTOPT_NODEVICES);
313                 vfs_setmntopt(zfsvfs->z_vfs, MNTOPT_DEVICES, NULL, 0);
314         }
315 }
316
317 static void
318 setuid_changed_cb(void *arg, uint64_t newval)
319 {
320         zfsvfs_t *zfsvfs = arg;
321
322         if (newval == FALSE) {
323                 zfsvfs->z_vfs->vfs_flag |= VFS_NOSETUID;
324                 vfs_clearmntopt(zfsvfs->z_vfs, MNTOPT_SETUID);
325                 vfs_setmntopt(zfsvfs->z_vfs, MNTOPT_NOSETUID, NULL, 0);
326         } else {
327                 zfsvfs->z_vfs->vfs_flag &= ~VFS_NOSETUID;
328                 vfs_clearmntopt(zfsvfs->z_vfs, MNTOPT_NOSETUID);
329                 vfs_setmntopt(zfsvfs->z_vfs, MNTOPT_SETUID, NULL, 0);
330         }
331 }
332
333 static void
334 exec_changed_cb(void *arg, uint64_t newval)
335 {
336         zfsvfs_t *zfsvfs = arg;
337
338         if (newval == FALSE) {
339                 zfsvfs->z_vfs->vfs_flag |= VFS_NOEXEC;
340                 vfs_clearmntopt(zfsvfs->z_vfs, MNTOPT_EXEC);
341                 vfs_setmntopt(zfsvfs->z_vfs, MNTOPT_NOEXEC, NULL, 0);
342         } else {
343                 zfsvfs->z_vfs->vfs_flag &= ~VFS_NOEXEC;
344                 vfs_clearmntopt(zfsvfs->z_vfs, MNTOPT_NOEXEC);
345                 vfs_setmntopt(zfsvfs->z_vfs, MNTOPT_EXEC, NULL, 0);
346         }
347 }
348
349 /*
350  * The nbmand mount option can be changed at mount time.
351  * We can't allow it to be toggled on live file systems or incorrect
352  * behavior may be seen from cifs clients
353  *
354  * This property isn't registered via dsl_prop_register(), but this callback
355  * will be called when a file system is first mounted
356  */
357 static void
358 nbmand_changed_cb(void *arg, uint64_t newval)
359 {
360         zfsvfs_t *zfsvfs = arg;
361         if (newval == FALSE) {
362                 vfs_clearmntopt(zfsvfs->z_vfs, MNTOPT_NBMAND);
363                 vfs_setmntopt(zfsvfs->z_vfs, MNTOPT_NONBMAND, NULL, 0);
364         } else {
365                 vfs_clearmntopt(zfsvfs->z_vfs, MNTOPT_NONBMAND);
366                 vfs_setmntopt(zfsvfs->z_vfs, MNTOPT_NBMAND, NULL, 0);
367         }
368 }
369
370 static void
371 snapdir_changed_cb(void *arg, uint64_t newval)
372 {
373         zfsvfs_t *zfsvfs = arg;
374
375         zfsvfs->z_show_ctldir = newval;
376 }
377
378 static void
379 vscan_changed_cb(void *arg, uint64_t newval)
380 {
381         zfsvfs_t *zfsvfs = arg;
382
383         zfsvfs->z_vscan = newval;
384 }
385
386 static void
387 acl_inherit_changed_cb(void *arg, uint64_t newval)
388 {
389         zfsvfs_t *zfsvfs = arg;
390
391         zfsvfs->z_acl_inherit = newval;
392 }
393
394 static int
395 zfs_register_callbacks(vfs_t *vfsp)
396 {
397         struct dsl_dataset *ds = NULL;
398         objset_t *os = NULL;
399         zfsvfs_t *zfsvfs = NULL;
400         uint64_t nbmand;
401         int readonly, do_readonly = B_FALSE;
402         int setuid, do_setuid = B_FALSE;
403         int exec, do_exec = B_FALSE;
404         int devices, do_devices = B_FALSE;
405         int xattr, do_xattr = B_FALSE;
406         int atime, do_atime = B_FALSE;
407         int error = 0;
408
409         ASSERT(vfsp);
410         zfsvfs = vfsp->vfs_data;
411         ASSERT(zfsvfs);
412         os = zfsvfs->z_os;
413
414         /*
415          * The act of registering our callbacks will destroy any mount
416          * options we may have.  In order to enable temporary overrides
417          * of mount options, we stash away the current values and
418          * restore them after we register the callbacks.
419          */
420         if (vfs_optionisset(vfsp, MNTOPT_RO, NULL)) {
421                 readonly = B_TRUE;
422                 do_readonly = B_TRUE;
423         } else if (vfs_optionisset(vfsp, MNTOPT_RW, NULL)) {
424                 readonly = B_FALSE;
425                 do_readonly = B_TRUE;
426         }
427         if (vfs_optionisset(vfsp, MNTOPT_NOSUID, NULL)) {
428                 devices = B_FALSE;
429                 setuid = B_FALSE;
430                 do_devices = B_TRUE;
431                 do_setuid = B_TRUE;
432         } else {
433                 if (vfs_optionisset(vfsp, MNTOPT_NODEVICES, NULL)) {
434                         devices = B_FALSE;
435                         do_devices = B_TRUE;
436                 } else if (vfs_optionisset(vfsp, MNTOPT_DEVICES, NULL)) {
437                         devices = B_TRUE;
438                         do_devices = B_TRUE;
439                 }
440
441                 if (vfs_optionisset(vfsp, MNTOPT_NOSETUID, NULL)) {
442                         setuid = B_FALSE;
443                         do_setuid = B_TRUE;
444                 } else if (vfs_optionisset(vfsp, MNTOPT_SETUID, NULL)) {
445                         setuid = B_TRUE;
446                         do_setuid = B_TRUE;
447                 }
448         }
449         if (vfs_optionisset(vfsp, MNTOPT_NOEXEC, NULL)) {
450                 exec = B_FALSE;
451                 do_exec = B_TRUE;
452         } else if (vfs_optionisset(vfsp, MNTOPT_EXEC, NULL)) {
453                 exec = B_TRUE;
454                 do_exec = B_TRUE;
455         }
456         if (vfs_optionisset(vfsp, MNTOPT_NOXATTR, NULL)) {
457                 xattr = B_FALSE;
458                 do_xattr = B_TRUE;
459         } else if (vfs_optionisset(vfsp, MNTOPT_XATTR, NULL)) {
460                 xattr = B_TRUE;
461                 do_xattr = B_TRUE;
462         }
463         if (vfs_optionisset(vfsp, MNTOPT_NOATIME, NULL)) {
464                 atime = B_FALSE;
465                 do_atime = B_TRUE;
466         } else if (vfs_optionisset(vfsp, MNTOPT_ATIME, NULL)) {
467                 atime = B_TRUE;
468                 do_atime = B_TRUE;
469         }
470
471         /*
472          * nbmand is a special property.  It can only be changed at
473          * mount time.
474          *
475          * This is weird, but it is documented to only be changeable
476          * at mount time.
477          */
478         if (vfs_optionisset(vfsp, MNTOPT_NONBMAND, NULL)) {
479                 nbmand = B_FALSE;
480         } else if (vfs_optionisset(vfsp, MNTOPT_NBMAND, NULL)) {
481                 nbmand = B_TRUE;
482         } else {
483                 char osname[MAXNAMELEN];
484
485                 dmu_objset_name(os, osname);
486                 if (error = dsl_prop_get_integer(osname, "nbmand", &nbmand,
487                     NULL)) {
488                         return (error);
489                 }
490         }
491
492         /*
493          * Register property callbacks.
494          *
495          * It would probably be fine to just check for i/o error from
496          * the first prop_register(), but I guess I like to go
497          * overboard...
498          */
499         ds = dmu_objset_ds(os);
500         error = dsl_prop_register(ds, "atime", atime_changed_cb, zfsvfs);
501         error = error ? error : dsl_prop_register(ds,
502             "xattr", xattr_changed_cb, zfsvfs);
503         error = error ? error : dsl_prop_register(ds,
504             "recordsize", blksz_changed_cb, zfsvfs);
505         error = error ? error : dsl_prop_register(ds,
506             "readonly", readonly_changed_cb, zfsvfs);
507         error = error ? error : dsl_prop_register(ds,
508             "devices", devices_changed_cb, zfsvfs);
509         error = error ? error : dsl_prop_register(ds,
510             "setuid", setuid_changed_cb, zfsvfs);
511         error = error ? error : dsl_prop_register(ds,
512             "exec", exec_changed_cb, zfsvfs);
513         error = error ? error : dsl_prop_register(ds,
514             "snapdir", snapdir_changed_cb, zfsvfs);
515         error = error ? error : dsl_prop_register(ds,
516             "aclinherit", acl_inherit_changed_cb, zfsvfs);
517         error = error ? error : dsl_prop_register(ds,
518             "vscan", vscan_changed_cb, zfsvfs);
519         if (error)
520                 goto unregister;
521
522         /*
523          * Invoke our callbacks to restore temporary mount options.
524          */
525         if (do_readonly)
526                 readonly_changed_cb(zfsvfs, readonly);
527         if (do_setuid)
528                 setuid_changed_cb(zfsvfs, setuid);
529         if (do_exec)
530                 exec_changed_cb(zfsvfs, exec);
531         if (do_devices)
532                 devices_changed_cb(zfsvfs, devices);
533         if (do_xattr)
534                 xattr_changed_cb(zfsvfs, xattr);
535         if (do_atime)
536                 atime_changed_cb(zfsvfs, atime);
537
538         nbmand_changed_cb(zfsvfs, nbmand);
539
540         return (0);
541
542 unregister:
543         /*
544          * We may attempt to unregister some callbacks that are not
545          * registered, but this is OK; it will simply return ENOMSG,
546          * which we will ignore.
547          */
548         (void) dsl_prop_unregister(ds, "atime", atime_changed_cb, zfsvfs);
549         (void) dsl_prop_unregister(ds, "xattr", xattr_changed_cb, zfsvfs);
550         (void) dsl_prop_unregister(ds, "recordsize", blksz_changed_cb, zfsvfs);
551         (void) dsl_prop_unregister(ds, "readonly", readonly_changed_cb, zfsvfs);
552         (void) dsl_prop_unregister(ds, "devices", devices_changed_cb, zfsvfs);
553         (void) dsl_prop_unregister(ds, "setuid", setuid_changed_cb, zfsvfs);
554         (void) dsl_prop_unregister(ds, "exec", exec_changed_cb, zfsvfs);
555         (void) dsl_prop_unregister(ds, "snapdir", snapdir_changed_cb, zfsvfs);
556         (void) dsl_prop_unregister(ds, "aclinherit", acl_inherit_changed_cb,
557             zfsvfs);
558         (void) dsl_prop_unregister(ds, "vscan", vscan_changed_cb, zfsvfs);
559         return (error);
560
561 }
562
563 static int
564 zfs_space_delta_cb(dmu_object_type_t bonustype, void *data,
565     uint64_t *userp, uint64_t *groupp)
566 {
567         znode_phys_t *znp = data;
568         int error = 0;
569
570         /*
571          * Is it a valid type of object to track?
572          */
573         if (bonustype != DMU_OT_ZNODE && bonustype != DMU_OT_SA)
574                 return (ENOENT);
575
576         /*
577          * If we have a NULL data pointer
578          * then assume the id's aren't changing and
579          * return EEXIST to the dmu to let it know to
580          * use the same ids
581          */
582         if (data == NULL)
583                 return (EEXIST);
584
585         if (bonustype == DMU_OT_ZNODE) {
586                 *userp = znp->zp_uid;
587                 *groupp = znp->zp_gid;
588         } else {
589                 int hdrsize;
590
591                 ASSERT(bonustype == DMU_OT_SA);
592                 hdrsize = sa_hdrsize(data);
593
594                 if (hdrsize != 0) {
595                         *userp = *((uint64_t *)((uintptr_t)data + hdrsize +
596                             SA_UID_OFFSET));
597                         *groupp = *((uint64_t *)((uintptr_t)data + hdrsize +
598                             SA_GID_OFFSET));
599                 } else {
600                         /*
601                          * This should only happen for newly created
602                          * files that haven't had the znode data filled
603                          * in yet.
604                          */
605                         *userp = 0;
606                         *groupp = 0;
607                 }
608         }
609         return (error);
610 }
611
612 static void
613 fuidstr_to_sid(zfsvfs_t *zfsvfs, const char *fuidstr,
614     char *domainbuf, int buflen, uid_t *ridp)
615 {
616         uint64_t fuid;
617         const char *domain;
618
619         fuid = strtonum(fuidstr, NULL);
620
621         domain = zfs_fuid_find_by_idx(zfsvfs, FUID_INDEX(fuid));
622         if (domain)
623                 (void) strlcpy(domainbuf, domain, buflen);
624         else
625                 domainbuf[0] = '\0';
626         *ridp = FUID_RID(fuid);
627 }
628
629 static uint64_t
630 zfs_userquota_prop_to_obj(zfsvfs_t *zfsvfs, zfs_userquota_prop_t type)
631 {
632         switch (type) {
633         case ZFS_PROP_USERUSED:
634                 return (DMU_USERUSED_OBJECT);
635         case ZFS_PROP_GROUPUSED:
636                 return (DMU_GROUPUSED_OBJECT);
637         case ZFS_PROP_USERQUOTA:
638                 return (zfsvfs->z_userquota_obj);
639         case ZFS_PROP_GROUPQUOTA:
640                 return (zfsvfs->z_groupquota_obj);
641         }
642         return (0);
643 }
644
645 int
646 zfs_userspace_many(zfsvfs_t *zfsvfs, zfs_userquota_prop_t type,
647     uint64_t *cookiep, void *vbuf, uint64_t *bufsizep)
648 {
649         int error;
650         zap_cursor_t zc;
651         zap_attribute_t za;
652         zfs_useracct_t *buf = vbuf;
653         uint64_t obj;
654
655         if (!dmu_objset_userspace_present(zfsvfs->z_os))
656                 return (ENOTSUP);
657
658         obj = zfs_userquota_prop_to_obj(zfsvfs, type);
659         if (obj == 0) {
660                 *bufsizep = 0;
661                 return (0);
662         }
663
664         for (zap_cursor_init_serialized(&zc, zfsvfs->z_os, obj, *cookiep);
665             (error = zap_cursor_retrieve(&zc, &za)) == 0;
666             zap_cursor_advance(&zc)) {
667                 if ((uintptr_t)buf - (uintptr_t)vbuf + sizeof (zfs_useracct_t) >
668                     *bufsizep)
669                         break;
670
671                 fuidstr_to_sid(zfsvfs, za.za_name,
672                     buf->zu_domain, sizeof (buf->zu_domain), &buf->zu_rid);
673
674                 buf->zu_space = za.za_first_integer;
675                 buf++;
676         }
677         if (error == ENOENT)
678                 error = 0;
679
680         ASSERT3U((uintptr_t)buf - (uintptr_t)vbuf, <=, *bufsizep);
681         *bufsizep = (uintptr_t)buf - (uintptr_t)vbuf;
682         *cookiep = zap_cursor_serialize(&zc);
683         zap_cursor_fini(&zc);
684         return (error);
685 }
686
687 /*
688  * buf must be big enough (eg, 32 bytes)
689  */
690 static int
691 id_to_fuidstr(zfsvfs_t *zfsvfs, const char *domain, uid_t rid,
692     char *buf, boolean_t addok)
693 {
694         uint64_t fuid;
695         int domainid = 0;
696
697         if (domain && domain[0]) {
698                 domainid = zfs_fuid_find_by_domain(zfsvfs, domain, NULL, addok);
699                 if (domainid == -1)
700                         return (ENOENT);
701         }
702         fuid = FUID_ENCODE(domainid, rid);
703         (void) sprintf(buf, "%llx", (longlong_t)fuid);
704         return (0);
705 }
706
707 int
708 zfs_userspace_one(zfsvfs_t *zfsvfs, zfs_userquota_prop_t type,
709     const char *domain, uint64_t rid, uint64_t *valp)
710 {
711         char buf[32];
712         int err;
713         uint64_t obj;
714
715         *valp = 0;
716
717         if (!dmu_objset_userspace_present(zfsvfs->z_os))
718                 return (ENOTSUP);
719
720         obj = zfs_userquota_prop_to_obj(zfsvfs, type);
721         if (obj == 0)
722                 return (0);
723
724         err = id_to_fuidstr(zfsvfs, domain, rid, buf, B_FALSE);
725         if (err)
726                 return (err);
727
728         err = zap_lookup(zfsvfs->z_os, obj, buf, 8, 1, valp);
729         if (err == ENOENT)
730                 err = 0;
731         return (err);
732 }
733
734 int
735 zfs_set_userquota(zfsvfs_t *zfsvfs, zfs_userquota_prop_t type,
736     const char *domain, uint64_t rid, uint64_t quota)
737 {
738         char buf[32];
739         int err;
740         dmu_tx_t *tx;
741         uint64_t *objp;
742         boolean_t fuid_dirtied;
743
744         if (type != ZFS_PROP_USERQUOTA && type != ZFS_PROP_GROUPQUOTA)
745                 return (EINVAL);
746
747         if (zfsvfs->z_version < ZPL_VERSION_USERSPACE)
748                 return (ENOTSUP);
749
750         objp = (type == ZFS_PROP_USERQUOTA) ? &zfsvfs->z_userquota_obj :
751             &zfsvfs->z_groupquota_obj;
752
753         err = id_to_fuidstr(zfsvfs, domain, rid, buf, B_TRUE);
754         if (err)
755                 return (err);
756         fuid_dirtied = zfsvfs->z_fuid_dirty;
757
758         tx = dmu_tx_create(zfsvfs->z_os);
759         dmu_tx_hold_zap(tx, *objp ? *objp : DMU_NEW_OBJECT, B_TRUE, NULL);
760         if (*objp == 0) {
761                 dmu_tx_hold_zap(tx, MASTER_NODE_OBJ, B_TRUE,
762                     zfs_userquota_prop_prefixes[type]);
763         }
764         if (fuid_dirtied)
765                 zfs_fuid_txhold(zfsvfs, tx);
766         err = dmu_tx_assign(tx, TXG_WAIT);
767         if (err) {
768                 dmu_tx_abort(tx);
769                 return (err);
770         }
771
772         mutex_enter(&zfsvfs->z_lock);
773         if (*objp == 0) {
774                 *objp = zap_create(zfsvfs->z_os, DMU_OT_USERGROUP_QUOTA,
775                     DMU_OT_NONE, 0, tx);
776                 VERIFY(0 == zap_add(zfsvfs->z_os, MASTER_NODE_OBJ,
777                     zfs_userquota_prop_prefixes[type], 8, 1, objp, tx));
778         }
779         mutex_exit(&zfsvfs->z_lock);
780
781         if (quota == 0) {
782                 err = zap_remove(zfsvfs->z_os, *objp, buf, tx);
783                 if (err == ENOENT)
784                         err = 0;
785         } else {
786                 err = zap_update(zfsvfs->z_os, *objp, buf, 8, 1, &quota, tx);
787         }
788         ASSERT(err == 0);
789         if (fuid_dirtied)
790                 zfs_fuid_sync(zfsvfs, tx);
791         dmu_tx_commit(tx);
792         return (err);
793 }
794
795 boolean_t
796 zfs_fuid_overquota(zfsvfs_t *zfsvfs, boolean_t isgroup, uint64_t fuid)
797 {
798         char buf[32];
799         uint64_t used, quota, usedobj, quotaobj;
800         int err;
801
802         usedobj = isgroup ? DMU_GROUPUSED_OBJECT : DMU_USERUSED_OBJECT;
803         quotaobj = isgroup ? zfsvfs->z_groupquota_obj : zfsvfs->z_userquota_obj;
804
805         if (quotaobj == 0 || zfsvfs->z_replay)
806                 return (B_FALSE);
807
808         (void) sprintf(buf, "%llx", (longlong_t)fuid);
809         err = zap_lookup(zfsvfs->z_os, quotaobj, buf, 8, 1, &quota);
810         if (err != 0)
811                 return (B_FALSE);
812
813         err = zap_lookup(zfsvfs->z_os, usedobj, buf, 8, 1, &used);
814         if (err != 0)
815                 return (B_FALSE);
816         return (used >= quota);
817 }
818
819 boolean_t
820 zfs_owner_overquota(zfsvfs_t *zfsvfs, znode_t *zp, boolean_t isgroup)
821 {
822         uint64_t fuid;
823         uint64_t quotaobj;
824         uid_t id;
825
826         quotaobj = isgroup ? zfsvfs->z_groupquota_obj : zfsvfs->z_userquota_obj;
827
828         id = isgroup ? zp->z_gid : zp->z_uid;
829
830         if (quotaobj == 0 || zfsvfs->z_replay)
831                 return (B_FALSE);
832
833         if (IS_EPHEMERAL(id)) {
834                 VERIFY(0 == sa_lookup(zp->z_sa_hdl,
835                     isgroup ? SA_ZPL_GID(zfsvfs) : SA_ZPL_UID(zfsvfs),
836                     &fuid, sizeof (fuid)));
837         } else {
838                 fuid = (uint64_t)id;
839         }
840
841         return (zfs_fuid_overquota(zfsvfs, isgroup, fuid));
842 }
843
844 int
845 zfsvfs_create(const char *osname, zfsvfs_t **zfvp)
846 {
847         objset_t *os;
848         zfsvfs_t *zfsvfs;
849         uint64_t zval;
850         int i, error;
851         uint64_t sa_obj;
852
853         zfsvfs = kmem_zalloc(sizeof (zfsvfs_t), KM_SLEEP);
854
855         /*
856          * We claim to always be readonly so we can open snapshots;
857          * other ZPL code will prevent us from writing to snapshots.
858          */
859         error = dmu_objset_own(osname, DMU_OST_ZFS, B_TRUE, zfsvfs, &os);
860         if (error) {
861                 kmem_free(zfsvfs, sizeof (zfsvfs_t));
862                 return (error);
863         }
864
865         /*
866          * Initialize the zfs-specific filesystem structure.
867          * Should probably make this a kmem cache, shuffle fields,
868          * and just bzero up to z_hold_mtx[].
869          */
870         zfsvfs->z_vfs = NULL;
871         zfsvfs->z_parent = zfsvfs;
872         zfsvfs->z_max_blksz = SPA_MAXBLOCKSIZE;
873         zfsvfs->z_show_ctldir = ZFS_SNAPDIR_VISIBLE;
874         zfsvfs->z_os = os;
875
876         error = zfs_get_zplprop(os, ZFS_PROP_VERSION, &zfsvfs->z_version);
877         if (error) {
878                 goto out;
879         } else if (zfsvfs->z_version >
880             zfs_zpl_version_map(spa_version(dmu_objset_spa(os)))) {
881                 (void) printf("Can't mount a version %lld file system "
882                     "on a version %lld pool\n. Pool must be upgraded to mount "
883                     "this file system.", (u_longlong_t)zfsvfs->z_version,
884                     (u_longlong_t)spa_version(dmu_objset_spa(os)));
885                 error = ENOTSUP;
886                 goto out;
887         }
888         if ((error = zfs_get_zplprop(os, ZFS_PROP_NORMALIZE, &zval)) != 0)
889                 goto out;
890         zfsvfs->z_norm = (int)zval;
891
892         if ((error = zfs_get_zplprop(os, ZFS_PROP_UTF8ONLY, &zval)) != 0)
893                 goto out;
894         zfsvfs->z_utf8 = (zval != 0);
895
896         if ((error = zfs_get_zplprop(os, ZFS_PROP_CASE, &zval)) != 0)
897                 goto out;
898         zfsvfs->z_case = (uint_t)zval;
899
900         /*
901          * Fold case on file systems that are always or sometimes case
902          * insensitive.
903          */
904         if (zfsvfs->z_case == ZFS_CASE_INSENSITIVE ||
905             zfsvfs->z_case == ZFS_CASE_MIXED)
906                 zfsvfs->z_norm |= U8_TEXTPREP_TOUPPER;
907
908         zfsvfs->z_use_fuids = USE_FUIDS(zfsvfs->z_version, zfsvfs->z_os);
909         zfsvfs->z_use_sa = USE_SA(zfsvfs->z_version, zfsvfs->z_os);
910
911         if (zfsvfs->z_use_sa) {
912                 /* should either have both of these objects or none */
913                 error = zap_lookup(os, MASTER_NODE_OBJ, ZFS_SA_ATTRS, 8, 1,
914                     &sa_obj);
915                 if (error)
916                         return (error);
917         } else {
918                 /*
919                  * Pre SA versions file systems should never touch
920                  * either the attribute registration or layout objects.
921                  */
922                 sa_obj = 0;
923         }
924
925         zfsvfs->z_attr_table = sa_setup(os, sa_obj, zfs_attr_table, ZPL_END);
926
927         if (zfsvfs->z_version >= ZPL_VERSION_SA)
928                 sa_register_update_callback(os, zfs_sa_upgrade);
929
930         error = zap_lookup(os, MASTER_NODE_OBJ, ZFS_ROOT_OBJ, 8, 1,
931             &zfsvfs->z_root);
932         if (error)
933                 goto out;
934         ASSERT(zfsvfs->z_root != 0);
935
936         error = zap_lookup(os, MASTER_NODE_OBJ, ZFS_UNLINKED_SET, 8, 1,
937             &zfsvfs->z_unlinkedobj);
938         if (error)
939                 goto out;
940
941         error = zap_lookup(os, MASTER_NODE_OBJ,
942             zfs_userquota_prop_prefixes[ZFS_PROP_USERQUOTA],
943             8, 1, &zfsvfs->z_userquota_obj);
944         if (error && error != ENOENT)
945                 goto out;
946
947         error = zap_lookup(os, MASTER_NODE_OBJ,
948             zfs_userquota_prop_prefixes[ZFS_PROP_GROUPQUOTA],
949             8, 1, &zfsvfs->z_groupquota_obj);
950         if (error && error != ENOENT)
951                 goto out;
952
953         error = zap_lookup(os, MASTER_NODE_OBJ, ZFS_FUID_TABLES, 8, 1,
954             &zfsvfs->z_fuid_obj);
955         if (error && error != ENOENT)
956                 goto out;
957
958         error = zap_lookup(os, MASTER_NODE_OBJ, ZFS_SHARES_DIR, 8, 1,
959             &zfsvfs->z_shares_dir);
960         if (error && error != ENOENT)
961                 goto out;
962
963         mutex_init(&zfsvfs->z_znodes_lock, NULL, MUTEX_DEFAULT, NULL);
964         mutex_init(&zfsvfs->z_lock, NULL, MUTEX_DEFAULT, NULL);
965         list_create(&zfsvfs->z_all_znodes, sizeof (znode_t),
966             offsetof(znode_t, z_link_node));
967         rrw_init(&zfsvfs->z_teardown_lock);
968         rw_init(&zfsvfs->z_teardown_inactive_lock, NULL, RW_DEFAULT, NULL);
969         rw_init(&zfsvfs->z_fuid_lock, NULL, RW_DEFAULT, NULL);
970         for (i = 0; i != ZFS_OBJ_MTX_SZ; i++)
971                 mutex_init(&zfsvfs->z_hold_mtx[i], NULL, MUTEX_DEFAULT, NULL);
972
973         *zfvp = zfsvfs;
974         return (0);
975
976 out:
977         dmu_objset_disown(os, zfsvfs);
978         *zfvp = NULL;
979         kmem_free(zfsvfs, sizeof (zfsvfs_t));
980         return (error);
981 }
982
983 static int
984 zfsvfs_setup(zfsvfs_t *zfsvfs, boolean_t mounting)
985 {
986         int error;
987
988         error = zfs_register_callbacks(zfsvfs->z_vfs);
989         if (error)
990                 return (error);
991
992         /*
993          * Set the objset user_ptr to track its zfsvfs.
994          */
995         mutex_enter(&zfsvfs->z_os->os_user_ptr_lock);
996         dmu_objset_set_user(zfsvfs->z_os, zfsvfs);
997         mutex_exit(&zfsvfs->z_os->os_user_ptr_lock);
998
999         zfsvfs->z_log = zil_open(zfsvfs->z_os, zfs_get_data);
1000
1001         /*
1002          * If we are not mounting (ie: online recv), then we don't
1003          * have to worry about replaying the log as we blocked all
1004          * operations out since we closed the ZIL.
1005          */
1006         if (mounting) {
1007                 boolean_t readonly;
1008
1009                 /*
1010                  * During replay we remove the read only flag to
1011                  * allow replays to succeed.
1012                  */
1013                 readonly = zfsvfs->z_vfs->vfs_flag & VFS_RDONLY;
1014                 if (readonly != 0)
1015                         zfsvfs->z_vfs->vfs_flag &= ~VFS_RDONLY;
1016                 else
1017                         zfs_unlinked_drain(zfsvfs);
1018
1019                 /*
1020                  * Parse and replay the intent log.
1021                  *
1022                  * Because of ziltest, this must be done after
1023                  * zfs_unlinked_drain().  (Further note: ziltest
1024                  * doesn't use readonly mounts, where
1025                  * zfs_unlinked_drain() isn't called.)  This is because
1026                  * ziltest causes spa_sync() to think it's committed,
1027                  * but actually it is not, so the intent log contains
1028                  * many txg's worth of changes.
1029                  *
1030                  * In particular, if object N is in the unlinked set in
1031                  * the last txg to actually sync, then it could be
1032                  * actually freed in a later txg and then reallocated
1033                  * in a yet later txg.  This would write a "create
1034                  * object N" record to the intent log.  Normally, this
1035                  * would be fine because the spa_sync() would have
1036                  * written out the fact that object N is free, before
1037                  * we could write the "create object N" intent log
1038                  * record.
1039                  *
1040                  * But when we are in ziltest mode, we advance the "open
1041                  * txg" without actually spa_sync()-ing the changes to
1042                  * disk.  So we would see that object N is still
1043                  * allocated and in the unlinked set, and there is an
1044                  * intent log record saying to allocate it.
1045                  */
1046                 if (zil_replay_disable) {
1047                         zil_destroy(zfsvfs->z_log, B_FALSE);
1048                 } else {
1049                         zfsvfs->z_replay = B_TRUE;
1050                         zil_replay(zfsvfs->z_os, zfsvfs, zfs_replay_vector);
1051                         zfsvfs->z_replay = B_FALSE;
1052                 }
1053                 zfsvfs->z_vfs->vfs_flag |= readonly; /* restore readonly bit */
1054         }
1055
1056         return (0);
1057 }
1058
1059 void
1060 zfsvfs_free(zfsvfs_t *zfsvfs)
1061 {
1062         int i;
1063         extern krwlock_t zfsvfs_lock; /* in zfs_znode.c */
1064
1065         /*
1066          * This is a barrier to prevent the filesystem from going away in
1067          * zfs_znode_move() until we can safely ensure that the filesystem is
1068          * not unmounted. We consider the filesystem valid before the barrier
1069          * and invalid after the barrier.
1070          */
1071         rw_enter(&zfsvfs_lock, RW_READER);
1072         rw_exit(&zfsvfs_lock);
1073
1074         zfs_fuid_destroy(zfsvfs);
1075
1076         mutex_destroy(&zfsvfs->z_znodes_lock);
1077         mutex_destroy(&zfsvfs->z_lock);
1078         list_destroy(&zfsvfs->z_all_znodes);
1079         rrw_destroy(&zfsvfs->z_teardown_lock);
1080         rw_destroy(&zfsvfs->z_teardown_inactive_lock);
1081         rw_destroy(&zfsvfs->z_fuid_lock);
1082         for (i = 0; i != ZFS_OBJ_MTX_SZ; i++)
1083                 mutex_destroy(&zfsvfs->z_hold_mtx[i]);
1084         kmem_free(zfsvfs, sizeof (zfsvfs_t));
1085 }
1086
1087 static void
1088 zfs_set_fuid_feature(zfsvfs_t *zfsvfs)
1089 {
1090         zfsvfs->z_use_fuids = USE_FUIDS(zfsvfs->z_version, zfsvfs->z_os);
1091         if (zfsvfs->z_use_fuids && zfsvfs->z_vfs) {
1092                 vfs_set_feature(zfsvfs->z_vfs, VFSFT_XVATTR);
1093                 vfs_set_feature(zfsvfs->z_vfs, VFSFT_SYSATTR_VIEWS);
1094                 vfs_set_feature(zfsvfs->z_vfs, VFSFT_ACEMASKONACCESS);
1095                 vfs_set_feature(zfsvfs->z_vfs, VFSFT_ACLONCREATE);
1096                 vfs_set_feature(zfsvfs->z_vfs, VFSFT_ACCESS_FILTER);
1097                 vfs_set_feature(zfsvfs->z_vfs, VFSFT_REPARSE);
1098         }
1099         zfsvfs->z_use_sa = USE_SA(zfsvfs->z_version, zfsvfs->z_os);
1100 }
1101
1102 static int
1103 zfs_domount(vfs_t *vfsp, char *osname)
1104 {
1105         dev_t mount_dev;
1106         uint64_t recordsize, fsid_guid;
1107         int error = 0;
1108         zfsvfs_t *zfsvfs;
1109
1110         ASSERT(vfsp);
1111         ASSERT(osname);
1112
1113         error = zfsvfs_create(osname, &zfsvfs);
1114         if (error)
1115                 return (error);
1116         zfsvfs->z_vfs = vfsp;
1117
1118         /* Initialize the generic filesystem structure. */
1119         vfsp->vfs_bcount = 0;
1120         vfsp->vfs_data = NULL;
1121
1122         if (zfs_create_unique_device(&mount_dev) == -1) {
1123                 error = ENODEV;
1124                 goto out;
1125         }
1126         ASSERT(vfs_devismounted(mount_dev) == 0);
1127
1128         if (error = dsl_prop_get_integer(osname, "recordsize", &recordsize,
1129             NULL))
1130                 goto out;
1131
1132         vfsp->vfs_dev = mount_dev;
1133         vfsp->vfs_fstype = zfsfstype;
1134         vfsp->vfs_bsize = recordsize;
1135         vfsp->vfs_flag |= VFS_NOTRUNC;
1136         vfsp->vfs_data = zfsvfs;
1137
1138         /*
1139          * The fsid is 64 bits, composed of an 8-bit fs type, which
1140          * separates our fsid from any other filesystem types, and a
1141          * 56-bit objset unique ID.  The objset unique ID is unique to
1142          * all objsets open on this system, provided by unique_create().
1143          * The 8-bit fs type must be put in the low bits of fsid[1]
1144          * because that's where other Solaris filesystems put it.
1145          */
1146         fsid_guid = dmu_objset_fsid_guid(zfsvfs->z_os);
1147         ASSERT((fsid_guid & ~((1ULL<<56)-1)) == 0);
1148         vfsp->vfs_fsid.val[0] = fsid_guid;
1149         vfsp->vfs_fsid.val[1] = ((fsid_guid>>32) << 8) |
1150             zfsfstype & 0xFF;
1151
1152         /*
1153          * Set features for file system.
1154          */
1155         zfs_set_fuid_feature(zfsvfs);
1156         if (zfsvfs->z_case == ZFS_CASE_INSENSITIVE) {
1157                 vfs_set_feature(vfsp, VFSFT_DIRENTFLAGS);
1158                 vfs_set_feature(vfsp, VFSFT_CASEINSENSITIVE);
1159                 vfs_set_feature(vfsp, VFSFT_NOCASESENSITIVE);
1160         } else if (zfsvfs->z_case == ZFS_CASE_MIXED) {
1161                 vfs_set_feature(vfsp, VFSFT_DIRENTFLAGS);
1162                 vfs_set_feature(vfsp, VFSFT_CASEINSENSITIVE);
1163         }
1164         vfs_set_feature(vfsp, VFSFT_ZEROCOPY_SUPPORTED);
1165
1166         if (dmu_objset_is_snapshot(zfsvfs->z_os)) {
1167                 uint64_t pval;
1168
1169                 atime_changed_cb(zfsvfs, B_FALSE);
1170                 readonly_changed_cb(zfsvfs, B_TRUE);
1171                 if (error = dsl_prop_get_integer(osname, "xattr", &pval, NULL))
1172                         goto out;
1173                 xattr_changed_cb(zfsvfs, pval);
1174                 zfsvfs->z_issnap = B_TRUE;
1175
1176                 mutex_enter(&zfsvfs->z_os->os_user_ptr_lock);
1177                 dmu_objset_set_user(zfsvfs->z_os, zfsvfs);
1178                 mutex_exit(&zfsvfs->z_os->os_user_ptr_lock);
1179         } else {
1180                 error = zfsvfs_setup(zfsvfs, B_TRUE);
1181         }
1182
1183         if (!zfsvfs->z_issnap)
1184                 zfsctl_create(zfsvfs);
1185 out:
1186         if (error) {
1187                 dmu_objset_disown(zfsvfs->z_os, zfsvfs);
1188                 zfsvfs_free(zfsvfs);
1189         } else {
1190                 atomic_add_32(&zfs_active_fs_count, 1);
1191         }
1192
1193         return (error);
1194 }
1195
1196 void
1197 zfs_unregister_callbacks(zfsvfs_t *zfsvfs)
1198 {
1199         objset_t *os = zfsvfs->z_os;
1200         struct dsl_dataset *ds;
1201
1202         /*
1203          * Unregister properties.
1204          */
1205         if (!dmu_objset_is_snapshot(os)) {
1206                 ds = dmu_objset_ds(os);
1207                 VERIFY(dsl_prop_unregister(ds, "atime", atime_changed_cb,
1208                     zfsvfs) == 0);
1209
1210                 VERIFY(dsl_prop_unregister(ds, "xattr", xattr_changed_cb,
1211                     zfsvfs) == 0);
1212
1213                 VERIFY(dsl_prop_unregister(ds, "recordsize", blksz_changed_cb,
1214                     zfsvfs) == 0);
1215
1216                 VERIFY(dsl_prop_unregister(ds, "readonly", readonly_changed_cb,
1217                     zfsvfs) == 0);
1218
1219                 VERIFY(dsl_prop_unregister(ds, "devices", devices_changed_cb,
1220                     zfsvfs) == 0);
1221
1222                 VERIFY(dsl_prop_unregister(ds, "setuid", setuid_changed_cb,
1223                     zfsvfs) == 0);
1224
1225                 VERIFY(dsl_prop_unregister(ds, "exec", exec_changed_cb,
1226                     zfsvfs) == 0);
1227
1228                 VERIFY(dsl_prop_unregister(ds, "snapdir", snapdir_changed_cb,
1229                     zfsvfs) == 0);
1230
1231                 VERIFY(dsl_prop_unregister(ds, "aclinherit",
1232                     acl_inherit_changed_cb, zfsvfs) == 0);
1233
1234                 VERIFY(dsl_prop_unregister(ds, "vscan",
1235                     vscan_changed_cb, zfsvfs) == 0);
1236         }
1237 }
1238
1239 /*
1240  * Convert a decimal digit string to a uint64_t integer.
1241  */
1242 static int
1243 str_to_uint64(char *str, uint64_t *objnum)
1244 {
1245         uint64_t num = 0;
1246
1247         while (*str) {
1248                 if (*str < '0' || *str > '9')
1249                         return (EINVAL);
1250
1251                 num = num*10 + *str++ - '0';
1252         }
1253
1254         *objnum = num;
1255         return (0);
1256 }
1257
1258 /*
1259  * The boot path passed from the boot loader is in the form of
1260  * "rootpool-name/root-filesystem-object-number'. Convert this
1261  * string to a dataset name: "rootpool-name/root-filesystem-name".
1262  */
1263 static int
1264 zfs_parse_bootfs(char *bpath, char *outpath)
1265 {
1266         char *slashp;
1267         uint64_t objnum;
1268         int error;
1269
1270         if (*bpath == 0 || *bpath == '/')
1271                 return (EINVAL);
1272
1273         (void) strcpy(outpath, bpath);
1274
1275         slashp = strchr(bpath, '/');
1276
1277         /* if no '/', just return the pool name */
1278         if (slashp == NULL) {
1279                 return (0);
1280         }
1281
1282         /* if not a number, just return the root dataset name */
1283         if (str_to_uint64(slashp+1, &objnum)) {
1284                 return (0);
1285         }
1286
1287         *slashp = '\0';
1288         error = dsl_dsobj_to_dsname(bpath, objnum, outpath);
1289         *slashp = '/';
1290
1291         return (error);
1292 }
1293
1294 /*
1295  * zfs_check_global_label:
1296  *      Check that the hex label string is appropriate for the dataset
1297  *      being mounted into the global_zone proper.
1298  *
1299  *      Return an error if the hex label string is not default or
1300  *      admin_low/admin_high.  For admin_low labels, the corresponding
1301  *      dataset must be readonly.
1302  */
1303 int
1304 zfs_check_global_label(const char *dsname, const char *hexsl)
1305 {
1306         if (strcasecmp(hexsl, ZFS_MLSLABEL_DEFAULT) == 0)
1307                 return (0);
1308         if (strcasecmp(hexsl, ADMIN_HIGH) == 0)
1309                 return (0);
1310         if (strcasecmp(hexsl, ADMIN_LOW) == 0) {
1311                 /* must be readonly */
1312                 uint64_t rdonly;
1313
1314                 if (dsl_prop_get_integer(dsname,
1315                     zfs_prop_to_name(ZFS_PROP_READONLY), &rdonly, NULL))
1316                         return (EACCES);
1317                 return (rdonly ? 0 : EACCES);
1318         }
1319         return (EACCES);
1320 }
1321
1322 /*
1323  * zfs_mount_label_policy:
1324  *      Determine whether the mount is allowed according to MAC check.
1325  *      by comparing (where appropriate) label of the dataset against
1326  *      the label of the zone being mounted into.  If the dataset has
1327  *      no label, create one.
1328  *
1329  *      Returns:
1330  *               0 :    access allowed
1331  *              >0 :    error code, such as EACCES
1332  */
1333 static int
1334 zfs_mount_label_policy(vfs_t *vfsp, char *osname)
1335 {
1336         int             error, retv;
1337         zone_t          *mntzone = NULL;
1338         ts_label_t      *mnt_tsl;
1339         bslabel_t       *mnt_sl;
1340         bslabel_t       ds_sl;
1341         char            ds_hexsl[MAXNAMELEN];
1342
1343         retv = EACCES;                          /* assume the worst */
1344
1345         /*
1346          * Start by getting the dataset label if it exists.
1347          */
1348         error = dsl_prop_get(osname, zfs_prop_to_name(ZFS_PROP_MLSLABEL),
1349             1, sizeof (ds_hexsl), &ds_hexsl, NULL);
1350         if (error)
1351                 return (EACCES);
1352
1353         /*
1354          * If labeling is NOT enabled, then disallow the mount of datasets
1355          * which have a non-default label already.  No other label checks
1356          * are needed.
1357          */
1358         if (!is_system_labeled()) {
1359                 if (strcasecmp(ds_hexsl, ZFS_MLSLABEL_DEFAULT) == 0)
1360                         return (0);
1361                 return (EACCES);
1362         }
1363
1364         /*
1365          * Get the label of the mountpoint.  If mounting into the global
1366          * zone (i.e. mountpoint is not within an active zone and the
1367          * zoned property is off), the label must be default or
1368          * admin_low/admin_high only; no other checks are needed.
1369          */
1370         mntzone = zone_find_by_any_path(refstr_value(vfsp->vfs_mntpt), B_FALSE);
1371         if (mntzone->zone_id == GLOBAL_ZONEID) {
1372                 uint64_t zoned;
1373
1374                 zone_rele(mntzone);
1375
1376                 if (dsl_prop_get_integer(osname,
1377                     zfs_prop_to_name(ZFS_PROP_ZONED), &zoned, NULL))
1378                         return (EACCES);
1379                 if (!zoned)
1380                         return (zfs_check_global_label(osname, ds_hexsl));
1381                 else
1382                         /*
1383                          * This is the case of a zone dataset being mounted
1384                          * initially, before the zone has been fully created;
1385                          * allow this mount into global zone.
1386                          */
1387                         return (0);
1388         }
1389
1390         mnt_tsl = mntzone->zone_slabel;
1391         ASSERT(mnt_tsl != NULL);
1392         label_hold(mnt_tsl);
1393         mnt_sl = label2bslabel(mnt_tsl);
1394
1395         if (strcasecmp(ds_hexsl, ZFS_MLSLABEL_DEFAULT) == 0) {
1396                 /*
1397                  * The dataset doesn't have a real label, so fabricate one.
1398                  */
1399                 char *str = NULL;
1400
1401                 if (l_to_str_internal(mnt_sl, &str) == 0 &&
1402                     dsl_prop_set(osname, zfs_prop_to_name(ZFS_PROP_MLSLABEL),
1403                     ZPROP_SRC_LOCAL, 1, strlen(str) + 1, str) == 0)
1404                         retv = 0;
1405                 if (str != NULL)
1406                         kmem_free(str, strlen(str) + 1);
1407         } else if (hexstr_to_label(ds_hexsl, &ds_sl) == 0) {
1408                 /*
1409                  * Now compare labels to complete the MAC check.  If the
1410                  * labels are equal then allow access.  If the mountpoint
1411                  * label dominates the dataset label, allow readonly access.
1412                  * Otherwise, access is denied.
1413                  */
1414                 if (blequal(mnt_sl, &ds_sl))
1415                         retv = 0;
1416                 else if (bldominates(mnt_sl, &ds_sl)) {
1417                         vfs_setmntopt(vfsp, MNTOPT_RO, NULL, 0);
1418                         retv = 0;
1419                 }
1420         }
1421
1422         label_rele(mnt_tsl);
1423         zone_rele(mntzone);
1424         return (retv);
1425 }
1426
1427 static int
1428 zfs_mountroot(vfs_t *vfsp, enum whymountroot why)
1429 {
1430         int error = 0;
1431         static int zfsrootdone = 0;
1432         zfsvfs_t *zfsvfs = NULL;
1433         znode_t *zp = NULL;
1434         vnode_t *vp = NULL;
1435         char *zfs_bootfs;
1436         char *zfs_devid;
1437
1438         ASSERT(vfsp);
1439
1440         /*
1441          * The filesystem that we mount as root is defined in the
1442          * boot property "zfs-bootfs" with a format of
1443          * "poolname/root-dataset-objnum".
1444          */
1445         if (why == ROOT_INIT) {
1446                 if (zfsrootdone++)
1447                         return (EBUSY);
1448                 /*
1449                  * the process of doing a spa_load will require the
1450                  * clock to be set before we could (for example) do
1451                  * something better by looking at the timestamp on
1452                  * an uberblock, so just set it to -1.
1453                  */
1454                 clkset(-1);
1455
1456                 if ((zfs_bootfs = spa_get_bootprop("zfs-bootfs")) == NULL) {
1457                         cmn_err(CE_NOTE, "spa_get_bootfs: can not get "
1458                             "bootfs name");
1459                         return (EINVAL);
1460                 }
1461                 zfs_devid = spa_get_bootprop("diskdevid");
1462                 error = spa_import_rootpool(rootfs.bo_name, zfs_devid);
1463                 if (zfs_devid)
1464                         spa_free_bootprop(zfs_devid);
1465                 if (error) {
1466                         spa_free_bootprop(zfs_bootfs);
1467                         cmn_err(CE_NOTE, "spa_import_rootpool: error %d",
1468                             error);
1469                         return (error);
1470                 }
1471                 if (error = zfs_parse_bootfs(zfs_bootfs, rootfs.bo_name)) {
1472                         spa_free_bootprop(zfs_bootfs);
1473                         cmn_err(CE_NOTE, "zfs_parse_bootfs: error %d",
1474                             error);
1475                         return (error);
1476                 }
1477
1478                 spa_free_bootprop(zfs_bootfs);
1479
1480                 if (error = vfs_lock(vfsp))
1481                         return (error);
1482
1483                 if (error = zfs_domount(vfsp, rootfs.bo_name)) {
1484                         cmn_err(CE_NOTE, "zfs_domount: error %d", error);
1485                         goto out;
1486                 }
1487
1488                 zfsvfs = (zfsvfs_t *)vfsp->vfs_data;
1489                 ASSERT(zfsvfs);
1490                 if (error = zfs_zget(zfsvfs, zfsvfs->z_root, &zp)) {
1491                         cmn_err(CE_NOTE, "zfs_zget: error %d", error);
1492                         goto out;
1493                 }
1494
1495                 vp = ZTOV(zp);
1496                 mutex_enter(&vp->v_lock);
1497                 vp->v_flag |= VROOT;
1498                 mutex_exit(&vp->v_lock);
1499                 rootvp = vp;
1500
1501                 /*
1502                  * Leave rootvp held.  The root file system is never unmounted.
1503                  */
1504
1505                 vfs_add((struct vnode *)0, vfsp,
1506                     (vfsp->vfs_flag & VFS_RDONLY) ? MS_RDONLY : 0);
1507 out:
1508                 vfs_unlock(vfsp);
1509                 return (error);
1510         } else if (why == ROOT_REMOUNT) {
1511                 readonly_changed_cb(vfsp->vfs_data, B_FALSE);
1512                 vfsp->vfs_flag |= VFS_REMOUNT;
1513
1514                 /* refresh mount options */
1515                 zfs_unregister_callbacks(vfsp->vfs_data);
1516                 return (zfs_register_callbacks(vfsp));
1517
1518         } else if (why == ROOT_UNMOUNT) {
1519                 zfs_unregister_callbacks((zfsvfs_t *)vfsp->vfs_data);
1520                 (void) zfs_sync(vfsp, 0, 0);
1521                 return (0);
1522         }
1523
1524         /*
1525          * if "why" is equal to anything else other than ROOT_INIT,
1526          * ROOT_REMOUNT, or ROOT_UNMOUNT, we do not support it.
1527          */
1528         return (ENOTSUP);
1529 }
1530
1531 /*ARGSUSED*/
1532 static int
1533 zfs_mount(vfs_t *vfsp, vnode_t *mvp, struct mounta *uap, cred_t *cr)
1534 {
1535         char            *osname;
1536         pathname_t      spn;
1537         int             error = 0;
1538         uio_seg_t       fromspace = (uap->flags & MS_SYSSPACE) ?
1539             UIO_SYSSPACE : UIO_USERSPACE;
1540         int             canwrite;
1541
1542         if (mvp->v_type != VDIR)
1543                 return (ENOTDIR);
1544
1545         mutex_enter(&mvp->v_lock);
1546         if ((uap->flags & MS_REMOUNT) == 0 &&
1547             (uap->flags & MS_OVERLAY) == 0 &&
1548             (mvp->v_count != 1 || (mvp->v_flag & VROOT))) {
1549                 mutex_exit(&mvp->v_lock);
1550                 return (EBUSY);
1551         }
1552         mutex_exit(&mvp->v_lock);
1553
1554         /*
1555          * ZFS does not support passing unparsed data in via MS_DATA.
1556          * Users should use the MS_OPTIONSTR interface; this means
1557          * that all option parsing is already done and the options struct
1558          * can be interrogated.
1559          */
1560         if ((uap->flags & MS_DATA) && uap->datalen > 0)
1561                 return (EINVAL);
1562
1563         /*
1564          * Get the objset name (the "special" mount argument).
1565          */
1566         if (error = pn_get(uap->spec, fromspace, &spn))
1567                 return (error);
1568
1569         osname = spn.pn_path;
1570
1571         /*
1572          * Check for mount privilege?
1573          *
1574          * If we don't have privilege then see if
1575          * we have local permission to allow it
1576          */
1577         error = secpolicy_fs_mount(cr, mvp, vfsp);
1578         if (error) {
1579                 if (dsl_deleg_access(osname, ZFS_DELEG_PERM_MOUNT, cr) == 0) {
1580                         vattr_t         vattr;
1581
1582                         /*
1583                          * Make sure user is the owner of the mount point
1584                          * or has sufficient privileges.
1585                          */
1586
1587                         vattr.va_mask = AT_UID;
1588
1589                         if (VOP_GETATTR(mvp, &vattr, 0, cr, NULL)) {
1590                                 goto out;
1591                         }
1592
1593                         if (secpolicy_vnode_owner(cr, vattr.va_uid) != 0 &&
1594                             VOP_ACCESS(mvp, VWRITE, 0, cr, NULL) != 0) {
1595                                 goto out;
1596                         }
1597                         secpolicy_fs_mount_clearopts(cr, vfsp);
1598                 } else {
1599                         goto out;
1600                 }
1601         }
1602
1603         /*
1604          * Refuse to mount a filesystem if we are in a local zone and the
1605          * dataset is not visible.
1606          */
1607         if (!INGLOBALZONE(curproc) &&
1608             (!zone_dataset_visible(osname, &canwrite) || !canwrite)) {
1609                 error = EPERM;
1610                 goto out;
1611         }
1612
1613         error = zfs_mount_label_policy(vfsp, osname);
1614         if (error)
1615                 goto out;
1616
1617         /*
1618          * When doing a remount, we simply refresh our temporary properties
1619          * according to those options set in the current VFS options.
1620          */
1621         if (uap->flags & MS_REMOUNT) {
1622                 /* refresh mount options */
1623                 zfs_unregister_callbacks(vfsp->vfs_data);
1624                 error = zfs_register_callbacks(vfsp);
1625                 goto out;
1626         }
1627
1628         error = zfs_domount(vfsp, osname);
1629
1630         /*
1631          * Add an extra VFS_HOLD on our parent vfs so that it can't
1632          * disappear due to a forced unmount.
1633          */
1634         if (error == 0 && ((zfsvfs_t *)vfsp->vfs_data)->z_issnap)
1635                 VFS_HOLD(mvp->v_vfsp);
1636
1637 out:
1638         pn_free(&spn);
1639         return (error);
1640 }
1641
1642 static int
1643 zfs_statvfs(vfs_t *vfsp, struct statvfs64 *statp)
1644 {
1645         zfsvfs_t *zfsvfs = vfsp->vfs_data;
1646         dev32_t d32;
1647         uint64_t refdbytes, availbytes, usedobjs, availobjs;
1648
1649         ZFS_ENTER(zfsvfs);
1650
1651         dmu_objset_space(zfsvfs->z_os,
1652             &refdbytes, &availbytes, &usedobjs, &availobjs);
1653
1654         /*
1655          * The underlying storage pool actually uses multiple block sizes.
1656          * We report the fragsize as the smallest block size we support,
1657          * and we report our blocksize as the filesystem's maximum blocksize.
1658          */
1659         statp->f_frsize = 1UL << SPA_MINBLOCKSHIFT;
1660         statp->f_bsize = zfsvfs->z_max_blksz;
1661
1662         /*
1663          * The following report "total" blocks of various kinds in the
1664          * file system, but reported in terms of f_frsize - the
1665          * "fragment" size.
1666          */
1667
1668         statp->f_blocks = (refdbytes + availbytes) >> SPA_MINBLOCKSHIFT;
1669         statp->f_bfree = availbytes >> SPA_MINBLOCKSHIFT;
1670         statp->f_bavail = statp->f_bfree; /* no root reservation */
1671
1672         /*
1673          * statvfs() should really be called statufs(), because it assumes
1674          * static metadata.  ZFS doesn't preallocate files, so the best
1675          * we can do is report the max that could possibly fit in f_files,
1676          * and that minus the number actually used in f_ffree.
1677          * For f_ffree, report the smaller of the number of object available
1678          * and the number of blocks (each object will take at least a block).
1679          */
1680         statp->f_ffree = MIN(availobjs, statp->f_bfree);
1681         statp->f_favail = statp->f_ffree;       /* no "root reservation" */
1682         statp->f_files = statp->f_ffree + usedobjs;
1683
1684         (void) cmpldev(&d32, vfsp->vfs_dev);
1685         statp->f_fsid = d32;
1686
1687         /*
1688          * We're a zfs filesystem.
1689          */
1690         (void) strcpy(statp->f_basetype, vfssw[vfsp->vfs_fstype].vsw_name);
1691
1692         statp->f_flag = vf_to_stf(vfsp->vfs_flag);
1693
1694         statp->f_namemax = ZFS_MAXNAMELEN;
1695
1696         /*
1697          * We have all of 32 characters to stuff a string here.
1698          * Is there anything useful we could/should provide?
1699          */
1700         bzero(statp->f_fstr, sizeof (statp->f_fstr));
1701
1702         ZFS_EXIT(zfsvfs);
1703         return (0);
1704 }
1705
1706 static int
1707 zfs_root(vfs_t *vfsp, vnode_t **vpp)
1708 {
1709         zfsvfs_t *zfsvfs = vfsp->vfs_data;
1710         znode_t *rootzp;
1711         int error;
1712
1713         ZFS_ENTER(zfsvfs);
1714
1715         error = zfs_zget(zfsvfs, zfsvfs->z_root, &rootzp);
1716         if (error == 0)
1717                 *vpp = ZTOV(rootzp);
1718
1719         ZFS_EXIT(zfsvfs);
1720         return (error);
1721 }
1722
1723 /*
1724  * Teardown the zfsvfs::z_os.
1725  *
1726  * Note, if 'unmounting' if FALSE, we return with the 'z_teardown_lock'
1727  * and 'z_teardown_inactive_lock' held.
1728  */
1729 static int
1730 zfsvfs_teardown(zfsvfs_t *zfsvfs, boolean_t unmounting)
1731 {
1732         znode_t *zp;
1733
1734         rrw_enter(&zfsvfs->z_teardown_lock, RW_WRITER, FTAG);
1735
1736         if (!unmounting) {
1737                 /*
1738                  * We purge the parent filesystem's vfsp as the parent
1739                  * filesystem and all of its snapshots have their vnode's
1740                  * v_vfsp set to the parent's filesystem's vfsp.  Note,
1741                  * 'z_parent' is self referential for non-snapshots.
1742                  */
1743                 (void) dnlc_purge_vfsp(zfsvfs->z_parent->z_vfs, 0);
1744         }
1745
1746         /*
1747          * Close the zil. NB: Can't close the zil while zfs_inactive
1748          * threads are blocked as zil_close can call zfs_inactive.
1749          */
1750         if (zfsvfs->z_log) {
1751                 zil_close(zfsvfs->z_log);
1752                 zfsvfs->z_log = NULL;
1753         }
1754
1755         rw_enter(&zfsvfs->z_teardown_inactive_lock, RW_WRITER);
1756
1757         /*
1758          * If we are not unmounting (ie: online recv) and someone already
1759          * unmounted this file system while we were doing the switcheroo,
1760          * or a reopen of z_os failed then just bail out now.
1761          */
1762         if (!unmounting && (zfsvfs->z_unmounted || zfsvfs->z_os == NULL)) {
1763                 rw_exit(&zfsvfs->z_teardown_inactive_lock);
1764                 rrw_exit(&zfsvfs->z_teardown_lock, FTAG);
1765                 return (EIO);
1766         }
1767
1768         /*
1769          * At this point there are no vops active, and any new vops will
1770          * fail with EIO since we have z_teardown_lock for writer (only
1771          * relavent for forced unmount).
1772          *
1773          * Release all holds on dbufs.
1774          */
1775         mutex_enter(&zfsvfs->z_znodes_lock);
1776         for (zp = list_head(&zfsvfs->z_all_znodes); zp != NULL;
1777             zp = list_next(&zfsvfs->z_all_znodes, zp))
1778                 if (zp->z_sa_hdl) {
1779                         ASSERT(ZTOV(zp)->v_count > 0);
1780                         zfs_znode_dmu_fini(zp);
1781                 }
1782         mutex_exit(&zfsvfs->z_znodes_lock);
1783
1784         /*
1785          * If we are unmounting, set the unmounted flag and let new vops
1786          * unblock.  zfs_inactive will have the unmounted behavior, and all
1787          * other vops will fail with EIO.
1788          */
1789         if (unmounting) {
1790                 zfsvfs->z_unmounted = B_TRUE;
1791                 rrw_exit(&zfsvfs->z_teardown_lock, FTAG);
1792                 rw_exit(&zfsvfs->z_teardown_inactive_lock);
1793         }
1794
1795         /*
1796          * z_os will be NULL if there was an error in attempting to reopen
1797          * zfsvfs, so just return as the properties had already been
1798          * unregistered and cached data had been evicted before.
1799          */
1800         if (zfsvfs->z_os == NULL)
1801                 return (0);
1802
1803         /*
1804          * Unregister properties.
1805          */
1806         zfs_unregister_callbacks(zfsvfs);
1807
1808         /*
1809          * Evict cached data
1810          */
1811         if (dmu_objset_evict_dbufs(zfsvfs->z_os)) {
1812                 txg_wait_synced(dmu_objset_pool(zfsvfs->z_os), 0);
1813                 (void) dmu_objset_evict_dbufs(zfsvfs->z_os);
1814         }
1815
1816         return (0);
1817 }
1818
1819 /*ARGSUSED*/
1820 static int
1821 zfs_umount(vfs_t *vfsp, int fflag, cred_t *cr)
1822 {
1823         zfsvfs_t *zfsvfs = vfsp->vfs_data;
1824         objset_t *os;
1825         int ret;
1826
1827         ret = secpolicy_fs_unmount(cr, vfsp);
1828         if (ret) {
1829                 if (dsl_deleg_access((char *)refstr_value(vfsp->vfs_resource),
1830                     ZFS_DELEG_PERM_MOUNT, cr))
1831                         return (ret);
1832         }
1833
1834         /*
1835          * We purge the parent filesystem's vfsp as the parent filesystem
1836          * and all of its snapshots have their vnode's v_vfsp set to the
1837          * parent's filesystem's vfsp.  Note, 'z_parent' is self
1838          * referential for non-snapshots.
1839          */
1840         (void) dnlc_purge_vfsp(zfsvfs->z_parent->z_vfs, 0);
1841
1842         /*
1843          * Unmount any snapshots mounted under .zfs before unmounting the
1844          * dataset itself.
1845          */
1846         if (zfsvfs->z_ctldir != NULL &&
1847             (ret = zfsctl_umount_snapshots(vfsp, fflag, cr)) != 0) {
1848                 return (ret);
1849         }
1850
1851         if (!(fflag & MS_FORCE)) {
1852                 /*
1853                  * Check the number of active vnodes in the file system.
1854                  * Our count is maintained in the vfs structure, but the
1855                  * number is off by 1 to indicate a hold on the vfs
1856                  * structure itself.
1857                  *
1858                  * The '.zfs' directory maintains a reference of its
1859                  * own, and any active references underneath are
1860                  * reflected in the vnode count.
1861                  */
1862                 if (zfsvfs->z_ctldir == NULL) {
1863                         if (vfsp->vfs_count > 1)
1864                                 return (EBUSY);
1865                 } else {
1866                         if (vfsp->vfs_count > 2 ||
1867                             zfsvfs->z_ctldir->v_count > 1)
1868                                 return (EBUSY);
1869                 }
1870         }
1871
1872         vfsp->vfs_flag |= VFS_UNMOUNTED;
1873
1874         VERIFY(zfsvfs_teardown(zfsvfs, B_TRUE) == 0);
1875         os = zfsvfs->z_os;
1876
1877         /*
1878          * z_os will be NULL if there was an error in
1879          * attempting to reopen zfsvfs.
1880          */
1881         if (os != NULL) {
1882                 /*
1883                  * Unset the objset user_ptr.
1884                  */
1885                 mutex_enter(&os->os_user_ptr_lock);
1886                 dmu_objset_set_user(os, NULL);
1887                 mutex_exit(&os->os_user_ptr_lock);
1888
1889                 /*
1890                  * Finally release the objset
1891                  */
1892                 dmu_objset_disown(os, zfsvfs);
1893         }
1894
1895         /*
1896          * We can now safely destroy the '.zfs' directory node.
1897          */
1898         if (zfsvfs->z_ctldir != NULL)
1899                 zfsctl_destroy(zfsvfs);
1900
1901         return (0);
1902 }
1903
1904 static int
1905 zfs_vget(vfs_t *vfsp, vnode_t **vpp, fid_t *fidp)
1906 {
1907         zfsvfs_t        *zfsvfs = vfsp->vfs_data;
1908         znode_t         *zp;
1909         uint64_t        object = 0;
1910         uint64_t        fid_gen = 0;
1911         uint64_t        gen_mask;
1912         uint64_t        zp_gen;
1913         int             i, err;
1914
1915         *vpp = NULL;
1916
1917         ZFS_ENTER(zfsvfs);
1918
1919         if (fidp->fid_len == LONG_FID_LEN) {
1920                 zfid_long_t     *zlfid = (zfid_long_t *)fidp;
1921                 uint64_t        objsetid = 0;
1922                 uint64_t        setgen = 0;
1923
1924                 for (i = 0; i < sizeof (zlfid->zf_setid); i++)
1925                         objsetid |= ((uint64_t)zlfid->zf_setid[i]) << (8 * i);
1926
1927                 for (i = 0; i < sizeof (zlfid->zf_setgen); i++)
1928                         setgen |= ((uint64_t)zlfid->zf_setgen[i]) << (8 * i);
1929
1930                 ZFS_EXIT(zfsvfs);
1931
1932                 err = zfsctl_lookup_objset(vfsp, objsetid, &zfsvfs);
1933                 if (err)
1934                         return (EINVAL);
1935                 ZFS_ENTER(zfsvfs);
1936         }
1937
1938         if (fidp->fid_len == SHORT_FID_LEN || fidp->fid_len == LONG_FID_LEN) {
1939                 zfid_short_t    *zfid = (zfid_short_t *)fidp;
1940
1941                 for (i = 0; i < sizeof (zfid->zf_object); i++)
1942                         object |= ((uint64_t)zfid->zf_object[i]) << (8 * i);
1943
1944                 for (i = 0; i < sizeof (zfid->zf_gen); i++)
1945                         fid_gen |= ((uint64_t)zfid->zf_gen[i]) << (8 * i);
1946         } else {
1947                 ZFS_EXIT(zfsvfs);
1948                 return (EINVAL);
1949         }
1950
1951         /* A zero fid_gen means we are in the .zfs control directories */
1952         if (fid_gen == 0 &&
1953             (object == ZFSCTL_INO_ROOT || object == ZFSCTL_INO_SNAPDIR)) {
1954                 *vpp = zfsvfs->z_ctldir;
1955                 ASSERT(*vpp != NULL);
1956                 if (object == ZFSCTL_INO_SNAPDIR) {
1957                         VERIFY(zfsctl_root_lookup(*vpp, "snapshot", vpp, NULL,
1958                             0, NULL, NULL, NULL, NULL, NULL) == 0);
1959                 } else {
1960                         VN_HOLD(*vpp);
1961                 }
1962                 ZFS_EXIT(zfsvfs);
1963                 return (0);
1964         }
1965
1966         gen_mask = -1ULL >> (64 - 8 * i);
1967
1968         dprintf("getting %llu [%u mask %llx]\n", object, fid_gen, gen_mask);
1969         if (err = zfs_zget(zfsvfs, object, &zp)) {
1970                 ZFS_EXIT(zfsvfs);
1971                 return (err);
1972         }
1973         (void) sa_lookup(zp->z_sa_hdl, SA_ZPL_GEN(zfsvfs), &zp_gen,
1974             sizeof (uint64_t));
1975         zp_gen = zp_gen & gen_mask;
1976         if (zp_gen == 0)
1977                 zp_gen = 1;
1978         if (zp->z_unlinked || zp_gen != fid_gen) {
1979                 dprintf("znode gen (%u) != fid gen (%u)\n", zp_gen, fid_gen);
1980                 VN_RELE(ZTOV(zp));
1981                 ZFS_EXIT(zfsvfs);
1982                 return (EINVAL);
1983         }
1984
1985         *vpp = ZTOV(zp);
1986         ZFS_EXIT(zfsvfs);
1987         return (0);
1988 }
1989
1990 /*
1991  * Block out VOPs and close zfsvfs_t::z_os
1992  *
1993  * Note, if successful, then we return with the 'z_teardown_lock' and
1994  * 'z_teardown_inactive_lock' write held.
1995  */
1996 int
1997 zfs_suspend_fs(zfsvfs_t *zfsvfs)
1998 {
1999         int error;
2000
2001         if ((error = zfsvfs_teardown(zfsvfs, B_FALSE)) != 0)
2002                 return (error);
2003         dmu_objset_disown(zfsvfs->z_os, zfsvfs);
2004
2005         return (0);
2006 }
2007
2008 /*
2009  * Reopen zfsvfs_t::z_os and release VOPs.
2010  */
2011 int
2012 zfs_resume_fs(zfsvfs_t *zfsvfs, const char *osname)
2013 {
2014         int err, err2;
2015
2016         ASSERT(RRW_WRITE_HELD(&zfsvfs->z_teardown_lock));
2017         ASSERT(RW_WRITE_HELD(&zfsvfs->z_teardown_inactive_lock));
2018
2019         err = dmu_objset_own(osname, DMU_OST_ZFS, B_FALSE, zfsvfs,
2020             &zfsvfs->z_os);
2021         if (err) {
2022                 zfsvfs->z_os = NULL;
2023         } else {
2024                 znode_t *zp;
2025                 uint64_t sa_obj = 0;
2026
2027                 err2 = zap_lookup(zfsvfs->z_os, MASTER_NODE_OBJ,
2028                     ZFS_SA_ATTRS, 8, 1, &sa_obj);
2029
2030                 if ((err || err2) && zfsvfs->z_version >= ZPL_VERSION_SA)
2031                         goto bail;
2032
2033
2034                 zfsvfs->z_attr_table = sa_setup(zfsvfs->z_os, sa_obj,
2035                     zfs_attr_table,  ZPL_END);
2036
2037                 VERIFY(zfsvfs_setup(zfsvfs, B_FALSE) == 0);
2038
2039                 /*
2040                  * Attempt to re-establish all the active znodes with
2041                  * their dbufs.  If a zfs_rezget() fails, then we'll let
2042                  * any potential callers discover that via ZFS_ENTER_VERIFY_VP
2043                  * when they try to use their znode.
2044                  */
2045                 mutex_enter(&zfsvfs->z_znodes_lock);
2046                 for (zp = list_head(&zfsvfs->z_all_znodes); zp;
2047                     zp = list_next(&zfsvfs->z_all_znodes, zp)) {
2048                         (void) zfs_rezget(zp);
2049                 }
2050                 mutex_exit(&zfsvfs->z_znodes_lock);
2051
2052         }
2053
2054 bail:
2055         /* release the VOPs */
2056         rw_exit(&zfsvfs->z_teardown_inactive_lock);
2057         rrw_exit(&zfsvfs->z_teardown_lock, FTAG);
2058
2059         if (err) {
2060                 /*
2061                  * Since we couldn't reopen zfsvfs::z_os, force
2062                  * unmount this file system.
2063                  */
2064                 if (vn_vfswlock(zfsvfs->z_vfs->vfs_vnodecovered) == 0)
2065                         (void) dounmount(zfsvfs->z_vfs, MS_FORCE, CRED());
2066         }
2067         return (err);
2068 }
2069
2070 static void
2071 zfs_freevfs(vfs_t *vfsp)
2072 {
2073         zfsvfs_t *zfsvfs = vfsp->vfs_data;
2074
2075         /*
2076          * If this is a snapshot, we have an extra VFS_HOLD on our parent
2077          * from zfs_mount().  Release it here.  If we came through
2078          * zfs_mountroot() instead, we didn't grab an extra hold, so
2079          * skip the VFS_RELE for rootvfs.
2080          */
2081         if (zfsvfs->z_issnap && (vfsp != rootvfs))
2082                 VFS_RELE(zfsvfs->z_parent->z_vfs);
2083
2084         zfsvfs_free(zfsvfs);
2085
2086         atomic_add_32(&zfs_active_fs_count, -1);
2087 }
2088
2089 /*
2090  * VFS_INIT() initialization.  Note that there is no VFS_FINI(),
2091  * so we can't safely do any non-idempotent initialization here.
2092  * Leave that to zfs_init() and zfs_fini(), which are called
2093  * from the module's _init() and _fini() entry points.
2094  */
2095 /*ARGSUSED*/
2096 static int
2097 zfs_vfsinit(int fstype, char *name)
2098 {
2099         int error;
2100
2101         zfsfstype = fstype;
2102
2103         /*
2104          * Setup vfsops and vnodeops tables.
2105          */
2106         error = vfs_setfsops(fstype, zfs_vfsops_template, &zfs_vfsops);
2107         if (error != 0) {
2108                 cmn_err(CE_WARN, "zfs: bad vfs ops template");
2109         }
2110
2111         error = zfs_create_op_tables();
2112         if (error) {
2113                 zfs_remove_op_tables();
2114                 cmn_err(CE_WARN, "zfs: bad vnode ops template");
2115                 (void) vfs_freevfsops_by_type(zfsfstype);
2116                 return (error);
2117         }
2118
2119         mutex_init(&zfs_dev_mtx, NULL, MUTEX_DEFAULT, NULL);
2120
2121         /*
2122          * Unique major number for all zfs mounts.
2123          * If we run out of 32-bit minors, we'll getudev() another major.
2124          */
2125         zfs_major = ddi_name_to_major(ZFS_DRIVER);
2126         zfs_minor = ZFS_MIN_MINOR;
2127
2128         return (0);
2129 }
2130
2131 void
2132 zfs_init(void)
2133 {
2134         /*
2135          * Initialize .zfs directory structures
2136          */
2137         zfsctl_init();
2138
2139         /*
2140          * Initialize znode cache, vnode ops, etc...
2141          */
2142         zfs_znode_init();
2143
2144         dmu_objset_register_type(DMU_OST_ZFS, zfs_space_delta_cb);
2145 }
2146
2147 void
2148 zfs_fini(void)
2149 {
2150         zfsctl_fini();
2151         zfs_znode_fini();
2152 }
2153
2154 int
2155 zfs_busy(void)
2156 {
2157         return (zfs_active_fs_count != 0);
2158 }
2159
2160 int
2161 zfs_set_version(zfsvfs_t *zfsvfs, uint64_t newvers)
2162 {
2163         int error;
2164         objset_t *os = zfsvfs->z_os;
2165         dmu_tx_t *tx;
2166
2167         if (newvers < ZPL_VERSION_INITIAL || newvers > ZPL_VERSION)
2168                 return (EINVAL);
2169
2170         if (newvers < zfsvfs->z_version)
2171                 return (EINVAL);
2172
2173         if (zfs_spa_version_map(newvers) >
2174             spa_version(dmu_objset_spa(zfsvfs->z_os)))
2175                 return (ENOTSUP);
2176
2177         tx = dmu_tx_create(os);
2178         dmu_tx_hold_zap(tx, MASTER_NODE_OBJ, B_FALSE, ZPL_VERSION_STR);
2179         if (newvers >= ZPL_VERSION_SA && !zfsvfs->z_use_sa) {
2180                 dmu_tx_hold_zap(tx, MASTER_NODE_OBJ, B_TRUE,
2181                     ZFS_SA_ATTRS);
2182                 dmu_tx_hold_zap(tx, DMU_NEW_OBJECT, FALSE, NULL);
2183         }
2184         error = dmu_tx_assign(tx, TXG_WAIT);
2185         if (error) {
2186                 dmu_tx_abort(tx);
2187                 return (error);
2188         }
2189
2190         error = zap_update(os, MASTER_NODE_OBJ, ZPL_VERSION_STR,
2191             8, 1, &newvers, tx);
2192
2193         if (error) {
2194                 dmu_tx_commit(tx);
2195                 return (error);
2196         }
2197
2198         if (newvers >= ZPL_VERSION_SA && !zfsvfs->z_use_sa) {
2199                 uint64_t sa_obj;
2200
2201                 ASSERT3U(spa_version(dmu_objset_spa(zfsvfs->z_os)), >=,
2202                     SPA_VERSION_SA);
2203                 sa_obj = zap_create(os, DMU_OT_SA_MASTER_NODE,
2204                     DMU_OT_NONE, 0, tx);
2205
2206                 error = zap_add(os, MASTER_NODE_OBJ,
2207                     ZFS_SA_ATTRS, 8, 1, &sa_obj, tx);
2208                 ASSERT3U(error, ==, 0);
2209
2210                 VERIFY(0 == sa_set_sa_object(os, sa_obj));
2211                 sa_register_update_callback(os, zfs_sa_upgrade);
2212         }
2213
2214         spa_history_log_internal(LOG_DS_UPGRADE,
2215             dmu_objset_spa(os), tx, "oldver=%llu newver=%llu dataset = %llu",
2216             zfsvfs->z_version, newvers, dmu_objset_id(os));
2217
2218         dmu_tx_commit(tx);
2219
2220         zfsvfs->z_version = newvers;
2221
2222         if (zfsvfs->z_version >= ZPL_VERSION_FUID)
2223                 zfs_set_fuid_feature(zfsvfs);
2224
2225         return (0);
2226 }
2227
2228 /*
2229  * Read a property stored within the master node.
2230  */
2231 int
2232 zfs_get_zplprop(objset_t *os, zfs_prop_t prop, uint64_t *value)
2233 {
2234         const char *pname;
2235         int error = ENOENT;
2236
2237         /*
2238          * Look up the file system's value for the property.  For the
2239          * version property, we look up a slightly different string.
2240          */
2241         if (prop == ZFS_PROP_VERSION)
2242                 pname = ZPL_VERSION_STR;
2243         else
2244                 pname = zfs_prop_to_name(prop);
2245
2246         if (os != NULL)
2247                 error = zap_lookup(os, MASTER_NODE_OBJ, pname, 8, 1, value);
2248
2249         if (error == ENOENT) {
2250                 /* No value set, use the default value */
2251                 switch (prop) {
2252                 case ZFS_PROP_VERSION:
2253                         *value = ZPL_VERSION;
2254                         break;
2255                 case ZFS_PROP_NORMALIZE:
2256                 case ZFS_PROP_UTF8ONLY:
2257                         *value = 0;
2258                         break;
2259                 case ZFS_PROP_CASE:
2260                         *value = ZFS_CASE_SENSITIVE;
2261                         break;
2262                 default:
2263                         return (error);
2264                 }
2265                 error = 0;
2266         }
2267         return (error);
2268 }
2269
2270 static vfsdef_t vfw = {
2271         VFSDEF_VERSION,
2272         MNTTYPE_ZFS,
2273         zfs_vfsinit,
2274         VSW_HASPROTO|VSW_CANRWRO|VSW_CANREMOUNT|VSW_VOLATILEDEV|VSW_STATS|
2275             VSW_XID,
2276         &zfs_mntopts
2277 };
2278
2279 struct modlfs zfs_modlfs = {
2280         &mod_fsops, "ZFS filesystem version " SPA_VERSION_STRING, &vfw
2281 };