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