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