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 * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
23 * Copyright (c) 2012 Pawel Jakub Dawidek <pawel@dawidek.net>.
24 * All rights reserved.
25 */
26
27#include <libintl.h>
28#include <libuutil.h>
29#include <stddef.h>
30#include <stdio.h>
31#include <stdlib.h>
32#include <strings.h>
33
34#include <libzfs.h>
35
36#include "zfs_util.h"
37#include "zfs_iter.h"
38
39/*
40 * This is a private interface used to gather up all the datasets specified on
41 * the command line so that we can iterate over them in order.
42 *
43 * First, we iterate over all filesystems, gathering them together into an
44 * AVL tree.  We report errors for any explicitly specified datasets
45 * that we couldn't open.
46 *
47 * When finished, we have an AVL tree of ZFS handles.  We go through and execute
48 * the provided callback for each one, passing whatever data the user supplied.
49 */
50
51typedef struct zfs_node {
52	zfs_handle_t	*zn_handle;
53	uu_avl_node_t	zn_avlnode;
54} zfs_node_t;
55
56typedef struct callback_data {
57	uu_avl_t		*cb_avl;
58	int			cb_flags;
59	zfs_type_t		cb_types;
60	zfs_sort_column_t	*cb_sortcol;
61	zprop_list_t		**cb_proplist;
62	int			cb_depth_limit;
63	int			cb_depth;
64	uint8_t			cb_props_table[ZFS_NUM_PROPS];
65} callback_data_t;
66
67uu_avl_pool_t *avl_pool;
68
69/*
70 * Include snaps if they were requested or if this a zfs list where types
71 * were not specified and the "listsnapshots" property is set on this pool.
72 */
73static int
74zfs_include_snapshots(zfs_handle_t *zhp, callback_data_t *cb)
75{
76	zpool_handle_t *zph;
77
78	if ((cb->cb_flags & ZFS_ITER_PROP_LISTSNAPS) == 0)
79		return (cb->cb_types & ZFS_TYPE_SNAPSHOT);
80
81	zph = zfs_get_pool_handle(zhp);
82	return (zpool_get_prop_int(zph, ZPOOL_PROP_LISTSNAPS, NULL));
83}
84
85/*
86 * Called for each dataset.  If the object is of an appropriate type,
87 * add it to the avl tree and recurse over any children as necessary.
88 */
89static int
90zfs_callback(zfs_handle_t *zhp, void *data)
91{
92	callback_data_t *cb = data;
93	int dontclose = 0;
94	int include_snaps = zfs_include_snapshots(zhp, cb);
95
96	if ((zfs_get_type(zhp) & cb->cb_types) ||
97	    ((zfs_get_type(zhp) == ZFS_TYPE_SNAPSHOT) && include_snaps)) {
98		uu_avl_index_t idx;
99		zfs_node_t *node = safe_malloc(sizeof (zfs_node_t));
100
101		node->zn_handle = zhp;
102		uu_avl_node_init(node, &node->zn_avlnode, avl_pool);
103		if (uu_avl_find(cb->cb_avl, node, cb->cb_sortcol,
104		    &idx) == NULL) {
105			if (cb->cb_proplist) {
106				if ((*cb->cb_proplist) &&
107				    !(*cb->cb_proplist)->pl_all)
108					zfs_prune_proplist(zhp,
109					    cb->cb_props_table);
110
111				if (zfs_expand_proplist(zhp, cb->cb_proplist,
112				    (cb->cb_flags & ZFS_ITER_RECVD_PROPS))
113				    != 0) {
114					free(node);
115					return (-1);
116				}
117			}
118			uu_avl_insert(cb->cb_avl, node, idx);
119			dontclose = 1;
120		} else {
121			free(node);
122		}
123	}
124
125	/*
126	 * Recurse if necessary.
127	 */
128	if (cb->cb_flags & ZFS_ITER_RECURSE &&
129	    ((cb->cb_flags & ZFS_ITER_DEPTH_LIMIT) == 0 ||
130	    cb->cb_depth < cb->cb_depth_limit)) {
131		cb->cb_depth++;
132		if (zfs_get_type(zhp) == ZFS_TYPE_FILESYSTEM)
133			(void) zfs_iter_filesystems(zhp, zfs_callback, data);
134		if ((zfs_get_type(zhp) != ZFS_TYPE_SNAPSHOT) && include_snaps) {
135			(void) zfs_iter_snapshots(zhp,
136			    (cb->cb_flags & ZFS_ITER_SIMPLE) != 0, zfs_callback,
137			    data);
138		}
139		cb->cb_depth--;
140	}
141
142	if (!dontclose)
143		zfs_close(zhp);
144
145	return (0);
146}
147
148int
149zfs_add_sort_column(zfs_sort_column_t **sc, const char *name,
150    boolean_t reverse)
151{
152	zfs_sort_column_t *col;
153	zfs_prop_t prop;
154
155	if ((prop = zfs_name_to_prop(name)) == ZPROP_INVAL &&
156	    !zfs_prop_user(name))
157		return (-1);
158
159	col = safe_malloc(sizeof (zfs_sort_column_t));
160
161	col->sc_prop = prop;
162	col->sc_reverse = reverse;
163	if (prop == ZPROP_INVAL) {
164		col->sc_user_prop = safe_malloc(strlen(name) + 1);
165		(void) strcpy(col->sc_user_prop, name);
166	}
167
168	if (*sc == NULL) {
169		col->sc_last = col;
170		*sc = col;
171	} else {
172		(*sc)->sc_last->sc_next = col;
173		(*sc)->sc_last = col;
174	}
175
176	return (0);
177}
178
179void
180zfs_free_sort_columns(zfs_sort_column_t *sc)
181{
182	zfs_sort_column_t *col;
183
184	while (sc != NULL) {
185		col = sc->sc_next;
186		free(sc->sc_user_prop);
187		free(sc);
188		sc = col;
189	}
190}
191
192boolean_t
193zfs_sort_only_by_name(const zfs_sort_column_t *sc)
194{
195
196	return (sc != NULL && sc->sc_next == NULL &&
197	    sc->sc_prop == ZFS_PROP_NAME);
198}
199
200/* ARGSUSED */
201static int
202zfs_compare(const void *larg, const void *rarg, void *unused)
203{
204	zfs_handle_t *l = ((zfs_node_t *)larg)->zn_handle;
205	zfs_handle_t *r = ((zfs_node_t *)rarg)->zn_handle;
206	const char *lname = zfs_get_name(l);
207	const char *rname = zfs_get_name(r);
208	char *lat, *rat;
209	uint64_t lcreate, rcreate;
210	int ret;
211
212	lat = (char *)strchr(lname, '@');
213	rat = (char *)strchr(rname, '@');
214
215	if (lat != NULL)
216		*lat = '\0';
217	if (rat != NULL)
218		*rat = '\0';
219
220	ret = strcmp(lname, rname);
221	if (ret == 0) {
222		/*
223		 * If we're comparing a dataset to one of its snapshots, we
224		 * always make the full dataset first.
225		 */
226		if (lat == NULL) {
227			ret = -1;
228		} else if (rat == NULL) {
229			ret = 1;
230		} else {
231			/*
232			 * If we have two snapshots from the same dataset, then
233			 * we want to sort them according to creation time.  We
234			 * use the hidden CREATETXG property to get an absolute
235			 * ordering of snapshots.
236			 */
237			lcreate = zfs_prop_get_int(l, ZFS_PROP_CREATETXG);
238			rcreate = zfs_prop_get_int(r, ZFS_PROP_CREATETXG);
239
240			/*
241			 * Both lcreate and rcreate being 0 means we don't have
242			 * properties and we should compare full name.
243			 */
244			if (lcreate == 0 && rcreate == 0)
245				ret = strcmp(lat + 1, rat + 1);
246			else if (lcreate < rcreate)
247				ret = -1;
248			else if (lcreate > rcreate)
249				ret = 1;
250		}
251	}
252
253	if (lat != NULL)
254		*lat = '@';
255	if (rat != NULL)
256		*rat = '@';
257
258	return (ret);
259}
260
261/*
262 * Sort datasets by specified columns.
263 *
264 * o  Numeric types sort in ascending order.
265 * o  String types sort in alphabetical order.
266 * o  Types inappropriate for a row sort that row to the literal
267 *    bottom, regardless of the specified ordering.
268 *
269 * If no sort columns are specified, or two datasets compare equally
270 * across all specified columns, they are sorted alphabetically by name
271 * with snapshots grouped under their parents.
272 */
273static int
274zfs_sort(const void *larg, const void *rarg, void *data)
275{
276	zfs_handle_t *l = ((zfs_node_t *)larg)->zn_handle;
277	zfs_handle_t *r = ((zfs_node_t *)rarg)->zn_handle;
278	zfs_sort_column_t *sc = (zfs_sort_column_t *)data;
279	zfs_sort_column_t *psc;
280
281	for (psc = sc; psc != NULL; psc = psc->sc_next) {
282		char lbuf[ZFS_MAXPROPLEN], rbuf[ZFS_MAXPROPLEN];
283		char *lstr, *rstr;
284		uint64_t lnum, rnum;
285		boolean_t lvalid, rvalid;
286		int ret = 0;
287
288		/*
289		 * We group the checks below the generic code.  If 'lstr' and
290		 * 'rstr' are non-NULL, then we do a string based comparison.
291		 * Otherwise, we compare 'lnum' and 'rnum'.
292		 */
293		lstr = rstr = NULL;
294		if (psc->sc_prop == ZPROP_INVAL) {
295			nvlist_t *luser, *ruser;
296			nvlist_t *lval, *rval;
297
298			luser = zfs_get_user_props(l);
299			ruser = zfs_get_user_props(r);
300
301			lvalid = (nvlist_lookup_nvlist(luser,
302			    psc->sc_user_prop, &lval) == 0);
303			rvalid = (nvlist_lookup_nvlist(ruser,
304			    psc->sc_user_prop, &rval) == 0);
305
306			if (lvalid)
307				verify(nvlist_lookup_string(lval,
308				    ZPROP_VALUE, &lstr) == 0);
309			if (rvalid)
310				verify(nvlist_lookup_string(rval,
311				    ZPROP_VALUE, &rstr) == 0);
312		} else if (psc->sc_prop == ZFS_PROP_NAME) {
313			lvalid = rvalid = B_TRUE;
314
315			(void) strlcpy(lbuf, zfs_get_name(l), sizeof(lbuf));
316			(void) strlcpy(rbuf, zfs_get_name(r), sizeof(rbuf));
317
318			lstr = lbuf;
319			rstr = rbuf;
320		} else if (zfs_prop_is_string(psc->sc_prop)) {
321			lvalid = (zfs_prop_get(l, psc->sc_prop, lbuf,
322			    sizeof (lbuf), NULL, NULL, 0, B_TRUE) == 0);
323			rvalid = (zfs_prop_get(r, psc->sc_prop, rbuf,
324			    sizeof (rbuf), NULL, NULL, 0, B_TRUE) == 0);
325
326			lstr = lbuf;
327			rstr = rbuf;
328		} else {
329			lvalid = zfs_prop_valid_for_type(psc->sc_prop,
330			    zfs_get_type(l));
331			rvalid = zfs_prop_valid_for_type(psc->sc_prop,
332			    zfs_get_type(r));
333
334			if (lvalid)
335				(void) zfs_prop_get_numeric(l, psc->sc_prop,
336				    &lnum, NULL, NULL, 0);
337			if (rvalid)
338				(void) zfs_prop_get_numeric(r, psc->sc_prop,
339				    &rnum, NULL, NULL, 0);
340		}
341
342		if (!lvalid && !rvalid)
343			continue;
344		else if (!lvalid)
345			return (1);
346		else if (!rvalid)
347			return (-1);
348
349		if (lstr)
350			ret = strcmp(lstr, rstr);
351		else if (lnum < rnum)
352			ret = -1;
353		else if (lnum > rnum)
354			ret = 1;
355
356		if (ret != 0) {
357			if (psc->sc_reverse == B_TRUE)
358				ret = (ret < 0) ? 1 : -1;
359			return (ret);
360		}
361	}
362
363	return (zfs_compare(larg, rarg, NULL));
364}
365
366int
367zfs_for_each(int argc, char **argv, int flags, zfs_type_t types,
368    zfs_sort_column_t *sortcol, zprop_list_t **proplist, int limit,
369    zfs_iter_f callback, void *data)
370{
371	callback_data_t cb = {0};
372	int ret = 0;
373	zfs_node_t *node;
374	uu_avl_walk_t *walk;
375
376	avl_pool = uu_avl_pool_create("zfs_pool", sizeof (zfs_node_t),
377	    offsetof(zfs_node_t, zn_avlnode), zfs_sort, UU_DEFAULT);
378
379	if (avl_pool == NULL)
380		nomem();
381
382	cb.cb_sortcol = sortcol;
383	cb.cb_flags = flags;
384	cb.cb_proplist = proplist;
385	cb.cb_types = types;
386	cb.cb_depth_limit = limit;
387	/*
388	 * If cb_proplist is provided then in the zfs_handles created we
389	 * retain only those properties listed in cb_proplist and sortcol.
390	 * The rest are pruned. So, the caller should make sure that no other
391	 * properties other than those listed in cb_proplist/sortcol are
392	 * accessed.
393	 *
394	 * If cb_proplist is NULL then we retain all the properties.  We
395	 * always retain the zoned property, which some other properties
396	 * need (userquota & friends), and the createtxg property, which
397	 * we need to sort snapshots.
398	 */
399	if (cb.cb_proplist && *cb.cb_proplist) {
400		zprop_list_t *p = *cb.cb_proplist;
401
402		while (p) {
403			if (p->pl_prop >= ZFS_PROP_TYPE &&
404			    p->pl_prop < ZFS_NUM_PROPS) {
405				cb.cb_props_table[p->pl_prop] = B_TRUE;
406			}
407			p = p->pl_next;
408		}
409
410		while (sortcol) {
411			if (sortcol->sc_prop >= ZFS_PROP_TYPE &&
412			    sortcol->sc_prop < ZFS_NUM_PROPS) {
413				cb.cb_props_table[sortcol->sc_prop] = B_TRUE;
414			}
415			sortcol = sortcol->sc_next;
416		}
417
418		cb.cb_props_table[ZFS_PROP_ZONED] = B_TRUE;
419		cb.cb_props_table[ZFS_PROP_CREATETXG] = B_TRUE;
420	} else {
421		(void) memset(cb.cb_props_table, B_TRUE,
422		    sizeof (cb.cb_props_table));
423	}
424
425	if ((cb.cb_avl = uu_avl_create(avl_pool, NULL, UU_DEFAULT)) == NULL)
426		nomem();
427
428	if (argc == 0) {
429		/*
430		 * If given no arguments, iterate over all datasets.
431		 */
432		cb.cb_flags |= ZFS_ITER_RECURSE;
433		ret = zfs_iter_root(g_zfs, zfs_callback, &cb);
434	} else {
435		int i;
436		zfs_handle_t *zhp;
437		zfs_type_t argtype;
438
439		/*
440		 * If we're recursive, then we always allow filesystems as
441		 * arguments.  If we also are interested in snapshots, then we
442		 * can take volumes as well.
443		 */
444		argtype = types;
445		if (flags & ZFS_ITER_RECURSE) {
446			argtype |= ZFS_TYPE_FILESYSTEM;
447			if (types & ZFS_TYPE_SNAPSHOT)
448				argtype |= ZFS_TYPE_VOLUME;
449		}
450
451		for (i = 0; i < argc; i++) {
452			if (flags & ZFS_ITER_ARGS_CAN_BE_PATHS) {
453				zhp = zfs_path_to_zhandle(g_zfs, argv[i],
454				    argtype);
455			} else {
456				zhp = zfs_open(g_zfs, argv[i], argtype);
457			}
458			if (zhp != NULL)
459				ret |= zfs_callback(zhp, &cb);
460			else
461				ret = 1;
462		}
463	}
464
465	/*
466	 * At this point we've got our AVL tree full of zfs handles, so iterate
467	 * over each one and execute the real user callback.
468	 */
469	for (node = uu_avl_first(cb.cb_avl); node != NULL;
470	    node = uu_avl_next(cb.cb_avl, node))
471		ret |= callback(node->zn_handle, data);
472
473	/*
474	 * Finally, clean up the AVL tree.
475	 */
476	if ((walk = uu_avl_walk_start(cb.cb_avl, UU_WALK_ROBUST)) == NULL)
477		nomem();
478
479	while ((node = uu_avl_walk_next(walk)) != NULL) {
480		uu_avl_remove(cb.cb_avl, node);
481		zfs_close(node->zn_handle);
482		free(node);
483	}
484
485	uu_avl_walk_end(walk);
486	uu_avl_destroy(cb.cb_avl);
487	uu_avl_pool_destroy(avl_pool);
488
489	return (ret);
490}
491