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