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