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