5f8847a931052f28da8cb9773f392a54429afe4d
[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 static boolean_t
1317 zfs_is_namespace_prop(zfs_prop_t prop)
1318 {
1319         switch (prop) {
1320
1321         case ZFS_PROP_ATIME:
1322         case ZFS_PROP_DEVICES:
1323         case ZFS_PROP_EXEC:
1324         case ZFS_PROP_SETUID:
1325         case ZFS_PROP_READONLY:
1326         case ZFS_PROP_XATTR:
1327         case ZFS_PROP_NBMAND:
1328                 return (B_TRUE);
1329
1330         default:
1331                 return (B_FALSE);
1332         }
1333 }
1334
1335 /*
1336  * Given a property name and value, set the property for the given dataset.
1337  */
1338 int
1339 zfs_prop_set(zfs_handle_t *zhp, const char *propname, const char *propval)
1340 {
1341         zfs_cmd_t zc = { "\0", "\0", "\0", "\0", 0 };
1342         int ret = -1;
1343         prop_changelist_t *cl = NULL;
1344         char errbuf[1024];
1345         libzfs_handle_t *hdl = zhp->zfs_hdl;
1346         nvlist_t *nvl = NULL, *realprops;
1347         zfs_prop_t prop;
1348         boolean_t do_prefix;
1349         uint64_t idx;
1350         int added_resv = 0;
1351
1352         (void) snprintf(errbuf, sizeof (errbuf),
1353             dgettext(TEXT_DOMAIN, "cannot set property for '%s'"),
1354             zhp->zfs_name);
1355
1356         if (nvlist_alloc(&nvl, NV_UNIQUE_NAME, 0) != 0 ||
1357             nvlist_add_string(nvl, propname, propval) != 0) {
1358                 (void) no_memory(hdl);
1359                 goto error;
1360         }
1361
1362         if ((realprops = zfs_valid_proplist(hdl, zhp->zfs_type, nvl,
1363             zfs_prop_get_int(zhp, ZFS_PROP_ZONED), zhp, errbuf)) == NULL)
1364                 goto error;
1365
1366         nvlist_free(nvl);
1367         nvl = realprops;
1368
1369         prop = zfs_name_to_prop(propname);
1370
1371         if (prop == ZFS_PROP_VOLSIZE) {
1372                 if ((added_resv = zfs_add_synthetic_resv(zhp, nvl)) == -1)
1373                         goto error;
1374         }
1375
1376         if ((cl = changelist_gather(zhp, prop, 0, 0)) == NULL)
1377                 goto error;
1378
1379         if (prop == ZFS_PROP_MOUNTPOINT && changelist_haszonedchild(cl)) {
1380                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1381                     "child dataset with inherited mountpoint is used "
1382                     "in a non-global zone"));
1383                 ret = zfs_error(hdl, EZFS_ZONED, errbuf);
1384                 goto error;
1385         }
1386
1387         /*
1388          * If the dataset's canmount property is being set to noauto,
1389          * then we want to prevent unmounting & remounting it.
1390          */
1391         do_prefix = !((prop == ZFS_PROP_CANMOUNT) &&
1392             (zprop_string_to_index(prop, propval, &idx,
1393             ZFS_TYPE_DATASET) == 0) && (idx == ZFS_CANMOUNT_NOAUTO));
1394
1395         if (do_prefix && (ret = changelist_prefix(cl)) != 0)
1396                 goto error;
1397
1398         /*
1399          * Execute the corresponding ioctl() to set this property.
1400          */
1401         (void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
1402
1403         if (zcmd_write_src_nvlist(hdl, &zc, nvl) != 0)
1404                 goto error;
1405
1406         ret = zfs_ioctl(hdl, ZFS_IOC_SET_PROP, &zc);
1407
1408         if (ret != 0) {
1409                 zfs_setprop_error(hdl, prop, errno, errbuf);
1410                 if (added_resv && errno == ENOSPC) {
1411                         /* clean up the volsize property we tried to set */
1412                         uint64_t old_volsize = zfs_prop_get_int(zhp,
1413                             ZFS_PROP_VOLSIZE);
1414                         nvlist_free(nvl);
1415                         zcmd_free_nvlists(&zc);
1416                         if (nvlist_alloc(&nvl, NV_UNIQUE_NAME, 0) != 0)
1417                                 goto error;
1418                         if (nvlist_add_uint64(nvl,
1419                             zfs_prop_to_name(ZFS_PROP_VOLSIZE),
1420                             old_volsize) != 0)
1421                                 goto error;
1422                         if (zcmd_write_src_nvlist(hdl, &zc, nvl) != 0)
1423                                 goto error;
1424                         (void) zfs_ioctl(hdl, ZFS_IOC_SET_PROP, &zc);
1425                 }
1426         } else {
1427                 if (do_prefix)
1428                         ret = changelist_postfix(cl);
1429
1430                 if (ret == 0) {
1431                         /*
1432                          * Refresh the statistics so the new property
1433                          * value is reflected.
1434                          */
1435                         (void) get_stats(zhp);
1436
1437                         /*
1438                          * Remount the filesystem to propagate the change
1439                          * if one of the options handled by the generic
1440                          * Linux namespace layer has been modified.
1441                          */
1442                         if (zfs_is_namespace_prop(prop) &&
1443                             zfs_is_mounted(zhp, NULL))
1444                                 ret = zfs_mount(zhp, MNTOPT_REMOUNT, 0);
1445                 }
1446         }
1447
1448 error:
1449         nvlist_free(nvl);
1450         zcmd_free_nvlists(&zc);
1451         if (cl)
1452                 changelist_free(cl);
1453         return (ret);
1454 }
1455
1456 /*
1457  * Given a property, inherit the value from the parent dataset, or if received
1458  * is TRUE, revert to the received value, if any.
1459  */
1460 int
1461 zfs_prop_inherit(zfs_handle_t *zhp, const char *propname, boolean_t received)
1462 {
1463         zfs_cmd_t zc = { "\0", "\0", "\0", "\0", 0 };
1464         int ret;
1465         prop_changelist_t *cl;
1466         libzfs_handle_t *hdl = zhp->zfs_hdl;
1467         char errbuf[1024];
1468         zfs_prop_t prop;
1469
1470         (void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
1471             "cannot inherit %s for '%s'"), propname, zhp->zfs_name);
1472
1473         zc.zc_cookie = received;
1474         if ((prop = zfs_name_to_prop(propname)) == ZPROP_INVAL) {
1475                 /*
1476                  * For user properties, the amount of work we have to do is very
1477                  * small, so just do it here.
1478                  */
1479                 if (!zfs_prop_user(propname)) {
1480                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1481                             "invalid property"));
1482                         return (zfs_error(hdl, EZFS_BADPROP, errbuf));
1483                 }
1484
1485                 (void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
1486                 (void) strlcpy(zc.zc_value, propname, sizeof (zc.zc_value));
1487
1488                 if (zfs_ioctl(zhp->zfs_hdl, ZFS_IOC_INHERIT_PROP, &zc) != 0)
1489                         return (zfs_standard_error(hdl, errno, errbuf));
1490
1491                 return (0);
1492         }
1493
1494         /*
1495          * Verify that this property is inheritable.
1496          */
1497         if (zfs_prop_readonly(prop))
1498                 return (zfs_error(hdl, EZFS_PROPREADONLY, errbuf));
1499
1500         if (!zfs_prop_inheritable(prop) && !received)
1501                 return (zfs_error(hdl, EZFS_PROPNONINHERIT, errbuf));
1502
1503         /*
1504          * Check to see if the value applies to this type
1505          */
1506         if (!zfs_prop_valid_for_type(prop, zhp->zfs_type))
1507                 return (zfs_error(hdl, EZFS_PROPTYPE, errbuf));
1508
1509         /*
1510          * Normalize the name, to get rid of shorthand abbreviations.
1511          */
1512         propname = zfs_prop_to_name(prop);
1513         (void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
1514         (void) strlcpy(zc.zc_value, propname, sizeof (zc.zc_value));
1515
1516         if (prop == ZFS_PROP_MOUNTPOINT && getzoneid() == GLOBAL_ZONEID &&
1517             zfs_prop_get_int(zhp, ZFS_PROP_ZONED)) {
1518                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1519                     "dataset is used in a non-global zone"));
1520                 return (zfs_error(hdl, EZFS_ZONED, errbuf));
1521         }
1522
1523         /*
1524          * Determine datasets which will be affected by this change, if any.
1525          */
1526         if ((cl = changelist_gather(zhp, prop, 0, 0)) == NULL)
1527                 return (-1);
1528
1529         if (prop == ZFS_PROP_MOUNTPOINT && changelist_haszonedchild(cl)) {
1530                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1531                     "child dataset with inherited mountpoint is used "
1532                     "in a non-global zone"));
1533                 ret = zfs_error(hdl, EZFS_ZONED, errbuf);
1534                 goto error;
1535         }
1536
1537         if ((ret = changelist_prefix(cl)) != 0)
1538                 goto error;
1539
1540         if ((ret = zfs_ioctl(zhp->zfs_hdl, ZFS_IOC_INHERIT_PROP, &zc)) != 0) {
1541                 return (zfs_standard_error(hdl, errno, errbuf));
1542         } else {
1543
1544                 if ((ret = changelist_postfix(cl)) != 0)
1545                         goto error;
1546
1547                 /*
1548                  * Refresh the statistics so the new property is reflected.
1549                  */
1550                 (void) get_stats(zhp);
1551         }
1552
1553 error:
1554         changelist_free(cl);
1555         return (ret);
1556 }
1557
1558 /*
1559  * True DSL properties are stored in an nvlist.  The following two functions
1560  * extract them appropriately.
1561  */
1562 uint64_t
1563 getprop_uint64(zfs_handle_t *zhp, zfs_prop_t prop, char **source)
1564 {
1565         nvlist_t *nv;
1566         uint64_t value;
1567
1568         *source = NULL;
1569         if (nvlist_lookup_nvlist(zhp->zfs_props,
1570             zfs_prop_to_name(prop), &nv) == 0) {
1571                 verify(nvlist_lookup_uint64(nv, ZPROP_VALUE, &value) == 0);
1572                 (void) nvlist_lookup_string(nv, ZPROP_SOURCE, source);
1573         } else {
1574                 verify(!zhp->zfs_props_table ||
1575                     zhp->zfs_props_table[prop] == B_TRUE);
1576                 value = zfs_prop_default_numeric(prop);
1577                 *source = "";
1578         }
1579
1580         return (value);
1581 }
1582
1583 static char *
1584 getprop_string(zfs_handle_t *zhp, zfs_prop_t prop, char **source)
1585 {
1586         nvlist_t *nv;
1587         char *value;
1588
1589         *source = NULL;
1590         if (nvlist_lookup_nvlist(zhp->zfs_props,
1591             zfs_prop_to_name(prop), &nv) == 0) {
1592                 verify(nvlist_lookup_string(nv, ZPROP_VALUE, &value) == 0);
1593                 (void) nvlist_lookup_string(nv, ZPROP_SOURCE, source);
1594         } else {
1595                 verify(!zhp->zfs_props_table ||
1596                     zhp->zfs_props_table[prop] == B_TRUE);
1597                 if ((value = (char *)zfs_prop_default_string(prop)) == NULL)
1598                         value = "";
1599                 *source = "";
1600         }
1601
1602         return (value);
1603 }
1604
1605 static boolean_t
1606 zfs_is_recvd_props_mode(zfs_handle_t *zhp)
1607 {
1608         return (zhp->zfs_props == zhp->zfs_recvd_props);
1609 }
1610
1611 static void
1612 zfs_set_recvd_props_mode(zfs_handle_t *zhp, uint64_t *cookie)
1613 {
1614         *cookie = (uint64_t)(uintptr_t)zhp->zfs_props;
1615         zhp->zfs_props = zhp->zfs_recvd_props;
1616 }
1617
1618 static void
1619 zfs_unset_recvd_props_mode(zfs_handle_t *zhp, uint64_t *cookie)
1620 {
1621         zhp->zfs_props = (nvlist_t *)(uintptr_t)*cookie;
1622         *cookie = 0;
1623 }
1624
1625 /*
1626  * Internal function for getting a numeric property.  Both zfs_prop_get() and
1627  * zfs_prop_get_int() are built using this interface.
1628  *
1629  * Certain properties can be overridden using 'mount -o'.  In this case, scan
1630  * the contents of the /etc/mtab entry, searching for the appropriate options.
1631  * If they differ from the on-disk values, report the current values and mark
1632  * the source "temporary".
1633  */
1634 static int
1635 get_numeric_property(zfs_handle_t *zhp, zfs_prop_t prop, zprop_source_t *src,
1636     char **source, uint64_t *val)
1637 {
1638         zfs_cmd_t zc = { "\0", "\0", "\0", "\0", 0 };
1639         nvlist_t *zplprops = NULL;
1640         struct mnttab mnt;
1641         char *mntopt_on = NULL;
1642         char *mntopt_off = NULL;
1643         boolean_t received = zfs_is_recvd_props_mode(zhp);
1644
1645         *source = NULL;
1646
1647         switch (prop) {
1648         case ZFS_PROP_ATIME:
1649                 mntopt_on = MNTOPT_ATIME;
1650                 mntopt_off = MNTOPT_NOATIME;
1651                 break;
1652
1653         case ZFS_PROP_DEVICES:
1654                 mntopt_on = MNTOPT_DEVICES;
1655                 mntopt_off = MNTOPT_NODEVICES;
1656                 break;
1657
1658         case ZFS_PROP_EXEC:
1659                 mntopt_on = MNTOPT_EXEC;
1660                 mntopt_off = MNTOPT_NOEXEC;
1661                 break;
1662
1663         case ZFS_PROP_READONLY:
1664                 mntopt_on = MNTOPT_RO;
1665                 mntopt_off = MNTOPT_RW;
1666                 break;
1667
1668         case ZFS_PROP_SETUID:
1669                 mntopt_on = MNTOPT_SETUID;
1670                 mntopt_off = MNTOPT_NOSETUID;
1671                 break;
1672
1673         case ZFS_PROP_XATTR:
1674                 mntopt_on = MNTOPT_XATTR;
1675                 mntopt_off = MNTOPT_NOXATTR;
1676                 break;
1677
1678         case ZFS_PROP_NBMAND:
1679                 mntopt_on = MNTOPT_NBMAND;
1680                 mntopt_off = MNTOPT_NONBMAND;
1681                 break;
1682         default:
1683                 break;
1684         }
1685
1686         /*
1687          * Because looking up the mount options is potentially expensive
1688          * (iterating over all of /etc/mtab), we defer its calculation until
1689          * we're looking up a property which requires its presence.
1690          */
1691         if (!zhp->zfs_mntcheck &&
1692             (mntopt_on != NULL || prop == ZFS_PROP_MOUNTED)) {
1693                 libzfs_handle_t *hdl = zhp->zfs_hdl;
1694                 struct mnttab entry;
1695
1696                 if (libzfs_mnttab_find(hdl, zhp->zfs_name, &entry) == 0) {
1697                         zhp->zfs_mntopts = zfs_strdup(hdl,
1698                             entry.mnt_mntopts);
1699                         if (zhp->zfs_mntopts == NULL)
1700                                 return (-1);
1701                 }
1702
1703                 zhp->zfs_mntcheck = B_TRUE;
1704         }
1705
1706         if (zhp->zfs_mntopts == NULL)
1707                 mnt.mnt_mntopts = "";
1708         else
1709                 mnt.mnt_mntopts = zhp->zfs_mntopts;
1710
1711         switch (prop) {
1712         case ZFS_PROP_ATIME:
1713         case ZFS_PROP_DEVICES:
1714         case ZFS_PROP_EXEC:
1715         case ZFS_PROP_READONLY:
1716         case ZFS_PROP_SETUID:
1717         case ZFS_PROP_XATTR:
1718         case ZFS_PROP_NBMAND:
1719                 *val = getprop_uint64(zhp, prop, source);
1720
1721                 if (received)
1722                         break;
1723
1724                 if (hasmntopt(&mnt, mntopt_on) && !*val) {
1725                         *val = B_TRUE;
1726                         if (src)
1727                                 *src = ZPROP_SRC_TEMPORARY;
1728                 } else if (hasmntopt(&mnt, mntopt_off) && *val) {
1729                         *val = B_FALSE;
1730                         if (src)
1731                                 *src = ZPROP_SRC_TEMPORARY;
1732                 }
1733                 break;
1734
1735         case ZFS_PROP_CANMOUNT:
1736         case ZFS_PROP_VOLSIZE:
1737         case ZFS_PROP_QUOTA:
1738         case ZFS_PROP_REFQUOTA:
1739         case ZFS_PROP_RESERVATION:
1740         case ZFS_PROP_REFRESERVATION:
1741                 *val = getprop_uint64(zhp, prop, source);
1742
1743                 if (*source == NULL) {
1744                         /* not default, must be local */
1745                         *source = zhp->zfs_name;
1746                 }
1747                 break;
1748
1749         case ZFS_PROP_MOUNTED:
1750                 *val = (zhp->zfs_mntopts != NULL);
1751                 break;
1752
1753         case ZFS_PROP_NUMCLONES:
1754                 *val = zhp->zfs_dmustats.dds_num_clones;
1755                 break;
1756
1757         case ZFS_PROP_VERSION:
1758         case ZFS_PROP_NORMALIZE:
1759         case ZFS_PROP_UTF8ONLY:
1760         case ZFS_PROP_CASE:
1761                 if (!zfs_prop_valid_for_type(prop, zhp->zfs_head_type) ||
1762                     zcmd_alloc_dst_nvlist(zhp->zfs_hdl, &zc, 0) != 0)
1763                         return (-1);
1764                 (void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
1765                 if (zfs_ioctl(zhp->zfs_hdl, ZFS_IOC_OBJSET_ZPLPROPS, &zc)) {
1766                         zcmd_free_nvlists(&zc);
1767                         return (-1);
1768                 }
1769                 if (zcmd_read_dst_nvlist(zhp->zfs_hdl, &zc, &zplprops) != 0 ||
1770                     nvlist_lookup_uint64(zplprops, zfs_prop_to_name(prop),
1771                     val) != 0) {
1772                         zcmd_free_nvlists(&zc);
1773                         return (-1);
1774                 }
1775                 if (zplprops)
1776                         nvlist_free(zplprops);
1777                 zcmd_free_nvlists(&zc);
1778                 break;
1779
1780         default:
1781                 switch (zfs_prop_get_type(prop)) {
1782                 case PROP_TYPE_NUMBER:
1783                 case PROP_TYPE_INDEX:
1784                         *val = getprop_uint64(zhp, prop, source);
1785                         /*
1786                          * If we tried to use a default value for a
1787                          * readonly property, it means that it was not
1788                          * present.
1789                          */
1790                         if (zfs_prop_readonly(prop) &&
1791                             *source != NULL && (*source)[0] == '\0') {
1792                                 *source = NULL;
1793                         }
1794                         break;
1795
1796                 case PROP_TYPE_STRING:
1797                 default:
1798                         zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1799                             "cannot get non-numeric property"));
1800                         return (zfs_error(zhp->zfs_hdl, EZFS_BADPROP,
1801                             dgettext(TEXT_DOMAIN, "internal error")));
1802                 }
1803         }
1804
1805         return (0);
1806 }
1807
1808 /*
1809  * Calculate the source type, given the raw source string.
1810  */
1811 static void
1812 get_source(zfs_handle_t *zhp, zprop_source_t *srctype, char *source,
1813     char *statbuf, size_t statlen)
1814 {
1815         if (statbuf == NULL || *srctype == ZPROP_SRC_TEMPORARY)
1816                 return;
1817
1818         if (source == NULL) {
1819                 *srctype = ZPROP_SRC_NONE;
1820         } else if (source[0] == '\0') {
1821                 *srctype = ZPROP_SRC_DEFAULT;
1822         } else if (strstr(source, ZPROP_SOURCE_VAL_RECVD) != NULL) {
1823                 *srctype = ZPROP_SRC_RECEIVED;
1824         } else {
1825                 if (strcmp(source, zhp->zfs_name) == 0) {
1826                         *srctype = ZPROP_SRC_LOCAL;
1827                 } else {
1828                         (void) strlcpy(statbuf, source, statlen);
1829                         *srctype = ZPROP_SRC_INHERITED;
1830                 }
1831         }
1832
1833 }
1834
1835 int
1836 zfs_prop_get_recvd(zfs_handle_t *zhp, const char *propname, char *propbuf,
1837     size_t proplen, boolean_t literal)
1838 {
1839         zfs_prop_t prop;
1840         int err = 0;
1841
1842         if (zhp->zfs_recvd_props == NULL)
1843                 if (get_recvd_props_ioctl(zhp) != 0)
1844                         return (-1);
1845
1846         prop = zfs_name_to_prop(propname);
1847
1848         if (prop != ZPROP_INVAL) {
1849                 uint64_t cookie;
1850                 if (!nvlist_exists(zhp->zfs_recvd_props, propname))
1851                         return (-1);
1852                 zfs_set_recvd_props_mode(zhp, &cookie);
1853                 err = zfs_prop_get(zhp, prop, propbuf, proplen,
1854                     NULL, NULL, 0, literal);
1855                 zfs_unset_recvd_props_mode(zhp, &cookie);
1856         } else if (zfs_prop_userquota(propname)) {
1857                 return (-1);
1858         } else {
1859                 nvlist_t *propval;
1860                 char *recvdval;
1861                 if (nvlist_lookup_nvlist(zhp->zfs_recvd_props,
1862                     propname, &propval) != 0)
1863                         return (-1);
1864                 verify(nvlist_lookup_string(propval, ZPROP_VALUE,
1865                     &recvdval) == 0);
1866                 (void) strlcpy(propbuf, recvdval, proplen);
1867         }
1868
1869         return (err == 0 ? 0 : -1);
1870 }
1871
1872 /*
1873  * Retrieve a property from the given object.  If 'literal' is specified, then
1874  * numbers are left as exact values.  Otherwise, numbers are converted to a
1875  * human-readable form.
1876  *
1877  * Returns 0 on success, or -1 on error.
1878  */
1879 int
1880 zfs_prop_get(zfs_handle_t *zhp, zfs_prop_t prop, char *propbuf, size_t proplen,
1881     zprop_source_t *src, char *statbuf, size_t statlen, boolean_t literal)
1882 {
1883         char *source = NULL;
1884         uint64_t val;
1885         char *str;
1886         const char *strval;
1887         boolean_t received = zfs_is_recvd_props_mode(zhp);
1888
1889         /*
1890          * Check to see if this property applies to our object
1891          */
1892         if (!zfs_prop_valid_for_type(prop, zhp->zfs_type))
1893                 return (-1);
1894
1895         if (received && zfs_prop_readonly(prop))
1896                 return (-1);
1897
1898         if (src)
1899                 *src = ZPROP_SRC_NONE;
1900
1901         switch (prop) {
1902         case ZFS_PROP_CREATION:
1903                 /*
1904                  * 'creation' is a time_t stored in the statistics.  We convert
1905                  * this into a string unless 'literal' is specified.
1906                  */
1907                 {
1908                         val = getprop_uint64(zhp, prop, &source);
1909                         time_t time = (time_t)val;
1910                         struct tm t;
1911
1912                         if (literal ||
1913                             localtime_r(&time, &t) == NULL ||
1914                             strftime(propbuf, proplen, "%a %b %e %k:%M %Y",
1915                             &t) == 0)
1916                                 (void) snprintf(propbuf, proplen, "%llu", (u_longlong_t) val);
1917                 }
1918                 break;
1919
1920         case ZFS_PROP_MOUNTPOINT:
1921                 /*
1922                  * Getting the precise mountpoint can be tricky.
1923                  *
1924                  *  - for 'none' or 'legacy', return those values.
1925                  *  - for inherited mountpoints, we want to take everything
1926                  *    after our ancestor and append it to the inherited value.
1927                  *
1928                  * If the pool has an alternate root, we want to prepend that
1929                  * root to any values we return.
1930                  */
1931
1932                 str = getprop_string(zhp, prop, &source);
1933
1934                 if (str[0] == '/') {
1935                         char buf[MAXPATHLEN];
1936                         char *root = buf;
1937                         const char *relpath;
1938
1939                         /*
1940                          * If we inherit the mountpoint, even from a dataset
1941                          * with a received value, the source will be the path of
1942                          * the dataset we inherit from. If source is
1943                          * ZPROP_SOURCE_VAL_RECVD, the received value is not
1944                          * inherited.
1945                          */
1946                         if (strcmp(source, ZPROP_SOURCE_VAL_RECVD) == 0) {
1947                                 relpath = "";
1948                         } else {
1949                                 relpath = zhp->zfs_name + strlen(source);
1950                                 if (relpath[0] == '/')
1951                                         relpath++;
1952                         }
1953
1954                         if ((zpool_get_prop(zhp->zpool_hdl,
1955                             ZPOOL_PROP_ALTROOT, buf, MAXPATHLEN, NULL)) ||
1956                             (strcmp(root, "-") == 0))
1957                                 root[0] = '\0';
1958                         /*
1959                          * Special case an alternate root of '/'. This will
1960                          * avoid having multiple leading slashes in the
1961                          * mountpoint path.
1962                          */
1963                         if (strcmp(root, "/") == 0)
1964                                 root++;
1965
1966                         /*
1967                          * If the mountpoint is '/' then skip over this
1968                          * if we are obtaining either an alternate root or
1969                          * an inherited mountpoint.
1970                          */
1971                         if (str[1] == '\0' && (root[0] != '\0' ||
1972                             relpath[0] != '\0'))
1973                                 str++;
1974
1975                         if (relpath[0] == '\0')
1976                                 (void) snprintf(propbuf, proplen, "%s%s",
1977                                     root, str);
1978                         else
1979                                 (void) snprintf(propbuf, proplen, "%s%s%s%s",
1980                                     root, str, relpath[0] == '@' ? "" : "/",
1981                                     relpath);
1982                 } else {
1983                         /* 'legacy' or 'none' */
1984                         (void) strlcpy(propbuf, str, proplen);
1985                 }
1986
1987                 break;
1988
1989         case ZFS_PROP_ORIGIN:
1990                 (void) strlcpy(propbuf, getprop_string(zhp, prop, &source),
1991                     proplen);
1992                 /*
1993                  * If there is no parent at all, return failure to indicate that
1994                  * it doesn't apply to this dataset.
1995                  */
1996                 if (propbuf[0] == '\0')
1997                         return (-1);
1998                 break;
1999
2000         case ZFS_PROP_QUOTA:
2001         case ZFS_PROP_REFQUOTA:
2002         case ZFS_PROP_RESERVATION:
2003         case ZFS_PROP_REFRESERVATION:
2004
2005                 if (get_numeric_property(zhp, prop, src, &source, &val) != 0)
2006                         return (-1);
2007
2008                 /*
2009                  * If quota or reservation is 0, we translate this into 'none'
2010                  * (unless literal is set), and indicate that it's the default
2011                  * value.  Otherwise, we print the number nicely and indicate
2012                  * that its set locally.
2013                  */
2014                 if (val == 0) {
2015                         if (literal)
2016                                 (void) strlcpy(propbuf, "0", proplen);
2017                         else
2018                                 (void) strlcpy(propbuf, "none", proplen);
2019                 } else {
2020                         if (literal)
2021                                 (void) snprintf(propbuf, proplen, "%llu",
2022                                     (u_longlong_t)val);
2023                         else
2024                                 zfs_nicenum(val, propbuf, proplen);
2025                 }
2026                 break;
2027
2028         case ZFS_PROP_COMPRESSRATIO:
2029                 if (get_numeric_property(zhp, prop, src, &source, &val) != 0)
2030                         return (-1);
2031                 (void) snprintf(propbuf, proplen, "%llu.%02llux",
2032                     (u_longlong_t)(val / 100),
2033                     (u_longlong_t)(val % 100));
2034                 break;
2035
2036         case ZFS_PROP_TYPE:
2037                 switch (zhp->zfs_type) {
2038                 case ZFS_TYPE_FILESYSTEM:
2039                         str = "filesystem";
2040                         break;
2041                 case ZFS_TYPE_VOLUME:
2042                         str = "volume";
2043                         break;
2044                 case ZFS_TYPE_SNAPSHOT:
2045                         str = "snapshot";
2046                         break;
2047                 default:
2048                         abort();
2049                 }
2050                 (void) snprintf(propbuf, proplen, "%s", str);
2051                 break;
2052
2053         case ZFS_PROP_MOUNTED:
2054                 /*
2055                  * The 'mounted' property is a pseudo-property that described
2056                  * whether the filesystem is currently mounted.  Even though
2057                  * it's a boolean value, the typical values of "on" and "off"
2058                  * don't make sense, so we translate to "yes" and "no".
2059                  */
2060                 if (get_numeric_property(zhp, ZFS_PROP_MOUNTED,
2061                     src, &source, &val) != 0)
2062                         return (-1);
2063                 if (val)
2064                         (void) strlcpy(propbuf, "yes", proplen);
2065                 else
2066                         (void) strlcpy(propbuf, "no", proplen);
2067                 break;
2068
2069         case ZFS_PROP_NAME:
2070                 /*
2071                  * The 'name' property is a pseudo-property derived from the
2072                  * dataset name.  It is presented as a real property to simplify
2073                  * consumers.
2074                  */
2075                 (void) strlcpy(propbuf, zhp->zfs_name, proplen);
2076                 break;
2077
2078         case ZFS_PROP_MLSLABEL:
2079                 {
2080 #ifdef HAVE_MLSLABEL
2081                         m_label_t *new_sl = NULL;
2082                         char *ascii = NULL;     /* human readable label */
2083
2084                         (void) strlcpy(propbuf,
2085                             getprop_string(zhp, prop, &source), proplen);
2086
2087                         if (literal || (strcasecmp(propbuf,
2088                             ZFS_MLSLABEL_DEFAULT) == 0))
2089                                 break;
2090
2091                         /*
2092                          * Try to translate the internal hex string to
2093                          * human-readable output.  If there are any
2094                          * problems just use the hex string.
2095                          */
2096
2097                         if (str_to_label(propbuf, &new_sl, MAC_LABEL,
2098                             L_NO_CORRECTION, NULL) == -1) {
2099                                 m_label_free(new_sl);
2100                                 break;
2101                         }
2102
2103                         if (label_to_str(new_sl, &ascii, M_LABEL,
2104                             DEF_NAMES) != 0) {
2105                                 if (ascii)
2106                                         free(ascii);
2107                                 m_label_free(new_sl);
2108                                 break;
2109                         }
2110                         m_label_free(new_sl);
2111
2112                         (void) strlcpy(propbuf, ascii, proplen);
2113                         free(ascii);
2114 #else
2115                         (void) strlcpy(propbuf,
2116                             getprop_string(zhp, prop, &source), proplen);
2117 #endif /* HAVE_MLSLABEL */
2118                 }
2119                 break;
2120
2121         default:
2122                 switch (zfs_prop_get_type(prop)) {
2123                 case PROP_TYPE_NUMBER:
2124                         if (get_numeric_property(zhp, prop, src,
2125                             &source, &val) != 0)
2126                                 return (-1);
2127                         if (literal)
2128                                 (void) snprintf(propbuf, proplen, "%llu",
2129                                     (u_longlong_t)val);
2130                         else
2131                                 zfs_nicenum(val, propbuf, proplen);
2132                         break;
2133
2134                 case PROP_TYPE_STRING:
2135                         (void) strlcpy(propbuf,
2136                             getprop_string(zhp, prop, &source), proplen);
2137                         break;
2138
2139                 case PROP_TYPE_INDEX:
2140                         if (get_numeric_property(zhp, prop, src,
2141                             &source, &val) != 0)
2142                                 return (-1);
2143                         if (zfs_prop_index_to_string(prop, val, &strval) != 0)
2144                                 return (-1);
2145                         (void) strlcpy(propbuf, strval, proplen);
2146                         break;
2147
2148                 default:
2149                         abort();
2150                 }
2151         }
2152
2153         get_source(zhp, src, source, statbuf, statlen);
2154
2155         return (0);
2156 }
2157
2158 /*
2159  * Utility function to get the given numeric property.  Does no validation that
2160  * the given property is the appropriate type; should only be used with
2161  * hard-coded property types.
2162  */
2163 uint64_t
2164 zfs_prop_get_int(zfs_handle_t *zhp, zfs_prop_t prop)
2165 {
2166         char *source;
2167         uint64_t val;
2168
2169         (void) get_numeric_property(zhp, prop, NULL, &source, &val);
2170
2171         return (val);
2172 }
2173
2174 int
2175 zfs_prop_set_int(zfs_handle_t *zhp, zfs_prop_t prop, uint64_t val)
2176 {
2177         char buf[64];
2178
2179         (void) snprintf(buf, sizeof (buf), "%llu", (longlong_t)val);
2180         return (zfs_prop_set(zhp, zfs_prop_to_name(prop), buf));
2181 }
2182
2183 /*
2184  * Similar to zfs_prop_get(), but returns the value as an integer.
2185  */
2186 int
2187 zfs_prop_get_numeric(zfs_handle_t *zhp, zfs_prop_t prop, uint64_t *value,
2188     zprop_source_t *src, char *statbuf, size_t statlen)
2189 {
2190         char *source;
2191
2192         /*
2193          * Check to see if this property applies to our object
2194          */
2195         if (!zfs_prop_valid_for_type(prop, zhp->zfs_type)) {
2196                 return (zfs_error_fmt(zhp->zfs_hdl, EZFS_PROPTYPE,
2197                     dgettext(TEXT_DOMAIN, "cannot get property '%s'"),
2198                     zfs_prop_to_name(prop)));
2199         }
2200
2201         if (src)
2202                 *src = ZPROP_SRC_NONE;
2203
2204         if (get_numeric_property(zhp, prop, src, &source, value) != 0)
2205                 return (-1);
2206
2207         get_source(zhp, src, source, statbuf, statlen);
2208
2209         return (0);
2210 }
2211
2212 #ifdef HAVE_IDMAP
2213 static int
2214 idmap_id_to_numeric_domain_rid(uid_t id, boolean_t isuser,
2215     char **domainp, idmap_rid_t *ridp)
2216 {
2217         idmap_get_handle_t *get_hdl = NULL;
2218         idmap_stat status;
2219         int err = EINVAL;
2220
2221         if (idmap_get_create(&get_hdl) != IDMAP_SUCCESS)
2222                 goto out;
2223
2224         if (isuser) {
2225                 err = idmap_get_sidbyuid(get_hdl, id,
2226                     IDMAP_REQ_FLG_USE_CACHE, domainp, ridp, &status);
2227         } else {
2228                 err = idmap_get_sidbygid(get_hdl, id,
2229                     IDMAP_REQ_FLG_USE_CACHE, domainp, ridp, &status);
2230         }
2231         if (err == IDMAP_SUCCESS &&
2232             idmap_get_mappings(get_hdl) == IDMAP_SUCCESS &&
2233             status == IDMAP_SUCCESS)
2234                 err = 0;
2235         else
2236                 err = EINVAL;
2237 out:
2238         if (get_hdl)
2239                 idmap_get_destroy(get_hdl);
2240         return (err);
2241 }
2242 #endif /* HAVE_IDMAP */
2243
2244 /*
2245  * convert the propname into parameters needed by kernel
2246  * Eg: userquota@ahrens -> ZFS_PROP_USERQUOTA, "", 126829
2247  * Eg: userused@matt@domain -> ZFS_PROP_USERUSED, "S-1-123-456", 789
2248  */
2249 static int
2250 userquota_propname_decode(const char *propname, boolean_t zoned,
2251     zfs_userquota_prop_t *typep, char *domain, int domainlen, uint64_t *ridp)
2252 {
2253         zfs_userquota_prop_t type;
2254         char *cp, *end;
2255         char *numericsid = NULL;
2256         boolean_t isuser;
2257
2258         domain[0] = '\0';
2259
2260         /* Figure out the property type ({user|group}{quota|space}) */
2261         for (type = 0; type < ZFS_NUM_USERQUOTA_PROPS; type++) {
2262                 if (strncmp(propname, zfs_userquota_prop_prefixes[type],
2263                     strlen(zfs_userquota_prop_prefixes[type])) == 0)
2264                         break;
2265         }
2266         if (type == ZFS_NUM_USERQUOTA_PROPS)
2267                 return (EINVAL);
2268         *typep = type;
2269
2270         isuser = (type == ZFS_PROP_USERQUOTA ||
2271             type == ZFS_PROP_USERUSED);
2272
2273         cp = strchr(propname, '@') + 1;
2274
2275         if (strchr(cp, '@')) {
2276 #ifdef HAVE_IDMAP
2277                 /*
2278                  * It's a SID name (eg "user@domain") that needs to be
2279                  * turned into S-1-domainID-RID.
2280                  */
2281                 directory_error_t e;
2282                 if (zoned && getzoneid() == GLOBAL_ZONEID)
2283                         return (ENOENT);
2284                 if (isuser) {
2285                         e = directory_sid_from_user_name(NULL,
2286                             cp, &numericsid);
2287                 } else {
2288                         e = directory_sid_from_group_name(NULL,
2289                             cp, &numericsid);
2290                 }
2291                 if (e != NULL) {
2292                         directory_error_free(e);
2293                         return (ENOENT);
2294                 }
2295                 if (numericsid == NULL)
2296                         return (ENOENT);
2297                 cp = numericsid;
2298                 /* will be further decoded below */
2299 #else
2300                 return (ENOSYS);
2301 #endif /* HAVE_IDMAP */
2302         }
2303
2304         if (strncmp(cp, "S-1-", 4) == 0) {
2305                 /* It's a numeric SID (eg "S-1-234-567-89") */
2306                 (void) strlcpy(domain, cp, domainlen);
2307                 cp = strrchr(domain, '-');
2308                 *cp = '\0';
2309                 cp++;
2310
2311                 errno = 0;
2312                 *ridp = strtoull(cp, &end, 10);
2313                 if (numericsid) {
2314                         free(numericsid);
2315                         numericsid = NULL;
2316                 }
2317                 if (errno != 0 || *end != '\0')
2318                         return (EINVAL);
2319         } else if (!isdigit(*cp)) {
2320                 /*
2321                  * It's a user/group name (eg "user") that needs to be
2322                  * turned into a uid/gid
2323                  */
2324                 if (zoned && getzoneid() == GLOBAL_ZONEID)
2325                         return (ENOENT);
2326                 if (isuser) {
2327                         struct passwd *pw;
2328                         pw = getpwnam(cp);
2329                         if (pw == NULL)
2330                                 return (ENOENT);
2331                         *ridp = pw->pw_uid;
2332                 } else {
2333                         struct group *gr;
2334                         gr = getgrnam(cp);
2335                         if (gr == NULL)
2336                                 return (ENOENT);
2337                         *ridp = gr->gr_gid;
2338                 }
2339         } else {
2340 #ifdef HAVE_IDMAP
2341                 /* It's a user/group ID (eg "12345"). */
2342                 uid_t id = strtoul(cp, &end, 10);
2343                 idmap_rid_t rid;
2344                 char *mapdomain;
2345
2346                 if (*end != '\0')
2347                         return (EINVAL);
2348                 if (id > MAXUID) {
2349                         /* It's an ephemeral ID. */
2350                         if (idmap_id_to_numeric_domain_rid(id, isuser,
2351                             &mapdomain, &rid) != 0)
2352                                 return (ENOENT);
2353                         (void) strlcpy(domain, mapdomain, domainlen);
2354                         *ridp = rid;
2355                 } else {
2356                         *ridp = id;
2357                 }
2358 #else
2359                 return (ENOSYS);
2360 #endif /* HAVE_IDMAP */
2361         }
2362
2363         ASSERT3P(numericsid, ==, NULL);
2364         return (0);
2365 }
2366
2367 static int
2368 zfs_prop_get_userquota_common(zfs_handle_t *zhp, const char *propname,
2369     uint64_t *propvalue, zfs_userquota_prop_t *typep)
2370 {
2371         int err;
2372         zfs_cmd_t zc = { "\0", "\0", "\0", "\0", 0 };
2373
2374         (void) strncpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
2375
2376         err = userquota_propname_decode(propname,
2377             zfs_prop_get_int(zhp, ZFS_PROP_ZONED),
2378             typep, zc.zc_value, sizeof (zc.zc_value), &zc.zc_guid);
2379         zc.zc_objset_type = *typep;
2380         if (err)
2381                 return (err);
2382
2383         err = ioctl(zhp->zfs_hdl->libzfs_fd, ZFS_IOC_USERSPACE_ONE, &zc);
2384         if (err)
2385                 return (err);
2386
2387         *propvalue = zc.zc_cookie;
2388         return (0);
2389 }
2390
2391 int
2392 zfs_prop_get_userquota_int(zfs_handle_t *zhp, const char *propname,
2393     uint64_t *propvalue)
2394 {
2395         zfs_userquota_prop_t type;
2396
2397         return (zfs_prop_get_userquota_common(zhp, propname, propvalue,
2398             &type));
2399 }
2400
2401 int
2402 zfs_prop_get_userquota(zfs_handle_t *zhp, const char *propname,
2403     char *propbuf, int proplen, boolean_t literal)
2404 {
2405         int err;
2406         uint64_t propvalue;
2407         zfs_userquota_prop_t type;
2408
2409         err = zfs_prop_get_userquota_common(zhp, propname, &propvalue,
2410             &type);
2411
2412         if (err)
2413                 return (err);
2414
2415         if (literal) {
2416                 (void) snprintf(propbuf, proplen, "%llu",
2417                                (u_longlong_t)propvalue);
2418         } else if (propvalue == 0 &&
2419             (type == ZFS_PROP_USERQUOTA || type == ZFS_PROP_GROUPQUOTA)) {
2420                 (void) strlcpy(propbuf, "none", proplen);
2421         } else {
2422                 zfs_nicenum(propvalue, propbuf, proplen);
2423         }
2424         return (0);
2425 }
2426
2427 /*
2428  * Returns the name of the given zfs handle.
2429  */
2430 const char *
2431 zfs_get_name(const zfs_handle_t *zhp)
2432 {
2433         return (zhp->zfs_name);
2434 }
2435
2436 /*
2437  * Returns the type of the given zfs handle.
2438  */
2439 zfs_type_t
2440 zfs_get_type(const zfs_handle_t *zhp)
2441 {
2442         return (zhp->zfs_type);
2443 }
2444
2445 static int
2446 zfs_do_list_ioctl(zfs_handle_t *zhp, int arg, zfs_cmd_t *zc)
2447 {
2448         int rc;
2449         uint64_t        orig_cookie;
2450
2451         orig_cookie = zc->zc_cookie;
2452 top:
2453         (void) strlcpy(zc->zc_name, zhp->zfs_name, sizeof (zc->zc_name));
2454         rc = ioctl(zhp->zfs_hdl->libzfs_fd, arg, zc);
2455
2456         if (rc == -1) {
2457                 switch (errno) {
2458                 case ENOMEM:
2459                         /* expand nvlist memory and try again */
2460                         if (zcmd_expand_dst_nvlist(zhp->zfs_hdl, zc) != 0) {
2461                                 zcmd_free_nvlists(zc);
2462                                 return (-1);
2463                         }
2464                         zc->zc_cookie = orig_cookie;
2465                         goto top;
2466                 /*
2467                  * An errno value of ESRCH indicates normal completion.
2468                  * If ENOENT is returned, then the underlying dataset
2469                  * has been removed since we obtained the handle.
2470                  */
2471                 case ESRCH:
2472                 case ENOENT:
2473                         rc = 1;
2474                         break;
2475                 default:
2476                         rc = zfs_standard_error(zhp->zfs_hdl, errno,
2477                             dgettext(TEXT_DOMAIN,
2478                             "cannot iterate filesystems"));
2479                         break;
2480                 }
2481         }
2482         return (rc);
2483 }
2484
2485 /*
2486  * Iterate over all child filesystems
2487  */
2488 int
2489 zfs_iter_filesystems(zfs_handle_t *zhp, zfs_iter_f func, void *data)
2490 {
2491         zfs_cmd_t zc = { "\0", "\0", "\0", "\0", 0 };
2492         zfs_handle_t *nzhp;
2493         int ret;
2494
2495         if (zhp->zfs_type != ZFS_TYPE_FILESYSTEM)
2496                 return (0);
2497
2498         if (zcmd_alloc_dst_nvlist(zhp->zfs_hdl, &zc, 0) != 0)
2499                 return (-1);
2500
2501         while ((ret = zfs_do_list_ioctl(zhp, ZFS_IOC_DATASET_LIST_NEXT,
2502             &zc)) == 0) {
2503                 /*
2504                  * Silently ignore errors, as the only plausible explanation is
2505                  * that the pool has since been removed.
2506                  */
2507                 if ((nzhp = make_dataset_handle_zc(zhp->zfs_hdl,
2508                     &zc)) == NULL) {
2509                         continue;
2510                 }
2511
2512                 if ((ret = func(nzhp, data)) != 0) {
2513                         zcmd_free_nvlists(&zc);
2514                         return (ret);
2515                 }
2516         }
2517         zcmd_free_nvlists(&zc);
2518         return ((ret < 0) ? ret : 0);
2519 }
2520
2521 /*
2522  * Iterate over all snapshots
2523  */
2524 int
2525 zfs_iter_snapshots(zfs_handle_t *zhp, zfs_iter_f func, void *data)
2526 {
2527         zfs_cmd_t zc = { "\0", "\0", "\0", "\0", 0 };
2528         zfs_handle_t *nzhp;
2529         int ret;
2530
2531         if (zhp->zfs_type == ZFS_TYPE_SNAPSHOT)
2532                 return (0);
2533
2534         if (zcmd_alloc_dst_nvlist(zhp->zfs_hdl, &zc, 0) != 0)
2535                 return (-1);
2536         while ((ret = zfs_do_list_ioctl(zhp, ZFS_IOC_SNAPSHOT_LIST_NEXT,
2537             &zc)) == 0) {
2538
2539                 if ((nzhp = make_dataset_handle_zc(zhp->zfs_hdl,
2540                     &zc)) == NULL) {
2541                         continue;
2542                 }
2543
2544                 if ((ret = func(nzhp, data)) != 0) {
2545                         zcmd_free_nvlists(&zc);
2546                         return (ret);
2547                 }
2548         }
2549         zcmd_free_nvlists(&zc);
2550         return ((ret < 0) ? ret : 0);
2551 }
2552
2553 /*
2554  * Iterate over all children, snapshots and filesystems
2555  */
2556 int
2557 zfs_iter_children(zfs_handle_t *zhp, zfs_iter_f func, void *data)
2558 {
2559         int ret;
2560
2561         if ((ret = zfs_iter_filesystems(zhp, func, data)) != 0)
2562                 return (ret);
2563
2564         return (zfs_iter_snapshots(zhp, func, data));
2565 }
2566
2567 /*
2568  * Is one dataset name a child dataset of another?
2569  *
2570  * Needs to handle these cases:
2571  * Dataset 1    "a/foo"         "a/foo"         "a/foo"         "a/foo"
2572  * Dataset 2    "a/fo"          "a/foobar"      "a/bar/baz"     "a/foo/bar"
2573  * Descendant?  No.             No.             No.             Yes.
2574  */
2575 static boolean_t
2576 is_descendant(const char *ds1, const char *ds2)
2577 {
2578         size_t d1len = strlen(ds1);
2579
2580         /* ds2 can't be a descendant if it's smaller */
2581         if (strlen(ds2) < d1len)
2582                 return (B_FALSE);
2583
2584         /* otherwise, compare strings and verify that there's a '/' char */
2585         return (ds2[d1len] == '/' && (strncmp(ds1, ds2, d1len) == 0));
2586 }
2587
2588 /*
2589  * Given a complete name, return just the portion that refers to the parent.
2590  * Can return NULL if this is a pool.
2591  */
2592 static int
2593 parent_name(const char *path, char *buf, size_t buflen)
2594 {
2595         char *loc;
2596
2597         if ((loc = strrchr(path, '/')) == NULL)
2598                 return (-1);
2599
2600         (void) strncpy(buf, path, MIN(buflen, loc - path));
2601         buf[loc - path] = '\0';
2602
2603         return (0);
2604 }
2605
2606 /*
2607  * If accept_ancestor is false, then check to make sure that the given path has
2608  * a parent, and that it exists.  If accept_ancestor is true, then find the
2609  * closest existing ancestor for the given path.  In prefixlen return the
2610  * length of already existing prefix of the given path.  We also fetch the
2611  * 'zoned' property, which is used to validate property settings when creating
2612  * new datasets.
2613  */
2614 static int
2615 check_parents(libzfs_handle_t *hdl, const char *path, uint64_t *zoned,
2616     boolean_t accept_ancestor, int *prefixlen)
2617 {
2618         zfs_cmd_t zc = { "\0", "\0", "\0", "\0", 0 };
2619         char parent[ZFS_MAXNAMELEN];
2620         char *slash;
2621         zfs_handle_t *zhp;
2622         char errbuf[1024];
2623         uint64_t is_zoned;
2624
2625         (void) snprintf(errbuf, sizeof (errbuf),
2626             dgettext(TEXT_DOMAIN, "cannot create '%s'"), path);
2627
2628         /* get parent, and check to see if this is just a pool */
2629         if (parent_name(path, parent, sizeof (parent)) != 0) {
2630                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2631                     "missing dataset name"));
2632                 return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
2633         }
2634
2635         /* check to see if the pool exists */
2636         if ((slash = strchr(parent, '/')) == NULL)
2637                 slash = parent + strlen(parent);
2638         (void) strncpy(zc.zc_name, parent, slash - parent);
2639         zc.zc_name[slash - parent] = '\0';
2640         if (ioctl(hdl->libzfs_fd, ZFS_IOC_OBJSET_STATS, &zc) != 0 &&
2641             errno == ENOENT) {
2642                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2643                     "no such pool '%s'"), zc.zc_name);
2644                 return (zfs_error(hdl, EZFS_NOENT, errbuf));
2645         }
2646
2647         /* check to see if the parent dataset exists */
2648         while ((zhp = make_dataset_handle(hdl, parent)) == NULL) {
2649                 if (errno == ENOENT && accept_ancestor) {
2650                         /*
2651                          * Go deeper to find an ancestor, give up on top level.
2652                          */
2653                         if (parent_name(parent, parent, sizeof (parent)) != 0) {
2654                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2655                                     "no such pool '%s'"), zc.zc_name);
2656                                 return (zfs_error(hdl, EZFS_NOENT, errbuf));
2657                         }
2658                 } else if (errno == ENOENT) {
2659                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2660                             "parent does not exist"));
2661                         return (zfs_error(hdl, EZFS_NOENT, errbuf));
2662                 } else
2663                         return (zfs_standard_error(hdl, errno, errbuf));
2664         }
2665
2666         is_zoned = zfs_prop_get_int(zhp, ZFS_PROP_ZONED);
2667         if (zoned != NULL)
2668                 *zoned = is_zoned;
2669
2670         /* we are in a non-global zone, but parent is in the global zone */
2671         if (getzoneid() != GLOBAL_ZONEID && !is_zoned) {
2672                 (void) zfs_standard_error(hdl, EPERM, errbuf);
2673                 zfs_close(zhp);
2674                 return (-1);
2675         }
2676
2677         /* make sure parent is a filesystem */
2678         if (zfs_get_type(zhp) != ZFS_TYPE_FILESYSTEM) {
2679                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2680                     "parent is not a filesystem"));
2681                 (void) zfs_error(hdl, EZFS_BADTYPE, errbuf);
2682                 zfs_close(zhp);
2683                 return (-1);
2684         }
2685
2686         zfs_close(zhp);
2687         if (prefixlen != NULL)
2688                 *prefixlen = strlen(parent);
2689         return (0);
2690 }
2691
2692 /*
2693  * Finds whether the dataset of the given type(s) exists.
2694  */
2695 boolean_t
2696 zfs_dataset_exists(libzfs_handle_t *hdl, const char *path, zfs_type_t types)
2697 {
2698         zfs_handle_t *zhp;
2699
2700         if (!zfs_validate_name(hdl, path, types, B_FALSE))
2701                 return (B_FALSE);
2702
2703         /*
2704          * Try to get stats for the dataset, which will tell us if it exists.
2705          */
2706         if ((zhp = make_dataset_handle(hdl, path)) != NULL) {
2707                 int ds_type = zhp->zfs_type;
2708
2709                 zfs_close(zhp);
2710                 if (types & ds_type)
2711                         return (B_TRUE);
2712         }
2713         return (B_FALSE);
2714 }
2715
2716 /*
2717  * Given a path to 'target', create all the ancestors between
2718  * the prefixlen portion of the path, and the target itself.
2719  * Fail if the initial prefixlen-ancestor does not already exist.
2720  */
2721 int
2722 create_parents(libzfs_handle_t *hdl, char *target, int prefixlen)
2723 {
2724         zfs_handle_t *h;
2725         char *cp;
2726         const char *opname;
2727
2728         /* make sure prefix exists */
2729         cp = target + prefixlen;
2730         if (*cp != '/') {
2731                 assert(strchr(cp, '/') == NULL);
2732                 h = zfs_open(hdl, target, ZFS_TYPE_FILESYSTEM);
2733         } else {
2734                 *cp = '\0';
2735                 h = zfs_open(hdl, target, ZFS_TYPE_FILESYSTEM);
2736                 *cp = '/';
2737         }
2738         if (h == NULL)
2739                 return (-1);
2740         zfs_close(h);
2741
2742         /*
2743          * Attempt to create, mount, and share any ancestor filesystems,
2744          * up to the prefixlen-long one.
2745          */
2746         for (cp = target + prefixlen + 1;
2747             (cp = strchr(cp, '/')); *cp = '/', cp++) {
2748                 char *logstr;
2749
2750                 *cp = '\0';
2751
2752                 h = make_dataset_handle(hdl, target);
2753                 if (h) {
2754                         /* it already exists, nothing to do here */
2755                         zfs_close(h);
2756                         continue;
2757                 }
2758
2759                 logstr = hdl->libzfs_log_str;
2760                 hdl->libzfs_log_str = NULL;
2761                 if (zfs_create(hdl, target, ZFS_TYPE_FILESYSTEM,
2762                     NULL) != 0) {
2763                         hdl->libzfs_log_str = logstr;
2764                         opname = dgettext(TEXT_DOMAIN, "create");
2765                         goto ancestorerr;
2766                 }
2767
2768                 hdl->libzfs_log_str = logstr;
2769                 h = zfs_open(hdl, target, ZFS_TYPE_FILESYSTEM);
2770                 if (h == NULL) {
2771                         opname = dgettext(TEXT_DOMAIN, "open");
2772                         goto ancestorerr;
2773                 }
2774
2775                 if (zfs_mount(h, NULL, 0) != 0) {
2776                         opname = dgettext(TEXT_DOMAIN, "mount");
2777                         goto ancestorerr;
2778                 }
2779
2780                 if (zfs_share(h) != 0) {
2781                         opname = dgettext(TEXT_DOMAIN, "share");
2782                         goto ancestorerr;
2783                 }
2784
2785                 zfs_close(h);
2786         }
2787
2788         return (0);
2789
2790 ancestorerr:
2791         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2792             "failed to %s ancestor '%s'"), opname, target);
2793         return (-1);
2794 }
2795
2796 /*
2797  * Creates non-existing ancestors of the given path.
2798  */
2799 int
2800 zfs_create_ancestors(libzfs_handle_t *hdl, const char *path)
2801 {
2802         int prefix;
2803         char *path_copy;
2804         int rc = 0;
2805
2806         if (check_parents(hdl, path, NULL, B_TRUE, &prefix) != 0)
2807                 return (-1);
2808
2809         if ((path_copy = strdup(path)) != NULL) {
2810                 rc = create_parents(hdl, path_copy, prefix);
2811                 free(path_copy);
2812         }
2813         if (path_copy == NULL || rc != 0)
2814                 return (-1);
2815
2816         return (0);
2817 }
2818
2819 /*
2820  * Create a new filesystem or volume.
2821  */
2822 int
2823 zfs_create(libzfs_handle_t *hdl, const char *path, zfs_type_t type,
2824     nvlist_t *props)
2825 {
2826         zfs_cmd_t zc = { "\0", "\0", "\0", "\0", 0 };
2827         int ret;
2828         uint64_t size = 0;
2829         uint64_t blocksize = zfs_prop_default_numeric(ZFS_PROP_VOLBLOCKSIZE);
2830         char errbuf[1024];
2831         uint64_t zoned;
2832
2833         (void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
2834             "cannot create '%s'"), path);
2835
2836         /* validate the path, taking care to note the extended error message */
2837         if (!zfs_validate_name(hdl, path, type, B_TRUE))
2838                 return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
2839
2840         /* validate parents exist */
2841         if (check_parents(hdl, path, &zoned, B_FALSE, NULL) != 0)
2842                 return (-1);
2843
2844         /*
2845          * The failure modes when creating a dataset of a different type over
2846          * one that already exists is a little strange.  In particular, if you
2847          * try to create a dataset on top of an existing dataset, the ioctl()
2848          * will return ENOENT, not EEXIST.  To prevent this from happening, we
2849          * first try to see if the dataset exists.
2850          */
2851         (void) strlcpy(zc.zc_name, path, sizeof (zc.zc_name));
2852         if (zfs_dataset_exists(hdl, zc.zc_name, ZFS_TYPE_DATASET)) {
2853                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2854                     "dataset already exists"));
2855                 return (zfs_error(hdl, EZFS_EXISTS, errbuf));
2856         }
2857
2858         if (type == ZFS_TYPE_VOLUME)
2859                 zc.zc_objset_type = DMU_OST_ZVOL;
2860         else
2861                 zc.zc_objset_type = DMU_OST_ZFS;
2862
2863         if (props && (props = zfs_valid_proplist(hdl, type, props,
2864             zoned, NULL, errbuf)) == 0)
2865                 return (-1);
2866
2867         if (type == ZFS_TYPE_VOLUME) {
2868                 /*
2869                  * If we are creating a volume, the size and block size must
2870                  * satisfy a few restraints.  First, the blocksize must be a
2871                  * valid block size between SPA_{MIN,MAX}BLOCKSIZE.  Second, the
2872                  * volsize must be a multiple of the block size, and cannot be
2873                  * zero.
2874                  */
2875                 if (props == NULL || nvlist_lookup_uint64(props,
2876                     zfs_prop_to_name(ZFS_PROP_VOLSIZE), &size) != 0) {
2877                         nvlist_free(props);
2878                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2879                             "missing volume size"));
2880                         return (zfs_error(hdl, EZFS_BADPROP, errbuf));
2881                 }
2882
2883                 if ((ret = nvlist_lookup_uint64(props,
2884                     zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE),
2885                     &blocksize)) != 0) {
2886                         if (ret == ENOENT) {
2887                                 blocksize = zfs_prop_default_numeric(
2888                                     ZFS_PROP_VOLBLOCKSIZE);
2889                         } else {
2890                                 nvlist_free(props);
2891                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2892                                     "missing volume block size"));
2893                                 return (zfs_error(hdl, EZFS_BADPROP, errbuf));
2894                         }
2895                 }
2896
2897                 if (size == 0) {
2898                         nvlist_free(props);
2899                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2900                             "volume size cannot be zero"));
2901                         return (zfs_error(hdl, EZFS_BADPROP, errbuf));
2902                 }
2903
2904                 if (size % blocksize != 0) {
2905                         nvlist_free(props);
2906                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2907                             "volume size must be a multiple of volume block "
2908                             "size"));
2909                         return (zfs_error(hdl, EZFS_BADPROP, errbuf));
2910                 }
2911         }
2912
2913         if (props && zcmd_write_src_nvlist(hdl, &zc, props) != 0)
2914                 return (-1);
2915         nvlist_free(props);
2916
2917         /* create the dataset */
2918         ret = zfs_ioctl(hdl, ZFS_IOC_CREATE, &zc);
2919
2920         if (ret == 0 && type == ZFS_TYPE_VOLUME) {
2921                 ret = zvol_create_link(hdl, path);
2922                 if (ret) {
2923                         (void) zfs_standard_error(hdl, errno,
2924                             dgettext(TEXT_DOMAIN,
2925                             "Volume successfully created, but device links "
2926                             "were not created"));
2927                         zcmd_free_nvlists(&zc);
2928                         return (-1);
2929                 }
2930         }
2931
2932         zcmd_free_nvlists(&zc);
2933
2934         /* check for failure */
2935         if (ret != 0) {
2936                 char parent[ZFS_MAXNAMELEN];
2937                 (void) parent_name(path, parent, sizeof (parent));
2938
2939                 switch (errno) {
2940                 case ENOENT:
2941                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2942                             "no such parent '%s'"), parent);
2943                         return (zfs_error(hdl, EZFS_NOENT, errbuf));
2944
2945                 case EINVAL:
2946                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2947                             "parent '%s' is not a filesystem"), parent);
2948                         return (zfs_error(hdl, EZFS_BADTYPE, errbuf));
2949
2950                 case EDOM:
2951                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2952                             "volume block size must be power of 2 from "
2953                             "%u to %uk"),
2954                             (uint_t)SPA_MINBLOCKSIZE,
2955                             (uint_t)SPA_MAXBLOCKSIZE >> 10);
2956
2957                         return (zfs_error(hdl, EZFS_BADPROP, errbuf));
2958
2959                 case ENOTSUP:
2960                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2961                             "pool must be upgraded to set this "
2962                             "property or value"));
2963                         return (zfs_error(hdl, EZFS_BADVERSION, errbuf));
2964 #ifdef _ILP32
2965                 case EOVERFLOW:
2966                         /*
2967                          * This platform can't address a volume this big.
2968                          */
2969                         if (type == ZFS_TYPE_VOLUME)
2970                                 return (zfs_error(hdl, EZFS_VOLTOOBIG,
2971                                     errbuf));
2972 #endif
2973                         /* FALLTHROUGH */
2974                 default:
2975                         return (zfs_standard_error(hdl, errno, errbuf));
2976                 }
2977         }
2978
2979         return (0);
2980 }
2981
2982 /*
2983  * Destroys the given dataset.  The caller must make sure that the filesystem
2984  * isn't mounted, and that there are no active dependents.
2985  */
2986 int
2987 zfs_destroy(zfs_handle_t *zhp, boolean_t defer)
2988 {
2989         zfs_cmd_t zc = { "\0", "\0", "\0", "\0", 0 };
2990
2991         (void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
2992
2993         if (ZFS_IS_VOLUME(zhp)) {
2994                 if (zvol_remove_link(zhp->zfs_hdl, zhp->zfs_name) != 0)
2995                         return (-1);
2996
2997                 zc.zc_objset_type = DMU_OST_ZVOL;
2998         } else {
2999                 zc.zc_objset_type = DMU_OST_ZFS;
3000         }
3001
3002         zc.zc_defer_destroy = defer;
3003         if (zfs_ioctl(zhp->zfs_hdl, ZFS_IOC_DESTROY, &zc) != 0) {
3004                 return (zfs_standard_error_fmt(zhp->zfs_hdl, errno,
3005                     dgettext(TEXT_DOMAIN, "cannot destroy '%s'"),
3006                     zhp->zfs_name));
3007         }
3008
3009         remove_mountpoint(zhp);
3010
3011         return (0);
3012 }
3013
3014 struct destroydata {
3015         char *snapname;
3016         boolean_t gotone;
3017         boolean_t closezhp;
3018 };
3019
3020 static int
3021 zfs_check_snap_cb(zfs_handle_t *zhp, void *arg)
3022 {
3023         struct destroydata *dd = arg;
3024         zfs_handle_t *szhp;
3025         char name[ZFS_MAXNAMELEN];
3026         boolean_t closezhp = dd->closezhp;
3027         int rv = 0;
3028
3029         (void) strlcpy(name, zhp->zfs_name, sizeof (name));
3030         (void) strlcat(name, "@", sizeof (name));
3031         (void) strlcat(name, dd->snapname, sizeof (name));
3032
3033         szhp = make_dataset_handle(zhp->zfs_hdl, name);
3034         if (szhp) {
3035                 dd->gotone = B_TRUE;
3036                 zfs_close(szhp);
3037         }
3038
3039         if (zhp->zfs_type == ZFS_TYPE_VOLUME) {
3040                 (void) zvol_remove_link(zhp->zfs_hdl, name);
3041                 /*
3042                  * NB: this is simply a best-effort.  We don't want to
3043                  * return an error, because then we wouldn't visit all
3044                  * the volumes.
3045                  */
3046         }
3047
3048         dd->closezhp = B_TRUE;
3049         rv = zfs_iter_filesystems(zhp, zfs_check_snap_cb, arg);
3050         if (closezhp)
3051                 zfs_close(zhp);
3052         return (rv);
3053 }
3054
3055 /*
3056  * Destroys all snapshots with the given name in zhp & descendants.
3057  */
3058 int
3059 zfs_destroy_snaps(zfs_handle_t *zhp, char *snapname, boolean_t defer)
3060 {
3061         zfs_cmd_t zc = { "\0", "\0", "\0", "\0", 0 };
3062         int ret;
3063         struct destroydata dd = { 0 };
3064
3065         dd.snapname = snapname;
3066         (void) zfs_check_snap_cb(zhp, &dd);
3067
3068         if (!dd.gotone) {
3069                 return (zfs_standard_error_fmt(zhp->zfs_hdl, ENOENT,
3070                     dgettext(TEXT_DOMAIN, "cannot destroy '%s@%s'"),
3071                     zhp->zfs_name, snapname));
3072         }
3073
3074         (void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
3075         (void) strlcpy(zc.zc_value, snapname, sizeof (zc.zc_value));
3076         zc.zc_defer_destroy = defer;
3077
3078         ret = zfs_ioctl(zhp->zfs_hdl, ZFS_IOC_DESTROY_SNAPS, &zc);
3079         if (ret != 0) {
3080                 char errbuf[1024];
3081
3082                 (void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
3083                     "cannot destroy '%s@%s'"), zc.zc_name, snapname);
3084
3085                 switch (errno) {
3086                 case EEXIST:
3087                         zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
3088                             "snapshot is cloned"));
3089                         return (zfs_error(zhp->zfs_hdl, EZFS_EXISTS, errbuf));
3090
3091                 default:
3092                         return (zfs_standard_error(zhp->zfs_hdl, errno,
3093                             errbuf));
3094                 }
3095         }
3096
3097         return (0);
3098 }
3099
3100 /*
3101  * Clones the given dataset.  The target must be of the same type as the source.
3102  */
3103 int
3104 zfs_clone(zfs_handle_t *zhp, const char *target, nvlist_t *props)
3105 {
3106         zfs_cmd_t zc = { "\0", "\0", "\0", "\0", 0 };
3107         char parent[ZFS_MAXNAMELEN];
3108         int ret;
3109         char errbuf[1024];
3110         libzfs_handle_t *hdl = zhp->zfs_hdl;
3111         zfs_type_t type;
3112         uint64_t zoned;
3113
3114         assert(zhp->zfs_type == ZFS_TYPE_SNAPSHOT);
3115
3116         (void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
3117             "cannot create '%s'"), target);
3118
3119         /* validate the target name */
3120         if (!zfs_validate_name(hdl, target, ZFS_TYPE_FILESYSTEM, B_TRUE))
3121                 return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
3122
3123         /* validate parents exist */
3124         if (check_parents(hdl, target, &zoned, B_FALSE, NULL) != 0)
3125                 return (-1);
3126
3127         (void) parent_name(target, parent, sizeof (parent));
3128
3129         /* do the clone */
3130         if (ZFS_IS_VOLUME(zhp)) {
3131                 zc.zc_objset_type = DMU_OST_ZVOL;
3132                 type = ZFS_TYPE_VOLUME;
3133         } else {
3134                 zc.zc_objset_type = DMU_OST_ZFS;
3135                 type = ZFS_TYPE_FILESYSTEM;
3136         }
3137
3138         if (props) {
3139                 if ((props = zfs_valid_proplist(hdl, type, props, zoned,
3140                     zhp, errbuf)) == NULL)
3141                         return (-1);
3142
3143                 if (zcmd_write_src_nvlist(hdl, &zc, props) != 0) {
3144                         nvlist_free(props);
3145                         return (-1);
3146                 }
3147
3148                 nvlist_free(props);
3149         }
3150
3151         (void) strlcpy(zc.zc_name, target, sizeof (zc.zc_name));
3152         (void) strlcpy(zc.zc_value, zhp->zfs_name, sizeof (zc.zc_value));
3153         ret = zfs_ioctl(zhp->zfs_hdl, ZFS_IOC_CREATE, &zc);
3154
3155         zcmd_free_nvlists(&zc);
3156
3157         if (ret != 0) {
3158                 switch (errno) {
3159
3160                 case ENOENT:
3161                         /*
3162                          * The parent doesn't exist.  We should have caught this
3163                          * above, but there may a race condition that has since
3164                          * destroyed the parent.
3165                          *
3166                          * At this point, we don't know whether it's the source
3167                          * that doesn't exist anymore, or whether the target
3168                          * dataset doesn't exist.
3169                          */
3170                         zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
3171                             "no such parent '%s'"), parent);
3172                         return (zfs_error(zhp->zfs_hdl, EZFS_NOENT, errbuf));
3173
3174                 case EXDEV:
3175                         zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
3176                             "source and target pools differ"));
3177                         return (zfs_error(zhp->zfs_hdl, EZFS_CROSSTARGET,
3178                             errbuf));
3179
3180                 default:
3181                         return (zfs_standard_error(zhp->zfs_hdl, errno,
3182                             errbuf));
3183                 }
3184         } else if (ZFS_IS_VOLUME(zhp)) {
3185                 ret = zvol_create_link(zhp->zfs_hdl, target);
3186         }
3187
3188         return (ret);
3189 }
3190
3191 typedef struct promote_data {
3192         char cb_mountpoint[MAXPATHLEN];
3193         const char *cb_target;
3194         const char *cb_errbuf;
3195         uint64_t cb_pivot_txg;
3196 } promote_data_t;
3197
3198 static int
3199 promote_snap_cb(zfs_handle_t *zhp, void *data)
3200 {
3201         promote_data_t *pd = data;
3202         zfs_handle_t *szhp;
3203         char snapname[MAXPATHLEN];
3204         int rv = 0;
3205
3206         /* We don't care about snapshots after the pivot point */
3207         if (zfs_prop_get_int(zhp, ZFS_PROP_CREATETXG) > pd->cb_pivot_txg) {
3208                 zfs_close(zhp);
3209                 return (0);
3210         }
3211
3212         /* Remove the device link if it's a zvol. */
3213         if (ZFS_IS_VOLUME(zhp))
3214                 (void) zvol_remove_link(zhp->zfs_hdl, zhp->zfs_name);
3215
3216         /* Check for conflicting names */
3217         (void) strlcpy(snapname, pd->cb_target, sizeof (snapname));
3218         (void) strlcat(snapname, strchr(zhp->zfs_name, '@'), sizeof (snapname));
3219         szhp = make_dataset_handle(zhp->zfs_hdl, snapname);
3220         if (szhp != NULL) {
3221                 zfs_close(szhp);
3222                 zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
3223                     "snapshot name '%s' from origin \n"
3224                     "conflicts with '%s' from target"),
3225                     zhp->zfs_name, snapname);
3226                 rv = zfs_error(zhp->zfs_hdl, EZFS_EXISTS, pd->cb_errbuf);
3227         }
3228         zfs_close(zhp);
3229         return (rv);
3230 }
3231
3232 static int
3233 promote_snap_done_cb(zfs_handle_t *zhp, void *data)
3234 {
3235         promote_data_t *pd = data;
3236
3237         /* We don't care about snapshots after the pivot point */
3238         if (zfs_prop_get_int(zhp, ZFS_PROP_CREATETXG) <= pd->cb_pivot_txg) {
3239                 /* Create the device link if it's a zvol. */
3240                 if (ZFS_IS_VOLUME(zhp))
3241                         (void) zvol_create_link(zhp->zfs_hdl, zhp->zfs_name);
3242         }
3243
3244         zfs_close(zhp);
3245         return (0);
3246 }
3247
3248 /*
3249  * Promotes the given clone fs to be the clone parent.
3250  */
3251 int
3252 zfs_promote(zfs_handle_t *zhp)
3253 {
3254         libzfs_handle_t *hdl = zhp->zfs_hdl;
3255         zfs_cmd_t zc = { "\0", "\0", "\0", "\0", 0 };
3256         char parent[MAXPATHLEN];
3257         char *cp;
3258         int ret;
3259         zfs_handle_t *pzhp;
3260         promote_data_t pd;
3261         char errbuf[1024];
3262
3263         (void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
3264             "cannot promote '%s'"), zhp->zfs_name);
3265
3266         if (zhp->zfs_type == ZFS_TYPE_SNAPSHOT) {
3267                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3268                     "snapshots can not be promoted"));
3269                 return (zfs_error(hdl, EZFS_BADTYPE, errbuf));
3270         }
3271
3272         (void) strlcpy(parent, zhp->zfs_dmustats.dds_origin, sizeof (parent));
3273         if (parent[0] == '\0') {
3274                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3275                     "not a cloned filesystem"));
3276                 return (zfs_error(hdl, EZFS_BADTYPE, errbuf));
3277         }
3278         cp = strchr(parent, '@');
3279         *cp = '\0';
3280
3281         /* Walk the snapshots we will be moving */
3282         pzhp = zfs_open(hdl, zhp->zfs_dmustats.dds_origin, ZFS_TYPE_SNAPSHOT);
3283         if (pzhp == NULL)
3284                 return (-1);
3285         pd.cb_pivot_txg = zfs_prop_get_int(pzhp, ZFS_PROP_CREATETXG);
3286         zfs_close(pzhp);
3287         pd.cb_target = zhp->zfs_name;
3288         pd.cb_errbuf = errbuf;
3289         pzhp = zfs_open(hdl, parent, ZFS_TYPE_DATASET);
3290         if (pzhp == NULL)
3291                 return (-1);
3292         (void) zfs_prop_get(pzhp, ZFS_PROP_MOUNTPOINT, pd.cb_mountpoint,
3293             sizeof (pd.cb_mountpoint), NULL, NULL, 0, FALSE);
3294         ret = zfs_iter_snapshots(pzhp, promote_snap_cb, &pd);
3295         if (ret != 0) {
3296                 zfs_close(pzhp);
3297                 return (-1);
3298         }
3299
3300         /* issue the ioctl */
3301         (void) strlcpy(zc.zc_value, zhp->zfs_dmustats.dds_origin,
3302             sizeof (zc.zc_value));
3303         (void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
3304         ret = zfs_ioctl(hdl, ZFS_IOC_PROMOTE, &zc);
3305
3306         if (ret != 0) {
3307                 int save_errno = errno;
3308
3309                 (void) zfs_iter_snapshots(pzhp, promote_snap_done_cb, &pd);
3310                 zfs_close(pzhp);
3311
3312                 switch (save_errno) {
3313                 case EEXIST:
3314                         /*
3315                          * There is a conflicting snapshot name.  We
3316                          * should have caught this above, but they could
3317                          * have renamed something in the mean time.
3318                          */
3319                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3320                             "conflicting snapshot '%s' from parent '%s'"),
3321                             zc.zc_string, parent);
3322                         return (zfs_error(hdl, EZFS_EXISTS, errbuf));
3323
3324                 default:
3325                         return (zfs_standard_error(hdl, save_errno, errbuf));
3326                 }
3327         } else {
3328                 (void) zfs_iter_snapshots(zhp, promote_snap_done_cb, &pd);
3329         }
3330
3331         zfs_close(pzhp);
3332         return (ret);
3333 }
3334
3335 struct createdata {
3336         const char *cd_snapname;
3337         int cd_ifexists;
3338 };
3339
3340 static int
3341 zfs_create_link_cb(zfs_handle_t *zhp, void *arg)
3342 {
3343         struct createdata *cd = arg;
3344         int ret;
3345
3346         if (zhp->zfs_type == ZFS_TYPE_VOLUME) {
3347                 char name[MAXPATHLEN];
3348
3349                 (void) strlcpy(name, zhp->zfs_name, sizeof (name));
3350                 (void) strlcat(name, "@", sizeof (name));
3351                 (void) strlcat(name, cd->cd_snapname, sizeof (name));
3352                 (void) zvol_create_link_common(zhp->zfs_hdl, name,
3353                     cd->cd_ifexists);
3354                 /*
3355                  * NB: this is simply a best-effort.  We don't want to
3356                  * return an error, because then we wouldn't visit all
3357                  * the volumes.
3358                  */
3359         }
3360
3361         ret = zfs_iter_filesystems(zhp, zfs_create_link_cb, cd);
3362
3363         zfs_close(zhp);
3364
3365         return (ret);
3366 }
3367
3368 /*
3369  * Takes a snapshot of the given dataset.
3370  */
3371 int
3372 zfs_snapshot(libzfs_handle_t *hdl, const char *path, boolean_t recursive,
3373     nvlist_t *props)
3374 {
3375         const char *delim;
3376         char parent[ZFS_MAXNAMELEN];
3377         zfs_handle_t *zhp;
3378         zfs_cmd_t zc = { "\0", "\0", "\0", "\0", 0 };
3379         int ret;
3380         char errbuf[1024];
3381
3382         (void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
3383             "cannot snapshot '%s'"), path);
3384
3385         /* validate the target name */
3386         if (!zfs_validate_name(hdl, path, ZFS_TYPE_SNAPSHOT, B_TRUE))
3387                 return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
3388
3389         if (props) {
3390                 if ((props = zfs_valid_proplist(hdl, ZFS_TYPE_SNAPSHOT,
3391                     props, B_FALSE, NULL, errbuf)) == NULL)
3392                         return (-1);
3393
3394                 if (zcmd_write_src_nvlist(hdl, &zc, props) != 0) {
3395                         nvlist_free(props);
3396                         return (-1);
3397                 }
3398
3399                 nvlist_free(props);
3400         }
3401
3402         /* make sure the parent exists and is of the appropriate type */
3403         delim = strchr(path, '@');
3404         (void) strncpy(parent, path, delim - path);
3405         parent[delim - path] = '\0';
3406
3407         if ((zhp = zfs_open(hdl, parent, ZFS_TYPE_FILESYSTEM |
3408             ZFS_TYPE_VOLUME)) == NULL) {
3409                 zcmd_free_nvlists(&zc);
3410                 return (-1);
3411         }
3412
3413         (void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
3414         (void) strlcpy(zc.zc_value, delim+1, sizeof (zc.zc_value));
3415         if (ZFS_IS_VOLUME(zhp))
3416                 zc.zc_objset_type = DMU_OST_ZVOL;
3417         else
3418                 zc.zc_objset_type = DMU_OST_ZFS;
3419         zc.zc_cookie = recursive;
3420         ret = zfs_ioctl(zhp->zfs_hdl, ZFS_IOC_SNAPSHOT, &zc);
3421
3422         zcmd_free_nvlists(&zc);
3423
3424         /*
3425          * if it was recursive, the one that actually failed will be in
3426          * zc.zc_name.
3427          */
3428         if (ret != 0)
3429                 (void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
3430                     "cannot create snapshot '%s@%s'"), zc.zc_name, zc.zc_value);
3431
3432         if (ret == 0 && recursive) {
3433                 struct createdata cd;
3434
3435                 cd.cd_snapname = delim + 1;
3436                 cd.cd_ifexists = B_FALSE;
3437                 (void) zfs_iter_filesystems(zhp, zfs_create_link_cb, &cd);
3438         }
3439         if (ret == 0 && zhp->zfs_type == ZFS_TYPE_VOLUME) {
3440                 ret = zvol_create_link(zhp->zfs_hdl, path);
3441                 if (ret != 0) {
3442                         (void) zfs_standard_error(hdl, errno,
3443                             dgettext(TEXT_DOMAIN,
3444                             "Volume successfully snapshotted, but device links "
3445                             "were not created"));
3446                         zfs_close(zhp);
3447                         return (-1);
3448                 }
3449         }
3450
3451         if (ret != 0)
3452                 (void) zfs_standard_error(hdl, errno, errbuf);
3453
3454         zfs_close(zhp);
3455
3456         return (ret);
3457 }
3458
3459 /*
3460  * Destroy any more recent snapshots.  We invoke this callback on any dependents
3461  * of the snapshot first.  If the 'cb_dependent' member is non-zero, then this
3462  * is a dependent and we should just destroy it without checking the transaction
3463  * group.
3464  */
3465 typedef struct rollback_data {
3466         const char      *cb_target;             /* the snapshot */
3467         uint64_t        cb_create;              /* creation time reference */
3468         boolean_t       cb_error;
3469         boolean_t       cb_dependent;
3470         boolean_t       cb_force;
3471 } rollback_data_t;
3472
3473 static int
3474 rollback_destroy(zfs_handle_t *zhp, void *data)
3475 {
3476         rollback_data_t *cbp = data;
3477
3478         if (!cbp->cb_dependent) {
3479                 if (strcmp(zhp->zfs_name, cbp->cb_target) != 0 &&
3480                     zfs_get_type(zhp) == ZFS_TYPE_SNAPSHOT &&
3481                     zfs_prop_get_int(zhp, ZFS_PROP_CREATETXG) >
3482                     cbp->cb_create) {
3483                         char *logstr;
3484
3485                         cbp->cb_dependent = B_TRUE;
3486                         cbp->cb_error |= zfs_iter_dependents(zhp, B_FALSE,
3487                             rollback_destroy, cbp);
3488                         cbp->cb_dependent = B_FALSE;
3489
3490                         logstr = zhp->zfs_hdl->libzfs_log_str;
3491                         zhp->zfs_hdl->libzfs_log_str = NULL;
3492                         cbp->cb_error |= zfs_destroy(zhp, B_FALSE);
3493                         zhp->zfs_hdl->libzfs_log_str = logstr;
3494                 }
3495         } else {
3496                 /* We must destroy this clone; first unmount it */
3497                 prop_changelist_t *clp;
3498
3499                 clp = changelist_gather(zhp, ZFS_PROP_NAME, 0,
3500                     cbp->cb_force ? MS_FORCE: 0);
3501                 if (clp == NULL || changelist_prefix(clp) != 0) {
3502                         cbp->cb_error = B_TRUE;
3503                         zfs_close(zhp);
3504                         return (0);
3505                 }
3506                 if (zfs_destroy(zhp, B_FALSE) != 0)
3507                         cbp->cb_error = B_TRUE;
3508                 else
3509                         changelist_remove(clp, zhp->zfs_name);
3510                 (void) changelist_postfix(clp);
3511                 changelist_free(clp);
3512         }
3513
3514         zfs_close(zhp);
3515         return (0);
3516 }
3517
3518 /*
3519  * Given a dataset, rollback to a specific snapshot, discarding any
3520  * data changes since then and making it the active dataset.
3521  *
3522  * Any snapshots more recent than the target are destroyed, along with
3523  * their dependents.
3524  */
3525 int
3526 zfs_rollback(zfs_handle_t *zhp, zfs_handle_t *snap, boolean_t force)
3527 {
3528         rollback_data_t cb = { 0 };
3529         int err;
3530         zfs_cmd_t zc = { "\0", "\0", "\0", "\0", 0 };
3531         boolean_t restore_resv = 0;
3532         uint64_t old_volsize = 0, new_volsize;
3533         zfs_prop_t resv_prop = { 0 };
3534
3535         assert(zhp->zfs_type == ZFS_TYPE_FILESYSTEM ||
3536             zhp->zfs_type == ZFS_TYPE_VOLUME);
3537
3538         /*
3539          * Destroy all recent snapshots and its dependends.
3540          */
3541         cb.cb_force = force;
3542         cb.cb_target = snap->zfs_name;
3543         cb.cb_create = zfs_prop_get_int(snap, ZFS_PROP_CREATETXG);
3544         (void) zfs_iter_children(zhp, rollback_destroy, &cb);
3545
3546         if (cb.cb_error)
3547                 return (-1);
3548
3549         /*
3550          * Now that we have verified that the snapshot is the latest,
3551          * rollback to the given snapshot.
3552          */
3553
3554         if (zhp->zfs_type == ZFS_TYPE_VOLUME) {
3555                 if (zvol_remove_link(zhp->zfs_hdl, zhp->zfs_name) != 0)
3556                         return (-1);
3557                 if (zfs_which_resv_prop(zhp, &resv_prop) < 0)
3558                         return (-1);
3559                 old_volsize = zfs_prop_get_int(zhp, ZFS_PROP_VOLSIZE);
3560                 restore_resv =
3561                     (old_volsize == zfs_prop_get_int(zhp, resv_prop));
3562         }
3563
3564         (void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
3565
3566         if (ZFS_IS_VOLUME(zhp))
3567                 zc.zc_objset_type = DMU_OST_ZVOL;
3568         else
3569                 zc.zc_objset_type = DMU_OST_ZFS;
3570
3571         /*
3572          * We rely on zfs_iter_children() to verify that there are no
3573          * newer snapshots for the given dataset.  Therefore, we can
3574          * simply pass the name on to the ioctl() call.  There is still
3575          * an unlikely race condition where the user has taken a
3576          * snapshot since we verified that this was the most recent.
3577          *
3578          */
3579         if ((err = zfs_ioctl(zhp->zfs_hdl, ZFS_IOC_ROLLBACK, &zc)) != 0) {
3580                 (void) zfs_standard_error_fmt(zhp->zfs_hdl, errno,
3581                     dgettext(TEXT_DOMAIN, "cannot rollback '%s'"),
3582                     zhp->zfs_name);
3583                 return (err);
3584         }
3585
3586         /*
3587          * For volumes, if the pre-rollback volsize matched the pre-
3588          * rollback reservation and the volsize has changed then set
3589          * the reservation property to the post-rollback volsize.
3590          * Make a new handle since the rollback closed the dataset.
3591          */
3592         if ((zhp->zfs_type == ZFS_TYPE_VOLUME) &&
3593             (zhp = make_dataset_handle(zhp->zfs_hdl, zhp->zfs_name))) {
3594                 if ((err = zvol_create_link(zhp->zfs_hdl, zhp->zfs_name))) {
3595                         zfs_close(zhp);
3596                         return (err);
3597                 }
3598                 if (restore_resv) {
3599                         new_volsize = zfs_prop_get_int(zhp, ZFS_PROP_VOLSIZE);
3600                         if (old_volsize != new_volsize)
3601                                 err = zfs_prop_set_int(zhp, resv_prop,
3602                                     new_volsize);
3603                 }
3604                 zfs_close(zhp);
3605         }
3606         return (err);
3607 }
3608
3609 /*
3610  * Iterate over all dependents for a given dataset.  This includes both
3611  * hierarchical dependents (children) and data dependents (snapshots and
3612  * clones).  The bulk of the processing occurs in get_dependents() in
3613  * libzfs_graph.c.
3614  */
3615 int
3616 zfs_iter_dependents(zfs_handle_t *zhp, boolean_t allowrecursion,
3617     zfs_iter_f func, void *data)
3618 {
3619         char **dependents;
3620         size_t count;
3621         int i;
3622         zfs_handle_t *child;
3623         int ret = 0;
3624
3625         if (get_dependents(zhp->zfs_hdl, allowrecursion, zhp->zfs_name,
3626             &dependents, &count) != 0)
3627                 return (-1);
3628
3629         for (i = 0; i < count; i++) {
3630                 if ((child = make_dataset_handle(zhp->zfs_hdl,
3631                     dependents[i])) == NULL)
3632                         continue;
3633
3634                 if ((ret = func(child, data)) != 0)
3635                         break;
3636         }
3637
3638         for (i = 0; i < count; i++)
3639                 free(dependents[i]);
3640         free(dependents);
3641
3642         return (ret);
3643 }
3644
3645 /*
3646  * Renames the given dataset.
3647  */
3648 int
3649 zfs_rename(zfs_handle_t *zhp, const char *target, boolean_t recursive)
3650 {
3651         int ret;
3652         zfs_cmd_t zc = { "\0", "\0", "\0", "\0", 0 };
3653         char *delim;
3654         prop_changelist_t *cl = NULL;
3655         zfs_handle_t *zhrp = NULL;
3656         char *parentname = NULL;
3657         char parent[ZFS_MAXNAMELEN];
3658         libzfs_handle_t *hdl = zhp->zfs_hdl;
3659         char errbuf[1024];
3660
3661         /* if we have the same exact name, just return success */
3662         if (strcmp(zhp->zfs_name, target) == 0)
3663                 return (0);
3664
3665         (void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
3666             "cannot rename to '%s'"), target);
3667
3668         /*
3669          * Make sure the target name is valid
3670          */
3671         if (zhp->zfs_type == ZFS_TYPE_SNAPSHOT) {
3672                 if ((strchr(target, '@') == NULL) ||
3673                     *target == '@') {
3674                         /*
3675                          * Snapshot target name is abbreviated,
3676                          * reconstruct full dataset name
3677                          */
3678                         (void) strlcpy(parent, zhp->zfs_name,
3679                             sizeof (parent));
3680                         delim = strchr(parent, '@');
3681                         if (strchr(target, '@') == NULL)
3682                                 *(++delim) = '\0';
3683                         else
3684                                 *delim = '\0';
3685                         (void) strlcat(parent, target, sizeof (parent));
3686                         target = parent;
3687                 } else {
3688                         /*
3689                          * Make sure we're renaming within the same dataset.
3690                          */
3691                         delim = strchr(target, '@');
3692                         if (strncmp(zhp->zfs_name, target, delim - target)
3693                             != 0 || zhp->zfs_name[delim - target] != '@') {
3694                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3695                                     "snapshots must be part of same "
3696                                     "dataset"));
3697                                 return (zfs_error(hdl, EZFS_CROSSTARGET,
3698                                     errbuf));
3699                         }
3700                 }
3701                 if (!zfs_validate_name(hdl, target, zhp->zfs_type, B_TRUE))
3702                         return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
3703         } else {
3704                 if (recursive) {
3705                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3706                             "recursive rename must be a snapshot"));
3707                         return (zfs_error(hdl, EZFS_BADTYPE, errbuf));
3708                 }
3709
3710                 if (!zfs_validate_name(hdl, target, zhp->zfs_type, B_TRUE))
3711                         return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
3712
3713                 /* validate parents */
3714                 if (check_parents(hdl, target, NULL, B_FALSE, NULL) != 0)
3715                         return (-1);
3716
3717                 /* make sure we're in the same pool */
3718                 verify((delim = strchr(target, '/')) != NULL);
3719                 if (strncmp(zhp->zfs_name, target, delim - target) != 0 ||
3720                     zhp->zfs_name[delim - target] != '/') {
3721                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3722                             "datasets must be within same pool"));
3723                         return (zfs_error(hdl, EZFS_CROSSTARGET, errbuf));
3724                 }
3725
3726                 /* new name cannot be a child of the current dataset name */
3727                 if (is_descendant(zhp->zfs_name, target)) {
3728                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3729                             "New dataset name cannot be a descendant of "
3730                             "current dataset name"));
3731                         return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
3732                 }
3733         }
3734
3735         (void) snprintf(errbuf, sizeof (errbuf),
3736             dgettext(TEXT_DOMAIN, "cannot rename '%s'"), zhp->zfs_name);
3737
3738         if (getzoneid() == GLOBAL_ZONEID &&
3739             zfs_prop_get_int(zhp, ZFS_PROP_ZONED)) {
3740                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3741                     "dataset is used in a non-global zone"));
3742                 return (zfs_error(hdl, EZFS_ZONED, errbuf));
3743         }
3744
3745         if (recursive) {
3746                 struct destroydata dd;
3747
3748                 parentname = zfs_strdup(zhp->zfs_hdl, zhp->zfs_name);
3749                 if (parentname == NULL) {
3750                         ret = -1;
3751                         goto error;
3752                 }
3753                 delim = strchr(parentname, '@');
3754                 *delim = '\0';
3755                 zhrp = zfs_open(zhp->zfs_hdl, parentname, ZFS_TYPE_DATASET);
3756                 if (zhrp == NULL) {
3757                         ret = -1;
3758                         goto error;
3759                 }
3760
3761                 dd.snapname = delim + 1;
3762                 dd.gotone = B_FALSE;
3763                 dd.closezhp = B_TRUE;
3764
3765                 /* We remove any zvol links prior to renaming them */
3766                 ret = zfs_iter_filesystems(zhrp, zfs_check_snap_cb, &dd);
3767                 if (ret) {
3768                         goto error;
3769                 }
3770         } else {
3771                 if ((cl = changelist_gather(zhp, ZFS_PROP_NAME, 0, 0)) == NULL)
3772                         return (-1);
3773
3774                 if (changelist_haszonedchild(cl)) {
3775                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3776                             "child dataset with inherited mountpoint is used "
3777                             "in a non-global zone"));
3778                         (void) zfs_error(hdl, EZFS_ZONED, errbuf);
3779                         ret = -1;
3780                         goto error;
3781                 }
3782
3783                 if ((ret = changelist_prefix(cl)) != 0)
3784                         goto error;
3785         }
3786
3787         if (ZFS_IS_VOLUME(zhp))
3788                 zc.zc_objset_type = DMU_OST_ZVOL;
3789         else
3790                 zc.zc_objset_type = DMU_OST_ZFS;
3791
3792         (void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
3793         (void) strlcpy(zc.zc_value, target, sizeof (zc.zc_value));
3794
3795         zc.zc_cookie = recursive;
3796
3797         if ((ret = zfs_ioctl(zhp->zfs_hdl, ZFS_IOC_RENAME, &zc)) != 0) {
3798                 /*
3799                  * if it was recursive, the one that actually failed will
3800                  * be in zc.zc_name
3801                  */
3802                 (void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
3803                     "cannot rename '%s'"), zc.zc_name);
3804
3805                 if (recursive && errno == EEXIST) {
3806                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3807                             "a child dataset already has a snapshot "
3808                             "with the new name"));
3809                         (void) zfs_error(hdl, EZFS_EXISTS, errbuf);
3810                 } else {
3811                         (void) zfs_standard_error(zhp->zfs_hdl, errno, errbuf);
3812                 }
3813
3814                 /*
3815                  * On failure, we still want to remount any filesystems that
3816                  * were previously mounted, so we don't alter the system state.
3817                  */
3818                 if (recursive) {
3819                         struct createdata cd;
3820
3821                         /* only create links for datasets that had existed */
3822                         cd.cd_snapname = delim + 1;
3823                         cd.cd_ifexists = B_TRUE;
3824                         (void) zfs_iter_filesystems(zhrp, zfs_create_link_cb,
3825                             &cd);
3826                 } else {
3827                         (void) changelist_postfix(cl);
3828                 }
3829         } else {
3830                 if (recursive) {
3831                         struct createdata cd;
3832
3833                         /* only create links for datasets that had existed */
3834                         cd.cd_snapname = strchr(target, '@') + 1;
3835                         cd.cd_ifexists = B_TRUE;
3836                         ret = zfs_iter_filesystems(zhrp, zfs_create_link_cb,
3837                             &cd);
3838                 } else {
3839                         changelist_rename(cl, zfs_get_name(zhp), target);
3840                         ret = changelist_postfix(cl);
3841                 }
3842         }
3843
3844 error:
3845         if (parentname) {
3846                 free(parentname);
3847         }
3848         if (zhrp) {
3849                 zfs_close(zhrp);
3850         }
3851         if (cl) {
3852                 changelist_free(cl);
3853         }
3854         return (ret);
3855 }
3856
3857 /*
3858  * Given a zvol dataset, issue the ioctl to create the appropriate minor node,
3859  * and wait briefly for udev to create the /dev link.
3860  */
3861 int
3862 zvol_create_link(libzfs_handle_t *hdl, const char *dataset)
3863 {
3864         return (zvol_create_link_common(hdl, dataset, B_FALSE));
3865 }
3866
3867 static int
3868 zvol_create_link_common(libzfs_handle_t *hdl, const char *dataset, int ifexists)
3869 {
3870         zfs_cmd_t zc = { "\0", "\0", "\0", "\0", 0 };
3871         char path[MAXPATHLEN];
3872         int error;
3873
3874         (void) strlcpy(zc.zc_name, dataset, sizeof (zc.zc_name));
3875
3876         /*
3877          * Issue the appropriate ioctl.
3878          */
3879         if (ioctl(hdl->libzfs_fd, ZFS_IOC_CREATE_MINOR, &zc) != 0) {
3880                 switch (errno) {
3881                 case EEXIST:
3882                         /*
3883                          * Silently ignore the case where the link already
3884                          * exists.  This allows 'zfs volinit' to be run multiple
3885                          * times without errors.
3886                          */
3887                         return (0);
3888
3889                 case ENOENT:
3890                         /*
3891                          * Dataset does not exist in the kernel.  If we
3892                          * don't care (see zfs_rename), then ignore the
3893                          * error quietly.
3894                          */
3895                         if (ifexists) {
3896                                 return (0);
3897                         }
3898
3899                         /* FALLTHROUGH */
3900
3901                 default:
3902                         return (zfs_standard_error_fmt(hdl, errno,
3903                             dgettext(TEXT_DOMAIN, "cannot create device links "
3904                             "for '%s'"), dataset));
3905                 }
3906         }
3907
3908         /*
3909          * Wait up to 10 seconds for udev to create the device.
3910          */
3911         (void) snprintf(path, sizeof (path), "%s/%s", ZVOL_DIR, dataset);
3912         error = zpool_label_disk_wait(path, 10000);
3913         if (error)
3914                 (void) printf(gettext("%s may not be immediately "
3915                     "available\n"), path);
3916
3917         return (0);
3918 }
3919
3920 /*
3921  * Remove a minor node for the given zvol and the associated /dev links.
3922  */
3923 int
3924 zvol_remove_link(libzfs_handle_t *hdl, const char *dataset)
3925 {
3926         zfs_cmd_t zc = { "\0", "\0", "\0", "\0", 0 };
3927
3928         (void) strlcpy(zc.zc_name, dataset, sizeof (zc.zc_name));
3929
3930         if (ioctl(hdl->libzfs_fd, ZFS_IOC_REMOVE_MINOR, &zc) != 0) {
3931                 switch (errno) {
3932                 case ENXIO:
3933                         /*
3934                          * Silently ignore the case where the link no longer
3935                          * exists, so that 'zfs volfini' can be run multiple
3936                          * times without errors.
3937                          */
3938                         return (0);
3939
3940                 default:
3941                         return (zfs_standard_error_fmt(hdl, errno,
3942                             dgettext(TEXT_DOMAIN, "cannot remove device "
3943                             "links for '%s'"), dataset));
3944                 }
3945         }
3946
3947         return (0);
3948 }
3949
3950 nvlist_t *
3951 zfs_get_user_props(zfs_handle_t *zhp)
3952 {
3953         return (zhp->zfs_user_props);
3954 }
3955
3956 /*
3957  * This function is used by 'zfs list' to determine the exact set of columns to
3958  * display, and their maximum widths.  This does two main things:
3959  *
3960  *      - If this is a list of all properties, then expand the list to include
3961  *        all native properties, and set a flag so that for each dataset we look
3962  *        for new unique user properties and add them to the list.
3963  *
3964  *      - For non fixed-width properties, keep track of the maximum width seen
3965  *        so that we can size the column appropriately. If the user has
3966  *        requested received property values, we also need to compute the width
3967  *        of the RECEIVED column.
3968  */
3969 int
3970 zfs_expand_proplist(zfs_handle_t *zhp, zprop_list_t **plp, boolean_t received)
3971 {
3972         libzfs_handle_t *hdl = zhp->zfs_hdl;
3973         zprop_list_t *entry;
3974         zprop_list_t **last, **start;
3975         nvlist_t *userprops, *propval;
3976         nvpair_t *elem;
3977         char *strval;
3978         char buf[ZFS_MAXPROPLEN];
3979
3980         if (zprop_expand_list(hdl, plp, ZFS_TYPE_DATASET) != 0)
3981                 return (-1);
3982
3983         userprops = zfs_get_user_props(zhp);
3984
3985         entry = *plp;
3986         if (entry->pl_all && nvlist_next_nvpair(userprops, NULL) != NULL) {
3987                 /*
3988                  * Go through and add any user properties as necessary.  We
3989                  * start by incrementing our list pointer to the first
3990                  * non-native property.
3991                  */
3992                 start = plp;
3993                 while (*start != NULL) {
3994                         if ((*start)->pl_prop == ZPROP_INVAL)
3995                                 break;
3996                         start = &(*start)->pl_next;
3997                 }
3998
3999                 elem = NULL;
4000                 while ((elem = nvlist_next_nvpair(userprops, elem)) != NULL) {
4001                         /*
4002                          * See if we've already found this property in our list.
4003                          */
4004                         for (last = start; *last != NULL;
4005                             last = &(*last)->pl_next) {
4006                                 if (strcmp((*last)->pl_user_prop,
4007                                     nvpair_name(elem)) == 0)
4008                                         break;
4009                         }
4010
4011                         if (*last == NULL) {
4012                                 if ((entry = zfs_alloc(hdl,
4013                                     sizeof (zprop_list_t))) == NULL ||
4014                                     ((entry->pl_user_prop = zfs_strdup(hdl,
4015                                     nvpair_name(elem)))) == NULL) {
4016                                         free(entry);
4017                                         return (-1);
4018                                 }
4019
4020                                 entry->pl_prop = ZPROP_INVAL;
4021                                 entry->pl_width = strlen(nvpair_name(elem));
4022                                 entry->pl_all = B_TRUE;
4023                                 *last = entry;
4024                         }
4025                 }
4026         }
4027
4028         /*
4029          * Now go through and check the width of any non-fixed columns
4030          */
4031         for (entry = *plp; entry != NULL; entry = entry->pl_next) {
4032                 if (entry->pl_fixed)
4033                         continue;
4034
4035                 if (entry->pl_prop != ZPROP_INVAL) {
4036                         if (zfs_prop_get(zhp, entry->pl_prop,
4037                             buf, sizeof (buf), NULL, NULL, 0, B_FALSE) == 0) {
4038                                 if (strlen(buf) > entry->pl_width)
4039                                         entry->pl_width = strlen(buf);
4040                         }
4041                         if (received && zfs_prop_get_recvd(zhp,
4042                             zfs_prop_to_name(entry->pl_prop),
4043                             buf, sizeof (buf), B_FALSE) == 0)
4044                                 if (strlen(buf) > entry->pl_recvd_width)
4045                                         entry->pl_recvd_width = strlen(buf);
4046                 } else {
4047                         if (nvlist_lookup_nvlist(userprops, entry->pl_user_prop,
4048                             &propval) == 0) {
4049                                 verify(nvlist_lookup_string(propval,
4050                                     ZPROP_VALUE, &strval) == 0);
4051                                 if (strlen(strval) > entry->pl_width)
4052                                         entry->pl_width = strlen(strval);
4053                         }
4054                         if (received && zfs_prop_get_recvd(zhp,
4055                             entry->pl_user_prop,
4056                             buf, sizeof (buf), B_FALSE) == 0)
4057                                 if (strlen(buf) > entry->pl_recvd_width)
4058                                         entry->pl_recvd_width = strlen(buf);
4059                 }
4060         }
4061
4062         return (0);
4063 }
4064
4065 void
4066 zfs_prune_proplist(zfs_handle_t *zhp, uint8_t *props)
4067 {
4068         nvpair_t *curr;
4069
4070         /*
4071          * Keep a reference to the props-table against which we prune the
4072          * properties.
4073          */
4074         zhp->zfs_props_table = props;
4075
4076         curr = nvlist_next_nvpair(zhp->zfs_props, NULL);
4077
4078         while (curr) {
4079                 zfs_prop_t zfs_prop = zfs_name_to_prop(nvpair_name(curr));
4080                 nvpair_t *next = nvlist_next_nvpair(zhp->zfs_props, curr);
4081
4082                 /*
4083                  * User properties will result in ZPROP_INVAL, and since we
4084                  * only know how to prune standard ZFS properties, we always
4085                  * leave these in the list.  This can also happen if we
4086                  * encounter an unknown DSL property (when running older
4087                  * software, for example).
4088                  */
4089                 if (zfs_prop != ZPROP_INVAL && props[zfs_prop] == B_FALSE)
4090                         (void) nvlist_remove(zhp->zfs_props,
4091                             nvpair_name(curr), nvpair_type(curr));
4092                 curr = next;
4093         }
4094 }
4095
4096 static int
4097 zfs_smb_acl_mgmt(libzfs_handle_t *hdl, char *dataset, char *path,
4098     zfs_smb_acl_op_t cmd, char *resource1, char *resource2)
4099 {
4100         zfs_cmd_t zc = { "\0", "\0", "\0", "\0", 0 };
4101         nvlist_t *nvlist = NULL;
4102         int error;
4103
4104         (void) strlcpy(zc.zc_name, dataset, sizeof (zc.zc_name));
4105         (void) strlcpy(zc.zc_value, path, sizeof (zc.zc_value));
4106         zc.zc_cookie = (uint64_t)cmd;
4107
4108         if (cmd == ZFS_SMB_ACL_RENAME) {
4109                 if (nvlist_alloc(&nvlist, NV_UNIQUE_NAME, 0) != 0) {
4110                         (void) no_memory(hdl);
4111                         return (-1);
4112                 }
4113         }
4114
4115         switch (cmd) {
4116         case ZFS_SMB_ACL_ADD:
4117         case ZFS_SMB_ACL_REMOVE:
4118                 (void) strlcpy(zc.zc_string, resource1, sizeof (zc.zc_string));
4119                 break;
4120         case ZFS_SMB_ACL_RENAME:
4121                 if (nvlist_add_string(nvlist, ZFS_SMB_ACL_SRC,
4122                     resource1) != 0) {
4123                                 (void) no_memory(hdl);
4124                                 return (-1);
4125                 }
4126                 if (nvlist_add_string(nvlist, ZFS_SMB_ACL_TARGET,
4127                     resource2) != 0) {
4128                                 (void) no_memory(hdl);
4129                                 return (-1);
4130                 }
4131                 if (zcmd_write_src_nvlist(hdl, &zc, nvlist) != 0) {
4132                         nvlist_free(nvlist);
4133                         return (-1);
4134                 }
4135                 break;
4136         case ZFS_SMB_ACL_PURGE:
4137                 break;
4138         default:
4139                 return (-1);
4140         }
4141         error = ioctl(hdl->libzfs_fd, ZFS_IOC_SMB_ACL, &zc);
4142         if (nvlist)
4143                 nvlist_free(nvlist);
4144         return (error);
4145 }
4146
4147 int
4148 zfs_smb_acl_add(libzfs_handle_t *hdl, char *dataset,
4149     char *path, char *resource)
4150 {
4151         return (zfs_smb_acl_mgmt(hdl, dataset, path, ZFS_SMB_ACL_ADD,
4152             resource, NULL));
4153 }
4154
4155 int
4156 zfs_smb_acl_remove(libzfs_handle_t *hdl, char *dataset,
4157     char *path, char *resource)
4158 {
4159         return (zfs_smb_acl_mgmt(hdl, dataset, path, ZFS_SMB_ACL_REMOVE,
4160             resource, NULL));
4161 }
4162
4163 int
4164 zfs_smb_acl_purge(libzfs_handle_t *hdl, char *dataset, char *path)
4165 {
4166         return (zfs_smb_acl_mgmt(hdl, dataset, path, ZFS_SMB_ACL_PURGE,
4167             NULL, NULL));
4168 }
4169
4170 int
4171 zfs_smb_acl_rename(libzfs_handle_t *hdl, char *dataset, char *path,
4172     char *oldname, char *newname)
4173 {
4174         return (zfs_smb_acl_mgmt(hdl, dataset, path, ZFS_SMB_ACL_RENAME,
4175             oldname, newname));
4176 }
4177
4178 int
4179 zfs_userspace(zfs_handle_t *zhp, zfs_userquota_prop_t type,
4180     zfs_userspace_cb_t func, void *arg)
4181 {
4182         zfs_cmd_t zc = { "\0", "\0", "\0", "\0", 0 };
4183         int error;
4184         zfs_useracct_t buf[100];
4185
4186         (void) strncpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
4187
4188         zc.zc_objset_type = type;
4189         zc.zc_nvlist_dst = (uintptr_t)buf;
4190
4191         /* CONSTCOND */
4192         while (1) {
4193                 zfs_useracct_t *zua = buf;
4194
4195                 zc.zc_nvlist_dst_size = sizeof (buf);
4196                 error = ioctl(zhp->zfs_hdl->libzfs_fd,
4197                     ZFS_IOC_USERSPACE_MANY, &zc);
4198                 if (error || zc.zc_nvlist_dst_size == 0)
4199                         break;
4200
4201                 while (zc.zc_nvlist_dst_size > 0) {
4202                         error = func(arg, zua->zu_domain, zua->zu_rid,
4203                             zua->zu_space);
4204                         if (error != 0)
4205                                 return (error);
4206                         zua++;
4207                         zc.zc_nvlist_dst_size -= sizeof (zfs_useracct_t);
4208                 }
4209         }
4210
4211         return (error);
4212 }
4213
4214 int
4215 zfs_hold(zfs_handle_t *zhp, const char *snapname, const char *tag,
4216     boolean_t recursive, boolean_t temphold, boolean_t enoent_ok,
4217     int cleanup_fd, uint64_t dsobj, uint64_t createtxg)
4218 {
4219         zfs_cmd_t zc = { "\0", "\0", "\0", "\0", 0 };
4220         libzfs_handle_t *hdl = zhp->zfs_hdl;
4221
4222         ASSERT(!recursive || dsobj == 0);
4223
4224         (void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
4225         (void) strlcpy(zc.zc_value, snapname, sizeof (zc.zc_value));
4226         if (strlcpy(zc.zc_string, tag, sizeof (zc.zc_string))
4227             >= sizeof (zc.zc_string))
4228                 return (zfs_error(hdl, EZFS_TAGTOOLONG, tag));
4229         zc.zc_cookie = recursive;
4230         zc.zc_temphold = temphold;
4231         zc.zc_cleanup_fd = cleanup_fd;
4232         zc.zc_sendobj = dsobj;
4233         zc.zc_createtxg = createtxg;
4234
4235         if (zfs_ioctl(hdl, ZFS_IOC_HOLD, &zc) != 0) {
4236                 char errbuf[ZFS_MAXNAMELEN+32];
4237
4238                 /*
4239                  * if it was recursive, the one that actually failed will be in
4240                  * zc.zc_name.
4241                  */
4242                 (void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
4243                     "cannot hold '%s@%s'"), zc.zc_name, snapname);
4244                 switch (errno) {
4245                 case E2BIG:
4246                         /*
4247                          * Temporary tags wind up having the ds object id
4248                          * prepended. So even if we passed the length check
4249                          * above, it's still possible for the tag to wind
4250                          * up being slightly too long.
4251                          */
4252                         return (zfs_error(hdl, EZFS_TAGTOOLONG, errbuf));
4253                 case ENOTSUP:
4254                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4255                             "pool must be upgraded"));
4256                         return (zfs_error(hdl, EZFS_BADVERSION, errbuf));
4257                 case EINVAL:
4258                         return (zfs_error(hdl, EZFS_BADTYPE, errbuf));
4259                 case EEXIST:
4260                         return (zfs_error(hdl, EZFS_REFTAG_HOLD, errbuf));
4261                 case ENOENT:
4262                         if (enoent_ok)
4263                                 return (ENOENT);
4264                         /* FALLTHROUGH */
4265                 default:
4266                         return (zfs_standard_error_fmt(hdl, errno, errbuf));
4267                 }
4268         }
4269
4270         return (0);
4271 }
4272
4273 int
4274 zfs_release(zfs_handle_t *zhp, const char *snapname, const char *tag,
4275     boolean_t recursive)
4276 {
4277         zfs_cmd_t zc = { "\0", "\0", "\0", "\0", 0 };
4278         libzfs_handle_t *hdl = zhp->zfs_hdl;
4279
4280         (void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
4281         (void) strlcpy(zc.zc_value, snapname, sizeof (zc.zc_value));
4282         if (strlcpy(zc.zc_string, tag, sizeof (zc.zc_string))
4283             >= sizeof (zc.zc_string))
4284                 return (zfs_error(hdl, EZFS_TAGTOOLONG, tag));
4285         zc.zc_cookie = recursive;
4286
4287         if (zfs_ioctl(hdl, ZFS_IOC_RELEASE, &zc) != 0) {
4288                 char errbuf[ZFS_MAXNAMELEN+32];
4289
4290                 /*
4291                  * if it was recursive, the one that actually failed will be in
4292                  * zc.zc_name.
4293                  */
4294                 (void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
4295                     "cannot release '%s' from '%s@%s'"), tag, zc.zc_name,
4296                     snapname);
4297                 switch (errno) {
4298                 case ESRCH:
4299                         return (zfs_error(hdl, EZFS_REFTAG_RELE, errbuf));
4300                 case ENOTSUP:
4301                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4302                             "pool must be upgraded"));
4303                         return (zfs_error(hdl, EZFS_BADVERSION, errbuf));
4304                 case EINVAL:
4305                         return (zfs_error(hdl, EZFS_BADTYPE, errbuf));
4306                 default:
4307                         return (zfs_standard_error_fmt(hdl, errno, errbuf));
4308                 }
4309         }
4310
4311         return (0);
4312 }
4313
4314 uint64_t
4315 zvol_volsize_to_reservation(uint64_t volsize, nvlist_t *props)
4316 {
4317         uint64_t numdb;
4318         uint64_t nblocks, volblocksize;
4319         int ncopies;
4320         char *strval;
4321
4322         if (nvlist_lookup_string(props,
4323             zfs_prop_to_name(ZFS_PROP_COPIES), &strval) == 0)
4324                 ncopies = atoi(strval);
4325         else
4326                 ncopies = 1;
4327         if (nvlist_lookup_uint64(props,
4328             zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE),
4329             &volblocksize) != 0)
4330                 volblocksize = ZVOL_DEFAULT_BLOCKSIZE;
4331         nblocks = volsize/volblocksize;
4332         /* start with metadnode L0-L6 */
4333         numdb = 7;
4334         /* calculate number of indirects */
4335         while (nblocks > 1) {
4336                 nblocks += DNODES_PER_LEVEL - 1;
4337                 nblocks /= DNODES_PER_LEVEL;
4338                 numdb += nblocks;
4339         }
4340         numdb *= MIN(SPA_DVAS_PER_BP, ncopies + 1);
4341         volsize *= ncopies;
4342         /*
4343          * this is exactly DN_MAX_INDBLKSHIFT when metadata isn't
4344          * compressed, but in practice they compress down to about
4345          * 1100 bytes
4346          */
4347         numdb *= 1ULL << DN_MAX_INDBLKSHIFT;
4348         volsize += numdb;
4349         return (volsize);
4350 }