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