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