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