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