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