]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_ioctl.c
Merge bmake-20121111
[FreeBSD/FreeBSD.git] / sys / cddl / contrib / opensolaris / uts / common / fs / zfs / zfs_ioctl.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 /*
23  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Copyright (c) 2011-2012 Pawel Jakub Dawidek <pawel@dawidek.net>.
25  * All rights reserved.
26  * Portions Copyright 2011 Martin Matuska <mm@FreeBSD.org>
27  * Copyright 2011 Nexenta Systems, Inc.  All rights reserved.
28  * Copyright (c) 2012 by Delphix. All rights reserved.
29  * Copyright (c) 2012, Joyent, Inc. All rights reserved.
30  */
31
32 #include <sys/types.h>
33 #include <sys/param.h>
34 #include <sys/systm.h>
35 #include <sys/conf.h>
36 #include <sys/kernel.h>
37 #include <sys/lock.h>
38 #include <sys/malloc.h>
39 #include <sys/mutex.h>
40 #include <sys/proc.h>
41 #include <sys/errno.h>
42 #include <sys/uio.h>
43 #include <sys/buf.h>
44 #include <sys/file.h>
45 #include <sys/kmem.h>
46 #include <sys/conf.h>
47 #include <sys/cmn_err.h>
48 #include <sys/stat.h>
49 #include <sys/zfs_ioctl.h>
50 #include <sys/zfs_vfsops.h>
51 #include <sys/zfs_znode.h>
52 #include <sys/zap.h>
53 #include <sys/spa.h>
54 #include <sys/spa_impl.h>
55 #include <sys/vdev.h>
56 #include <sys/dmu.h>
57 #include <sys/dsl_dir.h>
58 #include <sys/dsl_dataset.h>
59 #include <sys/dsl_prop.h>
60 #include <sys/dsl_deleg.h>
61 #include <sys/dmu_objset.h>
62 #include <sys/dmu_impl.h>
63 #include <sys/sunddi.h>
64 #include <sys/policy.h>
65 #include <sys/zone.h>
66 #include <sys/nvpair.h>
67 #include <sys/mount.h>
68 #include <sys/taskqueue.h>
69 #include <sys/sdt.h>
70 #include <sys/varargs.h>
71 #include <sys/fs/zfs.h>
72 #include <sys/zfs_ctldir.h>
73 #include <sys/zfs_dir.h>
74 #include <sys/zfs_onexit.h>
75 #include <sys/zvol.h>
76 #include <sys/dsl_scan.h>
77 #include <sys/dmu_objset.h>
78
79 #include "zfs_namecheck.h"
80 #include "zfs_prop.h"
81 #include "zfs_deleg.h"
82 #include "zfs_comutil.h"
83 #include "zfs_ioctl_compat.h"
84
85 CTASSERT(sizeof(zfs_cmd_t) < IOCPARM_MAX);
86
87 static int snapshot_list_prefetch;
88 SYSCTL_DECL(_vfs_zfs);
89 TUNABLE_INT("vfs.zfs.snapshot_list_prefetch", &snapshot_list_prefetch);
90 SYSCTL_INT(_vfs_zfs, OID_AUTO, snapshot_list_prefetch, CTLFLAG_RW,
91     &snapshot_list_prefetch, 0, "Prefetch data when listing snapshots");
92
93 static struct cdev *zfsdev;
94
95 extern void zfs_init(void);
96 extern void zfs_fini(void);
97
98 typedef int zfs_ioc_func_t(zfs_cmd_t *);
99 typedef int zfs_secpolicy_func_t(zfs_cmd_t *, cred_t *);
100
101 typedef enum {
102         NO_NAME,
103         POOL_NAME,
104         DATASET_NAME
105 } zfs_ioc_namecheck_t;
106
107 typedef struct zfs_ioc_vec {
108         zfs_ioc_func_t          *zvec_func;
109         zfs_secpolicy_func_t    *zvec_secpolicy;
110         zfs_ioc_namecheck_t     zvec_namecheck;
111         boolean_t               zvec_his_log;
112         boolean_t               zvec_pool_check;
113 } zfs_ioc_vec_t;
114
115 /* This array is indexed by zfs_userquota_prop_t */
116 static const char *userquota_perms[] = {
117         ZFS_DELEG_PERM_USERUSED,
118         ZFS_DELEG_PERM_USERQUOTA,
119         ZFS_DELEG_PERM_GROUPUSED,
120         ZFS_DELEG_PERM_GROUPQUOTA,
121 };
122
123 static int zfs_ioc_userspace_upgrade(zfs_cmd_t *zc);
124 static int zfs_check_settable(const char *name, nvpair_t *property,
125     cred_t *cr);
126 static int zfs_check_clearable(char *dataset, nvlist_t *props,
127     nvlist_t **errors);
128 static int zfs_fill_zplprops_root(uint64_t, nvlist_t *, nvlist_t *,
129     boolean_t *);
130 int zfs_set_prop_nvlist(const char *, zprop_source_t, nvlist_t *, nvlist_t **);
131  
132 static void zfsdev_close(void *data);
133
134 /* _NOTE(PRINTFLIKE(4)) - this is printf-like, but lint is too whiney */
135 void
136 __dprintf(const char *file, const char *func, int line, const char *fmt, ...)
137 {
138         const char *newfile;
139         char buf[512];
140         va_list adx;
141
142         /*
143          * Get rid of annoying "../common/" prefix to filename.
144          */
145         newfile = strrchr(file, '/');
146         if (newfile != NULL) {
147                 newfile = newfile + 1; /* Get rid of leading / */
148         } else {
149                 newfile = file;
150         }
151
152         va_start(adx, fmt);
153         (void) vsnprintf(buf, sizeof (buf), fmt, adx);
154         va_end(adx);
155
156         /*
157          * To get this data, use the zfs-dprintf probe as so:
158          * dtrace -q -n 'zfs-dprintf \
159          *      /stringof(arg0) == "dbuf.c"/ \
160          *      {printf("%s: %s", stringof(arg1), stringof(arg3))}'
161          * arg0 = file name
162          * arg1 = function name
163          * arg2 = line number
164          * arg3 = message
165          */
166         DTRACE_PROBE4(zfs__dprintf,
167             char *, newfile, char *, func, int, line, char *, buf);
168 }
169
170 static void
171 history_str_free(char *buf)
172 {
173         kmem_free(buf, HIS_MAX_RECORD_LEN);
174 }
175
176 static char *
177 history_str_get(zfs_cmd_t *zc)
178 {
179         char *buf;
180
181         if (zc->zc_history == 0)
182                 return (NULL);
183
184         buf = kmem_alloc(HIS_MAX_RECORD_LEN, KM_SLEEP);
185         if (copyinstr((void *)(uintptr_t)zc->zc_history,
186             buf, HIS_MAX_RECORD_LEN, NULL) != 0) {
187                 history_str_free(buf);
188                 return (NULL);
189         }
190
191         buf[HIS_MAX_RECORD_LEN -1] = '\0';
192
193         return (buf);
194 }
195
196 /*
197  * Check to see if the named dataset is currently defined as bootable
198  */
199 static boolean_t
200 zfs_is_bootfs(const char *name)
201 {
202         objset_t *os;
203
204         if (dmu_objset_hold(name, FTAG, &os) == 0) {
205                 boolean_t ret;
206                 ret = (dmu_objset_id(os) == spa_bootfs(dmu_objset_spa(os)));
207                 dmu_objset_rele(os, FTAG);
208                 return (ret);
209         }
210         return (B_FALSE);
211 }
212
213 /*
214  * zfs_earlier_version
215  *
216  *      Return non-zero if the spa version is less than requested version.
217  */
218 static int
219 zfs_earlier_version(const char *name, int version)
220 {
221         spa_t *spa;
222
223         if (spa_open(name, &spa, FTAG) == 0) {
224                 if (spa_version(spa) < version) {
225                         spa_close(spa, FTAG);
226                         return (1);
227                 }
228                 spa_close(spa, FTAG);
229         }
230         return (0);
231 }
232
233 /*
234  * zpl_earlier_version
235  *
236  * Return TRUE if the ZPL version is less than requested version.
237  */
238 static boolean_t
239 zpl_earlier_version(const char *name, int version)
240 {
241         objset_t *os;
242         boolean_t rc = B_TRUE;
243
244         if (dmu_objset_hold(name, FTAG, &os) == 0) {
245                 uint64_t zplversion;
246
247                 if (dmu_objset_type(os) != DMU_OST_ZFS) {
248                         dmu_objset_rele(os, FTAG);
249                         return (B_TRUE);
250                 }
251                 /* XXX reading from non-owned objset */
252                 if (zfs_get_zplprop(os, ZFS_PROP_VERSION, &zplversion) == 0)
253                         rc = zplversion < version;
254                 dmu_objset_rele(os, FTAG);
255         }
256         return (rc);
257 }
258
259 static void
260 zfs_log_history(zfs_cmd_t *zc)
261 {
262         spa_t *spa;
263         char *buf;
264
265         if ((buf = history_str_get(zc)) == NULL)
266                 return;
267
268         if (spa_open(zc->zc_name, &spa, FTAG) == 0) {
269                 if (spa_version(spa) >= SPA_VERSION_ZPOOL_HISTORY)
270                         (void) spa_history_log(spa, buf, LOG_CMD_NORMAL);
271                 spa_close(spa, FTAG);
272         }
273         history_str_free(buf);
274 }
275
276 /*
277  * Policy for top-level read operations (list pools).  Requires no privileges,
278  * and can be used in the local zone, as there is no associated dataset.
279  */
280 /* ARGSUSED */
281 static int
282 zfs_secpolicy_none(zfs_cmd_t *zc, cred_t *cr)
283 {
284         return (0);
285 }
286
287 /*
288  * Policy for dataset read operations (list children, get statistics).  Requires
289  * no privileges, but must be visible in the local zone.
290  */
291 /* ARGSUSED */
292 static int
293 zfs_secpolicy_read(zfs_cmd_t *zc, cred_t *cr)
294 {
295         if (INGLOBALZONE(curthread) ||
296             zone_dataset_visible(zc->zc_name, NULL))
297                 return (0);
298
299         return (ENOENT);
300 }
301
302 static int
303 zfs_dozonecheck_impl(const char *dataset, uint64_t zoned, cred_t *cr)
304 {
305         int writable = 1;
306
307         /*
308          * The dataset must be visible by this zone -- check this first
309          * so they don't see EPERM on something they shouldn't know about.
310          */
311         if (!INGLOBALZONE(curthread) &&
312             !zone_dataset_visible(dataset, &writable))
313                 return (ENOENT);
314
315         if (INGLOBALZONE(curthread)) {
316                 /*
317                  * If the fs is zoned, only root can access it from the
318                  * global zone.
319                  */
320                 if (secpolicy_zfs(cr) && zoned)
321                         return (EPERM);
322         } else {
323                 /*
324                  * If we are in a local zone, the 'zoned' property must be set.
325                  */
326                 if (!zoned)
327                         return (EPERM);
328
329                 /* must be writable by this zone */
330                 if (!writable)
331                         return (EPERM);
332         }
333         return (0);
334 }
335
336 static int
337 zfs_dozonecheck(const char *dataset, cred_t *cr)
338 {
339         uint64_t zoned;
340
341         if (dsl_prop_get_integer(dataset, "jailed", &zoned, NULL))
342                 return (ENOENT);
343
344         return (zfs_dozonecheck_impl(dataset, zoned, cr));
345 }
346
347 static int
348 zfs_dozonecheck_ds(const char *dataset, dsl_dataset_t *ds, cred_t *cr)
349 {
350         uint64_t zoned;
351
352         rw_enter(&ds->ds_dir->dd_pool->dp_config_rwlock, RW_READER);
353         if (dsl_prop_get_ds(ds, "jailed", 8, 1, &zoned, NULL)) {
354                 rw_exit(&ds->ds_dir->dd_pool->dp_config_rwlock);
355                 return (ENOENT);
356         }
357         rw_exit(&ds->ds_dir->dd_pool->dp_config_rwlock);
358
359         return (zfs_dozonecheck_impl(dataset, zoned, cr));
360 }
361
362 /*
363  * If name ends in a '@', then require recursive permissions.
364  */
365 int
366 zfs_secpolicy_write_perms(const char *name, const char *perm, cred_t *cr)
367 {
368         int error;
369         boolean_t descendent = B_FALSE;
370         dsl_dataset_t *ds;
371         char *at;
372
373         at = strchr(name, '@');
374         if (at != NULL && at[1] == '\0') {
375                 *at = '\0';
376                 descendent = B_TRUE;
377         }
378
379         error = dsl_dataset_hold(name, FTAG, &ds);
380         if (at != NULL)
381                 *at = '@';
382         if (error != 0)
383                 return (error);
384
385         error = zfs_dozonecheck_ds(name, ds, cr);
386         if (error == 0) {
387                 error = secpolicy_zfs(cr);
388                 if (error)
389                         error = dsl_deleg_access_impl(ds, descendent, perm, cr);
390         }
391
392         dsl_dataset_rele(ds, FTAG);
393         return (error);
394 }
395
396 int
397 zfs_secpolicy_write_perms_ds(const char *name, dsl_dataset_t *ds,
398     const char *perm, cred_t *cr)
399 {
400         int error;
401
402         error = zfs_dozonecheck_ds(name, ds, cr);
403         if (error == 0) {
404                 error = secpolicy_zfs(cr);
405                 if (error)
406                         error = dsl_deleg_access_impl(ds, B_FALSE, perm, cr);
407         }
408         return (error);
409 }
410
411 #ifdef SECLABEL
412 /*
413  * Policy for setting the security label property.
414  *
415  * Returns 0 for success, non-zero for access and other errors.
416  */
417 static int
418 zfs_set_slabel_policy(const char *name, char *strval, cred_t *cr)
419 {
420         char            ds_hexsl[MAXNAMELEN];
421         bslabel_t       ds_sl, new_sl;
422         boolean_t       new_default = FALSE;
423         uint64_t        zoned;
424         int             needed_priv = -1;
425         int             error;
426
427         /* First get the existing dataset label. */
428         error = dsl_prop_get(name, zfs_prop_to_name(ZFS_PROP_MLSLABEL),
429             1, sizeof (ds_hexsl), &ds_hexsl, NULL);
430         if (error)
431                 return (EPERM);
432
433         if (strcasecmp(strval, ZFS_MLSLABEL_DEFAULT) == 0)
434                 new_default = TRUE;
435
436         /* The label must be translatable */
437         if (!new_default && (hexstr_to_label(strval, &new_sl) != 0))
438                 return (EINVAL);
439
440         /*
441          * In a non-global zone, disallow attempts to set a label that
442          * doesn't match that of the zone; otherwise no other checks
443          * are needed.
444          */
445         if (!INGLOBALZONE(curproc)) {
446                 if (new_default || !blequal(&new_sl, CR_SL(CRED())))
447                         return (EPERM);
448                 return (0);
449         }
450
451         /*
452          * For global-zone datasets (i.e., those whose zoned property is
453          * "off", verify that the specified new label is valid for the
454          * global zone.
455          */
456         if (dsl_prop_get_integer(name,
457             zfs_prop_to_name(ZFS_PROP_ZONED), &zoned, NULL))
458                 return (EPERM);
459         if (!zoned) {
460                 if (zfs_check_global_label(name, strval) != 0)
461                         return (EPERM);
462         }
463
464         /*
465          * If the existing dataset label is nondefault, check if the
466          * dataset is mounted (label cannot be changed while mounted).
467          * Get the zfsvfs; if there isn't one, then the dataset isn't
468          * mounted (or isn't a dataset, doesn't exist, ...).
469          */
470         if (strcasecmp(ds_hexsl, ZFS_MLSLABEL_DEFAULT) != 0) {
471                 objset_t *os;
472                 static char *setsl_tag = "setsl_tag";
473
474                 /*
475                  * Try to own the dataset; abort if there is any error,
476                  * (e.g., already mounted, in use, or other error).
477                  */
478                 error = dmu_objset_own(name, DMU_OST_ZFS, B_TRUE,
479                     setsl_tag, &os);
480                 if (error)
481                         return (EPERM);
482
483                 dmu_objset_disown(os, setsl_tag);
484
485                 if (new_default) {
486                         needed_priv = PRIV_FILE_DOWNGRADE_SL;
487                         goto out_check;
488                 }
489
490                 if (hexstr_to_label(strval, &new_sl) != 0)
491                         return (EPERM);
492
493                 if (blstrictdom(&ds_sl, &new_sl))
494                         needed_priv = PRIV_FILE_DOWNGRADE_SL;
495                 else if (blstrictdom(&new_sl, &ds_sl))
496                         needed_priv = PRIV_FILE_UPGRADE_SL;
497         } else {
498                 /* dataset currently has a default label */
499                 if (!new_default)
500                         needed_priv = PRIV_FILE_UPGRADE_SL;
501         }
502
503 out_check:
504         if (needed_priv != -1)
505                 return (PRIV_POLICY(cr, needed_priv, B_FALSE, EPERM, NULL));
506         return (0);
507 }
508 #endif  /* SECLABEL */
509
510 static int
511 zfs_secpolicy_setprop(const char *dsname, zfs_prop_t prop, nvpair_t *propval,
512     cred_t *cr)
513 {
514         char *strval;
515
516         /*
517          * Check permissions for special properties.
518          */
519         switch (prop) {
520         case ZFS_PROP_ZONED:
521                 /*
522                  * Disallow setting of 'zoned' from within a local zone.
523                  */
524                 if (!INGLOBALZONE(curthread))
525                         return (EPERM);
526                 break;
527
528         case ZFS_PROP_QUOTA:
529                 if (!INGLOBALZONE(curthread)) {
530                         uint64_t zoned;
531                         char setpoint[MAXNAMELEN];
532                         /*
533                          * Unprivileged users are allowed to modify the
534                          * quota on things *under* (ie. contained by)
535                          * the thing they own.
536                          */
537                         if (dsl_prop_get_integer(dsname, "jailed", &zoned,
538                             setpoint))
539                                 return (EPERM);
540                         if (!zoned || strlen(dsname) <= strlen(setpoint))
541                                 return (EPERM);
542                 }
543                 break;
544
545         case ZFS_PROP_MLSLABEL:
546 #ifdef SECLABEL
547                 if (!is_system_labeled())
548                         return (EPERM);
549
550                 if (nvpair_value_string(propval, &strval) == 0) {
551                         int err;
552
553                         err = zfs_set_slabel_policy(dsname, strval, CRED());
554                         if (err != 0)
555                                 return (err);
556                 }
557 #else
558                 return (EOPNOTSUPP);
559 #endif
560                 break;
561         }
562
563         return (zfs_secpolicy_write_perms(dsname, zfs_prop_to_name(prop), cr));
564 }
565
566 int
567 zfs_secpolicy_fsacl(zfs_cmd_t *zc, cred_t *cr)
568 {
569         int error;
570
571         error = zfs_dozonecheck(zc->zc_name, cr);
572         if (error)
573                 return (error);
574
575         /*
576          * permission to set permissions will be evaluated later in
577          * dsl_deleg_can_allow()
578          */
579         return (0);
580 }
581
582 int
583 zfs_secpolicy_rollback(zfs_cmd_t *zc, cred_t *cr)
584 {
585         return (zfs_secpolicy_write_perms(zc->zc_name,
586             ZFS_DELEG_PERM_ROLLBACK, cr));
587 }
588
589 int
590 zfs_secpolicy_send(zfs_cmd_t *zc, cred_t *cr)
591 {
592         spa_t *spa;
593         dsl_pool_t *dp;
594         dsl_dataset_t *ds;
595         char *cp;
596         int error;
597
598         /*
599          * Generate the current snapshot name from the given objsetid, then
600          * use that name for the secpolicy/zone checks.
601          */
602         cp = strchr(zc->zc_name, '@');
603         if (cp == NULL)
604                 return (EINVAL);
605         error = spa_open(zc->zc_name, &spa, FTAG);
606         if (error)
607                 return (error);
608
609         dp = spa_get_dsl(spa);
610         rw_enter(&dp->dp_config_rwlock, RW_READER);
611         error = dsl_dataset_hold_obj(dp, zc->zc_sendobj, FTAG, &ds);
612         rw_exit(&dp->dp_config_rwlock);
613         spa_close(spa, FTAG);
614         if (error)
615                 return (error);
616
617         dsl_dataset_name(ds, zc->zc_name);
618
619         error = zfs_secpolicy_write_perms_ds(zc->zc_name, ds,
620             ZFS_DELEG_PERM_SEND, cr);
621         dsl_dataset_rele(ds, FTAG);
622
623         return (error);
624 }
625
626 static int
627 zfs_secpolicy_deleg_share(zfs_cmd_t *zc, cred_t *cr)
628 {
629         vnode_t *vp;
630         int error;
631
632         if ((error = lookupname(zc->zc_value, UIO_SYSSPACE,
633             NO_FOLLOW, NULL, &vp)) != 0)
634                 return (error);
635
636         /* Now make sure mntpnt and dataset are ZFS */
637
638         if (strcmp(vp->v_vfsp->mnt_stat.f_fstypename, "zfs") != 0 ||
639             (strcmp((char *)refstr_value(vp->v_vfsp->vfs_resource),
640             zc->zc_name) != 0)) {
641                 VN_RELE(vp);
642                 return (EPERM);
643         }
644
645         VN_RELE(vp);
646         return (dsl_deleg_access(zc->zc_name,
647             ZFS_DELEG_PERM_SHARE, cr));
648 }
649
650 int
651 zfs_secpolicy_share(zfs_cmd_t *zc, cred_t *cr)
652 {
653         if (!INGLOBALZONE(curthread))
654                 return (EPERM);
655
656         if (secpolicy_nfs(cr) == 0) {
657                 return (0);
658         } else {
659                 return (zfs_secpolicy_deleg_share(zc, cr));
660         }
661 }
662
663 int
664 zfs_secpolicy_smb_acl(zfs_cmd_t *zc, cred_t *cr)
665 {
666         if (!INGLOBALZONE(curthread))
667                 return (EPERM);
668
669         if (secpolicy_smb(cr) == 0) {
670                 return (0);
671         } else {
672                 return (zfs_secpolicy_deleg_share(zc, cr));
673         }
674 }
675
676 static int
677 zfs_get_parent(const char *datasetname, char *parent, int parentsize)
678 {
679         char *cp;
680
681         /*
682          * Remove the @bla or /bla from the end of the name to get the parent.
683          */
684         (void) strncpy(parent, datasetname, parentsize);
685         cp = strrchr(parent, '@');
686         if (cp != NULL) {
687                 cp[0] = '\0';
688         } else {
689                 cp = strrchr(parent, '/');
690                 if (cp == NULL)
691                         return (ENOENT);
692                 cp[0] = '\0';
693         }
694
695         return (0);
696 }
697
698 int
699 zfs_secpolicy_destroy_perms(const char *name, cred_t *cr)
700 {
701         int error;
702
703         if ((error = zfs_secpolicy_write_perms(name,
704             ZFS_DELEG_PERM_MOUNT, cr)) != 0)
705                 return (error);
706
707         return (zfs_secpolicy_write_perms(name, ZFS_DELEG_PERM_DESTROY, cr));
708 }
709
710 static int
711 zfs_secpolicy_destroy(zfs_cmd_t *zc, cred_t *cr)
712 {
713         return (zfs_secpolicy_destroy_perms(zc->zc_name, cr));
714 }
715
716 /*
717  * Destroying snapshots with delegated permissions requires
718  * descendent mount and destroy permissions.
719  */
720 static int
721 zfs_secpolicy_destroy_recursive(zfs_cmd_t *zc, cred_t *cr)
722 {
723         int error;
724         char *dsname;
725
726         dsname = kmem_asprintf("%s@", zc->zc_name);
727
728         error = zfs_secpolicy_destroy_perms(dsname, cr);
729
730         if (error == ENOENT)
731                 error = zfs_secpolicy_destroy_perms(zc->zc_name, cr);
732
733         strfree(dsname);
734         return (error);
735 }
736
737 int
738 zfs_secpolicy_rename_perms(const char *from, const char *to, cred_t *cr)
739 {
740         char    parentname[MAXNAMELEN];
741         int     error;
742
743         if ((error = zfs_secpolicy_write_perms(from,
744             ZFS_DELEG_PERM_RENAME, cr)) != 0)
745                 return (error);
746
747         if ((error = zfs_secpolicy_write_perms(from,
748             ZFS_DELEG_PERM_MOUNT, cr)) != 0)
749                 return (error);
750
751         if ((error = zfs_get_parent(to, parentname,
752             sizeof (parentname))) != 0)
753                 return (error);
754
755         if ((error = zfs_secpolicy_write_perms(parentname,
756             ZFS_DELEG_PERM_CREATE, cr)) != 0)
757                 return (error);
758
759         if ((error = zfs_secpolicy_write_perms(parentname,
760             ZFS_DELEG_PERM_MOUNT, cr)) != 0)
761                 return (error);
762
763         return (error);
764 }
765
766 static int
767 zfs_secpolicy_rename(zfs_cmd_t *zc, cred_t *cr)
768 {
769         char *at = NULL;
770         int error;
771
772         if ((zc->zc_cookie & 1) != 0) {
773                 /*
774                  * This is recursive rename, so the starting snapshot might
775                  * not exist. Check file system or volume permission instead.
776                  */
777                 at = strchr(zc->zc_name, '@');
778                 if (at == NULL)
779                         return (EINVAL);
780                 *at = '\0';
781         }
782
783         error = zfs_secpolicy_rename_perms(zc->zc_name, zc->zc_value, cr);
784
785         if (at != NULL)
786                 *at = '@';
787
788         return (error);
789 }
790
791 static int
792 zfs_secpolicy_promote(zfs_cmd_t *zc, cred_t *cr)
793 {
794         char    parentname[MAXNAMELEN];
795         objset_t *clone;
796         int error;
797
798         error = zfs_secpolicy_write_perms(zc->zc_name,
799             ZFS_DELEG_PERM_PROMOTE, cr);
800         if (error)
801                 return (error);
802
803         error = dmu_objset_hold(zc->zc_name, FTAG, &clone);
804
805         if (error == 0) {
806                 dsl_dataset_t *pclone = NULL;
807                 dsl_dir_t *dd;
808                 dd = clone->os_dsl_dataset->ds_dir;
809
810                 rw_enter(&dd->dd_pool->dp_config_rwlock, RW_READER);
811                 error = dsl_dataset_hold_obj(dd->dd_pool,
812                     dd->dd_phys->dd_origin_obj, FTAG, &pclone);
813                 rw_exit(&dd->dd_pool->dp_config_rwlock);
814                 if (error) {
815                         dmu_objset_rele(clone, FTAG);
816                         return (error);
817                 }
818
819                 error = zfs_secpolicy_write_perms(zc->zc_name,
820                     ZFS_DELEG_PERM_MOUNT, cr);
821
822                 dsl_dataset_name(pclone, parentname);
823                 dmu_objset_rele(clone, FTAG);
824                 dsl_dataset_rele(pclone, FTAG);
825                 if (error == 0)
826                         error = zfs_secpolicy_write_perms(parentname,
827                             ZFS_DELEG_PERM_PROMOTE, cr);
828         }
829         return (error);
830 }
831
832 static int
833 zfs_secpolicy_receive(zfs_cmd_t *zc, cred_t *cr)
834 {
835         int error;
836
837         if ((error = zfs_secpolicy_write_perms(zc->zc_name,
838             ZFS_DELEG_PERM_RECEIVE, cr)) != 0)
839                 return (error);
840
841         if ((error = zfs_secpolicy_write_perms(zc->zc_name,
842             ZFS_DELEG_PERM_MOUNT, cr)) != 0)
843                 return (error);
844
845         return (zfs_secpolicy_write_perms(zc->zc_name,
846             ZFS_DELEG_PERM_CREATE, cr));
847 }
848
849 int
850 zfs_secpolicy_snapshot_perms(const char *name, cred_t *cr)
851 {
852         return (zfs_secpolicy_write_perms(name,
853             ZFS_DELEG_PERM_SNAPSHOT, cr));
854 }
855
856 static int
857 zfs_secpolicy_snapshot(zfs_cmd_t *zc, cred_t *cr)
858 {
859
860         return (zfs_secpolicy_snapshot_perms(zc->zc_name, cr));
861 }
862
863 static int
864 zfs_secpolicy_create(zfs_cmd_t *zc, cred_t *cr)
865 {
866         char    parentname[MAXNAMELEN];
867         int     error;
868
869         if ((error = zfs_get_parent(zc->zc_name, parentname,
870             sizeof (parentname))) != 0)
871                 return (error);
872
873         if (zc->zc_value[0] != '\0') {
874                 if ((error = zfs_secpolicy_write_perms(zc->zc_value,
875                     ZFS_DELEG_PERM_CLONE, cr)) != 0)
876                         return (error);
877         }
878
879         if ((error = zfs_secpolicy_write_perms(parentname,
880             ZFS_DELEG_PERM_CREATE, cr)) != 0)
881                 return (error);
882
883         error = zfs_secpolicy_write_perms(parentname,
884             ZFS_DELEG_PERM_MOUNT, cr);
885
886         return (error);
887 }
888
889 static int
890 zfs_secpolicy_umount(zfs_cmd_t *zc, cred_t *cr)
891 {
892         int error;
893
894         error = secpolicy_fs_unmount(cr, NULL);
895         if (error) {
896                 error = dsl_deleg_access(zc->zc_name, ZFS_DELEG_PERM_MOUNT, cr);
897         }
898         return (error);
899 }
900
901 /*
902  * Policy for pool operations - create/destroy pools, add vdevs, etc.  Requires
903  * SYS_CONFIG privilege, which is not available in a local zone.
904  */
905 /* ARGSUSED */
906 static int
907 zfs_secpolicy_config(zfs_cmd_t *zc, cred_t *cr)
908 {
909         if (secpolicy_sys_config(cr, B_FALSE) != 0)
910                 return (EPERM);
911
912         return (0);
913 }
914
915 /*
916  * Policy for object to name lookups.
917  */
918 /* ARGSUSED */
919 static int
920 zfs_secpolicy_diff(zfs_cmd_t *zc, cred_t *cr)
921 {
922         int error;
923
924         if ((error = secpolicy_sys_config(cr, B_FALSE)) == 0)
925                 return (0);
926
927         error = zfs_secpolicy_write_perms(zc->zc_name, ZFS_DELEG_PERM_DIFF, cr);
928         return (error);
929 }
930
931 /*
932  * Policy for fault injection.  Requires all privileges.
933  */
934 /* ARGSUSED */
935 static int
936 zfs_secpolicy_inject(zfs_cmd_t *zc, cred_t *cr)
937 {
938         return (secpolicy_zinject(cr));
939 }
940
941 static int
942 zfs_secpolicy_inherit(zfs_cmd_t *zc, cred_t *cr)
943 {
944         zfs_prop_t prop = zfs_name_to_prop(zc->zc_value);
945
946         if (prop == ZPROP_INVAL) {
947                 if (!zfs_prop_user(zc->zc_value))
948                         return (EINVAL);
949                 return (zfs_secpolicy_write_perms(zc->zc_name,
950                     ZFS_DELEG_PERM_USERPROP, cr));
951         } else {
952                 return (zfs_secpolicy_setprop(zc->zc_name, prop,
953                     NULL, cr));
954         }
955 }
956
957 static int
958 zfs_secpolicy_userspace_one(zfs_cmd_t *zc, cred_t *cr)
959 {
960         int err = zfs_secpolicy_read(zc, cr);
961         if (err)
962                 return (err);
963
964         if (zc->zc_objset_type >= ZFS_NUM_USERQUOTA_PROPS)
965                 return (EINVAL);
966
967         if (zc->zc_value[0] == 0) {
968                 /*
969                  * They are asking about a posix uid/gid.  If it's
970                  * themself, allow it.
971                  */
972                 if (zc->zc_objset_type == ZFS_PROP_USERUSED ||
973                     zc->zc_objset_type == ZFS_PROP_USERQUOTA) {
974                         if (zc->zc_guid == crgetuid(cr))
975                                 return (0);
976                 } else {
977                         if (groupmember(zc->zc_guid, cr))
978                                 return (0);
979                 }
980         }
981
982         return (zfs_secpolicy_write_perms(zc->zc_name,
983             userquota_perms[zc->zc_objset_type], cr));
984 }
985
986 static int
987 zfs_secpolicy_userspace_many(zfs_cmd_t *zc, cred_t *cr)
988 {
989         int err = zfs_secpolicy_read(zc, cr);
990         if (err)
991                 return (err);
992
993         if (zc->zc_objset_type >= ZFS_NUM_USERQUOTA_PROPS)
994                 return (EINVAL);
995
996         return (zfs_secpolicy_write_perms(zc->zc_name,
997             userquota_perms[zc->zc_objset_type], cr));
998 }
999
1000 static int
1001 zfs_secpolicy_userspace_upgrade(zfs_cmd_t *zc, cred_t *cr)
1002 {
1003         return (zfs_secpolicy_setprop(zc->zc_name, ZFS_PROP_VERSION,
1004             NULL, cr));
1005 }
1006
1007 static int
1008 zfs_secpolicy_hold(zfs_cmd_t *zc, cred_t *cr)
1009 {
1010         return (zfs_secpolicy_write_perms(zc->zc_name,
1011             ZFS_DELEG_PERM_HOLD, cr));
1012 }
1013
1014 static int
1015 zfs_secpolicy_release(zfs_cmd_t *zc, cred_t *cr)
1016 {
1017         return (zfs_secpolicy_write_perms(zc->zc_name,
1018             ZFS_DELEG_PERM_RELEASE, cr));
1019 }
1020
1021 /*
1022  * Policy for allowing temporary snapshots to be taken or released
1023  */
1024 static int
1025 zfs_secpolicy_tmp_snapshot(zfs_cmd_t *zc, cred_t *cr)
1026 {
1027         /*
1028          * A temporary snapshot is the same as a snapshot,
1029          * hold, destroy and release all rolled into one.
1030          * Delegated diff alone is sufficient that we allow this.
1031          */
1032         int error;
1033
1034         if ((error = zfs_secpolicy_write_perms(zc->zc_name,
1035             ZFS_DELEG_PERM_DIFF, cr)) == 0)
1036                 return (0);
1037
1038         error = zfs_secpolicy_snapshot(zc, cr);
1039         if (!error)
1040                 error = zfs_secpolicy_hold(zc, cr);
1041         if (!error)
1042                 error = zfs_secpolicy_release(zc, cr);
1043         if (!error)
1044                 error = zfs_secpolicy_destroy(zc, cr);
1045         return (error);
1046 }
1047
1048 /*
1049  * Returns the nvlist as specified by the user in the zfs_cmd_t.
1050  */
1051 static int
1052 get_nvlist(uint64_t nvl, uint64_t size, int iflag, nvlist_t **nvp)
1053 {
1054         char *packed;
1055         int error;
1056         nvlist_t *list = NULL;
1057
1058         /*
1059          * Read in and unpack the user-supplied nvlist.
1060          */
1061         if (size == 0)
1062                 return (EINVAL);
1063
1064         packed = kmem_alloc(size, KM_SLEEP);
1065
1066         if ((error = ddi_copyin((void *)(uintptr_t)nvl, packed, size,
1067             iflag)) != 0) {
1068                 kmem_free(packed, size);
1069                 return (error);
1070         }
1071
1072         if ((error = nvlist_unpack(packed, size, &list, 0)) != 0) {
1073                 kmem_free(packed, size);
1074                 return (error);
1075         }
1076
1077         kmem_free(packed, size);
1078
1079         *nvp = list;
1080         return (0);
1081 }
1082
1083 static int
1084 fit_error_list(zfs_cmd_t *zc, nvlist_t **errors)
1085 {
1086         size_t size;
1087
1088         VERIFY(nvlist_size(*errors, &size, NV_ENCODE_NATIVE) == 0);
1089
1090         if (size > zc->zc_nvlist_dst_size) {
1091                 nvpair_t *more_errors;
1092                 int n = 0;
1093
1094                 if (zc->zc_nvlist_dst_size < 1024)
1095                         return (ENOMEM);
1096
1097                 VERIFY(nvlist_add_int32(*errors, ZPROP_N_MORE_ERRORS, 0) == 0);
1098                 more_errors = nvlist_prev_nvpair(*errors, NULL);
1099
1100                 do {
1101                         nvpair_t *pair = nvlist_prev_nvpair(*errors,
1102                             more_errors);
1103                         VERIFY(nvlist_remove_nvpair(*errors, pair) == 0);
1104                         n++;
1105                         VERIFY(nvlist_size(*errors, &size,
1106                             NV_ENCODE_NATIVE) == 0);
1107                 } while (size > zc->zc_nvlist_dst_size);
1108
1109                 VERIFY(nvlist_remove_nvpair(*errors, more_errors) == 0);
1110                 VERIFY(nvlist_add_int32(*errors, ZPROP_N_MORE_ERRORS, n) == 0);
1111                 ASSERT(nvlist_size(*errors, &size, NV_ENCODE_NATIVE) == 0);
1112                 ASSERT(size <= zc->zc_nvlist_dst_size);
1113         }
1114
1115         return (0);
1116 }
1117
1118 static int
1119 put_nvlist(zfs_cmd_t *zc, nvlist_t *nvl)
1120 {
1121         char *packed = NULL;
1122         int error = 0;
1123         size_t size;
1124
1125         VERIFY(nvlist_size(nvl, &size, NV_ENCODE_NATIVE) == 0);
1126
1127         if (size > zc->zc_nvlist_dst_size) {
1128                 /*
1129                  * Solaris returns ENOMEM here, because even if an error is
1130                  * returned from an ioctl(2), new zc_nvlist_dst_size will be
1131                  * passed to the userland. This is not the case for FreeBSD.
1132                  * We need to return 0, so the kernel will copy the
1133                  * zc_nvlist_dst_size back and the userland can discover that a
1134                  * bigger buffer is needed.
1135                  */
1136                 error = 0;
1137         } else {
1138                 packed = kmem_alloc(size, KM_SLEEP);
1139                 VERIFY(nvlist_pack(nvl, &packed, &size, NV_ENCODE_NATIVE,
1140                     KM_SLEEP) == 0);
1141                 if (ddi_copyout(packed, (void *)(uintptr_t)zc->zc_nvlist_dst,
1142                     size, zc->zc_iflags) != 0)
1143                         error = EFAULT;
1144                 kmem_free(packed, size);
1145         }
1146
1147         zc->zc_nvlist_dst_size = size;
1148         return (error);
1149 }
1150
1151 static int
1152 getzfsvfs(const char *dsname, zfsvfs_t **zfvp)
1153 {
1154         objset_t *os;
1155         int error;
1156
1157         error = dmu_objset_hold(dsname, FTAG, &os);
1158         if (error)
1159                 return (error);
1160         if (dmu_objset_type(os) != DMU_OST_ZFS) {
1161                 dmu_objset_rele(os, FTAG);
1162                 return (EINVAL);
1163         }
1164
1165         mutex_enter(&os->os_user_ptr_lock);
1166         *zfvp = dmu_objset_get_user(os);
1167         if (*zfvp) {
1168                 VFS_HOLD((*zfvp)->z_vfs);
1169         } else {
1170                 error = ESRCH;
1171         }
1172         mutex_exit(&os->os_user_ptr_lock);
1173         dmu_objset_rele(os, FTAG);
1174         return (error);
1175 }
1176
1177 /*
1178  * Find a zfsvfs_t for a mounted filesystem, or create our own, in which
1179  * case its z_vfs will be NULL, and it will be opened as the owner.
1180  * If 'writer' is set, the z_teardown_lock will be held for RW_WRITER,
1181  * which prevents all vnode ops from running.
1182  */
1183 static int
1184 zfsvfs_hold(const char *name, void *tag, zfsvfs_t **zfvp, boolean_t writer)
1185 {
1186         int error = 0;
1187
1188         if (getzfsvfs(name, zfvp) != 0)
1189                 error = zfsvfs_create(name, zfvp);
1190         if (error == 0) {
1191                 rrw_enter(&(*zfvp)->z_teardown_lock, (writer) ? RW_WRITER :
1192                     RW_READER, tag);
1193                 if ((*zfvp)->z_unmounted) {
1194                         /*
1195                          * XXX we could probably try again, since the unmounting
1196                          * thread should be just about to disassociate the
1197                          * objset from the zfsvfs.
1198                          */
1199                         rrw_exit(&(*zfvp)->z_teardown_lock, tag);
1200                         return (EBUSY);
1201                 }
1202         }
1203         return (error);
1204 }
1205
1206 static void
1207 zfsvfs_rele(zfsvfs_t *zfsvfs, void *tag)
1208 {
1209         rrw_exit(&zfsvfs->z_teardown_lock, tag);
1210
1211         if (zfsvfs->z_vfs) {
1212                 VFS_RELE(zfsvfs->z_vfs);
1213         } else {
1214                 dmu_objset_disown(zfsvfs->z_os, zfsvfs);
1215                 zfsvfs_free(zfsvfs);
1216         }
1217 }
1218
1219 static int
1220 zfs_ioc_pool_create(zfs_cmd_t *zc)
1221 {
1222         int error;
1223         nvlist_t *config, *props = NULL;
1224         nvlist_t *rootprops = NULL;
1225         nvlist_t *zplprops = NULL;
1226         char *buf;
1227
1228         if (error = get_nvlist(zc->zc_nvlist_conf, zc->zc_nvlist_conf_size,
1229             zc->zc_iflags, &config))
1230                 return (error);
1231
1232         if (zc->zc_nvlist_src_size != 0 && (error =
1233             get_nvlist(zc->zc_nvlist_src, zc->zc_nvlist_src_size,
1234             zc->zc_iflags, &props))) {
1235                 nvlist_free(config);
1236                 return (error);
1237         }
1238
1239         if (props) {
1240                 nvlist_t *nvl = NULL;
1241                 uint64_t version = SPA_VERSION;
1242
1243                 (void) nvlist_lookup_uint64(props,
1244                     zpool_prop_to_name(ZPOOL_PROP_VERSION), &version);
1245                 if (!SPA_VERSION_IS_SUPPORTED(version)) {
1246                         error = EINVAL;
1247                         goto pool_props_bad;
1248                 }
1249                 (void) nvlist_lookup_nvlist(props, ZPOOL_ROOTFS_PROPS, &nvl);
1250                 if (nvl) {
1251                         error = nvlist_dup(nvl, &rootprops, KM_SLEEP);
1252                         if (error != 0) {
1253                                 nvlist_free(config);
1254                                 nvlist_free(props);
1255                                 return (error);
1256                         }
1257                         (void) nvlist_remove_all(props, ZPOOL_ROOTFS_PROPS);
1258                 }
1259                 VERIFY(nvlist_alloc(&zplprops, NV_UNIQUE_NAME, KM_SLEEP) == 0);
1260                 error = zfs_fill_zplprops_root(version, rootprops,
1261                     zplprops, NULL);
1262                 if (error)
1263                         goto pool_props_bad;
1264         }
1265
1266         buf = history_str_get(zc);
1267
1268         error = spa_create(zc->zc_name, config, props, buf, zplprops);
1269
1270         /*
1271          * Set the remaining root properties
1272          */
1273         if (!error && (error = zfs_set_prop_nvlist(zc->zc_name,
1274             ZPROP_SRC_LOCAL, rootprops, NULL)) != 0)
1275                 (void) spa_destroy(zc->zc_name);
1276
1277         if (buf != NULL)
1278                 history_str_free(buf);
1279
1280 pool_props_bad:
1281         nvlist_free(rootprops);
1282         nvlist_free(zplprops);
1283         nvlist_free(config);
1284         nvlist_free(props);
1285
1286         return (error);
1287 }
1288
1289 static int
1290 zfs_ioc_pool_destroy(zfs_cmd_t *zc)
1291 {
1292         int error;
1293         zfs_log_history(zc);
1294         error = spa_destroy(zc->zc_name);
1295         if (error == 0)
1296                 zvol_remove_minors(zc->zc_name);
1297         return (error);
1298 }
1299
1300 static int
1301 zfs_ioc_pool_import(zfs_cmd_t *zc)
1302 {
1303         nvlist_t *config, *props = NULL;
1304         uint64_t guid;
1305         int error;
1306
1307         if ((error = get_nvlist(zc->zc_nvlist_conf, zc->zc_nvlist_conf_size,
1308             zc->zc_iflags, &config)) != 0)
1309                 return (error);
1310
1311         if (zc->zc_nvlist_src_size != 0 && (error =
1312             get_nvlist(zc->zc_nvlist_src, zc->zc_nvlist_src_size,
1313             zc->zc_iflags, &props))) {
1314                 nvlist_free(config);
1315                 return (error);
1316         }
1317
1318         if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID, &guid) != 0 ||
1319             guid != zc->zc_guid)
1320                 error = EINVAL;
1321         else
1322                 error = spa_import(zc->zc_name, config, props, zc->zc_cookie);
1323
1324         if (zc->zc_nvlist_dst != 0) {
1325                 int err;
1326
1327                 if ((err = put_nvlist(zc, config)) != 0)
1328                         error = err;
1329         }
1330
1331         nvlist_free(config);
1332
1333         if (props)
1334                 nvlist_free(props);
1335
1336         return (error);
1337 }
1338
1339 static int
1340 zfs_ioc_pool_export(zfs_cmd_t *zc)
1341 {
1342         int error;
1343         boolean_t force = (boolean_t)zc->zc_cookie;
1344         boolean_t hardforce = (boolean_t)zc->zc_guid;
1345
1346         zfs_log_history(zc);
1347         error = spa_export(zc->zc_name, NULL, force, hardforce);
1348         if (error == 0)
1349                 zvol_remove_minors(zc->zc_name);
1350         return (error);
1351 }
1352
1353 static int
1354 zfs_ioc_pool_configs(zfs_cmd_t *zc)
1355 {
1356         nvlist_t *configs;
1357         int error;
1358
1359         if ((configs = spa_all_configs(&zc->zc_cookie)) == NULL)
1360                 return (EEXIST);
1361
1362         error = put_nvlist(zc, configs);
1363
1364         nvlist_free(configs);
1365
1366         return (error);
1367 }
1368
1369 /*
1370  * inputs:
1371  * zc_name              name of the pool
1372  *
1373  * outputs:
1374  * zc_cookie            real errno
1375  * zc_nvlist_dst        config nvlist
1376  * zc_nvlist_dst_size   size of config nvlist
1377  */
1378 static int
1379 zfs_ioc_pool_stats(zfs_cmd_t *zc)
1380 {
1381         nvlist_t *config;
1382         int error;
1383         int ret = 0;
1384
1385         error = spa_get_stats(zc->zc_name, &config, zc->zc_value,
1386             sizeof (zc->zc_value));
1387
1388         if (config != NULL) {
1389                 ret = put_nvlist(zc, config);
1390                 nvlist_free(config);
1391
1392                 /*
1393                  * The config may be present even if 'error' is non-zero.
1394                  * In this case we return success, and preserve the real errno
1395                  * in 'zc_cookie'.
1396                  */
1397                 zc->zc_cookie = error;
1398         } else {
1399                 ret = error;
1400         }
1401
1402         return (ret);
1403 }
1404
1405 /*
1406  * Try to import the given pool, returning pool stats as appropriate so that
1407  * user land knows which devices are available and overall pool health.
1408  */
1409 static int
1410 zfs_ioc_pool_tryimport(zfs_cmd_t *zc)
1411 {
1412         nvlist_t *tryconfig, *config;
1413         int error;
1414
1415         if ((error = get_nvlist(zc->zc_nvlist_conf, zc->zc_nvlist_conf_size,
1416             zc->zc_iflags, &tryconfig)) != 0)
1417                 return (error);
1418
1419         config = spa_tryimport(tryconfig);
1420
1421         nvlist_free(tryconfig);
1422
1423         if (config == NULL)
1424                 return (EINVAL);
1425
1426         error = put_nvlist(zc, config);
1427         nvlist_free(config);
1428
1429         return (error);
1430 }
1431
1432 /*
1433  * inputs:
1434  * zc_name              name of the pool
1435  * zc_cookie            scan func (pool_scan_func_t)
1436  */
1437 static int
1438 zfs_ioc_pool_scan(zfs_cmd_t *zc)
1439 {
1440         spa_t *spa;
1441         int error;
1442
1443         if ((error = spa_open(zc->zc_name, &spa, FTAG)) != 0)
1444                 return (error);
1445
1446         if (zc->zc_cookie == POOL_SCAN_NONE)
1447                 error = spa_scan_stop(spa);
1448         else
1449                 error = spa_scan(spa, zc->zc_cookie);
1450
1451         spa_close(spa, FTAG);
1452
1453         return (error);
1454 }
1455
1456 static int
1457 zfs_ioc_pool_freeze(zfs_cmd_t *zc)
1458 {
1459         spa_t *spa;
1460         int error;
1461
1462         error = spa_open(zc->zc_name, &spa, FTAG);
1463         if (error == 0) {
1464                 spa_freeze(spa);
1465                 spa_close(spa, FTAG);
1466         }
1467         return (error);
1468 }
1469
1470 static int
1471 zfs_ioc_pool_upgrade(zfs_cmd_t *zc)
1472 {
1473         spa_t *spa;
1474         int error;
1475
1476         if ((error = spa_open(zc->zc_name, &spa, FTAG)) != 0)
1477                 return (error);
1478
1479         if (zc->zc_cookie < spa_version(spa) ||
1480             !SPA_VERSION_IS_SUPPORTED(zc->zc_cookie)) {
1481                 spa_close(spa, FTAG);
1482                 return (EINVAL);
1483         }
1484
1485         spa_upgrade(spa, zc->zc_cookie);
1486         spa_close(spa, FTAG);
1487
1488         return (error);
1489 }
1490
1491 static int
1492 zfs_ioc_pool_get_history(zfs_cmd_t *zc)
1493 {
1494         spa_t *spa;
1495         char *hist_buf;
1496         uint64_t size;
1497         int error;
1498
1499         if ((size = zc->zc_history_len) == 0)
1500                 return (EINVAL);
1501
1502         if ((error = spa_open(zc->zc_name, &spa, FTAG)) != 0)
1503                 return (error);
1504
1505         if (spa_version(spa) < SPA_VERSION_ZPOOL_HISTORY) {
1506                 spa_close(spa, FTAG);
1507                 return (ENOTSUP);
1508         }
1509
1510         hist_buf = kmem_alloc(size, KM_SLEEP);
1511         if ((error = spa_history_get(spa, &zc->zc_history_offset,
1512             &zc->zc_history_len, hist_buf)) == 0) {
1513                 error = ddi_copyout(hist_buf,
1514                     (void *)(uintptr_t)zc->zc_history,
1515                     zc->zc_history_len, zc->zc_iflags);
1516         }
1517
1518         spa_close(spa, FTAG);
1519         kmem_free(hist_buf, size);
1520         return (error);
1521 }
1522
1523 static int
1524 zfs_ioc_pool_reguid(zfs_cmd_t *zc)
1525 {
1526         spa_t *spa;
1527         int error;
1528
1529         error = spa_open(zc->zc_name, &spa, FTAG);
1530         if (error == 0) {
1531                 error = spa_change_guid(spa);
1532                 spa_close(spa, FTAG);
1533         }
1534         return (error);
1535 }
1536
1537 static int
1538 zfs_ioc_dsobj_to_dsname(zfs_cmd_t *zc)
1539 {
1540         int error;
1541
1542         if (error = dsl_dsobj_to_dsname(zc->zc_name, zc->zc_obj, zc->zc_value))
1543                 return (error);
1544
1545         return (0);
1546 }
1547
1548 /*
1549  * inputs:
1550  * zc_name              name of filesystem
1551  * zc_obj               object to find
1552  *
1553  * outputs:
1554  * zc_value             name of object
1555  */
1556 static int
1557 zfs_ioc_obj_to_path(zfs_cmd_t *zc)
1558 {
1559         objset_t *os;
1560         int error;
1561
1562         /* XXX reading from objset not owned */
1563         if ((error = dmu_objset_hold(zc->zc_name, FTAG, &os)) != 0)
1564                 return (error);
1565         if (dmu_objset_type(os) != DMU_OST_ZFS) {
1566                 dmu_objset_rele(os, FTAG);
1567                 return (EINVAL);
1568         }
1569         error = zfs_obj_to_path(os, zc->zc_obj, zc->zc_value,
1570             sizeof (zc->zc_value));
1571         dmu_objset_rele(os, FTAG);
1572
1573         return (error);
1574 }
1575
1576 /*
1577  * inputs:
1578  * zc_name              name of filesystem
1579  * zc_obj               object to find
1580  *
1581  * outputs:
1582  * zc_stat              stats on object
1583  * zc_value             path to object
1584  */
1585 static int
1586 zfs_ioc_obj_to_stats(zfs_cmd_t *zc)
1587 {
1588         objset_t *os;
1589         int error;
1590
1591         /* XXX reading from objset not owned */
1592         if ((error = dmu_objset_hold(zc->zc_name, FTAG, &os)) != 0)
1593                 return (error);
1594         if (dmu_objset_type(os) != DMU_OST_ZFS) {
1595                 dmu_objset_rele(os, FTAG);
1596                 return (EINVAL);
1597         }
1598         error = zfs_obj_to_stats(os, zc->zc_obj, &zc->zc_stat, zc->zc_value,
1599             sizeof (zc->zc_value));
1600         dmu_objset_rele(os, FTAG);
1601
1602         return (error);
1603 }
1604
1605 static int
1606 zfs_ioc_vdev_add(zfs_cmd_t *zc)
1607 {
1608         spa_t *spa;
1609         int error;
1610         nvlist_t *config, **l2cache, **spares;
1611         uint_t nl2cache = 0, nspares = 0;
1612
1613         error = spa_open(zc->zc_name, &spa, FTAG);
1614         if (error != 0)
1615                 return (error);
1616
1617         error = get_nvlist(zc->zc_nvlist_conf, zc->zc_nvlist_conf_size,
1618             zc->zc_iflags, &config);
1619         (void) nvlist_lookup_nvlist_array(config, ZPOOL_CONFIG_L2CACHE,
1620             &l2cache, &nl2cache);
1621
1622         (void) nvlist_lookup_nvlist_array(config, ZPOOL_CONFIG_SPARES,
1623             &spares, &nspares);
1624
1625         /*
1626          * A root pool with concatenated devices is not supported.
1627          * Thus, can not add a device to a root pool.
1628          *
1629          * Intent log device can not be added to a rootpool because
1630          * during mountroot, zil is replayed, a seperated log device
1631          * can not be accessed during the mountroot time.
1632          *
1633          * l2cache and spare devices are ok to be added to a rootpool.
1634          */
1635         if (spa_bootfs(spa) != 0 && nl2cache == 0 && nspares == 0) {
1636                 nvlist_free(config);
1637                 spa_close(spa, FTAG);
1638                 return (EDOM);
1639         }
1640
1641         if (error == 0) {
1642                 error = spa_vdev_add(spa, config);
1643                 nvlist_free(config);
1644         }
1645         spa_close(spa, FTAG);
1646         return (error);
1647 }
1648
1649 /*
1650  * inputs:
1651  * zc_name              name of the pool
1652  * zc_nvlist_conf       nvlist of devices to remove
1653  * zc_cookie            to stop the remove?
1654  */
1655 static int
1656 zfs_ioc_vdev_remove(zfs_cmd_t *zc)
1657 {
1658         spa_t *spa;
1659         int error;
1660
1661         error = spa_open(zc->zc_name, &spa, FTAG);
1662         if (error != 0)
1663                 return (error);
1664         error = spa_vdev_remove(spa, zc->zc_guid, B_FALSE);
1665         spa_close(spa, FTAG);
1666         return (error);
1667 }
1668
1669 static int
1670 zfs_ioc_vdev_set_state(zfs_cmd_t *zc)
1671 {
1672         spa_t *spa;
1673         int error;
1674         vdev_state_t newstate = VDEV_STATE_UNKNOWN;
1675
1676         if ((error = spa_open(zc->zc_name, &spa, FTAG)) != 0)
1677                 return (error);
1678         switch (zc->zc_cookie) {
1679         case VDEV_STATE_ONLINE:
1680                 error = vdev_online(spa, zc->zc_guid, zc->zc_obj, &newstate);
1681                 break;
1682
1683         case VDEV_STATE_OFFLINE:
1684                 error = vdev_offline(spa, zc->zc_guid, zc->zc_obj);
1685                 break;
1686
1687         case VDEV_STATE_FAULTED:
1688                 if (zc->zc_obj != VDEV_AUX_ERR_EXCEEDED &&
1689                     zc->zc_obj != VDEV_AUX_EXTERNAL)
1690                         zc->zc_obj = VDEV_AUX_ERR_EXCEEDED;
1691
1692                 error = vdev_fault(spa, zc->zc_guid, zc->zc_obj);
1693                 break;
1694
1695         case VDEV_STATE_DEGRADED:
1696                 if (zc->zc_obj != VDEV_AUX_ERR_EXCEEDED &&
1697                     zc->zc_obj != VDEV_AUX_EXTERNAL)
1698                         zc->zc_obj = VDEV_AUX_ERR_EXCEEDED;
1699
1700                 error = vdev_degrade(spa, zc->zc_guid, zc->zc_obj);
1701                 break;
1702
1703         default:
1704                 error = EINVAL;
1705         }
1706         zc->zc_cookie = newstate;
1707         spa_close(spa, FTAG);
1708         return (error);
1709 }
1710
1711 static int
1712 zfs_ioc_vdev_attach(zfs_cmd_t *zc)
1713 {
1714         spa_t *spa;
1715         int replacing = zc->zc_cookie;
1716         nvlist_t *config;
1717         int error;
1718
1719         if ((error = spa_open(zc->zc_name, &spa, FTAG)) != 0)
1720                 return (error);
1721
1722         if ((error = get_nvlist(zc->zc_nvlist_conf, zc->zc_nvlist_conf_size,
1723             zc->zc_iflags, &config)) == 0) {
1724                 error = spa_vdev_attach(spa, zc->zc_guid, config, replacing);
1725                 nvlist_free(config);
1726         }
1727
1728         spa_close(spa, FTAG);
1729         return (error);
1730 }
1731
1732 static int
1733 zfs_ioc_vdev_detach(zfs_cmd_t *zc)
1734 {
1735         spa_t *spa;
1736         int error;
1737
1738         if ((error = spa_open(zc->zc_name, &spa, FTAG)) != 0)
1739                 return (error);
1740
1741         error = spa_vdev_detach(spa, zc->zc_guid, 0, B_FALSE);
1742
1743         spa_close(spa, FTAG);
1744         return (error);
1745 }
1746
1747 static int
1748 zfs_ioc_vdev_split(zfs_cmd_t *zc)
1749 {
1750         spa_t *spa;
1751         nvlist_t *config, *props = NULL;
1752         int error;
1753         boolean_t exp = !!(zc->zc_cookie & ZPOOL_EXPORT_AFTER_SPLIT);
1754
1755         if ((error = spa_open(zc->zc_name, &spa, FTAG)) != 0)
1756                 return (error);
1757
1758         if (error = get_nvlist(zc->zc_nvlist_conf, zc->zc_nvlist_conf_size,
1759             zc->zc_iflags, &config)) {
1760                 spa_close(spa, FTAG);
1761                 return (error);
1762         }
1763
1764         if (zc->zc_nvlist_src_size != 0 && (error =
1765             get_nvlist(zc->zc_nvlist_src, zc->zc_nvlist_src_size,
1766             zc->zc_iflags, &props))) {
1767                 spa_close(spa, FTAG);
1768                 nvlist_free(config);
1769                 return (error);
1770         }
1771
1772         error = spa_vdev_split_mirror(spa, zc->zc_string, config, props, exp);
1773
1774         spa_close(spa, FTAG);
1775
1776         nvlist_free(config);
1777         nvlist_free(props);
1778
1779         return (error);
1780 }
1781
1782 static int
1783 zfs_ioc_vdev_setpath(zfs_cmd_t *zc)
1784 {
1785         spa_t *spa;
1786         char *path = zc->zc_value;
1787         uint64_t guid = zc->zc_guid;
1788         int error;
1789
1790         error = spa_open(zc->zc_name, &spa, FTAG);
1791         if (error != 0)
1792                 return (error);
1793
1794         error = spa_vdev_setpath(spa, guid, path);
1795         spa_close(spa, FTAG);
1796         return (error);
1797 }
1798
1799 static int
1800 zfs_ioc_vdev_setfru(zfs_cmd_t *zc)
1801 {
1802         spa_t *spa;
1803         char *fru = zc->zc_value;
1804         uint64_t guid = zc->zc_guid;
1805         int error;
1806
1807         error = spa_open(zc->zc_name, &spa, FTAG);
1808         if (error != 0)
1809                 return (error);
1810
1811         error = spa_vdev_setfru(spa, guid, fru);
1812         spa_close(spa, FTAG);
1813         return (error);
1814 }
1815
1816 static int
1817 zfs_ioc_objset_stats_impl(zfs_cmd_t *zc, objset_t *os)
1818 {
1819         int error = 0;
1820         nvlist_t *nv;
1821
1822         dmu_objset_fast_stat(os, &zc->zc_objset_stats);
1823
1824         if (zc->zc_nvlist_dst != 0 &&
1825             (error = dsl_prop_get_all(os, &nv)) == 0) {
1826                 dmu_objset_stats(os, nv);
1827                 /*
1828                  * NB: zvol_get_stats() will read the objset contents,
1829                  * which we aren't supposed to do with a
1830                  * DS_MODE_USER hold, because it could be
1831                  * inconsistent.  So this is a bit of a workaround...
1832                  * XXX reading with out owning
1833                  */
1834                 if (!zc->zc_objset_stats.dds_inconsistent &&
1835                     dmu_objset_type(os) == DMU_OST_ZVOL) {
1836                         error = zvol_get_stats(os, nv);
1837                         if (error == EIO)
1838                                 return (error);
1839                         VERIFY0(error);
1840                 }
1841                 error = put_nvlist(zc, nv);
1842                 nvlist_free(nv);
1843         }
1844
1845         return (error);
1846 }
1847
1848 /*
1849  * inputs:
1850  * zc_name              name of filesystem
1851  * zc_nvlist_dst_size   size of buffer for property nvlist
1852  *
1853  * outputs:
1854  * zc_objset_stats      stats
1855  * zc_nvlist_dst        property nvlist
1856  * zc_nvlist_dst_size   size of property nvlist
1857  */
1858 static int
1859 zfs_ioc_objset_stats(zfs_cmd_t *zc)
1860 {
1861         objset_t *os = NULL;
1862         int error;
1863
1864         if (error = dmu_objset_hold(zc->zc_name, FTAG, &os))
1865                 return (error);
1866
1867         error = zfs_ioc_objset_stats_impl(zc, os);
1868
1869         dmu_objset_rele(os, FTAG);
1870
1871         if (error == ENOMEM)
1872                 error = 0;
1873         return (error);
1874 }
1875
1876 /*
1877  * inputs:
1878  * zc_name              name of filesystem
1879  * zc_nvlist_dst_size   size of buffer for property nvlist
1880  *
1881  * outputs:
1882  * zc_nvlist_dst        received property nvlist
1883  * zc_nvlist_dst_size   size of received property nvlist
1884  *
1885  * Gets received properties (distinct from local properties on or after
1886  * SPA_VERSION_RECVD_PROPS) for callers who want to differentiate received from
1887  * local property values.
1888  */
1889 static int
1890 zfs_ioc_objset_recvd_props(zfs_cmd_t *zc)
1891 {
1892         objset_t *os = NULL;
1893         int error;
1894         nvlist_t *nv;
1895
1896         if (error = dmu_objset_hold(zc->zc_name, FTAG, &os))
1897                 return (error);
1898
1899         /*
1900          * Without this check, we would return local property values if the
1901          * caller has not already received properties on or after
1902          * SPA_VERSION_RECVD_PROPS.
1903          */
1904         if (!dsl_prop_get_hasrecvd(os)) {
1905                 dmu_objset_rele(os, FTAG);
1906                 return (ENOTSUP);
1907         }
1908
1909         if (zc->zc_nvlist_dst != 0 &&
1910             (error = dsl_prop_get_received(os, &nv)) == 0) {
1911                 error = put_nvlist(zc, nv);
1912                 nvlist_free(nv);
1913         }
1914
1915         dmu_objset_rele(os, FTAG);
1916         return (error);
1917 }
1918
1919 static int
1920 nvl_add_zplprop(objset_t *os, nvlist_t *props, zfs_prop_t prop)
1921 {
1922         uint64_t value;
1923         int error;
1924
1925         /*
1926          * zfs_get_zplprop() will either find a value or give us
1927          * the default value (if there is one).
1928          */
1929         if ((error = zfs_get_zplprop(os, prop, &value)) != 0)
1930                 return (error);
1931         VERIFY(nvlist_add_uint64(props, zfs_prop_to_name(prop), value) == 0);
1932         return (0);
1933 }
1934
1935 /*
1936  * inputs:
1937  * zc_name              name of filesystem
1938  * zc_nvlist_dst_size   size of buffer for zpl property nvlist
1939  *
1940  * outputs:
1941  * zc_nvlist_dst        zpl property nvlist
1942  * zc_nvlist_dst_size   size of zpl property nvlist
1943  */
1944 static int
1945 zfs_ioc_objset_zplprops(zfs_cmd_t *zc)
1946 {
1947         objset_t *os;
1948         int err;
1949
1950         /* XXX reading without owning */
1951         if (err = dmu_objset_hold(zc->zc_name, FTAG, &os))
1952                 return (err);
1953
1954         dmu_objset_fast_stat(os, &zc->zc_objset_stats);
1955
1956         /*
1957          * NB: nvl_add_zplprop() will read the objset contents,
1958          * which we aren't supposed to do with a DS_MODE_USER
1959          * hold, because it could be inconsistent.
1960          */
1961         if (zc->zc_nvlist_dst != 0 &&
1962             !zc->zc_objset_stats.dds_inconsistent &&
1963             dmu_objset_type(os) == DMU_OST_ZFS) {
1964                 nvlist_t *nv;
1965
1966                 VERIFY(nvlist_alloc(&nv, NV_UNIQUE_NAME, KM_SLEEP) == 0);
1967                 if ((err = nvl_add_zplprop(os, nv, ZFS_PROP_VERSION)) == 0 &&
1968                     (err = nvl_add_zplprop(os, nv, ZFS_PROP_NORMALIZE)) == 0 &&
1969                     (err = nvl_add_zplprop(os, nv, ZFS_PROP_UTF8ONLY)) == 0 &&
1970                     (err = nvl_add_zplprop(os, nv, ZFS_PROP_CASE)) == 0)
1971                         err = put_nvlist(zc, nv);
1972                 nvlist_free(nv);
1973         } else {
1974                 err = ENOENT;
1975         }
1976         dmu_objset_rele(os, FTAG);
1977         return (err);
1978 }
1979
1980 boolean_t
1981 dataset_name_hidden(const char *name)
1982 {
1983         /*
1984          * Skip over datasets that are not visible in this zone,
1985          * internal datasets (which have a $ in their name), and
1986          * temporary datasets (which have a % in their name).
1987          */
1988         if (strchr(name, '$') != NULL)
1989                 return (B_TRUE);
1990         if (strchr(name, '%') != NULL)
1991                 return (B_TRUE);
1992         if (!INGLOBALZONE(curthread) && !zone_dataset_visible(name, NULL))
1993                 return (B_TRUE);
1994         return (B_FALSE);
1995 }
1996
1997 /*
1998  * inputs:
1999  * zc_name              name of filesystem
2000  * zc_cookie            zap cursor
2001  * zc_nvlist_dst_size   size of buffer for property nvlist
2002  *
2003  * outputs:
2004  * zc_name              name of next filesystem
2005  * zc_cookie            zap cursor
2006  * zc_objset_stats      stats
2007  * zc_nvlist_dst        property nvlist
2008  * zc_nvlist_dst_size   size of property nvlist
2009  */
2010 static int
2011 zfs_ioc_dataset_list_next(zfs_cmd_t *zc)
2012 {
2013         objset_t *os;
2014         int error;
2015         char *p;
2016         size_t orig_len = strlen(zc->zc_name);
2017
2018 top:
2019         if (error = dmu_objset_hold(zc->zc_name, FTAG, &os)) {
2020                 if (error == ENOENT)
2021                         error = ESRCH;
2022                 return (error);
2023         }
2024
2025         p = strrchr(zc->zc_name, '/');
2026         if (p == NULL || p[1] != '\0')
2027                 (void) strlcat(zc->zc_name, "/", sizeof (zc->zc_name));
2028         p = zc->zc_name + strlen(zc->zc_name);
2029
2030         /*
2031          * Pre-fetch the datasets.  dmu_objset_prefetch() always returns 0
2032          * but is not declared void because its called by dmu_objset_find().
2033          */
2034         if (zc->zc_cookie == 0) {
2035                 uint64_t cookie = 0;
2036                 int len = sizeof (zc->zc_name) - (p - zc->zc_name);
2037
2038                 while (dmu_dir_list_next(os, len, p, NULL, &cookie) == 0) {
2039                         if (!dataset_name_hidden(zc->zc_name))
2040                                 (void) dmu_objset_prefetch(zc->zc_name, NULL);
2041                 }
2042         }
2043
2044         do {
2045                 error = dmu_dir_list_next(os,
2046                     sizeof (zc->zc_name) - (p - zc->zc_name), p,
2047                     NULL, &zc->zc_cookie);
2048                 if (error == ENOENT)
2049                         error = ESRCH;
2050         } while (error == 0 && dataset_name_hidden(zc->zc_name));
2051         dmu_objset_rele(os, FTAG);
2052
2053         /*
2054          * If it's an internal dataset (ie. with a '$' in its name),
2055          * don't try to get stats for it, otherwise we'll return ENOENT.
2056          */
2057         if (error == 0 && strchr(zc->zc_name, '$') == NULL) {
2058                 error = zfs_ioc_objset_stats(zc); /* fill in the stats */
2059                 if (error == ENOENT) {
2060                         /* We lost a race with destroy, get the next one. */
2061                         zc->zc_name[orig_len] = '\0';
2062                         goto top;
2063                 }
2064         }
2065         return (error);
2066 }
2067
2068 /*
2069  * inputs:
2070  * zc_name              name of filesystem
2071  * zc_cookie            zap cursor
2072  * zc_nvlist_dst_size   size of buffer for property nvlist
2073  * zc_simple            when set, only name is requested
2074  *
2075  * outputs:
2076  * zc_name              name of next snapshot
2077  * zc_objset_stats      stats
2078  * zc_nvlist_dst        property nvlist
2079  * zc_nvlist_dst_size   size of property nvlist
2080  */
2081 static int
2082 zfs_ioc_snapshot_list_next(zfs_cmd_t *zc)
2083 {
2084         objset_t *os;
2085         int error;
2086
2087 top:
2088         if (snapshot_list_prefetch && zc->zc_cookie == 0 && !zc->zc_simple)
2089                 (void) dmu_objset_find(zc->zc_name, dmu_objset_prefetch,
2090                     NULL, DS_FIND_SNAPSHOTS);
2091
2092         error = dmu_objset_hold(zc->zc_name, FTAG, &os);
2093         if (error)
2094                 return (error == ENOENT ? ESRCH : error);
2095
2096         /*
2097          * A dataset name of maximum length cannot have any snapshots,
2098          * so exit immediately.
2099          */
2100         if (strlcat(zc->zc_name, "@", sizeof (zc->zc_name)) >= MAXNAMELEN) {
2101                 dmu_objset_rele(os, FTAG);
2102                 return (ESRCH);
2103         }
2104
2105         error = dmu_snapshot_list_next(os,
2106             sizeof (zc->zc_name) - strlen(zc->zc_name),
2107             zc->zc_name + strlen(zc->zc_name), &zc->zc_obj, &zc->zc_cookie,
2108             NULL);
2109
2110         if (error == 0 && !zc->zc_simple) {
2111                 dsl_dataset_t *ds;
2112                 dsl_pool_t *dp = os->os_dsl_dataset->ds_dir->dd_pool;
2113
2114                 /*
2115                  * Since we probably don't have a hold on this snapshot,
2116                  * it's possible that the objsetid could have been destroyed
2117                  * and reused for a new objset. It's OK if this happens during
2118                  * a zfs send operation, since the new createtxg will be
2119                  * beyond the range we're interested in.
2120                  */
2121                 rw_enter(&dp->dp_config_rwlock, RW_READER);
2122                 error = dsl_dataset_hold_obj(dp, zc->zc_obj, FTAG, &ds);
2123                 rw_exit(&dp->dp_config_rwlock);
2124                 if (error) {
2125                         if (error == ENOENT) {
2126                                 /* Racing with destroy, get the next one. */
2127                                 *strchr(zc->zc_name, '@') = '\0';
2128                                 dmu_objset_rele(os, FTAG);
2129                                 goto top;
2130                         }
2131                 } else {
2132                         objset_t *ossnap;
2133
2134                         error = dmu_objset_from_ds(ds, &ossnap);
2135                         if (error == 0)
2136                                 error = zfs_ioc_objset_stats_impl(zc, ossnap);
2137                         dsl_dataset_rele(ds, FTAG);
2138                 }
2139         } else if (error == ENOENT) {
2140                 error = ESRCH;
2141         }
2142
2143         dmu_objset_rele(os, FTAG);
2144         /* if we failed, undo the @ that we tacked on to zc_name */
2145         if (error)
2146                 *strchr(zc->zc_name, '@') = '\0';
2147         return (error);
2148 }
2149
2150 static int
2151 zfs_prop_set_userquota(const char *dsname, nvpair_t *pair)
2152 {
2153         const char *propname = nvpair_name(pair);
2154         uint64_t *valary;
2155         unsigned int vallen;
2156         const char *domain;
2157         char *dash;
2158         zfs_userquota_prop_t type;
2159         uint64_t rid;
2160         uint64_t quota;
2161         zfsvfs_t *zfsvfs;
2162         int err;
2163
2164         if (nvpair_type(pair) == DATA_TYPE_NVLIST) {
2165                 nvlist_t *attrs;
2166                 VERIFY(nvpair_value_nvlist(pair, &attrs) == 0);
2167                 if (nvlist_lookup_nvpair(attrs, ZPROP_VALUE,
2168                     &pair) != 0)
2169                         return (EINVAL);
2170         }
2171
2172         /*
2173          * A correctly constructed propname is encoded as
2174          * userquota@<rid>-<domain>.
2175          */
2176         if ((dash = strchr(propname, '-')) == NULL ||
2177             nvpair_value_uint64_array(pair, &valary, &vallen) != 0 ||
2178             vallen != 3)
2179                 return (EINVAL);
2180
2181         domain = dash + 1;
2182         type = valary[0];
2183         rid = valary[1];
2184         quota = valary[2];
2185
2186         err = zfsvfs_hold(dsname, FTAG, &zfsvfs, B_FALSE);
2187         if (err == 0) {
2188                 err = zfs_set_userquota(zfsvfs, type, domain, rid, quota);
2189                 zfsvfs_rele(zfsvfs, FTAG);
2190         }
2191
2192         return (err);
2193 }
2194
2195 /*
2196  * If the named property is one that has a special function to set its value,
2197  * return 0 on success and a positive error code on failure; otherwise if it is
2198  * not one of the special properties handled by this function, return -1.
2199  *
2200  * XXX: It would be better for callers of the property interface if we handled
2201  * these special cases in dsl_prop.c (in the dsl layer).
2202  */
2203 static int
2204 zfs_prop_set_special(const char *dsname, zprop_source_t source,
2205     nvpair_t *pair)
2206 {
2207         const char *propname = nvpair_name(pair);
2208         zfs_prop_t prop = zfs_name_to_prop(propname);
2209         uint64_t intval;
2210         int err;
2211
2212         if (prop == ZPROP_INVAL) {
2213                 if (zfs_prop_userquota(propname))
2214                         return (zfs_prop_set_userquota(dsname, pair));
2215                 return (-1);
2216         }
2217
2218         if (nvpair_type(pair) == DATA_TYPE_NVLIST) {
2219                 nvlist_t *attrs;
2220                 VERIFY(nvpair_value_nvlist(pair, &attrs) == 0);
2221                 VERIFY(nvlist_lookup_nvpair(attrs, ZPROP_VALUE,
2222                     &pair) == 0);
2223         }
2224
2225         if (zfs_prop_get_type(prop) == PROP_TYPE_STRING)
2226                 return (-1);
2227
2228         VERIFY(0 == nvpair_value_uint64(pair, &intval));
2229
2230         switch (prop) {
2231         case ZFS_PROP_QUOTA:
2232                 err = dsl_dir_set_quota(dsname, source, intval);
2233                 break;
2234         case ZFS_PROP_REFQUOTA:
2235                 err = dsl_dataset_set_quota(dsname, source, intval);
2236                 break;
2237         case ZFS_PROP_RESERVATION:
2238                 err = dsl_dir_set_reservation(dsname, source, intval);
2239                 break;
2240         case ZFS_PROP_REFRESERVATION:
2241                 err = dsl_dataset_set_reservation(dsname, source, intval);
2242                 break;
2243         case ZFS_PROP_VOLSIZE:
2244                 err = zvol_set_volsize(dsname, ddi_driver_major(zfs_dip),
2245                     intval);
2246                 break;
2247         case ZFS_PROP_VERSION:
2248         {
2249                 zfsvfs_t *zfsvfs;
2250
2251                 if ((err = zfsvfs_hold(dsname, FTAG, &zfsvfs, B_TRUE)) != 0)
2252                         break;
2253
2254                 err = zfs_set_version(zfsvfs, intval);
2255                 zfsvfs_rele(zfsvfs, FTAG);
2256
2257                 if (err == 0 && intval >= ZPL_VERSION_USERSPACE) {
2258                         zfs_cmd_t *zc;
2259
2260                         zc = kmem_zalloc(sizeof (zfs_cmd_t), KM_SLEEP);
2261                         (void) strcpy(zc->zc_name, dsname);
2262                         (void) zfs_ioc_userspace_upgrade(zc);
2263                         kmem_free(zc, sizeof (zfs_cmd_t));
2264                 }
2265                 break;
2266         }
2267
2268         default:
2269                 err = -1;
2270         }
2271
2272         return (err);
2273 }
2274
2275 /*
2276  * This function is best effort. If it fails to set any of the given properties,
2277  * it continues to set as many as it can and returns the first error
2278  * encountered. If the caller provides a non-NULL errlist, it also gives the
2279  * complete list of names of all the properties it failed to set along with the
2280  * corresponding error numbers. The caller is responsible for freeing the
2281  * returned errlist.
2282  *
2283  * If every property is set successfully, zero is returned and the list pointed
2284  * at by errlist is NULL.
2285  */
2286 int
2287 zfs_set_prop_nvlist(const char *dsname, zprop_source_t source, nvlist_t *nvl,
2288     nvlist_t **errlist)
2289 {
2290         nvpair_t *pair;
2291         nvpair_t *propval;
2292         int rv = 0;
2293         uint64_t intval;
2294         char *strval;
2295         nvlist_t *genericnvl;
2296         nvlist_t *errors;
2297         nvlist_t *retrynvl;
2298
2299         VERIFY(nvlist_alloc(&genericnvl, NV_UNIQUE_NAME, KM_SLEEP) == 0);
2300         VERIFY(nvlist_alloc(&errors, NV_UNIQUE_NAME, KM_SLEEP) == 0);
2301         VERIFY(nvlist_alloc(&retrynvl, NV_UNIQUE_NAME, KM_SLEEP) == 0);
2302
2303 retry:
2304         pair = NULL;
2305         while ((pair = nvlist_next_nvpair(nvl, pair)) != NULL) {
2306                 const char *propname = nvpair_name(pair);
2307                 zfs_prop_t prop = zfs_name_to_prop(propname);
2308                 int err = 0;
2309
2310                 /* decode the property value */
2311                 propval = pair;
2312                 if (nvpair_type(pair) == DATA_TYPE_NVLIST) {
2313                         nvlist_t *attrs;
2314                         VERIFY(nvpair_value_nvlist(pair, &attrs) == 0);
2315                         if (nvlist_lookup_nvpair(attrs, ZPROP_VALUE,
2316                             &propval) != 0)
2317                                 err = EINVAL;
2318                 }
2319
2320                 /* Validate value type */
2321                 if (err == 0 && prop == ZPROP_INVAL) {
2322                         if (zfs_prop_user(propname)) {
2323                                 if (nvpair_type(propval) != DATA_TYPE_STRING)
2324                                         err = EINVAL;
2325                         } else if (zfs_prop_userquota(propname)) {
2326                                 if (nvpair_type(propval) !=
2327                                     DATA_TYPE_UINT64_ARRAY)
2328                                         err = EINVAL;
2329                         } else {
2330                                 err = EINVAL;
2331                         }
2332                 } else if (err == 0) {
2333                         if (nvpair_type(propval) == DATA_TYPE_STRING) {
2334                                 if (zfs_prop_get_type(prop) != PROP_TYPE_STRING)
2335                                         err = EINVAL;
2336                         } else if (nvpair_type(propval) == DATA_TYPE_UINT64) {
2337                                 const char *unused;
2338
2339                                 VERIFY(nvpair_value_uint64(propval,
2340                                     &intval) == 0);
2341
2342                                 switch (zfs_prop_get_type(prop)) {
2343                                 case PROP_TYPE_NUMBER:
2344                                         break;
2345                                 case PROP_TYPE_STRING:
2346                                         err = EINVAL;
2347                                         break;
2348                                 case PROP_TYPE_INDEX:
2349                                         if (zfs_prop_index_to_string(prop,
2350                                             intval, &unused) != 0)
2351                                                 err = EINVAL;
2352                                         break;
2353                                 default:
2354                                         cmn_err(CE_PANIC,
2355                                             "unknown property type");
2356                                 }
2357                         } else {
2358                                 err = EINVAL;
2359                         }
2360                 }
2361
2362                 /* Validate permissions */
2363                 if (err == 0)
2364                         err = zfs_check_settable(dsname, pair, CRED());
2365
2366                 if (err == 0) {
2367                         err = zfs_prop_set_special(dsname, source, pair);
2368                         if (err == -1) {
2369                                 /*
2370                                  * For better performance we build up a list of
2371                                  * properties to set in a single transaction.
2372                                  */
2373                                 err = nvlist_add_nvpair(genericnvl, pair);
2374                         } else if (err != 0 && nvl != retrynvl) {
2375                                 /*
2376                                  * This may be a spurious error caused by
2377                                  * receiving quota and reservation out of order.
2378                                  * Try again in a second pass.
2379                                  */
2380                                 err = nvlist_add_nvpair(retrynvl, pair);
2381                         }
2382                 }
2383
2384                 if (err != 0)
2385                         VERIFY(nvlist_add_int32(errors, propname, err) == 0);
2386         }
2387
2388         if (nvl != retrynvl && !nvlist_empty(retrynvl)) {
2389                 nvl = retrynvl;
2390                 goto retry;
2391         }
2392
2393         if (!nvlist_empty(genericnvl) &&
2394             dsl_props_set(dsname, source, genericnvl) != 0) {
2395                 /*
2396                  * If this fails, we still want to set as many properties as we
2397                  * can, so try setting them individually.
2398                  */
2399                 pair = NULL;
2400                 while ((pair = nvlist_next_nvpair(genericnvl, pair)) != NULL) {
2401                         const char *propname = nvpair_name(pair);
2402                         int err = 0;
2403
2404                         propval = pair;
2405                         if (nvpair_type(pair) == DATA_TYPE_NVLIST) {
2406                                 nvlist_t *attrs;
2407                                 VERIFY(nvpair_value_nvlist(pair, &attrs) == 0);
2408                                 VERIFY(nvlist_lookup_nvpair(attrs, ZPROP_VALUE,
2409                                     &propval) == 0);
2410                         }
2411
2412                         if (nvpair_type(propval) == DATA_TYPE_STRING) {
2413                                 VERIFY(nvpair_value_string(propval,
2414                                     &strval) == 0);
2415                                 err = dsl_prop_set(dsname, propname, source, 1,
2416                                     strlen(strval) + 1, strval);
2417                         } else {
2418                                 VERIFY(nvpair_value_uint64(propval,
2419                                     &intval) == 0);
2420                                 err = dsl_prop_set(dsname, propname, source, 8,
2421                                     1, &intval);
2422                         }
2423
2424                         if (err != 0) {
2425                                 VERIFY(nvlist_add_int32(errors, propname,
2426                                     err) == 0);
2427                         }
2428                 }
2429         }
2430         nvlist_free(genericnvl);
2431         nvlist_free(retrynvl);
2432
2433         if ((pair = nvlist_next_nvpair(errors, NULL)) == NULL) {
2434                 nvlist_free(errors);
2435                 errors = NULL;
2436         } else {
2437                 VERIFY(nvpair_value_int32(pair, &rv) == 0);
2438         }
2439
2440         if (errlist == NULL)
2441                 nvlist_free(errors);
2442         else
2443                 *errlist = errors;
2444
2445         return (rv);
2446 }
2447
2448 /*
2449  * Check that all the properties are valid user properties.
2450  */
2451 static int
2452 zfs_check_userprops(char *fsname, nvlist_t *nvl)
2453 {
2454         nvpair_t *pair = NULL;
2455         int error = 0;
2456
2457         while ((pair = nvlist_next_nvpair(nvl, pair)) != NULL) {
2458                 const char *propname = nvpair_name(pair);
2459                 char *valstr;
2460
2461                 if (!zfs_prop_user(propname) ||
2462                     nvpair_type(pair) != DATA_TYPE_STRING)
2463                         return (EINVAL);
2464
2465                 if (error = zfs_secpolicy_write_perms(fsname,
2466                     ZFS_DELEG_PERM_USERPROP, CRED()))
2467                         return (error);
2468
2469                 if (strlen(propname) >= ZAP_MAXNAMELEN)
2470                         return (ENAMETOOLONG);
2471
2472                 VERIFY(nvpair_value_string(pair, &valstr) == 0);
2473                 if (strlen(valstr) >= ZAP_MAXVALUELEN)
2474                         return (E2BIG);
2475         }
2476         return (0);
2477 }
2478
2479 static void
2480 props_skip(nvlist_t *props, nvlist_t *skipped, nvlist_t **newprops)
2481 {
2482         nvpair_t *pair;
2483
2484         VERIFY(nvlist_alloc(newprops, NV_UNIQUE_NAME, KM_SLEEP) == 0);
2485
2486         pair = NULL;
2487         while ((pair = nvlist_next_nvpair(props, pair)) != NULL) {
2488                 if (nvlist_exists(skipped, nvpair_name(pair)))
2489                         continue;
2490
2491                 VERIFY(nvlist_add_nvpair(*newprops, pair) == 0);
2492         }
2493 }
2494
2495 static int
2496 clear_received_props(objset_t *os, const char *fs, nvlist_t *props,
2497     nvlist_t *skipped)
2498 {
2499         int err = 0;
2500         nvlist_t *cleared_props = NULL;
2501         props_skip(props, skipped, &cleared_props);
2502         if (!nvlist_empty(cleared_props)) {
2503                 /*
2504                  * Acts on local properties until the dataset has received
2505                  * properties at least once on or after SPA_VERSION_RECVD_PROPS.
2506                  */
2507                 zprop_source_t flags = (ZPROP_SRC_NONE |
2508                     (dsl_prop_get_hasrecvd(os) ? ZPROP_SRC_RECEIVED : 0));
2509                 err = zfs_set_prop_nvlist(fs, flags, cleared_props, NULL);
2510         }
2511         nvlist_free(cleared_props);
2512         return (err);
2513 }
2514
2515 /*
2516  * inputs:
2517  * zc_name              name of filesystem
2518  * zc_value             name of property to set
2519  * zc_nvlist_src{_size} nvlist of properties to apply
2520  * zc_cookie            received properties flag
2521  *
2522  * outputs:
2523  * zc_nvlist_dst{_size} error for each unapplied received property
2524  */
2525 static int
2526 zfs_ioc_set_prop(zfs_cmd_t *zc)
2527 {
2528         nvlist_t *nvl;
2529         boolean_t received = zc->zc_cookie;
2530         zprop_source_t source = (received ? ZPROP_SRC_RECEIVED :
2531             ZPROP_SRC_LOCAL);
2532         nvlist_t *errors = NULL;
2533         int error;
2534
2535         if ((error = get_nvlist(zc->zc_nvlist_src, zc->zc_nvlist_src_size,
2536             zc->zc_iflags, &nvl)) != 0)
2537                 return (error);
2538
2539         if (received) {
2540                 nvlist_t *origprops;
2541                 objset_t *os;
2542
2543                 if (dmu_objset_hold(zc->zc_name, FTAG, &os) == 0) {
2544                         if (dsl_prop_get_received(os, &origprops) == 0) {
2545                                 (void) clear_received_props(os,
2546                                     zc->zc_name, origprops, nvl);
2547                                 nvlist_free(origprops);
2548                         }
2549
2550                         dsl_prop_set_hasrecvd(os);
2551                         dmu_objset_rele(os, FTAG);
2552                 }
2553         }
2554
2555         error = zfs_set_prop_nvlist(zc->zc_name, source, nvl, &errors);
2556
2557         if (zc->zc_nvlist_dst != 0 && errors != NULL) {
2558                 (void) put_nvlist(zc, errors);
2559         }
2560
2561         nvlist_free(errors);
2562         nvlist_free(nvl);
2563         return (error);
2564 }
2565
2566 /*
2567  * inputs:
2568  * zc_name              name of filesystem
2569  * zc_value             name of property to inherit
2570  * zc_cookie            revert to received value if TRUE
2571  *
2572  * outputs:             none
2573  */
2574 static int
2575 zfs_ioc_inherit_prop(zfs_cmd_t *zc)
2576 {
2577         const char *propname = zc->zc_value;
2578         zfs_prop_t prop = zfs_name_to_prop(propname);
2579         boolean_t received = zc->zc_cookie;
2580         zprop_source_t source = (received
2581             ? ZPROP_SRC_NONE            /* revert to received value, if any */
2582             : ZPROP_SRC_INHERITED);     /* explicitly inherit */
2583
2584         if (received) {
2585                 nvlist_t *dummy;
2586                 nvpair_t *pair;
2587                 zprop_type_t type;
2588                 int err;
2589
2590                 /*
2591                  * zfs_prop_set_special() expects properties in the form of an
2592                  * nvpair with type info.
2593                  */
2594                 if (prop == ZPROP_INVAL) {
2595                         if (!zfs_prop_user(propname))
2596                                 return (EINVAL);
2597
2598                         type = PROP_TYPE_STRING;
2599                 } else if (prop == ZFS_PROP_VOLSIZE ||
2600                     prop == ZFS_PROP_VERSION) {
2601                         return (EINVAL);
2602                 } else {
2603                         type = zfs_prop_get_type(prop);
2604                 }
2605
2606                 VERIFY(nvlist_alloc(&dummy, NV_UNIQUE_NAME, KM_SLEEP) == 0);
2607
2608                 switch (type) {
2609                 case PROP_TYPE_STRING:
2610                         VERIFY(0 == nvlist_add_string(dummy, propname, ""));
2611                         break;
2612                 case PROP_TYPE_NUMBER:
2613                 case PROP_TYPE_INDEX:
2614                         VERIFY(0 == nvlist_add_uint64(dummy, propname, 0));
2615                         break;
2616                 default:
2617                         nvlist_free(dummy);
2618                         return (EINVAL);
2619                 }
2620
2621                 pair = nvlist_next_nvpair(dummy, NULL);
2622                 err = zfs_prop_set_special(zc->zc_name, source, pair);
2623                 nvlist_free(dummy);
2624                 if (err != -1)
2625                         return (err); /* special property already handled */
2626         } else {
2627                 /*
2628                  * Only check this in the non-received case. We want to allow
2629                  * 'inherit -S' to revert non-inheritable properties like quota
2630                  * and reservation to the received or default values even though
2631                  * they are not considered inheritable.
2632                  */
2633                 if (prop != ZPROP_INVAL && !zfs_prop_inheritable(prop))
2634                         return (EINVAL);
2635         }
2636
2637         /* the property name has been validated by zfs_secpolicy_inherit() */
2638         return (dsl_prop_set(zc->zc_name, zc->zc_value, source, 0, 0, NULL));
2639 }
2640
2641 static int
2642 zfs_ioc_pool_set_props(zfs_cmd_t *zc)
2643 {
2644         nvlist_t *props;
2645         spa_t *spa;
2646         int error;
2647         nvpair_t *pair;
2648
2649         if (error = get_nvlist(zc->zc_nvlist_src, zc->zc_nvlist_src_size,
2650             zc->zc_iflags, &props))
2651                 return (error);
2652
2653         /*
2654          * If the only property is the configfile, then just do a spa_lookup()
2655          * to handle the faulted case.
2656          */
2657         pair = nvlist_next_nvpair(props, NULL);
2658         if (pair != NULL && strcmp(nvpair_name(pair),
2659             zpool_prop_to_name(ZPOOL_PROP_CACHEFILE)) == 0 &&
2660             nvlist_next_nvpair(props, pair) == NULL) {
2661                 mutex_enter(&spa_namespace_lock);
2662                 if ((spa = spa_lookup(zc->zc_name)) != NULL) {
2663                         spa_configfile_set(spa, props, B_FALSE);
2664                         spa_config_sync(spa, B_FALSE, B_TRUE);
2665                 }
2666                 mutex_exit(&spa_namespace_lock);
2667                 if (spa != NULL) {
2668                         nvlist_free(props);
2669                         return (0);
2670                 }
2671         }
2672
2673         if ((error = spa_open(zc->zc_name, &spa, FTAG)) != 0) {
2674                 nvlist_free(props);
2675                 return (error);
2676         }
2677
2678         error = spa_prop_set(spa, props);
2679
2680         nvlist_free(props);
2681         spa_close(spa, FTAG);
2682
2683         return (error);
2684 }
2685
2686 static int
2687 zfs_ioc_pool_get_props(zfs_cmd_t *zc)
2688 {
2689         spa_t *spa;
2690         int error;
2691         nvlist_t *nvp = NULL;
2692
2693         if ((error = spa_open(zc->zc_name, &spa, FTAG)) != 0) {
2694                 /*
2695                  * If the pool is faulted, there may be properties we can still
2696                  * get (such as altroot and cachefile), so attempt to get them
2697                  * anyway.
2698                  */
2699                 mutex_enter(&spa_namespace_lock);
2700                 if ((spa = spa_lookup(zc->zc_name)) != NULL)
2701                         error = spa_prop_get(spa, &nvp);
2702                 mutex_exit(&spa_namespace_lock);
2703         } else {
2704                 error = spa_prop_get(spa, &nvp);
2705                 spa_close(spa, FTAG);
2706         }
2707
2708         if (error == 0 && zc->zc_nvlist_dst != 0)
2709                 error = put_nvlist(zc, nvp);
2710         else
2711                 error = EFAULT;
2712
2713         nvlist_free(nvp);
2714         return (error);
2715 }
2716
2717 /*
2718  * inputs:
2719  * zc_name              name of filesystem
2720  * zc_nvlist_src{_size} nvlist of delegated permissions
2721  * zc_perm_action       allow/unallow flag
2722  *
2723  * outputs:             none
2724  */
2725 static int
2726 zfs_ioc_set_fsacl(zfs_cmd_t *zc)
2727 {
2728         int error;
2729         nvlist_t *fsaclnv = NULL;
2730
2731         if ((error = get_nvlist(zc->zc_nvlist_src, zc->zc_nvlist_src_size,
2732             zc->zc_iflags, &fsaclnv)) != 0)
2733                 return (error);
2734
2735         /*
2736          * Verify nvlist is constructed correctly
2737          */
2738         if ((error = zfs_deleg_verify_nvlist(fsaclnv)) != 0) {
2739                 nvlist_free(fsaclnv);
2740                 return (EINVAL);
2741         }
2742
2743         /*
2744          * If we don't have PRIV_SYS_MOUNT, then validate
2745          * that user is allowed to hand out each permission in
2746          * the nvlist(s)
2747          */
2748
2749         error = secpolicy_zfs(CRED());
2750         if (error) {
2751                 if (zc->zc_perm_action == B_FALSE) {
2752                         error = dsl_deleg_can_allow(zc->zc_name,
2753                             fsaclnv, CRED());
2754                 } else {
2755                         error = dsl_deleg_can_unallow(zc->zc_name,
2756                             fsaclnv, CRED());
2757                 }
2758         }
2759
2760         if (error == 0)
2761                 error = dsl_deleg_set(zc->zc_name, fsaclnv, zc->zc_perm_action);
2762
2763         nvlist_free(fsaclnv);
2764         return (error);
2765 }
2766
2767 /*
2768  * inputs:
2769  * zc_name              name of filesystem
2770  *
2771  * outputs:
2772  * zc_nvlist_src{_size} nvlist of delegated permissions
2773  */
2774 static int
2775 zfs_ioc_get_fsacl(zfs_cmd_t *zc)
2776 {
2777         nvlist_t *nvp;
2778         int error;
2779
2780         if ((error = dsl_deleg_get(zc->zc_name, &nvp)) == 0) {
2781                 error = put_nvlist(zc, nvp);
2782                 nvlist_free(nvp);
2783         }
2784
2785         return (error);
2786 }
2787
2788 /*
2789  * Search the vfs list for a specified resource.  Returns a pointer to it
2790  * or NULL if no suitable entry is found. The caller of this routine
2791  * is responsible for releasing the returned vfs pointer.
2792  */
2793 static vfs_t *
2794 zfs_get_vfs(const char *resource)
2795 {
2796         vfs_t *vfsp;
2797
2798         mtx_lock(&mountlist_mtx);
2799         TAILQ_FOREACH(vfsp, &mountlist, mnt_list) {
2800                 if (strcmp(refstr_value(vfsp->vfs_resource), resource) == 0) {
2801                         VFS_HOLD(vfsp);
2802                         break;
2803                 }
2804         }
2805         mtx_unlock(&mountlist_mtx);
2806         return (vfsp);
2807 }
2808
2809 /* ARGSUSED */
2810 static void
2811 zfs_create_cb(objset_t *os, void *arg, cred_t *cr, dmu_tx_t *tx)
2812 {
2813         zfs_creat_t *zct = arg;
2814
2815         zfs_create_fs(os, cr, zct->zct_zplprops, tx);
2816 }
2817
2818 #define ZFS_PROP_UNDEFINED      ((uint64_t)-1)
2819
2820 /*
2821  * inputs:
2822  * createprops          list of properties requested by creator
2823  * default_zplver       zpl version to use if unspecified in createprops
2824  * fuids_ok             fuids allowed in this version of the spa?
2825  * os                   parent objset pointer (NULL if root fs)
2826  *
2827  * outputs:
2828  * zplprops     values for the zplprops we attach to the master node object
2829  * is_ci        true if requested file system will be purely case-insensitive
2830  *
2831  * Determine the settings for utf8only, normalization and
2832  * casesensitivity.  Specific values may have been requested by the
2833  * creator and/or we can inherit values from the parent dataset.  If
2834  * the file system is of too early a vintage, a creator can not
2835  * request settings for these properties, even if the requested
2836  * setting is the default value.  We don't actually want to create dsl
2837  * properties for these, so remove them from the source nvlist after
2838  * processing.
2839  */
2840 static int
2841 zfs_fill_zplprops_impl(objset_t *os, uint64_t zplver,
2842     boolean_t fuids_ok, boolean_t sa_ok, nvlist_t *createprops,
2843     nvlist_t *zplprops, boolean_t *is_ci)
2844 {
2845         uint64_t sense = ZFS_PROP_UNDEFINED;
2846         uint64_t norm = ZFS_PROP_UNDEFINED;
2847         uint64_t u8 = ZFS_PROP_UNDEFINED;
2848
2849         ASSERT(zplprops != NULL);
2850
2851         /*
2852          * Pull out creator prop choices, if any.
2853          */
2854         if (createprops) {
2855                 (void) nvlist_lookup_uint64(createprops,
2856                     zfs_prop_to_name(ZFS_PROP_VERSION), &zplver);
2857                 (void) nvlist_lookup_uint64(createprops,
2858                     zfs_prop_to_name(ZFS_PROP_NORMALIZE), &norm);
2859                 (void) nvlist_remove_all(createprops,
2860                     zfs_prop_to_name(ZFS_PROP_NORMALIZE));
2861                 (void) nvlist_lookup_uint64(createprops,
2862                     zfs_prop_to_name(ZFS_PROP_UTF8ONLY), &u8);
2863                 (void) nvlist_remove_all(createprops,
2864                     zfs_prop_to_name(ZFS_PROP_UTF8ONLY));
2865                 (void) nvlist_lookup_uint64(createprops,
2866                     zfs_prop_to_name(ZFS_PROP_CASE), &sense);
2867                 (void) nvlist_remove_all(createprops,
2868                     zfs_prop_to_name(ZFS_PROP_CASE));
2869         }
2870
2871         /*
2872          * If the zpl version requested is whacky or the file system
2873          * or pool is version is too "young" to support normalization
2874          * and the creator tried to set a value for one of the props,
2875          * error out.
2876          */
2877         if ((zplver < ZPL_VERSION_INITIAL || zplver > ZPL_VERSION) ||
2878             (zplver >= ZPL_VERSION_FUID && !fuids_ok) ||
2879             (zplver >= ZPL_VERSION_SA && !sa_ok) ||
2880             (zplver < ZPL_VERSION_NORMALIZATION &&
2881             (norm != ZFS_PROP_UNDEFINED || u8 != ZFS_PROP_UNDEFINED ||
2882             sense != ZFS_PROP_UNDEFINED)))
2883                 return (ENOTSUP);
2884
2885         /*
2886          * Put the version in the zplprops
2887          */
2888         VERIFY(nvlist_add_uint64(zplprops,
2889             zfs_prop_to_name(ZFS_PROP_VERSION), zplver) == 0);
2890
2891         if (norm == ZFS_PROP_UNDEFINED)
2892                 VERIFY(zfs_get_zplprop(os, ZFS_PROP_NORMALIZE, &norm) == 0);
2893         VERIFY(nvlist_add_uint64(zplprops,
2894             zfs_prop_to_name(ZFS_PROP_NORMALIZE), norm) == 0);
2895
2896         /*
2897          * If we're normalizing, names must always be valid UTF-8 strings.
2898          */
2899         if (norm)
2900                 u8 = 1;
2901         if (u8 == ZFS_PROP_UNDEFINED)
2902                 VERIFY(zfs_get_zplprop(os, ZFS_PROP_UTF8ONLY, &u8) == 0);
2903         VERIFY(nvlist_add_uint64(zplprops,
2904             zfs_prop_to_name(ZFS_PROP_UTF8ONLY), u8) == 0);
2905
2906         if (sense == ZFS_PROP_UNDEFINED)
2907                 VERIFY(zfs_get_zplprop(os, ZFS_PROP_CASE, &sense) == 0);
2908         VERIFY(nvlist_add_uint64(zplprops,
2909             zfs_prop_to_name(ZFS_PROP_CASE), sense) == 0);
2910
2911         if (is_ci)
2912                 *is_ci = (sense == ZFS_CASE_INSENSITIVE);
2913
2914         return (0);
2915 }
2916
2917 static int
2918 zfs_fill_zplprops(const char *dataset, nvlist_t *createprops,
2919     nvlist_t *zplprops, boolean_t *is_ci)
2920 {
2921         boolean_t fuids_ok, sa_ok;
2922         uint64_t zplver = ZPL_VERSION;
2923         objset_t *os = NULL;
2924         char parentname[MAXNAMELEN];
2925         char *cp;
2926         spa_t *spa;
2927         uint64_t spa_vers;
2928         int error;
2929
2930         (void) strlcpy(parentname, dataset, sizeof (parentname));
2931         cp = strrchr(parentname, '/');
2932         ASSERT(cp != NULL);
2933         cp[0] = '\0';
2934
2935         if ((error = spa_open(dataset, &spa, FTAG)) != 0)
2936                 return (error);
2937
2938         spa_vers = spa_version(spa);
2939         spa_close(spa, FTAG);
2940
2941         zplver = zfs_zpl_version_map(spa_vers);
2942         fuids_ok = (zplver >= ZPL_VERSION_FUID);
2943         sa_ok = (zplver >= ZPL_VERSION_SA);
2944
2945         /*
2946          * Open parent object set so we can inherit zplprop values.
2947          */
2948         if ((error = dmu_objset_hold(parentname, FTAG, &os)) != 0)
2949                 return (error);
2950
2951         error = zfs_fill_zplprops_impl(os, zplver, fuids_ok, sa_ok, createprops,
2952             zplprops, is_ci);
2953         dmu_objset_rele(os, FTAG);
2954         return (error);
2955 }
2956
2957 static int
2958 zfs_fill_zplprops_root(uint64_t spa_vers, nvlist_t *createprops,
2959     nvlist_t *zplprops, boolean_t *is_ci)
2960 {
2961         boolean_t fuids_ok;
2962         boolean_t sa_ok;
2963         uint64_t zplver = ZPL_VERSION;
2964         int error;
2965
2966         zplver = zfs_zpl_version_map(spa_vers);
2967         fuids_ok = (zplver >= ZPL_VERSION_FUID);
2968         sa_ok = (zplver >= ZPL_VERSION_SA);
2969
2970         error = zfs_fill_zplprops_impl(NULL, zplver, fuids_ok, sa_ok,
2971             createprops, zplprops, is_ci);
2972         return (error);
2973 }
2974
2975 /*
2976  * inputs:
2977  * zc_objset_type       type of objset to create (fs vs zvol)
2978  * zc_name              name of new objset
2979  * zc_value             name of snapshot to clone from (may be empty)
2980  * zc_nvlist_src{_size} nvlist of properties to apply
2981  *
2982  * outputs: none
2983  */
2984 static int
2985 zfs_ioc_create(zfs_cmd_t *zc)
2986 {
2987         objset_t *clone;
2988         int error = 0;
2989         zfs_creat_t zct;
2990         nvlist_t *nvprops = NULL;
2991         void (*cbfunc)(objset_t *os, void *arg, cred_t *cr, dmu_tx_t *tx);
2992         dmu_objset_type_t type = zc->zc_objset_type;
2993
2994         switch (type) {
2995
2996         case DMU_OST_ZFS:
2997                 cbfunc = zfs_create_cb;
2998                 break;
2999
3000         case DMU_OST_ZVOL:
3001                 cbfunc = zvol_create_cb;
3002                 break;
3003
3004         default:
3005                 cbfunc = NULL;
3006                 break;
3007         }
3008         if (strchr(zc->zc_name, '@') ||
3009             strchr(zc->zc_name, '%'))
3010                 return (EINVAL);
3011
3012         if (zc->zc_nvlist_src != 0 &&
3013             (error = get_nvlist(zc->zc_nvlist_src, zc->zc_nvlist_src_size,
3014             zc->zc_iflags, &nvprops)) != 0)
3015                 return (error);
3016
3017         zct.zct_zplprops = NULL;
3018         zct.zct_props = nvprops;
3019
3020         if (zc->zc_value[0] != '\0') {
3021                 /*
3022                  * We're creating a clone of an existing snapshot.
3023                  */
3024                 zc->zc_value[sizeof (zc->zc_value) - 1] = '\0';
3025                 if (dataset_namecheck(zc->zc_value, NULL, NULL) != 0) {
3026                         nvlist_free(nvprops);
3027                         return (EINVAL);
3028                 }
3029
3030                 error = dmu_objset_hold(zc->zc_value, FTAG, &clone);
3031                 if (error) {
3032                         nvlist_free(nvprops);
3033                         return (error);
3034                 }
3035
3036                 error = dmu_objset_clone(zc->zc_name, dmu_objset_ds(clone), 0);
3037                 dmu_objset_rele(clone, FTAG);
3038                 if (error) {
3039                         nvlist_free(nvprops);
3040                         return (error);
3041                 }
3042         } else {
3043                 boolean_t is_insensitive = B_FALSE;
3044
3045                 if (cbfunc == NULL) {
3046                         nvlist_free(nvprops);
3047                         return (EINVAL);
3048                 }
3049
3050                 if (type == DMU_OST_ZVOL) {
3051                         uint64_t volsize, volblocksize;
3052
3053                         if (nvprops == NULL ||
3054                             nvlist_lookup_uint64(nvprops,
3055                             zfs_prop_to_name(ZFS_PROP_VOLSIZE),
3056                             &volsize) != 0) {
3057                                 nvlist_free(nvprops);
3058                                 return (EINVAL);
3059                         }
3060
3061                         if ((error = nvlist_lookup_uint64(nvprops,
3062                             zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE),
3063                             &volblocksize)) != 0 && error != ENOENT) {
3064                                 nvlist_free(nvprops);
3065                                 return (EINVAL);
3066                         }
3067
3068                         if (error != 0)
3069                                 volblocksize = zfs_prop_default_numeric(
3070                                     ZFS_PROP_VOLBLOCKSIZE);
3071
3072                         if ((error = zvol_check_volblocksize(
3073                             volblocksize)) != 0 ||
3074                             (error = zvol_check_volsize(volsize,
3075                             volblocksize)) != 0) {
3076                                 nvlist_free(nvprops);
3077                                 return (error);
3078                         }
3079                 } else if (type == DMU_OST_ZFS) {
3080                         int error;
3081
3082                         /*
3083                          * We have to have normalization and
3084                          * case-folding flags correct when we do the
3085                          * file system creation, so go figure them out
3086                          * now.
3087                          */
3088                         VERIFY(nvlist_alloc(&zct.zct_zplprops,
3089                             NV_UNIQUE_NAME, KM_SLEEP) == 0);
3090                         error = zfs_fill_zplprops(zc->zc_name, nvprops,
3091                             zct.zct_zplprops, &is_insensitive);
3092                         if (error != 0) {
3093                                 nvlist_free(nvprops);
3094                                 nvlist_free(zct.zct_zplprops);
3095                                 return (error);
3096                         }
3097                 }
3098                 error = dmu_objset_create(zc->zc_name, type,
3099                     is_insensitive ? DS_FLAG_CI_DATASET : 0, cbfunc, &zct);
3100                 nvlist_free(zct.zct_zplprops);
3101         }
3102
3103         /*
3104          * It would be nice to do this atomically.
3105          */
3106         if (error == 0) {
3107                 error = zfs_set_prop_nvlist(zc->zc_name, ZPROP_SRC_LOCAL,
3108                     nvprops, NULL);
3109                 if (error != 0)
3110                         (void) dmu_objset_destroy(zc->zc_name, B_FALSE);
3111         }
3112         nvlist_free(nvprops);
3113 #ifdef __FreeBSD__
3114         if (error == 0 && type == DMU_OST_ZVOL)
3115                 zvol_create_minors(zc->zc_name);
3116 #endif
3117         return (error);
3118 }
3119
3120 /*
3121  * inputs:
3122  * zc_name      name of filesystem
3123  * zc_value     short name of snapshot
3124  * zc_cookie    recursive flag
3125  * zc_nvlist_src[_size] property list
3126  *
3127  * outputs:
3128  * zc_value     short snapname (i.e. part after the '@')
3129  */
3130 static int
3131 zfs_ioc_snapshot(zfs_cmd_t *zc)
3132 {
3133         nvlist_t *nvprops = NULL;
3134         int error;
3135         boolean_t recursive = zc->zc_cookie;
3136
3137         if (snapshot_namecheck(zc->zc_value, NULL, NULL) != 0)
3138                 return (EINVAL);
3139
3140         if (zc->zc_nvlist_src != 0 &&
3141             (error = get_nvlist(zc->zc_nvlist_src, zc->zc_nvlist_src_size,
3142             zc->zc_iflags, &nvprops)) != 0)
3143                 return (error);
3144
3145         error = zfs_check_userprops(zc->zc_name, nvprops);
3146         if (error)
3147                 goto out;
3148
3149         if (!nvlist_empty(nvprops) &&
3150             zfs_earlier_version(zc->zc_name, SPA_VERSION_SNAP_PROPS)) {
3151                 error = ENOTSUP;
3152                 goto out;
3153         }
3154
3155         error = dmu_objset_snapshot(zc->zc_name, zc->zc_value, NULL,
3156             nvprops, recursive, B_FALSE, -1);
3157
3158 out:
3159         nvlist_free(nvprops);
3160         return (error);
3161 }
3162
3163 int
3164 zfs_unmount_snap(const char *name, void *arg)
3165 {
3166         vfs_t *vfsp = NULL;
3167
3168         if (arg) {
3169                 char *snapname = arg;
3170                 char *fullname = kmem_asprintf("%s@%s", name, snapname);
3171                 vfsp = zfs_get_vfs(fullname);
3172                 strfree(fullname);
3173         } else if (strchr(name, '@')) {
3174                 vfsp = zfs_get_vfs(name);
3175         }
3176
3177         if (vfsp) {
3178                 /*
3179                  * Always force the unmount for snapshots.
3180                  */
3181                 int flag = MS_FORCE;
3182                 int err;
3183
3184                 if ((err = vn_vfswlock(vfsp->vfs_vnodecovered)) != 0) {
3185                         VFS_RELE(vfsp);
3186                         return (err);
3187                 }
3188                 VFS_RELE(vfsp);
3189                 mtx_lock(&Giant);       /* dounmount() */
3190                 dounmount(vfsp, flag, curthread);
3191                 mtx_unlock(&Giant);     /* dounmount() */
3192         }
3193         return (0);
3194 }
3195
3196 /*
3197  * inputs:
3198  * zc_name              name of filesystem, snaps must be under it
3199  * zc_nvlist_src[_size] full names of snapshots to destroy
3200  * zc_defer_destroy     mark for deferred destroy
3201  *
3202  * outputs:
3203  * zc_name              on failure, name of failed snapshot
3204  */
3205 static int
3206 zfs_ioc_destroy_snaps_nvl(zfs_cmd_t *zc)
3207 {
3208         int err, len;
3209         nvlist_t *nvl;
3210         nvpair_t *pair;
3211
3212         if ((err = get_nvlist(zc->zc_nvlist_src, zc->zc_nvlist_src_size,
3213             zc->zc_iflags, &nvl)) != 0) {
3214 #ifndef __FreeBSD__
3215                 return (err);
3216 #else
3217                 /*
3218                  * We are probably called by older binaries,
3219                  * allocate and populate nvlist with recursive snapshots
3220                  */
3221                 if (snapshot_namecheck(zc->zc_value, NULL, NULL) != 0)
3222                         return (EINVAL);
3223                 VERIFY(nvlist_alloc(&nvl, NV_UNIQUE_NAME, KM_SLEEP) == 0);
3224                 err = dmu_get_recursive_snaps_nvl(zc->zc_name,
3225                     zc->zc_value, nvl);
3226                 if (err) {
3227                         nvlist_free(nvl);
3228                         return (err);
3229                 }
3230 #endif /* __FreeBSD__ */
3231         }
3232
3233         len = strlen(zc->zc_name);
3234         for (pair = nvlist_next_nvpair(nvl, NULL); pair != NULL;
3235             pair = nvlist_next_nvpair(nvl, pair)) {
3236                 const char *name = nvpair_name(pair);
3237                 /*
3238                  * The snap name must be underneath the zc_name.  This ensures
3239                  * that our permission checks were legitimate.
3240                  */
3241                 if (strncmp(zc->zc_name, name, len) != 0 ||
3242                     (name[len] != '@' && name[len] != '/')) {
3243                         nvlist_free(nvl);
3244                         return (EINVAL);
3245                 }
3246
3247                 (void) zfs_unmount_snap(name, NULL);
3248                 (void) zvol_remove_minor(name);
3249         }
3250
3251         err = dmu_snapshots_destroy_nvl(nvl, zc->zc_defer_destroy,
3252             zc->zc_name);
3253         nvlist_free(nvl);
3254         return (err);
3255 }
3256
3257 /*
3258  * inputs:
3259  * zc_name              name of dataset to destroy
3260  * zc_objset_type       type of objset
3261  * zc_defer_destroy     mark for deferred destroy
3262  *
3263  * outputs:             none
3264  */
3265 static int
3266 zfs_ioc_destroy(zfs_cmd_t *zc)
3267 {
3268         int err;
3269         if (strchr(zc->zc_name, '@') && zc->zc_objset_type == DMU_OST_ZFS) {
3270                 err = zfs_unmount_snap(zc->zc_name, NULL);
3271                 if (err)
3272                         return (err);
3273         }
3274
3275         err = dmu_objset_destroy(zc->zc_name, zc->zc_defer_destroy);
3276         if (zc->zc_objset_type == DMU_OST_ZVOL && err == 0)
3277                 (void) zvol_remove_minor(zc->zc_name);
3278         return (err);
3279 }
3280
3281 /*
3282  * inputs:
3283  * zc_name      name of dataset to rollback (to most recent snapshot)
3284  *
3285  * outputs:     none
3286  */
3287 static int
3288 zfs_ioc_rollback(zfs_cmd_t *zc)
3289 {
3290         dsl_dataset_t *ds, *clone;
3291         int error;
3292         zfsvfs_t *zfsvfs;
3293         char *clone_name;
3294
3295         error = dsl_dataset_hold(zc->zc_name, FTAG, &ds);
3296         if (error)
3297                 return (error);
3298
3299         /* must not be a snapshot */
3300         if (dsl_dataset_is_snapshot(ds)) {
3301                 dsl_dataset_rele(ds, FTAG);
3302                 return (EINVAL);
3303         }
3304
3305         /* must have a most recent snapshot */
3306         if (ds->ds_phys->ds_prev_snap_txg < TXG_INITIAL) {
3307                 dsl_dataset_rele(ds, FTAG);
3308                 return (EINVAL);
3309         }
3310
3311         /*
3312          * Create clone of most recent snapshot.
3313          */
3314         clone_name = kmem_asprintf("%s/%%rollback", zc->zc_name);
3315         error = dmu_objset_clone(clone_name, ds->ds_prev, DS_FLAG_INCONSISTENT);
3316         if (error)
3317                 goto out;
3318
3319         error = dsl_dataset_own(clone_name, B_TRUE, FTAG, &clone);
3320         if (error)
3321                 goto out;
3322
3323         /*
3324          * Do clone swap.
3325          */
3326         if (getzfsvfs(zc->zc_name, &zfsvfs) == 0) {
3327                 error = zfs_suspend_fs(zfsvfs);
3328                 if (error == 0) {
3329                         int resume_err;
3330
3331                         if (dsl_dataset_tryown(ds, B_FALSE, FTAG)) {
3332                                 error = dsl_dataset_clone_swap(clone, ds,
3333                                     B_TRUE);
3334                                 dsl_dataset_disown(ds, FTAG);
3335                                 ds = NULL;
3336                         } else {
3337                                 error = EBUSY;
3338                         }
3339                         resume_err = zfs_resume_fs(zfsvfs, zc->zc_name);
3340                         error = error ? error : resume_err;
3341                 }
3342                 VFS_RELE(zfsvfs->z_vfs);
3343         } else {
3344                 if (dsl_dataset_tryown(ds, B_FALSE, FTAG)) {
3345                         error = dsl_dataset_clone_swap(clone, ds, B_TRUE);
3346                         dsl_dataset_disown(ds, FTAG);
3347                         ds = NULL;
3348                 } else {
3349                         error = EBUSY;
3350                 }
3351         }
3352
3353         /*
3354          * Destroy clone (which also closes it).
3355          */
3356         (void) dsl_dataset_destroy(clone, FTAG, B_FALSE);
3357
3358 out:
3359         strfree(clone_name);
3360         if (ds)
3361                 dsl_dataset_rele(ds, FTAG);
3362         return (error);
3363 }
3364
3365 /*
3366  * inputs:
3367  * zc_name      old name of dataset
3368  * zc_value     new name of dataset
3369  * zc_cookie    recursive flag (only valid for snapshots)
3370  *
3371  * outputs:     none
3372  */
3373 static int
3374 zfs_ioc_rename(zfs_cmd_t *zc)
3375 {
3376         int flags = 0;
3377
3378         if (zc->zc_cookie & 1)
3379                 flags |= ZFS_RENAME_RECURSIVE;
3380         if (zc->zc_cookie & 2)
3381                 flags |= ZFS_RENAME_ALLOW_MOUNTED;
3382
3383         zc->zc_value[sizeof (zc->zc_value) - 1] = '\0';
3384         if (dataset_namecheck(zc->zc_value, NULL, NULL) != 0 ||
3385             strchr(zc->zc_value, '%'))
3386                 return (EINVAL);
3387
3388         /*
3389          * Unmount snapshot unless we're doing a recursive rename,
3390          * in which case the dataset code figures out which snapshots
3391          * to unmount.
3392          */
3393         if (!(flags & ZFS_RENAME_RECURSIVE) &&
3394             strchr(zc->zc_name, '@') != NULL &&
3395             zc->zc_objset_type == DMU_OST_ZFS) {
3396                 int err = zfs_unmount_snap(zc->zc_name, NULL);
3397                 if (err)
3398                         return (err);
3399         }
3400         return (dmu_objset_rename(zc->zc_name, zc->zc_value, flags));
3401 }
3402
3403 static int
3404 zfs_check_settable(const char *dsname, nvpair_t *pair, cred_t *cr)
3405 {
3406         const char *propname = nvpair_name(pair);
3407         boolean_t issnap = (strchr(dsname, '@') != NULL);
3408         zfs_prop_t prop = zfs_name_to_prop(propname);
3409         uint64_t intval;
3410         int err;
3411
3412         if (prop == ZPROP_INVAL) {
3413                 if (zfs_prop_user(propname)) {
3414                         if (err = zfs_secpolicy_write_perms(dsname,
3415                             ZFS_DELEG_PERM_USERPROP, cr))
3416                                 return (err);
3417                         return (0);
3418                 }
3419
3420                 if (!issnap && zfs_prop_userquota(propname)) {
3421                         const char *perm = NULL;
3422                         const char *uq_prefix =
3423                             zfs_userquota_prop_prefixes[ZFS_PROP_USERQUOTA];
3424                         const char *gq_prefix =
3425                             zfs_userquota_prop_prefixes[ZFS_PROP_GROUPQUOTA];
3426
3427                         if (strncmp(propname, uq_prefix,
3428                             strlen(uq_prefix)) == 0) {
3429                                 perm = ZFS_DELEG_PERM_USERQUOTA;
3430                         } else if (strncmp(propname, gq_prefix,
3431                             strlen(gq_prefix)) == 0) {
3432                                 perm = ZFS_DELEG_PERM_GROUPQUOTA;
3433                         } else {
3434                                 /* USERUSED and GROUPUSED are read-only */
3435                                 return (EINVAL);
3436                         }
3437
3438                         if (err = zfs_secpolicy_write_perms(dsname, perm, cr))
3439                                 return (err);
3440                         return (0);
3441                 }
3442
3443                 return (EINVAL);
3444         }
3445
3446         if (issnap)
3447                 return (EINVAL);
3448
3449         if (nvpair_type(pair) == DATA_TYPE_NVLIST) {
3450                 /*
3451                  * dsl_prop_get_all_impl() returns properties in this
3452                  * format.
3453                  */
3454                 nvlist_t *attrs;
3455                 VERIFY(nvpair_value_nvlist(pair, &attrs) == 0);
3456                 VERIFY(nvlist_lookup_nvpair(attrs, ZPROP_VALUE,
3457                     &pair) == 0);
3458         }
3459
3460         /*
3461          * Check that this value is valid for this pool version
3462          */
3463         switch (prop) {
3464         case ZFS_PROP_COMPRESSION:
3465                 /*
3466                  * If the user specified gzip compression, make sure
3467                  * the SPA supports it. We ignore any errors here since
3468                  * we'll catch them later.
3469                  */
3470                 if (nvpair_type(pair) == DATA_TYPE_UINT64 &&
3471                     nvpair_value_uint64(pair, &intval) == 0) {
3472                         if (intval >= ZIO_COMPRESS_GZIP_1 &&
3473                             intval <= ZIO_COMPRESS_GZIP_9 &&
3474                             zfs_earlier_version(dsname,
3475                             SPA_VERSION_GZIP_COMPRESSION)) {
3476                                 return (ENOTSUP);
3477                         }
3478
3479                         if (intval == ZIO_COMPRESS_ZLE &&
3480                             zfs_earlier_version(dsname,
3481                             SPA_VERSION_ZLE_COMPRESSION))
3482                                 return (ENOTSUP);
3483
3484                         /*
3485                          * If this is a bootable dataset then
3486                          * verify that the compression algorithm
3487                          * is supported for booting. We must return
3488                          * something other than ENOTSUP since it
3489                          * implies a downrev pool version.
3490                          */
3491                         if (zfs_is_bootfs(dsname) &&
3492                             !BOOTFS_COMPRESS_VALID(intval)) {
3493                                 return (ERANGE);
3494                         }
3495                 }
3496                 break;
3497
3498         case ZFS_PROP_COPIES:
3499                 if (zfs_earlier_version(dsname, SPA_VERSION_DITTO_BLOCKS))
3500                         return (ENOTSUP);
3501                 break;
3502
3503         case ZFS_PROP_DEDUP:
3504                 if (zfs_earlier_version(dsname, SPA_VERSION_DEDUP))
3505                         return (ENOTSUP);
3506                 break;
3507
3508         case ZFS_PROP_SHARESMB:
3509                 if (zpl_earlier_version(dsname, ZPL_VERSION_FUID))
3510                         return (ENOTSUP);
3511                 break;
3512
3513         case ZFS_PROP_ACLINHERIT:
3514                 if (nvpair_type(pair) == DATA_TYPE_UINT64 &&
3515                     nvpair_value_uint64(pair, &intval) == 0) {
3516                         if (intval == ZFS_ACL_PASSTHROUGH_X &&
3517                             zfs_earlier_version(dsname,
3518                             SPA_VERSION_PASSTHROUGH_X))
3519                                 return (ENOTSUP);
3520                 }
3521                 break;
3522         }
3523
3524         return (zfs_secpolicy_setprop(dsname, prop, pair, CRED()));
3525 }
3526
3527 /*
3528  * Removes properties from the given props list that fail permission checks
3529  * needed to clear them and to restore them in case of a receive error. For each
3530  * property, make sure we have both set and inherit permissions.
3531  *
3532  * Returns the first error encountered if any permission checks fail. If the
3533  * caller provides a non-NULL errlist, it also gives the complete list of names
3534  * of all the properties that failed a permission check along with the
3535  * corresponding error numbers. The caller is responsible for freeing the
3536  * returned errlist.
3537  *
3538  * If every property checks out successfully, zero is returned and the list
3539  * pointed at by errlist is NULL.
3540  */
3541 static int
3542 zfs_check_clearable(char *dataset, nvlist_t *props, nvlist_t **errlist)
3543 {
3544         zfs_cmd_t *zc;
3545         nvpair_t *pair, *next_pair;
3546         nvlist_t *errors;
3547         int err, rv = 0;
3548
3549         if (props == NULL)
3550                 return (0);
3551
3552         VERIFY(nvlist_alloc(&errors, NV_UNIQUE_NAME, KM_SLEEP) == 0);
3553
3554         zc = kmem_alloc(sizeof (zfs_cmd_t), KM_SLEEP);
3555         (void) strcpy(zc->zc_name, dataset);
3556         pair = nvlist_next_nvpair(props, NULL);
3557         while (pair != NULL) {
3558                 next_pair = nvlist_next_nvpair(props, pair);
3559
3560                 (void) strcpy(zc->zc_value, nvpair_name(pair));
3561                 if ((err = zfs_check_settable(dataset, pair, CRED())) != 0 ||
3562                     (err = zfs_secpolicy_inherit(zc, CRED())) != 0) {
3563                         VERIFY(nvlist_remove_nvpair(props, pair) == 0);
3564                         VERIFY(nvlist_add_int32(errors,
3565                             zc->zc_value, err) == 0);
3566                 }
3567                 pair = next_pair;
3568         }
3569         kmem_free(zc, sizeof (zfs_cmd_t));
3570
3571         if ((pair = nvlist_next_nvpair(errors, NULL)) == NULL) {
3572                 nvlist_free(errors);
3573                 errors = NULL;
3574         } else {
3575                 VERIFY(nvpair_value_int32(pair, &rv) == 0);
3576         }
3577
3578         if (errlist == NULL)
3579                 nvlist_free(errors);
3580         else
3581                 *errlist = errors;
3582
3583         return (rv);
3584 }
3585
3586 static boolean_t
3587 propval_equals(nvpair_t *p1, nvpair_t *p2)
3588 {
3589         if (nvpair_type(p1) == DATA_TYPE_NVLIST) {
3590                 /* dsl_prop_get_all_impl() format */
3591                 nvlist_t *attrs;
3592                 VERIFY(nvpair_value_nvlist(p1, &attrs) == 0);
3593                 VERIFY(nvlist_lookup_nvpair(attrs, ZPROP_VALUE,
3594                     &p1) == 0);
3595         }
3596
3597         if (nvpair_type(p2) == DATA_TYPE_NVLIST) {
3598                 nvlist_t *attrs;
3599                 VERIFY(nvpair_value_nvlist(p2, &attrs) == 0);
3600                 VERIFY(nvlist_lookup_nvpair(attrs, ZPROP_VALUE,
3601                     &p2) == 0);
3602         }
3603
3604         if (nvpair_type(p1) != nvpair_type(p2))
3605                 return (B_FALSE);
3606
3607         if (nvpair_type(p1) == DATA_TYPE_STRING) {
3608                 char *valstr1, *valstr2;
3609
3610                 VERIFY(nvpair_value_string(p1, (char **)&valstr1) == 0);
3611                 VERIFY(nvpair_value_string(p2, (char **)&valstr2) == 0);
3612                 return (strcmp(valstr1, valstr2) == 0);
3613         } else {
3614                 uint64_t intval1, intval2;
3615
3616                 VERIFY(nvpair_value_uint64(p1, &intval1) == 0);
3617                 VERIFY(nvpair_value_uint64(p2, &intval2) == 0);
3618                 return (intval1 == intval2);
3619         }
3620 }
3621
3622 /*
3623  * Remove properties from props if they are not going to change (as determined
3624  * by comparison with origprops). Remove them from origprops as well, since we
3625  * do not need to clear or restore properties that won't change.
3626  */
3627 static void
3628 props_reduce(nvlist_t *props, nvlist_t *origprops)
3629 {
3630         nvpair_t *pair, *next_pair;
3631
3632         if (origprops == NULL)
3633                 return; /* all props need to be received */
3634
3635         pair = nvlist_next_nvpair(props, NULL);
3636         while (pair != NULL) {
3637                 const char *propname = nvpair_name(pair);
3638                 nvpair_t *match;
3639
3640                 next_pair = nvlist_next_nvpair(props, pair);
3641
3642                 if ((nvlist_lookup_nvpair(origprops, propname,
3643                     &match) != 0) || !propval_equals(pair, match))
3644                         goto next; /* need to set received value */
3645
3646                 /* don't clear the existing received value */
3647                 (void) nvlist_remove_nvpair(origprops, match);
3648                 /* don't bother receiving the property */
3649                 (void) nvlist_remove_nvpair(props, pair);
3650 next:
3651                 pair = next_pair;
3652         }
3653 }
3654
3655 #ifdef  DEBUG
3656 static boolean_t zfs_ioc_recv_inject_err;
3657 #endif
3658
3659 /*
3660  * inputs:
3661  * zc_name              name of containing filesystem
3662  * zc_nvlist_src{_size} nvlist of properties to apply
3663  * zc_value             name of snapshot to create
3664  * zc_string            name of clone origin (if DRR_FLAG_CLONE)
3665  * zc_cookie            file descriptor to recv from
3666  * zc_begin_record      the BEGIN record of the stream (not byteswapped)
3667  * zc_guid              force flag
3668  * zc_cleanup_fd        cleanup-on-exit file descriptor
3669  * zc_action_handle     handle for this guid/ds mapping (or zero on first call)
3670  *
3671  * outputs:
3672  * zc_cookie            number of bytes read
3673  * zc_nvlist_dst{_size} error for each unapplied received property
3674  * zc_obj               zprop_errflags_t
3675  * zc_action_handle     handle for this guid/ds mapping
3676  */
3677 static int
3678 zfs_ioc_recv(zfs_cmd_t *zc)
3679 {
3680         file_t *fp;
3681         objset_t *os;
3682         dmu_recv_cookie_t drc;
3683         boolean_t force = (boolean_t)zc->zc_guid;
3684         int fd;
3685         int error = 0;
3686         int props_error = 0;
3687         nvlist_t *errors;
3688         offset_t off;
3689         nvlist_t *props = NULL; /* sent properties */
3690         nvlist_t *origprops = NULL; /* existing properties */
3691         objset_t *origin = NULL;
3692         char *tosnap;
3693         char tofs[ZFS_MAXNAMELEN];
3694         boolean_t first_recvd_props = B_FALSE;
3695
3696         if (dataset_namecheck(zc->zc_value, NULL, NULL) != 0 ||
3697             strchr(zc->zc_value, '@') == NULL ||
3698             strchr(zc->zc_value, '%'))
3699                 return (EINVAL);
3700
3701         (void) strcpy(tofs, zc->zc_value);
3702         tosnap = strchr(tofs, '@');
3703         *tosnap++ = '\0';
3704
3705         if (zc->zc_nvlist_src != 0 &&
3706             (error = get_nvlist(zc->zc_nvlist_src, zc->zc_nvlist_src_size,
3707             zc->zc_iflags, &props)) != 0)
3708                 return (error);
3709
3710         fd = zc->zc_cookie;
3711         fp = getf(fd);
3712         if (fp == NULL) {
3713                 nvlist_free(props);
3714                 return (EBADF);
3715         }
3716
3717         VERIFY(nvlist_alloc(&errors, NV_UNIQUE_NAME, KM_SLEEP) == 0);
3718
3719         if (props && dmu_objset_hold(tofs, FTAG, &os) == 0) {
3720                 if ((spa_version(os->os_spa) >= SPA_VERSION_RECVD_PROPS) &&
3721                     !dsl_prop_get_hasrecvd(os)) {
3722                         first_recvd_props = B_TRUE;
3723                 }
3724
3725                 /*
3726                  * If new received properties are supplied, they are to
3727                  * completely replace the existing received properties, so stash
3728                  * away the existing ones.
3729                  */
3730                 if (dsl_prop_get_received(os, &origprops) == 0) {
3731                         nvlist_t *errlist = NULL;
3732                         /*
3733                          * Don't bother writing a property if its value won't
3734                          * change (and avoid the unnecessary security checks).
3735                          *
3736                          * The first receive after SPA_VERSION_RECVD_PROPS is a
3737                          * special case where we blow away all local properties
3738                          * regardless.
3739                          */
3740                         if (!first_recvd_props)
3741                                 props_reduce(props, origprops);
3742                         if (zfs_check_clearable(tofs, origprops,
3743                             &errlist) != 0)
3744                                 (void) nvlist_merge(errors, errlist, 0);
3745                         nvlist_free(errlist);
3746                 }
3747
3748                 dmu_objset_rele(os, FTAG);
3749         }
3750
3751         if (zc->zc_string[0]) {
3752                 error = dmu_objset_hold(zc->zc_string, FTAG, &origin);
3753                 if (error)
3754                         goto out;
3755         }
3756
3757         error = dmu_recv_begin(tofs, tosnap, zc->zc_top_ds,
3758             &zc->zc_begin_record, force, origin, &drc);
3759         if (origin)
3760                 dmu_objset_rele(origin, FTAG);
3761         if (error)
3762                 goto out;
3763
3764         /*
3765          * Set properties before we receive the stream so that they are applied
3766          * to the new data. Note that we must call dmu_recv_stream() if
3767          * dmu_recv_begin() succeeds.
3768          */
3769         if (props) {
3770                 nvlist_t *errlist;
3771
3772                 if (dmu_objset_from_ds(drc.drc_logical_ds, &os) == 0) {
3773                         if (drc.drc_newfs) {
3774                                 if (spa_version(os->os_spa) >=
3775                                     SPA_VERSION_RECVD_PROPS)
3776                                         first_recvd_props = B_TRUE;
3777                         } else if (origprops != NULL) {
3778                                 if (clear_received_props(os, tofs, origprops,
3779                                     first_recvd_props ? NULL : props) != 0)
3780                                         zc->zc_obj |= ZPROP_ERR_NOCLEAR;
3781                         } else {
3782                                 zc->zc_obj |= ZPROP_ERR_NOCLEAR;
3783                         }
3784                         dsl_prop_set_hasrecvd(os);
3785                 } else if (!drc.drc_newfs) {
3786                         zc->zc_obj |= ZPROP_ERR_NOCLEAR;
3787                 }
3788
3789                 (void) zfs_set_prop_nvlist(tofs, ZPROP_SRC_RECEIVED,
3790                     props, &errlist);
3791                 (void) nvlist_merge(errors, errlist, 0);
3792                 nvlist_free(errlist);
3793         }
3794
3795         if (fit_error_list(zc, &errors) != 0 || put_nvlist(zc, errors) != 0) {
3796                 /*
3797                  * Caller made zc->zc_nvlist_dst less than the minimum expected
3798                  * size or supplied an invalid address.
3799                  */
3800                 props_error = EINVAL;
3801         }
3802
3803         off = fp->f_offset;
3804         error = dmu_recv_stream(&drc, fp, &off, zc->zc_cleanup_fd,
3805             &zc->zc_action_handle);
3806
3807         if (error == 0) {
3808                 zfsvfs_t *zfsvfs = NULL;
3809
3810                 if (getzfsvfs(tofs, &zfsvfs) == 0) {
3811                         /* online recv */
3812                         int end_err;
3813
3814                         error = zfs_suspend_fs(zfsvfs);
3815                         /*
3816                          * If the suspend fails, then the recv_end will
3817                          * likely also fail, and clean up after itself.
3818                          */
3819                         end_err = dmu_recv_end(&drc);
3820                         if (error == 0)
3821                                 error = zfs_resume_fs(zfsvfs, tofs);
3822                         error = error ? error : end_err;
3823                         VFS_RELE(zfsvfs->z_vfs);
3824                 } else {
3825                         error = dmu_recv_end(&drc);
3826                 }
3827         }
3828
3829         zc->zc_cookie = off - fp->f_offset;
3830         if (off >= 0 && off <= MAXOFFSET_T)
3831                 fp->f_offset = off;
3832
3833 #ifdef  DEBUG
3834         if (zfs_ioc_recv_inject_err) {
3835                 zfs_ioc_recv_inject_err = B_FALSE;
3836                 error = 1;
3837         }
3838 #endif
3839         /*
3840          * On error, restore the original props.
3841          */
3842         if (error && props) {
3843                 if (dmu_objset_hold(tofs, FTAG, &os) == 0) {
3844                         if (clear_received_props(os, tofs, props, NULL) != 0) {
3845                                 /*
3846                                  * We failed to clear the received properties.
3847                                  * Since we may have left a $recvd value on the
3848                                  * system, we can't clear the $hasrecvd flag.
3849                                  */
3850                                 zc->zc_obj |= ZPROP_ERR_NORESTORE;
3851                         } else if (first_recvd_props) {
3852                                 dsl_prop_unset_hasrecvd(os);
3853                         }
3854                         dmu_objset_rele(os, FTAG);
3855                 } else if (!drc.drc_newfs) {
3856                         /* We failed to clear the received properties. */
3857                         zc->zc_obj |= ZPROP_ERR_NORESTORE;
3858                 }
3859
3860                 if (origprops == NULL && !drc.drc_newfs) {
3861                         /* We failed to stash the original properties. */
3862                         zc->zc_obj |= ZPROP_ERR_NORESTORE;
3863                 }
3864
3865                 /*
3866                  * dsl_props_set() will not convert RECEIVED to LOCAL on or
3867                  * after SPA_VERSION_RECVD_PROPS, so we need to specify LOCAL
3868                  * explictly if we're restoring local properties cleared in the
3869                  * first new-style receive.
3870                  */
3871                 if (origprops != NULL &&
3872                     zfs_set_prop_nvlist(tofs, (first_recvd_props ?
3873                     ZPROP_SRC_LOCAL : ZPROP_SRC_RECEIVED),
3874                     origprops, NULL) != 0) {
3875                         /*
3876                          * We stashed the original properties but failed to
3877                          * restore them.
3878                          */
3879                         zc->zc_obj |= ZPROP_ERR_NORESTORE;
3880                 }
3881         }
3882 out:
3883         nvlist_free(props);
3884         nvlist_free(origprops);
3885         nvlist_free(errors);
3886         releasef(fd);
3887
3888         if (error == 0)
3889                 error = props_error;
3890
3891         return (error);
3892 }
3893
3894 /*
3895  * inputs:
3896  * zc_name      name of snapshot to send
3897  * zc_cookie    file descriptor to send stream to
3898  * zc_obj       fromorigin flag (mutually exclusive with zc_fromobj)
3899  * zc_sendobj   objsetid of snapshot to send
3900  * zc_fromobj   objsetid of incremental fromsnap (may be zero)
3901  * zc_guid      if set, estimate size of stream only.  zc_cookie is ignored.
3902  *              output size in zc_objset_type.
3903  *
3904  * outputs: none
3905  */
3906 static int
3907 zfs_ioc_send(zfs_cmd_t *zc)
3908 {
3909         objset_t *fromsnap = NULL;
3910         objset_t *tosnap;
3911         int error;
3912         offset_t off;
3913         dsl_dataset_t *ds;
3914         dsl_dataset_t *dsfrom = NULL;
3915         spa_t *spa;
3916         dsl_pool_t *dp;
3917         boolean_t estimate = (zc->zc_guid != 0);
3918
3919         error = spa_open(zc->zc_name, &spa, FTAG);
3920         if (error)
3921                 return (error);
3922
3923         dp = spa_get_dsl(spa);
3924         rw_enter(&dp->dp_config_rwlock, RW_READER);
3925         error = dsl_dataset_hold_obj(dp, zc->zc_sendobj, FTAG, &ds);
3926         rw_exit(&dp->dp_config_rwlock);
3927         if (error) {
3928                 spa_close(spa, FTAG);
3929                 return (error);
3930         }
3931
3932         error = dmu_objset_from_ds(ds, &tosnap);
3933         if (error) {
3934                 dsl_dataset_rele(ds, FTAG);
3935                 spa_close(spa, FTAG);
3936                 return (error);
3937         }
3938
3939         if (zc->zc_fromobj != 0) {
3940                 rw_enter(&dp->dp_config_rwlock, RW_READER);
3941                 error = dsl_dataset_hold_obj(dp, zc->zc_fromobj, FTAG, &dsfrom);
3942                 rw_exit(&dp->dp_config_rwlock);
3943                 spa_close(spa, FTAG);
3944                 if (error) {
3945                         dsl_dataset_rele(ds, FTAG);
3946                         return (error);
3947                 }
3948                 error = dmu_objset_from_ds(dsfrom, &fromsnap);
3949                 if (error) {
3950                         dsl_dataset_rele(dsfrom, FTAG);
3951                         dsl_dataset_rele(ds, FTAG);
3952                         return (error);
3953                 }
3954         } else {
3955                 spa_close(spa, FTAG);
3956         }
3957
3958         if (estimate) {
3959                 error = dmu_send_estimate(tosnap, fromsnap, zc->zc_obj,
3960                     &zc->zc_objset_type);
3961         } else {
3962                 file_t *fp = getf(zc->zc_cookie);
3963                 if (fp == NULL) {
3964                         dsl_dataset_rele(ds, FTAG);
3965                         if (dsfrom)
3966                                 dsl_dataset_rele(dsfrom, FTAG);
3967                         return (EBADF);
3968                 }
3969
3970                 off = fp->f_offset;
3971                 error = dmu_send(tosnap, fromsnap, zc->zc_obj,
3972                     zc->zc_cookie, fp, &off);
3973
3974                 if (off >= 0 && off <= MAXOFFSET_T)
3975                         fp->f_offset = off;
3976                 releasef(zc->zc_cookie);
3977         }
3978         if (dsfrom)
3979                 dsl_dataset_rele(dsfrom, FTAG);
3980         dsl_dataset_rele(ds, FTAG);
3981         return (error);
3982 }
3983
3984 /*
3985  * inputs:
3986  * zc_name      name of snapshot on which to report progress
3987  * zc_cookie    file descriptor of send stream
3988  *
3989  * outputs:
3990  * zc_cookie    number of bytes written in send stream thus far
3991  */
3992 static int
3993 zfs_ioc_send_progress(zfs_cmd_t *zc)
3994 {
3995         dsl_dataset_t *ds;
3996         dmu_sendarg_t *dsp = NULL;
3997         int error;
3998
3999         if ((error = dsl_dataset_hold(zc->zc_name, FTAG, &ds)) != 0)
4000                 return (error);
4001
4002         mutex_enter(&ds->ds_sendstream_lock);
4003
4004         /*
4005          * Iterate over all the send streams currently active on this dataset.
4006          * If there's one which matches the specified file descriptor _and_ the
4007          * stream was started by the current process, return the progress of
4008          * that stream.
4009          */
4010         for (dsp = list_head(&ds->ds_sendstreams); dsp != NULL;
4011             dsp = list_next(&ds->ds_sendstreams, dsp)) {
4012                 if (dsp->dsa_outfd == zc->zc_cookie &&
4013                     dsp->dsa_proc == curproc)
4014                         break;
4015         }
4016
4017         if (dsp != NULL)
4018                 zc->zc_cookie = *(dsp->dsa_off);
4019         else
4020                 error = ENOENT;
4021
4022         mutex_exit(&ds->ds_sendstream_lock);
4023         dsl_dataset_rele(ds, FTAG);
4024         return (error);
4025 }
4026
4027 static int
4028 zfs_ioc_inject_fault(zfs_cmd_t *zc)
4029 {
4030         int id, error;
4031
4032         error = zio_inject_fault(zc->zc_name, (int)zc->zc_guid, &id,
4033             &zc->zc_inject_record);
4034
4035         if (error == 0)
4036                 zc->zc_guid = (uint64_t)id;
4037
4038         return (error);
4039 }
4040
4041 static int
4042 zfs_ioc_clear_fault(zfs_cmd_t *zc)
4043 {
4044         return (zio_clear_fault((int)zc->zc_guid));
4045 }
4046
4047 static int
4048 zfs_ioc_inject_list_next(zfs_cmd_t *zc)
4049 {
4050         int id = (int)zc->zc_guid;
4051         int error;
4052
4053         error = zio_inject_list_next(&id, zc->zc_name, sizeof (zc->zc_name),
4054             &zc->zc_inject_record);
4055
4056         zc->zc_guid = id;
4057
4058         return (error);
4059 }
4060
4061 static int
4062 zfs_ioc_error_log(zfs_cmd_t *zc)
4063 {
4064         spa_t *spa;
4065         int error;
4066         size_t count = (size_t)zc->zc_nvlist_dst_size;
4067
4068         if ((error = spa_open(zc->zc_name, &spa, FTAG)) != 0)
4069                 return (error);
4070
4071         error = spa_get_errlog(spa, (void *)(uintptr_t)zc->zc_nvlist_dst,
4072             &count);
4073         if (error == 0)
4074                 zc->zc_nvlist_dst_size = count;
4075         else
4076                 zc->zc_nvlist_dst_size = spa_get_errlog_size(spa);
4077
4078         spa_close(spa, FTAG);
4079
4080         return (error);
4081 }
4082
4083 static int
4084 zfs_ioc_clear(zfs_cmd_t *zc)
4085 {
4086         spa_t *spa;
4087         vdev_t *vd;
4088         int error;
4089
4090         /*
4091          * On zpool clear we also fix up missing slogs
4092          */
4093         mutex_enter(&spa_namespace_lock);
4094         spa = spa_lookup(zc->zc_name);
4095         if (spa == NULL) {
4096                 mutex_exit(&spa_namespace_lock);
4097                 return (EIO);
4098         }
4099         if (spa_get_log_state(spa) == SPA_LOG_MISSING) {
4100                 /* we need to let spa_open/spa_load clear the chains */
4101                 spa_set_log_state(spa, SPA_LOG_CLEAR);
4102         }
4103         spa->spa_last_open_failed = 0;
4104         mutex_exit(&spa_namespace_lock);
4105
4106         if (zc->zc_cookie & ZPOOL_NO_REWIND) {
4107                 error = spa_open(zc->zc_name, &spa, FTAG);
4108         } else {
4109                 nvlist_t *policy;
4110                 nvlist_t *config = NULL;
4111
4112                 if (zc->zc_nvlist_src == 0)
4113                         return (EINVAL);
4114
4115                 if ((error = get_nvlist(zc->zc_nvlist_src,
4116                     zc->zc_nvlist_src_size, zc->zc_iflags, &policy)) == 0) {
4117                         error = spa_open_rewind(zc->zc_name, &spa, FTAG,
4118                             policy, &config);
4119                         if (config != NULL) {
4120                                 int err;
4121
4122                                 if ((err = put_nvlist(zc, config)) != 0)
4123                                         error = err;
4124                                 nvlist_free(config);
4125                         }
4126                         nvlist_free(policy);
4127                 }
4128         }
4129
4130         if (error)
4131                 return (error);
4132
4133         spa_vdev_state_enter(spa, SCL_NONE);
4134
4135         if (zc->zc_guid == 0) {
4136                 vd = NULL;
4137         } else {
4138                 vd = spa_lookup_by_guid(spa, zc->zc_guid, B_TRUE);
4139                 if (vd == NULL) {
4140                         (void) spa_vdev_state_exit(spa, NULL, ENODEV);
4141                         spa_close(spa, FTAG);
4142                         return (ENODEV);
4143                 }
4144         }
4145
4146         vdev_clear(spa, vd);
4147
4148         (void) spa_vdev_state_exit(spa, NULL, 0);
4149
4150         /*
4151          * Resume any suspended I/Os.
4152          */
4153         if (zio_resume(spa) != 0)
4154                 error = EIO;
4155
4156         spa_close(spa, FTAG);
4157
4158         return (error);
4159 }
4160
4161 static int
4162 zfs_ioc_pool_reopen(zfs_cmd_t *zc)
4163 {
4164         spa_t *spa;
4165         int error;
4166
4167         error = spa_open(zc->zc_name, &spa, FTAG);
4168         if (error)
4169                 return (error);
4170
4171         spa_vdev_state_enter(spa, SCL_NONE);
4172
4173         /*
4174          * If a resilver is already in progress then set the
4175          * spa_scrub_reopen flag to B_TRUE so that we don't restart
4176          * the scan as a side effect of the reopen. Otherwise, let
4177          * vdev_open() decided if a resilver is required.
4178          */
4179         spa->spa_scrub_reopen = dsl_scan_resilvering(spa->spa_dsl_pool);
4180         vdev_reopen(spa->spa_root_vdev);
4181         spa->spa_scrub_reopen = B_FALSE;
4182
4183         (void) spa_vdev_state_exit(spa, NULL, 0);
4184         spa_close(spa, FTAG);
4185         return (0);
4186 }
4187 /*
4188  * inputs:
4189  * zc_name      name of filesystem
4190  * zc_value     name of origin snapshot
4191  *
4192  * outputs:
4193  * zc_string    name of conflicting snapshot, if there is one
4194  */
4195 static int
4196 zfs_ioc_promote(zfs_cmd_t *zc)
4197 {
4198         char *cp;
4199
4200         /*
4201          * We don't need to unmount *all* the origin fs's snapshots, but
4202          * it's easier.
4203          */
4204         cp = strchr(zc->zc_value, '@');
4205         if (cp)
4206                 *cp = '\0';
4207         (void) dmu_objset_find(zc->zc_value,
4208             zfs_unmount_snap, NULL, DS_FIND_SNAPSHOTS);
4209         return (dsl_dataset_promote(zc->zc_name, zc->zc_string));
4210 }
4211
4212 /*
4213  * Retrieve a single {user|group}{used|quota}@... property.
4214  *
4215  * inputs:
4216  * zc_name      name of filesystem
4217  * zc_objset_type zfs_userquota_prop_t
4218  * zc_value     domain name (eg. "S-1-234-567-89")
4219  * zc_guid      RID/UID/GID
4220  *
4221  * outputs:
4222  * zc_cookie    property value
4223  */
4224 static int
4225 zfs_ioc_userspace_one(zfs_cmd_t *zc)
4226 {
4227         zfsvfs_t *zfsvfs;
4228         int error;
4229
4230         if (zc->zc_objset_type >= ZFS_NUM_USERQUOTA_PROPS)
4231                 return (EINVAL);
4232
4233         error = zfsvfs_hold(zc->zc_name, FTAG, &zfsvfs, B_FALSE);
4234         if (error)
4235                 return (error);
4236
4237         error = zfs_userspace_one(zfsvfs,
4238             zc->zc_objset_type, zc->zc_value, zc->zc_guid, &zc->zc_cookie);
4239         zfsvfs_rele(zfsvfs, FTAG);
4240
4241         return (error);
4242 }
4243
4244 /*
4245  * inputs:
4246  * zc_name              name of filesystem
4247  * zc_cookie            zap cursor
4248  * zc_objset_type       zfs_userquota_prop_t
4249  * zc_nvlist_dst[_size] buffer to fill (not really an nvlist)
4250  *
4251  * outputs:
4252  * zc_nvlist_dst[_size] data buffer (array of zfs_useracct_t)
4253  * zc_cookie    zap cursor
4254  */
4255 static int
4256 zfs_ioc_userspace_many(zfs_cmd_t *zc)
4257 {
4258         zfsvfs_t *zfsvfs;
4259         int bufsize = zc->zc_nvlist_dst_size;
4260
4261         if (bufsize <= 0)
4262                 return (ENOMEM);
4263
4264         int error = zfsvfs_hold(zc->zc_name, FTAG, &zfsvfs, B_FALSE);
4265         if (error)
4266                 return (error);
4267
4268         void *buf = kmem_alloc(bufsize, KM_SLEEP);
4269
4270         error = zfs_userspace_many(zfsvfs, zc->zc_objset_type, &zc->zc_cookie,
4271             buf, &zc->zc_nvlist_dst_size);
4272
4273         if (error == 0) {
4274                 error = ddi_copyout(buf,
4275                     (void *)(uintptr_t)zc->zc_nvlist_dst,
4276                     zc->zc_nvlist_dst_size, zc->zc_iflags);
4277         }
4278         kmem_free(buf, bufsize);
4279         zfsvfs_rele(zfsvfs, FTAG);
4280
4281         return (error);
4282 }
4283
4284 /*
4285  * inputs:
4286  * zc_name              name of filesystem
4287  *
4288  * outputs:
4289  * none
4290  */
4291 static int
4292 zfs_ioc_userspace_upgrade(zfs_cmd_t *zc)
4293 {
4294         objset_t *os;
4295         int error = 0;
4296         zfsvfs_t *zfsvfs;
4297
4298         if (getzfsvfs(zc->zc_name, &zfsvfs) == 0) {
4299                 if (!dmu_objset_userused_enabled(zfsvfs->z_os)) {
4300                         /*
4301                          * If userused is not enabled, it may be because the
4302                          * objset needs to be closed & reopened (to grow the
4303                          * objset_phys_t).  Suspend/resume the fs will do that.
4304                          */
4305                         error = zfs_suspend_fs(zfsvfs);
4306                         if (error == 0)
4307                                 error = zfs_resume_fs(zfsvfs, zc->zc_name);
4308                 }
4309                 if (error == 0)
4310                         error = dmu_objset_userspace_upgrade(zfsvfs->z_os);
4311                 VFS_RELE(zfsvfs->z_vfs);
4312         } else {
4313                 /* XXX kind of reading contents without owning */
4314                 error = dmu_objset_hold(zc->zc_name, FTAG, &os);
4315                 if (error)
4316                         return (error);
4317
4318                 error = dmu_objset_userspace_upgrade(os);
4319                 dmu_objset_rele(os, FTAG);
4320         }
4321
4322         return (error);
4323 }
4324
4325 #ifdef sun
4326 /*
4327  * We don't want to have a hard dependency
4328  * against some special symbols in sharefs
4329  * nfs, and smbsrv.  Determine them if needed when
4330  * the first file system is shared.
4331  * Neither sharefs, nfs or smbsrv are unloadable modules.
4332  */
4333 int (*znfsexport_fs)(void *arg);
4334 int (*zshare_fs)(enum sharefs_sys_op, share_t *, uint32_t);
4335 int (*zsmbexport_fs)(void *arg, boolean_t add_share);
4336
4337 int zfs_nfsshare_inited;
4338 int zfs_smbshare_inited;
4339
4340 ddi_modhandle_t nfs_mod;
4341 ddi_modhandle_t sharefs_mod;
4342 ddi_modhandle_t smbsrv_mod;
4343 #endif  /* sun */
4344 kmutex_t zfs_share_lock;
4345
4346 #ifdef sun
4347 static int
4348 zfs_init_sharefs()
4349 {
4350         int error;
4351
4352         ASSERT(MUTEX_HELD(&zfs_share_lock));
4353         /* Both NFS and SMB shares also require sharetab support. */
4354         if (sharefs_mod == NULL && ((sharefs_mod =
4355             ddi_modopen("fs/sharefs",
4356             KRTLD_MODE_FIRST, &error)) == NULL)) {
4357                 return (ENOSYS);
4358         }
4359         if (zshare_fs == NULL && ((zshare_fs =
4360             (int (*)(enum sharefs_sys_op, share_t *, uint32_t))
4361             ddi_modsym(sharefs_mod, "sharefs_impl", &error)) == NULL)) {
4362                 return (ENOSYS);
4363         }
4364         return (0);
4365 }
4366 #endif  /* sun */
4367
4368 static int
4369 zfs_ioc_share(zfs_cmd_t *zc)
4370 {
4371 #ifdef sun
4372         int error;
4373         int opcode;
4374
4375         switch (zc->zc_share.z_sharetype) {
4376         case ZFS_SHARE_NFS:
4377         case ZFS_UNSHARE_NFS:
4378                 if (zfs_nfsshare_inited == 0) {
4379                         mutex_enter(&zfs_share_lock);
4380                         if (nfs_mod == NULL && ((nfs_mod = ddi_modopen("fs/nfs",
4381                             KRTLD_MODE_FIRST, &error)) == NULL)) {
4382                                 mutex_exit(&zfs_share_lock);
4383                                 return (ENOSYS);
4384                         }
4385                         if (znfsexport_fs == NULL &&
4386                             ((znfsexport_fs = (int (*)(void *))
4387                             ddi_modsym(nfs_mod,
4388                             "nfs_export", &error)) == NULL)) {
4389                                 mutex_exit(&zfs_share_lock);
4390                                 return (ENOSYS);
4391                         }
4392                         error = zfs_init_sharefs();
4393                         if (error) {
4394                                 mutex_exit(&zfs_share_lock);
4395                                 return (ENOSYS);
4396                         }
4397                         zfs_nfsshare_inited = 1;
4398                         mutex_exit(&zfs_share_lock);
4399                 }
4400                 break;
4401         case ZFS_SHARE_SMB:
4402         case ZFS_UNSHARE_SMB:
4403                 if (zfs_smbshare_inited == 0) {
4404                         mutex_enter(&zfs_share_lock);
4405                         if (smbsrv_mod == NULL && ((smbsrv_mod =
4406                             ddi_modopen("drv/smbsrv",
4407                             KRTLD_MODE_FIRST, &error)) == NULL)) {
4408                                 mutex_exit(&zfs_share_lock);
4409                                 return (ENOSYS);
4410                         }
4411                         if (zsmbexport_fs == NULL && ((zsmbexport_fs =
4412                             (int (*)(void *, boolean_t))ddi_modsym(smbsrv_mod,
4413                             "smb_server_share", &error)) == NULL)) {
4414                                 mutex_exit(&zfs_share_lock);
4415                                 return (ENOSYS);
4416                         }
4417                         error = zfs_init_sharefs();
4418                         if (error) {
4419                                 mutex_exit(&zfs_share_lock);
4420                                 return (ENOSYS);
4421                         }
4422                         zfs_smbshare_inited = 1;
4423                         mutex_exit(&zfs_share_lock);
4424                 }
4425                 break;
4426         default:
4427                 return (EINVAL);
4428         }
4429
4430         switch (zc->zc_share.z_sharetype) {
4431         case ZFS_SHARE_NFS:
4432         case ZFS_UNSHARE_NFS:
4433                 if (error =
4434                     znfsexport_fs((void *)
4435                     (uintptr_t)zc->zc_share.z_exportdata))
4436                         return (error);
4437                 break;
4438         case ZFS_SHARE_SMB:
4439         case ZFS_UNSHARE_SMB:
4440                 if (error = zsmbexport_fs((void *)
4441                     (uintptr_t)zc->zc_share.z_exportdata,
4442                     zc->zc_share.z_sharetype == ZFS_SHARE_SMB ?
4443                     B_TRUE: B_FALSE)) {
4444                         return (error);
4445                 }
4446                 break;
4447         }
4448
4449         opcode = (zc->zc_share.z_sharetype == ZFS_SHARE_NFS ||
4450             zc->zc_share.z_sharetype == ZFS_SHARE_SMB) ?
4451             SHAREFS_ADD : SHAREFS_REMOVE;
4452
4453         /*
4454          * Add or remove share from sharetab
4455          */
4456         error = zshare_fs(opcode,
4457             (void *)(uintptr_t)zc->zc_share.z_sharedata,
4458             zc->zc_share.z_sharemax);
4459
4460         return (error);
4461
4462 #else   /* !sun */
4463         return (ENOSYS);
4464 #endif  /* !sun */
4465 }
4466
4467 ace_t full_access[] = {
4468         {(uid_t)-1, ACE_ALL_PERMS, ACE_EVERYONE, 0}
4469 };
4470
4471 /*
4472  * inputs:
4473  * zc_name              name of containing filesystem
4474  * zc_obj               object # beyond which we want next in-use object #
4475  *
4476  * outputs:
4477  * zc_obj               next in-use object #
4478  */
4479 static int
4480 zfs_ioc_next_obj(zfs_cmd_t *zc)
4481 {
4482         objset_t *os = NULL;
4483         int error;
4484
4485         error = dmu_objset_hold(zc->zc_name, FTAG, &os);
4486         if (error)
4487                 return (error);
4488
4489         error = dmu_object_next(os, &zc->zc_obj, B_FALSE,
4490             os->os_dsl_dataset->ds_phys->ds_prev_snap_txg);
4491
4492         dmu_objset_rele(os, FTAG);
4493         return (error);
4494 }
4495
4496 /*
4497  * inputs:
4498  * zc_name              name of filesystem
4499  * zc_value             prefix name for snapshot
4500  * zc_cleanup_fd        cleanup-on-exit file descriptor for calling process
4501  *
4502  * outputs:
4503  */
4504 static int
4505 zfs_ioc_tmp_snapshot(zfs_cmd_t *zc)
4506 {
4507         char *snap_name;
4508         int error;
4509
4510         snap_name = kmem_asprintf("%s-%016llx", zc->zc_value,
4511             (u_longlong_t)ddi_get_lbolt64());
4512
4513         if (strlen(snap_name) >= MAXNAMELEN) {
4514                 strfree(snap_name);
4515                 return (E2BIG);
4516         }
4517
4518         error = dmu_objset_snapshot(zc->zc_name, snap_name, snap_name,
4519             NULL, B_FALSE, B_TRUE, zc->zc_cleanup_fd);
4520         if (error != 0) {
4521                 strfree(snap_name);
4522                 return (error);
4523         }
4524
4525         (void) strcpy(zc->zc_value, snap_name);
4526         strfree(snap_name);
4527         return (0);
4528 }
4529
4530 /*
4531  * inputs:
4532  * zc_name              name of "to" snapshot
4533  * zc_value             name of "from" snapshot
4534  * zc_cookie            file descriptor to write diff data on
4535  *
4536  * outputs:
4537  * dmu_diff_record_t's to the file descriptor
4538  */
4539 static int
4540 zfs_ioc_diff(zfs_cmd_t *zc)
4541 {
4542         objset_t *fromsnap;
4543         objset_t *tosnap;
4544         file_t *fp;
4545         offset_t off;
4546         int error;
4547
4548         error = dmu_objset_hold(zc->zc_name, FTAG, &tosnap);
4549         if (error)
4550                 return (error);
4551
4552         error = dmu_objset_hold(zc->zc_value, FTAG, &fromsnap);
4553         if (error) {
4554                 dmu_objset_rele(tosnap, FTAG);
4555                 return (error);
4556         }
4557
4558         fp = getf(zc->zc_cookie);
4559         if (fp == NULL) {
4560                 dmu_objset_rele(fromsnap, FTAG);
4561                 dmu_objset_rele(tosnap, FTAG);
4562                 return (EBADF);
4563         }
4564
4565         off = fp->f_offset;
4566
4567         error = dmu_diff(tosnap, fromsnap, fp, &off);
4568
4569         if (off >= 0 && off <= MAXOFFSET_T)
4570                 fp->f_offset = off;
4571         releasef(zc->zc_cookie);
4572
4573         dmu_objset_rele(fromsnap, FTAG);
4574         dmu_objset_rele(tosnap, FTAG);
4575         return (error);
4576 }
4577
4578 #ifdef sun
4579 /*
4580  * Remove all ACL files in shares dir
4581  */
4582 static int
4583 zfs_smb_acl_purge(znode_t *dzp)
4584 {
4585         zap_cursor_t    zc;
4586         zap_attribute_t zap;
4587         zfsvfs_t *zfsvfs = dzp->z_zfsvfs;
4588         int error;
4589
4590         for (zap_cursor_init(&zc, zfsvfs->z_os, dzp->z_id);
4591             (error = zap_cursor_retrieve(&zc, &zap)) == 0;
4592             zap_cursor_advance(&zc)) {
4593                 if ((error = VOP_REMOVE(ZTOV(dzp), zap.za_name, kcred,
4594                     NULL, 0)) != 0)
4595                         break;
4596         }
4597         zap_cursor_fini(&zc);
4598         return (error);
4599 }
4600 #endif  /* sun */
4601
4602 static int
4603 zfs_ioc_smb_acl(zfs_cmd_t *zc)
4604 {
4605 #ifdef sun
4606         vnode_t *vp;
4607         znode_t *dzp;
4608         vnode_t *resourcevp = NULL;
4609         znode_t *sharedir;
4610         zfsvfs_t *zfsvfs;
4611         nvlist_t *nvlist;
4612         char *src, *target;
4613         vattr_t vattr;
4614         vsecattr_t vsec;
4615         int error = 0;
4616
4617         if ((error = lookupname(zc->zc_value, UIO_SYSSPACE,
4618             NO_FOLLOW, NULL, &vp)) != 0)
4619                 return (error);
4620
4621         /* Now make sure mntpnt and dataset are ZFS */
4622
4623         if (strcmp(vp->v_vfsp->mnt_stat.f_fstypename, "zfs") != 0 ||
4624             (strcmp((char *)refstr_value(vp->v_vfsp->vfs_resource),
4625             zc->zc_name) != 0)) {
4626                 VN_RELE(vp);
4627                 return (EINVAL);
4628         }
4629
4630         dzp = VTOZ(vp);
4631         zfsvfs = dzp->z_zfsvfs;
4632         ZFS_ENTER(zfsvfs);
4633
4634         /*
4635          * Create share dir if its missing.
4636          */
4637         mutex_enter(&zfsvfs->z_lock);
4638         if (zfsvfs->z_shares_dir == 0) {
4639                 dmu_tx_t *tx;
4640
4641                 tx = dmu_tx_create(zfsvfs->z_os);
4642                 dmu_tx_hold_zap(tx, MASTER_NODE_OBJ, TRUE,
4643                     ZFS_SHARES_DIR);
4644                 dmu_tx_hold_zap(tx, DMU_NEW_OBJECT, FALSE, NULL);
4645                 error = dmu_tx_assign(tx, TXG_WAIT);
4646                 if (error) {
4647                         dmu_tx_abort(tx);
4648                 } else {
4649                         error = zfs_create_share_dir(zfsvfs, tx);
4650                         dmu_tx_commit(tx);
4651                 }
4652                 if (error) {
4653                         mutex_exit(&zfsvfs->z_lock);
4654                         VN_RELE(vp);
4655                         ZFS_EXIT(zfsvfs);
4656                         return (error);
4657                 }
4658         }
4659         mutex_exit(&zfsvfs->z_lock);
4660
4661         ASSERT(zfsvfs->z_shares_dir);
4662         if ((error = zfs_zget(zfsvfs, zfsvfs->z_shares_dir, &sharedir)) != 0) {
4663                 VN_RELE(vp);
4664                 ZFS_EXIT(zfsvfs);
4665                 return (error);
4666         }
4667
4668         switch (zc->zc_cookie) {
4669         case ZFS_SMB_ACL_ADD:
4670                 vattr.va_mask = AT_MODE|AT_UID|AT_GID|AT_TYPE;
4671                 vattr.va_type = VREG;
4672                 vattr.va_mode = S_IFREG|0777;
4673                 vattr.va_uid = 0;
4674                 vattr.va_gid = 0;
4675
4676                 vsec.vsa_mask = VSA_ACE;
4677                 vsec.vsa_aclentp = &full_access;
4678                 vsec.vsa_aclentsz = sizeof (full_access);
4679                 vsec.vsa_aclcnt = 1;
4680
4681                 error = VOP_CREATE(ZTOV(sharedir), zc->zc_string,
4682                     &vattr, EXCL, 0, &resourcevp, kcred, 0, NULL, &vsec);
4683                 if (resourcevp)
4684                         VN_RELE(resourcevp);
4685                 break;
4686
4687         case ZFS_SMB_ACL_REMOVE:
4688                 error = VOP_REMOVE(ZTOV(sharedir), zc->zc_string, kcred,
4689                     NULL, 0);
4690                 break;
4691
4692         case ZFS_SMB_ACL_RENAME:
4693                 if ((error = get_nvlist(zc->zc_nvlist_src,
4694                     zc->zc_nvlist_src_size, zc->zc_iflags, &nvlist)) != 0) {
4695                         VN_RELE(vp);
4696                         ZFS_EXIT(zfsvfs);
4697                         return (error);
4698                 }
4699                 if (nvlist_lookup_string(nvlist, ZFS_SMB_ACL_SRC, &src) ||
4700                     nvlist_lookup_string(nvlist, ZFS_SMB_ACL_TARGET,
4701                     &target)) {
4702                         VN_RELE(vp);
4703                         VN_RELE(ZTOV(sharedir));
4704                         ZFS_EXIT(zfsvfs);
4705                         nvlist_free(nvlist);
4706                         return (error);
4707                 }
4708                 error = VOP_RENAME(ZTOV(sharedir), src, ZTOV(sharedir), target,
4709                     kcred, NULL, 0);
4710                 nvlist_free(nvlist);
4711                 break;
4712
4713         case ZFS_SMB_ACL_PURGE:
4714                 error = zfs_smb_acl_purge(sharedir);
4715                 break;
4716
4717         default:
4718                 error = EINVAL;
4719                 break;
4720         }
4721
4722         VN_RELE(vp);
4723         VN_RELE(ZTOV(sharedir));
4724
4725         ZFS_EXIT(zfsvfs);
4726
4727         return (error);
4728 #else   /* !sun */
4729         return (EOPNOTSUPP);
4730 #endif  /* !sun */
4731 }
4732
4733 /*
4734  * inputs:
4735  * zc_name              name of filesystem
4736  * zc_value             short name of snap
4737  * zc_string            user-supplied tag for this hold
4738  * zc_cookie            recursive flag
4739  * zc_temphold          set if hold is temporary
4740  * zc_cleanup_fd        cleanup-on-exit file descriptor for calling process
4741  * zc_sendobj           if non-zero, the objid for zc_name@zc_value
4742  * zc_createtxg         if zc_sendobj is non-zero, snap must have zc_createtxg
4743  *
4744  * outputs:             none
4745  */
4746 static int
4747 zfs_ioc_hold(zfs_cmd_t *zc)
4748 {
4749         boolean_t recursive = zc->zc_cookie;
4750         spa_t *spa;
4751         dsl_pool_t *dp;
4752         dsl_dataset_t *ds;
4753         int error;
4754         minor_t minor = 0;
4755
4756         if (snapshot_namecheck(zc->zc_value, NULL, NULL) != 0)
4757                 return (EINVAL);
4758
4759         if (zc->zc_sendobj == 0) {
4760                 return (dsl_dataset_user_hold(zc->zc_name, zc->zc_value,
4761                     zc->zc_string, recursive, zc->zc_temphold,
4762                     zc->zc_cleanup_fd));
4763         }
4764
4765         if (recursive)
4766                 return (EINVAL);
4767
4768         error = spa_open(zc->zc_name, &spa, FTAG);
4769         if (error)
4770                 return (error);
4771
4772         dp = spa_get_dsl(spa);
4773         rw_enter(&dp->dp_config_rwlock, RW_READER);
4774         error = dsl_dataset_hold_obj(dp, zc->zc_sendobj, FTAG, &ds);
4775         rw_exit(&dp->dp_config_rwlock);
4776         spa_close(spa, FTAG);
4777         if (error)
4778                 return (error);
4779
4780         /*
4781          * Until we have a hold on this snapshot, it's possible that
4782          * zc_sendobj could've been destroyed and reused as part
4783          * of a later txg.  Make sure we're looking at the right object.
4784          */
4785         if (zc->zc_createtxg != ds->ds_phys->ds_creation_txg) {
4786                 dsl_dataset_rele(ds, FTAG);
4787                 return (ENOENT);
4788         }
4789
4790         if (zc->zc_cleanup_fd != -1 && zc->zc_temphold) {
4791                 error = zfs_onexit_fd_hold(zc->zc_cleanup_fd, &minor);
4792                 if (error) {
4793                         dsl_dataset_rele(ds, FTAG);
4794                         return (error);
4795                 }
4796         }
4797
4798         error = dsl_dataset_user_hold_for_send(ds, zc->zc_string,
4799             zc->zc_temphold);
4800         if (minor != 0) {
4801                 if (error == 0) {
4802                         dsl_register_onexit_hold_cleanup(ds, zc->zc_string,
4803                             minor);
4804                 }
4805                 zfs_onexit_fd_rele(zc->zc_cleanup_fd);
4806         }
4807         dsl_dataset_rele(ds, FTAG);
4808
4809         return (error);
4810 }
4811
4812 /*
4813  * inputs:
4814  * zc_name      name of dataset from which we're releasing a user hold
4815  * zc_value     short name of snap
4816  * zc_string    user-supplied tag for this hold
4817  * zc_cookie    recursive flag
4818  *
4819  * outputs:     none
4820  */
4821 static int
4822 zfs_ioc_release(zfs_cmd_t *zc)
4823 {
4824         boolean_t recursive = zc->zc_cookie;
4825
4826         if (snapshot_namecheck(zc->zc_value, NULL, NULL) != 0)
4827                 return (EINVAL);
4828
4829         return (dsl_dataset_user_release(zc->zc_name, zc->zc_value,
4830             zc->zc_string, recursive));
4831 }
4832
4833 /*
4834  * inputs:
4835  * zc_name              name of filesystem
4836  *
4837  * outputs:
4838  * zc_nvlist_src{_size} nvlist of snapshot holds
4839  */
4840 static int
4841 zfs_ioc_get_holds(zfs_cmd_t *zc)
4842 {
4843         nvlist_t *nvp;
4844         int error;
4845
4846         if ((error = dsl_dataset_get_holds(zc->zc_name, &nvp)) == 0) {
4847                 error = put_nvlist(zc, nvp);
4848                 nvlist_free(nvp);
4849         }
4850
4851         return (error);
4852 }
4853
4854 /*
4855  * inputs:
4856  * zc_name              name of new filesystem or snapshot
4857  * zc_value             full name of old snapshot
4858  *
4859  * outputs:
4860  * zc_cookie            space in bytes
4861  * zc_objset_type       compressed space in bytes
4862  * zc_perm_action       uncompressed space in bytes
4863  */
4864 static int
4865 zfs_ioc_space_written(zfs_cmd_t *zc)
4866 {
4867         int error;
4868         dsl_dataset_t *new, *old;
4869
4870         error = dsl_dataset_hold(zc->zc_name, FTAG, &new);
4871         if (error != 0)
4872                 return (error);
4873         error = dsl_dataset_hold(zc->zc_value, FTAG, &old);
4874         if (error != 0) {
4875                 dsl_dataset_rele(new, FTAG);
4876                 return (error);
4877         }
4878
4879         error = dsl_dataset_space_written(old, new, &zc->zc_cookie,
4880             &zc->zc_objset_type, &zc->zc_perm_action);
4881         dsl_dataset_rele(old, FTAG);
4882         dsl_dataset_rele(new, FTAG);
4883         return (error);
4884 }
4885
4886 /*
4887  * inputs:
4888  * zc_name              full name of last snapshot
4889  * zc_value             full name of first snapshot
4890  *
4891  * outputs:
4892  * zc_cookie            space in bytes
4893  * zc_objset_type       compressed space in bytes
4894  * zc_perm_action       uncompressed space in bytes
4895  */
4896 static int
4897 zfs_ioc_space_snaps(zfs_cmd_t *zc)
4898 {
4899         int error;
4900         dsl_dataset_t *new, *old;
4901
4902         error = dsl_dataset_hold(zc->zc_name, FTAG, &new);
4903         if (error != 0)
4904                 return (error);
4905         error = dsl_dataset_hold(zc->zc_value, FTAG, &old);
4906         if (error != 0) {
4907                 dsl_dataset_rele(new, FTAG);
4908                 return (error);
4909         }
4910
4911         error = dsl_dataset_space_wouldfree(old, new, &zc->zc_cookie,
4912             &zc->zc_objset_type, &zc->zc_perm_action);
4913         dsl_dataset_rele(old, FTAG);
4914         dsl_dataset_rele(new, FTAG);
4915         return (error);
4916 }
4917
4918 /*
4919  * pool create, destroy, and export don't log the history as part of
4920  * zfsdev_ioctl, but rather zfs_ioc_pool_create, and zfs_ioc_pool_export
4921  * do the logging of those commands.
4922  */
4923 static int
4924 zfs_ioc_jail(zfs_cmd_t *zc)
4925 {
4926
4927         return (zone_dataset_attach(curthread->td_ucred, zc->zc_name,
4928             (int)zc->zc_jailid));
4929 }
4930
4931 static int
4932 zfs_ioc_unjail(zfs_cmd_t *zc)
4933 {
4934
4935         return (zone_dataset_detach(curthread->td_ucred, zc->zc_name,
4936             (int)zc->zc_jailid));
4937 }
4938
4939 static zfs_ioc_vec_t zfs_ioc_vec[] = {
4940         { zfs_ioc_pool_create, zfs_secpolicy_config, POOL_NAME, B_FALSE,
4941             B_FALSE },
4942         { zfs_ioc_pool_destroy, zfs_secpolicy_config, POOL_NAME, B_FALSE,
4943             B_FALSE },
4944         { zfs_ioc_pool_import, zfs_secpolicy_config, POOL_NAME, B_TRUE,
4945             B_FALSE },
4946         { zfs_ioc_pool_export, zfs_secpolicy_config, POOL_NAME, B_FALSE,
4947             B_FALSE },
4948         { zfs_ioc_pool_configs, zfs_secpolicy_none, NO_NAME, B_FALSE,
4949             B_FALSE },
4950         { zfs_ioc_pool_stats, zfs_secpolicy_read, POOL_NAME, B_FALSE,
4951             B_FALSE },
4952         { zfs_ioc_pool_tryimport, zfs_secpolicy_config, NO_NAME, B_FALSE,
4953             B_FALSE },
4954         { zfs_ioc_pool_scan, zfs_secpolicy_config, POOL_NAME, B_TRUE,
4955             B_TRUE },
4956         { zfs_ioc_pool_freeze, zfs_secpolicy_config, NO_NAME, B_FALSE,
4957             B_FALSE },
4958         { zfs_ioc_pool_upgrade, zfs_secpolicy_config, POOL_NAME, B_TRUE,
4959             B_TRUE },
4960         { zfs_ioc_pool_get_history, zfs_secpolicy_config, POOL_NAME, B_FALSE,
4961             B_FALSE },
4962         { zfs_ioc_vdev_add, zfs_secpolicy_config, POOL_NAME, B_TRUE,
4963             B_TRUE },
4964         { zfs_ioc_vdev_remove, zfs_secpolicy_config, POOL_NAME, B_TRUE,
4965             B_TRUE },
4966         { zfs_ioc_vdev_set_state, zfs_secpolicy_config, POOL_NAME, B_TRUE,
4967             B_FALSE },
4968         { zfs_ioc_vdev_attach, zfs_secpolicy_config, POOL_NAME, B_TRUE,
4969             B_TRUE },
4970         { zfs_ioc_vdev_detach, zfs_secpolicy_config, POOL_NAME, B_TRUE,
4971             B_TRUE },
4972         { zfs_ioc_vdev_setpath, zfs_secpolicy_config, POOL_NAME, B_FALSE,
4973             B_TRUE },
4974         { zfs_ioc_vdev_setfru,  zfs_secpolicy_config, POOL_NAME, B_FALSE,
4975             B_TRUE },
4976         { zfs_ioc_objset_stats, zfs_secpolicy_read, DATASET_NAME, B_FALSE,
4977             B_TRUE },
4978         { zfs_ioc_objset_zplprops, zfs_secpolicy_read, DATASET_NAME, B_FALSE,
4979             B_FALSE },
4980         { zfs_ioc_dataset_list_next, zfs_secpolicy_read, DATASET_NAME, B_FALSE,
4981             B_TRUE },
4982         { zfs_ioc_snapshot_list_next, zfs_secpolicy_read, DATASET_NAME, B_FALSE,
4983             B_TRUE },
4984         { zfs_ioc_set_prop, zfs_secpolicy_none, DATASET_NAME, B_TRUE, B_TRUE },
4985         { zfs_ioc_create, zfs_secpolicy_create, DATASET_NAME, B_TRUE, B_TRUE },
4986         { zfs_ioc_destroy, zfs_secpolicy_destroy, DATASET_NAME, B_TRUE,
4987             B_TRUE},
4988         { zfs_ioc_rollback, zfs_secpolicy_rollback, DATASET_NAME, B_TRUE,
4989             B_TRUE },
4990         { zfs_ioc_rename, zfs_secpolicy_rename, DATASET_NAME, B_TRUE, B_TRUE },
4991         { zfs_ioc_recv, zfs_secpolicy_receive, DATASET_NAME, B_TRUE, B_TRUE },
4992         { zfs_ioc_send, zfs_secpolicy_send, DATASET_NAME, B_FALSE, B_FALSE },
4993         { zfs_ioc_inject_fault, zfs_secpolicy_inject, NO_NAME, B_FALSE,
4994             B_FALSE },
4995         { zfs_ioc_clear_fault, zfs_secpolicy_inject, NO_NAME, B_FALSE,
4996             B_FALSE },
4997         { zfs_ioc_inject_list_next, zfs_secpolicy_inject, NO_NAME, B_FALSE,
4998             B_FALSE },
4999         { zfs_ioc_error_log, zfs_secpolicy_inject, POOL_NAME, B_FALSE,
5000             B_FALSE },
5001         { zfs_ioc_clear, zfs_secpolicy_config, POOL_NAME, B_TRUE, B_FALSE },
5002         { zfs_ioc_promote, zfs_secpolicy_promote, DATASET_NAME, B_TRUE,
5003             B_TRUE },
5004         { zfs_ioc_destroy_snaps_nvl, zfs_secpolicy_destroy_recursive, DATASET_NAME,
5005             B_TRUE, B_TRUE },
5006         { zfs_ioc_snapshot, zfs_secpolicy_snapshot, DATASET_NAME, B_TRUE,
5007             B_TRUE },
5008         { zfs_ioc_dsobj_to_dsname, zfs_secpolicy_diff, POOL_NAME, B_FALSE,
5009             B_FALSE },
5010         { zfs_ioc_obj_to_path, zfs_secpolicy_diff, DATASET_NAME, B_FALSE,
5011             B_TRUE },
5012         { zfs_ioc_pool_set_props, zfs_secpolicy_config, POOL_NAME, B_TRUE,
5013             B_TRUE },
5014         { zfs_ioc_pool_get_props, zfs_secpolicy_read, POOL_NAME, B_FALSE,
5015             B_FALSE },
5016         { zfs_ioc_set_fsacl, zfs_secpolicy_fsacl, DATASET_NAME, B_TRUE,
5017             B_TRUE },
5018         { zfs_ioc_get_fsacl, zfs_secpolicy_read, DATASET_NAME, B_FALSE,
5019             B_FALSE },
5020         { zfs_ioc_share, zfs_secpolicy_share, DATASET_NAME, B_FALSE, B_FALSE },
5021         { zfs_ioc_inherit_prop, zfs_secpolicy_inherit, DATASET_NAME, B_TRUE,
5022             B_TRUE },
5023         { zfs_ioc_smb_acl, zfs_secpolicy_smb_acl, DATASET_NAME, B_FALSE,
5024             B_FALSE },
5025         { zfs_ioc_userspace_one, zfs_secpolicy_userspace_one,
5026             DATASET_NAME, B_FALSE, B_FALSE },
5027         { zfs_ioc_userspace_many, zfs_secpolicy_userspace_many,
5028             DATASET_NAME, B_FALSE, B_FALSE },
5029         { zfs_ioc_userspace_upgrade, zfs_secpolicy_userspace_upgrade,
5030             DATASET_NAME, B_FALSE, B_TRUE },
5031         { zfs_ioc_hold, zfs_secpolicy_hold, DATASET_NAME, B_TRUE, B_TRUE },
5032         { zfs_ioc_release, zfs_secpolicy_release, DATASET_NAME, B_TRUE,
5033             B_TRUE },
5034         { zfs_ioc_get_holds, zfs_secpolicy_read, DATASET_NAME, B_FALSE,
5035             B_TRUE },
5036         { zfs_ioc_objset_recvd_props, zfs_secpolicy_read, DATASET_NAME, B_FALSE,
5037             B_FALSE },
5038         { zfs_ioc_vdev_split, zfs_secpolicy_config, POOL_NAME, B_TRUE,
5039             B_TRUE },
5040         { zfs_ioc_next_obj, zfs_secpolicy_read, DATASET_NAME, B_FALSE,
5041             B_FALSE },
5042         { zfs_ioc_diff, zfs_secpolicy_diff, DATASET_NAME, B_FALSE, B_FALSE },
5043         { zfs_ioc_tmp_snapshot, zfs_secpolicy_tmp_snapshot, DATASET_NAME,
5044             B_FALSE, B_FALSE },
5045         { zfs_ioc_obj_to_stats, zfs_secpolicy_diff, DATASET_NAME, B_FALSE,
5046             B_TRUE },
5047         { zfs_ioc_jail, zfs_secpolicy_config, DATASET_NAME, B_TRUE, B_FALSE },
5048         { zfs_ioc_unjail, zfs_secpolicy_config, DATASET_NAME, B_TRUE, B_FALSE },
5049         { zfs_ioc_pool_reguid, zfs_secpolicy_config, POOL_NAME, B_TRUE,
5050             B_TRUE },
5051         { zfs_ioc_space_written, zfs_secpolicy_read, DATASET_NAME, B_FALSE,
5052             B_TRUE },
5053         { zfs_ioc_space_snaps, zfs_secpolicy_read, DATASET_NAME, B_FALSE,
5054             B_TRUE },
5055         { zfs_ioc_send_progress, zfs_secpolicy_read, DATASET_NAME, B_FALSE,
5056             B_FALSE },
5057         { zfs_ioc_pool_reopen, zfs_secpolicy_config, POOL_NAME, B_TRUE,
5058             B_TRUE },
5059 };
5060
5061 int
5062 pool_status_check(const char *name, zfs_ioc_namecheck_t type)
5063 {
5064         spa_t *spa;
5065         int error;
5066
5067         ASSERT(type == POOL_NAME || type == DATASET_NAME);
5068
5069         error = spa_open(name, &spa, FTAG);
5070         if (error == 0) {
5071                 if (spa_suspended(spa))
5072                         error = EAGAIN;
5073                 spa_close(spa, FTAG);
5074         }
5075         return (error);
5076 }
5077
5078 /*
5079  * Find a free minor number.
5080  */
5081 minor_t
5082 zfsdev_minor_alloc(void)
5083 {
5084         static minor_t last_minor;
5085         minor_t m;
5086
5087         ASSERT(MUTEX_HELD(&spa_namespace_lock));
5088
5089         for (m = last_minor + 1; m != last_minor; m++) {
5090                 if (m > ZFSDEV_MAX_MINOR)
5091                         m = 1;
5092                 if (ddi_get_soft_state(zfsdev_state, m) == NULL) {
5093                         last_minor = m;
5094                         return (m);
5095                 }
5096         }
5097
5098         return (0);
5099 }
5100
5101 static int
5102 zfs_ctldev_init(struct cdev *devp)
5103 {
5104         minor_t minor;
5105         zfs_soft_state_t *zs;
5106
5107         ASSERT(MUTEX_HELD(&spa_namespace_lock));
5108
5109         minor = zfsdev_minor_alloc();
5110         if (minor == 0)
5111                 return (ENXIO);
5112
5113         if (ddi_soft_state_zalloc(zfsdev_state, minor) != DDI_SUCCESS)
5114                 return (EAGAIN);
5115
5116         devfs_set_cdevpriv((void *)(uintptr_t)minor, zfsdev_close);
5117
5118         zs = ddi_get_soft_state(zfsdev_state, minor);
5119         zs->zss_type = ZSST_CTLDEV;
5120         zfs_onexit_init((zfs_onexit_t **)&zs->zss_data);
5121
5122         return (0);
5123 }
5124
5125 static void
5126 zfs_ctldev_destroy(zfs_onexit_t *zo, minor_t minor)
5127 {
5128         ASSERT(MUTEX_HELD(&spa_namespace_lock));
5129
5130         zfs_onexit_destroy(zo);
5131         ddi_soft_state_free(zfsdev_state, minor);
5132 }
5133
5134 void *
5135 zfsdev_get_soft_state(minor_t minor, enum zfs_soft_state_type which)
5136 {
5137         zfs_soft_state_t *zp;
5138
5139         zp = ddi_get_soft_state(zfsdev_state, minor);
5140         if (zp == NULL || zp->zss_type != which)
5141                 return (NULL);
5142
5143         return (zp->zss_data);
5144 }
5145
5146 static int
5147 zfsdev_open(struct cdev *devp, int flag, int mode, struct thread *td)
5148 {
5149         int error = 0;
5150
5151 #ifdef sun
5152         if (getminor(*devp) != 0)
5153                 return (zvol_open(devp, flag, otyp, cr));
5154 #endif
5155
5156         /* This is the control device. Allocate a new minor if requested. */
5157         if (flag & FEXCL) {
5158                 mutex_enter(&spa_namespace_lock);
5159                 error = zfs_ctldev_init(devp);
5160                 mutex_exit(&spa_namespace_lock);
5161         }
5162
5163         return (error);
5164 }
5165
5166 static void
5167 zfsdev_close(void *data)
5168 {
5169         zfs_onexit_t *zo;
5170         minor_t minor = (minor_t)(uintptr_t)data;
5171
5172         if (minor == 0)
5173                 return;
5174
5175         mutex_enter(&spa_namespace_lock);
5176         zo = zfsdev_get_soft_state(minor, ZSST_CTLDEV);
5177         if (zo == NULL) {
5178                 mutex_exit(&spa_namespace_lock);
5179                 return;
5180         }
5181         zfs_ctldev_destroy(zo, minor);
5182         mutex_exit(&spa_namespace_lock);
5183 }
5184
5185 static int
5186 zfsdev_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
5187     struct thread *td)
5188 {
5189         zfs_cmd_t *zc;
5190         uint_t vec;
5191         int cflag, error, len;
5192
5193         cflag = ZFS_CMD_COMPAT_NONE;
5194         len = IOCPARM_LEN(cmd);
5195
5196         /*
5197          * Check if we have sufficient kernel memory allocated
5198          * for the zfs_cmd_t request.  Bail out if not so we
5199          * will not access undefined memory region.
5200          */
5201         if (len < sizeof(zfs_cmd_t))
5202                 if (len == sizeof(zfs_cmd_v15_t)) {
5203                         cflag = ZFS_CMD_COMPAT_V15;
5204                         vec = zfs_ioctl_v15_to_v28[ZFS_IOC(cmd)];
5205                 } else
5206                         return (EINVAL);
5207         else
5208                 vec = ZFS_IOC(cmd);
5209
5210         if (cflag != ZFS_CMD_COMPAT_NONE) {
5211                 if (vec == ZFS_IOC_COMPAT_PASS)
5212                         return (0);
5213                 else if (vec == ZFS_IOC_COMPAT_FAIL)
5214                         return (ENOTSUP);
5215         }
5216
5217         if (vec >= sizeof (zfs_ioc_vec) / sizeof (zfs_ioc_vec[0]))
5218                 return (EINVAL);
5219
5220         if (cflag != ZFS_CMD_COMPAT_NONE) {
5221                 zc = kmem_zalloc(sizeof(zfs_cmd_t), KM_SLEEP);
5222                 bzero(zc, sizeof(zfs_cmd_t));
5223                 zfs_cmd_compat_get(zc, addr, cflag);
5224                 zfs_ioctl_compat_pre(zc, &vec, cflag);
5225         } else {
5226                 zc = (void *)addr;
5227         }
5228
5229         error = zfs_ioc_vec[vec].zvec_secpolicy(zc, td->td_ucred);
5230
5231         /*
5232          * Ensure that all pool/dataset names are valid before we pass down to
5233          * the lower layers.
5234          */
5235         if (error == 0) {
5236                 zc->zc_name[sizeof (zc->zc_name) - 1] = '\0';
5237                 zc->zc_iflags = flag & FKIOCTL;
5238                 switch (zfs_ioc_vec[vec].zvec_namecheck) {
5239                 case POOL_NAME:
5240                         if (pool_namecheck(zc->zc_name, NULL, NULL) != 0)
5241                                 error = EINVAL;
5242                         if (zfs_ioc_vec[vec].zvec_pool_check)
5243                                 error = pool_status_check(zc->zc_name,
5244                                     zfs_ioc_vec[vec].zvec_namecheck);
5245                         break;
5246
5247                 case DATASET_NAME:
5248                         if (dataset_namecheck(zc->zc_name, NULL, NULL) != 0)
5249                                 error = EINVAL;
5250                         if (zfs_ioc_vec[vec].zvec_pool_check)
5251                                 error = pool_status_check(zc->zc_name,
5252                                     zfs_ioc_vec[vec].zvec_namecheck);
5253                         break;
5254
5255                 case NO_NAME:
5256                         break;
5257                 }
5258         }
5259
5260         if (error == 0)
5261                 error = zfs_ioc_vec[vec].zvec_func(zc);
5262
5263         if (error == 0) {
5264                 if (zfs_ioc_vec[vec].zvec_his_log)
5265                         zfs_log_history(zc);
5266         }
5267
5268         if (cflag != ZFS_CMD_COMPAT_NONE) {
5269                 zfs_ioctl_compat_post(zc, ZFS_IOC(cmd), cflag);
5270                 zfs_cmd_compat_put(zc, addr, cflag);
5271                 kmem_free(zc, sizeof(zfs_cmd_t));
5272         }
5273
5274         return (error);
5275 }
5276
5277 #ifdef sun
5278 static int
5279 zfs_attach(dev_info_t *dip, ddi_attach_cmd_t cmd)
5280 {
5281         if (cmd != DDI_ATTACH)
5282                 return (DDI_FAILURE);
5283
5284         if (ddi_create_minor_node(dip, "zfs", S_IFCHR, 0,
5285             DDI_PSEUDO, 0) == DDI_FAILURE)
5286                 return (DDI_FAILURE);
5287
5288         zfs_dip = dip;
5289
5290         ddi_report_dev(dip);
5291
5292         return (DDI_SUCCESS);
5293 }
5294
5295 static int
5296 zfs_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
5297 {
5298         if (spa_busy() || zfs_busy() || zvol_busy())
5299                 return (DDI_FAILURE);
5300
5301         if (cmd != DDI_DETACH)
5302                 return (DDI_FAILURE);
5303
5304         zfs_dip = NULL;
5305
5306         ddi_prop_remove_all(dip);
5307         ddi_remove_minor_node(dip, NULL);
5308
5309         return (DDI_SUCCESS);
5310 }
5311
5312 /*ARGSUSED*/
5313 static int
5314 zfs_info(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg, void **result)
5315 {
5316         switch (infocmd) {
5317         case DDI_INFO_DEVT2DEVINFO:
5318                 *result = zfs_dip;
5319                 return (DDI_SUCCESS);
5320
5321         case DDI_INFO_DEVT2INSTANCE:
5322                 *result = (void *)0;
5323                 return (DDI_SUCCESS);
5324         }
5325
5326         return (DDI_FAILURE);
5327 }
5328 #endif  /* sun */
5329
5330 /*
5331  * OK, so this is a little weird.
5332  *
5333  * /dev/zfs is the control node, i.e. minor 0.
5334  * /dev/zvol/[r]dsk/pool/dataset are the zvols, minor > 0.
5335  *
5336  * /dev/zfs has basically nothing to do except serve up ioctls,
5337  * so most of the standard driver entry points are in zvol.c.
5338  */
5339 #ifdef sun
5340 static struct cb_ops zfs_cb_ops = {
5341         zfsdev_open,    /* open */
5342         zfsdev_close,   /* close */
5343         zvol_strategy,  /* strategy */
5344         nodev,          /* print */
5345         zvol_dump,      /* dump */
5346         zvol_read,      /* read */
5347         zvol_write,     /* write */
5348         zfsdev_ioctl,   /* ioctl */
5349         nodev,          /* devmap */
5350         nodev,          /* mmap */
5351         nodev,          /* segmap */
5352         nochpoll,       /* poll */
5353         ddi_prop_op,    /* prop_op */
5354         NULL,           /* streamtab */
5355         D_NEW | D_MP | D_64BIT,         /* Driver compatibility flag */
5356         CB_REV,         /* version */
5357         nodev,          /* async read */
5358         nodev,          /* async write */
5359 };
5360
5361 static struct dev_ops zfs_dev_ops = {
5362         DEVO_REV,       /* version */
5363         0,              /* refcnt */
5364         zfs_info,       /* info */
5365         nulldev,        /* identify */
5366         nulldev,        /* probe */
5367         zfs_attach,     /* attach */
5368         zfs_detach,     /* detach */
5369         nodev,          /* reset */
5370         &zfs_cb_ops,    /* driver operations */
5371         NULL,           /* no bus operations */
5372         NULL,           /* power */
5373         ddi_quiesce_not_needed, /* quiesce */
5374 };
5375
5376 static struct modldrv zfs_modldrv = {
5377         &mod_driverops,
5378         "ZFS storage pool",
5379         &zfs_dev_ops
5380 };
5381
5382 static struct modlinkage modlinkage = {
5383         MODREV_1,
5384         (void *)&zfs_modlfs,
5385         (void *)&zfs_modldrv,
5386         NULL
5387 };
5388 #endif  /* sun */
5389
5390 static struct cdevsw zfs_cdevsw = {
5391         .d_version =    D_VERSION,
5392         .d_open =       zfsdev_open,
5393         .d_ioctl =      zfsdev_ioctl,
5394         .d_name =       ZFS_DEV_NAME
5395 };
5396
5397 static void
5398 zfsdev_init(void)
5399 {
5400         zfsdev = make_dev(&zfs_cdevsw, 0x0, UID_ROOT, GID_OPERATOR, 0666,
5401             ZFS_DEV_NAME);
5402 }
5403
5404 static void
5405 zfsdev_fini(void)
5406 {
5407         if (zfsdev != NULL)
5408                 destroy_dev(zfsdev);
5409 }
5410
5411 static struct root_hold_token *zfs_root_token;
5412 struct proc *zfsproc;
5413
5414 uint_t zfs_fsyncer_key;
5415 extern uint_t rrw_tsd_key;
5416
5417 #ifdef sun
5418 int
5419 _init(void)
5420 {
5421         int error;
5422
5423         spa_init(FREAD | FWRITE);
5424         zfs_init();
5425         zvol_init();
5426
5427         if ((error = mod_install(&modlinkage)) != 0) {
5428                 zvol_fini();
5429                 zfs_fini();
5430                 spa_fini();
5431                 return (error);
5432         }
5433
5434         tsd_create(&zfs_fsyncer_key, NULL);
5435         tsd_create(&rrw_tsd_key, NULL);
5436
5437         error = ldi_ident_from_mod(&modlinkage, &zfs_li);
5438         ASSERT(error == 0);
5439         mutex_init(&zfs_share_lock, NULL, MUTEX_DEFAULT, NULL);
5440
5441         return (0);
5442 }
5443
5444 int
5445 _fini(void)
5446 {
5447         int error;
5448
5449         if (spa_busy() || zfs_busy() || zvol_busy() || zio_injection_enabled)
5450                 return (EBUSY);
5451
5452         if ((error = mod_remove(&modlinkage)) != 0)
5453                 return (error);
5454
5455         zvol_fini();
5456         zfs_fini();
5457         spa_fini();
5458         if (zfs_nfsshare_inited)
5459                 (void) ddi_modclose(nfs_mod);
5460         if (zfs_smbshare_inited)
5461                 (void) ddi_modclose(smbsrv_mod);
5462         if (zfs_nfsshare_inited || zfs_smbshare_inited)
5463                 (void) ddi_modclose(sharefs_mod);
5464
5465         tsd_destroy(&zfs_fsyncer_key);
5466         ldi_ident_release(zfs_li);
5467         zfs_li = NULL;
5468         mutex_destroy(&zfs_share_lock);
5469
5470         return (error);
5471 }
5472
5473 int
5474 _info(struct modinfo *modinfop)
5475 {
5476         return (mod_info(&modlinkage, modinfop));
5477 }
5478 #endif  /* sun */
5479
5480 static int
5481 zfs_modevent(module_t mod, int type, void *unused __unused)
5482 {
5483         int error = 0;
5484
5485         switch (type) {
5486         case MOD_LOAD:
5487                 zfs_root_token = root_mount_hold("ZFS");
5488
5489                 mutex_init(&zfs_share_lock, NULL, MUTEX_DEFAULT, NULL);
5490
5491                 spa_init(FREAD | FWRITE);
5492                 zfs_init();
5493                 zvol_init();
5494
5495                 tsd_create(&zfs_fsyncer_key, NULL);
5496                 tsd_create(&rrw_tsd_key, NULL);
5497
5498                 printf("ZFS storage pool version: features support (" SPA_VERSION_STRING ")\n");
5499                 root_mount_rel(zfs_root_token);
5500
5501                 zfsdev_init();
5502                 break;
5503         case MOD_UNLOAD:
5504                 if (spa_busy() || zfs_busy() || zvol_busy() ||
5505                     zio_injection_enabled) {
5506                         error = EBUSY;
5507                         break;
5508                 }
5509
5510                 zfsdev_fini();
5511                 zvol_fini();
5512                 zfs_fini();
5513                 spa_fini();
5514
5515                 tsd_destroy(&zfs_fsyncer_key);
5516                 tsd_destroy(&rrw_tsd_key);
5517
5518                 mutex_destroy(&zfs_share_lock);
5519                 break;
5520         default:
5521                 error = EOPNOTSUPP;
5522                 break;
5523         }
5524         return (error);
5525 }
5526
5527 static moduledata_t zfs_mod = {
5528         "zfsctrl",
5529         zfs_modevent,
5530         0
5531 };
5532 DECLARE_MODULE(zfsctrl, zfs_mod, SI_SUB_VFS, SI_ORDER_ANY);
5533 MODULE_DEPEND(zfsctrl, opensolaris, 1, 1, 1);
5534 MODULE_DEPEND(zfsctrl, krpc, 1, 1, 1);
5535 MODULE_DEPEND(zfsctrl, acl_nfs4, 1, 1, 1);