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