]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - cddl/contrib/opensolaris/lib/libzfs_core/common/libzfs_core.c
Merge ACPICA 20170929.
[FreeBSD/FreeBSD.git] / cddl / contrib / opensolaris / lib / libzfs_core / common / libzfs_core.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) 2012, 2014 by Delphix. All rights reserved.
24  * Copyright (c) 2013 Steven Hartland. All rights reserved.
25  * Copyright (c) 2014 Integros [integros.com]
26  * Copyright 2017 RackTop Systems.
27  */
28
29 /*
30  * LibZFS_Core (lzc) is intended to replace most functionality in libzfs.
31  * It has the following characteristics:
32  *
33  *  - Thread Safe.  libzfs_core is accessible concurrently from multiple
34  *  threads.  This is accomplished primarily by avoiding global data
35  *  (e.g. caching).  Since it's thread-safe, there is no reason for a
36  *  process to have multiple libzfs "instances".  Therefore, we store
37  *  our few pieces of data (e.g. the file descriptor) in global
38  *  variables.  The fd is reference-counted so that the libzfs_core
39  *  library can be "initialized" multiple times (e.g. by different
40  *  consumers within the same process).
41  *
42  *  - Committed Interface.  The libzfs_core interface will be committed,
43  *  therefore consumers can compile against it and be confident that
44  *  their code will continue to work on future releases of this code.
45  *  Currently, the interface is Evolving (not Committed), but we intend
46  *  to commit to it once it is more complete and we determine that it
47  *  meets the needs of all consumers.
48  *
49  *  - Programatic Error Handling.  libzfs_core communicates errors with
50  *  defined error numbers, and doesn't print anything to stdout/stderr.
51  *
52  *  - Thin Layer.  libzfs_core is a thin layer, marshaling arguments
53  *  to/from the kernel ioctls.  There is generally a 1:1 correspondence
54  *  between libzfs_core functions and ioctls to /dev/zfs.
55  *
56  *  - Clear Atomicity.  Because libzfs_core functions are generally 1:1
57  *  with kernel ioctls, and kernel ioctls are general atomic, each
58  *  libzfs_core function is atomic.  For example, creating multiple
59  *  snapshots with a single call to lzc_snapshot() is atomic -- it
60  *  can't fail with only some of the requested snapshots created, even
61  *  in the event of power loss or system crash.
62  *
63  *  - Continued libzfs Support.  Some higher-level operations (e.g.
64  *  support for "zfs send -R") are too complicated to fit the scope of
65  *  libzfs_core.  This functionality will continue to live in libzfs.
66  *  Where appropriate, libzfs will use the underlying atomic operations
67  *  of libzfs_core.  For example, libzfs may implement "zfs send -R |
68  *  zfs receive" by using individual "send one snapshot", rename,
69  *  destroy, and "receive one snapshot" operations in libzfs_core.
70  *  /sbin/zfs and /zbin/zpool will link with both libzfs and
71  *  libzfs_core.  Other consumers should aim to use only libzfs_core,
72  *  since that will be the supported, stable interface going forwards.
73  */
74
75 #define _IN_LIBZFS_CORE_
76
77 #include <libzfs_core.h>
78 #include <ctype.h>
79 #include <unistd.h>
80 #include <stdlib.h>
81 #include <string.h>
82 #include <errno.h>
83 #include <fcntl.h>
84 #include <pthread.h>
85 #include <sys/nvpair.h>
86 #include <sys/param.h>
87 #include <sys/types.h>
88 #include <sys/stat.h>
89 #include <sys/zfs_ioctl.h>
90 #include "libzfs_core_compat.h"
91 #include "libzfs_compat.h"
92
93 #ifdef __FreeBSD__
94 extern int zfs_ioctl_version;
95 #endif
96
97 static int g_fd;
98 static pthread_mutex_t g_lock = PTHREAD_MUTEX_INITIALIZER;
99 static int g_refcount;
100
101 int
102 libzfs_core_init(void)
103 {
104         (void) pthread_mutex_lock(&g_lock);
105         if (g_refcount == 0) {
106                 g_fd = open("/dev/zfs", O_RDWR);
107                 if (g_fd < 0) {
108                         (void) pthread_mutex_unlock(&g_lock);
109                         return (errno);
110                 }
111         }
112         g_refcount++;
113         (void) pthread_mutex_unlock(&g_lock);
114
115         return (0);
116 }
117
118 void
119 libzfs_core_fini(void)
120 {
121         (void) pthread_mutex_lock(&g_lock);
122         ASSERT3S(g_refcount, >, 0);
123         g_refcount--;
124         if (g_refcount == 0)
125                 (void) close(g_fd);
126         (void) pthread_mutex_unlock(&g_lock);
127 }
128
129 static int
130 lzc_ioctl(zfs_ioc_t ioc, const char *name,
131     nvlist_t *source, nvlist_t **resultp)
132 {
133         zfs_cmd_t zc = { 0 };
134         int error = 0;
135         char *packed;
136 #ifdef __FreeBSD__
137         nvlist_t *oldsource;
138 #endif
139         size_t size;
140
141         ASSERT3S(g_refcount, >, 0);
142
143         (void) strlcpy(zc.zc_name, name, sizeof (zc.zc_name));
144
145 #ifdef __FreeBSD__
146         if (zfs_ioctl_version == ZFS_IOCVER_UNDEF)
147                 zfs_ioctl_version = get_zfs_ioctl_version();
148
149         if (zfs_ioctl_version < ZFS_IOCVER_LZC) {
150                 oldsource = source;
151                 error = lzc_compat_pre(&zc, &ioc, &source);
152                 if (error)
153                         return (error);
154         }
155 #endif
156
157         packed = fnvlist_pack(source, &size);
158         zc.zc_nvlist_src = (uint64_t)(uintptr_t)packed;
159         zc.zc_nvlist_src_size = size;
160
161         if (resultp != NULL) {
162                 *resultp = NULL;
163                 zc.zc_nvlist_dst_size = MAX(size * 2, 128 * 1024);
164                 zc.zc_nvlist_dst = (uint64_t)(uintptr_t)
165                     malloc(zc.zc_nvlist_dst_size);
166 #ifdef illumos
167                 if (zc.zc_nvlist_dst == NULL) {
168 #else
169                 if (zc.zc_nvlist_dst == 0) {
170 #endif
171                         error = ENOMEM;
172                         goto out;
173                 }
174         }
175
176         while (ioctl(g_fd, ioc, &zc) != 0) {
177                 if (errno == ENOMEM && resultp != NULL) {
178                         free((void *)(uintptr_t)zc.zc_nvlist_dst);
179                         zc.zc_nvlist_dst_size *= 2;
180                         zc.zc_nvlist_dst = (uint64_t)(uintptr_t)
181                             malloc(zc.zc_nvlist_dst_size);
182 #ifdef illumos
183                         if (zc.zc_nvlist_dst == NULL) {
184 #else
185                         if (zc.zc_nvlist_dst == 0) {
186 #endif
187                                 error = ENOMEM;
188                                 goto out;
189                         }
190                 } else {
191                         error = errno;
192                         break;
193                 }
194         }
195
196 #ifdef __FreeBSD__
197         if (zfs_ioctl_version < ZFS_IOCVER_LZC)
198                 lzc_compat_post(&zc, ioc);
199 #endif
200         if (zc.zc_nvlist_dst_filled) {
201                 *resultp = fnvlist_unpack((void *)(uintptr_t)zc.zc_nvlist_dst,
202                     zc.zc_nvlist_dst_size);
203         }
204 #ifdef __FreeBSD__
205         if (zfs_ioctl_version < ZFS_IOCVER_LZC)
206                 lzc_compat_outnvl(&zc, ioc, resultp);
207 #endif
208 out:
209 #ifdef __FreeBSD__
210         if (zfs_ioctl_version < ZFS_IOCVER_LZC) {
211                 if (source != oldsource)
212                         nvlist_free(source);
213                 source = oldsource;
214         }
215 #endif
216         fnvlist_pack_free(packed, size);
217         free((void *)(uintptr_t)zc.zc_nvlist_dst);
218         return (error);
219 }
220
221 int
222 lzc_create(const char *fsname, enum lzc_dataset_type type, nvlist_t *props)
223 {
224         int error;
225         nvlist_t *args = fnvlist_alloc();
226         fnvlist_add_int32(args, "type", (dmu_objset_type_t)type);
227         if (props != NULL)
228                 fnvlist_add_nvlist(args, "props", props);
229         error = lzc_ioctl(ZFS_IOC_CREATE, fsname, args, NULL);
230         nvlist_free(args);
231         return (error);
232 }
233
234 int
235 lzc_clone(const char *fsname, const char *origin,
236     nvlist_t *props)
237 {
238         int error;
239         nvlist_t *args = fnvlist_alloc();
240         fnvlist_add_string(args, "origin", origin);
241         if (props != NULL)
242                 fnvlist_add_nvlist(args, "props", props);
243         error = lzc_ioctl(ZFS_IOC_CLONE, fsname, args, NULL);
244         nvlist_free(args);
245         return (error);
246 }
247
248 int
249 lzc_promote(const char *fsname, char *snapnamebuf, int snapnamelen)
250 {
251         /*
252          * The promote ioctl is still legacy, so we need to construct our
253          * own zfs_cmd_t rather than using lzc_ioctl().
254          */
255         zfs_cmd_t zc = { 0 };
256
257         ASSERT3S(g_refcount, >, 0);
258         VERIFY3S(g_fd, !=, -1);
259
260         (void) strlcpy(zc.zc_name, fsname, sizeof (zc.zc_name));
261         if (ioctl(g_fd, ZFS_IOC_PROMOTE, &zc) != 0) {
262                 int error = errno;
263                 if (error == EEXIST && snapnamebuf != NULL)
264                         (void) strlcpy(snapnamebuf, zc.zc_string, snapnamelen);
265                 return (error);
266         }
267         return (0);
268 }
269
270 /*
271  * Creates snapshots.
272  *
273  * The keys in the snaps nvlist are the snapshots to be created.
274  * They must all be in the same pool.
275  *
276  * The props nvlist is properties to set.  Currently only user properties
277  * are supported.  { user:prop_name -> string value }
278  *
279  * The returned results nvlist will have an entry for each snapshot that failed.
280  * The value will be the (int32) error code.
281  *
282  * The return value will be 0 if all snapshots were created, otherwise it will
283  * be the errno of a (unspecified) snapshot that failed.
284  */
285 int
286 lzc_snapshot(nvlist_t *snaps, nvlist_t *props, nvlist_t **errlist)
287 {
288         nvpair_t *elem;
289         nvlist_t *args;
290         int error;
291         char pool[ZFS_MAX_DATASET_NAME_LEN];
292
293         *errlist = NULL;
294
295         /* determine the pool name */
296         elem = nvlist_next_nvpair(snaps, NULL);
297         if (elem == NULL)
298                 return (0);
299         (void) strlcpy(pool, nvpair_name(elem), sizeof (pool));
300         pool[strcspn(pool, "/@")] = '\0';
301
302         args = fnvlist_alloc();
303         fnvlist_add_nvlist(args, "snaps", snaps);
304         if (props != NULL)
305                 fnvlist_add_nvlist(args, "props", props);
306
307         error = lzc_ioctl(ZFS_IOC_SNAPSHOT, pool, args, errlist);
308         nvlist_free(args);
309
310         return (error);
311 }
312
313 /*
314  * Destroys snapshots.
315  *
316  * The keys in the snaps nvlist are the snapshots to be destroyed.
317  * They must all be in the same pool.
318  *
319  * Snapshots that do not exist will be silently ignored.
320  *
321  * If 'defer' is not set, and a snapshot has user holds or clones, the
322  * destroy operation will fail and none of the snapshots will be
323  * destroyed.
324  *
325  * If 'defer' is set, and a snapshot has user holds or clones, it will be
326  * marked for deferred destruction, and will be destroyed when the last hold
327  * or clone is removed/destroyed.
328  *
329  * The return value will be 0 if all snapshots were destroyed (or marked for
330  * later destruction if 'defer' is set) or didn't exist to begin with.
331  *
332  * Otherwise the return value will be the errno of a (unspecified) snapshot
333  * that failed, no snapshots will be destroyed, and the errlist will have an
334  * entry for each snapshot that failed.  The value in the errlist will be
335  * the (int32) error code.
336  */
337 int
338 lzc_destroy_snaps(nvlist_t *snaps, boolean_t defer, nvlist_t **errlist)
339 {
340         nvpair_t *elem;
341         nvlist_t *args;
342         int error;
343         char pool[ZFS_MAX_DATASET_NAME_LEN];
344
345         /* determine the pool name */
346         elem = nvlist_next_nvpair(snaps, NULL);
347         if (elem == NULL)
348                 return (0);
349         (void) strlcpy(pool, nvpair_name(elem), sizeof (pool));
350         pool[strcspn(pool, "/@")] = '\0';
351
352         args = fnvlist_alloc();
353         fnvlist_add_nvlist(args, "snaps", snaps);
354         if (defer)
355                 fnvlist_add_boolean(args, "defer");
356
357         error = lzc_ioctl(ZFS_IOC_DESTROY_SNAPS, pool, args, errlist);
358         nvlist_free(args);
359
360         return (error);
361 }
362
363 int
364 lzc_snaprange_space(const char *firstsnap, const char *lastsnap,
365     uint64_t *usedp)
366 {
367         nvlist_t *args;
368         nvlist_t *result;
369         int err;
370         char fs[ZFS_MAX_DATASET_NAME_LEN];
371         char *atp;
372
373         /* determine the fs name */
374         (void) strlcpy(fs, firstsnap, sizeof (fs));
375         atp = strchr(fs, '@');
376         if (atp == NULL)
377                 return (EINVAL);
378         *atp = '\0';
379
380         args = fnvlist_alloc();
381         fnvlist_add_string(args, "firstsnap", firstsnap);
382
383         err = lzc_ioctl(ZFS_IOC_SPACE_SNAPS, lastsnap, args, &result);
384         nvlist_free(args);
385         if (err == 0)
386                 *usedp = fnvlist_lookup_uint64(result, "used");
387         fnvlist_free(result);
388
389         return (err);
390 }
391
392 boolean_t
393 lzc_exists(const char *dataset)
394 {
395         /*
396          * The objset_stats ioctl is still legacy, so we need to construct our
397          * own zfs_cmd_t rather than using lzc_ioctl().
398          */
399         zfs_cmd_t zc = { 0 };
400
401         (void) strlcpy(zc.zc_name, dataset, sizeof (zc.zc_name));
402         return (ioctl(g_fd, ZFS_IOC_OBJSET_STATS, &zc) == 0);
403 }
404
405 /*
406  * Create "user holds" on snapshots.  If there is a hold on a snapshot,
407  * the snapshot can not be destroyed.  (However, it can be marked for deletion
408  * by lzc_destroy_snaps(defer=B_TRUE).)
409  *
410  * The keys in the nvlist are snapshot names.
411  * The snapshots must all be in the same pool.
412  * The value is the name of the hold (string type).
413  *
414  * If cleanup_fd is not -1, it must be the result of open("/dev/zfs", O_EXCL).
415  * In this case, when the cleanup_fd is closed (including on process
416  * termination), the holds will be released.  If the system is shut down
417  * uncleanly, the holds will be released when the pool is next opened
418  * or imported.
419  *
420  * Holds for snapshots which don't exist will be skipped and have an entry
421  * added to errlist, but will not cause an overall failure.
422  *
423  * The return value will be 0 if all holds, for snapshots that existed,
424  * were succesfully created.
425  *
426  * Otherwise the return value will be the errno of a (unspecified) hold that
427  * failed and no holds will be created.
428  *
429  * In all cases the errlist will have an entry for each hold that failed
430  * (name = snapshot), with its value being the error code (int32).
431  */
432 int
433 lzc_hold(nvlist_t *holds, int cleanup_fd, nvlist_t **errlist)
434 {
435         char pool[ZFS_MAX_DATASET_NAME_LEN];
436         nvlist_t *args;
437         nvpair_t *elem;
438         int error;
439
440         /* determine the pool name */
441         elem = nvlist_next_nvpair(holds, NULL);
442         if (elem == NULL)
443                 return (0);
444         (void) strlcpy(pool, nvpair_name(elem), sizeof (pool));
445         pool[strcspn(pool, "/@")] = '\0';
446
447         args = fnvlist_alloc();
448         fnvlist_add_nvlist(args, "holds", holds);
449         if (cleanup_fd != -1)
450                 fnvlist_add_int32(args, "cleanup_fd", cleanup_fd);
451
452         error = lzc_ioctl(ZFS_IOC_HOLD, pool, args, errlist);
453         nvlist_free(args);
454         return (error);
455 }
456
457 /*
458  * Release "user holds" on snapshots.  If the snapshot has been marked for
459  * deferred destroy (by lzc_destroy_snaps(defer=B_TRUE)), it does not have
460  * any clones, and all the user holds are removed, then the snapshot will be
461  * destroyed.
462  *
463  * The keys in the nvlist are snapshot names.
464  * The snapshots must all be in the same pool.
465  * The value is a nvlist whose keys are the holds to remove.
466  *
467  * Holds which failed to release because they didn't exist will have an entry
468  * added to errlist, but will not cause an overall failure.
469  *
470  * The return value will be 0 if the nvl holds was empty or all holds that
471  * existed, were successfully removed.
472  *
473  * Otherwise the return value will be the errno of a (unspecified) hold that
474  * failed to release and no holds will be released.
475  *
476  * In all cases the errlist will have an entry for each hold that failed to
477  * to release.
478  */
479 int
480 lzc_release(nvlist_t *holds, nvlist_t **errlist)
481 {
482         char pool[ZFS_MAX_DATASET_NAME_LEN];
483         nvpair_t *elem;
484
485         /* determine the pool name */
486         elem = nvlist_next_nvpair(holds, NULL);
487         if (elem == NULL)
488                 return (0);
489         (void) strlcpy(pool, nvpair_name(elem), sizeof (pool));
490         pool[strcspn(pool, "/@")] = '\0';
491
492         return (lzc_ioctl(ZFS_IOC_RELEASE, pool, holds, errlist));
493 }
494
495 /*
496  * Retrieve list of user holds on the specified snapshot.
497  *
498  * On success, *holdsp will be set to a nvlist which the caller must free.
499  * The keys are the names of the holds, and the value is the creation time
500  * of the hold (uint64) in seconds since the epoch.
501  */
502 int
503 lzc_get_holds(const char *snapname, nvlist_t **holdsp)
504 {
505         int error;
506         nvlist_t *innvl = fnvlist_alloc();
507         error = lzc_ioctl(ZFS_IOC_GET_HOLDS, snapname, innvl, holdsp);
508         fnvlist_free(innvl);
509         return (error);
510 }
511
512 /*
513  * Generate a zfs send stream for the specified snapshot and write it to
514  * the specified file descriptor.
515  *
516  * "snapname" is the full name of the snapshot to send (e.g. "pool/fs@snap")
517  *
518  * If "from" is NULL, a full (non-incremental) stream will be sent.
519  * If "from" is non-NULL, it must be the full name of a snapshot or
520  * bookmark to send an incremental from (e.g. "pool/fs@earlier_snap" or
521  * "pool/fs#earlier_bmark").  If non-NULL, the specified snapshot or
522  * bookmark must represent an earlier point in the history of "snapname").
523  * It can be an earlier snapshot in the same filesystem or zvol as "snapname",
524  * or it can be the origin of "snapname"'s filesystem, or an earlier
525  * snapshot in the origin, etc.
526  *
527  * "fd" is the file descriptor to write the send stream to.
528  *
529  * If "flags" contains LZC_SEND_FLAG_LARGE_BLOCK, the stream is permitted
530  * to contain DRR_WRITE records with drr_length > 128K, and DRR_OBJECT
531  * records with drr_blksz > 128K.
532  *
533  * If "flags" contains LZC_SEND_FLAG_EMBED_DATA, the stream is permitted
534  * to contain DRR_WRITE_EMBEDDED records with drr_etype==BP_EMBEDDED_TYPE_DATA,
535  * which the receiving system must support (as indicated by support
536  * for the "embedded_data" feature).
537  */
538 int
539 lzc_send(const char *snapname, const char *from, int fd,
540     enum lzc_send_flags flags)
541 {
542         return (lzc_send_resume(snapname, from, fd, flags, 0, 0));
543 }
544
545 int
546 lzc_send_resume(const char *snapname, const char *from, int fd,
547     enum lzc_send_flags flags, uint64_t resumeobj, uint64_t resumeoff)
548 {
549         nvlist_t *args;
550         int err;
551
552         args = fnvlist_alloc();
553         fnvlist_add_int32(args, "fd", fd);
554         if (from != NULL)
555                 fnvlist_add_string(args, "fromsnap", from);
556         if (flags & LZC_SEND_FLAG_LARGE_BLOCK)
557                 fnvlist_add_boolean(args, "largeblockok");
558         if (flags & LZC_SEND_FLAG_EMBED_DATA)
559                 fnvlist_add_boolean(args, "embedok");
560         if (flags & LZC_SEND_FLAG_COMPRESS)
561                 fnvlist_add_boolean(args, "compressok");
562         if (resumeobj != 0 || resumeoff != 0) {
563                 fnvlist_add_uint64(args, "resume_object", resumeobj);
564                 fnvlist_add_uint64(args, "resume_offset", resumeoff);
565         }
566         err = lzc_ioctl(ZFS_IOC_SEND_NEW, snapname, args, NULL);
567         nvlist_free(args);
568         return (err);
569 }
570
571 /*
572  * "from" can be NULL, a snapshot, or a bookmark.
573  *
574  * If from is NULL, a full (non-incremental) stream will be estimated.  This
575  * is calculated very efficiently.
576  *
577  * If from is a snapshot, lzc_send_space uses the deadlists attached to
578  * each snapshot to efficiently estimate the stream size.
579  *
580  * If from is a bookmark, the indirect blocks in the destination snapshot
581  * are traversed, looking for blocks with a birth time since the creation TXG of
582  * the snapshot this bookmark was created from.  This will result in
583  * significantly more I/O and be less efficient than a send space estimation on
584  * an equivalent snapshot.
585  */
586 int
587 lzc_send_space(const char *snapname, const char *from,
588     enum lzc_send_flags flags, uint64_t *spacep)
589 {
590         nvlist_t *args;
591         nvlist_t *result;
592         int err;
593
594         args = fnvlist_alloc();
595         if (from != NULL)
596                 fnvlist_add_string(args, "from", from);
597         if (flags & LZC_SEND_FLAG_LARGE_BLOCK)
598                 fnvlist_add_boolean(args, "largeblockok");
599         if (flags & LZC_SEND_FLAG_EMBED_DATA)
600                 fnvlist_add_boolean(args, "embedok");
601         if (flags & LZC_SEND_FLAG_COMPRESS)
602                 fnvlist_add_boolean(args, "compressok");
603         err = lzc_ioctl(ZFS_IOC_SEND_SPACE, snapname, args, &result);
604         nvlist_free(args);
605         if (err == 0)
606                 *spacep = fnvlist_lookup_uint64(result, "space");
607         nvlist_free(result);
608         return (err);
609 }
610
611 static int
612 recv_read(int fd, void *buf, int ilen)
613 {
614         char *cp = buf;
615         int rv;
616         int len = ilen;
617
618         do {
619                 rv = read(fd, cp, len);
620                 cp += rv;
621                 len -= rv;
622         } while (rv > 0);
623
624         if (rv < 0 || len != 0)
625                 return (EIO);
626
627         return (0);
628 }
629
630 static int
631 recv_impl(const char *snapname, nvlist_t *props, const char *origin,
632     boolean_t force, boolean_t resumable, int fd,
633     const dmu_replay_record_t *begin_record)
634 {
635         /*
636          * The receive ioctl is still legacy, so we need to construct our own
637          * zfs_cmd_t rather than using zfsc_ioctl().
638          */
639         zfs_cmd_t zc = { 0 };
640         char *atp;
641         char *packed = NULL;
642         size_t size;
643         int error;
644
645         ASSERT3S(g_refcount, >, 0);
646
647         /* zc_name is name of containing filesystem */
648         (void) strlcpy(zc.zc_name, snapname, sizeof (zc.zc_name));
649         atp = strchr(zc.zc_name, '@');
650         if (atp == NULL)
651                 return (EINVAL);
652         *atp = '\0';
653
654         /* if the fs does not exist, try its parent. */
655         if (!lzc_exists(zc.zc_name)) {
656                 char *slashp = strrchr(zc.zc_name, '/');
657                 if (slashp == NULL)
658                         return (ENOENT);
659                 *slashp = '\0';
660
661         }
662
663         /* zc_value is full name of the snapshot to create */
664         (void) strlcpy(zc.zc_value, snapname, sizeof (zc.zc_value));
665
666         if (props != NULL) {
667                 /* zc_nvlist_src is props to set */
668                 packed = fnvlist_pack(props, &size);
669                 zc.zc_nvlist_src = (uint64_t)(uintptr_t)packed;
670                 zc.zc_nvlist_src_size = size;
671         }
672
673         /* zc_string is name of clone origin (if DRR_FLAG_CLONE) */
674         if (origin != NULL)
675                 (void) strlcpy(zc.zc_string, origin, sizeof (zc.zc_string));
676
677         /* zc_begin_record is non-byteswapped BEGIN record */
678         if (begin_record == NULL) {
679                 error = recv_read(fd, &zc.zc_begin_record,
680                     sizeof (zc.zc_begin_record));
681                 if (error != 0)
682                         goto out;
683         } else {
684                 zc.zc_begin_record = *begin_record;
685         }
686
687         /* zc_cookie is fd to read from */
688         zc.zc_cookie = fd;
689
690         /* zc guid is force flag */
691         zc.zc_guid = force;
692
693         zc.zc_resumable = resumable;
694
695         /* zc_cleanup_fd is unused */
696         zc.zc_cleanup_fd = -1;
697
698         error = ioctl(g_fd, ZFS_IOC_RECV, &zc);
699         if (error != 0)
700                 error = errno;
701
702 out:
703         if (packed != NULL)
704                 fnvlist_pack_free(packed, size);
705         free((void*)(uintptr_t)zc.zc_nvlist_dst);
706         return (error);
707 }
708
709 /*
710  * The simplest receive case: receive from the specified fd, creating the
711  * specified snapshot.  Apply the specified properties as "received" properties
712  * (which can be overridden by locally-set properties).  If the stream is a
713  * clone, its origin snapshot must be specified by 'origin'.  The 'force'
714  * flag will cause the target filesystem to be rolled back or destroyed if
715  * necessary to receive.
716  *
717  * Return 0 on success or an errno on failure.
718  *
719  * Note: this interface does not work on dedup'd streams
720  * (those with DMU_BACKUP_FEATURE_DEDUP).
721  */
722 int
723 lzc_receive(const char *snapname, nvlist_t *props, const char *origin,
724     boolean_t force, int fd)
725 {
726         return (recv_impl(snapname, props, origin, force, B_FALSE, fd, NULL));
727 }
728
729 /*
730  * Like lzc_receive, but if the receive fails due to premature stream
731  * termination, the intermediate state will be preserved on disk.  In this
732  * case, ECKSUM will be returned.  The receive may subsequently be resumed
733  * with a resuming send stream generated by lzc_send_resume().
734  */
735 int
736 lzc_receive_resumable(const char *snapname, nvlist_t *props, const char *origin,
737     boolean_t force, int fd)
738 {
739         return (recv_impl(snapname, props, origin, force, B_TRUE, fd, NULL));
740 }
741
742 /*
743  * Like lzc_receive, but allows the caller to read the begin record and then to
744  * pass it in.  That could be useful if the caller wants to derive, for example,
745  * the snapname or the origin parameters based on the information contained in
746  * the begin record.
747  * The begin record must be in its original form as read from the stream,
748  * in other words, it should not be byteswapped.
749  *
750  * The 'resumable' parameter allows to obtain the same behavior as with
751  * lzc_receive_resumable.
752  */
753 int
754 lzc_receive_with_header(const char *snapname, nvlist_t *props,
755     const char *origin, boolean_t force, boolean_t resumable, int fd,
756     const dmu_replay_record_t *begin_record)
757 {
758         if (begin_record == NULL)
759                 return (EINVAL);
760         return (recv_impl(snapname, props, origin, force, resumable, fd,
761             begin_record));
762 }
763
764 /*
765  * Roll back this filesystem or volume to its most recent snapshot.
766  * If snapnamebuf is not NULL, it will be filled in with the name
767  * of the most recent snapshot.
768  * Note that the latest snapshot may change if a new one is concurrently
769  * created or the current one is destroyed.  lzc_rollback_to can be used
770  * to roll back to a specific latest snapshot.
771  *
772  * Return 0 on success or an errno on failure.
773  */
774 int
775 lzc_rollback(const char *fsname, char *snapnamebuf, int snapnamelen)
776 {
777         nvlist_t *args;
778         nvlist_t *result;
779         int err;
780
781         args = fnvlist_alloc();
782         err = lzc_ioctl(ZFS_IOC_ROLLBACK, fsname, args, &result);
783         nvlist_free(args);
784         if (err == 0 && snapnamebuf != NULL) {
785                 const char *snapname = fnvlist_lookup_string(result, "target");
786                 (void) strlcpy(snapnamebuf, snapname, snapnamelen);
787         }
788         nvlist_free(result);
789
790         return (err);
791 }
792
793 /*
794  * Roll back this filesystem or volume to the specified snapshot,
795  * if possible.
796  *
797  * Return 0 on success or an errno on failure.
798  */
799 int
800 lzc_rollback_to(const char *fsname, const char *snapname)
801 {
802         nvlist_t *args;
803         nvlist_t *result;
804         int err;
805
806         args = fnvlist_alloc();
807         fnvlist_add_string(args, "target", snapname);
808         err = lzc_ioctl(ZFS_IOC_ROLLBACK, fsname, args, &result);
809         nvlist_free(args);
810         nvlist_free(result);
811         return (err);
812 }
813
814 /*
815  * Creates bookmarks.
816  *
817  * The bookmarks nvlist maps from name of the bookmark (e.g. "pool/fs#bmark") to
818  * the name of the snapshot (e.g. "pool/fs@snap").  All the bookmarks and
819  * snapshots must be in the same pool.
820  *
821  * The returned results nvlist will have an entry for each bookmark that failed.
822  * The value will be the (int32) error code.
823  *
824  * The return value will be 0 if all bookmarks were created, otherwise it will
825  * be the errno of a (undetermined) bookmarks that failed.
826  */
827 int
828 lzc_bookmark(nvlist_t *bookmarks, nvlist_t **errlist)
829 {
830         nvpair_t *elem;
831         int error;
832         char pool[ZFS_MAX_DATASET_NAME_LEN];
833
834         /* determine the pool name */
835         elem = nvlist_next_nvpair(bookmarks, NULL);
836         if (elem == NULL)
837                 return (0);
838         (void) strlcpy(pool, nvpair_name(elem), sizeof (pool));
839         pool[strcspn(pool, "/#")] = '\0';
840
841         error = lzc_ioctl(ZFS_IOC_BOOKMARK, pool, bookmarks, errlist);
842
843         return (error);
844 }
845
846 /*
847  * Retrieve bookmarks.
848  *
849  * Retrieve the list of bookmarks for the given file system. The props
850  * parameter is an nvlist of property names (with no values) that will be
851  * returned for each bookmark.
852  *
853  * The following are valid properties on bookmarks, all of which are numbers
854  * (represented as uint64 in the nvlist)
855  *
856  * "guid" - globally unique identifier of the snapshot it refers to
857  * "createtxg" - txg when the snapshot it refers to was created
858  * "creation" - timestamp when the snapshot it refers to was created
859  *
860  * The format of the returned nvlist as follows:
861  * <short name of bookmark> -> {
862  *     <name of property> -> {
863  *         "value" -> uint64
864  *     }
865  *  }
866  */
867 int
868 lzc_get_bookmarks(const char *fsname, nvlist_t *props, nvlist_t **bmarks)
869 {
870         return (lzc_ioctl(ZFS_IOC_GET_BOOKMARKS, fsname, props, bmarks));
871 }
872
873 /*
874  * Destroys bookmarks.
875  *
876  * The keys in the bmarks nvlist are the bookmarks to be destroyed.
877  * They must all be in the same pool.  Bookmarks are specified as
878  * <fs>#<bmark>.
879  *
880  * Bookmarks that do not exist will be silently ignored.
881  *
882  * The return value will be 0 if all bookmarks that existed were destroyed.
883  *
884  * Otherwise the return value will be the errno of a (undetermined) bookmark
885  * that failed, no bookmarks will be destroyed, and the errlist will have an
886  * entry for each bookmarks that failed.  The value in the errlist will be
887  * the (int32) error code.
888  */
889 int
890 lzc_destroy_bookmarks(nvlist_t *bmarks, nvlist_t **errlist)
891 {
892         nvpair_t *elem;
893         int error;
894         char pool[ZFS_MAX_DATASET_NAME_LEN];
895
896         /* determine the pool name */
897         elem = nvlist_next_nvpair(bmarks, NULL);
898         if (elem == NULL)
899                 return (0);
900         (void) strlcpy(pool, nvpair_name(elem), sizeof (pool));
901         pool[strcspn(pool, "/#")] = '\0';
902
903         error = lzc_ioctl(ZFS_IOC_DESTROY_BOOKMARKS, pool, bmarks, errlist);
904
905         return (error);
906 }