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