xref: /netbsd-src/sys/modules/lua/lua.c (revision 03dcb730d46d34d85c9f496c1f5a3a6a43f2b7b3)
1 /*	$NetBSD: lua.c,v 1.23 2017/05/20 09:46:17 mbalmer Exp $ */
2 
3 /*
4  * Copyright (c) 2011 - 2017 by Marc Balmer <mbalmer@NetBSD.org>.
5  * Copyright (c) 2014 by Lourival Vieira Neto <lneto@NetBSD.org>.
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. The name of the Author may not be used to endorse or promote products
17  *    derived from this software without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 
32 /* Lua device driver */
33 
34 #include <sys/param.h>
35 #include <sys/fcntl.h>
36 #include <sys/conf.h>
37 #include <sys/condvar.h>
38 #include <sys/device.h>
39 #include <sys/ioctl.h>
40 #include <sys/kmem.h>
41 #include <sys/lock.h>
42 #include <sys/lua.h>
43 #include <sys/module.h>
44 #include <sys/mutex.h>
45 #include <sys/namei.h>
46 #include <sys/queue.h>
47 #include <sys/sysctl.h>
48 #include <sys/vnode.h>
49 #include <sys/cpu.h>
50 
51 #include <lauxlib.h>
52 
53 #include "luavar.h"
54 
55 struct lua_softc {
56 	device_t		 sc_dev;
57 
58 	kmutex_t		 sc_lock;
59 	kcondvar_t		 sc_inuse_cv;
60 	bool			 sc_inuse;
61 
62 	/* Locking access to state queues */
63 	kmutex_t		 sc_state_lock;
64 	kcondvar_t		 sc_state_cv;
65 	bool			 sc_state;
66 
67 	struct sysctllog	*sc_log;
68 };
69 
70 static device_t	sc_self;
71 static bool	lua_autoload_on = true;
72 static bool	lua_require_on = true;
73 static bool	lua_bytecode_on = false;
74 static int	lua_verbose;
75 static int	lua_max_instr;
76 
77 static LIST_HEAD(, lua_state)	lua_states;
78 static LIST_HEAD(, lua_module)	lua_modules;
79 
80 static int lua_match(device_t, cfdata_t, void *);
81 static void lua_attach(device_t, device_t, void *);
82 static int lua_detach(device_t, int);
83 static klua_State *klua_find(const char *);
84 static const char *lua_reader(lua_State *, void *, size_t *);
85 static void lua_maxcount(lua_State *, lua_Debug *);
86 
87 static int lua_require(lua_State *);
88 
89 CFATTACH_DECL_NEW(lua, sizeof(struct lua_softc),
90 	lua_match, lua_attach, lua_detach, NULL);
91 
92 dev_type_open(luaopen);
93 dev_type_close(luaclose);
94 dev_type_ioctl(luaioctl);
95 
96 const struct cdevsw lua_cdevsw = {
97 	.d_open = luaopen,
98 	.d_close = luaclose,
99 	.d_read = noread,
100 	.d_write = nowrite,
101 	.d_ioctl = luaioctl,
102 	.d_stop = nostop,
103 	.d_tty = notty,
104 	.d_poll = nopoll,
105 	.d_mmap = nommap,
106 	.d_kqfilter = nokqfilter,
107 	.d_discard = nodiscard,
108 	.d_flag = D_OTHER | D_MPSAFE
109 };
110 
111 struct lua_loadstate {
112 	struct vnode	*vp;
113 	size_t		 size;
114 	off_t		 off;
115 };
116 
117 extern struct cfdriver lua_cd;
118 
119 static int
120 lua_match(device_t parent, cfdata_t match, void *aux)
121 {
122 	return 1;
123 }
124 
125 static void
126 lua_attach(device_t parent, device_t self, void *aux)
127 {
128 	struct lua_softc *sc;
129 	const struct sysctlnode *node;
130 
131 	if (sc_self)
132 		return;
133 
134 	sc = device_private(self);
135 	sc->sc_dev = self;
136 	sc_self = self;
137 
138 	mutex_init(&sc->sc_lock, MUTEX_DEFAULT, IPL_VM);
139 	cv_init(&sc->sc_inuse_cv, "luactl");
140 
141 	mutex_init(&sc->sc_state_lock, MUTEX_DEFAULT, IPL_VM);
142 	cv_init(&sc->sc_state_cv, "luastate");
143 
144 	if (!pmf_device_register(self, NULL, NULL))
145 		aprint_error_dev(self, "couldn't establish power handler\n");
146 
147 	/* Sysctl to provide some control over behaviour */
148         sysctl_createv(&sc->sc_log, 0, NULL, &node,
149             CTLFLAG_OWNDESC,
150             CTLTYPE_NODE, "lua",
151             SYSCTL_DESCR("Lua options"),
152             NULL, 0, NULL, 0,
153             CTL_KERN, CTL_CREATE, CTL_EOL);
154 
155         if (node == NULL) {
156 		aprint_error(": can't create sysctl node\n");
157                 return;
158 	}
159 
160 	/*
161 	 * XXX Some of the sysctl values must not be changed after the
162 	 * securelevel has been raised.
163 	 */
164         sysctl_createv(&sc->sc_log, 0, &node, NULL,
165             CTLFLAG_READWRITE | CTLFLAG_OWNDESC,
166             CTLTYPE_BOOL, "require",
167             SYSCTL_DESCR("Enable the require command"),
168             NULL, 0, &lua_require_on, 0,
169 	    CTL_CREATE, CTL_EOL);
170 
171         sysctl_createv(&sc->sc_log, 0, &node, NULL,
172             CTLFLAG_READWRITE | CTLFLAG_OWNDESC,
173             CTLTYPE_BOOL, "autoload",
174             SYSCTL_DESCR("Enable automatic load of modules"),
175             NULL, 0, &lua_autoload_on, 0,
176 	    CTL_CREATE, CTL_EOL);
177 
178         sysctl_createv(&sc->sc_log, 0, &node, NULL,
179             CTLFLAG_READWRITE | CTLFLAG_OWNDESC,
180             CTLTYPE_BOOL, "bytecode",
181             SYSCTL_DESCR("Enable loading of bytecode"),
182             NULL, 0, &lua_bytecode_on, 0,
183 	    CTL_CREATE, CTL_EOL);
184 
185         sysctl_createv(&sc->sc_log, 0, &node, NULL,
186             CTLFLAG_READWRITE | CTLFLAG_OWNDESC,
187             CTLTYPE_INT, "verbose",
188             SYSCTL_DESCR("Enable verbose output"),
189             NULL, 0, &lua_verbose, 0,
190 	    CTL_CREATE, CTL_EOL);
191 
192         sysctl_createv(&sc->sc_log, 0, &node, NULL,
193             CTLFLAG_READWRITE | CTLFLAG_OWNDESC,
194             CTLTYPE_INT, "maxcount",
195             SYSCTL_DESCR("Limit maximum instruction count"),
196             NULL, 0, &lua_max_instr, 0,
197 	    CTL_CREATE, CTL_EOL);
198 
199 	aprint_normal_dev(self, "%s\n", LUA_COPYRIGHT);
200 }
201 
202 static int
203 lua_detach(device_t self, int flags)
204 {
205 	struct lua_softc *sc;
206 	struct lua_state *s;
207 
208 	sc = device_private(self);
209 	pmf_device_deregister(self);
210 
211 	if (sc->sc_log != NULL) {
212 		sysctl_teardown(&sc->sc_log);
213 		sc->sc_log = NULL;
214 	}
215 
216 	/* Traverse the list of states and close them */
217 	while ((s = LIST_FIRST(&lua_states)) != NULL) {
218 		LIST_REMOVE(s, lua_next);
219 		klua_close(s->K);
220 		if (lua_verbose)
221 			device_printf(self, "state %s destroyed\n",
222 			    s->lua_name);
223 		kmem_free(s, sizeof(struct lua_state));
224 	}
225 	mutex_destroy(&sc->sc_lock);
226 	cv_destroy(&sc->sc_inuse_cv);
227 	mutex_destroy(&sc->sc_state_lock);
228 	cv_destroy(&sc->sc_state_cv);
229 	sc_self = NULL;
230 	return 0;
231 }
232 
233 int
234 luaopen(dev_t dev, int flag, int mode, struct lwp *l)
235 {
236 	struct lua_softc *sc;
237 	int error = 0;
238 
239 	if (minor(dev) > 0)
240 		return ENXIO;
241 
242 	sc = device_lookup_private(&lua_cd, minor(dev));
243 	if (sc == NULL)
244 		return ENXIO;
245 
246 	mutex_enter(&sc->sc_lock);
247 	while (sc->sc_inuse == true) {
248 		error = cv_wait_sig(&sc->sc_inuse_cv, &sc->sc_lock);
249 		if (error)
250 			break;
251 	}
252 	if (!error)
253 		sc->sc_inuse = true;
254 	mutex_exit(&sc->sc_lock);
255 
256 	if (error)
257 		return error;
258 	return 0;
259 }
260 
261 int
262 luaclose(dev_t dev, int flag, int mode, struct lwp *l)
263 {
264 	struct lua_softc *sc;
265 
266 	if (minor(dev) > 0)
267 		return ENXIO;
268 	sc = device_lookup_private(&lua_cd, minor(dev));
269 	mutex_enter(&sc->sc_lock);
270 	sc->sc_inuse = false;
271 	cv_signal(&sc->sc_inuse_cv);
272 	mutex_exit(&sc->sc_lock);
273 	return 0;
274 }
275 
276 int
277 luaioctl(dev_t dev, u_long cmd, void *data, int flag, struct lwp *l)
278 {
279 	struct lua_softc *sc;
280 	struct lua_info *info;
281 	struct lua_create *create;
282 	struct lua_require *require;
283 	struct lua_load *load;
284 	struct lua_state *s;
285 	struct lua_module *m;
286 	kauth_cred_t cred;
287 	struct nameidata nd;
288 	struct pathbuf *pb;
289 	struct vattr va;
290 	struct lua_loadstate ls;
291 	int error, n;
292 	klua_State *K;
293 
294 	sc = device_lookup_private(&lua_cd, minor(dev));
295 	if (!device_is_active(sc->sc_dev))
296 		return EBUSY;
297 
298 	switch (cmd) {
299 	case LUAINFO:
300 		info = data;
301 		if (info->states == NULL) {
302 			info->num_states = 0;
303 			LIST_FOREACH(s, &lua_states, lua_next)
304 				info->num_states++;
305 		} else {
306 			n = 0;
307 			LIST_FOREACH(s, &lua_states, lua_next) {
308 				if (n > info->num_states)
309 					break;
310 				copyoutstr(s->lua_name, info->states[n].name,
311 				    MAX_LUA_NAME, NULL);
312 				copyoutstr(s->lua_desc, info->states[n].desc,
313 				    MAX_LUA_DESC, NULL);
314 				info->states[n].user = s->K->ks_user;
315 				n++;
316 			}
317 			info->num_states = n;
318 		}
319 		break;
320 	case LUACREATE:
321 		create = data;
322 
323 		if (*create->name == '_') {
324 			if (lua_verbose)
325 				device_printf(sc->sc_dev, "names of user "
326 				    "created states must not begin with '_'");
327 				return ENXIO;
328 		}
329 		LIST_FOREACH(s, &lua_states, lua_next)
330 			if (!strcmp(s->lua_name, create->name)) {
331 				if (lua_verbose)
332 					device_printf(sc->sc_dev,
333 					    "state %s exists\n", create->name);
334 				return EBUSY;
335 			}
336 
337 		K = kluaL_newstate(create->name, create->desc, IPL_NONE);
338 
339 		if (K == NULL)
340 			return ENOMEM;
341 
342 		K->ks_user = true;
343 
344 		if (lua_verbose)
345 			device_printf(sc->sc_dev, "state %s created\n",
346 			    create->name);
347 		break;
348 	case LUADESTROY:
349 		create = data;
350 
351 		K = klua_find(create->name);
352 
353 		if (K != NULL && (K->ks_user == true)) {
354 			klua_close(K);
355 			return 0;
356 		}
357 		return EBUSY;
358 	case LUAREQUIRE:	/* 'require' a module in a State */
359 		require = data;
360 		LIST_FOREACH(s, &lua_states, lua_next)
361 			if (!strcmp(s->lua_name, require->state)) {
362 				LIST_FOREACH(m, &s->lua_modules, mod_next)
363 					if (!strcmp(m->mod_name, require->module))
364 						return ENXIO;
365 				LIST_FOREACH(m, &lua_modules, mod_next)
366 					if (!strcmp(m->mod_name,
367 					    require->module)) {
368 					    	if (lua_verbose)
369 						    	device_printf(
370 						    	    sc->sc_dev,
371 					    		    "requiring module "
372 					    		    "%s to state %s\n",
373 					    		    m->mod_name,
374 					    		    s->lua_name);
375 						klua_lock(s->K);
376 						luaL_requiref(
377 							s->K->L,
378 							m->mod_name,
379 							m->open,
380 							1);
381 						klua_unlock(s->K);
382 					    	m->refcount++;
383 					    	LIST_INSERT_HEAD(
384 					    	    &s->lua_modules, m,
385 					    	    mod_next);
386 					    	return 0;
387 					}
388 			}
389 		return ENXIO;
390 	case LUALOAD:
391 		load = data;
392 		if (strrchr(load->path, '/') == NULL)
393 			return ENXIO;
394 
395 		LIST_FOREACH(s, &lua_states, lua_next)
396 			if (!strcmp(s->lua_name, load->state)) {
397 				if (lua_verbose)
398 					device_printf(sc->sc_dev,
399 					    "loading %s into state %s\n",
400 					    load->path, s->lua_name);
401 				cred = kauth_cred_get();
402 				pb = pathbuf_create(load->path);
403 				if (pb == NULL)
404 					return ENOMEM;
405 				NDINIT(&nd, LOOKUP, FOLLOW | NOCHROOT, pb);
406 				error = vn_open(&nd, FREAD, 0);
407 				pathbuf_destroy(pb);
408 				if (error) {
409 					if (lua_verbose)
410 						device_printf(sc->sc_dev,
411 						    "error vn_open %d\n",
412 						    error);
413 					return error;
414 				}
415 				error = VOP_GETATTR(nd.ni_vp, &va,
416 				    kauth_cred_get());
417 				if (error) {
418 					VOP_UNLOCK(nd.ni_vp);
419 					vn_close(nd.ni_vp, FREAD,
420 					    kauth_cred_get());
421 					if (lua_verbose)
422 						device_printf(sc->sc_dev,
423 						    "erro VOP_GETATTR %d\n",
424 						    error);
425 					return error;
426 				}
427 				if (va.va_type != VREG) {
428 					VOP_UNLOCK(nd.ni_vp);
429 					vn_close(nd.ni_vp, FREAD,
430 					    kauth_cred_get());
431 					return EINVAL;
432 				}
433 				ls.vp = nd.ni_vp;
434 				ls.off = 0L;
435 				ls.size = va.va_size;
436 				VOP_UNLOCK(nd.ni_vp);
437 				klua_lock(s->K);
438 				error = lua_load(s->K->L, lua_reader, &ls,
439 				    strrchr(load->path, '/') + 1, "bt");
440 				vn_close(nd.ni_vp, FREAD, cred);
441 				switch (error) {
442 				case 0:	/* no error */
443 					break;
444 				case LUA_ERRSYNTAX:
445 					if (lua_verbose)
446 						device_printf(sc->sc_dev,
447 						    "syntax error\n");
448 					klua_unlock(s->K);
449 					return EINVAL;
450 				case LUA_ERRMEM:
451 					if (lua_verbose)
452 						device_printf(sc->sc_dev,
453 						    "memory error\n");
454 					klua_unlock(s->K);
455 					return ENOMEM;
456 				default:
457 					if (lua_verbose)
458 						device_printf(sc->sc_dev,
459 						    "load error %d: %s\n",
460 						    error,
461 						    lua_tostring(s->K->L, -1));
462 					klua_unlock(s->K);
463 					return EINVAL;
464 				}
465 				if (lua_max_instr > 0)
466 					lua_sethook(s->K->L, lua_maxcount,
467 					    LUA_MASKCOUNT, lua_max_instr);
468 				error = lua_pcall(s->K->L, 0, LUA_MULTRET, 0);
469 				if (error) {
470 					if (lua_verbose) {
471 						device_printf(sc->sc_dev,
472 						    "execution error: %s\n",
473 						    lua_tostring(s->K->L, -1));
474 					}
475 					klua_unlock(s->K);
476 					return EINVAL;
477 				}
478 				klua_unlock(s->K);
479 				return 0;
480 			}
481 		return ENXIO;
482 	}
483 	return 0;
484 }
485 
486 static int
487 lua_require(lua_State *L)
488 {
489 	struct lua_state *s;
490 	struct lua_module *m, *md;
491 	const char *module;
492 	char name[MAXPATHLEN];
493 
494 	module = lua_tostring(L, -1);
495 	md = NULL;
496 	LIST_FOREACH(m, &lua_modules, mod_next)
497 		if (!strcmp(m->mod_name, module)) {
498 			md = m;
499 			break;
500 		}
501 
502 	if (md == NULL && lua_autoload_on && strchr(module, '/') == NULL) {
503 		snprintf(name, sizeof name, "lua%s", module);
504 		if (lua_verbose)
505 			device_printf(sc_self, "autoload %s\n", name);
506 		module_autoload(name, MODULE_CLASS_MISC);
507 		LIST_FOREACH(m, &lua_modules, mod_next)
508 			if (!strcmp(m->mod_name, module)) {
509 				md = m;
510 				break;
511 			}
512 	}
513 
514 	if (md != NULL)
515 		LIST_FOREACH(s, &lua_states, lua_next)
516 			if (s->K->L == L) {
517 				if (lua_verbose)
518 					device_printf(sc_self,
519 					    "require module %s\n",
520 					    md->mod_name);
521 				luaL_requiref(L, md->mod_name, md->open, 0);
522 
523 				LIST_FOREACH(m, &s->lua_modules, mod_next)
524 					if (m == md)
525 						return 1;
526 
527 				md->refcount++;
528 				LIST_INSERT_HEAD(&s->lua_modules, md, mod_next);
529 				return 1;
530 			}
531 
532 	lua_pushstring(L, "module not found");
533 	return lua_error(L);
534 }
535 
536 typedef struct {
537 	size_t size;
538 } __packed alloc_header_t;
539 
540 static void *
541 lua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
542 {
543 	void *nptr = NULL;
544 
545 	const size_t hdr_size = sizeof(alloc_header_t);
546 	alloc_header_t *hdr = (alloc_header_t *) ((char *) ptr - hdr_size);
547 
548 	if (nsize == 0) { /* freeing */
549 		if (ptr != NULL)
550 			kmem_intr_free(hdr, hdr->size);
551 	} else if (ptr != NULL && nsize <= hdr->size - hdr_size) /* shrinking */
552 		return ptr; /* don't need to reallocate */
553 	else { /* creating or expanding */
554 		km_flag_t sleep = cpu_intr_p() || cpu_softintr_p() ?
555 			KM_NOSLEEP : KM_SLEEP;
556 
557 		size_t alloc_size = nsize + hdr_size;
558 		alloc_header_t *nhdr = kmem_intr_alloc(alloc_size, sleep);
559 		if (nhdr == NULL) /* failed to allocate */
560 			return NULL;
561 
562 		nhdr->size = alloc_size;
563 		nptr = (void *) ((char *) nhdr + hdr_size);
564 
565 		if (ptr != NULL) { /* expanding */
566 			memcpy(nptr, ptr, osize);
567 			kmem_intr_free(hdr, hdr->size);
568 		}
569 	}
570 	return nptr;
571 }
572 
573 static const char *
574 lua_reader(lua_State *L, void *data, size_t *size)
575 {
576 	struct lua_loadstate *ls;
577 	static char buf[1024];
578 	size_t rsiz;
579 
580 	ls = data;
581 	if (ls->size < sizeof(buf))
582 		rsiz = ls->size;
583 	else
584 		rsiz = sizeof(buf);
585 	vn_rdwr(UIO_READ, ls->vp, buf, rsiz, ls->off, UIO_SYSSPACE,
586 	    0, curlwp->l_cred, NULL, curlwp);
587 	if (ls->off == 0L && lua_bytecode_on == false && buf[0] == 0x1b) {
588 		*size = 0L;
589 		lua_pushstring(L, "loading of bytecode is not allowed");
590 		lua_error(L);
591 		return NULL;
592 	} else {
593 		*size = rsiz;
594 		ls->off += *size;
595 		ls->size -= *size;
596 	}
597 	return buf;
598 }
599 
600 static void
601 lua_maxcount(lua_State *L, lua_Debug *d)
602 {
603 	lua_pushstring(L, "maximum instruction count exceeded");
604 	lua_error(L);
605 }
606 
607 int
608 klua_mod_register(const char *name, lua_CFunction open)
609 {
610 	struct lua_module *m;
611 
612 	LIST_FOREACH(m, &lua_modules, mod_next)
613 		if (!strcmp(m->mod_name, name))
614 			return EBUSY;
615 	m = kmem_zalloc(sizeof(struct lua_module), KM_SLEEP);
616 	strlcpy(m->mod_name, name, LUA_MAX_MODNAME);
617 	m->open = open;
618 	m->refcount = 0;
619 	LIST_INSERT_HEAD(&lua_modules, m, mod_next);
620 	if (lua_verbose)
621 		device_printf(sc_self, "registered lua module %s\n", name);
622 	return 0;
623 }
624 
625 int
626 klua_mod_unregister(const char *name)
627 {
628 	struct lua_module *m;
629 
630 	LIST_FOREACH(m, &lua_modules, mod_next)
631 		if (!strcmp(m->mod_name, name)) {
632 			if (m->refcount == 0) {
633 				LIST_REMOVE(m, mod_next);
634 				kmem_free(m, sizeof(struct lua_module));
635 				if (lua_verbose)
636 					device_printf(sc_self,
637 					    "unregistered lua module %s\n",
638 					    name);
639 				return 0;
640 			} else
641 				return EBUSY;
642 		}
643 	return 0;
644 }
645 
646 klua_State *
647 klua_newstate(lua_Alloc f, void *ud, const char *name, const char *desc,
648     int ipl)
649 {
650 	klua_State *K;
651 	struct lua_state *s;
652 	struct lua_softc *sc;
653 	int error = 0;
654 
655 	s = kmem_zalloc(sizeof(struct lua_state), KM_SLEEP);
656 	sc = device_private(sc_self);
657 	mutex_enter(&sc->sc_state_lock);
658 	while (sc->sc_state == true) {
659 		error = cv_wait_sig(&sc->sc_state_cv, &sc->sc_state_lock);
660 		if (error)
661 			break;
662 	}
663 	if (!error)
664 		sc->sc_state = true;
665 	mutex_exit(&sc->sc_state_lock);
666 
667 	if (error) {
668 		kmem_free(s, sizeof(struct lua_state));
669 		return NULL;
670 	}
671 
672 	K = kmem_zalloc(sizeof(klua_State), KM_SLEEP);
673 	K->L = lua_newstate(f, ud);
674 	K->ks_user = false;
675 	if (K->L == NULL) {
676 		kmem_free(K, sizeof(klua_State));
677 		K = NULL;
678 		goto finish;
679 	}
680 
681 	strlcpy(s->lua_name, name, MAX_LUA_NAME);
682 	strlcpy(s->lua_desc, desc, MAX_LUA_DESC);
683 	s->K = K;
684 
685 	if (lua_require_on || lua_autoload_on) {
686 		lua_pushcfunction(K->L, lua_require);
687 		lua_setglobal(K->L, "require");
688 	}
689 	LIST_INSERT_HEAD(&lua_states, s, lua_next);
690 
691 	mutex_init(&K->ks_lock, MUTEX_DEFAULT, ipl);
692 
693 finish:
694 	mutex_enter(&sc->sc_state_lock);
695 	sc->sc_state = false;
696 	cv_signal(&sc->sc_state_cv);
697 	mutex_exit(&sc->sc_state_lock);
698 	return K;
699 }
700 
701 inline klua_State *
702 kluaL_newstate(const char *name, const char *desc, int ipl)
703 {
704 	return klua_newstate(lua_alloc, NULL, name, desc, ipl);
705 }
706 
707 void
708 klua_close(klua_State *K)
709 {
710 	struct lua_state *s;
711 	struct lua_softc *sc;
712 	struct lua_module *m;
713 	int error = 0;
714 
715 	/* XXX consider registering a handler instead of a fixed name. */
716 	lua_getglobal(K->L, "onClose");
717 	if (lua_isfunction(K->L, -1))
718 		lua_pcall(K->L, -1, 0, 0);
719 
720 	sc = device_private(sc_self);
721 	mutex_enter(&sc->sc_state_lock);
722 	while (sc->sc_state == true) {
723 		error = cv_wait_sig(&sc->sc_state_cv, &sc->sc_state_lock);
724 		if (error)
725 			break;
726 	}
727 	if (!error)
728 		sc->sc_state = true;
729 	mutex_exit(&sc->sc_state_lock);
730 
731 	if (error)
732 		return;		/* Nothing we can do... */
733 
734 	LIST_FOREACH(s, &lua_states, lua_next)
735 		if (s->K == K) {
736 			LIST_REMOVE(s, lua_next);
737 			LIST_FOREACH(m, &s->lua_modules, mod_next)
738 				m->refcount--;
739 			kmem_free(s, sizeof(struct lua_state));
740 		}
741 
742 	lua_close(K->L);
743 	mutex_destroy(&K->ks_lock);
744 	kmem_free(K, sizeof(klua_State));
745 
746 	mutex_enter(&sc->sc_state_lock);
747 	sc->sc_state = false;
748 	cv_signal(&sc->sc_state_cv);
749 	mutex_exit(&sc->sc_state_lock);
750 }
751 
752 static klua_State *
753 klua_find(const char *name)
754 {
755 	struct lua_state *s;
756 	struct lua_softc *sc;
757 	klua_State *K;
758 	int error = 0;
759 
760 	K = NULL;
761 	sc = device_private(sc_self);
762 	mutex_enter(&sc->sc_state_lock);
763 	while (sc->sc_state == true) {
764 		error = cv_wait_sig(&sc->sc_state_cv, &sc->sc_state_lock);
765 		if (error)
766 			break;
767 	}
768 	if (!error)
769 		sc->sc_state = true;
770 	mutex_exit(&sc->sc_state_lock);
771 
772 	if (error)
773 		return NULL;
774 
775 	LIST_FOREACH(s, &lua_states, lua_next)
776 		if (!strcmp(s->lua_name, name)) {
777 			K = s->K;
778 			break;
779 		}
780 
781 	mutex_enter(&sc->sc_state_lock);
782 	sc->sc_state = false;
783 	cv_signal(&sc->sc_state_cv);
784 	mutex_exit(&sc->sc_state_lock);
785 	return K;
786 }
787 
788 inline void
789 klua_lock(klua_State *K)
790 {
791 	mutex_enter(&K->ks_lock);
792 }
793 
794 inline void
795 klua_unlock(klua_State *K)
796 {
797 	mutex_exit(&K->ks_lock);
798 }
799 
800 MODULE(MODULE_CLASS_MISC, lua, NULL);
801 
802 #ifdef _MODULE
803 static const struct cfiattrdata luabus_iattrdata = {
804 	"luabus", 0, { { NULL, NULL, 0 },}
805 };
806 
807 static const struct cfiattrdata *const lua_attrs[] = {
808 	&luabus_iattrdata, NULL
809 };
810 
811 CFDRIVER_DECL(lua, DV_DULL, lua_attrs);
812 extern struct cfattach lua_ca;
813 static int lualoc[] = {
814 	-1,
815 	-1,
816 	-1
817 };
818 
819 static struct cfdata lua_cfdata[] = {
820 	{
821 		.cf_name = "lua",
822 		.cf_atname = "lua",
823 		.cf_unit = 0,
824 		.cf_fstate = FSTATE_STAR,
825 		.cf_loc = lualoc,
826 		.cf_flags = 0,
827 		.cf_pspec = NULL,
828 	},
829 	{ NULL, NULL, 0, FSTATE_NOTFOUND, NULL, 0, NULL }
830 };
831 #endif
832 
833 static int
834 lua_modcmd(modcmd_t cmd, void *opaque)
835 {
836 #ifdef _MODULE
837 	devmajor_t cmajor, bmajor;
838 	int error = 0;
839 
840 	cmajor = bmajor = NODEVMAJOR;
841 #endif
842 	switch (cmd) {
843 	case MODULE_CMD_INIT:
844 #ifdef _MODULE
845 		error = config_cfdriver_attach(&lua_cd);
846 		if (error)
847 			return error;
848 
849 		error = config_cfattach_attach(lua_cd.cd_name,
850 		    &lua_ca);
851 		if (error) {
852 			config_cfdriver_detach(&lua_cd);
853 			aprint_error("%s: unable to register cfattach\n",
854 			    lua_cd.cd_name);
855 			return error;
856 		}
857 		error = config_cfdata_attach(lua_cfdata, 1);
858 		if (error) {
859 			config_cfattach_detach(lua_cd.cd_name,
860 			    &lua_ca);
861 			config_cfdriver_detach(&lua_cd);
862 			aprint_error("%s: unable to register cfdata\n",
863 			    lua_cd.cd_name);
864 			return error;
865 		}
866 		error = devsw_attach(lua_cd.cd_name, NULL, &bmajor,
867 		    &lua_cdevsw, &cmajor);
868 		if (error) {
869 			aprint_error("%s: unable to register devsw\n",
870 			    lua_cd.cd_name);
871 			config_cfattach_detach(lua_cd.cd_name, &lua_ca);
872 			config_cfdriver_detach(&lua_cd);
873 			return error;
874 		}
875 		config_attach_pseudo(lua_cfdata);
876 #endif
877 		return 0;
878 	case MODULE_CMD_FINI:
879 #ifdef _MODULE
880 		error = config_cfdata_detach(lua_cfdata);
881 		if (error)
882 			return error;
883 
884 		config_cfattach_detach(lua_cd.cd_name, &lua_ca);
885 		config_cfdriver_detach(&lua_cd);
886 		devsw_detach(NULL, &lua_cdevsw);
887 #endif
888 		return 0;
889 	case MODULE_CMD_AUTOUNLOAD:
890 		/* no auto-unload */
891 		return EBUSY;
892 	default:
893 		return ENOTTY;
894 	}
895 }
896