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