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