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