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