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