]> CyberLeo.Net >> Repos - FreeBSD/stable/8.git/blob - cddl/contrib/opensolaris/lib/libzfs/common/libzfs_dataset.c
MFC r209962, r211970-r211972, r212050, r212605, r212611
[FreeBSD/stable/8.git] / cddl / contrib / opensolaris / lib / libzfs / common / libzfs_dataset.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 2009 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26
27 #include <assert.h>
28 #include <ctype.h>
29 #include <errno.h>
30 #include <libintl.h>
31 #include <math.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <strings.h>
35 #include <unistd.h>
36 #include <stddef.h>
37 #include <zone.h>
38 #include <fcntl.h>
39 #include <sys/mntent.h>
40 #include <sys/mount.h>
41 #include <sys/avl.h>
42 #include <priv.h>
43 #include <pwd.h>
44 #include <grp.h>
45 #include <stddef.h>
46 #include <idmap.h>
47
48 #include <sys/spa.h>
49 #include <sys/zap.h>
50 #include <sys/misc.h>
51 #include <libzfs.h>
52
53 #include "zfs_namecheck.h"
54 #include "zfs_prop.h"
55 #include "libzfs_impl.h"
56 #include "zfs_deleg.h"
57
58 static int zvol_create_link_common(libzfs_handle_t *, const char *, int);
59 static int userquota_propname_decode(const char *propname, boolean_t zoned,
60     zfs_userquota_prop_t *typep, char *domain, int domainlen, uint64_t *ridp);
61
62 /*
63  * Given a single type (not a mask of types), return the type in a human
64  * readable form.
65  */
66 const char *
67 zfs_type_to_name(zfs_type_t type)
68 {
69         switch (type) {
70         case ZFS_TYPE_FILESYSTEM:
71                 return (dgettext(TEXT_DOMAIN, "filesystem"));
72         case ZFS_TYPE_SNAPSHOT:
73                 return (dgettext(TEXT_DOMAIN, "snapshot"));
74         case ZFS_TYPE_VOLUME:
75                 return (dgettext(TEXT_DOMAIN, "volume"));
76         }
77
78         return (NULL);
79 }
80
81 /*
82  * Given a path and mask of ZFS types, return a string describing this dataset.
83  * This is used when we fail to open a dataset and we cannot get an exact type.
84  * We guess what the type would have been based on the path and the mask of
85  * acceptable types.
86  */
87 static const char *
88 path_to_str(const char *path, int types)
89 {
90         /*
91          * When given a single type, always report the exact type.
92          */
93         if (types == ZFS_TYPE_SNAPSHOT)
94                 return (dgettext(TEXT_DOMAIN, "snapshot"));
95         if (types == ZFS_TYPE_FILESYSTEM)
96                 return (dgettext(TEXT_DOMAIN, "filesystem"));
97         if (types == ZFS_TYPE_VOLUME)
98                 return (dgettext(TEXT_DOMAIN, "volume"));
99
100         /*
101          * The user is requesting more than one type of dataset.  If this is the
102          * case, consult the path itself.  If we're looking for a snapshot, and
103          * a '@' is found, then report it as "snapshot".  Otherwise, remove the
104          * snapshot attribute and try again.
105          */
106         if (types & ZFS_TYPE_SNAPSHOT) {
107                 if (strchr(path, '@') != NULL)
108                         return (dgettext(TEXT_DOMAIN, "snapshot"));
109                 return (path_to_str(path, types & ~ZFS_TYPE_SNAPSHOT));
110         }
111
112         /*
113          * The user has requested either filesystems or volumes.
114          * We have no way of knowing a priori what type this would be, so always
115          * report it as "filesystem" or "volume", our two primitive types.
116          */
117         if (types & ZFS_TYPE_FILESYSTEM)
118                 return (dgettext(TEXT_DOMAIN, "filesystem"));
119
120         assert(types & ZFS_TYPE_VOLUME);
121         return (dgettext(TEXT_DOMAIN, "volume"));
122 }
123
124 /*
125  * Validate a ZFS path.  This is used even before trying to open the dataset, to
126  * provide a more meaningful error message.  We call zfs_error_aux() to
127  * explain exactly why the name was not valid.
128  */
129 static int
130 zfs_validate_name(libzfs_handle_t *hdl, const char *path, int type,
131     boolean_t modifying)
132 {
133         namecheck_err_t why;
134         char what;
135
136         if (dataset_namecheck(path, &why, &what) != 0) {
137                 if (hdl != NULL) {
138                         switch (why) {
139                         case NAME_ERR_TOOLONG:
140                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
141                                     "name is too long"));
142                                 break;
143
144                         case NAME_ERR_LEADING_SLASH:
145                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
146                                     "leading slash in name"));
147                                 break;
148
149                         case NAME_ERR_EMPTY_COMPONENT:
150                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
151                                     "empty component in name"));
152                                 break;
153
154                         case NAME_ERR_TRAILING_SLASH:
155                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
156                                     "trailing slash in name"));
157                                 break;
158
159                         case NAME_ERR_INVALCHAR:
160                                 zfs_error_aux(hdl,
161                                     dgettext(TEXT_DOMAIN, "invalid character "
162                                     "'%c' in name"), what);
163                                 break;
164
165                         case NAME_ERR_MULTIPLE_AT:
166                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
167                                     "multiple '@' delimiters in name"));
168                                 break;
169
170                         case NAME_ERR_NOLETTER:
171                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
172                                     "pool doesn't begin with a letter"));
173                                 break;
174
175                         case NAME_ERR_RESERVED:
176                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
177                                     "name is reserved"));
178                                 break;
179
180                         case NAME_ERR_DISKLIKE:
181                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
182                                     "reserved disk name"));
183                                 break;
184                         }
185                 }
186
187                 return (0);
188         }
189
190         if (!(type & ZFS_TYPE_SNAPSHOT) && strchr(path, '@') != NULL) {
191                 if (hdl != NULL)
192                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
193                             "snapshot delimiter '@' in filesystem name"));
194                 return (0);
195         }
196
197         if (type == ZFS_TYPE_SNAPSHOT && strchr(path, '@') == NULL) {
198                 if (hdl != NULL)
199                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
200                             "missing '@' delimiter in snapshot name"));
201                 return (0);
202         }
203
204         if (modifying && strchr(path, '%') != NULL) {
205                 if (hdl != NULL)
206                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
207                             "invalid character %c in name"), '%');
208                 return (0);
209         }
210
211         return (-1);
212 }
213
214 int
215 zfs_name_valid(const char *name, zfs_type_t type)
216 {
217         if (type == ZFS_TYPE_POOL)
218                 return (zpool_name_valid(NULL, B_FALSE, name));
219         return (zfs_validate_name(NULL, name, type, B_FALSE));
220 }
221
222 /*
223  * This function takes the raw DSL properties, and filters out the user-defined
224  * properties into a separate nvlist.
225  */
226 static nvlist_t *
227 process_user_props(zfs_handle_t *zhp, nvlist_t *props)
228 {
229         libzfs_handle_t *hdl = zhp->zfs_hdl;
230         nvpair_t *elem;
231         nvlist_t *propval;
232         nvlist_t *nvl;
233
234         if (nvlist_alloc(&nvl, NV_UNIQUE_NAME, 0) != 0) {
235                 (void) no_memory(hdl);
236                 return (NULL);
237         }
238
239         elem = NULL;
240         while ((elem = nvlist_next_nvpair(props, elem)) != NULL) {
241                 if (!zfs_prop_user(nvpair_name(elem)))
242                         continue;
243
244                 verify(nvpair_value_nvlist(elem, &propval) == 0);
245                 if (nvlist_add_nvlist(nvl, nvpair_name(elem), propval) != 0) {
246                         nvlist_free(nvl);
247                         (void) no_memory(hdl);
248                         return (NULL);
249                 }
250         }
251
252         return (nvl);
253 }
254
255 static zpool_handle_t *
256 zpool_add_handle(zfs_handle_t *zhp, const char *pool_name)
257 {
258         libzfs_handle_t *hdl = zhp->zfs_hdl;
259         zpool_handle_t *zph;
260
261         if ((zph = zpool_open_canfail(hdl, pool_name)) != NULL) {
262                 if (hdl->libzfs_pool_handles != NULL)
263                         zph->zpool_next = hdl->libzfs_pool_handles;
264                 hdl->libzfs_pool_handles = zph;
265         }
266         return (zph);
267 }
268
269 static zpool_handle_t *
270 zpool_find_handle(zfs_handle_t *zhp, const char *pool_name, int len)
271 {
272         libzfs_handle_t *hdl = zhp->zfs_hdl;
273         zpool_handle_t *zph = hdl->libzfs_pool_handles;
274
275         while ((zph != NULL) &&
276             (strncmp(pool_name, zpool_get_name(zph), len) != 0))
277                 zph = zph->zpool_next;
278         return (zph);
279 }
280
281 /*
282  * Returns a handle to the pool that contains the provided dataset.
283  * If a handle to that pool already exists then that handle is returned.
284  * Otherwise, a new handle is created and added to the list of handles.
285  */
286 static zpool_handle_t *
287 zpool_handle(zfs_handle_t *zhp)
288 {
289         char *pool_name;
290         int len;
291         zpool_handle_t *zph;
292
293         len = strcspn(zhp->zfs_name, "/@") + 1;
294         pool_name = zfs_alloc(zhp->zfs_hdl, len);
295         (void) strlcpy(pool_name, zhp->zfs_name, len);
296
297         zph = zpool_find_handle(zhp, pool_name, len);
298         if (zph == NULL)
299                 zph = zpool_add_handle(zhp, pool_name);
300
301         free(pool_name);
302         return (zph);
303 }
304
305 void
306 zpool_free_handles(libzfs_handle_t *hdl)
307 {
308         zpool_handle_t *next, *zph = hdl->libzfs_pool_handles;
309
310         while (zph != NULL) {
311                 next = zph->zpool_next;
312                 zpool_close(zph);
313                 zph = next;
314         }
315         hdl->libzfs_pool_handles = NULL;
316 }
317
318 /*
319  * Utility function to gather stats (objset and zpl) for the given object.
320  */
321 get_stats_ioctl(zfs_handle_t *zhp, zfs_cmd_t *zc)
322 {
323         libzfs_handle_t *hdl = zhp->zfs_hdl;
324
325         (void) strlcpy(zc->zc_name, zhp->zfs_name, sizeof (zc->zc_name));
326
327         while (ioctl(hdl->libzfs_fd, ZFS_IOC_OBJSET_STATS, zc) != 0) {
328                 if (errno == ENOMEM) {
329                         if (zcmd_expand_dst_nvlist(hdl, zc) != 0) {
330                                 return (-1);
331                         }
332                 } else {
333                         return (-1);
334                 }
335         }
336         return (0);
337 }
338
339 static int
340 put_stats_zhdl(zfs_handle_t *zhp, zfs_cmd_t *zc)
341 {
342         nvlist_t *allprops, *userprops;
343
344         zhp->zfs_dmustats = zc->zc_objset_stats; /* structure assignment */
345
346         if (zcmd_read_dst_nvlist(zhp->zfs_hdl, zc, &allprops) != 0) {
347                 return (-1);
348         }
349
350         /*
351          * XXX Why do we store the user props separately, in addition to
352          * storing them in zfs_props?
353          */
354         if ((userprops = process_user_props(zhp, allprops)) == NULL) {
355                 nvlist_free(allprops);
356                 return (-1);
357         }
358
359         nvlist_free(zhp->zfs_props);
360         nvlist_free(zhp->zfs_user_props);
361
362         zhp->zfs_props = allprops;
363         zhp->zfs_user_props = userprops;
364
365         return (0);
366 }
367
368 static int
369 get_stats(zfs_handle_t *zhp)
370 {
371         int rc = 0;
372         zfs_cmd_t zc = { 0 };
373
374         if (zcmd_alloc_dst_nvlist(zhp->zfs_hdl, &zc, 0) != 0)
375                 return (-1);
376         if (get_stats_ioctl(zhp, &zc) != 0)
377                 rc = -1;
378         else if (put_stats_zhdl(zhp, &zc) != 0)
379                 rc = -1;
380         zcmd_free_nvlists(&zc);
381         return (rc);
382 }
383
384 /*
385  * Refresh the properties currently stored in the handle.
386  */
387 void
388 zfs_refresh_properties(zfs_handle_t *zhp)
389 {
390         (void) get_stats(zhp);
391 }
392
393 /*
394  * Makes a handle from the given dataset name.  Used by zfs_open() and
395  * zfs_iter_* to create child handles on the fly.
396  */
397 static int
398 make_dataset_handle_common(zfs_handle_t *zhp, zfs_cmd_t *zc)
399 {
400         char *logstr;
401         libzfs_handle_t *hdl = zhp->zfs_hdl;
402
403         /*
404          * Preserve history log string.
405          * any changes performed here will be
406          * logged as an internal event.
407          */
408         logstr = zhp->zfs_hdl->libzfs_log_str;
409         zhp->zfs_hdl->libzfs_log_str = NULL;
410
411 top:
412         if (put_stats_zhdl(zhp, zc) != 0) {
413                 zhp->zfs_hdl->libzfs_log_str = logstr;
414                 return (-1);
415         }
416
417
418         if (zhp->zfs_dmustats.dds_inconsistent) {
419                 zfs_cmd_t zc2 = { 0 };
420
421                 /*
422                  * If it is dds_inconsistent, then we've caught it in
423                  * the middle of a 'zfs receive' or 'zfs destroy', and
424                  * it is inconsistent from the ZPL's point of view, so
425                  * can't be mounted.  However, it could also be that we
426                  * have crashed in the middle of one of those
427                  * operations, in which case we need to get rid of the
428                  * inconsistent state.  We do that by either rolling
429                  * back to the previous snapshot (which will fail if
430                  * there is none), or destroying the filesystem.  Note
431                  * that if we are still in the middle of an active
432                  * 'receive' or 'destroy', then the rollback and destroy
433                  * will fail with EBUSY and we will drive on as usual.
434                  */
435
436                 (void) strlcpy(zc2.zc_name, zhp->zfs_name,
437                     sizeof (zc2.zc_name));
438
439                 if (zhp->zfs_dmustats.dds_type == DMU_OST_ZVOL) {
440                         (void) zvol_remove_link(hdl, zhp->zfs_name);
441                         zc2.zc_objset_type = DMU_OST_ZVOL;
442                 } else {
443                         zc2.zc_objset_type = DMU_OST_ZFS;
444                 }
445
446                 /*
447                  * If we can successfully destroy it, pretend that it
448                  * never existed.
449                  */
450                 if (ioctl(hdl->libzfs_fd, ZFS_IOC_DESTROY, &zc2) == 0) {
451                         zhp->zfs_hdl->libzfs_log_str = logstr;
452                         errno = ENOENT;
453                         return (-1);
454                 }
455                 /* If we can successfully roll it back, reset the stats */
456                 if (ioctl(hdl->libzfs_fd, ZFS_IOC_ROLLBACK, &zc2) == 0) {
457                         if (get_stats_ioctl(zhp, zc) != 0) {
458                                 zhp->zfs_hdl->libzfs_log_str = logstr;
459                                 return (-1);
460                         }
461                         goto top;
462                 }
463         }
464
465         /*
466          * We've managed to open the dataset and gather statistics.  Determine
467          * the high-level type.
468          */
469         if (zhp->zfs_dmustats.dds_type == DMU_OST_ZVOL)
470                 zhp->zfs_head_type = ZFS_TYPE_VOLUME;
471         else if (zhp->zfs_dmustats.dds_type == DMU_OST_ZFS)
472                 zhp->zfs_head_type = ZFS_TYPE_FILESYSTEM;
473         else
474                 abort();
475
476         if (zhp->zfs_dmustats.dds_is_snapshot)
477                 zhp->zfs_type = ZFS_TYPE_SNAPSHOT;
478         else if (zhp->zfs_dmustats.dds_type == DMU_OST_ZVOL)
479                 zhp->zfs_type = ZFS_TYPE_VOLUME;
480         else if (zhp->zfs_dmustats.dds_type == DMU_OST_ZFS)
481                 zhp->zfs_type = ZFS_TYPE_FILESYSTEM;
482         else
483                 abort();        /* we should never see any other types */
484
485         zhp->zfs_hdl->libzfs_log_str = logstr;
486         zhp->zpool_hdl = zpool_handle(zhp);
487         return (0);
488 }
489
490 zfs_handle_t *
491 make_dataset_handle(libzfs_handle_t *hdl, const char *path)
492 {
493         zfs_cmd_t zc = { 0 };
494
495         zfs_handle_t *zhp = calloc(sizeof (zfs_handle_t), 1);
496
497         if (zhp == NULL)
498                 return (NULL);
499
500         zhp->zfs_hdl = hdl;
501         (void) strlcpy(zhp->zfs_name, path, sizeof (zhp->zfs_name));
502         if (zcmd_alloc_dst_nvlist(hdl, &zc, 0) != 0) {
503                 free(zhp);
504                 return (NULL);
505         }
506         if (get_stats_ioctl(zhp, &zc) == -1) {
507                 zcmd_free_nvlists(&zc);
508                 free(zhp);
509                 return (NULL);
510         }
511         if (make_dataset_handle_common(zhp, &zc) == -1) {
512                 free(zhp);
513                 zhp = NULL;
514         }
515         zcmd_free_nvlists(&zc);
516         return (zhp);
517 }
518
519 static zfs_handle_t *
520 make_dataset_handle_zc(libzfs_handle_t *hdl, zfs_cmd_t *zc)
521 {
522         zfs_handle_t *zhp = calloc(sizeof (zfs_handle_t), 1);
523
524         if (zhp == NULL)
525                 return (NULL);
526
527         zhp->zfs_hdl = hdl;
528         (void) strlcpy(zhp->zfs_name, zc->zc_name, sizeof (zhp->zfs_name));
529         if (make_dataset_handle_common(zhp, zc) == -1) {
530                 free(zhp);
531                 return (NULL);
532         }
533         return (zhp);
534 }
535
536 /*
537  * Opens the given snapshot, filesystem, or volume.   The 'types'
538  * argument is a mask of acceptable types.  The function will print an
539  * appropriate error message and return NULL if it can't be opened.
540  */
541 zfs_handle_t *
542 zfs_open(libzfs_handle_t *hdl, const char *path, int types)
543 {
544         zfs_handle_t *zhp;
545         char errbuf[1024];
546
547         (void) snprintf(errbuf, sizeof (errbuf),
548             dgettext(TEXT_DOMAIN, "cannot open '%s'"), path);
549
550         /*
551          * Validate the name before we even try to open it.
552          */
553         if (!zfs_validate_name(hdl, path, ZFS_TYPE_DATASET, B_FALSE)) {
554                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
555                     "invalid dataset name"));
556                 (void) zfs_error(hdl, EZFS_INVALIDNAME, errbuf);
557                 return (NULL);
558         }
559
560         /*
561          * Try to get stats for the dataset, which will tell us if it exists.
562          */
563         errno = 0;
564         if ((zhp = make_dataset_handle(hdl, path)) == NULL) {
565                 (void) zfs_standard_error(hdl, errno, errbuf);
566                 return (NULL);
567         }
568
569         if (!(types & zhp->zfs_type)) {
570                 (void) zfs_error(hdl, EZFS_BADTYPE, errbuf);
571                 zfs_close(zhp);
572                 return (NULL);
573         }
574
575         return (zhp);
576 }
577
578 /*
579  * Release a ZFS handle.  Nothing to do but free the associated memory.
580  */
581 void
582 zfs_close(zfs_handle_t *zhp)
583 {
584         if (zhp->zfs_mntopts)
585                 free(zhp->zfs_mntopts);
586         nvlist_free(zhp->zfs_props);
587         nvlist_free(zhp->zfs_user_props);
588         free(zhp);
589 }
590
591 typedef struct mnttab_node {
592         struct mnttab mtn_mt;
593         avl_node_t mtn_node;
594 } mnttab_node_t;
595
596 static int
597 libzfs_mnttab_cache_compare(const void *arg1, const void *arg2)
598 {
599         const mnttab_node_t *mtn1 = arg1;
600         const mnttab_node_t *mtn2 = arg2;
601         int rv;
602
603         rv = strcmp(mtn1->mtn_mt.mnt_special, mtn2->mtn_mt.mnt_special);
604
605         if (rv == 0)
606                 return (0);
607         return (rv > 0 ? 1 : -1);
608 }
609
610 void
611 libzfs_mnttab_init(libzfs_handle_t *hdl)
612 {
613         assert(avl_numnodes(&hdl->libzfs_mnttab_cache) == 0);
614         avl_create(&hdl->libzfs_mnttab_cache, libzfs_mnttab_cache_compare,
615             sizeof (mnttab_node_t), offsetof(mnttab_node_t, mtn_node));
616 }
617
618 void
619 libzfs_mnttab_update(libzfs_handle_t *hdl)
620 {
621         struct mnttab entry;
622
623         rewind(hdl->libzfs_mnttab);
624         while (getmntent(hdl->libzfs_mnttab, &entry) == 0) {
625                 mnttab_node_t *mtn;
626
627                 if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0)
628                         continue;
629                 mtn = zfs_alloc(hdl, sizeof (mnttab_node_t));
630                 mtn->mtn_mt.mnt_special = zfs_strdup(hdl, entry.mnt_special);
631                 mtn->mtn_mt.mnt_mountp = zfs_strdup(hdl, entry.mnt_mountp);
632                 mtn->mtn_mt.mnt_fstype = zfs_strdup(hdl, entry.mnt_fstype);
633                 mtn->mtn_mt.mnt_mntopts = zfs_strdup(hdl, entry.mnt_mntopts);
634                 avl_add(&hdl->libzfs_mnttab_cache, mtn);
635         }
636 }
637
638 void
639 libzfs_mnttab_fini(libzfs_handle_t *hdl)
640 {
641         void *cookie = NULL;
642         mnttab_node_t *mtn;
643
644         while (mtn = avl_destroy_nodes(&hdl->libzfs_mnttab_cache, &cookie)) {
645                 free(mtn->mtn_mt.mnt_special);
646                 free(mtn->mtn_mt.mnt_mountp);
647                 free(mtn->mtn_mt.mnt_fstype);
648                 free(mtn->mtn_mt.mnt_mntopts);
649                 free(mtn);
650         }
651         avl_destroy(&hdl->libzfs_mnttab_cache);
652 }
653
654 void
655 libzfs_mnttab_cache(libzfs_handle_t *hdl, boolean_t enable)
656 {
657         hdl->libzfs_mnttab_enable = enable;
658 }
659
660 int
661 libzfs_mnttab_find(libzfs_handle_t *hdl, const char *fsname,
662     struct mnttab *entry)
663 {
664         mnttab_node_t find;
665         mnttab_node_t *mtn;
666
667         if (!hdl->libzfs_mnttab_enable) {
668                 struct mnttab srch = { 0 };
669
670                 if (avl_numnodes(&hdl->libzfs_mnttab_cache))
671                         libzfs_mnttab_fini(hdl);
672                 rewind(hdl->libzfs_mnttab);
673                 srch.mnt_special = (char *)fsname;
674                 srch.mnt_fstype = MNTTYPE_ZFS;
675                 if (getmntany(hdl->libzfs_mnttab, entry, &srch) == 0)
676                         return (0);
677                 else
678                         return (ENOENT);
679         }
680
681         if (avl_numnodes(&hdl->libzfs_mnttab_cache) == 0)
682                 libzfs_mnttab_update(hdl);
683
684         find.mtn_mt.mnt_special = (char *)fsname;
685         mtn = avl_find(&hdl->libzfs_mnttab_cache, &find, NULL);
686         if (mtn) {
687                 *entry = mtn->mtn_mt;
688                 return (0);
689         }
690         return (ENOENT);
691 }
692
693 void
694 libzfs_mnttab_add(libzfs_handle_t *hdl, const char *special,
695     const char *mountp, const char *mntopts)
696 {
697         mnttab_node_t *mtn;
698
699         if (avl_numnodes(&hdl->libzfs_mnttab_cache) == 0)
700                 return;
701         mtn = zfs_alloc(hdl, sizeof (mnttab_node_t));
702         mtn->mtn_mt.mnt_special = zfs_strdup(hdl, special);
703         mtn->mtn_mt.mnt_mountp = zfs_strdup(hdl, mountp);
704         mtn->mtn_mt.mnt_fstype = zfs_strdup(hdl, MNTTYPE_ZFS);
705         mtn->mtn_mt.mnt_mntopts = zfs_strdup(hdl, mntopts);
706         avl_add(&hdl->libzfs_mnttab_cache, mtn);
707 }
708
709 void
710 libzfs_mnttab_remove(libzfs_handle_t *hdl, const char *fsname)
711 {
712         mnttab_node_t find;
713         mnttab_node_t *ret;
714
715         find.mtn_mt.mnt_special = (char *)fsname;
716         if (ret = avl_find(&hdl->libzfs_mnttab_cache, (void *)&find, NULL)) {
717                 avl_remove(&hdl->libzfs_mnttab_cache, ret);
718                 free(ret->mtn_mt.mnt_special);
719                 free(ret->mtn_mt.mnt_mountp);
720                 free(ret->mtn_mt.mnt_fstype);
721                 free(ret->mtn_mt.mnt_mntopts);
722                 free(ret);
723         }
724 }
725
726 int
727 zfs_spa_version(zfs_handle_t *zhp, int *spa_version)
728 {
729         zpool_handle_t *zpool_handle = zhp->zpool_hdl;
730
731         if (zpool_handle == NULL)
732                 return (-1);
733
734         *spa_version = zpool_get_prop_int(zpool_handle,
735             ZPOOL_PROP_VERSION, NULL);
736         return (0);
737 }
738
739 /*
740  * The choice of reservation property depends on the SPA version.
741  */
742 static int
743 zfs_which_resv_prop(zfs_handle_t *zhp, zfs_prop_t *resv_prop)
744 {
745         int spa_version;
746
747         if (zfs_spa_version(zhp, &spa_version) < 0)
748                 return (-1);
749
750         if (spa_version >= SPA_VERSION_REFRESERVATION)
751                 *resv_prop = ZFS_PROP_REFRESERVATION;
752         else
753                 *resv_prop = ZFS_PROP_RESERVATION;
754
755         return (0);
756 }
757
758 /*
759  * Given an nvlist of properties to set, validates that they are correct, and
760  * parses any numeric properties (index, boolean, etc) if they are specified as
761  * strings.
762  */
763 nvlist_t *
764 zfs_valid_proplist(libzfs_handle_t *hdl, zfs_type_t type, nvlist_t *nvl,
765     uint64_t zoned, zfs_handle_t *zhp, const char *errbuf)
766 {
767         nvpair_t *elem;
768         uint64_t intval;
769         char *strval;
770         zfs_prop_t prop;
771         nvlist_t *ret;
772         int chosen_normal = -1;
773         int chosen_utf = -1;
774
775         if (nvlist_alloc(&ret, NV_UNIQUE_NAME, 0) != 0) {
776                 (void) no_memory(hdl);
777                 return (NULL);
778         }
779
780         /*
781          * Make sure this property is valid and applies to this type.
782          */
783
784         elem = NULL;
785         while ((elem = nvlist_next_nvpair(nvl, elem)) != NULL) {
786                 const char *propname = nvpair_name(elem);
787
788                 prop = zfs_name_to_prop(propname);
789                 if (prop == ZPROP_INVAL && zfs_prop_user(propname)) {
790                         /*
791                          * This is a user property: make sure it's a
792                          * string, and that it's less than ZAP_MAXNAMELEN.
793                          */
794                         if (nvpair_type(elem) != DATA_TYPE_STRING) {
795                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
796                                     "'%s' must be a string"), propname);
797                                 (void) zfs_error(hdl, EZFS_BADPROP, errbuf);
798                                 goto error;
799                         }
800
801                         if (strlen(nvpair_name(elem)) >= ZAP_MAXNAMELEN) {
802                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
803                                     "property name '%s' is too long"),
804                                     propname);
805                                 (void) zfs_error(hdl, EZFS_BADPROP, errbuf);
806                                 goto error;
807                         }
808
809                         (void) nvpair_value_string(elem, &strval);
810                         if (nvlist_add_string(ret, propname, strval) != 0) {
811                                 (void) no_memory(hdl);
812                                 goto error;
813                         }
814                         continue;
815                 }
816
817                 /*
818                  * Currently, only user properties can be modified on
819                  * snapshots.
820                  */
821                 if (type == ZFS_TYPE_SNAPSHOT) {
822                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
823                             "this property can not be modified for snapshots"));
824                         (void) zfs_error(hdl, EZFS_PROPTYPE, errbuf);
825                         goto error;
826                 }
827
828                 if (prop == ZPROP_INVAL && zfs_prop_userquota(propname)) {
829                         zfs_userquota_prop_t uqtype;
830                         char newpropname[128];
831                         char domain[128];
832                         uint64_t rid;
833                         uint64_t valary[3];
834
835                         if (userquota_propname_decode(propname, zoned,
836                             &uqtype, domain, sizeof (domain), &rid) != 0) {
837                                 zfs_error_aux(hdl,
838                                     dgettext(TEXT_DOMAIN,
839                                     "'%s' has an invalid user/group name"),
840                                     propname);
841                                 (void) zfs_error(hdl, EZFS_BADPROP, errbuf);
842                                 goto error;
843                         }
844
845                         if (uqtype != ZFS_PROP_USERQUOTA &&
846                             uqtype != ZFS_PROP_GROUPQUOTA) {
847                                 zfs_error_aux(hdl,
848                                     dgettext(TEXT_DOMAIN, "'%s' is readonly"),
849                                     propname);
850                                 (void) zfs_error(hdl, EZFS_PROPREADONLY,
851                                     errbuf);
852                                 goto error;
853                         }
854
855                         if (nvpair_type(elem) == DATA_TYPE_STRING) {
856                                 (void) nvpair_value_string(elem, &strval);
857                                 if (strcmp(strval, "none") == 0) {
858                                         intval = 0;
859                                 } else if (zfs_nicestrtonum(hdl,
860                                     strval, &intval) != 0) {
861                                         (void) zfs_error(hdl,
862                                             EZFS_BADPROP, errbuf);
863                                         goto error;
864                                 }
865                         } else if (nvpair_type(elem) ==
866                             DATA_TYPE_UINT64) {
867                                 (void) nvpair_value_uint64(elem, &intval);
868                                 if (intval == 0) {
869                                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
870                                             "use 'none' to disable "
871                                             "userquota/groupquota"));
872                                         goto error;
873                                 }
874                         } else {
875                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
876                                     "'%s' must be a number"), propname);
877                                 (void) zfs_error(hdl, EZFS_BADPROP, errbuf);
878                                 goto error;
879                         }
880
881                         (void) snprintf(newpropname, sizeof (newpropname),
882                             "%s%s", zfs_userquota_prop_prefixes[uqtype],
883                             domain);
884                         valary[0] = uqtype;
885                         valary[1] = rid;
886                         valary[2] = intval;
887                         if (nvlist_add_uint64_array(ret, newpropname,
888                             valary, 3) != 0) {
889                                 (void) no_memory(hdl);
890                                 goto error;
891                         }
892                         continue;
893                 }
894
895                 if (prop == ZPROP_INVAL) {
896                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
897                             "invalid property '%s'"), propname);
898                         (void) zfs_error(hdl, EZFS_BADPROP, errbuf);
899                         goto error;
900                 }
901
902                 if (!zfs_prop_valid_for_type(prop, type)) {
903                         zfs_error_aux(hdl,
904                             dgettext(TEXT_DOMAIN, "'%s' does not "
905                             "apply to datasets of this type"), propname);
906                         (void) zfs_error(hdl, EZFS_PROPTYPE, errbuf);
907                         goto error;
908                 }
909
910                 if (zfs_prop_readonly(prop) &&
911                     (!zfs_prop_setonce(prop) || zhp != NULL)) {
912                         zfs_error_aux(hdl,
913                             dgettext(TEXT_DOMAIN, "'%s' is readonly"),
914                             propname);
915                         (void) zfs_error(hdl, EZFS_PROPREADONLY, errbuf);
916                         goto error;
917                 }
918
919                 if (zprop_parse_value(hdl, elem, prop, type, ret,
920                     &strval, &intval, errbuf) != 0)
921                         goto error;
922
923                 /*
924                  * Perform some additional checks for specific properties.
925                  */
926                 switch (prop) {
927                 case ZFS_PROP_VERSION:
928                 {
929                         int version;
930
931                         if (zhp == NULL)
932                                 break;
933                         version = zfs_prop_get_int(zhp, ZFS_PROP_VERSION);
934                         if (intval < version) {
935                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
936                                     "Can not downgrade; already at version %u"),
937                                     version);
938                                 (void) zfs_error(hdl, EZFS_BADPROP, errbuf);
939                                 goto error;
940                         }
941                         break;
942                 }
943
944                 case ZFS_PROP_RECORDSIZE:
945                 case ZFS_PROP_VOLBLOCKSIZE:
946                         /* must be power of two within SPA_{MIN,MAX}BLOCKSIZE */
947                         if (intval < SPA_MINBLOCKSIZE ||
948                             intval > SPA_MAXBLOCKSIZE || !ISP2(intval)) {
949                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
950                                     "'%s' must be power of 2 from %u "
951                                     "to %uk"), propname,
952                                     (uint_t)SPA_MINBLOCKSIZE,
953                                     (uint_t)SPA_MAXBLOCKSIZE >> 10);
954                                 (void) zfs_error(hdl, EZFS_BADPROP, errbuf);
955                                 goto error;
956                         }
957                         break;
958
959                 case ZFS_PROP_SHAREISCSI:
960                         if (strcmp(strval, "off") != 0 &&
961                             strcmp(strval, "on") != 0 &&
962                             strcmp(strval, "type=disk") != 0) {
963                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
964                                     "'%s' must be 'on', 'off', or 'type=disk'"),
965                                     propname);
966                                 (void) zfs_error(hdl, EZFS_BADPROP, errbuf);
967                                 goto error;
968                         }
969
970                         break;
971
972                 case ZFS_PROP_MOUNTPOINT:
973                 {
974                         namecheck_err_t why;
975
976                         if (strcmp(strval, ZFS_MOUNTPOINT_NONE) == 0 ||
977                             strcmp(strval, ZFS_MOUNTPOINT_LEGACY) == 0)
978                                 break;
979
980                         if (mountpoint_namecheck(strval, &why)) {
981                                 switch (why) {
982                                 case NAME_ERR_LEADING_SLASH:
983                                         zfs_error_aux(hdl,
984                                             dgettext(TEXT_DOMAIN,
985                                             "'%s' must be an absolute path, "
986                                             "'none', or 'legacy'"), propname);
987                                         break;
988                                 case NAME_ERR_TOOLONG:
989                                         zfs_error_aux(hdl,
990                                             dgettext(TEXT_DOMAIN,
991                                             "component of '%s' is too long"),
992                                             propname);
993                                         break;
994                                 }
995                                 (void) zfs_error(hdl, EZFS_BADPROP, errbuf);
996                                 goto error;
997                         }
998                 }
999
1000                         /*FALLTHRU*/
1001
1002                 case ZFS_PROP_SHARESMB:
1003                 case ZFS_PROP_SHARENFS:
1004                         /*
1005                          * For the mountpoint and sharenfs or sharesmb
1006                          * properties, check if it can be set in a
1007                          * global/non-global zone based on
1008                          * the zoned property value:
1009                          *
1010                          *              global zone         non-global zone
1011                          * --------------------------------------------------
1012                          * zoned=on     mountpoint (no)     mountpoint (yes)
1013                          *              sharenfs (no)       sharenfs (no)
1014                          *              sharesmb (no)       sharesmb (no)
1015                          *
1016                          * zoned=off    mountpoint (yes)        N/A
1017                          *              sharenfs (yes)
1018                          *              sharesmb (yes)
1019                          */
1020                         if (zoned) {
1021                                 if (getzoneid() == GLOBAL_ZONEID) {
1022                                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1023                                             "'%s' cannot be set on "
1024                                             "dataset in a non-global zone"),
1025                                             propname);
1026                                         (void) zfs_error(hdl, EZFS_ZONED,
1027                                             errbuf);
1028                                         goto error;
1029                                 } else if (prop == ZFS_PROP_SHARENFS ||
1030                                     prop == ZFS_PROP_SHARESMB) {
1031                                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1032                                             "'%s' cannot be set in "
1033                                             "a non-global zone"), propname);
1034                                         (void) zfs_error(hdl, EZFS_ZONED,
1035                                             errbuf);
1036                                         goto error;
1037                                 }
1038                         } else if (getzoneid() != GLOBAL_ZONEID) {
1039                                 /*
1040                                  * If zoned property is 'off', this must be in
1041                                  * a global zone. If not, something is wrong.
1042                                  */
1043                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1044                                     "'%s' cannot be set while dataset "
1045                                     "'zoned' property is set"), propname);
1046                                 (void) zfs_error(hdl, EZFS_ZONED, errbuf);
1047                                 goto error;
1048                         }
1049
1050                         /*
1051                          * At this point, it is legitimate to set the
1052                          * property. Now we want to make sure that the
1053                          * property value is valid if it is sharenfs.
1054                          */
1055                         if ((prop == ZFS_PROP_SHARENFS ||
1056                             prop == ZFS_PROP_SHARESMB) &&
1057                             strcmp(strval, "on") != 0 &&
1058                             strcmp(strval, "off") != 0) {
1059                                 zfs_share_proto_t proto;
1060
1061                                 if (prop == ZFS_PROP_SHARESMB)
1062                                         proto = PROTO_SMB;
1063                                 else
1064                                         proto = PROTO_NFS;
1065
1066                                 /*
1067                                  * Must be an valid sharing protocol
1068                                  * option string so init the libshare
1069                                  * in order to enable the parser and
1070                                  * then parse the options. We use the
1071                                  * control API since we don't care about
1072                                  * the current configuration and don't
1073                                  * want the overhead of loading it
1074                                  * until we actually do something.
1075                                  */
1076
1077                                 if (zfs_init_libshare(hdl,
1078                                     SA_INIT_CONTROL_API) != SA_OK) {
1079                                         /*
1080                                          * An error occurred so we can't do
1081                                          * anything
1082                                          */
1083                                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1084                                             "'%s' cannot be set: problem "
1085                                             "in share initialization"),
1086                                             propname);
1087                                         (void) zfs_error(hdl, EZFS_BADPROP,
1088                                             errbuf);
1089                                         goto error;
1090                                 }
1091
1092                                 if (zfs_parse_options(strval, proto) != SA_OK) {
1093                                         /*
1094                                          * There was an error in parsing so
1095                                          * deal with it by issuing an error
1096                                          * message and leaving after
1097                                          * uninitializing the the libshare
1098                                          * interface.
1099                                          */
1100                                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1101                                             "'%s' cannot be set to invalid "
1102                                             "options"), propname);
1103                                         (void) zfs_error(hdl, EZFS_BADPROP,
1104                                             errbuf);
1105                                         zfs_uninit_libshare(hdl);
1106                                         goto error;
1107                                 }
1108                                 zfs_uninit_libshare(hdl);
1109                         }
1110
1111                         break;
1112                 case ZFS_PROP_UTF8ONLY:
1113                         chosen_utf = (int)intval;
1114                         break;
1115                 case ZFS_PROP_NORMALIZE:
1116                         chosen_normal = (int)intval;
1117                         break;
1118                 }
1119
1120                 /*
1121                  * For changes to existing volumes, we have some additional
1122                  * checks to enforce.
1123                  */
1124                 if (type == ZFS_TYPE_VOLUME && zhp != NULL) {
1125                         uint64_t volsize = zfs_prop_get_int(zhp,
1126                             ZFS_PROP_VOLSIZE);
1127                         uint64_t blocksize = zfs_prop_get_int(zhp,
1128                             ZFS_PROP_VOLBLOCKSIZE);
1129                         char buf[64];
1130
1131                         switch (prop) {
1132                         case ZFS_PROP_RESERVATION:
1133                         case ZFS_PROP_REFRESERVATION:
1134                                 if (intval > volsize) {
1135                                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1136                                             "'%s' is greater than current "
1137                                             "volume size"), propname);
1138                                         (void) zfs_error(hdl, EZFS_BADPROP,
1139                                             errbuf);
1140                                         goto error;
1141                                 }
1142                                 break;
1143
1144                         case ZFS_PROP_VOLSIZE:
1145                                 if (intval % blocksize != 0) {
1146                                         zfs_nicenum(blocksize, buf,
1147                                             sizeof (buf));
1148                                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1149                                             "'%s' must be a multiple of "
1150                                             "volume block size (%s)"),
1151                                             propname, buf);
1152                                         (void) zfs_error(hdl, EZFS_BADPROP,
1153                                             errbuf);
1154                                         goto error;
1155                                 }
1156
1157                                 if (intval == 0) {
1158                                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1159                                             "'%s' cannot be zero"),
1160                                             propname);
1161                                         (void) zfs_error(hdl, EZFS_BADPROP,
1162                                             errbuf);
1163                                         goto error;
1164                                 }
1165                                 break;
1166                         }
1167                 }
1168         }
1169
1170         /*
1171          * If normalization was chosen, but no UTF8 choice was made,
1172          * enforce rejection of non-UTF8 names.
1173          *
1174          * If normalization was chosen, but rejecting non-UTF8 names
1175          * was explicitly not chosen, it is an error.
1176          */
1177         if (chosen_normal > 0 && chosen_utf < 0) {
1178                 if (nvlist_add_uint64(ret,
1179                     zfs_prop_to_name(ZFS_PROP_UTF8ONLY), 1) != 0) {
1180                         (void) no_memory(hdl);
1181                         goto error;
1182                 }
1183         } else if (chosen_normal > 0 && chosen_utf == 0) {
1184                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1185                     "'%s' must be set 'on' if normalization chosen"),
1186                     zfs_prop_to_name(ZFS_PROP_UTF8ONLY));
1187                 (void) zfs_error(hdl, EZFS_BADPROP, errbuf);
1188                 goto error;
1189         }
1190
1191         /*
1192          * If this is an existing volume, and someone is setting the volsize,
1193          * make sure that it matches the reservation, or add it if necessary.
1194          */
1195         if (zhp != NULL && type == ZFS_TYPE_VOLUME &&
1196             nvlist_lookup_uint64(ret, zfs_prop_to_name(ZFS_PROP_VOLSIZE),
1197             &intval) == 0) {
1198                 uint64_t old_volsize = zfs_prop_get_int(zhp,
1199                     ZFS_PROP_VOLSIZE);
1200                 uint64_t old_reservation;
1201                 uint64_t new_reservation;
1202                 zfs_prop_t resv_prop;
1203
1204                 if (zfs_which_resv_prop(zhp, &resv_prop) < 0)
1205                         goto error;
1206                 old_reservation = zfs_prop_get_int(zhp, resv_prop);
1207
1208                 if (old_volsize == old_reservation &&
1209                     nvlist_lookup_uint64(ret, zfs_prop_to_name(resv_prop),
1210                     &new_reservation) != 0) {
1211                         if (nvlist_add_uint64(ret,
1212                             zfs_prop_to_name(resv_prop), intval) != 0) {
1213                                 (void) no_memory(hdl);
1214                                 goto error;
1215                         }
1216                 }
1217         }
1218         return (ret);
1219
1220 error:
1221         nvlist_free(ret);
1222         return (NULL);
1223 }
1224
1225 /*
1226  * Given a property name and value, set the property for the given dataset.
1227  */
1228 int
1229 zfs_prop_set(zfs_handle_t *zhp, const char *propname, const char *propval)
1230 {
1231         zfs_cmd_t zc = { 0 };
1232         int ret = -1;
1233         prop_changelist_t *cl = NULL;
1234         char errbuf[1024];
1235         libzfs_handle_t *hdl = zhp->zfs_hdl;
1236         nvlist_t *nvl = NULL, *realprops;
1237         zfs_prop_t prop;
1238         boolean_t do_prefix;
1239         uint64_t idx;
1240
1241         (void) snprintf(errbuf, sizeof (errbuf),
1242             dgettext(TEXT_DOMAIN, "cannot set property for '%s'"),
1243             zhp->zfs_name);
1244
1245         if (nvlist_alloc(&nvl, NV_UNIQUE_NAME, 0) != 0 ||
1246             nvlist_add_string(nvl, propname, propval) != 0) {
1247                 (void) no_memory(hdl);
1248                 goto error;
1249         }
1250
1251         if ((realprops = zfs_valid_proplist(hdl, zhp->zfs_type, nvl,
1252             zfs_prop_get_int(zhp, ZFS_PROP_ZONED), zhp, errbuf)) == NULL)
1253                 goto error;
1254
1255         nvlist_free(nvl);
1256         nvl = realprops;
1257
1258         prop = zfs_name_to_prop(propname);
1259
1260         /* We don't support those properties on FreeBSD. */
1261         switch (prop) {
1262         case ZFS_PROP_DEVICES:
1263         case ZFS_PROP_SHAREISCSI:
1264         case ZFS_PROP_ISCSIOPTIONS:
1265         case ZFS_PROP_XATTR:
1266         case ZFS_PROP_VSCAN:
1267         case ZFS_PROP_NBMAND:
1268         case ZFS_PROP_SHARESMB:
1269                 (void) snprintf(errbuf, sizeof (errbuf),
1270                     "property '%s' not supported on FreeBSD", propname);
1271                 ret = zfs_error(hdl, EZFS_PERM, errbuf);
1272                 goto error;
1273         }
1274
1275         if ((cl = changelist_gather(zhp, prop, 0, 0)) == NULL)
1276                 goto error;
1277
1278         if (prop == ZFS_PROP_MOUNTPOINT && changelist_haszonedchild(cl)) {
1279                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1280                     "child dataset with inherited mountpoint is used "
1281                     "in a non-global zone"));
1282                 ret = zfs_error(hdl, EZFS_ZONED, errbuf);
1283                 goto error;
1284         }
1285
1286         /*
1287          * If the dataset's canmount property is being set to noauto,
1288          * then we want to prevent unmounting & remounting it.
1289          */
1290         do_prefix = !((prop == ZFS_PROP_CANMOUNT) &&
1291             (zprop_string_to_index(prop, propval, &idx,
1292             ZFS_TYPE_DATASET) == 0) && (idx == ZFS_CANMOUNT_NOAUTO));
1293
1294         if (do_prefix && (ret = changelist_prefix(cl)) != 0)
1295                 goto error;
1296
1297         /*
1298          * Execute the corresponding ioctl() to set this property.
1299          */
1300         (void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
1301
1302         if (zcmd_write_src_nvlist(hdl, &zc, nvl) != 0)
1303                 goto error;
1304
1305         ret = zfs_ioctl(hdl, ZFS_IOC_SET_PROP, &zc);
1306
1307         if (ret != 0) {
1308                 switch (errno) {
1309
1310                 case ENOSPC:
1311                         /*
1312                          * For quotas and reservations, ENOSPC indicates
1313                          * something different; setting a quota or reservation
1314                          * doesn't use any disk space.
1315                          */
1316                         switch (prop) {
1317                         case ZFS_PROP_QUOTA:
1318                         case ZFS_PROP_REFQUOTA:
1319                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1320                                     "size is less than current used or "
1321                                     "reserved space"));
1322                                 (void) zfs_error(hdl, EZFS_PROPSPACE, errbuf);
1323                                 break;
1324
1325                         case ZFS_PROP_RESERVATION:
1326                         case ZFS_PROP_REFRESERVATION:
1327                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1328                                     "size is greater than available space"));
1329                                 (void) zfs_error(hdl, EZFS_PROPSPACE, errbuf);
1330                                 break;
1331
1332                         default:
1333                                 (void) zfs_standard_error(hdl, errno, errbuf);
1334                                 break;
1335                         }
1336                         break;
1337
1338                 case EBUSY:
1339                         if (prop == ZFS_PROP_VOLBLOCKSIZE)
1340                                 (void) zfs_error(hdl, EZFS_VOLHASDATA, errbuf);
1341                         else
1342                                 (void) zfs_standard_error(hdl, EBUSY, errbuf);
1343                         break;
1344
1345                 case EROFS:
1346                         (void) zfs_error(hdl, EZFS_DSREADONLY, errbuf);
1347                         break;
1348
1349                 case ENOTSUP:
1350                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1351                             "pool and or dataset must be upgraded to set this "
1352                             "property or value"));
1353                         (void) zfs_error(hdl, EZFS_BADVERSION, errbuf);
1354                         break;
1355
1356                 case ERANGE:
1357                         if (prop == ZFS_PROP_COMPRESSION) {
1358                                 (void) zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1359                                     "property setting is not allowed on "
1360                                     "bootable datasets"));
1361                                 (void) zfs_error(hdl, EZFS_NOTSUP, errbuf);
1362                         } else {
1363                                 (void) zfs_standard_error(hdl, errno, errbuf);
1364                         }
1365                         break;
1366
1367                 case EOVERFLOW:
1368                         /*
1369                          * This platform can't address a volume this big.
1370                          */
1371 #ifdef _ILP32
1372                         if (prop == ZFS_PROP_VOLSIZE) {
1373                                 (void) zfs_error(hdl, EZFS_VOLTOOBIG, errbuf);
1374                                 break;
1375                         }
1376 #endif
1377                         /* FALLTHROUGH */
1378                 default:
1379                         (void) zfs_standard_error(hdl, errno, errbuf);
1380                 }
1381         } else {
1382                 if (do_prefix)
1383                         ret = changelist_postfix(cl);
1384
1385                 /*
1386                  * Refresh the statistics so the new property value
1387                  * is reflected.
1388                  */
1389                 if (ret == 0)
1390                         (void) get_stats(zhp);
1391         }
1392
1393 error:
1394         nvlist_free(nvl);
1395         zcmd_free_nvlists(&zc);
1396         if (cl)
1397                 changelist_free(cl);
1398         return (ret);
1399 }
1400
1401 /*
1402  * Given a property, inherit the value from the parent dataset.
1403  */
1404 int
1405 zfs_prop_inherit(zfs_handle_t *zhp, const char *propname)
1406 {
1407         zfs_cmd_t zc = { 0 };
1408         int ret;
1409         prop_changelist_t *cl;
1410         libzfs_handle_t *hdl = zhp->zfs_hdl;
1411         char errbuf[1024];
1412         zfs_prop_t prop;
1413
1414         (void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
1415             "cannot inherit %s for '%s'"), propname, zhp->zfs_name);
1416
1417         if ((prop = zfs_name_to_prop(propname)) == ZPROP_INVAL) {
1418                 /*
1419                  * For user properties, the amount of work we have to do is very
1420                  * small, so just do it here.
1421                  */
1422                 if (!zfs_prop_user(propname)) {
1423                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1424                             "invalid property"));
1425                         return (zfs_error(hdl, EZFS_BADPROP, errbuf));
1426                 }
1427
1428                 (void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
1429                 (void) strlcpy(zc.zc_value, propname, sizeof (zc.zc_value));
1430
1431                 if (zfs_ioctl(zhp->zfs_hdl, ZFS_IOC_INHERIT_PROP, &zc) != 0)
1432                         return (zfs_standard_error(hdl, errno, errbuf));
1433
1434                 return (0);
1435         }
1436
1437         /*
1438          * Verify that this property is inheritable.
1439          */
1440         if (zfs_prop_readonly(prop))
1441                 return (zfs_error(hdl, EZFS_PROPREADONLY, errbuf));
1442
1443         if (!zfs_prop_inheritable(prop))
1444                 return (zfs_error(hdl, EZFS_PROPNONINHERIT, errbuf));
1445
1446         /*
1447          * Check to see if the value applies to this type
1448          */
1449         if (!zfs_prop_valid_for_type(prop, zhp->zfs_type))
1450                 return (zfs_error(hdl, EZFS_PROPTYPE, errbuf));
1451
1452         /*
1453          * Normalize the name, to get rid of shorthand abbrevations.
1454          */
1455         propname = zfs_prop_to_name(prop);
1456         (void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
1457         (void) strlcpy(zc.zc_value, propname, sizeof (zc.zc_value));
1458
1459         if (prop == ZFS_PROP_MOUNTPOINT && getzoneid() == GLOBAL_ZONEID &&
1460             zfs_prop_get_int(zhp, ZFS_PROP_ZONED)) {
1461                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1462                     "dataset is used in a non-global zone"));
1463                 return (zfs_error(hdl, EZFS_ZONED, errbuf));
1464         }
1465
1466         /*
1467          * Determine datasets which will be affected by this change, if any.
1468          */
1469         if ((cl = changelist_gather(zhp, prop, 0, 0)) == NULL)
1470                 return (-1);
1471
1472         if (prop == ZFS_PROP_MOUNTPOINT && changelist_haszonedchild(cl)) {
1473                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1474                     "child dataset with inherited mountpoint is used "
1475                     "in a non-global zone"));
1476                 ret = zfs_error(hdl, EZFS_ZONED, errbuf);
1477                 goto error;
1478         }
1479
1480         if ((ret = changelist_prefix(cl)) != 0)
1481                 goto error;
1482
1483         if ((ret = zfs_ioctl(zhp->zfs_hdl, ZFS_IOC_INHERIT_PROP, &zc)) != 0) {
1484                 return (zfs_standard_error(hdl, errno, errbuf));
1485         } else {
1486
1487                 if ((ret = changelist_postfix(cl)) != 0)
1488                         goto error;
1489
1490                 /*
1491                  * Refresh the statistics so the new property is reflected.
1492                  */
1493                 (void) get_stats(zhp);
1494         }
1495
1496 error:
1497         changelist_free(cl);
1498         return (ret);
1499 }
1500
1501 /*
1502  * True DSL properties are stored in an nvlist.  The following two functions
1503  * extract them appropriately.
1504  */
1505 static uint64_t
1506 getprop_uint64(zfs_handle_t *zhp, zfs_prop_t prop, char **source)
1507 {
1508         nvlist_t *nv;
1509         uint64_t value;
1510
1511         *source = NULL;
1512         if (nvlist_lookup_nvlist(zhp->zfs_props,
1513             zfs_prop_to_name(prop), &nv) == 0) {
1514                 verify(nvlist_lookup_uint64(nv, ZPROP_VALUE, &value) == 0);
1515                 (void) nvlist_lookup_string(nv, ZPROP_SOURCE, source);
1516         } else {
1517                 verify(!zhp->zfs_props_table ||
1518                     zhp->zfs_props_table[prop] == B_TRUE);
1519                 value = zfs_prop_default_numeric(prop);
1520                 *source = "";
1521         }
1522
1523         return (value);
1524 }
1525
1526 static char *
1527 getprop_string(zfs_handle_t *zhp, zfs_prop_t prop, char **source)
1528 {
1529         nvlist_t *nv;
1530         char *value;
1531
1532         *source = NULL;
1533         if (nvlist_lookup_nvlist(zhp->zfs_props,
1534             zfs_prop_to_name(prop), &nv) == 0) {
1535                 verify(nvlist_lookup_string(nv, ZPROP_VALUE, &value) == 0);
1536                 (void) nvlist_lookup_string(nv, ZPROP_SOURCE, source);
1537         } else {
1538                 verify(!zhp->zfs_props_table ||
1539                     zhp->zfs_props_table[prop] == B_TRUE);
1540                 if ((value = (char *)zfs_prop_default_string(prop)) == NULL)
1541                         value = "";
1542                 *source = "";
1543         }
1544
1545         return (value);
1546 }
1547
1548 /*
1549  * Internal function for getting a numeric property.  Both zfs_prop_get() and
1550  * zfs_prop_get_int() are built using this interface.
1551  *
1552  * Certain properties can be overridden using 'mount -o'.  In this case, scan
1553  * the contents of the /etc/mnttab entry, searching for the appropriate options.
1554  * If they differ from the on-disk values, report the current values and mark
1555  * the source "temporary".
1556  */
1557 static int
1558 get_numeric_property(zfs_handle_t *zhp, zfs_prop_t prop, zprop_source_t *src,
1559     char **source, uint64_t *val)
1560 {
1561         zfs_cmd_t zc = { 0 };
1562         nvlist_t *zplprops = NULL;
1563         struct mnttab mnt;
1564         char *mntopt_on = NULL;
1565         char *mntopt_off = NULL;
1566
1567         *source = NULL;
1568
1569         switch (prop) {
1570         case ZFS_PROP_ATIME:
1571                 mntopt_on = MNTOPT_ATIME;
1572                 mntopt_off = MNTOPT_NOATIME;
1573                 break;
1574
1575         case ZFS_PROP_DEVICES:
1576                 mntopt_on = MNTOPT_DEVICES;
1577                 mntopt_off = MNTOPT_NODEVICES;
1578                 break;
1579
1580         case ZFS_PROP_EXEC:
1581                 mntopt_on = MNTOPT_EXEC;
1582                 mntopt_off = MNTOPT_NOEXEC;
1583                 break;
1584
1585         case ZFS_PROP_READONLY:
1586                 mntopt_on = MNTOPT_RO;
1587                 mntopt_off = MNTOPT_RW;
1588                 break;
1589
1590         case ZFS_PROP_SETUID:
1591                 mntopt_on = MNTOPT_SETUID;
1592                 mntopt_off = MNTOPT_NOSETUID;
1593                 break;
1594
1595         case ZFS_PROP_XATTR:
1596                 mntopt_on = MNTOPT_XATTR;
1597                 mntopt_off = MNTOPT_NOXATTR;
1598                 break;
1599
1600         case ZFS_PROP_NBMAND:
1601                 mntopt_on = MNTOPT_NBMAND;
1602                 mntopt_off = MNTOPT_NONBMAND;
1603                 break;
1604         }
1605
1606         /*
1607          * Because looking up the mount options is potentially expensive
1608          * (iterating over all of /etc/mnttab), we defer its calculation until
1609          * we're looking up a property which requires its presence.
1610          */
1611         if (!zhp->zfs_mntcheck &&
1612             (mntopt_on != NULL || prop == ZFS_PROP_MOUNTED)) {
1613                 libzfs_handle_t *hdl = zhp->zfs_hdl;
1614                 struct mnttab entry;
1615
1616                 if (libzfs_mnttab_find(hdl, zhp->zfs_name, &entry) == 0) {
1617                         zhp->zfs_mntopts = zfs_strdup(hdl,
1618                             entry.mnt_mntopts);
1619                         if (zhp->zfs_mntopts == NULL)
1620                                 return (-1);
1621                 }
1622
1623                 zhp->zfs_mntcheck = B_TRUE;
1624         }
1625
1626         if (zhp->zfs_mntopts == NULL)
1627                 mnt.mnt_mntopts = "";
1628         else
1629                 mnt.mnt_mntopts = zhp->zfs_mntopts;
1630
1631         switch (prop) {
1632         case ZFS_PROP_ATIME:
1633         case ZFS_PROP_DEVICES:
1634         case ZFS_PROP_EXEC:
1635         case ZFS_PROP_READONLY:
1636         case ZFS_PROP_SETUID:
1637         case ZFS_PROP_XATTR:
1638         case ZFS_PROP_NBMAND:
1639                 *val = getprop_uint64(zhp, prop, source);
1640
1641                 if (hasmntopt(&mnt, mntopt_on) && !*val) {
1642                         *val = B_TRUE;
1643                         if (src)
1644                                 *src = ZPROP_SRC_TEMPORARY;
1645                 } else if (hasmntopt(&mnt, mntopt_off) && *val) {
1646                         *val = B_FALSE;
1647                         if (src)
1648                                 *src = ZPROP_SRC_TEMPORARY;
1649                 }
1650                 break;
1651
1652         case ZFS_PROP_CANMOUNT:
1653                 *val = getprop_uint64(zhp, prop, source);
1654                 if (*val != ZFS_CANMOUNT_ON)
1655                         *source = zhp->zfs_name;
1656                 else
1657                         *source = "";   /* default */
1658                 break;
1659
1660         case ZFS_PROP_QUOTA:
1661         case ZFS_PROP_REFQUOTA:
1662         case ZFS_PROP_RESERVATION:
1663         case ZFS_PROP_REFRESERVATION:
1664                 *val = getprop_uint64(zhp, prop, source);
1665                 if (*val == 0)
1666                         *source = "";   /* default */
1667                 else
1668                         *source = zhp->zfs_name;
1669                 break;
1670
1671         case ZFS_PROP_MOUNTED:
1672                 *val = (zhp->zfs_mntopts != NULL);
1673                 break;
1674
1675         case ZFS_PROP_NUMCLONES:
1676                 *val = zhp->zfs_dmustats.dds_num_clones;
1677                 break;
1678
1679         case ZFS_PROP_VERSION:
1680         case ZFS_PROP_NORMALIZE:
1681         case ZFS_PROP_UTF8ONLY:
1682         case ZFS_PROP_CASE:
1683                 if (!zfs_prop_valid_for_type(prop, zhp->zfs_head_type) ||
1684                     zcmd_alloc_dst_nvlist(zhp->zfs_hdl, &zc, 0) != 0)
1685                         return (-1);
1686                 (void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
1687                 if (zfs_ioctl(zhp->zfs_hdl, ZFS_IOC_OBJSET_ZPLPROPS, &zc)) {
1688                         zcmd_free_nvlists(&zc);
1689                         zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1690                             "unable to get %s property"),
1691                             zfs_prop_to_name(prop));
1692                         return (zfs_error(zhp->zfs_hdl, EZFS_BADVERSION,
1693                             dgettext(TEXT_DOMAIN, "internal error")));
1694                 }
1695                 if (zcmd_read_dst_nvlist(zhp->zfs_hdl, &zc, &zplprops) != 0 ||
1696                     nvlist_lookup_uint64(zplprops, zfs_prop_to_name(prop),
1697                     val) != 0) {
1698                         zcmd_free_nvlists(&zc);
1699                         zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1700                             "unable to get %s property"),
1701                             zfs_prop_to_name(prop));
1702                         return (zfs_error(zhp->zfs_hdl, EZFS_NOMEM,
1703                             dgettext(TEXT_DOMAIN, "internal error")));
1704                 }
1705                 if (zplprops)
1706                         nvlist_free(zplprops);
1707                 zcmd_free_nvlists(&zc);
1708                 break;
1709
1710         default:
1711                 switch (zfs_prop_get_type(prop)) {
1712                 case PROP_TYPE_NUMBER:
1713                 case PROP_TYPE_INDEX:
1714                         *val = getprop_uint64(zhp, prop, source);
1715                         /*
1716                          * If we tried to use a default value for a
1717                          * readonly property, it means that it was not
1718                          * present; return an error.
1719                          */
1720                         if (zfs_prop_readonly(prop) &&
1721                             *source && (*source)[0] == '\0') {
1722                                 return (-1);
1723                         }
1724                         break;
1725
1726                 case PROP_TYPE_STRING:
1727                 default:
1728                         zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1729                             "cannot get non-numeric property"));
1730                         return (zfs_error(zhp->zfs_hdl, EZFS_BADPROP,
1731                             dgettext(TEXT_DOMAIN, "internal error")));
1732                 }
1733         }
1734
1735         return (0);
1736 }
1737
1738 /*
1739  * Calculate the source type, given the raw source string.
1740  */
1741 static void
1742 get_source(zfs_handle_t *zhp, zprop_source_t *srctype, char *source,
1743     char *statbuf, size_t statlen)
1744 {
1745         if (statbuf == NULL || *srctype == ZPROP_SRC_TEMPORARY)
1746                 return;
1747
1748         if (source == NULL) {
1749                 *srctype = ZPROP_SRC_NONE;
1750         } else if (source[0] == '\0') {
1751                 *srctype = ZPROP_SRC_DEFAULT;
1752         } else {
1753                 if (strcmp(source, zhp->zfs_name) == 0) {
1754                         *srctype = ZPROP_SRC_LOCAL;
1755                 } else {
1756                         (void) strlcpy(statbuf, source, statlen);
1757                         *srctype = ZPROP_SRC_INHERITED;
1758                 }
1759         }
1760
1761 }
1762
1763 /*
1764  * Retrieve a property from the given object.  If 'literal' is specified, then
1765  * numbers are left as exact values.  Otherwise, numbers are converted to a
1766  * human-readable form.
1767  *
1768  * Returns 0 on success, or -1 on error.
1769  */
1770 int
1771 zfs_prop_get(zfs_handle_t *zhp, zfs_prop_t prop, char *propbuf, size_t proplen,
1772     zprop_source_t *src, char *statbuf, size_t statlen, boolean_t literal)
1773 {
1774         char *source = NULL;
1775         uint64_t val;
1776         char *str;
1777         const char *strval;
1778
1779         /*
1780          * Check to see if this property applies to our object
1781          */
1782         if (!zfs_prop_valid_for_type(prop, zhp->zfs_type))
1783                 return (-1);
1784
1785         if (src)
1786                 *src = ZPROP_SRC_NONE;
1787
1788         switch (prop) {
1789         case ZFS_PROP_CREATION:
1790                 /*
1791                  * 'creation' is a time_t stored in the statistics.  We convert
1792                  * this into a string unless 'literal' is specified.
1793                  */
1794                 {
1795                         val = getprop_uint64(zhp, prop, &source);
1796                         time_t time = (time_t)val;
1797                         struct tm t;
1798
1799                         if (literal ||
1800                             localtime_r(&time, &t) == NULL ||
1801                             strftime(propbuf, proplen, "%a %b %e %k:%M %Y",
1802                             &t) == 0)
1803                                 (void) snprintf(propbuf, proplen, "%llu", val);
1804                 }
1805                 break;
1806
1807         case ZFS_PROP_MOUNTPOINT:
1808                 /*
1809                  * Getting the precise mountpoint can be tricky.
1810                  *
1811                  *  - for 'none' or 'legacy', return those values.
1812                  *  - for inherited mountpoints, we want to take everything
1813                  *    after our ancestor and append it to the inherited value.
1814                  *
1815                  * If the pool has an alternate root, we want to prepend that
1816                  * root to any values we return.
1817                  */
1818
1819                 str = getprop_string(zhp, prop, &source);
1820
1821                 if (str[0] == '/') {
1822                         char buf[MAXPATHLEN];
1823                         char *root = buf;
1824                         const char *relpath = zhp->zfs_name + strlen(source);
1825
1826                         if (relpath[0] == '/')
1827                                 relpath++;
1828
1829                         if ((zpool_get_prop(zhp->zpool_hdl,
1830                             ZPOOL_PROP_ALTROOT, buf, MAXPATHLEN, NULL)) ||
1831                             (strcmp(root, "-") == 0))
1832                                 root[0] = '\0';
1833                         /*
1834                          * Special case an alternate root of '/'. This will
1835                          * avoid having multiple leading slashes in the
1836                          * mountpoint path.
1837                          */
1838                         if (strcmp(root, "/") == 0)
1839                                 root++;
1840
1841                         /*
1842                          * If the mountpoint is '/' then skip over this
1843                          * if we are obtaining either an alternate root or
1844                          * an inherited mountpoint.
1845                          */
1846                         if (str[1] == '\0' && (root[0] != '\0' ||
1847                             relpath[0] != '\0'))
1848                                 str++;
1849
1850                         if (relpath[0] == '\0')
1851                                 (void) snprintf(propbuf, proplen, "%s%s",
1852                                     root, str);
1853                         else
1854                                 (void) snprintf(propbuf, proplen, "%s%s%s%s",
1855                                     root, str, relpath[0] == '@' ? "" : "/",
1856                                     relpath);
1857                 } else {
1858                         /* 'legacy' or 'none' */
1859                         (void) strlcpy(propbuf, str, proplen);
1860                 }
1861
1862                 break;
1863
1864         case ZFS_PROP_ORIGIN:
1865                 (void) strlcpy(propbuf, getprop_string(zhp, prop, &source),
1866                     proplen);
1867                 /*
1868                  * If there is no parent at all, return failure to indicate that
1869                  * it doesn't apply to this dataset.
1870                  */
1871                 if (propbuf[0] == '\0')
1872                         return (-1);
1873                 break;
1874
1875         case ZFS_PROP_QUOTA:
1876         case ZFS_PROP_REFQUOTA:
1877         case ZFS_PROP_RESERVATION:
1878         case ZFS_PROP_REFRESERVATION:
1879
1880                 if (get_numeric_property(zhp, prop, src, &source, &val) != 0)
1881                         return (-1);
1882
1883                 /*
1884                  * If quota or reservation is 0, we translate this into 'none'
1885                  * (unless literal is set), and indicate that it's the default
1886                  * value.  Otherwise, we print the number nicely and indicate
1887                  * that its set locally.
1888                  */
1889                 if (val == 0) {
1890                         if (literal)
1891                                 (void) strlcpy(propbuf, "0", proplen);
1892                         else
1893                                 (void) strlcpy(propbuf, "none", proplen);
1894                 } else {
1895                         if (literal)
1896                                 (void) snprintf(propbuf, proplen, "%llu",
1897                                     (u_longlong_t)val);
1898                         else
1899                                 zfs_nicenum(val, propbuf, proplen);
1900                 }
1901                 break;
1902
1903         case ZFS_PROP_COMPRESSRATIO:
1904                 if (get_numeric_property(zhp, prop, src, &source, &val) != 0)
1905                         return (-1);
1906                 (void) snprintf(propbuf, proplen, "%lld.%02lldx", (longlong_t)
1907                     val / 100, (longlong_t)val % 100);
1908                 break;
1909
1910         case ZFS_PROP_TYPE:
1911                 switch (zhp->zfs_type) {
1912                 case ZFS_TYPE_FILESYSTEM:
1913                         str = "filesystem";
1914                         break;
1915                 case ZFS_TYPE_VOLUME:
1916                         str = "volume";
1917                         break;
1918                 case ZFS_TYPE_SNAPSHOT:
1919                         str = "snapshot";
1920                         break;
1921                 default:
1922                         abort();
1923                 }
1924                 (void) snprintf(propbuf, proplen, "%s", str);
1925                 break;
1926
1927         case ZFS_PROP_MOUNTED:
1928                 /*
1929                  * The 'mounted' property is a pseudo-property that described
1930                  * whether the filesystem is currently mounted.  Even though
1931                  * it's a boolean value, the typical values of "on" and "off"
1932                  * don't make sense, so we translate to "yes" and "no".
1933                  */
1934                 if (get_numeric_property(zhp, ZFS_PROP_MOUNTED,
1935                     src, &source, &val) != 0)
1936                         return (-1);
1937                 if (val)
1938                         (void) strlcpy(propbuf, "yes", proplen);
1939                 else
1940                         (void) strlcpy(propbuf, "no", proplen);
1941                 break;
1942
1943         case ZFS_PROP_NAME:
1944                 /*
1945                  * The 'name' property is a pseudo-property derived from the
1946                  * dataset name.  It is presented as a real property to simplify
1947                  * consumers.
1948                  */
1949                 (void) strlcpy(propbuf, zhp->zfs_name, proplen);
1950                 break;
1951
1952         default:
1953                 switch (zfs_prop_get_type(prop)) {
1954                 case PROP_TYPE_NUMBER:
1955                         if (get_numeric_property(zhp, prop, src,
1956                             &source, &val) != 0)
1957                                 return (-1);
1958                         if (literal)
1959                                 (void) snprintf(propbuf, proplen, "%llu",
1960                                     (u_longlong_t)val);
1961                         else
1962                                 zfs_nicenum(val, propbuf, proplen);
1963                         break;
1964
1965                 case PROP_TYPE_STRING:
1966                         (void) strlcpy(propbuf,
1967                             getprop_string(zhp, prop, &source), proplen);
1968                         break;
1969
1970                 case PROP_TYPE_INDEX:
1971                         if (get_numeric_property(zhp, prop, src,
1972                             &source, &val) != 0)
1973                                 return (-1);
1974                         if (zfs_prop_index_to_string(prop, val, &strval) != 0)
1975                                 return (-1);
1976                         (void) strlcpy(propbuf, strval, proplen);
1977                         break;
1978
1979                 default:
1980                         abort();
1981                 }
1982         }
1983
1984         get_source(zhp, src, source, statbuf, statlen);
1985
1986         return (0);
1987 }
1988
1989 /*
1990  * Utility function to get the given numeric property.  Does no validation that
1991  * the given property is the appropriate type; should only be used with
1992  * hard-coded property types.
1993  */
1994 uint64_t
1995 zfs_prop_get_int(zfs_handle_t *zhp, zfs_prop_t prop)
1996 {
1997         char *source;
1998         uint64_t val;
1999
2000         (void) get_numeric_property(zhp, prop, NULL, &source, &val);
2001
2002         return (val);
2003 }
2004
2005 int
2006 zfs_prop_set_int(zfs_handle_t *zhp, zfs_prop_t prop, uint64_t val)
2007 {
2008         char buf[64];
2009
2010         (void) snprintf(buf, sizeof (buf), "%llu", (longlong_t)val);
2011         return (zfs_prop_set(zhp, zfs_prop_to_name(prop), buf));
2012 }
2013
2014 /*
2015  * Similar to zfs_prop_get(), but returns the value as an integer.
2016  */
2017 int
2018 zfs_prop_get_numeric(zfs_handle_t *zhp, zfs_prop_t prop, uint64_t *value,
2019     zprop_source_t *src, char *statbuf, size_t statlen)
2020 {
2021         char *source;
2022
2023         /*
2024          * Check to see if this property applies to our object
2025          */
2026         if (!zfs_prop_valid_for_type(prop, zhp->zfs_type)) {
2027                 return (zfs_error_fmt(zhp->zfs_hdl, EZFS_PROPTYPE,
2028                     dgettext(TEXT_DOMAIN, "cannot get property '%s'"),
2029                     zfs_prop_to_name(prop)));
2030         }
2031
2032         if (src)
2033                 *src = ZPROP_SRC_NONE;
2034
2035         if (get_numeric_property(zhp, prop, src, &source, value) != 0)
2036                 return (-1);
2037
2038         get_source(zhp, src, source, statbuf, statlen);
2039
2040         return (0);
2041 }
2042
2043 static int
2044 idmap_id_to_numeric_domain_rid(uid_t id, boolean_t isuser,
2045     char **domainp, idmap_rid_t *ridp)
2046 {
2047 #ifdef sun
2048         idmap_handle_t *idmap_hdl = NULL;
2049         idmap_get_handle_t *get_hdl = NULL;
2050         idmap_stat status;
2051         int err = EINVAL;
2052
2053         if (idmap_init(&idmap_hdl) != IDMAP_SUCCESS)
2054                 goto out;
2055         if (idmap_get_create(idmap_hdl, &get_hdl) != IDMAP_SUCCESS)
2056                 goto out;
2057
2058         if (isuser) {
2059                 err = idmap_get_sidbyuid(get_hdl, id,
2060                     IDMAP_REQ_FLG_USE_CACHE, domainp, ridp, &status);
2061         } else {
2062                 err = idmap_get_sidbygid(get_hdl, id,
2063                     IDMAP_REQ_FLG_USE_CACHE, domainp, ridp, &status);
2064         }
2065         if (err == IDMAP_SUCCESS &&
2066             idmap_get_mappings(get_hdl) == IDMAP_SUCCESS &&
2067             status == IDMAP_SUCCESS)
2068                 err = 0;
2069         else
2070                 err = EINVAL;
2071 out:
2072         if (get_hdl)
2073                 idmap_get_destroy(get_hdl);
2074         if (idmap_hdl)
2075                 (void) idmap_fini(idmap_hdl);
2076         return (err);
2077 #else   /* !sun */
2078         assert(!"invalid code path");
2079 #endif  /* !sun */
2080 }
2081
2082 #ifndef sun
2083 /* Check if a string contains only digits */
2084 static int
2085 string_is_digits(char *cp)
2086 {
2087         int i;
2088
2089         for(i = 0; i < strlen(cp); i++)
2090             if(!isdigit(cp[i]))
2091                 return (0);
2092         return (1);
2093 }
2094
2095 #endif  /* !sun */
2096
2097 /*
2098  * convert the propname into parameters needed by kernel
2099  * Eg: userquota@ahrens -> ZFS_PROP_USERQUOTA, "", 126829
2100  * Eg: userused@matt@domain -> ZFS_PROP_USERUSED, "S-1-123-456", 789
2101  */
2102 static int
2103 userquota_propname_decode(const char *propname, boolean_t zoned,
2104     zfs_userquota_prop_t *typep, char *domain, int domainlen, uint64_t *ridp)
2105 {
2106         zfs_userquota_prop_t type;
2107         char *cp, *end;
2108         char *numericsid = NULL;
2109         boolean_t isuser;
2110
2111         domain[0] = '\0';
2112
2113         /* Figure out the property type ({user|group}{quota|space}) */
2114         for (type = 0; type < ZFS_NUM_USERQUOTA_PROPS; type++) {
2115                 if (strncmp(propname, zfs_userquota_prop_prefixes[type],
2116                     strlen(zfs_userquota_prop_prefixes[type])) == 0)
2117                         break;
2118         }
2119         if (type == ZFS_NUM_USERQUOTA_PROPS)
2120                 return (EINVAL);
2121         *typep = type;
2122
2123         isuser = (type == ZFS_PROP_USERQUOTA ||
2124             type == ZFS_PROP_USERUSED);
2125
2126         cp = strchr(propname, '@') + 1;
2127
2128         if (strchr(cp, '@')) {
2129 #ifdef sun
2130                 /*
2131                  * It's a SID name (eg "user@domain") that needs to be
2132                  * turned into S-1-domainID-RID.
2133                  */
2134                 directory_error_t e;
2135
2136                 if (zoned && getzoneid() == GLOBAL_ZONEID)
2137                         return (ENOENT);
2138                 if (isuser) {
2139                         e = directory_sid_from_user_name(NULL,
2140                             cp, &numericsid);
2141                 } else {
2142                         e = directory_sid_from_group_name(NULL,
2143                             cp, &numericsid);
2144                 }
2145                 if (e != NULL) {
2146                         directory_error_free(e);
2147                         return (ENOENT);
2148                 }
2149                 if (numericsid == NULL)
2150                         return (ENOENT);
2151                 cp = numericsid;
2152                 /* will be further decoded below */
2153 #else   /* !sun */
2154                 return (ENOENT);
2155 #endif  /* !sun */
2156         }
2157
2158         if (strncmp(cp, "S-1-", 4) == 0) {
2159                 /* It's a numeric SID (eg "S-1-234-567-89") */
2160                 (void) strlcpy(domain, cp, domainlen);
2161                 cp = strrchr(domain, '-');
2162                 *cp = '\0';
2163                 cp++;
2164
2165                 errno = 0;
2166                 *ridp = strtoull(cp, &end, 10);
2167                 if (numericsid) {
2168                         free(numericsid);
2169                         numericsid = NULL;
2170                 }
2171                 if (errno != 0 || *end != '\0')
2172                         return (EINVAL);
2173 #ifdef sun
2174         } else if (!isdigit(*cp)) {
2175 #else   /* sun */
2176         /*
2177          * In FreeBSD user and group names can begin with a digit so treat
2178          * as a uid/gid if string contains digits only
2179          */
2180         } else if (!string_is_digits(cp)) {
2181 #endif  /* sun */
2182                 /*
2183                  * It's a user/group name (eg "user") that needs to be
2184                  * turned into a uid/gid
2185                  */
2186                 if (zoned && getzoneid() == GLOBAL_ZONEID)
2187                         return (ENOENT);
2188                 if (isuser) {
2189                         struct passwd *pw;
2190                         pw = getpwnam(cp);
2191                         if (pw == NULL)
2192                                 return (ENOENT);
2193                         *ridp = pw->pw_uid;
2194                 } else {
2195                         struct group *gr;
2196                         gr = getgrnam(cp);
2197                         if (gr == NULL)
2198                                 return (ENOENT);
2199                         *ridp = gr->gr_gid;
2200                 }
2201         } else {
2202                 /* It's a user/group ID (eg "12345"). */
2203                 uid_t id = strtoul(cp, &end, 10);
2204                 idmap_rid_t rid;
2205                 char *mapdomain;
2206
2207                 if (*end != '\0')
2208                         return (EINVAL);
2209                 if (id > MAXUID) {
2210                         /* It's an ephemeral ID. */
2211                         if (idmap_id_to_numeric_domain_rid(id, isuser,
2212                             &mapdomain, &rid) != 0)
2213                                 return (ENOENT);
2214                         (void) strlcpy(domain, mapdomain, domainlen);
2215                         *ridp = rid;
2216                 } else {
2217                         *ridp = id;
2218                 }
2219         }
2220
2221         ASSERT3P(numericsid, ==, NULL);
2222         return (0);
2223 }
2224
2225 static int
2226 zfs_prop_get_userquota_common(zfs_handle_t *zhp, const char *propname,
2227     uint64_t *propvalue, zfs_userquota_prop_t *typep)
2228 {
2229         int err;
2230         zfs_cmd_t zc = { 0 };
2231
2232         (void) strncpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
2233
2234         err = userquota_propname_decode(propname,
2235             zfs_prop_get_int(zhp, ZFS_PROP_ZONED),
2236             typep, zc.zc_value, sizeof (zc.zc_value), &zc.zc_guid);
2237         zc.zc_objset_type = *typep;
2238         if (err)
2239                 return (err);
2240
2241         err = ioctl(zhp->zfs_hdl->libzfs_fd, ZFS_IOC_USERSPACE_ONE, &zc);
2242         if (err)
2243                 return (err);
2244
2245         *propvalue = zc.zc_cookie;
2246         return (0);
2247 }
2248
2249 int
2250 zfs_prop_get_userquota_int(zfs_handle_t *zhp, const char *propname,
2251     uint64_t *propvalue)
2252 {
2253         zfs_userquota_prop_t type;
2254
2255         return (zfs_prop_get_userquota_common(zhp, propname, propvalue,
2256             &type));
2257 }
2258
2259 int
2260 zfs_prop_get_userquota(zfs_handle_t *zhp, const char *propname,
2261     char *propbuf, int proplen, boolean_t literal)
2262 {
2263         int err;
2264         uint64_t propvalue;
2265         zfs_userquota_prop_t type;
2266
2267         err = zfs_prop_get_userquota_common(zhp, propname, &propvalue,
2268             &type);
2269
2270         if (err)
2271                 return (err);
2272
2273         if (literal) {
2274                 (void) snprintf(propbuf, proplen, "%llu", propvalue);
2275         } else if (propvalue == 0 &&
2276             (type == ZFS_PROP_USERQUOTA || type == ZFS_PROP_GROUPQUOTA)) {
2277                 (void) strlcpy(propbuf, "none", proplen);
2278         } else {
2279                 zfs_nicenum(propvalue, propbuf, proplen);
2280         }
2281         return (0);
2282 }
2283
2284 /*
2285  * Returns the name of the given zfs handle.
2286  */
2287 const char *
2288 zfs_get_name(const zfs_handle_t *zhp)
2289 {
2290         return (zhp->zfs_name);
2291 }
2292
2293 /*
2294  * Returns the type of the given zfs handle.
2295  */
2296 zfs_type_t
2297 zfs_get_type(const zfs_handle_t *zhp)
2298 {
2299         return (zhp->zfs_type);
2300 }
2301
2302 static int
2303 zfs_do_list_ioctl(zfs_handle_t *zhp, unsigned long arg, zfs_cmd_t *zc)
2304 {
2305         int rc;
2306         uint64_t        orig_cookie;
2307
2308         orig_cookie = zc->zc_cookie;
2309 top:
2310         (void) strlcpy(zc->zc_name, zhp->zfs_name, sizeof (zc->zc_name));
2311         rc = ioctl(zhp->zfs_hdl->libzfs_fd, arg, zc);
2312
2313         /*
2314          * FreeBSD compatibility with pre-v15 kernel module.
2315          * Ignore private dataset names.
2316          */
2317         if (strchr(zc->zc_name, '$') != NULL)
2318                 rc = 0;
2319
2320         if (rc == -1) {
2321                 switch (errno) {
2322                 case ENOMEM:
2323                         /* expand nvlist memory and try again */
2324                         if (zcmd_expand_dst_nvlist(zhp->zfs_hdl, zc) != 0) {
2325                                 zcmd_free_nvlists(zc);
2326                                 return (-1);
2327                         }
2328                         zc->zc_cookie = orig_cookie;
2329                         goto top;
2330                 /*
2331                  * An errno value of ESRCH indicates normal completion.
2332                  * If ENOENT is returned, then the underlying dataset
2333                  * has been removed since we obtained the handle.
2334                  */
2335                 case ESRCH:
2336                 case ENOENT:
2337                         rc = 1;
2338                         break;
2339                 default:
2340                         rc = zfs_standard_error(zhp->zfs_hdl, errno,
2341                             dgettext(TEXT_DOMAIN,
2342                             "cannot iterate filesystems"));
2343                         break;
2344                 }
2345         }
2346         return (rc);
2347 }
2348
2349 /*
2350  * Iterate over all child filesystems
2351  */
2352 int
2353 zfs_iter_filesystems(zfs_handle_t *zhp, zfs_iter_f func, void *data)
2354 {
2355         zfs_cmd_t zc = { 0 };
2356         zfs_handle_t *nzhp;
2357         int ret;
2358
2359         if (zhp->zfs_type != ZFS_TYPE_FILESYSTEM)
2360                 return (0);
2361
2362         if (zcmd_alloc_dst_nvlist(zhp->zfs_hdl, &zc, 0) != 0)
2363                 return (-1);
2364
2365         while ((ret = zfs_do_list_ioctl(zhp, ZFS_IOC_DATASET_LIST_NEXT,
2366             &zc)) == 0) {
2367
2368                 /*
2369                  * FreeBSD compatibility with pre-v15 kernel module.
2370                  * Ignore private dataset names.
2371                  */
2372                 if (strchr(zc.zc_name, '$') != NULL)
2373                         continue;
2374
2375                 /*
2376                  * Silently ignore errors, as the only plausible explanation is
2377                  * that the pool has since been removed.
2378                  */
2379                 if ((nzhp = make_dataset_handle_zc(zhp->zfs_hdl,
2380                     &zc)) == NULL) {
2381                         continue;
2382                 }
2383
2384                 if ((ret = func(nzhp, data)) != 0) {
2385                         zcmd_free_nvlists(&zc);
2386                         return (ret);
2387                 }
2388         }
2389         zcmd_free_nvlists(&zc);
2390         return ((ret < 0) ? ret : 0);
2391 }
2392
2393 /*
2394  * Iterate over all snapshots
2395  */
2396 int
2397 zfs_iter_snapshots(zfs_handle_t *zhp, zfs_iter_f func, void *data)
2398 {
2399         zfs_cmd_t zc = { 0 };
2400         zfs_handle_t *nzhp;
2401         int ret;
2402
2403         if (zhp->zfs_type == ZFS_TYPE_SNAPSHOT)
2404                 return (0);
2405
2406         if (zcmd_alloc_dst_nvlist(zhp->zfs_hdl, &zc, 0) != 0)
2407                 return (-1);
2408         while ((ret = zfs_do_list_ioctl(zhp, ZFS_IOC_SNAPSHOT_LIST_NEXT,
2409             &zc)) == 0) {
2410
2411                 /*
2412                  * FreeBSD compatibility with pre-v15 kernel module.
2413                  * Ignore private dataset names.
2414                  */
2415                 if (strchr(zc.zc_name, '$') != NULL)
2416                         continue;
2417
2418                 if ((nzhp = make_dataset_handle_zc(zhp->zfs_hdl,
2419                     &zc)) == NULL) {
2420                         continue;
2421                 }
2422
2423                 if ((ret = func(nzhp, data)) != 0) {
2424                         zcmd_free_nvlists(&zc);
2425                         return (ret);
2426                 }
2427         }
2428         zcmd_free_nvlists(&zc);
2429         return ((ret < 0) ? ret : 0);
2430 }
2431
2432 /*
2433  * Iterate over all children, snapshots and filesystems
2434  */
2435 int
2436 zfs_iter_children(zfs_handle_t *zhp, zfs_iter_f func, void *data)
2437 {
2438         int ret;
2439
2440         if ((ret = zfs_iter_filesystems(zhp, func, data)) != 0)
2441                 return (ret);
2442
2443         return (zfs_iter_snapshots(zhp, func, data));
2444 }
2445
2446 /*
2447  * Given a complete name, return just the portion that refers to the parent.
2448  * Can return NULL if this is a pool.
2449  */
2450 static int
2451 parent_name(const char *path, char *buf, size_t buflen)
2452 {
2453         char *loc;
2454
2455         if ((loc = strrchr(path, '/')) == NULL)
2456                 return (-1);
2457
2458         (void) strncpy(buf, path, MIN(buflen, loc - path));
2459         buf[loc - path] = '\0';
2460
2461         return (0);
2462 }
2463
2464 /*
2465  * If accept_ancestor is false, then check to make sure that the given path has
2466  * a parent, and that it exists.  If accept_ancestor is true, then find the
2467  * closest existing ancestor for the given path.  In prefixlen return the
2468  * length of already existing prefix of the given path.  We also fetch the
2469  * 'zoned' property, which is used to validate property settings when creating
2470  * new datasets.
2471  */
2472 static int
2473 check_parents(libzfs_handle_t *hdl, const char *path, uint64_t *zoned,
2474     boolean_t accept_ancestor, int *prefixlen)
2475 {
2476         zfs_cmd_t zc = { 0 };
2477         char parent[ZFS_MAXNAMELEN];
2478         char *slash;
2479         zfs_handle_t *zhp;
2480         char errbuf[1024];
2481
2482         (void) snprintf(errbuf, sizeof (errbuf),
2483             dgettext(TEXT_DOMAIN, "cannot create '%s'"), path);
2484
2485         /* get parent, and check to see if this is just a pool */
2486         if (parent_name(path, parent, sizeof (parent)) != 0) {
2487                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2488                     "missing dataset name"));
2489                 return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
2490         }
2491
2492         /* check to see if the pool exists */
2493         if ((slash = strchr(parent, '/')) == NULL)
2494                 slash = parent + strlen(parent);
2495         (void) strncpy(zc.zc_name, parent, slash - parent);
2496         zc.zc_name[slash - parent] = '\0';
2497         if (ioctl(hdl->libzfs_fd, ZFS_IOC_OBJSET_STATS, &zc) != 0 &&
2498             errno == ENOENT) {
2499                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2500                     "no such pool '%s'"), zc.zc_name);
2501                 return (zfs_error(hdl, EZFS_NOENT, errbuf));
2502         }
2503
2504         /* check to see if the parent dataset exists */
2505         while ((zhp = make_dataset_handle(hdl, parent)) == NULL) {
2506                 if (errno == ENOENT && accept_ancestor) {
2507                         /*
2508                          * Go deeper to find an ancestor, give up on top level.
2509                          */
2510                         if (parent_name(parent, parent, sizeof (parent)) != 0) {
2511                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2512                                     "no such pool '%s'"), zc.zc_name);
2513                                 return (zfs_error(hdl, EZFS_NOENT, errbuf));
2514                         }
2515                 } else if (errno == ENOENT) {
2516                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2517                             "parent does not exist"));
2518                         return (zfs_error(hdl, EZFS_NOENT, errbuf));
2519                 } else
2520                         return (zfs_standard_error(hdl, errno, errbuf));
2521         }
2522
2523         *zoned = zfs_prop_get_int(zhp, ZFS_PROP_ZONED);
2524         /* we are in a non-global zone, but parent is in the global zone */
2525         if (getzoneid() != GLOBAL_ZONEID && !(*zoned)) {
2526                 (void) zfs_standard_error(hdl, EPERM, errbuf);
2527                 zfs_close(zhp);
2528                 return (-1);
2529         }
2530
2531         /* make sure parent is a filesystem */
2532         if (zfs_get_type(zhp) != ZFS_TYPE_FILESYSTEM) {
2533                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2534                     "parent is not a filesystem"));
2535                 (void) zfs_error(hdl, EZFS_BADTYPE, errbuf);
2536                 zfs_close(zhp);
2537                 return (-1);
2538         }
2539
2540         zfs_close(zhp);
2541         if (prefixlen != NULL)
2542                 *prefixlen = strlen(parent);
2543         return (0);
2544 }
2545
2546 /*
2547  * Finds whether the dataset of the given type(s) exists.
2548  */
2549 boolean_t
2550 zfs_dataset_exists(libzfs_handle_t *hdl, const char *path, zfs_type_t types)
2551 {
2552         zfs_handle_t *zhp;
2553
2554         if (!zfs_validate_name(hdl, path, types, B_FALSE))
2555                 return (B_FALSE);
2556
2557         /*
2558          * Try to get stats for the dataset, which will tell us if it exists.
2559          */
2560         if ((zhp = make_dataset_handle(hdl, path)) != NULL) {
2561                 int ds_type = zhp->zfs_type;
2562
2563                 zfs_close(zhp);
2564                 if (types & ds_type)
2565                         return (B_TRUE);
2566         }
2567         return (B_FALSE);
2568 }
2569
2570 /*
2571  * Given a path to 'target', create all the ancestors between
2572  * the prefixlen portion of the path, and the target itself.
2573  * Fail if the initial prefixlen-ancestor does not already exist.
2574  */
2575 int
2576 create_parents(libzfs_handle_t *hdl, char *target, int prefixlen)
2577 {
2578         zfs_handle_t *h;
2579         char *cp;
2580         const char *opname;
2581
2582         /* make sure prefix exists */
2583         cp = target + prefixlen;
2584         if (*cp != '/') {
2585                 assert(strchr(cp, '/') == NULL);
2586                 h = zfs_open(hdl, target, ZFS_TYPE_FILESYSTEM);
2587         } else {
2588                 *cp = '\0';
2589                 h = zfs_open(hdl, target, ZFS_TYPE_FILESYSTEM);
2590                 *cp = '/';
2591         }
2592         if (h == NULL)
2593                 return (-1);
2594         zfs_close(h);
2595
2596         /*
2597          * Attempt to create, mount, and share any ancestor filesystems,
2598          * up to the prefixlen-long one.
2599          */
2600         for (cp = target + prefixlen + 1;
2601             cp = strchr(cp, '/'); *cp = '/', cp++) {
2602                 char *logstr;
2603
2604                 *cp = '\0';
2605
2606                 h = make_dataset_handle(hdl, target);
2607                 if (h) {
2608                         /* it already exists, nothing to do here */
2609                         zfs_close(h);
2610                         continue;
2611                 }
2612
2613                 logstr = hdl->libzfs_log_str;
2614                 hdl->libzfs_log_str = NULL;
2615                 if (zfs_create(hdl, target, ZFS_TYPE_FILESYSTEM,
2616                     NULL) != 0) {
2617                         hdl->libzfs_log_str = logstr;
2618                         opname = dgettext(TEXT_DOMAIN, "create");
2619                         goto ancestorerr;
2620                 }
2621
2622                 hdl->libzfs_log_str = logstr;
2623                 h = zfs_open(hdl, target, ZFS_TYPE_FILESYSTEM);
2624                 if (h == NULL) {
2625                         opname = dgettext(TEXT_DOMAIN, "open");
2626                         goto ancestorerr;
2627                 }
2628
2629                 if (zfs_mount(h, NULL, 0) != 0) {
2630                         opname = dgettext(TEXT_DOMAIN, "mount");
2631                         goto ancestorerr;
2632                 }
2633
2634                 if (zfs_share(h) != 0) {
2635                         opname = dgettext(TEXT_DOMAIN, "share");
2636                         goto ancestorerr;
2637                 }
2638
2639                 zfs_close(h);
2640         }
2641
2642         return (0);
2643
2644 ancestorerr:
2645         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2646             "failed to %s ancestor '%s'"), opname, target);
2647         return (-1);
2648 }
2649
2650 /*
2651  * Creates non-existing ancestors of the given path.
2652  */
2653 int
2654 zfs_create_ancestors(libzfs_handle_t *hdl, const char *path)
2655 {
2656         int prefix;
2657         uint64_t zoned;
2658         char *path_copy;
2659         int rc;
2660
2661         if (check_parents(hdl, path, &zoned, B_TRUE, &prefix) != 0)
2662                 return (-1);
2663
2664         if ((path_copy = strdup(path)) != NULL) {
2665                 rc = create_parents(hdl, path_copy, prefix);
2666                 free(path_copy);
2667         }
2668         if (path_copy == NULL || rc != 0)
2669                 return (-1);
2670
2671         return (0);
2672 }
2673
2674 /*
2675  * Create a new filesystem or volume.
2676  */
2677 int
2678 zfs_create(libzfs_handle_t *hdl, const char *path, zfs_type_t type,
2679     nvlist_t *props)
2680 {
2681         zfs_cmd_t zc = { 0 };
2682         int ret;
2683         uint64_t size = 0;
2684         uint64_t blocksize = zfs_prop_default_numeric(ZFS_PROP_VOLBLOCKSIZE);
2685         char errbuf[1024];
2686         uint64_t zoned;
2687
2688         (void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
2689             "cannot create '%s'"), path);
2690
2691         /* validate the path, taking care to note the extended error message */
2692         if (!zfs_validate_name(hdl, path, type, B_TRUE))
2693                 return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
2694
2695         /* validate parents exist */
2696         if (check_parents(hdl, path, &zoned, B_FALSE, NULL) != 0)
2697                 return (-1);
2698
2699         /*
2700          * The failure modes when creating a dataset of a different type over
2701          * one that already exists is a little strange.  In particular, if you
2702          * try to create a dataset on top of an existing dataset, the ioctl()
2703          * will return ENOENT, not EEXIST.  To prevent this from happening, we
2704          * first try to see if the dataset exists.
2705          */
2706         (void) strlcpy(zc.zc_name, path, sizeof (zc.zc_name));
2707         if (zfs_dataset_exists(hdl, zc.zc_name, ZFS_TYPE_DATASET)) {
2708                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2709                     "dataset already exists"));
2710                 return (zfs_error(hdl, EZFS_EXISTS, errbuf));
2711         }
2712
2713         if (type == ZFS_TYPE_VOLUME)
2714                 zc.zc_objset_type = DMU_OST_ZVOL;
2715         else
2716                 zc.zc_objset_type = DMU_OST_ZFS;
2717
2718         if (props && (props = zfs_valid_proplist(hdl, type, props,
2719             zoned, NULL, errbuf)) == 0)
2720                 return (-1);
2721
2722         if (type == ZFS_TYPE_VOLUME) {
2723                 /*
2724                  * If we are creating a volume, the size and block size must
2725                  * satisfy a few restraints.  First, the blocksize must be a
2726                  * valid block size between SPA_{MIN,MAX}BLOCKSIZE.  Second, the
2727                  * volsize must be a multiple of the block size, and cannot be
2728                  * zero.
2729                  */
2730                 if (props == NULL || nvlist_lookup_uint64(props,
2731                     zfs_prop_to_name(ZFS_PROP_VOLSIZE), &size) != 0) {
2732                         nvlist_free(props);
2733                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2734                             "missing volume size"));
2735                         return (zfs_error(hdl, EZFS_BADPROP, errbuf));
2736                 }
2737
2738                 if ((ret = nvlist_lookup_uint64(props,
2739                     zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE),
2740                     &blocksize)) != 0) {
2741                         if (ret == ENOENT) {
2742                                 blocksize = zfs_prop_default_numeric(
2743                                     ZFS_PROP_VOLBLOCKSIZE);
2744                         } else {
2745                                 nvlist_free(props);
2746                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2747                                     "missing volume block size"));
2748                                 return (zfs_error(hdl, EZFS_BADPROP, errbuf));
2749                         }
2750                 }
2751
2752                 if (size == 0) {
2753                         nvlist_free(props);
2754                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2755                             "volume size cannot be zero"));
2756                         return (zfs_error(hdl, EZFS_BADPROP, errbuf));
2757                 }
2758
2759                 if (size % blocksize != 0) {
2760                         nvlist_free(props);
2761                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2762                             "volume size must be a multiple of volume block "
2763                             "size"));
2764                         return (zfs_error(hdl, EZFS_BADPROP, errbuf));
2765                 }
2766         }
2767
2768         if (props && zcmd_write_src_nvlist(hdl, &zc, props) != 0)
2769                 return (-1);
2770         nvlist_free(props);
2771
2772         /* create the dataset */
2773         ret = zfs_ioctl(hdl, ZFS_IOC_CREATE, &zc);
2774
2775         if (ret == 0 && type == ZFS_TYPE_VOLUME) {
2776                 ret = zvol_create_link(hdl, path);
2777                 if (ret) {
2778                         (void) zfs_standard_error(hdl, errno,
2779                             dgettext(TEXT_DOMAIN,
2780                             "Volume successfully created, but device links "
2781                             "were not created"));
2782                         zcmd_free_nvlists(&zc);
2783                         return (-1);
2784                 }
2785         }
2786
2787         zcmd_free_nvlists(&zc);
2788
2789         /* check for failure */
2790         if (ret != 0) {
2791                 char parent[ZFS_MAXNAMELEN];
2792                 (void) parent_name(path, parent, sizeof (parent));
2793
2794                 switch (errno) {
2795                 case ENOENT:
2796                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2797                             "no such parent '%s'"), parent);
2798                         return (zfs_error(hdl, EZFS_NOENT, errbuf));
2799
2800                 case EINVAL:
2801                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2802                             "parent '%s' is not a filesystem"), parent);
2803                         return (zfs_error(hdl, EZFS_BADTYPE, errbuf));
2804
2805                 case EDOM:
2806                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2807                             "volume block size must be power of 2 from "
2808                             "%u to %uk"),
2809                             (uint_t)SPA_MINBLOCKSIZE,
2810                             (uint_t)SPA_MAXBLOCKSIZE >> 10);
2811
2812                         return (zfs_error(hdl, EZFS_BADPROP, errbuf));
2813
2814                 case ENOTSUP:
2815                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2816                             "pool must be upgraded to set this "
2817                             "property or value"));
2818                         return (zfs_error(hdl, EZFS_BADVERSION, errbuf));
2819 #ifdef _ILP32
2820                 case EOVERFLOW:
2821                         /*
2822                          * This platform can't address a volume this big.
2823                          */
2824                         if (type == ZFS_TYPE_VOLUME)
2825                                 return (zfs_error(hdl, EZFS_VOLTOOBIG,
2826                                     errbuf));
2827 #endif
2828                         /* FALLTHROUGH */
2829                 default:
2830                         return (zfs_standard_error(hdl, errno, errbuf));
2831                 }
2832         }
2833
2834         return (0);
2835 }
2836
2837 /*
2838  * Destroys the given dataset.  The caller must make sure that the filesystem
2839  * isn't mounted, and that there are no active dependents.
2840  */
2841 int
2842 zfs_destroy(zfs_handle_t *zhp)
2843 {
2844         zfs_cmd_t zc = { 0 };
2845
2846         (void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
2847
2848         if (ZFS_IS_VOLUME(zhp)) {
2849                 /*
2850                  * If user doesn't have permissions to unshare volume, then
2851                  * abort the request.  This would only happen for a
2852                  * non-privileged user.
2853                  */
2854                 if (zfs_unshare_iscsi(zhp) != 0) {
2855                         return (-1);
2856                 }
2857
2858                 if (zvol_remove_link(zhp->zfs_hdl, zhp->zfs_name) != 0)
2859                         return (-1);
2860
2861                 zc.zc_objset_type = DMU_OST_ZVOL;
2862         } else {
2863                 zc.zc_objset_type = DMU_OST_ZFS;
2864         }
2865
2866         if (zfs_ioctl(zhp->zfs_hdl, ZFS_IOC_DESTROY, &zc) != 0) {
2867                 return (zfs_standard_error_fmt(zhp->zfs_hdl, errno,
2868                     dgettext(TEXT_DOMAIN, "cannot destroy '%s'"),
2869                     zhp->zfs_name));
2870         }
2871
2872         remove_mountpoint(zhp);
2873
2874         return (0);
2875 }
2876
2877 struct destroydata {
2878         char *snapname;
2879         boolean_t gotone;
2880         boolean_t closezhp;
2881 };
2882
2883 static int
2884 zfs_remove_link_cb(zfs_handle_t *zhp, void *arg)
2885 {
2886         struct destroydata *dd = arg;
2887         zfs_handle_t *szhp;
2888         char name[ZFS_MAXNAMELEN];
2889         boolean_t closezhp = dd->closezhp;
2890         int rv;
2891
2892         (void) strlcpy(name, zhp->zfs_name, sizeof (name));
2893         (void) strlcat(name, "@", sizeof (name));
2894         (void) strlcat(name, dd->snapname, sizeof (name));
2895
2896         szhp = make_dataset_handle(zhp->zfs_hdl, name);
2897         if (szhp) {
2898                 dd->gotone = B_TRUE;
2899                 zfs_close(szhp);
2900         }
2901
2902         if (zhp->zfs_type == ZFS_TYPE_VOLUME) {
2903                 (void) zvol_remove_link(zhp->zfs_hdl, name);
2904                 /*
2905                  * NB: this is simply a best-effort.  We don't want to
2906                  * return an error, because then we wouldn't visit all
2907                  * the volumes.
2908                  */
2909         }
2910
2911         dd->closezhp = B_TRUE;
2912         rv = zfs_iter_filesystems(zhp, zfs_remove_link_cb, arg);
2913         if (closezhp)
2914                 zfs_close(zhp);
2915         return (rv);
2916 }
2917
2918 /*
2919  * Destroys all snapshots with the given name in zhp & descendants.
2920  */
2921 int
2922 zfs_destroy_snaps(zfs_handle_t *zhp, char *snapname)
2923 {
2924         zfs_cmd_t zc = { 0 };
2925         int ret;
2926         struct destroydata dd = { 0 };
2927
2928         dd.snapname = snapname;
2929         (void) zfs_remove_link_cb(zhp, &dd);
2930
2931         if (!dd.gotone) {
2932                 return (zfs_standard_error_fmt(zhp->zfs_hdl, ENOENT,
2933                     dgettext(TEXT_DOMAIN, "cannot destroy '%s@%s'"),
2934                     zhp->zfs_name, snapname));
2935         }
2936
2937         (void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
2938         (void) strlcpy(zc.zc_value, snapname, sizeof (zc.zc_value));
2939
2940         ret = zfs_ioctl(zhp->zfs_hdl, ZFS_IOC_DESTROY_SNAPS, &zc);
2941         if (ret != 0) {
2942                 char errbuf[1024];
2943
2944                 (void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
2945                     "cannot destroy '%s@%s'"), zc.zc_name, snapname);
2946
2947                 switch (errno) {
2948                 case EEXIST:
2949                         zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
2950                             "snapshot is cloned"));
2951                         return (zfs_error(zhp->zfs_hdl, EZFS_EXISTS, errbuf));
2952
2953                 default:
2954                         return (zfs_standard_error(zhp->zfs_hdl, errno,
2955                             errbuf));
2956                 }
2957         }
2958
2959         return (0);
2960 }
2961
2962 /*
2963  * Clones the given dataset.  The target must be of the same type as the source.
2964  */
2965 int
2966 zfs_clone(zfs_handle_t *zhp, const char *target, nvlist_t *props)
2967 {
2968         zfs_cmd_t zc = { 0 };
2969         char parent[ZFS_MAXNAMELEN];
2970         int ret;
2971         char errbuf[1024];
2972         libzfs_handle_t *hdl = zhp->zfs_hdl;
2973         zfs_type_t type;
2974         uint64_t zoned;
2975
2976         assert(zhp->zfs_type == ZFS_TYPE_SNAPSHOT);
2977
2978         (void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
2979             "cannot create '%s'"), target);
2980
2981         /* validate the target name */
2982         if (!zfs_validate_name(hdl, target, ZFS_TYPE_FILESYSTEM, B_TRUE))
2983                 return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
2984
2985         /* validate parents exist */
2986         if (check_parents(hdl, target, &zoned, B_FALSE, NULL) != 0)
2987                 return (-1);
2988
2989         (void) parent_name(target, parent, sizeof (parent));
2990
2991         /* do the clone */
2992         if (ZFS_IS_VOLUME(zhp)) {
2993                 zc.zc_objset_type = DMU_OST_ZVOL;
2994                 type = ZFS_TYPE_VOLUME;
2995         } else {
2996                 zc.zc_objset_type = DMU_OST_ZFS;
2997                 type = ZFS_TYPE_FILESYSTEM;
2998         }
2999
3000         if (props) {
3001                 if ((props = zfs_valid_proplist(hdl, type, props, zoned,
3002                     zhp, errbuf)) == NULL)
3003                         return (-1);
3004
3005                 if (zcmd_write_src_nvlist(hdl, &zc, props) != 0) {
3006                         nvlist_free(props);
3007                         return (-1);
3008                 }
3009
3010                 nvlist_free(props);
3011         }
3012
3013         (void) strlcpy(zc.zc_name, target, sizeof (zc.zc_name));
3014         (void) strlcpy(zc.zc_value, zhp->zfs_name, sizeof (zc.zc_value));
3015         ret = zfs_ioctl(zhp->zfs_hdl, ZFS_IOC_CREATE, &zc);
3016
3017         zcmd_free_nvlists(&zc);
3018
3019         if (ret != 0) {
3020                 switch (errno) {
3021
3022                 case ENOENT:
3023                         /*
3024                          * The parent doesn't exist.  We should have caught this
3025                          * above, but there may a race condition that has since
3026                          * destroyed the parent.
3027                          *
3028                          * At this point, we don't know whether it's the source
3029                          * that doesn't exist anymore, or whether the target
3030                          * dataset doesn't exist.
3031                          */
3032                         zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
3033                             "no such parent '%s'"), parent);
3034                         return (zfs_error(zhp->zfs_hdl, EZFS_NOENT, errbuf));
3035
3036                 case EXDEV:
3037                         zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
3038                             "source and target pools differ"));
3039                         return (zfs_error(zhp->zfs_hdl, EZFS_CROSSTARGET,
3040                             errbuf));
3041
3042                 default:
3043                         return (zfs_standard_error(zhp->zfs_hdl, errno,
3044                             errbuf));
3045                 }
3046         } else if (ZFS_IS_VOLUME(zhp)) {
3047                 ret = zvol_create_link(zhp->zfs_hdl, target);
3048         }
3049
3050         return (ret);
3051 }
3052
3053 typedef struct promote_data {
3054         char cb_mountpoint[MAXPATHLEN];
3055         const char *cb_target;
3056         const char *cb_errbuf;
3057         uint64_t cb_pivot_txg;
3058 } promote_data_t;
3059
3060 static int
3061 promote_snap_cb(zfs_handle_t *zhp, void *data)
3062 {
3063         promote_data_t *pd = data;
3064         zfs_handle_t *szhp;
3065         char snapname[MAXPATHLEN];
3066         int rv = 0;
3067
3068         /* We don't care about snapshots after the pivot point */
3069         if (zfs_prop_get_int(zhp, ZFS_PROP_CREATETXG) > pd->cb_pivot_txg) {
3070                 zfs_close(zhp);
3071                 return (0);
3072         }
3073
3074         /* Remove the device link if it's a zvol. */
3075         if (ZFS_IS_VOLUME(zhp))
3076                 (void) zvol_remove_link(zhp->zfs_hdl, zhp->zfs_name);
3077
3078         /* Check for conflicting names */
3079         (void) strlcpy(snapname, pd->cb_target, sizeof (snapname));
3080         (void) strlcat(snapname, strchr(zhp->zfs_name, '@'), sizeof (snapname));
3081         szhp = make_dataset_handle(zhp->zfs_hdl, snapname);
3082         if (szhp != NULL) {
3083                 zfs_close(szhp);
3084                 zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
3085                     "snapshot name '%s' from origin \n"
3086                     "conflicts with '%s' from target"),
3087                     zhp->zfs_name, snapname);
3088                 rv = zfs_error(zhp->zfs_hdl, EZFS_EXISTS, pd->cb_errbuf);
3089         }
3090         zfs_close(zhp);
3091         return (rv);
3092 }
3093
3094 static int
3095 promote_snap_done_cb(zfs_handle_t *zhp, void *data)
3096 {
3097         promote_data_t *pd = data;
3098
3099         /* We don't care about snapshots after the pivot point */
3100         if (zfs_prop_get_int(zhp, ZFS_PROP_CREATETXG) <= pd->cb_pivot_txg) {
3101                 /* Create the device link if it's a zvol. */
3102                 if (ZFS_IS_VOLUME(zhp))
3103                         (void) zvol_create_link(zhp->zfs_hdl, zhp->zfs_name);
3104         }
3105
3106         zfs_close(zhp);
3107         return (0);
3108 }
3109
3110 /*
3111  * Promotes the given clone fs to be the clone parent.
3112  */
3113 int
3114 zfs_promote(zfs_handle_t *zhp)
3115 {
3116         libzfs_handle_t *hdl = zhp->zfs_hdl;
3117         zfs_cmd_t zc = { 0 };
3118         char parent[MAXPATHLEN];
3119         char *cp;
3120         int ret;
3121         zfs_handle_t *pzhp;
3122         promote_data_t pd;
3123         char errbuf[1024];
3124
3125         (void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
3126             "cannot promote '%s'"), zhp->zfs_name);
3127
3128         if (zhp->zfs_type == ZFS_TYPE_SNAPSHOT) {
3129                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3130                     "snapshots can not be promoted"));
3131                 return (zfs_error(hdl, EZFS_BADTYPE, errbuf));
3132         }
3133
3134         (void) strlcpy(parent, zhp->zfs_dmustats.dds_origin, sizeof (parent));
3135         if (parent[0] == '\0') {
3136                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3137                     "not a cloned filesystem"));
3138                 return (zfs_error(hdl, EZFS_BADTYPE, errbuf));
3139         }
3140         cp = strchr(parent, '@');
3141         *cp = '\0';
3142
3143         /* Walk the snapshots we will be moving */
3144         pzhp = zfs_open(hdl, zhp->zfs_dmustats.dds_origin, ZFS_TYPE_SNAPSHOT);
3145         if (pzhp == NULL)
3146                 return (-1);
3147         pd.cb_pivot_txg = zfs_prop_get_int(pzhp, ZFS_PROP_CREATETXG);
3148         zfs_close(pzhp);
3149         pd.cb_target = zhp->zfs_name;
3150         pd.cb_errbuf = errbuf;
3151         pzhp = zfs_open(hdl, parent, ZFS_TYPE_DATASET);
3152         if (pzhp == NULL)
3153                 return (-1);
3154         (void) zfs_prop_get(pzhp, ZFS_PROP_MOUNTPOINT, pd.cb_mountpoint,
3155             sizeof (pd.cb_mountpoint), NULL, NULL, 0, FALSE);
3156         ret = zfs_iter_snapshots(pzhp, promote_snap_cb, &pd);
3157         if (ret != 0) {
3158                 zfs_close(pzhp);
3159                 return (-1);
3160         }
3161
3162         /* issue the ioctl */
3163         (void) strlcpy(zc.zc_value, zhp->zfs_dmustats.dds_origin,
3164             sizeof (zc.zc_value));
3165         (void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
3166         ret = zfs_ioctl(hdl, ZFS_IOC_PROMOTE, &zc);
3167
3168         if (ret != 0) {
3169                 int save_errno = errno;
3170
3171                 (void) zfs_iter_snapshots(pzhp, promote_snap_done_cb, &pd);
3172                 zfs_close(pzhp);
3173
3174                 switch (save_errno) {
3175                 case EEXIST:
3176                         /*
3177                          * There is a conflicting snapshot name.  We
3178                          * should have caught this above, but they could
3179                          * have renamed something in the mean time.
3180                          */
3181                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3182                             "conflicting snapshot name from parent '%s'"),
3183                             parent);
3184                         return (zfs_error(hdl, EZFS_EXISTS, errbuf));
3185
3186                 default:
3187                         return (zfs_standard_error(hdl, save_errno, errbuf));
3188                 }
3189         } else {
3190                 (void) zfs_iter_snapshots(zhp, promote_snap_done_cb, &pd);
3191         }
3192
3193         zfs_close(pzhp);
3194         return (ret);
3195 }
3196
3197 struct createdata {
3198         const char *cd_snapname;
3199         int cd_ifexists;
3200 };
3201
3202 static int
3203 zfs_create_link_cb(zfs_handle_t *zhp, void *arg)
3204 {
3205         struct createdata *cd = arg;
3206         int ret;
3207
3208         if (zhp->zfs_type == ZFS_TYPE_VOLUME) {
3209                 char name[MAXPATHLEN];
3210
3211                 (void) strlcpy(name, zhp->zfs_name, sizeof (name));
3212                 (void) strlcat(name, "@", sizeof (name));
3213                 (void) strlcat(name, cd->cd_snapname, sizeof (name));
3214                 (void) zvol_create_link_common(zhp->zfs_hdl, name,
3215                     cd->cd_ifexists);
3216                 /*
3217                  * NB: this is simply a best-effort.  We don't want to
3218                  * return an error, because then we wouldn't visit all
3219                  * the volumes.
3220                  */
3221         }
3222
3223         ret = zfs_iter_filesystems(zhp, zfs_create_link_cb, cd);
3224
3225         zfs_close(zhp);
3226
3227         return (ret);
3228 }
3229
3230 /*
3231  * Takes a snapshot of the given dataset.
3232  */
3233 int
3234 zfs_snapshot(libzfs_handle_t *hdl, const char *path, boolean_t recursive,
3235     nvlist_t *props)
3236 {
3237         const char *delim;
3238         char parent[ZFS_MAXNAMELEN];
3239         zfs_handle_t *zhp;
3240         zfs_cmd_t zc = { 0 };
3241         int ret;
3242         char errbuf[1024];
3243
3244         (void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
3245             "cannot snapshot '%s'"), path);
3246
3247         /* validate the target name */
3248         if (!zfs_validate_name(hdl, path, ZFS_TYPE_SNAPSHOT, B_TRUE))
3249                 return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
3250
3251         if (props) {
3252                 if ((props = zfs_valid_proplist(hdl, ZFS_TYPE_SNAPSHOT,
3253                     props, B_FALSE, NULL, errbuf)) == NULL)
3254                         return (-1);
3255
3256                 if (zcmd_write_src_nvlist(hdl, &zc, props) != 0) {
3257                         nvlist_free(props);
3258                         return (-1);
3259                 }
3260
3261                 nvlist_free(props);
3262         }
3263
3264         /* make sure the parent exists and is of the appropriate type */
3265         delim = strchr(path, '@');
3266         (void) strncpy(parent, path, delim - path);
3267         parent[delim - path] = '\0';
3268
3269         if ((zhp = zfs_open(hdl, parent, ZFS_TYPE_FILESYSTEM |
3270             ZFS_TYPE_VOLUME)) == NULL) {
3271                 zcmd_free_nvlists(&zc);
3272                 return (-1);
3273         }
3274
3275         (void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
3276         (void) strlcpy(zc.zc_value, delim+1, sizeof (zc.zc_value));
3277         if (ZFS_IS_VOLUME(zhp))
3278                 zc.zc_objset_type = DMU_OST_ZVOL;
3279         else
3280                 zc.zc_objset_type = DMU_OST_ZFS;
3281         zc.zc_cookie = recursive;
3282         ret = zfs_ioctl(zhp->zfs_hdl, ZFS_IOC_SNAPSHOT, &zc);
3283
3284         zcmd_free_nvlists(&zc);
3285
3286         /*
3287          * if it was recursive, the one that actually failed will be in
3288          * zc.zc_name.
3289          */
3290         if (ret != 0)
3291                 (void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
3292                     "cannot create snapshot '%s@%s'"), zc.zc_name, zc.zc_value);
3293
3294         if (ret == 0 && recursive) {
3295                 struct createdata cd;
3296
3297                 cd.cd_snapname = delim + 1;
3298                 cd.cd_ifexists = B_FALSE;
3299                 (void) zfs_iter_filesystems(zhp, zfs_create_link_cb, &cd);
3300         }
3301         if (ret == 0 && zhp->zfs_type == ZFS_TYPE_VOLUME) {
3302                 ret = zvol_create_link(zhp->zfs_hdl, path);
3303                 if (ret != 0) {
3304                         (void) zfs_standard_error(hdl, errno,
3305                             dgettext(TEXT_DOMAIN,
3306                             "Volume successfully snapshotted, but device links "
3307                             "were not created"));
3308                         zfs_close(zhp);
3309                         return (-1);
3310                 }
3311         }
3312
3313         if (ret != 0)
3314                 (void) zfs_standard_error(hdl, errno, errbuf);
3315
3316         zfs_close(zhp);
3317
3318         return (ret);
3319 }
3320
3321 /*
3322  * Destroy any more recent snapshots.  We invoke this callback on any dependents
3323  * of the snapshot first.  If the 'cb_dependent' member is non-zero, then this
3324  * is a dependent and we should just destroy it without checking the transaction
3325  * group.
3326  */
3327 typedef struct rollback_data {
3328         const char      *cb_target;             /* the snapshot */
3329         uint64_t        cb_create;              /* creation time reference */
3330         boolean_t       cb_error;
3331         boolean_t       cb_dependent;
3332         boolean_t       cb_force;
3333 } rollback_data_t;
3334
3335 static int
3336 rollback_destroy(zfs_handle_t *zhp, void *data)
3337 {
3338         rollback_data_t *cbp = data;
3339
3340         if (!cbp->cb_dependent) {
3341                 if (strcmp(zhp->zfs_name, cbp->cb_target) != 0 &&
3342                     zfs_get_type(zhp) == ZFS_TYPE_SNAPSHOT &&
3343                     zfs_prop_get_int(zhp, ZFS_PROP_CREATETXG) >
3344                     cbp->cb_create) {
3345                         char *logstr;
3346
3347                         cbp->cb_dependent = B_TRUE;
3348                         cbp->cb_error |= zfs_iter_dependents(zhp, B_FALSE,
3349                             rollback_destroy, cbp);
3350                         cbp->cb_dependent = B_FALSE;
3351
3352                         logstr = zhp->zfs_hdl->libzfs_log_str;
3353                         zhp->zfs_hdl->libzfs_log_str = NULL;
3354                         cbp->cb_error |= zfs_destroy(zhp);
3355                         zhp->zfs_hdl->libzfs_log_str = logstr;
3356                 }
3357         } else {
3358                 /* We must destroy this clone; first unmount it */
3359                 prop_changelist_t *clp;
3360
3361                 clp = changelist_gather(zhp, ZFS_PROP_NAME, 0,
3362                     cbp->cb_force ? MS_FORCE: 0);
3363                 if (clp == NULL || changelist_prefix(clp) != 0) {
3364                         cbp->cb_error = B_TRUE;
3365                         zfs_close(zhp);
3366                         return (0);
3367                 }
3368                 if (zfs_destroy(zhp) != 0)
3369                         cbp->cb_error = B_TRUE;
3370                 else
3371                         changelist_remove(clp, zhp->zfs_name);
3372                 (void) changelist_postfix(clp);
3373                 changelist_free(clp);
3374         }
3375
3376         zfs_close(zhp);
3377         return (0);
3378 }
3379
3380 /*
3381  * Given a dataset, rollback to a specific snapshot, discarding any
3382  * data changes since then and making it the active dataset.
3383  *
3384  * Any snapshots more recent than the target are destroyed, along with
3385  * their dependents.
3386  */
3387 int
3388 zfs_rollback(zfs_handle_t *zhp, zfs_handle_t *snap, boolean_t force)
3389 {
3390         rollback_data_t cb = { 0 };
3391         int err;
3392         zfs_cmd_t zc = { 0 };
3393         boolean_t restore_resv = 0;
3394         uint64_t old_volsize, new_volsize;
3395         zfs_prop_t resv_prop;
3396
3397         assert(zhp->zfs_type == ZFS_TYPE_FILESYSTEM ||
3398             zhp->zfs_type == ZFS_TYPE_VOLUME);
3399
3400         /*
3401          * Destroy all recent snapshots and its dependends.
3402          */
3403         cb.cb_force = force;
3404         cb.cb_target = snap->zfs_name;
3405         cb.cb_create = zfs_prop_get_int(snap, ZFS_PROP_CREATETXG);
3406         (void) zfs_iter_children(zhp, rollback_destroy, &cb);
3407
3408         if (cb.cb_error)
3409                 return (-1);
3410
3411         /*
3412          * Now that we have verified that the snapshot is the latest,
3413          * rollback to the given snapshot.
3414          */
3415
3416         if (zhp->zfs_type == ZFS_TYPE_VOLUME) {
3417                 if (zvol_remove_link(zhp->zfs_hdl, zhp->zfs_name) != 0)
3418                         return (-1);
3419                 if (zfs_which_resv_prop(zhp, &resv_prop) < 0)
3420                         return (-1);
3421                 old_volsize = zfs_prop_get_int(zhp, ZFS_PROP_VOLSIZE);
3422                 restore_resv =
3423                     (old_volsize == zfs_prop_get_int(zhp, resv_prop));
3424         }
3425
3426         (void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
3427
3428         if (ZFS_IS_VOLUME(zhp))
3429                 zc.zc_objset_type = DMU_OST_ZVOL;
3430         else
3431                 zc.zc_objset_type = DMU_OST_ZFS;
3432
3433         /*
3434          * We rely on zfs_iter_children() to verify that there are no
3435          * newer snapshots for the given dataset.  Therefore, we can
3436          * simply pass the name on to the ioctl() call.  There is still
3437          * an unlikely race condition where the user has taken a
3438          * snapshot since we verified that this was the most recent.
3439          *
3440          */
3441         if ((err = zfs_ioctl(zhp->zfs_hdl, ZFS_IOC_ROLLBACK, &zc)) != 0) {
3442                 (void) zfs_standard_error_fmt(zhp->zfs_hdl, errno,
3443                     dgettext(TEXT_DOMAIN, "cannot rollback '%s'"),
3444                     zhp->zfs_name);
3445                 return (err);
3446         }
3447
3448         /*
3449          * For volumes, if the pre-rollback volsize matched the pre-
3450          * rollback reservation and the volsize has changed then set
3451          * the reservation property to the post-rollback volsize.
3452          * Make a new handle since the rollback closed the dataset.
3453          */
3454         if ((zhp->zfs_type == ZFS_TYPE_VOLUME) &&
3455             (zhp = make_dataset_handle(zhp->zfs_hdl, zhp->zfs_name))) {
3456                 if (err = zvol_create_link(zhp->zfs_hdl, zhp->zfs_name)) {
3457                         zfs_close(zhp);
3458                         return (err);
3459                 }
3460                 if (restore_resv) {
3461                         new_volsize = zfs_prop_get_int(zhp, ZFS_PROP_VOLSIZE);
3462                         if (old_volsize != new_volsize)
3463                                 err = zfs_prop_set_int(zhp, resv_prop,
3464                                     new_volsize);
3465                 }
3466                 zfs_close(zhp);
3467         }
3468         return (err);
3469 }
3470
3471 /*
3472  * Iterate over all dependents for a given dataset.  This includes both
3473  * hierarchical dependents (children) and data dependents (snapshots and
3474  * clones).  The bulk of the processing occurs in get_dependents() in
3475  * libzfs_graph.c.
3476  */
3477 int
3478 zfs_iter_dependents(zfs_handle_t *zhp, boolean_t allowrecursion,
3479     zfs_iter_f func, void *data)
3480 {
3481         char **dependents;
3482         size_t count;
3483         int i;
3484         zfs_handle_t *child;
3485         int ret = 0;
3486
3487         if (get_dependents(zhp->zfs_hdl, allowrecursion, zhp->zfs_name,
3488             &dependents, &count) != 0)
3489                 return (-1);
3490
3491         for (i = 0; i < count; i++) {
3492                 if ((child = make_dataset_handle(zhp->zfs_hdl,
3493                     dependents[i])) == NULL)
3494                         continue;
3495
3496                 if ((ret = func(child, data)) != 0)
3497                         break;
3498         }
3499
3500         for (i = 0; i < count; i++)
3501                 free(dependents[i]);
3502         free(dependents);
3503
3504         return (ret);
3505 }
3506
3507 /*
3508  * Renames the given dataset.
3509  */
3510 int
3511 zfs_rename(zfs_handle_t *zhp, const char *target, boolean_t recursive)
3512 {
3513         int ret;
3514         zfs_cmd_t zc = { 0 };
3515         char *delim;
3516         prop_changelist_t *cl = NULL;
3517         zfs_handle_t *zhrp = NULL;
3518         char *parentname = NULL;
3519         char parent[ZFS_MAXNAMELEN];
3520         libzfs_handle_t *hdl = zhp->zfs_hdl;
3521         char errbuf[1024];
3522
3523         /* if we have the same exact name, just return success */
3524         if (strcmp(zhp->zfs_name, target) == 0)
3525                 return (0);
3526
3527         (void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
3528             "cannot rename to '%s'"), target);
3529
3530         /*
3531          * Make sure the target name is valid
3532          */
3533         if (zhp->zfs_type == ZFS_TYPE_SNAPSHOT) {
3534                 if ((strchr(target, '@') == NULL) ||
3535                     *target == '@') {
3536                         /*
3537                          * Snapshot target name is abbreviated,
3538                          * reconstruct full dataset name
3539                          */
3540                         (void) strlcpy(parent, zhp->zfs_name,
3541                             sizeof (parent));
3542                         delim = strchr(parent, '@');
3543                         if (strchr(target, '@') == NULL)
3544                                 *(++delim) = '\0';
3545                         else
3546                                 *delim = '\0';
3547                         (void) strlcat(parent, target, sizeof (parent));
3548                         target = parent;
3549                 } else {
3550                         /*
3551                          * Make sure we're renaming within the same dataset.
3552                          */
3553                         delim = strchr(target, '@');
3554                         if (strncmp(zhp->zfs_name, target, delim - target)
3555                             != 0 || zhp->zfs_name[delim - target] != '@') {
3556                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3557                                     "snapshots must be part of same "
3558                                     "dataset"));
3559                                 return (zfs_error(hdl, EZFS_CROSSTARGET,
3560                                     errbuf));
3561                         }
3562                 }
3563                 if (!zfs_validate_name(hdl, target, zhp->zfs_type, B_TRUE))
3564                         return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
3565         } else {
3566                 if (recursive) {
3567                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3568                             "recursive rename must be a snapshot"));
3569                         return (zfs_error(hdl, EZFS_BADTYPE, errbuf));
3570                 }
3571
3572                 if (!zfs_validate_name(hdl, target, zhp->zfs_type, B_TRUE))
3573                         return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
3574                 uint64_t unused;
3575
3576                 /* validate parents */
3577                 if (check_parents(hdl, target, &unused, B_FALSE, NULL) != 0)
3578                         return (-1);
3579
3580                 (void) parent_name(target, parent, sizeof (parent));
3581
3582                 /* make sure we're in the same pool */
3583                 verify((delim = strchr(target, '/')) != NULL);
3584                 if (strncmp(zhp->zfs_name, target, delim - target) != 0 ||
3585                     zhp->zfs_name[delim - target] != '/') {
3586                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3587                             "datasets must be within same pool"));
3588                         return (zfs_error(hdl, EZFS_CROSSTARGET, errbuf));
3589                 }
3590
3591                 /* new name cannot be a child of the current dataset name */
3592                 if (strncmp(parent, zhp->zfs_name,
3593                     strlen(zhp->zfs_name)) == 0) {
3594                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3595                             "New dataset name cannot be a descendent of "
3596                             "current dataset name"));
3597                         return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
3598                 }
3599         }
3600
3601         (void) snprintf(errbuf, sizeof (errbuf),
3602             dgettext(TEXT_DOMAIN, "cannot rename '%s'"), zhp->zfs_name);
3603
3604         if (getzoneid() == GLOBAL_ZONEID &&
3605             zfs_prop_get_int(zhp, ZFS_PROP_ZONED)) {
3606                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3607                     "dataset is used in a non-global zone"));
3608                 return (zfs_error(hdl, EZFS_ZONED, errbuf));
3609         }
3610
3611         if (recursive) {
3612                 struct destroydata dd;
3613
3614                 parentname = zfs_strdup(zhp->zfs_hdl, zhp->zfs_name);
3615                 if (parentname == NULL) {
3616                         ret = -1;
3617                         goto error;
3618                 }
3619                 delim = strchr(parentname, '@');
3620                 *delim = '\0';
3621                 zhrp = zfs_open(zhp->zfs_hdl, parentname, ZFS_TYPE_DATASET);
3622                 if (zhrp == NULL) {
3623                         ret = -1;
3624                         goto error;
3625                 }
3626
3627                 dd.snapname = delim + 1;
3628                 dd.gotone = B_FALSE;
3629                 dd.closezhp = B_TRUE;
3630
3631                 /* We remove any zvol links prior to renaming them */
3632                 ret = zfs_iter_filesystems(zhrp, zfs_remove_link_cb, &dd);
3633                 if (ret) {
3634                         goto error;
3635                 }
3636         } else {
3637                 if ((cl = changelist_gather(zhp, ZFS_PROP_NAME, 0, 0)) == NULL)
3638                         return (-1);
3639
3640                 if (changelist_haszonedchild(cl)) {
3641                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3642                             "child dataset with inherited mountpoint is used "
3643                             "in a non-global zone"));
3644                         (void) zfs_error(hdl, EZFS_ZONED, errbuf);
3645                         goto error;
3646                 }
3647
3648                 if ((ret = changelist_prefix(cl)) != 0)
3649                         goto error;
3650         }
3651
3652         if (ZFS_IS_VOLUME(zhp))
3653                 zc.zc_objset_type = DMU_OST_ZVOL;
3654         else
3655                 zc.zc_objset_type = DMU_OST_ZFS;
3656
3657         (void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
3658         (void) strlcpy(zc.zc_value, target, sizeof (zc.zc_value));
3659
3660         zc.zc_cookie = recursive;
3661
3662         if ((ret = zfs_ioctl(zhp->zfs_hdl, ZFS_IOC_RENAME, &zc)) != 0) {
3663                 /*
3664                  * if it was recursive, the one that actually failed will
3665                  * be in zc.zc_name
3666                  */
3667                 (void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
3668                     "cannot rename '%s'"), zc.zc_name);
3669
3670                 if (recursive && errno == EEXIST) {
3671                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3672                             "a child dataset already has a snapshot "
3673                             "with the new name"));
3674                         (void) zfs_error(hdl, EZFS_EXISTS, errbuf);
3675                 } else {
3676                         (void) zfs_standard_error(zhp->zfs_hdl, errno, errbuf);
3677                 }
3678
3679                 /*
3680                  * On failure, we still want to remount any filesystems that
3681                  * were previously mounted, so we don't alter the system state.
3682                  */
3683                 if (recursive) {
3684                         struct createdata cd;
3685
3686                         /* only create links for datasets that had existed */
3687                         cd.cd_snapname = delim + 1;
3688                         cd.cd_ifexists = B_TRUE;
3689                         (void) zfs_iter_filesystems(zhrp, zfs_create_link_cb,
3690                             &cd);
3691                 } else {
3692                         (void) changelist_postfix(cl);
3693                 }
3694         } else {
3695                 if (recursive) {
3696                         struct createdata cd;
3697
3698                         /* only create links for datasets that had existed */
3699                         cd.cd_snapname = strchr(target, '@') + 1;
3700                         cd.cd_ifexists = B_TRUE;
3701                         ret = zfs_iter_filesystems(zhrp, zfs_create_link_cb,
3702                             &cd);
3703                 } else {
3704                         changelist_rename(cl, zfs_get_name(zhp), target);
3705                         ret = changelist_postfix(cl);
3706                 }
3707         }
3708
3709 error:
3710         if (parentname) {
3711                 free(parentname);
3712         }
3713         if (zhrp) {
3714                 zfs_close(zhrp);
3715         }
3716         if (cl) {
3717                 changelist_free(cl);
3718         }
3719         return (ret);
3720 }
3721
3722 /*
3723  * Given a zvol dataset, issue the ioctl to create the appropriate minor node,
3724  * poke devfsadm to create the /dev link, and then wait for the link to appear.
3725  */
3726 int
3727 zvol_create_link(libzfs_handle_t *hdl, const char *dataset)
3728 {
3729         return (zvol_create_link_common(hdl, dataset, B_FALSE));
3730 }
3731
3732 static int
3733 zvol_create_link_common(libzfs_handle_t *hdl, const char *dataset, int ifexists)
3734 {
3735         zfs_cmd_t zc = { 0 };
3736 #if 0
3737         di_devlink_handle_t dhdl;
3738         priv_set_t *priv_effective;
3739         int privileged;
3740 #endif
3741
3742         (void) strlcpy(zc.zc_name, dataset, sizeof (zc.zc_name));
3743
3744         /*
3745          * Issue the appropriate ioctl.
3746          */
3747         if (ioctl(hdl->libzfs_fd, ZFS_IOC_CREATE_MINOR, &zc) != 0) {
3748                 switch (errno) {
3749                 case EEXIST:
3750                         /*
3751                          * Silently ignore the case where the link already
3752                          * exists.  This allows 'zfs volinit' to be run multiple
3753                          * times without errors.
3754                          */
3755                         return (0);
3756
3757                 case ENOENT:
3758                         /*
3759                          * Dataset does not exist in the kernel.  If we
3760                          * don't care (see zfs_rename), then ignore the
3761                          * error quietly.
3762                          */
3763                         if (ifexists) {
3764                                 return (0);
3765                         }
3766
3767                         /* FALLTHROUGH */
3768
3769                 default:
3770                         return (zfs_standard_error_fmt(hdl, errno,
3771                             dgettext(TEXT_DOMAIN, "cannot create device links "
3772                             "for '%s'"), dataset));
3773                 }
3774         }
3775
3776 #if 0
3777         /*
3778          * If privileged call devfsadm and wait for the links to
3779          * magically appear.
3780          * Otherwise, print out an informational message.
3781          */
3782
3783         priv_effective = priv_allocset();
3784         (void) getppriv(PRIV_EFFECTIVE, priv_effective);
3785         privileged = (priv_isfullset(priv_effective) == B_TRUE);
3786         priv_freeset(priv_effective);
3787
3788         if (privileged) {
3789                 if ((dhdl = di_devlink_init(ZFS_DRIVER,
3790                     DI_MAKE_LINK)) == NULL) {
3791                         zfs_error_aux(hdl, strerror(errno));
3792                         (void) zfs_error_fmt(hdl, errno,
3793                             dgettext(TEXT_DOMAIN, "cannot create device links "
3794                             "for '%s'"), dataset);
3795                         (void) ioctl(hdl->libzfs_fd, ZFS_IOC_REMOVE_MINOR, &zc);
3796                         return (-1);
3797                 } else {
3798                         (void) di_devlink_fini(&dhdl);
3799                 }
3800         } else {
3801                 char pathname[MAXPATHLEN];
3802                 struct stat64 statbuf;
3803                 int i;
3804
3805 #define MAX_WAIT        10
3806
3807                 /*
3808                  * This is the poor mans way of waiting for the link
3809                  * to show up.  If after 10 seconds we still don't
3810                  * have it, then print out a message.
3811                  */
3812                 (void) snprintf(pathname, sizeof (pathname), "/dev/zvol/dsk/%s",
3813                     dataset);
3814
3815                 for (i = 0; i != MAX_WAIT; i++) {
3816                         if (stat64(pathname, &statbuf) == 0)
3817                                 break;
3818                         (void) sleep(1);
3819                 }
3820                 if (i == MAX_WAIT)
3821                         (void) printf(gettext("%s may not be immediately "
3822                             "available\n"), pathname);
3823         }
3824 #endif
3825
3826         return (0);
3827 }
3828
3829 /*
3830  * Remove a minor node for the given zvol and the associated /dev links.
3831  */
3832 int
3833 zvol_remove_link(libzfs_handle_t *hdl, const char *dataset)
3834 {
3835         zfs_cmd_t zc = { 0 };
3836
3837         (void) strlcpy(zc.zc_name, dataset, sizeof (zc.zc_name));
3838
3839         if (ioctl(hdl->libzfs_fd, ZFS_IOC_REMOVE_MINOR, &zc) != 0) {
3840                 switch (errno) {
3841                 case ENXIO:
3842                         /*
3843                          * Silently ignore the case where the link no longer
3844                          * exists, so that 'zfs volfini' can be run multiple
3845                          * times without errors.
3846                          */
3847                         return (0);
3848
3849                 default:
3850                         return (zfs_standard_error_fmt(hdl, errno,
3851                             dgettext(TEXT_DOMAIN, "cannot remove device "
3852                             "links for '%s'"), dataset));
3853                 }
3854         }
3855
3856         return (0);
3857 }
3858
3859 nvlist_t *
3860 zfs_get_user_props(zfs_handle_t *zhp)
3861 {
3862         return (zhp->zfs_user_props);
3863 }
3864
3865 /*
3866  * This function is used by 'zfs list' to determine the exact set of columns to
3867  * display, and their maximum widths.  This does two main things:
3868  *
3869  *      - If this is a list of all properties, then expand the list to include
3870  *        all native properties, and set a flag so that for each dataset we look
3871  *        for new unique user properties and add them to the list.
3872  *
3873  *      - For non fixed-width properties, keep track of the maximum width seen
3874  *        so that we can size the column appropriately.
3875  */
3876 int
3877 zfs_expand_proplist(zfs_handle_t *zhp, zprop_list_t **plp)
3878 {
3879         libzfs_handle_t *hdl = zhp->zfs_hdl;
3880         zprop_list_t *entry;
3881         zprop_list_t **last, **start;
3882         nvlist_t *userprops, *propval;
3883         nvpair_t *elem;
3884         char *strval;
3885         char buf[ZFS_MAXPROPLEN];
3886
3887         if (zprop_expand_list(hdl, plp, ZFS_TYPE_DATASET) != 0)
3888                 return (-1);
3889
3890         userprops = zfs_get_user_props(zhp);
3891
3892         entry = *plp;
3893         if (entry->pl_all && nvlist_next_nvpair(userprops, NULL) != NULL) {
3894                 /*
3895                  * Go through and add any user properties as necessary.  We
3896                  * start by incrementing our list pointer to the first
3897                  * non-native property.
3898                  */
3899                 start = plp;
3900                 while (*start != NULL) {
3901                         if ((*start)->pl_prop == ZPROP_INVAL)
3902                                 break;
3903                         start = &(*start)->pl_next;
3904                 }
3905
3906                 elem = NULL;
3907                 while ((elem = nvlist_next_nvpair(userprops, elem)) != NULL) {
3908                         /*
3909                          * See if we've already found this property in our list.
3910                          */
3911                         for (last = start; *last != NULL;
3912                             last = &(*last)->pl_next) {
3913                                 if (strcmp((*last)->pl_user_prop,
3914                                     nvpair_name(elem)) == 0)
3915                                         break;
3916                         }
3917
3918                         if (*last == NULL) {
3919                                 if ((entry = zfs_alloc(hdl,
3920                                     sizeof (zprop_list_t))) == NULL ||
3921                                     ((entry->pl_user_prop = zfs_strdup(hdl,
3922                                     nvpair_name(elem)))) == NULL) {
3923                                         free(entry);
3924                                         return (-1);
3925                                 }
3926
3927                                 entry->pl_prop = ZPROP_INVAL;
3928                                 entry->pl_width = strlen(nvpair_name(elem));
3929                                 entry->pl_all = B_TRUE;
3930                                 *last = entry;
3931                         }
3932                 }
3933         }
3934
3935         /*
3936          * Now go through and check the width of any non-fixed columns
3937          */
3938         for (entry = *plp; entry != NULL; entry = entry->pl_next) {
3939                 if (entry->pl_fixed)
3940                         continue;
3941
3942                 if (entry->pl_prop != ZPROP_INVAL) {
3943                         if (zfs_prop_get(zhp, entry->pl_prop,
3944                             buf, sizeof (buf), NULL, NULL, 0, B_FALSE) == 0) {
3945                                 if (strlen(buf) > entry->pl_width)
3946                                         entry->pl_width = strlen(buf);
3947                         }
3948                 } else if (nvlist_lookup_nvlist(userprops,
3949                     entry->pl_user_prop, &propval)  == 0) {
3950                         verify(nvlist_lookup_string(propval,
3951                             ZPROP_VALUE, &strval) == 0);
3952                         if (strlen(strval) > entry->pl_width)
3953                                 entry->pl_width = strlen(strval);
3954                 }
3955         }
3956
3957         return (0);
3958 }
3959
3960 #ifdef TODO
3961 int
3962 zfs_iscsi_perm_check(libzfs_handle_t *hdl, char *dataset, ucred_t *cred)
3963 {
3964         zfs_cmd_t zc = { 0 };
3965         nvlist_t *nvp;
3966         gid_t gid;
3967         uid_t uid;
3968         const gid_t *groups;
3969         int group_cnt;
3970         int error;
3971
3972         if (nvlist_alloc(&nvp, NV_UNIQUE_NAME, 0) != 0)
3973                 return (no_memory(hdl));
3974
3975         uid = ucred_geteuid(cred);
3976         gid = ucred_getegid(cred);
3977         group_cnt = ucred_getgroups(cred, &groups);
3978
3979         if (uid == (uid_t)-1 || gid == (uid_t)-1 || group_cnt == (uid_t)-1)
3980                 return (1);
3981
3982         if (nvlist_add_uint32(nvp, ZFS_DELEG_PERM_UID, uid) != 0) {
3983                 nvlist_free(nvp);
3984                 return (1);
3985         }
3986
3987         if (nvlist_add_uint32(nvp, ZFS_DELEG_PERM_GID, gid) != 0) {
3988                 nvlist_free(nvp);
3989                 return (1);
3990         }
3991
3992         if (nvlist_add_uint32_array(nvp,
3993             ZFS_DELEG_PERM_GROUPS, (uint32_t *)groups, group_cnt) != 0) {
3994                 nvlist_free(nvp);
3995                 return (1);
3996         }
3997         (void) strlcpy(zc.zc_name, dataset, sizeof (zc.zc_name));
3998
3999         if (zcmd_write_src_nvlist(hdl, &zc, nvp))
4000                 return (-1);
4001
4002         error = ioctl(hdl->libzfs_fd, ZFS_IOC_ISCSI_PERM_CHECK, &zc);
4003         nvlist_free(nvp);
4004         return (error);
4005 }
4006 #endif
4007
4008 int
4009 zfs_deleg_share_nfs(libzfs_handle_t *hdl, char *dataset, char *path,
4010     char *resource, void *export, void *sharetab,
4011     int sharemax, zfs_share_op_t operation)
4012 {
4013         zfs_cmd_t zc = { 0 };
4014         int error;
4015
4016         (void) strlcpy(zc.zc_name, dataset, sizeof (zc.zc_name));
4017         (void) strlcpy(zc.zc_value, path, sizeof (zc.zc_value));
4018         if (resource)
4019                 (void) strlcpy(zc.zc_string, resource, sizeof (zc.zc_string));
4020         zc.zc_share.z_sharedata = (uint64_t)(uintptr_t)sharetab;
4021         zc.zc_share.z_exportdata = (uint64_t)(uintptr_t)export;
4022         zc.zc_share.z_sharetype = operation;
4023         zc.zc_share.z_sharemax = sharemax;
4024         error = ioctl(hdl->libzfs_fd, ZFS_IOC_SHARE, &zc);
4025         return (error);
4026 }
4027
4028 void
4029 zfs_prune_proplist(zfs_handle_t *zhp, uint8_t *props)
4030 {
4031         nvpair_t *curr;
4032
4033         /*
4034          * Keep a reference to the props-table against which we prune the
4035          * properties.
4036          */
4037         zhp->zfs_props_table = props;
4038
4039         curr = nvlist_next_nvpair(zhp->zfs_props, NULL);
4040
4041         while (curr) {
4042                 zfs_prop_t zfs_prop = zfs_name_to_prop(nvpair_name(curr));
4043                 nvpair_t *next = nvlist_next_nvpair(zhp->zfs_props, curr);
4044
4045                 /*
4046                  * We leave user:props in the nvlist, so there will be
4047                  * some ZPROP_INVAL.  To be extra safe, don't prune
4048                  * those.
4049                  */
4050                 if (zfs_prop != ZPROP_INVAL && props[zfs_prop] == B_FALSE)
4051                         (void) nvlist_remove(zhp->zfs_props,
4052                             nvpair_name(curr), nvpair_type(curr));
4053                 curr = next;
4054         }
4055 }
4056
4057 #ifdef sun
4058 static int
4059 zfs_smb_acl_mgmt(libzfs_handle_t *hdl, char *dataset, char *path,
4060     zfs_smb_acl_op_t cmd, char *resource1, char *resource2)
4061 {
4062         zfs_cmd_t zc = { 0 };
4063         nvlist_t *nvlist = NULL;
4064         int error;
4065
4066         (void) strlcpy(zc.zc_name, dataset, sizeof (zc.zc_name));
4067         (void) strlcpy(zc.zc_value, path, sizeof (zc.zc_value));
4068         zc.zc_cookie = (uint64_t)cmd;
4069
4070         if (cmd == ZFS_SMB_ACL_RENAME) {
4071                 if (nvlist_alloc(&nvlist, NV_UNIQUE_NAME, 0) != 0) {
4072                         (void) no_memory(hdl);
4073                         return (NULL);
4074                 }
4075         }
4076
4077         switch (cmd) {
4078         case ZFS_SMB_ACL_ADD:
4079         case ZFS_SMB_ACL_REMOVE:
4080                 (void) strlcpy(zc.zc_string, resource1, sizeof (zc.zc_string));
4081                 break;
4082         case ZFS_SMB_ACL_RENAME:
4083                 if (nvlist_add_string(nvlist, ZFS_SMB_ACL_SRC,
4084                     resource1) != 0) {
4085                                 (void) no_memory(hdl);
4086                                 return (-1);
4087                 }
4088                 if (nvlist_add_string(nvlist, ZFS_SMB_ACL_TARGET,
4089                     resource2) != 0) {
4090                                 (void) no_memory(hdl);
4091                                 return (-1);
4092                 }
4093                 if (zcmd_write_src_nvlist(hdl, &zc, nvlist) != 0) {
4094                         nvlist_free(nvlist);
4095                         return (-1);
4096                 }
4097                 break;
4098         case ZFS_SMB_ACL_PURGE:
4099                 break;
4100         default:
4101                 return (-1);
4102         }
4103         error = ioctl(hdl->libzfs_fd, ZFS_IOC_SMB_ACL, &zc);
4104         if (nvlist)
4105                 nvlist_free(nvlist);
4106         return (error);
4107 }
4108
4109 int
4110 zfs_smb_acl_add(libzfs_handle_t *hdl, char *dataset,
4111     char *path, char *resource)
4112 {
4113         return (zfs_smb_acl_mgmt(hdl, dataset, path, ZFS_SMB_ACL_ADD,
4114             resource, NULL));
4115 }
4116
4117 int
4118 zfs_smb_acl_remove(libzfs_handle_t *hdl, char *dataset,
4119     char *path, char *resource)
4120 {
4121         return (zfs_smb_acl_mgmt(hdl, dataset, path, ZFS_SMB_ACL_REMOVE,
4122             resource, NULL));
4123 }
4124
4125 int
4126 zfs_smb_acl_purge(libzfs_handle_t *hdl, char *dataset, char *path)
4127 {
4128         return (zfs_smb_acl_mgmt(hdl, dataset, path, ZFS_SMB_ACL_PURGE,
4129             NULL, NULL));
4130 }
4131
4132 int
4133 zfs_smb_acl_rename(libzfs_handle_t *hdl, char *dataset, char *path,
4134     char *oldname, char *newname)
4135 {
4136         return (zfs_smb_acl_mgmt(hdl, dataset, path, ZFS_SMB_ACL_RENAME,
4137             oldname, newname));
4138 }
4139 #endif  /* sun */
4140
4141 int
4142 zfs_userspace(zfs_handle_t *zhp, zfs_userquota_prop_t type,
4143     zfs_userspace_cb_t func, void *arg)
4144 {
4145         zfs_cmd_t zc = { 0 };
4146         int error;
4147         zfs_useracct_t buf[100];
4148
4149         (void) strncpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
4150
4151         zc.zc_objset_type = type;
4152         zc.zc_nvlist_dst = (uintptr_t)buf;
4153
4154         /* CONSTCOND */
4155         while (1) {
4156                 zfs_useracct_t *zua = buf;
4157
4158                 zc.zc_nvlist_dst_size = sizeof (buf);
4159                 error = ioctl(zhp->zfs_hdl->libzfs_fd,
4160                     ZFS_IOC_USERSPACE_MANY, &zc);
4161                 if (error || zc.zc_nvlist_dst_size == 0)
4162                         break;
4163
4164                 while (zc.zc_nvlist_dst_size > 0) {
4165                         error = func(arg, zua->zu_domain, zua->zu_rid,
4166                             zua->zu_space);
4167                         if (error != 0)
4168                                 return (error);
4169                         zua++;
4170                         zc.zc_nvlist_dst_size -= sizeof (zfs_useracct_t);
4171                 }
4172         }
4173
4174         return (error);
4175 }
4176
4177 /*
4178  * Attach/detach the given filesystem to/from the given jail.
4179  */
4180 int
4181 zfs_jail(zfs_handle_t *zhp, int jailid, int attach)
4182 {
4183         libzfs_handle_t *hdl = zhp->zfs_hdl;
4184         zfs_cmd_t zc = { 0 };
4185         char errbuf[1024];
4186         int cmd, ret;
4187
4188         if (attach) {
4189                 (void) snprintf(errbuf, sizeof (errbuf),
4190                     dgettext(TEXT_DOMAIN, "cannot jail '%s'"), zhp->zfs_name);
4191         } else {
4192                 (void) snprintf(errbuf, sizeof (errbuf),
4193                     dgettext(TEXT_DOMAIN, "cannot jail '%s'"), zhp->zfs_name);
4194         }
4195
4196         switch (zhp->zfs_type) {
4197         case ZFS_TYPE_VOLUME:
4198                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4199                     "volumes can not be jailed"));
4200                 return (zfs_error(hdl, EZFS_BADTYPE, errbuf));
4201         case ZFS_TYPE_SNAPSHOT:
4202                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4203                     "snapshots can not be jailed"));
4204                 return (zfs_error(hdl, EZFS_BADTYPE, errbuf));
4205         }
4206         assert(zhp->zfs_type == ZFS_TYPE_FILESYSTEM);
4207
4208         (void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
4209         zc.zc_objset_type = DMU_OST_ZFS;
4210         zc.zc_jailid = jailid;
4211
4212         cmd = attach ? ZFS_IOC_JAIL : ZFS_IOC_UNJAIL;
4213         if ((ret = ioctl(hdl->libzfs_fd, cmd, &zc)) != 0)
4214                 zfs_standard_error(hdl, errno, errbuf);
4215
4216         return (ret);
4217 }