xref: /freebsd-src/sys/contrib/openzfs/module/zfs/zcp.c (revision aca928a50a42f00f344df934005b09dbcb4e2f77)
1eda14cbcSMatt Macy /*
2eda14cbcSMatt Macy  * CDDL HEADER START
3eda14cbcSMatt Macy  *
4eda14cbcSMatt Macy  * This file and its contents are supplied under the terms of the
5eda14cbcSMatt Macy  * Common Development and Distribution License ("CDDL"), version 1.0.
6eda14cbcSMatt Macy  * You may only use this file in accordance with the terms of version
7eda14cbcSMatt Macy  * 1.0 of the CDDL.
8eda14cbcSMatt Macy  *
9eda14cbcSMatt Macy  * A full copy of the text of the CDDL should have accompanied this
10eda14cbcSMatt Macy  * source.  A copy of the CDDL is also available via the Internet at
11eda14cbcSMatt Macy  * http://www.illumos.org/license/CDDL.
12eda14cbcSMatt Macy  *
13eda14cbcSMatt Macy  * CDDL HEADER END
14eda14cbcSMatt Macy  */
15eda14cbcSMatt Macy 
16eda14cbcSMatt Macy /*
17eda14cbcSMatt Macy  * Copyright (c) 2016, 2018 by Delphix. All rights reserved.
18eda14cbcSMatt Macy  */
19eda14cbcSMatt Macy 
20eda14cbcSMatt Macy /*
21eda14cbcSMatt Macy  * ZFS Channel Programs (ZCP)
22eda14cbcSMatt Macy  *
23eda14cbcSMatt Macy  * The ZCP interface allows various ZFS commands and operations ZFS
24eda14cbcSMatt Macy  * administrative operations (e.g. creating and destroying snapshots, typically
25eda14cbcSMatt Macy  * performed via an ioctl to /dev/zfs by the zfs(8) command and
26eda14cbcSMatt Macy  * libzfs/libzfs_core) to be run * programmatically as a Lua script.  A ZCP
27eda14cbcSMatt Macy  * script is run as a dsl_sync_task and fully executed during one transaction
28eda14cbcSMatt Macy  * group sync.  This ensures that no other changes can be written concurrently
29eda14cbcSMatt Macy  * with a running Lua script.  Combining multiple calls to the exposed ZFS
30eda14cbcSMatt Macy  * functions into one script gives a number of benefits:
31eda14cbcSMatt Macy  *
32eda14cbcSMatt Macy  * 1. Atomicity.  For some compound or iterative operations, it's useful to be
33eda14cbcSMatt Macy  * able to guarantee that the state of a pool has not changed between calls to
34eda14cbcSMatt Macy  * ZFS.
35eda14cbcSMatt Macy  *
36eda14cbcSMatt Macy  * 2. Performance.  If a large number of changes need to be made (e.g. deleting
37eda14cbcSMatt Macy  * many filesystems), there can be a significant performance penalty as a
38eda14cbcSMatt Macy  * result of the need to wait for a transaction group sync to pass for every
39eda14cbcSMatt Macy  * single operation.  When expressed as a single ZCP script, all these changes
40eda14cbcSMatt Macy  * can be performed at once in one txg sync.
41eda14cbcSMatt Macy  *
42eda14cbcSMatt Macy  * A modified version of the Lua 5.2 interpreter is used to run channel program
43eda14cbcSMatt Macy  * scripts. The Lua 5.2 manual can be found at:
44eda14cbcSMatt Macy  *
45eda14cbcSMatt Macy  *      http://www.lua.org/manual/5.2/
46eda14cbcSMatt Macy  *
47eda14cbcSMatt Macy  * If being run by a user (via an ioctl syscall), executing a ZCP script
48eda14cbcSMatt Macy  * requires root privileges in the global zone.
49eda14cbcSMatt Macy  *
50eda14cbcSMatt Macy  * Scripts are passed to zcp_eval() as a string, then run in a synctask by
51eda14cbcSMatt Macy  * zcp_eval_sync().  Arguments can be passed into the Lua script as an nvlist,
52eda14cbcSMatt Macy  * which will be converted to a Lua table.  Similarly, values returned from
53eda14cbcSMatt Macy  * a ZCP script will be converted to an nvlist.  See zcp_lua_to_nvlist_impl()
54eda14cbcSMatt Macy  * for details on exact allowed types and conversion.
55eda14cbcSMatt Macy  *
56eda14cbcSMatt Macy  * ZFS functionality is exposed to a ZCP script as a library of function calls.
57eda14cbcSMatt Macy  * These calls are sorted into submodules, such as zfs.list and zfs.sync, for
58eda14cbcSMatt Macy  * iterators and synctasks, respectively.  Each of these submodules resides in
59eda14cbcSMatt Macy  * its own source file, with a zcp_*_info structure describing each library
60eda14cbcSMatt Macy  * call in the submodule.
61eda14cbcSMatt Macy  *
62eda14cbcSMatt Macy  * Error handling in ZCP scripts is handled by a number of different methods
63eda14cbcSMatt Macy  * based on severity:
64eda14cbcSMatt Macy  *
65eda14cbcSMatt Macy  * 1. Memory and time limits are in place to prevent a channel program from
66eda14cbcSMatt Macy  * consuming excessive system or running forever.  If one of these limits is
67eda14cbcSMatt Macy  * hit, the channel program will be stopped immediately and return from
68eda14cbcSMatt Macy  * zcp_eval() with an error code. No attempt will be made to roll back or undo
69eda14cbcSMatt Macy  * any changes made by the channel program before the error occurred.
70eda14cbcSMatt Macy  * Consumers invoking zcp_eval() from elsewhere in the kernel may pass a time
71eda14cbcSMatt Macy  * limit of 0, disabling the time limit.
72eda14cbcSMatt Macy  *
73eda14cbcSMatt Macy  * 2. Internal Lua errors can occur as a result of a syntax error, calling a
74eda14cbcSMatt Macy  * library function with incorrect arguments, invoking the error() function,
75eda14cbcSMatt Macy  * failing an assert(), or other runtime errors.  In these cases the channel
76eda14cbcSMatt Macy  * program will stop executing and return from zcp_eval() with an error code.
77eda14cbcSMatt Macy  * In place of a return value, an error message will also be returned in the
78eda14cbcSMatt Macy  * 'result' nvlist containing information about the error. No attempt will be
79eda14cbcSMatt Macy  * made to roll back or undo any changes made by the channel program before the
80eda14cbcSMatt Macy  * error occurred.
81eda14cbcSMatt Macy  *
82eda14cbcSMatt Macy  * 3. If an error occurs inside a ZFS library call which returns an error code,
83eda14cbcSMatt Macy  * the error is returned to the Lua script to be handled as desired.
84eda14cbcSMatt Macy  *
85eda14cbcSMatt Macy  * In the first two cases, Lua's error-throwing mechanism is used, which
86eda14cbcSMatt Macy  * longjumps out of the script execution with luaL_error() and returns with the
87eda14cbcSMatt Macy  * error.
88eda14cbcSMatt Macy  *
89eda14cbcSMatt Macy  * See zfs-program(8) for more information on high level usage.
90eda14cbcSMatt Macy  */
91eda14cbcSMatt Macy 
92eda14cbcSMatt Macy #include <sys/lua/lua.h>
93eda14cbcSMatt Macy #include <sys/lua/lualib.h>
94eda14cbcSMatt Macy #include <sys/lua/lauxlib.h>
95eda14cbcSMatt Macy 
96eda14cbcSMatt Macy #include <sys/dsl_prop.h>
97eda14cbcSMatt Macy #include <sys/dsl_synctask.h>
98eda14cbcSMatt Macy #include <sys/dsl_dataset.h>
99eda14cbcSMatt Macy #include <sys/zcp.h>
100eda14cbcSMatt Macy #include <sys/zcp_iter.h>
101eda14cbcSMatt Macy #include <sys/zcp_prop.h>
102eda14cbcSMatt Macy #include <sys/zcp_global.h>
103eda14cbcSMatt Macy #include <sys/zvol.h>
104eda14cbcSMatt Macy 
105eda14cbcSMatt Macy #ifndef KM_NORMALPRI
106eda14cbcSMatt Macy #define	KM_NORMALPRI	0
107eda14cbcSMatt Macy #endif
108eda14cbcSMatt Macy 
109eda14cbcSMatt Macy #define	ZCP_NVLIST_MAX_DEPTH 20
110eda14cbcSMatt Macy 
111e92ffd9bSMartin Matuska static const uint64_t zfs_lua_check_instrlimit_interval = 100;
112dbd5678dSMartin Matuska uint64_t zfs_lua_max_instrlimit = ZCP_MAX_INSTRLIMIT;
113dbd5678dSMartin Matuska uint64_t zfs_lua_max_memlimit = ZCP_MAX_MEMLIMIT;
114eda14cbcSMatt Macy 
115eda14cbcSMatt Macy /*
116eda14cbcSMatt Macy  * Forward declarations for mutually recursive functions
117eda14cbcSMatt Macy  */
118eda14cbcSMatt Macy static int zcp_nvpair_value_to_lua(lua_State *, nvpair_t *, char *, int);
119eda14cbcSMatt Macy static int zcp_lua_to_nvlist_impl(lua_State *, int, nvlist_t *, const char *,
120eda14cbcSMatt Macy     int);
121eda14cbcSMatt Macy 
122eda14cbcSMatt Macy /*
123eda14cbcSMatt Macy  * The outer-most error callback handler for use with lua_pcall(). On
124eda14cbcSMatt Macy  * error Lua will call this callback with a single argument that
125eda14cbcSMatt Macy  * represents the error value. In most cases this will be a string
126eda14cbcSMatt Macy  * containing an error message, but channel programs can use Lua's
127eda14cbcSMatt Macy  * error() function to return arbitrary objects as errors. This callback
128eda14cbcSMatt Macy  * returns (on the Lua stack) the original error object along with a traceback.
129eda14cbcSMatt Macy  *
130eda14cbcSMatt Macy  * Fatal Lua errors can occur while resources are held, so we also call any
131eda14cbcSMatt Macy  * registered cleanup function here.
132eda14cbcSMatt Macy  */
133eda14cbcSMatt Macy static int
zcp_error_handler(lua_State * state)134eda14cbcSMatt Macy zcp_error_handler(lua_State *state)
135eda14cbcSMatt Macy {
136eda14cbcSMatt Macy 	const char *msg;
137eda14cbcSMatt Macy 
138eda14cbcSMatt Macy 	zcp_cleanup(state);
139eda14cbcSMatt Macy 
140eda14cbcSMatt Macy 	VERIFY3U(1, ==, lua_gettop(state));
141eda14cbcSMatt Macy 	msg = lua_tostring(state, 1);
142eda14cbcSMatt Macy 	luaL_traceback(state, state, msg, 1);
143eda14cbcSMatt Macy 	return (1);
144eda14cbcSMatt Macy }
145eda14cbcSMatt Macy 
146eda14cbcSMatt Macy int
zcp_argerror(lua_State * state,int narg,const char * msg,...)147eda14cbcSMatt Macy zcp_argerror(lua_State *state, int narg, const char *msg, ...)
148eda14cbcSMatt Macy {
149eda14cbcSMatt Macy 	va_list alist;
150eda14cbcSMatt Macy 
151eda14cbcSMatt Macy 	va_start(alist, msg);
152eda14cbcSMatt Macy 	const char *buf = lua_pushvfstring(state, msg, alist);
153eda14cbcSMatt Macy 	va_end(alist);
154eda14cbcSMatt Macy 
155eda14cbcSMatt Macy 	return (luaL_argerror(state, narg, buf));
156eda14cbcSMatt Macy }
157eda14cbcSMatt Macy 
158eda14cbcSMatt Macy /*
159eda14cbcSMatt Macy  * Install a new cleanup function, which will be invoked with the given
160eda14cbcSMatt Macy  * opaque argument if a fatal error causes the Lua interpreter to longjump out
161eda14cbcSMatt Macy  * of a function call.
162eda14cbcSMatt Macy  *
163eda14cbcSMatt Macy  * If an error occurs, the cleanup function will be invoked exactly once and
164eda14cbcSMatt Macy  * then unregistered.
165eda14cbcSMatt Macy  *
166eda14cbcSMatt Macy  * Returns the registered cleanup handler so the caller can deregister it
167eda14cbcSMatt Macy  * if no error occurs.
168eda14cbcSMatt Macy  */
169eda14cbcSMatt Macy zcp_cleanup_handler_t *
zcp_register_cleanup(lua_State * state,zcp_cleanup_t cleanfunc,void * cleanarg)170eda14cbcSMatt Macy zcp_register_cleanup(lua_State *state, zcp_cleanup_t cleanfunc, void *cleanarg)
171eda14cbcSMatt Macy {
172eda14cbcSMatt Macy 	zcp_run_info_t *ri = zcp_run_info(state);
173eda14cbcSMatt Macy 
174eda14cbcSMatt Macy 	zcp_cleanup_handler_t *zch = kmem_alloc(sizeof (*zch), KM_SLEEP);
175eda14cbcSMatt Macy 	zch->zch_cleanup_func = cleanfunc;
176eda14cbcSMatt Macy 	zch->zch_cleanup_arg = cleanarg;
177eda14cbcSMatt Macy 	list_insert_head(&ri->zri_cleanup_handlers, zch);
178eda14cbcSMatt Macy 
179eda14cbcSMatt Macy 	return (zch);
180eda14cbcSMatt Macy }
181eda14cbcSMatt Macy 
182eda14cbcSMatt Macy void
zcp_deregister_cleanup(lua_State * state,zcp_cleanup_handler_t * zch)183eda14cbcSMatt Macy zcp_deregister_cleanup(lua_State *state, zcp_cleanup_handler_t *zch)
184eda14cbcSMatt Macy {
185eda14cbcSMatt Macy 	zcp_run_info_t *ri = zcp_run_info(state);
186eda14cbcSMatt Macy 	list_remove(&ri->zri_cleanup_handlers, zch);
187eda14cbcSMatt Macy 	kmem_free(zch, sizeof (*zch));
188eda14cbcSMatt Macy }
189eda14cbcSMatt Macy 
190eda14cbcSMatt Macy /*
191eda14cbcSMatt Macy  * Execute the currently registered cleanup handlers then free them and
192eda14cbcSMatt Macy  * destroy the handler list.
193eda14cbcSMatt Macy  */
194eda14cbcSMatt Macy void
zcp_cleanup(lua_State * state)195eda14cbcSMatt Macy zcp_cleanup(lua_State *state)
196eda14cbcSMatt Macy {
197eda14cbcSMatt Macy 	zcp_run_info_t *ri = zcp_run_info(state);
198eda14cbcSMatt Macy 
199eda14cbcSMatt Macy 	for (zcp_cleanup_handler_t *zch =
200eda14cbcSMatt Macy 	    list_remove_head(&ri->zri_cleanup_handlers); zch != NULL;
201eda14cbcSMatt Macy 	    zch = list_remove_head(&ri->zri_cleanup_handlers)) {
202eda14cbcSMatt Macy 		zch->zch_cleanup_func(zch->zch_cleanup_arg);
203eda14cbcSMatt Macy 		kmem_free(zch, sizeof (*zch));
204eda14cbcSMatt Macy 	}
205eda14cbcSMatt Macy }
206eda14cbcSMatt Macy 
207eda14cbcSMatt Macy /*
208eda14cbcSMatt Macy  * Convert the lua table at the given index on the Lua stack to an nvlist
209eda14cbcSMatt Macy  * and return it.
210eda14cbcSMatt Macy  *
211eda14cbcSMatt Macy  * If the table can not be converted for any reason, NULL is returned and
212eda14cbcSMatt Macy  * an error message is pushed onto the Lua stack.
213eda14cbcSMatt Macy  */
214eda14cbcSMatt Macy static nvlist_t *
zcp_table_to_nvlist(lua_State * state,int index,int depth)215eda14cbcSMatt Macy zcp_table_to_nvlist(lua_State *state, int index, int depth)
216eda14cbcSMatt Macy {
217eda14cbcSMatt Macy 	nvlist_t *nvl;
218eda14cbcSMatt Macy 	/*
219eda14cbcSMatt Macy 	 * Converting a Lua table to an nvlist with key uniqueness checking is
220eda14cbcSMatt Macy 	 * O(n^2) in the number of keys in the nvlist, which can take a long
221eda14cbcSMatt Macy 	 * time when we return a large table from a channel program.
222eda14cbcSMatt Macy 	 * Furthermore, Lua's table interface *almost* guarantees unique keys
223eda14cbcSMatt Macy 	 * on its own (details below). Therefore, we don't use fnvlist_alloc()
224eda14cbcSMatt Macy 	 * here to avoid the built-in uniqueness checking.
225eda14cbcSMatt Macy 	 *
226eda14cbcSMatt Macy 	 * The *almost* is because it's possible to have key collisions between
227eda14cbcSMatt Macy 	 * e.g. the string "1" and the number 1, or the string "true" and the
228eda14cbcSMatt Macy 	 * boolean true, so we explicitly check that when we're looking at a
229eda14cbcSMatt Macy 	 * key which is an integer / boolean or a string that can be parsed as
230eda14cbcSMatt Macy 	 * one of those types. In the worst case this could still devolve into
231eda14cbcSMatt Macy 	 * O(n^2), so we only start doing these checks on boolean/integer keys
232eda14cbcSMatt Macy 	 * once we've seen a string key which fits this weird usage pattern.
233eda14cbcSMatt Macy 	 *
234eda14cbcSMatt Macy 	 * Ultimately, we still want callers to know that the keys in this
235eda14cbcSMatt Macy 	 * nvlist are unique, so before we return this we set the nvlist's
236eda14cbcSMatt Macy 	 * flags to reflect that.
237eda14cbcSMatt Macy 	 */
238eda14cbcSMatt Macy 	VERIFY0(nvlist_alloc(&nvl, 0, KM_SLEEP));
239eda14cbcSMatt Macy 
240eda14cbcSMatt Macy 	/*
241eda14cbcSMatt Macy 	 * Push an empty stack slot where lua_next() will store each
242eda14cbcSMatt Macy 	 * table key.
243eda14cbcSMatt Macy 	 */
244eda14cbcSMatt Macy 	lua_pushnil(state);
245eda14cbcSMatt Macy 	boolean_t saw_str_could_collide = B_FALSE;
246eda14cbcSMatt Macy 	while (lua_next(state, index) != 0) {
247eda14cbcSMatt Macy 		/*
248eda14cbcSMatt Macy 		 * The next key-value pair from the table at index is
249eda14cbcSMatt Macy 		 * now on the stack, with the key at stack slot -2 and
250eda14cbcSMatt Macy 		 * the value at slot -1.
251eda14cbcSMatt Macy 		 */
252eda14cbcSMatt Macy 		int err = 0;
253eda14cbcSMatt Macy 		char buf[32];
254eda14cbcSMatt Macy 		const char *key = NULL;
255eda14cbcSMatt Macy 		boolean_t key_could_collide = B_FALSE;
256eda14cbcSMatt Macy 
257eda14cbcSMatt Macy 		switch (lua_type(state, -2)) {
258eda14cbcSMatt Macy 		case LUA_TSTRING:
259eda14cbcSMatt Macy 			key = lua_tostring(state, -2);
260eda14cbcSMatt Macy 
261eda14cbcSMatt Macy 			/* check if this could collide with a number or bool */
262eda14cbcSMatt Macy 			long long tmp;
263eda14cbcSMatt Macy 			int parselen;
264eda14cbcSMatt Macy 			if ((sscanf(key, "%lld%n", &tmp, &parselen) > 0 &&
265eda14cbcSMatt Macy 			    parselen == strlen(key)) ||
266eda14cbcSMatt Macy 			    strcmp(key, "true") == 0 ||
267eda14cbcSMatt Macy 			    strcmp(key, "false") == 0) {
268eda14cbcSMatt Macy 				key_could_collide = B_TRUE;
269eda14cbcSMatt Macy 				saw_str_could_collide = B_TRUE;
270eda14cbcSMatt Macy 			}
271eda14cbcSMatt Macy 			break;
272eda14cbcSMatt Macy 		case LUA_TBOOLEAN:
273eda14cbcSMatt Macy 			key = (lua_toboolean(state, -2) == B_TRUE ?
274eda14cbcSMatt Macy 			    "true" : "false");
275eda14cbcSMatt Macy 			if (saw_str_could_collide) {
276eda14cbcSMatt Macy 				key_could_collide = B_TRUE;
277eda14cbcSMatt Macy 			}
278eda14cbcSMatt Macy 			break;
279eda14cbcSMatt Macy 		case LUA_TNUMBER:
280dbd5678dSMartin Matuska 			(void) snprintf(buf, sizeof (buf), "%lld",
281dbd5678dSMartin Matuska 			    (longlong_t)lua_tonumber(state, -2));
282dbd5678dSMartin Matuska 
283eda14cbcSMatt Macy 			key = buf;
284eda14cbcSMatt Macy 			if (saw_str_could_collide) {
285eda14cbcSMatt Macy 				key_could_collide = B_TRUE;
286eda14cbcSMatt Macy 			}
287eda14cbcSMatt Macy 			break;
288eda14cbcSMatt Macy 		default:
289eda14cbcSMatt Macy 			fnvlist_free(nvl);
290eda14cbcSMatt Macy 			(void) lua_pushfstring(state, "Invalid key "
291eda14cbcSMatt Macy 			    "type '%s' in table",
292eda14cbcSMatt Macy 			    lua_typename(state, lua_type(state, -2)));
293eda14cbcSMatt Macy 			return (NULL);
294eda14cbcSMatt Macy 		}
295eda14cbcSMatt Macy 		/*
296eda14cbcSMatt Macy 		 * Check for type-mismatched key collisions, and throw an error.
297eda14cbcSMatt Macy 		 */
298eda14cbcSMatt Macy 		if (key_could_collide && nvlist_exists(nvl, key)) {
299eda14cbcSMatt Macy 			fnvlist_free(nvl);
300eda14cbcSMatt Macy 			(void) lua_pushfstring(state, "Collision of "
301eda14cbcSMatt Macy 			    "key '%s' in table", key);
302eda14cbcSMatt Macy 			return (NULL);
303eda14cbcSMatt Macy 		}
304eda14cbcSMatt Macy 		/*
305eda14cbcSMatt Macy 		 * Recursively convert the table value and insert into
306eda14cbcSMatt Macy 		 * the new nvlist with the parsed key.  To prevent
307eda14cbcSMatt Macy 		 * stack overflow on circular or heavily nested tables,
308eda14cbcSMatt Macy 		 * we track the current nvlist depth.
309eda14cbcSMatt Macy 		 */
310eda14cbcSMatt Macy 		if (depth >= ZCP_NVLIST_MAX_DEPTH) {
311eda14cbcSMatt Macy 			fnvlist_free(nvl);
312eda14cbcSMatt Macy 			(void) lua_pushfstring(state, "Maximum table "
313eda14cbcSMatt Macy 			    "depth (%d) exceeded for table",
314eda14cbcSMatt Macy 			    ZCP_NVLIST_MAX_DEPTH);
315eda14cbcSMatt Macy 			return (NULL);
316eda14cbcSMatt Macy 		}
317eda14cbcSMatt Macy 		err = zcp_lua_to_nvlist_impl(state, -1, nvl, key,
318eda14cbcSMatt Macy 		    depth + 1);
319eda14cbcSMatt Macy 		if (err != 0) {
320eda14cbcSMatt Macy 			fnvlist_free(nvl);
321eda14cbcSMatt Macy 			/*
322eda14cbcSMatt Macy 			 * Error message has been pushed to the lua
323eda14cbcSMatt Macy 			 * stack by the recursive call.
324eda14cbcSMatt Macy 			 */
325eda14cbcSMatt Macy 			return (NULL);
326eda14cbcSMatt Macy 		}
327eda14cbcSMatt Macy 		/*
328eda14cbcSMatt Macy 		 * Pop the value pushed by lua_next().
329eda14cbcSMatt Macy 		 */
330eda14cbcSMatt Macy 		lua_pop(state, 1);
331eda14cbcSMatt Macy 	}
332eda14cbcSMatt Macy 
333eda14cbcSMatt Macy 	/*
334eda14cbcSMatt Macy 	 * Mark the nvlist as having unique keys. This is a little ugly, but we
335eda14cbcSMatt Macy 	 * ensured above that there are no duplicate keys in the nvlist.
336eda14cbcSMatt Macy 	 */
337eda14cbcSMatt Macy 	nvl->nvl_nvflag |= NV_UNIQUE_NAME;
338eda14cbcSMatt Macy 
339eda14cbcSMatt Macy 	return (nvl);
340eda14cbcSMatt Macy }
341eda14cbcSMatt Macy 
342eda14cbcSMatt Macy /*
343eda14cbcSMatt Macy  * Convert a value from the given index into the lua stack to an nvpair, adding
344eda14cbcSMatt Macy  * it to an nvlist with the given key.
345eda14cbcSMatt Macy  *
346eda14cbcSMatt Macy  * Values are converted as follows:
347eda14cbcSMatt Macy  *
348eda14cbcSMatt Macy  *   string -> string
349eda14cbcSMatt Macy  *   number -> int64
350eda14cbcSMatt Macy  *   boolean -> boolean
351eda14cbcSMatt Macy  *   nil -> boolean (no value)
352eda14cbcSMatt Macy  *
353eda14cbcSMatt Macy  * Lua tables are converted to nvlists and then inserted. The table's keys
354eda14cbcSMatt Macy  * are converted to strings then used as keys in the nvlist to store each table
355eda14cbcSMatt Macy  * element.  Keys are converted as follows:
356eda14cbcSMatt Macy  *
357eda14cbcSMatt Macy  *   string -> no change
358eda14cbcSMatt Macy  *   number -> "%lld"
359eda14cbcSMatt Macy  *   boolean -> "true" | "false"
360eda14cbcSMatt Macy  *   nil -> error
361eda14cbcSMatt Macy  *
362eda14cbcSMatt Macy  * In the case of a key collision, an error is thrown.
363eda14cbcSMatt Macy  *
364eda14cbcSMatt Macy  * If an error is encountered, a nonzero error code is returned, and an error
365eda14cbcSMatt Macy  * string will be pushed onto the Lua stack.
366eda14cbcSMatt Macy  */
367eda14cbcSMatt Macy static int
zcp_lua_to_nvlist_impl(lua_State * state,int index,nvlist_t * nvl,const char * key,int depth)368eda14cbcSMatt Macy zcp_lua_to_nvlist_impl(lua_State *state, int index, nvlist_t *nvl,
369eda14cbcSMatt Macy     const char *key, int depth)
370eda14cbcSMatt Macy {
371eda14cbcSMatt Macy 	/*
372eda14cbcSMatt Macy 	 * Verify that we have enough remaining space in the lua stack to parse
373eda14cbcSMatt Macy 	 * a key-value pair and push an error.
374eda14cbcSMatt Macy 	 */
375eda14cbcSMatt Macy 	if (!lua_checkstack(state, 3)) {
376eda14cbcSMatt Macy 		(void) lua_pushstring(state, "Lua stack overflow");
377eda14cbcSMatt Macy 		return (1);
378eda14cbcSMatt Macy 	}
379eda14cbcSMatt Macy 
380eda14cbcSMatt Macy 	index = lua_absindex(state, index);
381eda14cbcSMatt Macy 
382eda14cbcSMatt Macy 	switch (lua_type(state, index)) {
383eda14cbcSMatt Macy 	case LUA_TNIL:
384eda14cbcSMatt Macy 		fnvlist_add_boolean(nvl, key);
385eda14cbcSMatt Macy 		break;
386eda14cbcSMatt Macy 	case LUA_TBOOLEAN:
387eda14cbcSMatt Macy 		fnvlist_add_boolean_value(nvl, key,
388eda14cbcSMatt Macy 		    lua_toboolean(state, index));
389eda14cbcSMatt Macy 		break;
390eda14cbcSMatt Macy 	case LUA_TNUMBER:
391eda14cbcSMatt Macy 		fnvlist_add_int64(nvl, key, lua_tonumber(state, index));
392eda14cbcSMatt Macy 		break;
393eda14cbcSMatt Macy 	case LUA_TSTRING:
394eda14cbcSMatt Macy 		fnvlist_add_string(nvl, key, lua_tostring(state, index));
395eda14cbcSMatt Macy 		break;
396eda14cbcSMatt Macy 	case LUA_TTABLE: {
397eda14cbcSMatt Macy 		nvlist_t *value_nvl = zcp_table_to_nvlist(state, index, depth);
398eda14cbcSMatt Macy 		if (value_nvl == NULL)
399eda14cbcSMatt Macy 			return (SET_ERROR(EINVAL));
400eda14cbcSMatt Macy 
401eda14cbcSMatt Macy 		fnvlist_add_nvlist(nvl, key, value_nvl);
402eda14cbcSMatt Macy 		fnvlist_free(value_nvl);
403eda14cbcSMatt Macy 		break;
404eda14cbcSMatt Macy 	}
405eda14cbcSMatt Macy 	default:
406eda14cbcSMatt Macy 		(void) lua_pushfstring(state,
407eda14cbcSMatt Macy 		    "Invalid value type '%s' for key '%s'",
408eda14cbcSMatt Macy 		    lua_typename(state, lua_type(state, index)), key);
409eda14cbcSMatt Macy 		return (SET_ERROR(EINVAL));
410eda14cbcSMatt Macy 	}
411eda14cbcSMatt Macy 
412eda14cbcSMatt Macy 	return (0);
413eda14cbcSMatt Macy }
414eda14cbcSMatt Macy 
415eda14cbcSMatt Macy /*
416eda14cbcSMatt Macy  * Convert a lua value to an nvpair, adding it to an nvlist with the given key.
417eda14cbcSMatt Macy  */
418eda14cbcSMatt Macy static void
zcp_lua_to_nvlist(lua_State * state,int index,nvlist_t * nvl,const char * key)419eda14cbcSMatt Macy zcp_lua_to_nvlist(lua_State *state, int index, nvlist_t *nvl, const char *key)
420eda14cbcSMatt Macy {
421eda14cbcSMatt Macy 	/*
422eda14cbcSMatt Macy 	 * On error, zcp_lua_to_nvlist_impl pushes an error string onto the Lua
423eda14cbcSMatt Macy 	 * stack before returning with a nonzero error code. If an error is
424eda14cbcSMatt Macy 	 * returned, throw a fatal lua error with the given string.
425eda14cbcSMatt Macy 	 */
426eda14cbcSMatt Macy 	if (zcp_lua_to_nvlist_impl(state, index, nvl, key, 0) != 0)
427eda14cbcSMatt Macy 		(void) lua_error(state);
428eda14cbcSMatt Macy }
429eda14cbcSMatt Macy 
430eda14cbcSMatt Macy static int
zcp_lua_to_nvlist_helper(lua_State * state)431eda14cbcSMatt Macy zcp_lua_to_nvlist_helper(lua_State *state)
432eda14cbcSMatt Macy {
433eda14cbcSMatt Macy 	nvlist_t *nv = (nvlist_t *)lua_touserdata(state, 2);
434eda14cbcSMatt Macy 	const char *key = (const char *)lua_touserdata(state, 1);
435eda14cbcSMatt Macy 	zcp_lua_to_nvlist(state, 3, nv, key);
436eda14cbcSMatt Macy 	return (0);
437eda14cbcSMatt Macy }
438eda14cbcSMatt Macy 
439eda14cbcSMatt Macy static void
zcp_convert_return_values(lua_State * state,nvlist_t * nvl,const char * key,int * result)440eda14cbcSMatt Macy zcp_convert_return_values(lua_State *state, nvlist_t *nvl,
441eda14cbcSMatt Macy     const char *key, int *result)
442eda14cbcSMatt Macy {
443eda14cbcSMatt Macy 	int err;
444eda14cbcSMatt Macy 	VERIFY3U(1, ==, lua_gettop(state));
445eda14cbcSMatt Macy 	lua_pushcfunction(state, zcp_lua_to_nvlist_helper);
446eda14cbcSMatt Macy 	lua_pushlightuserdata(state, (char *)key);
447eda14cbcSMatt Macy 	lua_pushlightuserdata(state, nvl);
448eda14cbcSMatt Macy 	lua_pushvalue(state, 1);
449eda14cbcSMatt Macy 	lua_remove(state, 1);
450eda14cbcSMatt Macy 	err = lua_pcall(state, 3, 0, 0); /* zcp_lua_to_nvlist_helper */
451eda14cbcSMatt Macy 	if (err != 0) {
452eda14cbcSMatt Macy 		zcp_lua_to_nvlist(state, 1, nvl, ZCP_RET_ERROR);
453eda14cbcSMatt Macy 		*result = SET_ERROR(ECHRNG);
454eda14cbcSMatt Macy 	}
455eda14cbcSMatt Macy }
456eda14cbcSMatt Macy 
457eda14cbcSMatt Macy /*
458eda14cbcSMatt Macy  * Push a Lua table representing nvl onto the stack.  If it can't be
459eda14cbcSMatt Macy  * converted, return EINVAL, fill in errbuf, and push nothing. errbuf may
460eda14cbcSMatt Macy  * be specified as NULL, in which case no error string will be output.
461eda14cbcSMatt Macy  *
462eda14cbcSMatt Macy  * Most nvlists are converted as simple key->value Lua tables, but we make
463eda14cbcSMatt Macy  * an exception for the case where all nvlist entries are BOOLEANs (a string
464eda14cbcSMatt Macy  * key without a value). In Lua, a table key pointing to a value of Nil
465eda14cbcSMatt Macy  * (no value) is equivalent to the key not existing, so a BOOLEAN nvlist
466eda14cbcSMatt Macy  * entry can't be directly converted to a Lua table entry. Nvlists of entirely
467eda14cbcSMatt Macy  * BOOLEAN entries are frequently used to pass around lists of datasets, so for
468eda14cbcSMatt Macy  * convenience we check for this case, and convert it to a simple Lua array of
469eda14cbcSMatt Macy  * strings.
470eda14cbcSMatt Macy  */
471eda14cbcSMatt Macy int
zcp_nvlist_to_lua(lua_State * state,nvlist_t * nvl,char * errbuf,int errbuf_len)472eda14cbcSMatt Macy zcp_nvlist_to_lua(lua_State *state, nvlist_t *nvl,
473eda14cbcSMatt Macy     char *errbuf, int errbuf_len)
474eda14cbcSMatt Macy {
475eda14cbcSMatt Macy 	nvpair_t *pair;
476eda14cbcSMatt Macy 	lua_newtable(state);
477eda14cbcSMatt Macy 	boolean_t has_values = B_FALSE;
478eda14cbcSMatt Macy 	/*
479eda14cbcSMatt Macy 	 * If the list doesn't have any values, just convert it to a string
480eda14cbcSMatt Macy 	 * array.
481eda14cbcSMatt Macy 	 */
482eda14cbcSMatt Macy 	for (pair = nvlist_next_nvpair(nvl, NULL);
483eda14cbcSMatt Macy 	    pair != NULL; pair = nvlist_next_nvpair(nvl, pair)) {
484eda14cbcSMatt Macy 		if (nvpair_type(pair) != DATA_TYPE_BOOLEAN) {
485eda14cbcSMatt Macy 			has_values = B_TRUE;
486eda14cbcSMatt Macy 			break;
487eda14cbcSMatt Macy 		}
488eda14cbcSMatt Macy 	}
489eda14cbcSMatt Macy 	if (!has_values) {
490eda14cbcSMatt Macy 		int i = 1;
491eda14cbcSMatt Macy 		for (pair = nvlist_next_nvpair(nvl, NULL);
492eda14cbcSMatt Macy 		    pair != NULL; pair = nvlist_next_nvpair(nvl, pair)) {
493eda14cbcSMatt Macy 			(void) lua_pushinteger(state, i);
494eda14cbcSMatt Macy 			(void) lua_pushstring(state, nvpair_name(pair));
495eda14cbcSMatt Macy 			(void) lua_settable(state, -3);
496eda14cbcSMatt Macy 			i++;
497eda14cbcSMatt Macy 		}
498eda14cbcSMatt Macy 	} else {
499eda14cbcSMatt Macy 		for (pair = nvlist_next_nvpair(nvl, NULL);
500eda14cbcSMatt Macy 		    pair != NULL; pair = nvlist_next_nvpair(nvl, pair)) {
501eda14cbcSMatt Macy 			int err = zcp_nvpair_value_to_lua(state, pair,
502eda14cbcSMatt Macy 			    errbuf, errbuf_len);
503eda14cbcSMatt Macy 			if (err != 0) {
504eda14cbcSMatt Macy 				lua_pop(state, 1);
505eda14cbcSMatt Macy 				return (err);
506eda14cbcSMatt Macy 			}
507eda14cbcSMatt Macy 			(void) lua_setfield(state, -2, nvpair_name(pair));
508eda14cbcSMatt Macy 		}
509eda14cbcSMatt Macy 	}
510eda14cbcSMatt Macy 	return (0);
511eda14cbcSMatt Macy }
512eda14cbcSMatt Macy 
513eda14cbcSMatt Macy /*
514eda14cbcSMatt Macy  * Push a Lua object representing the value of "pair" onto the stack.
515eda14cbcSMatt Macy  *
516eda14cbcSMatt Macy  * Only understands boolean_value, string, int64, nvlist,
517eda14cbcSMatt Macy  * string_array, and int64_array type values.  For other
518eda14cbcSMatt Macy  * types, returns EINVAL, fills in errbuf, and pushes nothing.
519eda14cbcSMatt Macy  */
520eda14cbcSMatt Macy static int
zcp_nvpair_value_to_lua(lua_State * state,nvpair_t * pair,char * errbuf,int errbuf_len)521eda14cbcSMatt Macy zcp_nvpair_value_to_lua(lua_State *state, nvpair_t *pair,
522eda14cbcSMatt Macy     char *errbuf, int errbuf_len)
523eda14cbcSMatt Macy {
524eda14cbcSMatt Macy 	int err = 0;
525eda14cbcSMatt Macy 
526eda14cbcSMatt Macy 	if (pair == NULL) {
527eda14cbcSMatt Macy 		lua_pushnil(state);
528eda14cbcSMatt Macy 		return (0);
529eda14cbcSMatt Macy 	}
530eda14cbcSMatt Macy 
531eda14cbcSMatt Macy 	switch (nvpair_type(pair)) {
532eda14cbcSMatt Macy 	case DATA_TYPE_BOOLEAN_VALUE:
533eda14cbcSMatt Macy 		(void) lua_pushboolean(state,
534eda14cbcSMatt Macy 		    fnvpair_value_boolean_value(pair));
535eda14cbcSMatt Macy 		break;
536eda14cbcSMatt Macy 	case DATA_TYPE_STRING:
537eda14cbcSMatt Macy 		(void) lua_pushstring(state, fnvpair_value_string(pair));
538eda14cbcSMatt Macy 		break;
539eda14cbcSMatt Macy 	case DATA_TYPE_INT64:
540eda14cbcSMatt Macy 		(void) lua_pushinteger(state, fnvpair_value_int64(pair));
541eda14cbcSMatt Macy 		break;
542eda14cbcSMatt Macy 	case DATA_TYPE_NVLIST:
543eda14cbcSMatt Macy 		err = zcp_nvlist_to_lua(state,
544eda14cbcSMatt Macy 		    fnvpair_value_nvlist(pair), errbuf, errbuf_len);
545eda14cbcSMatt Macy 		break;
546eda14cbcSMatt Macy 	case DATA_TYPE_STRING_ARRAY: {
5472a58b312SMartin Matuska 		const char **strarr;
548eda14cbcSMatt Macy 		uint_t nelem;
549eda14cbcSMatt Macy 		(void) nvpair_value_string_array(pair, &strarr, &nelem);
550eda14cbcSMatt Macy 		lua_newtable(state);
551eda14cbcSMatt Macy 		for (int i = 0; i < nelem; i++) {
552eda14cbcSMatt Macy 			(void) lua_pushinteger(state, i + 1);
553eda14cbcSMatt Macy 			(void) lua_pushstring(state, strarr[i]);
554eda14cbcSMatt Macy 			(void) lua_settable(state, -3);
555eda14cbcSMatt Macy 		}
556eda14cbcSMatt Macy 		break;
557eda14cbcSMatt Macy 	}
558eda14cbcSMatt Macy 	case DATA_TYPE_UINT64_ARRAY: {
559eda14cbcSMatt Macy 		uint64_t *intarr;
560eda14cbcSMatt Macy 		uint_t nelem;
561eda14cbcSMatt Macy 		(void) nvpair_value_uint64_array(pair, &intarr, &nelem);
562eda14cbcSMatt Macy 		lua_newtable(state);
563eda14cbcSMatt Macy 		for (int i = 0; i < nelem; i++) {
564eda14cbcSMatt Macy 			(void) lua_pushinteger(state, i + 1);
565eda14cbcSMatt Macy 			(void) lua_pushinteger(state, intarr[i]);
566eda14cbcSMatt Macy 			(void) lua_settable(state, -3);
567eda14cbcSMatt Macy 		}
568eda14cbcSMatt Macy 		break;
569eda14cbcSMatt Macy 	}
570eda14cbcSMatt Macy 	case DATA_TYPE_INT64_ARRAY: {
571eda14cbcSMatt Macy 		int64_t *intarr;
572eda14cbcSMatt Macy 		uint_t nelem;
573eda14cbcSMatt Macy 		(void) nvpair_value_int64_array(pair, &intarr, &nelem);
574eda14cbcSMatt Macy 		lua_newtable(state);
575eda14cbcSMatt Macy 		for (int i = 0; i < nelem; i++) {
576eda14cbcSMatt Macy 			(void) lua_pushinteger(state, i + 1);
577eda14cbcSMatt Macy 			(void) lua_pushinteger(state, intarr[i]);
578eda14cbcSMatt Macy 			(void) lua_settable(state, -3);
579eda14cbcSMatt Macy 		}
580eda14cbcSMatt Macy 		break;
581eda14cbcSMatt Macy 	}
582eda14cbcSMatt Macy 	default: {
583eda14cbcSMatt Macy 		if (errbuf != NULL) {
584eda14cbcSMatt Macy 			(void) snprintf(errbuf, errbuf_len,
585eda14cbcSMatt Macy 			    "Unhandled nvpair type %d for key '%s'",
586eda14cbcSMatt Macy 			    nvpair_type(pair), nvpair_name(pair));
587eda14cbcSMatt Macy 		}
588eda14cbcSMatt Macy 		return (SET_ERROR(EINVAL));
589eda14cbcSMatt Macy 	}
590eda14cbcSMatt Macy 	}
591eda14cbcSMatt Macy 	return (err);
592eda14cbcSMatt Macy }
593eda14cbcSMatt Macy 
594eda14cbcSMatt Macy int
zcp_dataset_hold_error(lua_State * state,dsl_pool_t * dp,const char * dsname,int error)595eda14cbcSMatt Macy zcp_dataset_hold_error(lua_State *state, dsl_pool_t *dp, const char *dsname,
596eda14cbcSMatt Macy     int error)
597eda14cbcSMatt Macy {
598eda14cbcSMatt Macy 	if (error == ENOENT) {
599eda14cbcSMatt Macy 		(void) zcp_argerror(state, 1, "no such dataset '%s'", dsname);
600eda14cbcSMatt Macy 		return (0); /* not reached; zcp_argerror will longjmp */
601eda14cbcSMatt Macy 	} else if (error == EXDEV) {
602eda14cbcSMatt Macy 		(void) zcp_argerror(state, 1,
603eda14cbcSMatt Macy 		    "dataset '%s' is not in the target pool '%s'",
604eda14cbcSMatt Macy 		    dsname, spa_name(dp->dp_spa));
605eda14cbcSMatt Macy 		return (0); /* not reached; zcp_argerror will longjmp */
606eda14cbcSMatt Macy 	} else if (error == EIO) {
607eda14cbcSMatt Macy 		(void) luaL_error(state,
608eda14cbcSMatt Macy 		    "I/O error while accessing dataset '%s'", dsname);
609eda14cbcSMatt Macy 		return (0); /* not reached; luaL_error will longjmp */
610eda14cbcSMatt Macy 	} else if (error != 0) {
611eda14cbcSMatt Macy 		(void) luaL_error(state,
612eda14cbcSMatt Macy 		    "unexpected error %d while accessing dataset '%s'",
613eda14cbcSMatt Macy 		    error, dsname);
614eda14cbcSMatt Macy 		return (0); /* not reached; luaL_error will longjmp */
615eda14cbcSMatt Macy 	}
616eda14cbcSMatt Macy 	return (0);
617eda14cbcSMatt Macy }
618eda14cbcSMatt Macy 
619eda14cbcSMatt Macy /*
620eda14cbcSMatt Macy  * Note: will longjmp (via lua_error()) on error.
621eda14cbcSMatt Macy  * Assumes that the dsname is argument #1 (for error reporting purposes).
622eda14cbcSMatt Macy  */
623eda14cbcSMatt Macy dsl_dataset_t *
zcp_dataset_hold(lua_State * state,dsl_pool_t * dp,const char * dsname,const void * tag)624eda14cbcSMatt Macy zcp_dataset_hold(lua_State *state, dsl_pool_t *dp, const char *dsname,
625a0b956f5SMartin Matuska     const void *tag)
626eda14cbcSMatt Macy {
627eda14cbcSMatt Macy 	dsl_dataset_t *ds;
628eda14cbcSMatt Macy 	int error = dsl_dataset_hold(dp, dsname, tag, &ds);
629eda14cbcSMatt Macy 	(void) zcp_dataset_hold_error(state, dp, dsname, error);
630eda14cbcSMatt Macy 	return (ds);
631eda14cbcSMatt Macy }
632eda14cbcSMatt Macy 
633eda14cbcSMatt Macy static int zcp_debug(lua_State *);
634e92ffd9bSMartin Matuska static const zcp_lib_info_t zcp_debug_info = {
635eda14cbcSMatt Macy 	.name = "debug",
636eda14cbcSMatt Macy 	.func = zcp_debug,
637eda14cbcSMatt Macy 	.pargs = {
638eda14cbcSMatt Macy 	    { .za_name = "debug string", .za_lua_type = LUA_TSTRING },
639eda14cbcSMatt Macy 	    {NULL, 0}
640eda14cbcSMatt Macy 	},
641eda14cbcSMatt Macy 	.kwargs = {
642eda14cbcSMatt Macy 	    {NULL, 0}
643eda14cbcSMatt Macy 	}
644eda14cbcSMatt Macy };
645eda14cbcSMatt Macy 
646eda14cbcSMatt Macy static int
zcp_debug(lua_State * state)647eda14cbcSMatt Macy zcp_debug(lua_State *state)
648eda14cbcSMatt Macy {
649eda14cbcSMatt Macy 	const char *dbgstring;
650eda14cbcSMatt Macy 	zcp_run_info_t *ri = zcp_run_info(state);
651e92ffd9bSMartin Matuska 	const zcp_lib_info_t *libinfo = &zcp_debug_info;
652eda14cbcSMatt Macy 
653eda14cbcSMatt Macy 	zcp_parse_args(state, libinfo->name, libinfo->pargs, libinfo->kwargs);
654eda14cbcSMatt Macy 
655eda14cbcSMatt Macy 	dbgstring = lua_tostring(state, 1);
656eda14cbcSMatt Macy 
65733b8c039SMartin Matuska 	zfs_dbgmsg("txg %lld ZCP: %s", (longlong_t)ri->zri_tx->tx_txg,
65833b8c039SMartin Matuska 	    dbgstring);
659eda14cbcSMatt Macy 
660eda14cbcSMatt Macy 	return (0);
661eda14cbcSMatt Macy }
662eda14cbcSMatt Macy 
663eda14cbcSMatt Macy static int zcp_exists(lua_State *);
664e92ffd9bSMartin Matuska static const zcp_lib_info_t zcp_exists_info = {
665eda14cbcSMatt Macy 	.name = "exists",
666eda14cbcSMatt Macy 	.func = zcp_exists,
667eda14cbcSMatt Macy 	.pargs = {
668eda14cbcSMatt Macy 	    { .za_name = "dataset", .za_lua_type = LUA_TSTRING },
669eda14cbcSMatt Macy 	    {NULL, 0}
670eda14cbcSMatt Macy 	},
671eda14cbcSMatt Macy 	.kwargs = {
672eda14cbcSMatt Macy 	    {NULL, 0}
673eda14cbcSMatt Macy 	}
674eda14cbcSMatt Macy };
675eda14cbcSMatt Macy 
676eda14cbcSMatt Macy static int
zcp_exists(lua_State * state)677eda14cbcSMatt Macy zcp_exists(lua_State *state)
678eda14cbcSMatt Macy {
679eda14cbcSMatt Macy 	zcp_run_info_t *ri = zcp_run_info(state);
680eda14cbcSMatt Macy 	dsl_pool_t *dp = ri->zri_pool;
681e92ffd9bSMartin Matuska 	const zcp_lib_info_t *libinfo = &zcp_exists_info;
682eda14cbcSMatt Macy 
683eda14cbcSMatt Macy 	zcp_parse_args(state, libinfo->name, libinfo->pargs, libinfo->kwargs);
684eda14cbcSMatt Macy 
685eda14cbcSMatt Macy 	const char *dsname = lua_tostring(state, 1);
686eda14cbcSMatt Macy 
687eda14cbcSMatt Macy 	dsl_dataset_t *ds;
688eda14cbcSMatt Macy 	int error = dsl_dataset_hold(dp, dsname, FTAG, &ds);
689eda14cbcSMatt Macy 	if (error == 0) {
690eda14cbcSMatt Macy 		dsl_dataset_rele(ds, FTAG);
691eda14cbcSMatt Macy 		lua_pushboolean(state, B_TRUE);
692eda14cbcSMatt Macy 	} else if (error == ENOENT) {
693eda14cbcSMatt Macy 		lua_pushboolean(state, B_FALSE);
694eda14cbcSMatt Macy 	} else if (error == EXDEV) {
695eda14cbcSMatt Macy 		return (luaL_error(state, "dataset '%s' is not in the "
696eda14cbcSMatt Macy 		    "target pool", dsname));
697eda14cbcSMatt Macy 	} else if (error == EIO) {
698eda14cbcSMatt Macy 		return (luaL_error(state, "I/O error opening dataset '%s'",
699eda14cbcSMatt Macy 		    dsname));
700eda14cbcSMatt Macy 	} else if (error != 0) {
701eda14cbcSMatt Macy 		return (luaL_error(state, "unexpected error %d", error));
702eda14cbcSMatt Macy 	}
703eda14cbcSMatt Macy 
704eda14cbcSMatt Macy 	return (1);
705eda14cbcSMatt Macy }
706eda14cbcSMatt Macy 
707eda14cbcSMatt Macy /*
708eda14cbcSMatt Macy  * Allocate/realloc/free a buffer for the lua interpreter.
709eda14cbcSMatt Macy  *
710eda14cbcSMatt Macy  * When nsize is 0, behaves as free() and returns NULL.
711eda14cbcSMatt Macy  *
712eda14cbcSMatt Macy  * If ptr is NULL, behaves as malloc() and returns an allocated buffer of size
713eda14cbcSMatt Macy  * at least nsize.
714eda14cbcSMatt Macy  *
715eda14cbcSMatt Macy  * Otherwise, behaves as realloc(), changing the allocation from osize to nsize.
716eda14cbcSMatt Macy  * Shrinking the buffer size never fails.
717eda14cbcSMatt Macy  *
718eda14cbcSMatt Macy  * The original allocated buffer size is stored as a uint64 at the beginning of
719eda14cbcSMatt Macy  * the buffer to avoid actually reallocating when shrinking a buffer, since lua
720eda14cbcSMatt Macy  * requires that this operation never fail.
721eda14cbcSMatt Macy  */
722eda14cbcSMatt Macy static void *
zcp_lua_alloc(void * ud,void * ptr,size_t osize,size_t nsize)723eda14cbcSMatt Macy zcp_lua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
724eda14cbcSMatt Macy {
725eda14cbcSMatt Macy 	zcp_alloc_arg_t *allocargs = ud;
726eda14cbcSMatt Macy 
727eda14cbcSMatt Macy 	if (nsize == 0) {
728eda14cbcSMatt Macy 		if (ptr != NULL) {
729eda14cbcSMatt Macy 			int64_t *allocbuf = (int64_t *)ptr - 1;
730eda14cbcSMatt Macy 			int64_t allocsize = *allocbuf;
731eda14cbcSMatt Macy 			ASSERT3S(allocsize, >, 0);
732eda14cbcSMatt Macy 			ASSERT3S(allocargs->aa_alloc_remaining + allocsize, <=,
733eda14cbcSMatt Macy 			    allocargs->aa_alloc_limit);
734eda14cbcSMatt Macy 			allocargs->aa_alloc_remaining += allocsize;
735eda14cbcSMatt Macy 			vmem_free(allocbuf, allocsize);
736eda14cbcSMatt Macy 		}
737eda14cbcSMatt Macy 		return (NULL);
738eda14cbcSMatt Macy 	} else if (ptr == NULL) {
739eda14cbcSMatt Macy 		int64_t *allocbuf;
740eda14cbcSMatt Macy 		int64_t allocsize = nsize + sizeof (int64_t);
741eda14cbcSMatt Macy 
742eda14cbcSMatt Macy 		if (!allocargs->aa_must_succeed &&
743eda14cbcSMatt Macy 		    (allocsize <= 0 ||
744eda14cbcSMatt Macy 		    allocsize > allocargs->aa_alloc_remaining)) {
745eda14cbcSMatt Macy 			return (NULL);
746eda14cbcSMatt Macy 		}
747eda14cbcSMatt Macy 
7487877fdebSMatt Macy 		allocbuf = vmem_alloc(allocsize, KM_SLEEP);
749eda14cbcSMatt Macy 		allocargs->aa_alloc_remaining -= allocsize;
750eda14cbcSMatt Macy 
751eda14cbcSMatt Macy 		*allocbuf = allocsize;
752eda14cbcSMatt Macy 		return (allocbuf + 1);
753eda14cbcSMatt Macy 	} else if (nsize <= osize) {
754eda14cbcSMatt Macy 		/*
755eda14cbcSMatt Macy 		 * If shrinking the buffer, lua requires that the reallocation
756eda14cbcSMatt Macy 		 * never fail.
757eda14cbcSMatt Macy 		 */
758eda14cbcSMatt Macy 		return (ptr);
759eda14cbcSMatt Macy 	} else {
760eda14cbcSMatt Macy 		ASSERT3U(nsize, >, osize);
761eda14cbcSMatt Macy 
762eda14cbcSMatt Macy 		uint64_t *luabuf = zcp_lua_alloc(ud, NULL, 0, nsize);
763eda14cbcSMatt Macy 		if (luabuf == NULL) {
764eda14cbcSMatt Macy 			return (NULL);
765eda14cbcSMatt Macy 		}
766eda14cbcSMatt Macy 		(void) memcpy(luabuf, ptr, osize);
767eda14cbcSMatt Macy 		VERIFY3P(zcp_lua_alloc(ud, ptr, osize, 0), ==, NULL);
768eda14cbcSMatt Macy 		return (luabuf);
769eda14cbcSMatt Macy 	}
770eda14cbcSMatt Macy }
771eda14cbcSMatt Macy 
772eda14cbcSMatt Macy static void
zcp_lua_counthook(lua_State * state,lua_Debug * ar)773eda14cbcSMatt Macy zcp_lua_counthook(lua_State *state, lua_Debug *ar)
774eda14cbcSMatt Macy {
775e92ffd9bSMartin Matuska 	(void) ar;
776eda14cbcSMatt Macy 	lua_getfield(state, LUA_REGISTRYINDEX, ZCP_RUN_INFO_KEY);
777eda14cbcSMatt Macy 	zcp_run_info_t *ri = lua_touserdata(state, -1);
778eda14cbcSMatt Macy 
779eda14cbcSMatt Macy 	/*
780eda14cbcSMatt Macy 	 * Check if we were canceled while waiting for the
781eda14cbcSMatt Macy 	 * txg to sync or from our open context thread
782eda14cbcSMatt Macy 	 */
783*aca928a5SMartin Matuska 	if (ri->zri_canceled || (!ri->zri_sync && issig())) {
784eda14cbcSMatt Macy 		ri->zri_canceled = B_TRUE;
785eda14cbcSMatt Macy 		(void) lua_pushstring(state, "Channel program was canceled.");
786eda14cbcSMatt Macy 		(void) lua_error(state);
787eda14cbcSMatt Macy 		/* Unreachable */
788eda14cbcSMatt Macy 	}
789eda14cbcSMatt Macy 
790eda14cbcSMatt Macy 	/*
791eda14cbcSMatt Macy 	 * Check how many instructions the channel program has
792eda14cbcSMatt Macy 	 * executed so far, and compare against the limit.
793eda14cbcSMatt Macy 	 */
794eda14cbcSMatt Macy 	ri->zri_curinstrs += zfs_lua_check_instrlimit_interval;
795eda14cbcSMatt Macy 	if (ri->zri_maxinstrs != 0 && ri->zri_curinstrs > ri->zri_maxinstrs) {
796eda14cbcSMatt Macy 		ri->zri_timed_out = B_TRUE;
797eda14cbcSMatt Macy 		(void) lua_pushstring(state,
798eda14cbcSMatt Macy 		    "Channel program timed out.");
799eda14cbcSMatt Macy 		(void) lua_error(state);
800eda14cbcSMatt Macy 		/* Unreachable */
801eda14cbcSMatt Macy 	}
802eda14cbcSMatt Macy }
803eda14cbcSMatt Macy 
804eda14cbcSMatt Macy static int
zcp_panic_cb(lua_State * state)805eda14cbcSMatt Macy zcp_panic_cb(lua_State *state)
806eda14cbcSMatt Macy {
807eda14cbcSMatt Macy 	panic("unprotected error in call to Lua API (%s)\n",
808eda14cbcSMatt Macy 	    lua_tostring(state, -1));
809eda14cbcSMatt Macy 	return (0);
810eda14cbcSMatt Macy }
811eda14cbcSMatt Macy 
812eda14cbcSMatt Macy static void
zcp_eval_impl(dmu_tx_t * tx,zcp_run_info_t * ri)813eda14cbcSMatt Macy zcp_eval_impl(dmu_tx_t *tx, zcp_run_info_t *ri)
814eda14cbcSMatt Macy {
815eda14cbcSMatt Macy 	int err;
816eda14cbcSMatt Macy 	lua_State *state = ri->zri_state;
817eda14cbcSMatt Macy 
818eda14cbcSMatt Macy 	VERIFY3U(3, ==, lua_gettop(state));
819eda14cbcSMatt Macy 
820eda14cbcSMatt Macy 	/* finish initializing our runtime state */
821eda14cbcSMatt Macy 	ri->zri_pool = dmu_tx_pool(tx);
822eda14cbcSMatt Macy 	ri->zri_tx = tx;
823eda14cbcSMatt Macy 	list_create(&ri->zri_cleanup_handlers, sizeof (zcp_cleanup_handler_t),
824eda14cbcSMatt Macy 	    offsetof(zcp_cleanup_handler_t, zch_node));
825eda14cbcSMatt Macy 
826eda14cbcSMatt Macy 	/*
827eda14cbcSMatt Macy 	 * Store the zcp_run_info_t struct for this run in the Lua registry.
828eda14cbcSMatt Macy 	 * Registry entries are not directly accessible by the Lua scripts but
829eda14cbcSMatt Macy 	 * can be accessed by our callbacks.
830eda14cbcSMatt Macy 	 */
831eda14cbcSMatt Macy 	lua_pushlightuserdata(state, ri);
832eda14cbcSMatt Macy 	lua_setfield(state, LUA_REGISTRYINDEX, ZCP_RUN_INFO_KEY);
833eda14cbcSMatt Macy 	VERIFY3U(3, ==, lua_gettop(state));
834eda14cbcSMatt Macy 
835eda14cbcSMatt Macy 	/*
836eda14cbcSMatt Macy 	 * Tell the Lua interpreter to call our handler every count
837eda14cbcSMatt Macy 	 * instructions. Channel programs that execute too many instructions
838eda14cbcSMatt Macy 	 * should die with ETIME.
839eda14cbcSMatt Macy 	 */
840eda14cbcSMatt Macy 	(void) lua_sethook(state, zcp_lua_counthook, LUA_MASKCOUNT,
841eda14cbcSMatt Macy 	    zfs_lua_check_instrlimit_interval);
842eda14cbcSMatt Macy 
843eda14cbcSMatt Macy 	/*
844eda14cbcSMatt Macy 	 * Tell the Lua memory allocator to stop using KM_SLEEP before handing
845eda14cbcSMatt Macy 	 * off control to the channel program. Channel programs that use too
846eda14cbcSMatt Macy 	 * much memory should die with ENOSPC.
847eda14cbcSMatt Macy 	 */
848eda14cbcSMatt Macy 	ri->zri_allocargs->aa_must_succeed = B_FALSE;
849eda14cbcSMatt Macy 
850eda14cbcSMatt Macy 	/*
851eda14cbcSMatt Macy 	 * Call the Lua function that open-context passed us. This pops the
852eda14cbcSMatt Macy 	 * function and its input from the stack and pushes any return
853eda14cbcSMatt Macy 	 * or error values.
854eda14cbcSMatt Macy 	 */
855eda14cbcSMatt Macy 	err = lua_pcall(state, 1, LUA_MULTRET, 1);
856eda14cbcSMatt Macy 
857eda14cbcSMatt Macy 	/*
858eda14cbcSMatt Macy 	 * Let Lua use KM_SLEEP while we interpret the return values.
859eda14cbcSMatt Macy 	 */
860eda14cbcSMatt Macy 	ri->zri_allocargs->aa_must_succeed = B_TRUE;
861eda14cbcSMatt Macy 
862eda14cbcSMatt Macy 	/*
863eda14cbcSMatt Macy 	 * Remove the error handler callback from the stack. At this point,
864eda14cbcSMatt Macy 	 * there shouldn't be any cleanup handler registered in the handler
865eda14cbcSMatt Macy 	 * list (zri_cleanup_handlers), regardless of whether it ran or not.
866eda14cbcSMatt Macy 	 */
867eda14cbcSMatt Macy 	list_destroy(&ri->zri_cleanup_handlers);
868eda14cbcSMatt Macy 	lua_remove(state, 1);
869eda14cbcSMatt Macy 
870eda14cbcSMatt Macy 	switch (err) {
871eda14cbcSMatt Macy 	case LUA_OK: {
872eda14cbcSMatt Macy 		/*
873eda14cbcSMatt Macy 		 * Lua supports returning multiple values in a single return
874eda14cbcSMatt Macy 		 * statement.  Return values will have been pushed onto the
875eda14cbcSMatt Macy 		 * stack:
876eda14cbcSMatt Macy 		 * 1: Return value 1
877eda14cbcSMatt Macy 		 * 2: Return value 2
878eda14cbcSMatt Macy 		 * 3: etc...
879eda14cbcSMatt Macy 		 * To simplify the process of retrieving a return value from a
880eda14cbcSMatt Macy 		 * channel program, we disallow returning more than one value
881eda14cbcSMatt Macy 		 * to ZFS from the Lua script, yielding a singleton return
882eda14cbcSMatt Macy 		 * nvlist of the form { "return": Return value 1 }.
883eda14cbcSMatt Macy 		 */
884eda14cbcSMatt Macy 		int return_count = lua_gettop(state);
885eda14cbcSMatt Macy 
886eda14cbcSMatt Macy 		if (return_count == 1) {
887eda14cbcSMatt Macy 			ri->zri_result = 0;
888eda14cbcSMatt Macy 			zcp_convert_return_values(state, ri->zri_outnvl,
889eda14cbcSMatt Macy 			    ZCP_RET_RETURN, &ri->zri_result);
890eda14cbcSMatt Macy 		} else if (return_count > 1) {
891eda14cbcSMatt Macy 			ri->zri_result = SET_ERROR(ECHRNG);
892eda14cbcSMatt Macy 			lua_settop(state, 0);
893eda14cbcSMatt Macy 			(void) lua_pushfstring(state, "Multiple return "
894eda14cbcSMatt Macy 			    "values not supported");
895eda14cbcSMatt Macy 			zcp_convert_return_values(state, ri->zri_outnvl,
896eda14cbcSMatt Macy 			    ZCP_RET_ERROR, &ri->zri_result);
897eda14cbcSMatt Macy 		}
898eda14cbcSMatt Macy 		break;
899eda14cbcSMatt Macy 	}
900eda14cbcSMatt Macy 	case LUA_ERRRUN:
901eda14cbcSMatt Macy 	case LUA_ERRGCMM: {
902eda14cbcSMatt Macy 		/*
903eda14cbcSMatt Macy 		 * The channel program encountered a fatal error within the
904eda14cbcSMatt Macy 		 * script, such as failing an assertion, or calling a function
905eda14cbcSMatt Macy 		 * with incompatible arguments. The error value and the
906eda14cbcSMatt Macy 		 * traceback generated by zcp_error_handler() should be on the
907eda14cbcSMatt Macy 		 * stack.
908eda14cbcSMatt Macy 		 */
909eda14cbcSMatt Macy 		VERIFY3U(1, ==, lua_gettop(state));
910eda14cbcSMatt Macy 		if (ri->zri_timed_out) {
911eda14cbcSMatt Macy 			ri->zri_result = SET_ERROR(ETIME);
912eda14cbcSMatt Macy 		} else if (ri->zri_canceled) {
913eda14cbcSMatt Macy 			ri->zri_result = SET_ERROR(EINTR);
914eda14cbcSMatt Macy 		} else {
915eda14cbcSMatt Macy 			ri->zri_result = SET_ERROR(ECHRNG);
916eda14cbcSMatt Macy 		}
917eda14cbcSMatt Macy 
918eda14cbcSMatt Macy 		zcp_convert_return_values(state, ri->zri_outnvl,
919eda14cbcSMatt Macy 		    ZCP_RET_ERROR, &ri->zri_result);
920eda14cbcSMatt Macy 
921eda14cbcSMatt Macy 		if (ri->zri_result == ETIME && ri->zri_outnvl != NULL) {
922eda14cbcSMatt Macy 			(void) nvlist_add_uint64(ri->zri_outnvl,
923eda14cbcSMatt Macy 			    ZCP_ARG_INSTRLIMIT, ri->zri_curinstrs);
924eda14cbcSMatt Macy 		}
925eda14cbcSMatt Macy 		break;
926eda14cbcSMatt Macy 	}
927eda14cbcSMatt Macy 	case LUA_ERRERR: {
928eda14cbcSMatt Macy 		/*
929eda14cbcSMatt Macy 		 * The channel program encountered a fatal error within the
930eda14cbcSMatt Macy 		 * script, and we encountered another error while trying to
931eda14cbcSMatt Macy 		 * compute the traceback in zcp_error_handler(). We can only
932eda14cbcSMatt Macy 		 * return the error message.
933eda14cbcSMatt Macy 		 */
934eda14cbcSMatt Macy 		VERIFY3U(1, ==, lua_gettop(state));
935eda14cbcSMatt Macy 		if (ri->zri_timed_out) {
936eda14cbcSMatt Macy 			ri->zri_result = SET_ERROR(ETIME);
937eda14cbcSMatt Macy 		} else if (ri->zri_canceled) {
938eda14cbcSMatt Macy 			ri->zri_result = SET_ERROR(EINTR);
939eda14cbcSMatt Macy 		} else {
940eda14cbcSMatt Macy 			ri->zri_result = SET_ERROR(ECHRNG);
941eda14cbcSMatt Macy 		}
942eda14cbcSMatt Macy 
943eda14cbcSMatt Macy 		zcp_convert_return_values(state, ri->zri_outnvl,
944eda14cbcSMatt Macy 		    ZCP_RET_ERROR, &ri->zri_result);
945eda14cbcSMatt Macy 		break;
946eda14cbcSMatt Macy 	}
947eda14cbcSMatt Macy 	case LUA_ERRMEM:
948eda14cbcSMatt Macy 		/*
949eda14cbcSMatt Macy 		 * Lua ran out of memory while running the channel program.
950eda14cbcSMatt Macy 		 * There's not much we can do.
951eda14cbcSMatt Macy 		 */
952eda14cbcSMatt Macy 		ri->zri_result = SET_ERROR(ENOSPC);
953eda14cbcSMatt Macy 		break;
954eda14cbcSMatt Macy 	default:
955eda14cbcSMatt Macy 		VERIFY0(err);
956eda14cbcSMatt Macy 	}
957eda14cbcSMatt Macy }
958eda14cbcSMatt Macy 
959eda14cbcSMatt Macy static void
zcp_pool_error(zcp_run_info_t * ri,const char * poolname,int error)96015f0b8c3SMartin Matuska zcp_pool_error(zcp_run_info_t *ri, const char *poolname, int error)
961eda14cbcSMatt Macy {
962eda14cbcSMatt Macy 	ri->zri_result = SET_ERROR(ECHRNG);
963eda14cbcSMatt Macy 	lua_settop(ri->zri_state, 0);
96415f0b8c3SMartin Matuska 	(void) lua_pushfstring(ri->zri_state, "Could not open pool: %s "
96515f0b8c3SMartin Matuska 	    "errno: %d", poolname, error);
966eda14cbcSMatt Macy 	zcp_convert_return_values(ri->zri_state, ri->zri_outnvl,
967eda14cbcSMatt Macy 	    ZCP_RET_ERROR, &ri->zri_result);
968eda14cbcSMatt Macy 
969eda14cbcSMatt Macy }
970eda14cbcSMatt Macy 
971eda14cbcSMatt Macy /*
972eda14cbcSMatt Macy  * This callback is called when txg_wait_synced_sig encountered a signal.
973eda14cbcSMatt Macy  * The txg_wait_synced_sig will continue to wait for the txg to complete
974eda14cbcSMatt Macy  * after calling this callback.
975eda14cbcSMatt Macy  */
976eda14cbcSMatt Macy static void
zcp_eval_sig(void * arg,dmu_tx_t * tx)977eda14cbcSMatt Macy zcp_eval_sig(void *arg, dmu_tx_t *tx)
978eda14cbcSMatt Macy {
979e92ffd9bSMartin Matuska 	(void) tx;
980eda14cbcSMatt Macy 	zcp_run_info_t *ri = arg;
981eda14cbcSMatt Macy 
982eda14cbcSMatt Macy 	ri->zri_canceled = B_TRUE;
983eda14cbcSMatt Macy }
984eda14cbcSMatt Macy 
985eda14cbcSMatt Macy static void
zcp_eval_sync(void * arg,dmu_tx_t * tx)986eda14cbcSMatt Macy zcp_eval_sync(void *arg, dmu_tx_t *tx)
987eda14cbcSMatt Macy {
988eda14cbcSMatt Macy 	zcp_run_info_t *ri = arg;
989eda14cbcSMatt Macy 
990eda14cbcSMatt Macy 	/*
991eda14cbcSMatt Macy 	 * Open context should have setup the stack to contain:
992eda14cbcSMatt Macy 	 * 1: Error handler callback
993eda14cbcSMatt Macy 	 * 2: Script to run (converted to a Lua function)
994eda14cbcSMatt Macy 	 * 3: nvlist input to function (converted to Lua table or nil)
995eda14cbcSMatt Macy 	 */
996eda14cbcSMatt Macy 	VERIFY3U(3, ==, lua_gettop(ri->zri_state));
997eda14cbcSMatt Macy 
998eda14cbcSMatt Macy 	zcp_eval_impl(tx, ri);
999eda14cbcSMatt Macy }
1000eda14cbcSMatt Macy 
1001eda14cbcSMatt Macy static void
zcp_eval_open(zcp_run_info_t * ri,const char * poolname)1002eda14cbcSMatt Macy zcp_eval_open(zcp_run_info_t *ri, const char *poolname)
1003eda14cbcSMatt Macy {
1004eda14cbcSMatt Macy 	int error;
1005eda14cbcSMatt Macy 	dsl_pool_t *dp;
1006eda14cbcSMatt Macy 	dmu_tx_t *tx;
1007eda14cbcSMatt Macy 
1008eda14cbcSMatt Macy 	/*
1009eda14cbcSMatt Macy 	 * See comment from the same assertion in zcp_eval_sync().
1010eda14cbcSMatt Macy 	 */
1011eda14cbcSMatt Macy 	VERIFY3U(3, ==, lua_gettop(ri->zri_state));
1012eda14cbcSMatt Macy 
1013eda14cbcSMatt Macy 	error = dsl_pool_hold(poolname, FTAG, &dp);
1014eda14cbcSMatt Macy 	if (error != 0) {
101515f0b8c3SMartin Matuska 		zcp_pool_error(ri, poolname, error);
1016eda14cbcSMatt Macy 		return;
1017eda14cbcSMatt Macy 	}
1018eda14cbcSMatt Macy 
1019eda14cbcSMatt Macy 	/*
1020eda14cbcSMatt Macy 	 * As we are running in open-context, we have no transaction associated
1021eda14cbcSMatt Macy 	 * with the channel program. At the same time, functions from the
1022eda14cbcSMatt Macy 	 * zfs.check submodule need to be associated with a transaction as
1023eda14cbcSMatt Macy 	 * they are basically dry-runs of their counterparts in the zfs.sync
1024eda14cbcSMatt Macy 	 * submodule. These functions should be able to run in open-context.
1025eda14cbcSMatt Macy 	 * Therefore we create a new transaction that we later abort once
1026eda14cbcSMatt Macy 	 * the channel program has been evaluated.
1027eda14cbcSMatt Macy 	 */
1028eda14cbcSMatt Macy 	tx = dmu_tx_create_dd(dp->dp_mos_dir);
1029eda14cbcSMatt Macy 
1030eda14cbcSMatt Macy 	zcp_eval_impl(tx, ri);
1031eda14cbcSMatt Macy 
1032eda14cbcSMatt Macy 	dmu_tx_abort(tx);
1033eda14cbcSMatt Macy 
1034eda14cbcSMatt Macy 	dsl_pool_rele(dp, FTAG);
1035eda14cbcSMatt Macy }
1036eda14cbcSMatt Macy 
1037eda14cbcSMatt Macy int
zcp_eval(const char * poolname,const char * program,boolean_t sync,uint64_t instrlimit,uint64_t memlimit,nvpair_t * nvarg,nvlist_t * outnvl)1038eda14cbcSMatt Macy zcp_eval(const char *poolname, const char *program, boolean_t sync,
1039eda14cbcSMatt Macy     uint64_t instrlimit, uint64_t memlimit, nvpair_t *nvarg, nvlist_t *outnvl)
1040eda14cbcSMatt Macy {
1041eda14cbcSMatt Macy 	int err;
1042eda14cbcSMatt Macy 	lua_State *state;
1043eda14cbcSMatt Macy 	zcp_run_info_t runinfo;
1044eda14cbcSMatt Macy 
1045eda14cbcSMatt Macy 	if (instrlimit > zfs_lua_max_instrlimit)
1046eda14cbcSMatt Macy 		return (SET_ERROR(EINVAL));
1047eda14cbcSMatt Macy 	if (memlimit == 0 || memlimit > zfs_lua_max_memlimit)
1048eda14cbcSMatt Macy 		return (SET_ERROR(EINVAL));
1049eda14cbcSMatt Macy 
1050eda14cbcSMatt Macy 	zcp_alloc_arg_t allocargs = {
1051eda14cbcSMatt Macy 		.aa_must_succeed = B_TRUE,
1052eda14cbcSMatt Macy 		.aa_alloc_remaining = (int64_t)memlimit,
1053eda14cbcSMatt Macy 		.aa_alloc_limit = (int64_t)memlimit,
1054eda14cbcSMatt Macy 	};
1055eda14cbcSMatt Macy 
1056eda14cbcSMatt Macy 	/*
1057eda14cbcSMatt Macy 	 * Creates a Lua state with a memory allocator that uses KM_SLEEP.
1058eda14cbcSMatt Macy 	 * This should never fail.
1059eda14cbcSMatt Macy 	 */
1060eda14cbcSMatt Macy 	state = lua_newstate(zcp_lua_alloc, &allocargs);
1061eda14cbcSMatt Macy 	VERIFY(state != NULL);
1062eda14cbcSMatt Macy 	(void) lua_atpanic(state, zcp_panic_cb);
1063eda14cbcSMatt Macy 
1064eda14cbcSMatt Macy 	/*
1065eda14cbcSMatt Macy 	 * Load core Lua libraries we want access to.
1066eda14cbcSMatt Macy 	 */
1067eda14cbcSMatt Macy 	VERIFY3U(1, ==, luaopen_base(state));
1068eda14cbcSMatt Macy 	lua_pop(state, 1);
1069eda14cbcSMatt Macy 	VERIFY3U(1, ==, luaopen_coroutine(state));
1070eda14cbcSMatt Macy 	lua_setglobal(state, LUA_COLIBNAME);
1071eda14cbcSMatt Macy 	VERIFY0(lua_gettop(state));
1072eda14cbcSMatt Macy 	VERIFY3U(1, ==, luaopen_string(state));
1073eda14cbcSMatt Macy 	lua_setglobal(state, LUA_STRLIBNAME);
1074eda14cbcSMatt Macy 	VERIFY0(lua_gettop(state));
1075eda14cbcSMatt Macy 	VERIFY3U(1, ==, luaopen_table(state));
1076eda14cbcSMatt Macy 	lua_setglobal(state, LUA_TABLIBNAME);
1077eda14cbcSMatt Macy 	VERIFY0(lua_gettop(state));
1078eda14cbcSMatt Macy 
1079eda14cbcSMatt Macy 	/*
1080eda14cbcSMatt Macy 	 * Load globally visible variables such as errno aliases.
1081eda14cbcSMatt Macy 	 */
1082eda14cbcSMatt Macy 	zcp_load_globals(state);
1083eda14cbcSMatt Macy 	VERIFY0(lua_gettop(state));
1084eda14cbcSMatt Macy 
1085eda14cbcSMatt Macy 	/*
1086eda14cbcSMatt Macy 	 * Load ZFS-specific modules.
1087eda14cbcSMatt Macy 	 */
1088eda14cbcSMatt Macy 	lua_newtable(state);
1089eda14cbcSMatt Macy 	VERIFY3U(1, ==, zcp_load_list_lib(state));
1090eda14cbcSMatt Macy 	lua_setfield(state, -2, "list");
1091eda14cbcSMatt Macy 	VERIFY3U(1, ==, zcp_load_synctask_lib(state, B_FALSE));
1092eda14cbcSMatt Macy 	lua_setfield(state, -2, "check");
1093eda14cbcSMatt Macy 	VERIFY3U(1, ==, zcp_load_synctask_lib(state, B_TRUE));
1094eda14cbcSMatt Macy 	lua_setfield(state, -2, "sync");
1095eda14cbcSMatt Macy 	VERIFY3U(1, ==, zcp_load_get_lib(state));
1096eda14cbcSMatt Macy 	lua_pushcclosure(state, zcp_debug_info.func, 0);
1097eda14cbcSMatt Macy 	lua_setfield(state, -2, zcp_debug_info.name);
1098eda14cbcSMatt Macy 	lua_pushcclosure(state, zcp_exists_info.func, 0);
1099eda14cbcSMatt Macy 	lua_setfield(state, -2, zcp_exists_info.name);
1100eda14cbcSMatt Macy 	lua_setglobal(state, "zfs");
1101eda14cbcSMatt Macy 	VERIFY0(lua_gettop(state));
1102eda14cbcSMatt Macy 
1103eda14cbcSMatt Macy 	/*
1104eda14cbcSMatt Macy 	 * Push the error-callback that calculates Lua stack traces on
1105eda14cbcSMatt Macy 	 * unexpected failures.
1106eda14cbcSMatt Macy 	 */
1107eda14cbcSMatt Macy 	lua_pushcfunction(state, zcp_error_handler);
1108eda14cbcSMatt Macy 	VERIFY3U(1, ==, lua_gettop(state));
1109eda14cbcSMatt Macy 
1110eda14cbcSMatt Macy 	/*
1111eda14cbcSMatt Macy 	 * Load the actual script as a function onto the stack as text ("t").
1112eda14cbcSMatt Macy 	 * The only valid error condition is a syntax error in the script.
1113eda14cbcSMatt Macy 	 * ERRMEM should not be possible because our allocator is using
1114eda14cbcSMatt Macy 	 * KM_SLEEP.  ERRGCMM should not be possible because we have not added
1115eda14cbcSMatt Macy 	 * any objects with __gc metamethods to the interpreter that could
1116eda14cbcSMatt Macy 	 * fail.
1117eda14cbcSMatt Macy 	 */
1118eda14cbcSMatt Macy 	err = luaL_loadbufferx(state, program, strlen(program),
1119eda14cbcSMatt Macy 	    "channel program", "t");
1120eda14cbcSMatt Macy 	if (err == LUA_ERRSYNTAX) {
1121eda14cbcSMatt Macy 		fnvlist_add_string(outnvl, ZCP_RET_ERROR,
1122eda14cbcSMatt Macy 		    lua_tostring(state, -1));
1123eda14cbcSMatt Macy 		lua_close(state);
1124eda14cbcSMatt Macy 		return (SET_ERROR(EINVAL));
1125eda14cbcSMatt Macy 	}
1126eda14cbcSMatt Macy 	VERIFY0(err);
1127eda14cbcSMatt Macy 	VERIFY3U(2, ==, lua_gettop(state));
1128eda14cbcSMatt Macy 
1129eda14cbcSMatt Macy 	/*
1130eda14cbcSMatt Macy 	 * Convert the input nvlist to a Lua object and put it on top of the
1131eda14cbcSMatt Macy 	 * stack.
1132eda14cbcSMatt Macy 	 */
1133eda14cbcSMatt Macy 	char errmsg[128];
1134eda14cbcSMatt Macy 	err = zcp_nvpair_value_to_lua(state, nvarg,
1135eda14cbcSMatt Macy 	    errmsg, sizeof (errmsg));
1136eda14cbcSMatt Macy 	if (err != 0) {
1137eda14cbcSMatt Macy 		fnvlist_add_string(outnvl, ZCP_RET_ERROR, errmsg);
1138eda14cbcSMatt Macy 		lua_close(state);
1139eda14cbcSMatt Macy 		return (SET_ERROR(EINVAL));
1140eda14cbcSMatt Macy 	}
1141eda14cbcSMatt Macy 	VERIFY3U(3, ==, lua_gettop(state));
1142eda14cbcSMatt Macy 
1143eda14cbcSMatt Macy 	runinfo.zri_state = state;
1144eda14cbcSMatt Macy 	runinfo.zri_allocargs = &allocargs;
1145eda14cbcSMatt Macy 	runinfo.zri_outnvl = outnvl;
1146eda14cbcSMatt Macy 	runinfo.zri_result = 0;
1147eda14cbcSMatt Macy 	runinfo.zri_cred = CRED();
1148eda14cbcSMatt Macy 	runinfo.zri_proc = curproc;
1149eda14cbcSMatt Macy 	runinfo.zri_timed_out = B_FALSE;
1150eda14cbcSMatt Macy 	runinfo.zri_canceled = B_FALSE;
1151eda14cbcSMatt Macy 	runinfo.zri_sync = sync;
1152eda14cbcSMatt Macy 	runinfo.zri_space_used = 0;
1153eda14cbcSMatt Macy 	runinfo.zri_curinstrs = 0;
1154eda14cbcSMatt Macy 	runinfo.zri_maxinstrs = instrlimit;
1155eda14cbcSMatt Macy 	runinfo.zri_new_zvols = fnvlist_alloc();
1156eda14cbcSMatt Macy 
1157eda14cbcSMatt Macy 	if (sync) {
1158eda14cbcSMatt Macy 		err = dsl_sync_task_sig(poolname, NULL, zcp_eval_sync,
1159eda14cbcSMatt Macy 		    zcp_eval_sig, &runinfo, 0, ZFS_SPACE_CHECK_ZCP_EVAL);
1160eda14cbcSMatt Macy 		if (err != 0)
116115f0b8c3SMartin Matuska 			zcp_pool_error(&runinfo, poolname, err);
1162eda14cbcSMatt Macy 	} else {
1163eda14cbcSMatt Macy 		zcp_eval_open(&runinfo, poolname);
1164eda14cbcSMatt Macy 	}
1165eda14cbcSMatt Macy 	lua_close(state);
1166eda14cbcSMatt Macy 
1167eda14cbcSMatt Macy 	/*
1168eda14cbcSMatt Macy 	 * Create device minor nodes for any new zvols.
1169eda14cbcSMatt Macy 	 */
1170eda14cbcSMatt Macy 	for (nvpair_t *pair = nvlist_next_nvpair(runinfo.zri_new_zvols, NULL);
1171eda14cbcSMatt Macy 	    pair != NULL;
1172eda14cbcSMatt Macy 	    pair = nvlist_next_nvpair(runinfo.zri_new_zvols, pair)) {
1173eda14cbcSMatt Macy 		zvol_create_minor(nvpair_name(pair));
1174eda14cbcSMatt Macy 	}
1175eda14cbcSMatt Macy 	fnvlist_free(runinfo.zri_new_zvols);
1176eda14cbcSMatt Macy 
1177eda14cbcSMatt Macy 	return (runinfo.zri_result);
1178eda14cbcSMatt Macy }
1179eda14cbcSMatt Macy 
1180eda14cbcSMatt Macy /*
1181eda14cbcSMatt Macy  * Retrieve metadata about the currently running channel program.
1182eda14cbcSMatt Macy  */
1183eda14cbcSMatt Macy zcp_run_info_t *
zcp_run_info(lua_State * state)1184eda14cbcSMatt Macy zcp_run_info(lua_State *state)
1185eda14cbcSMatt Macy {
1186eda14cbcSMatt Macy 	zcp_run_info_t *ri;
1187eda14cbcSMatt Macy 
1188eda14cbcSMatt Macy 	lua_getfield(state, LUA_REGISTRYINDEX, ZCP_RUN_INFO_KEY);
1189eda14cbcSMatt Macy 	ri = lua_touserdata(state, -1);
1190eda14cbcSMatt Macy 	lua_pop(state, 1);
1191eda14cbcSMatt Macy 	return (ri);
1192eda14cbcSMatt Macy }
1193eda14cbcSMatt Macy 
1194eda14cbcSMatt Macy /*
1195eda14cbcSMatt Macy  * Argument Parsing
1196eda14cbcSMatt Macy  * ================
1197eda14cbcSMatt Macy  *
1198eda14cbcSMatt Macy  * The Lua language allows methods to be called with any number
1199eda14cbcSMatt Macy  * of arguments of any type. When calling back into ZFS we need to sanitize
1200eda14cbcSMatt Macy  * arguments from channel programs to make sure unexpected arguments or
1201eda14cbcSMatt Macy  * arguments of the wrong type result in clear error messages. To do this
1202eda14cbcSMatt Macy  * in a uniform way all callbacks from channel programs should use the
1203eda14cbcSMatt Macy  * zcp_parse_args() function to interpret inputs.
1204eda14cbcSMatt Macy  *
1205eda14cbcSMatt Macy  * Positional vs Keyword Arguments
1206eda14cbcSMatt Macy  * ===============================
1207eda14cbcSMatt Macy  *
1208eda14cbcSMatt Macy  * Every callback function takes a fixed set of required positional arguments
1209eda14cbcSMatt Macy  * and optional keyword arguments. For example, the destroy function takes
1210eda14cbcSMatt Macy  * a single positional string argument (the name of the dataset to destroy)
1211eda14cbcSMatt Macy  * and an optional "defer" keyword boolean argument. When calling lua functions
1212eda14cbcSMatt Macy  * with parentheses, only positional arguments can be used:
1213eda14cbcSMatt Macy  *
1214eda14cbcSMatt Macy  *     zfs.sync.snapshot("rpool@snap")
1215eda14cbcSMatt Macy  *
1216eda14cbcSMatt Macy  * To use keyword arguments functions should be called with a single argument
1217eda14cbcSMatt Macy  * that is a lua table containing mappings of integer -> positional arguments
1218eda14cbcSMatt Macy  * and string -> keyword arguments:
1219eda14cbcSMatt Macy  *
1220eda14cbcSMatt Macy  *     zfs.sync.snapshot({1="rpool@snap", defer=true})
1221eda14cbcSMatt Macy  *
1222eda14cbcSMatt Macy  * The lua language allows curly braces to be used in place of parenthesis as
1223eda14cbcSMatt Macy  * syntactic sugar for this calling convention:
1224eda14cbcSMatt Macy  *
1225eda14cbcSMatt Macy  *     zfs.sync.snapshot{"rpool@snap", defer=true}
1226eda14cbcSMatt Macy  */
1227eda14cbcSMatt Macy 
1228eda14cbcSMatt Macy /*
1229eda14cbcSMatt Macy  * Throw an error and print the given arguments.  If there are too many
1230eda14cbcSMatt Macy  * arguments to fit in the output buffer, only the error format string is
1231eda14cbcSMatt Macy  * output.
1232eda14cbcSMatt Macy  */
1233eda14cbcSMatt Macy static void
zcp_args_error(lua_State * state,const char * fname,const zcp_arg_t * pargs,const zcp_arg_t * kwargs,const char * fmt,...)1234eda14cbcSMatt Macy zcp_args_error(lua_State *state, const char *fname, const zcp_arg_t *pargs,
1235eda14cbcSMatt Macy     const zcp_arg_t *kwargs, const char *fmt, ...)
1236eda14cbcSMatt Macy {
1237eda14cbcSMatt Macy 	int i;
1238eda14cbcSMatt Macy 	char errmsg[512];
1239eda14cbcSMatt Macy 	size_t len = sizeof (errmsg);
1240eda14cbcSMatt Macy 	size_t msglen = 0;
1241eda14cbcSMatt Macy 	va_list argp;
1242eda14cbcSMatt Macy 
1243eda14cbcSMatt Macy 	va_start(argp, fmt);
1244eda14cbcSMatt Macy 	VERIFY3U(len, >, vsnprintf(errmsg, len, fmt, argp));
1245eda14cbcSMatt Macy 	va_end(argp);
1246eda14cbcSMatt Macy 
1247eda14cbcSMatt Macy 	/*
1248eda14cbcSMatt Macy 	 * Calculate the total length of the final string, including extra
1249eda14cbcSMatt Macy 	 * formatting characters. If the argument dump would be too large,
1250eda14cbcSMatt Macy 	 * only print the error string.
1251eda14cbcSMatt Macy 	 */
1252eda14cbcSMatt Macy 	msglen = strlen(errmsg);
1253eda14cbcSMatt Macy 	msglen += strlen(fname) + 4; /* : + {} + null terminator */
1254eda14cbcSMatt Macy 	for (i = 0; pargs[i].za_name != NULL; i++) {
1255eda14cbcSMatt Macy 		msglen += strlen(pargs[i].za_name);
1256eda14cbcSMatt Macy 		msglen += strlen(lua_typename(state, pargs[i].za_lua_type));
1257eda14cbcSMatt Macy 		if (pargs[i + 1].za_name != NULL || kwargs[0].za_name != NULL)
1258eda14cbcSMatt Macy 			msglen += 5; /* < + ( + )> + , */
1259eda14cbcSMatt Macy 		else
1260eda14cbcSMatt Macy 			msglen += 4; /* < + ( + )> */
1261eda14cbcSMatt Macy 	}
1262eda14cbcSMatt Macy 	for (i = 0; kwargs[i].za_name != NULL; i++) {
1263eda14cbcSMatt Macy 		msglen += strlen(kwargs[i].za_name);
1264eda14cbcSMatt Macy 		msglen += strlen(lua_typename(state, kwargs[i].za_lua_type));
1265eda14cbcSMatt Macy 		if (kwargs[i + 1].za_name != NULL)
1266eda14cbcSMatt Macy 			msglen += 4; /* =( + ) + , */
1267eda14cbcSMatt Macy 		else
1268eda14cbcSMatt Macy 			msglen += 3; /* =( + ) */
1269eda14cbcSMatt Macy 	}
1270eda14cbcSMatt Macy 
1271eda14cbcSMatt Macy 	if (msglen >= len)
1272eda14cbcSMatt Macy 		(void) luaL_error(state, errmsg);
1273eda14cbcSMatt Macy 
1274eda14cbcSMatt Macy 	VERIFY3U(len, >, strlcat(errmsg, ": ", len));
1275eda14cbcSMatt Macy 	VERIFY3U(len, >, strlcat(errmsg, fname, len));
1276eda14cbcSMatt Macy 	VERIFY3U(len, >, strlcat(errmsg, "{", len));
1277eda14cbcSMatt Macy 	for (i = 0; pargs[i].za_name != NULL; i++) {
1278eda14cbcSMatt Macy 		VERIFY3U(len, >, strlcat(errmsg, "<", len));
1279eda14cbcSMatt Macy 		VERIFY3U(len, >, strlcat(errmsg, pargs[i].za_name, len));
1280eda14cbcSMatt Macy 		VERIFY3U(len, >, strlcat(errmsg, "(", len));
1281eda14cbcSMatt Macy 		VERIFY3U(len, >, strlcat(errmsg,
1282eda14cbcSMatt Macy 		    lua_typename(state, pargs[i].za_lua_type), len));
1283eda14cbcSMatt Macy 		VERIFY3U(len, >, strlcat(errmsg, ")>", len));
1284eda14cbcSMatt Macy 		if (pargs[i + 1].za_name != NULL || kwargs[0].za_name != NULL) {
1285eda14cbcSMatt Macy 			VERIFY3U(len, >, strlcat(errmsg, ", ", len));
1286eda14cbcSMatt Macy 		}
1287eda14cbcSMatt Macy 	}
1288eda14cbcSMatt Macy 	for (i = 0; kwargs[i].za_name != NULL; i++) {
1289eda14cbcSMatt Macy 		VERIFY3U(len, >, strlcat(errmsg, kwargs[i].za_name, len));
1290eda14cbcSMatt Macy 		VERIFY3U(len, >, strlcat(errmsg, "=(", len));
1291eda14cbcSMatt Macy 		VERIFY3U(len, >, strlcat(errmsg,
1292eda14cbcSMatt Macy 		    lua_typename(state, kwargs[i].za_lua_type), len));
1293eda14cbcSMatt Macy 		VERIFY3U(len, >, strlcat(errmsg, ")", len));
1294eda14cbcSMatt Macy 		if (kwargs[i + 1].za_name != NULL) {
1295eda14cbcSMatt Macy 			VERIFY3U(len, >, strlcat(errmsg, ", ", len));
1296eda14cbcSMatt Macy 		}
1297eda14cbcSMatt Macy 	}
1298eda14cbcSMatt Macy 	VERIFY3U(len, >, strlcat(errmsg, "}", len));
1299eda14cbcSMatt Macy 
1300eda14cbcSMatt Macy 	(void) luaL_error(state, errmsg);
1301eda14cbcSMatt Macy 	panic("unreachable code");
1302eda14cbcSMatt Macy }
1303eda14cbcSMatt Macy 
1304eda14cbcSMatt Macy static void
zcp_parse_table_args(lua_State * state,const char * fname,const zcp_arg_t * pargs,const zcp_arg_t * kwargs)1305eda14cbcSMatt Macy zcp_parse_table_args(lua_State *state, const char *fname,
1306eda14cbcSMatt Macy     const zcp_arg_t *pargs, const zcp_arg_t *kwargs)
1307eda14cbcSMatt Macy {
1308eda14cbcSMatt Macy 	int i;
1309eda14cbcSMatt Macy 	int type;
1310eda14cbcSMatt Macy 
1311eda14cbcSMatt Macy 	for (i = 0; pargs[i].za_name != NULL; i++) {
1312eda14cbcSMatt Macy 		/*
1313eda14cbcSMatt Macy 		 * Check the table for this positional argument, leaving it
1314eda14cbcSMatt Macy 		 * on the top of the stack once we finish validating it.
1315eda14cbcSMatt Macy 		 */
1316eda14cbcSMatt Macy 		lua_pushinteger(state, i + 1);
1317eda14cbcSMatt Macy 		lua_gettable(state, 1);
1318eda14cbcSMatt Macy 
1319eda14cbcSMatt Macy 		type = lua_type(state, -1);
1320eda14cbcSMatt Macy 		if (type == LUA_TNIL) {
1321eda14cbcSMatt Macy 			zcp_args_error(state, fname, pargs, kwargs,
1322eda14cbcSMatt Macy 			    "too few arguments");
1323eda14cbcSMatt Macy 			panic("unreachable code");
1324eda14cbcSMatt Macy 		} else if (type != pargs[i].za_lua_type) {
1325eda14cbcSMatt Macy 			zcp_args_error(state, fname, pargs, kwargs,
1326eda14cbcSMatt Macy 			    "arg %d wrong type (is '%s', expected '%s')",
1327eda14cbcSMatt Macy 			    i + 1, lua_typename(state, type),
1328eda14cbcSMatt Macy 			    lua_typename(state, pargs[i].za_lua_type));
1329eda14cbcSMatt Macy 			panic("unreachable code");
1330eda14cbcSMatt Macy 		}
1331eda14cbcSMatt Macy 
1332eda14cbcSMatt Macy 		/*
1333eda14cbcSMatt Macy 		 * Remove the positional argument from the table.
1334eda14cbcSMatt Macy 		 */
1335eda14cbcSMatt Macy 		lua_pushinteger(state, i + 1);
1336eda14cbcSMatt Macy 		lua_pushnil(state);
1337eda14cbcSMatt Macy 		lua_settable(state, 1);
1338eda14cbcSMatt Macy 	}
1339eda14cbcSMatt Macy 
1340eda14cbcSMatt Macy 	for (i = 0; kwargs[i].za_name != NULL; i++) {
1341eda14cbcSMatt Macy 		/*
1342eda14cbcSMatt Macy 		 * Check the table for this keyword argument, which may be
1343eda14cbcSMatt Macy 		 * nil if it was omitted. Leave the value on the top of
1344eda14cbcSMatt Macy 		 * the stack after validating it.
1345eda14cbcSMatt Macy 		 */
1346eda14cbcSMatt Macy 		lua_getfield(state, 1, kwargs[i].za_name);
1347eda14cbcSMatt Macy 
1348eda14cbcSMatt Macy 		type = lua_type(state, -1);
1349eda14cbcSMatt Macy 		if (type != LUA_TNIL && type != kwargs[i].za_lua_type) {
1350eda14cbcSMatt Macy 			zcp_args_error(state, fname, pargs, kwargs,
1351eda14cbcSMatt Macy 			    "kwarg '%s' wrong type (is '%s', expected '%s')",
1352eda14cbcSMatt Macy 			    kwargs[i].za_name, lua_typename(state, type),
1353eda14cbcSMatt Macy 			    lua_typename(state, kwargs[i].za_lua_type));
1354eda14cbcSMatt Macy 			panic("unreachable code");
1355eda14cbcSMatt Macy 		}
1356eda14cbcSMatt Macy 
1357eda14cbcSMatt Macy 		/*
1358eda14cbcSMatt Macy 		 * Remove the keyword argument from the table.
1359eda14cbcSMatt Macy 		 */
1360eda14cbcSMatt Macy 		lua_pushnil(state);
1361eda14cbcSMatt Macy 		lua_setfield(state, 1, kwargs[i].za_name);
1362eda14cbcSMatt Macy 	}
1363eda14cbcSMatt Macy 
1364eda14cbcSMatt Macy 	/*
1365eda14cbcSMatt Macy 	 * Any entries remaining in the table are invalid inputs, print
1366eda14cbcSMatt Macy 	 * an error message based on what the entry is.
1367eda14cbcSMatt Macy 	 */
1368eda14cbcSMatt Macy 	lua_pushnil(state);
1369eda14cbcSMatt Macy 	if (lua_next(state, 1)) {
1370eda14cbcSMatt Macy 		if (lua_isnumber(state, -2) && lua_tointeger(state, -2) > 0) {
1371eda14cbcSMatt Macy 			zcp_args_error(state, fname, pargs, kwargs,
1372eda14cbcSMatt Macy 			    "too many positional arguments");
1373eda14cbcSMatt Macy 		} else if (lua_isstring(state, -2)) {
1374eda14cbcSMatt Macy 			zcp_args_error(state, fname, pargs, kwargs,
1375eda14cbcSMatt Macy 			    "invalid kwarg '%s'", lua_tostring(state, -2));
1376eda14cbcSMatt Macy 		} else {
1377eda14cbcSMatt Macy 			zcp_args_error(state, fname, pargs, kwargs,
1378eda14cbcSMatt Macy 			    "kwarg keys must be strings");
1379eda14cbcSMatt Macy 		}
1380eda14cbcSMatt Macy 		panic("unreachable code");
1381eda14cbcSMatt Macy 	}
1382eda14cbcSMatt Macy 
1383eda14cbcSMatt Macy 	lua_remove(state, 1);
1384eda14cbcSMatt Macy }
1385eda14cbcSMatt Macy 
1386eda14cbcSMatt Macy static void
zcp_parse_pos_args(lua_State * state,const char * fname,const zcp_arg_t * pargs,const zcp_arg_t * kwargs)1387eda14cbcSMatt Macy zcp_parse_pos_args(lua_State *state, const char *fname, const zcp_arg_t *pargs,
1388eda14cbcSMatt Macy     const zcp_arg_t *kwargs)
1389eda14cbcSMatt Macy {
1390eda14cbcSMatt Macy 	int i;
1391eda14cbcSMatt Macy 	int type;
1392eda14cbcSMatt Macy 
1393eda14cbcSMatt Macy 	for (i = 0; pargs[i].za_name != NULL; i++) {
1394eda14cbcSMatt Macy 		type = lua_type(state, i + 1);
1395eda14cbcSMatt Macy 		if (type == LUA_TNONE) {
1396eda14cbcSMatt Macy 			zcp_args_error(state, fname, pargs, kwargs,
1397eda14cbcSMatt Macy 			    "too few arguments");
1398eda14cbcSMatt Macy 			panic("unreachable code");
1399eda14cbcSMatt Macy 		} else if (type != pargs[i].za_lua_type) {
1400eda14cbcSMatt Macy 			zcp_args_error(state, fname, pargs, kwargs,
1401eda14cbcSMatt Macy 			    "arg %d wrong type (is '%s', expected '%s')",
1402eda14cbcSMatt Macy 			    i + 1, lua_typename(state, type),
1403eda14cbcSMatt Macy 			    lua_typename(state, pargs[i].za_lua_type));
1404eda14cbcSMatt Macy 			panic("unreachable code");
1405eda14cbcSMatt Macy 		}
1406eda14cbcSMatt Macy 	}
1407eda14cbcSMatt Macy 	if (lua_gettop(state) != i) {
1408eda14cbcSMatt Macy 		zcp_args_error(state, fname, pargs, kwargs,
1409eda14cbcSMatt Macy 		    "too many positional arguments");
1410eda14cbcSMatt Macy 		panic("unreachable code");
1411eda14cbcSMatt Macy 	}
1412eda14cbcSMatt Macy 
1413eda14cbcSMatt Macy 	for (i = 0; kwargs[i].za_name != NULL; i++) {
1414eda14cbcSMatt Macy 		lua_pushnil(state);
1415eda14cbcSMatt Macy 	}
1416eda14cbcSMatt Macy }
1417eda14cbcSMatt Macy 
1418eda14cbcSMatt Macy /*
1419eda14cbcSMatt Macy  * Checks the current Lua stack against an expected set of positional and
1420eda14cbcSMatt Macy  * keyword arguments. If the stack does not match the expected arguments
1421eda14cbcSMatt Macy  * aborts the current channel program with a useful error message, otherwise
1422eda14cbcSMatt Macy  * it re-arranges the stack so that it contains the positional arguments
1423eda14cbcSMatt Macy  * followed by the keyword argument values in declaration order. Any missing
1424eda14cbcSMatt Macy  * keyword argument will be represented by a nil value on the stack.
1425eda14cbcSMatt Macy  *
1426eda14cbcSMatt Macy  * If the stack contains exactly one argument of type LUA_TTABLE the curly
1427eda14cbcSMatt Macy  * braces calling convention is assumed, otherwise the stack is parsed for
1428eda14cbcSMatt Macy  * positional arguments only.
1429eda14cbcSMatt Macy  *
1430eda14cbcSMatt Macy  * This function should be used by every function callback. It should be called
1431eda14cbcSMatt Macy  * before the callback manipulates the Lua stack as it assumes the stack
1432eda14cbcSMatt Macy  * represents the function arguments.
1433eda14cbcSMatt Macy  */
1434eda14cbcSMatt Macy void
zcp_parse_args(lua_State * state,const char * fname,const zcp_arg_t * pargs,const zcp_arg_t * kwargs)1435eda14cbcSMatt Macy zcp_parse_args(lua_State *state, const char *fname, const zcp_arg_t *pargs,
1436eda14cbcSMatt Macy     const zcp_arg_t *kwargs)
1437eda14cbcSMatt Macy {
1438eda14cbcSMatt Macy 	if (lua_gettop(state) == 1 && lua_istable(state, 1)) {
1439eda14cbcSMatt Macy 		zcp_parse_table_args(state, fname, pargs, kwargs);
1440eda14cbcSMatt Macy 	} else {
1441eda14cbcSMatt Macy 		zcp_parse_pos_args(state, fname, pargs, kwargs);
1442eda14cbcSMatt Macy 	}
1443eda14cbcSMatt Macy }
1444eda14cbcSMatt Macy 
1445dbd5678dSMartin Matuska ZFS_MODULE_PARAM(zfs_lua, zfs_lua_, max_instrlimit, U64, ZMOD_RW,
1446eda14cbcSMatt Macy 	"Max instruction limit that can be specified for a channel program");
1447eda14cbcSMatt Macy 
1448dbd5678dSMartin Matuska ZFS_MODULE_PARAM(zfs_lua, zfs_lua_, max_memlimit, U64, ZMOD_RW,
1449eda14cbcSMatt Macy 	"Max memory limit that can be specified for a channel program");
1450