xref: /netbsd-src/lib/libpuffs/puffs.c (revision c2f76ff004a2cb67efe5b12d97bd3ef7fe89e18d)
1 /*	$NetBSD: puffs.c,v 1.115 2010/12/06 14:50:34 pooka Exp $	*/
2 
3 /*
4  * Copyright (c) 2005, 2006, 2007  Antti Kantee.  All Rights Reserved.
5  *
6  * Development of this software was supported by the
7  * Google Summer of Code program and the Ulla Tuominen Foundation.
8  * The Google SoC project was mentored by Bill Studenmund.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
20  * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
21  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22  * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR 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 OR
25  * 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 #include <sys/cdefs.h>
33 #if !defined(lint)
34 __RCSID("$NetBSD: puffs.c,v 1.115 2010/12/06 14:50:34 pooka Exp $");
35 #endif /* !lint */
36 
37 #include <sys/param.h>
38 #include <sys/mount.h>
39 
40 #include <assert.h>
41 #include <err.h>
42 #include <errno.h>
43 #include <fcntl.h>
44 #include <mntopts.h>
45 #include <paths.h>
46 #include <pthread.h>
47 #include <puffs.h>
48 #include <stdio.h>
49 #include <stdlib.h>
50 #include <string.h>
51 #include <syslog.h>
52 #include <unistd.h>
53 
54 #include "puffs_priv.h"
55 
56 /* Most file systems want this for opts, so just give it to them */
57 const struct mntopt puffsmopts[] = {
58 	MOPT_STDOPTS,
59 	PUFFSMOPT_STD,
60 	MOPT_NULL,
61 };
62 
63 pthread_mutex_t pu_lock = PTHREAD_MUTEX_INITIALIZER;
64 
65 #define FILLOP(lower, upper)						\
66 do {									\
67 	if (pops->puffs_node_##lower)					\
68 		opmask[PUFFS_VN_##upper] = 1;				\
69 } while (/*CONSTCOND*/0)
70 static void
71 fillvnopmask(struct puffs_ops *pops, struct puffs_kargs *pa)
72 {
73 	uint8_t *opmask = pa->pa_vnopmask;
74 
75 	memset(opmask, 0, sizeof(pa->pa_vnopmask));
76 
77 	FILLOP(create,   CREATE);
78 	FILLOP(mknod,    MKNOD);
79 	FILLOP(open,     OPEN);
80 	FILLOP(close,    CLOSE);
81 	FILLOP(access,   ACCESS);
82 	FILLOP(getattr,  GETATTR);
83 	FILLOP(setattr,  SETATTR);
84 	FILLOP(poll,     POLL);
85 	FILLOP(mmap,     MMAP);
86 	FILLOP(fsync,    FSYNC);
87 	FILLOP(seek,     SEEK);
88 	FILLOP(remove,   REMOVE);
89 	FILLOP(link,     LINK);
90 	FILLOP(rename,   RENAME);
91 	FILLOP(mkdir,    MKDIR);
92 	FILLOP(rmdir,    RMDIR);
93 	FILLOP(symlink,  SYMLINK);
94 	FILLOP(readdir,  READDIR);
95 	FILLOP(readlink, READLINK);
96 	FILLOP(reclaim,  RECLAIM);
97 	FILLOP(inactive, INACTIVE);
98 	FILLOP(print,    PRINT);
99 	FILLOP(read,     READ);
100 	FILLOP(write,    WRITE);
101 	FILLOP(abortop,  ABORTOP);
102 	FILLOP(pathconf, PATHCONF);
103 
104 	FILLOP(getextattr,  GETEXTATTR);
105 	FILLOP(setextattr,  SETEXTATTR);
106 	FILLOP(listextattr, LISTEXTATTR);
107 	FILLOP(deleteextattr, DELETEEXTATTR);
108 }
109 #undef FILLOP
110 
111 /*
112  * Go over all framev entries and write everything we can.  This is
113  * mostly for the benefit of delivering "unmount" to the kernel.
114  */
115 static void
116 finalpush(struct puffs_usermount *pu)
117 {
118 	struct puffs_fctrl_io *fio;
119 
120 	LIST_FOREACH(fio, &pu->pu_ios, fio_entries) {
121 		if (fio->stat & FIO_WRGONE)
122 			continue;
123 
124 		puffs__framev_output(pu, fio->fctrl, fio);
125 	}
126 }
127 
128 /*ARGSUSED*/
129 void
130 puffs_kernerr_abort(struct puffs_usermount *pu, uint8_t type,
131 	int error, const char *str, puffs_cookie_t cookie)
132 {
133 
134 	fprintf(stderr, "abort: type %d, error %d, cookie %p (%s)\n",
135 	    type, error, cookie, str);
136 	abort();
137 }
138 
139 /*ARGSUSED*/
140 void
141 puffs_kernerr_log(struct puffs_usermount *pu, uint8_t type,
142 	int error, const char *str, puffs_cookie_t cookie)
143 {
144 
145 	syslog(LOG_WARNING, "kernel: type %d, error %d, cookie %p (%s)\n",
146 	    type, error, cookie, str);
147 }
148 
149 int
150 puffs_getselectable(struct puffs_usermount *pu)
151 {
152 
153 	return pu->pu_fd;
154 }
155 
156 uint64_t
157 puffs__nextreq(struct puffs_usermount *pu)
158 {
159 	uint64_t rv;
160 
161 	PU_LOCK();
162 	rv = pu->pu_nextreq++ | (uint64_t)1<<63;
163 	PU_UNLOCK();
164 
165 	return rv;
166 }
167 
168 int
169 puffs_setblockingmode(struct puffs_usermount *pu, int mode)
170 {
171 	int rv, x;
172 
173 	assert(puffs_getstate(pu) == PUFFS_STATE_RUNNING);
174 
175 	if (mode != PUFFSDEV_BLOCK && mode != PUFFSDEV_NONBLOCK) {
176 		errno = EINVAL;
177 		return -1;
178 	}
179 
180 	x = mode;
181 	rv = ioctl(pu->pu_fd, FIONBIO, &x);
182 
183 	if (rv == 0) {
184 		if (mode == PUFFSDEV_BLOCK)
185 			pu->pu_state &= ~PU_ASYNCFD;
186 		else
187 			pu->pu_state |= PU_ASYNCFD;
188 	}
189 
190 	return rv;
191 }
192 
193 int
194 puffs_getstate(struct puffs_usermount *pu)
195 {
196 
197 	return pu->pu_state & PU_STATEMASK;
198 }
199 
200 void
201 puffs_setstacksize(struct puffs_usermount *pu, size_t ss)
202 {
203 	long psize, minsize;
204 	int stackshift;
205 	int bonus;
206 
207 	assert(puffs_getstate(pu) == PUFFS_STATE_BEFOREMOUNT);
208 
209 	psize = sysconf(_SC_PAGESIZE);
210 	minsize = 4*psize;
211 	if (ss < (size_t)minsize || ss == PUFFS_STACKSIZE_MIN) {
212 		if (ss != PUFFS_STACKSIZE_MIN)
213 			fprintf(stderr, "puffs_setstacksize: adjusting "
214 			    "stacksize to minimum %ld\n", minsize);
215 		ss = 4*psize;
216 	}
217 
218 	stackshift = -1;
219 	bonus = 0;
220 	while (ss) {
221 		if (ss & 0x1)
222 			bonus++;
223 		ss >>= 1;
224 		stackshift++;
225 	}
226 	if (bonus > 1) {
227 		stackshift++;
228 		fprintf(stderr, "puffs_setstacksize: using next power of two: "
229 		    "%d\n", 1<<stackshift);
230 	}
231 
232 	pu->pu_cc_stackshift = stackshift;
233 }
234 
235 struct puffs_pathobj *
236 puffs_getrootpathobj(struct puffs_usermount *pu)
237 {
238 	struct puffs_node *pnr;
239 
240 	pnr = pu->pu_pn_root;
241 	if (pnr == NULL) {
242 		errno = ENOENT;
243 		return NULL;
244 	}
245 
246 	return &pnr->pn_po;
247 }
248 
249 void
250 puffs_setroot(struct puffs_usermount *pu, struct puffs_node *pn)
251 {
252 
253 	pu->pu_pn_root = pn;
254 }
255 
256 struct puffs_node *
257 puffs_getroot(struct puffs_usermount *pu)
258 {
259 
260 	return pu->pu_pn_root;
261 }
262 
263 void
264 puffs_setrootinfo(struct puffs_usermount *pu, enum vtype vt,
265 	vsize_t vsize, dev_t rdev)
266 {
267 	struct puffs_kargs *pargs = pu->pu_kargp;
268 
269 	if (puffs_getstate(pu) != PUFFS_STATE_BEFOREMOUNT) {
270 		warnx("puffs_setrootinfo: call has effect only "
271 		    "before mount\n");
272 		return;
273 	}
274 
275 	pargs->pa_root_vtype = vt;
276 	pargs->pa_root_vsize = vsize;
277 	pargs->pa_root_rdev = rdev;
278 }
279 
280 void *
281 puffs_getspecific(struct puffs_usermount *pu)
282 {
283 
284 	return pu->pu_privdata;
285 }
286 
287 void
288 puffs_setspecific(struct puffs_usermount *pu, void *privdata)
289 {
290 
291 	pu->pu_privdata = privdata;
292 }
293 
294 void
295 puffs_setmntinfo(struct puffs_usermount *pu,
296 	const char *mntfromname, const char *puffsname)
297 {
298 	struct puffs_kargs *pargs = pu->pu_kargp;
299 
300 	(void)strlcpy(pargs->pa_mntfromname, mntfromname,
301 	    sizeof(pargs->pa_mntfromname));
302 	(void)strlcpy(pargs->pa_typename, puffsname,
303 	    sizeof(pargs->pa_typename));
304 }
305 
306 size_t
307 puffs_getmaxreqlen(struct puffs_usermount *pu)
308 {
309 
310 	return pu->pu_maxreqlen;
311 }
312 
313 void
314 puffs_setmaxreqlen(struct puffs_usermount *pu, size_t reqlen)
315 {
316 
317 	if (puffs_getstate(pu) != PUFFS_STATE_BEFOREMOUNT)
318 		warnx("puffs_setmaxreqlen: call has effect only "
319 		    "before mount\n");
320 
321 	pu->pu_kargp->pa_maxmsglen = reqlen;
322 }
323 
324 void
325 puffs_setfhsize(struct puffs_usermount *pu, size_t fhsize, int flags)
326 {
327 
328 	if (puffs_getstate(pu) != PUFFS_STATE_BEFOREMOUNT)
329 		warnx("puffs_setfhsize: call has effect only before mount\n");
330 
331 	pu->pu_kargp->pa_fhsize = fhsize;
332 	pu->pu_kargp->pa_fhflags = flags;
333 }
334 
335 void
336 puffs_setncookiehash(struct puffs_usermount *pu, int nhash)
337 {
338 
339 	if (puffs_getstate(pu) != PUFFS_STATE_BEFOREMOUNT)
340 		warnx("puffs_setfhsize: call has effect only before mount\n");
341 
342 	pu->pu_kargp->pa_nhashbuckets = nhash;
343 }
344 
345 void
346 puffs_set_pathbuild(struct puffs_usermount *pu, pu_pathbuild_fn fn)
347 {
348 
349 	pu->pu_pathbuild = fn;
350 }
351 
352 void
353 puffs_set_pathtransform(struct puffs_usermount *pu, pu_pathtransform_fn fn)
354 {
355 
356 	pu->pu_pathtransform = fn;
357 }
358 
359 void
360 puffs_set_pathcmp(struct puffs_usermount *pu, pu_pathcmp_fn fn)
361 {
362 
363 	pu->pu_pathcmp = fn;
364 }
365 
366 void
367 puffs_set_pathfree(struct puffs_usermount *pu, pu_pathfree_fn fn)
368 {
369 
370 	pu->pu_pathfree = fn;
371 }
372 
373 void
374 puffs_set_namemod(struct puffs_usermount *pu, pu_namemod_fn fn)
375 {
376 
377 	pu->pu_namemod = fn;
378 }
379 
380 void
381 puffs_set_errnotify(struct puffs_usermount *pu, pu_errnotify_fn fn)
382 {
383 
384 	pu->pu_errnotify = fn;
385 }
386 
387 void
388 puffs_set_cmap(struct puffs_usermount *pu, pu_cmap_fn fn)
389 {
390 
391 	pu->pu_cmap = fn;
392 }
393 
394 void
395 puffs_ml_setloopfn(struct puffs_usermount *pu, puffs_ml_loop_fn lfn)
396 {
397 
398 	pu->pu_ml_lfn = lfn;
399 }
400 
401 void
402 puffs_ml_settimeout(struct puffs_usermount *pu, struct timespec *ts)
403 {
404 
405 	if (ts == NULL) {
406 		pu->pu_ml_timep = NULL;
407 	} else {
408 		pu->pu_ml_timeout = *ts;
409 		pu->pu_ml_timep = &pu->pu_ml_timeout;
410 	}
411 }
412 
413 void
414 puffs_set_prepost(struct puffs_usermount *pu,
415 	pu_prepost_fn pre, pu_prepost_fn pst)
416 {
417 
418 	pu->pu_oppre = pre;
419 	pu->pu_oppost = pst;
420 }
421 
422 void
423 puffs_setback(struct puffs_cc *pcc, int whatback)
424 {
425 	struct puffs_req *preq = puffs__framebuf_getdataptr(pcc->pcc_pb);
426 
427 	assert(PUFFSOP_OPCLASS(preq->preq_opclass) == PUFFSOP_VN && (
428 	    preq->preq_optype == PUFFS_VN_OPEN ||
429 	    preq->preq_optype == PUFFS_VN_MMAP ||
430 	    preq->preq_optype == PUFFS_VN_REMOVE ||
431 	    preq->preq_optype == PUFFS_VN_RMDIR ||
432 	    preq->preq_optype == PUFFS_VN_INACTIVE));
433 
434 	preq->preq_setbacks |= whatback & PUFFS_SETBACK_MASK;
435 }
436 
437 int
438 puffs_daemon(struct puffs_usermount *pu, int nochdir, int noclose)
439 {
440 	long int n;
441 	int parent, value, fd;
442 
443 	if (pipe(pu->pu_dpipe) == -1)
444 		return -1;
445 
446 	switch (fork()) {
447 	case -1:
448 		return -1;
449 	case 0:
450 		parent = 0;
451 		break;
452 	default:
453 		parent = 1;
454 		break;
455 	}
456 	pu->pu_state |= PU_PUFFSDAEMON;
457 
458 	if (parent) {
459 		close(pu->pu_dpipe[1]);
460 		n = read(pu->pu_dpipe[0], &value, sizeof(int));
461 		if (n == -1)
462 			err(1, "puffs_daemon");
463 		if (n != sizeof(value))
464 			errx(1, "puffs_daemon got %ld bytes", n);
465 		if (value) {
466 			errno = value;
467 			err(1, "puffs_daemon");
468 		}
469 		exit(0);
470 	} else {
471 		if (setsid() == -1)
472 			goto fail;
473 
474 		if (!nochdir)
475 			chdir("/");
476 
477 		if (!noclose) {
478 			fd = open(_PATH_DEVNULL, O_RDWR, 0);
479 			if (fd == -1)
480 				goto fail;
481 			dup2(fd, STDIN_FILENO);
482 			dup2(fd, STDOUT_FILENO);
483 			dup2(fd, STDERR_FILENO);
484 			if (fd > STDERR_FILENO)
485 				close(fd);
486 		}
487 		return 0;
488 	}
489 
490  fail:
491 	n = write(pu->pu_dpipe[1], &errno, sizeof(int));
492 	assert(n == 4);
493 	return -1;
494 }
495 
496 static void
497 shutdaemon(struct puffs_usermount *pu, int error)
498 {
499 	ssize_t n;
500 
501 	n = write(pu->pu_dpipe[1], &error, sizeof(int));
502 	assert(n == 4);
503 	close(pu->pu_dpipe[0]);
504 	close(pu->pu_dpipe[1]);
505 	pu->pu_state &= ~PU_PUFFSDAEMON;
506 }
507 
508 int
509 puffs_mount(struct puffs_usermount *pu, const char *dir, int mntflags,
510 	puffs_cookie_t cookie)
511 {
512 	int rv, fd, sverrno;
513 	char *comfd;
514 
515 	pu->pu_kargp->pa_root_cookie = cookie;
516 
517 	/* XXXkludgehere */
518 	/* kauth doesn't provide this service any longer */
519 	if (geteuid() != 0)
520 		mntflags |= MNT_NOSUID | MNT_NODEV;
521 
522 	/*
523 	 * Undocumented...  Well, documented only here.
524 	 *
525 	 * This is used for imaginative purposes.  If the env variable is
526 	 * set, puffs_mount() doesn't do the regular mount procedure.
527 	 * Rather, it crams the mount data down the comfd and sets comfd as
528 	 * the puffs descriptor.
529 	 *
530 	 * This shouldn't be used unless you can read my mind ( ... or write
531 	 * it, not to mention execute it, but that's starting to get silly).
532 	 */
533 	if ((comfd = getenv("PUFFS_COMFD")) != NULL) {
534 		size_t len;
535 
536 		if (sscanf(comfd, "%d", &pu->pu_fd) != 1) {
537 			errno = EINVAL;
538 			rv = -1;
539 			goto out;
540 		}
541 		/* check that what we got at least resembles an fd */
542 		if (fcntl(pu->pu_fd, F_GETFL) == -1) {
543 			rv = -1;
544 			goto out;
545 		}
546 
547 #define allwrite(buf, len)						\
548 do {									\
549 	ssize_t al_rv;							\
550 	al_rv = write(pu->pu_fd, buf, len);				\
551 	if ((size_t)al_rv != len) {					\
552 		if (al_rv != -1)					\
553 			errno = EIO;					\
554 		rv = -1;						\
555 		goto out;						\
556 	}								\
557 } while (/*CONSTCOND*/0)
558 		len = strlen(dir)+1;
559 		allwrite(&len, sizeof(len));
560 		allwrite(dir, len);
561 		len = strlen(pu->pu_kargp->pa_mntfromname)+1;
562 		allwrite(&len, sizeof(len));
563 		allwrite(pu->pu_kargp->pa_mntfromname, len);
564 		allwrite(&mntflags, sizeof(mntflags));
565 		len = sizeof(*pu->pu_kargp);
566 		allwrite(&len, sizeof(len));
567 		allwrite(pu->pu_kargp, sizeof(*pu->pu_kargp));
568 		allwrite(&pu->pu_flags, sizeof(pu->pu_flags));
569 #undef allwrite
570 
571 		rv = 0;
572 	} else {
573 		char rp[MAXPATHLEN];
574 
575 		if (realpath(dir, rp) == NULL) {
576 			rv = -1;
577 			goto out;
578 		}
579 
580 		if (strcmp(dir, rp) != 0) {
581 			warnx("puffs_mount: \"%s\" is a relative path.", dir);
582 			warnx("puffs_mount: using \"%s\" instead.", rp);
583 		}
584 
585 		fd = open(_PATH_PUFFS, O_RDWR);
586 		if (fd == -1) {
587 			warnx("puffs_mount: cannot open %s", _PATH_PUFFS);
588 			rv = -1;
589 			goto out;
590 		}
591 		if (fd <= 2)
592 			warnx("puffs_mount: device fd %d (<= 2), sure this is "
593 			    "what you want?", fd);
594 
595 		pu->pu_kargp->pa_fd = pu->pu_fd = fd;
596 		if ((rv = mount(MOUNT_PUFFS, rp, mntflags,
597 		    pu->pu_kargp, sizeof(struct puffs_kargs))) == -1)
598 			goto out;
599 	}
600 
601 	PU_SETSTATE(pu, PUFFS_STATE_RUNNING);
602 
603  out:
604 	if (rv != 0)
605 		sverrno = errno;
606 	else
607 		sverrno = 0;
608 	free(pu->pu_kargp);
609 	pu->pu_kargp = NULL;
610 
611 	if (pu->pu_state & PU_PUFFSDAEMON)
612 		shutdaemon(pu, sverrno);
613 
614 	errno = sverrno;
615 	return rv;
616 }
617 
618 struct puffs_usermount *
619 puffs_init(struct puffs_ops *pops, const char *mntfromname,
620 	const char *puffsname, void *priv, uint32_t pflags)
621 {
622 	struct puffs_usermount *pu;
623 	struct puffs_kargs *pargs;
624 	int sverrno;
625 
626 	if (puffsname == PUFFS_DEFER)
627 		puffsname = "n/a";
628 	if (mntfromname == PUFFS_DEFER)
629 		mntfromname = "n/a";
630 	if (priv == PUFFS_DEFER)
631 		priv = NULL;
632 
633 	pu = malloc(sizeof(struct puffs_usermount));
634 	if (pu == NULL)
635 		goto failfree;
636 	memset(pu, 0, sizeof(struct puffs_usermount));
637 
638 	pargs = pu->pu_kargp = malloc(sizeof(struct puffs_kargs));
639 	if (pargs == NULL)
640 		goto failfree;
641 	memset(pargs, 0, sizeof(struct puffs_kargs));
642 
643 	pargs->pa_vers = PUFFSVERSION;
644 	pargs->pa_flags = PUFFS_FLAG_KERN(pflags);
645 	fillvnopmask(pops, pargs);
646 	puffs_setmntinfo(pu, mntfromname, puffsname);
647 
648 	puffs_zerostatvfs(&pargs->pa_svfsb);
649 	pargs->pa_root_cookie = NULL;
650 	pargs->pa_root_vtype = VDIR;
651 	pargs->pa_root_vsize = 0;
652 	pargs->pa_root_rdev = 0;
653 	pargs->pa_maxmsglen = 0;
654 	if (/*CONSTCOND*/ sizeof(time_t) == 4)
655 		pargs->pa_time32 = 1;
656 	else
657 		pargs->pa_time32 = 0;
658 
659 	pu->pu_flags = pflags;
660 	pu->pu_ops = *pops;
661 	free(pops); /* XXX */
662 
663 	pu->pu_privdata = priv;
664 	pu->pu_cc_stackshift = PUFFS_CC_STACKSHIFT_DEFAULT;
665 	LIST_INIT(&pu->pu_pnodelst);
666 	LIST_INIT(&pu->pu_ios);
667 	LIST_INIT(&pu->pu_ios_rmlist);
668 	LIST_INIT(&pu->pu_ccmagazin);
669 	TAILQ_INIT(&pu->pu_sched);
670 
671 	pu->pu_framectrl[PU_FRAMECTRL_FS].rfb = puffs__fsframe_read;
672 	pu->pu_framectrl[PU_FRAMECTRL_FS].wfb = puffs__fsframe_write;
673 	pu->pu_framectrl[PU_FRAMECTRL_FS].cmpfb = puffs__fsframe_cmp;
674 	pu->pu_framectrl[PU_FRAMECTRL_FS].gotfb = puffs__fsframe_gotframe;
675 	pu->pu_framectrl[PU_FRAMECTRL_FS].fdnotfn = puffs_framev_unmountonclose;
676 
677 	/* defaults for some user-settable translation functions */
678 	pu->pu_cmap = NULL; /* identity translation */
679 
680 	pu->pu_pathbuild = puffs_stdpath_buildpath;
681 	pu->pu_pathfree = puffs_stdpath_freepath;
682 	pu->pu_pathcmp = puffs_stdpath_cmppath;
683 	pu->pu_pathtransform = NULL;
684 	pu->pu_namemod = NULL;
685 
686 	pu->pu_errnotify = puffs_kernerr_log;
687 
688 	PU_SETSTATE(pu, PUFFS_STATE_BEFOREMOUNT);
689 
690 	return pu;
691 
692  failfree:
693 	/* can't unmount() from here for obvious reasons */
694 	sverrno = errno;
695 	free(pu);
696 	errno = sverrno;
697 	return NULL;
698 }
699 
700 void
701 puffs_cancel(struct puffs_usermount *pu, int error)
702 {
703 
704 	assert(puffs_getstate(pu) < PUFFS_STATE_RUNNING);
705 	shutdaemon(pu, error);
706 	free(pu);
707 }
708 
709 /*ARGSUSED1*/
710 int
711 puffs_exit(struct puffs_usermount *pu, int unused /* strict compat */)
712 {
713 	struct puffs_framebuf *pb;
714 	struct puffs_req *preq;
715 	void *winp;
716 	size_t winlen;
717 	int sverrno;
718 
719 	pb = puffs_framebuf_make();
720 	if (pb == NULL) {
721 		errno = ENOMEM;
722 		return -1;
723 	}
724 
725 	winlen = sizeof(struct puffs_req);
726 	if (puffs_framebuf_getwindow(pb, 0, &winp, &winlen) == -1) {
727 		sverrno = errno;
728 		puffs_framebuf_destroy(pb);
729 		errno = sverrno;
730 		return -1;
731 	}
732 	preq = winp;
733 
734 	preq->preq_buflen = sizeof(struct puffs_req);
735 	preq->preq_opclass = PUFFSOP_UNMOUNT;
736 	preq->preq_id = puffs__nextreq(pu);
737 
738 	puffs_framev_enqueue_justsend(pu, puffs_getselectable(pu), pb, 1, 0);
739 
740 	return 0;
741 }
742 
743 /* no sigset_t static intializer */
744 static int sigs[NSIG] = { 0, };
745 static int sigcatch = 0;
746 
747 int
748 puffs_unmountonsignal(int sig, bool sigignore)
749 {
750 
751 	if (sig < 0 || sig >= (int)NSIG) {
752 		errno = EINVAL;
753 		return -1;
754 	}
755 	if (sigignore)
756 		if (signal(sig, SIG_IGN) == SIG_ERR)
757 			return -1;
758 
759 	if (!sigs[sig])
760 		sigcatch++;
761 	sigs[sig] = 1;
762 
763 	return 0;
764 }
765 
766 /*
767  * Actual mainloop.  This is called from a context which can block.
768  * It is called either from puffs_mainloop (indirectly, via
769  * puffs_cc_continue() or from puffs_cc_yield()).
770  */
771 void
772 puffs__theloop(struct puffs_cc *pcc)
773 {
774 	struct puffs_usermount *pu = pcc->pcc_pu;
775 	struct puffs_framectrl *pfctrl;
776 	struct puffs_fctrl_io *fio;
777 	struct kevent *curev;
778 	size_t nchanges;
779 	int ndone;
780 
781 	while (puffs_getstate(pu) != PUFFS_STATE_UNMOUNTED) {
782 
783 		/*
784 		 * Schedule existing requests.
785 		 */
786 		while ((pcc = TAILQ_FIRST(&pu->pu_sched)) != NULL) {
787 			TAILQ_REMOVE(&pu->pu_sched, pcc, pcc_schedent);
788 			puffs__goto(pcc);
789 		}
790 
791 		if (pu->pu_ml_lfn)
792 			pu->pu_ml_lfn(pu);
793 
794 		/* XXX: can we still do these optimizations? */
795 #if 0
796 		/*
797 		 * Do this here, because:
798 		 *  a) loopfunc might generate some results
799 		 *  b) it's still "after" event handling (except for round 1)
800 		 */
801 		if (puffs_req_putput(ppr) == -1)
802 			goto out;
803 		puffs_req_resetput(ppr);
804 
805 		/* micro optimization: skip kevent syscall if possible */
806 		if (pu->pu_nfds == 1 && pu->pu_ml_timep == NULL
807 		    && (pu->pu_state & PU_ASYNCFD) == 0) {
808 			pfctrl = XXX->fctrl;
809 			puffs_framev_input(pu, pfctrl, XXX);
810 			continue;
811 		}
812 #endif
813 
814 		/* else: do full processing */
815 		/* Don't bother worrying about O(n) for now */
816 		LIST_FOREACH(fio, &pu->pu_ios, fio_entries) {
817 			if (fio->stat & FIO_WRGONE)
818 				continue;
819 
820 			pfctrl = fio->fctrl;
821 
822 			/*
823 			 * Try to write out everything to avoid the
824 			 * need for enabling EVFILT_WRITE.  The likely
825 			 * case is that we can fit everything into the
826 			 * socket buffer.
827 			 */
828 			puffs__framev_output(pu, pfctrl, fio);
829 		}
830 
831 		/*
832 		 * Build list of which to enable/disable in writecheck.
833 		 */
834 		nchanges = 0;
835 		LIST_FOREACH(fio, &pu->pu_ios, fio_entries) {
836 			if (fio->stat & FIO_WRGONE)
837 				continue;
838 
839 			/* en/disable write checks for kqueue as needed */
840 			assert((FIO_EN_WRITE(fio) && FIO_RM_WRITE(fio)) == 0);
841 			if (FIO_EN_WRITE(fio)) {
842 				EV_SET(&pu->pu_evs[nchanges], fio->io_fd,
843 				    EVFILT_WRITE, EV_ENABLE, 0, 0,
844 				    (uintptr_t)fio);
845 				fio->stat |= FIO_WR;
846 				nchanges++;
847 			}
848 			if (FIO_RM_WRITE(fio)) {
849 				EV_SET(&pu->pu_evs[nchanges], fio->io_fd,
850 				    EVFILT_WRITE, EV_DISABLE, 0, 0,
851 				    (uintptr_t)fio);
852 				fio->stat &= ~FIO_WR;
853 				nchanges++;
854 			}
855 		}
856 
857 		ndone = kevent(pu->pu_kq, pu->pu_evs, nchanges,
858 		    pu->pu_evs, pu->pu_nevs, pu->pu_ml_timep);
859 
860 		if (ndone == -1) {
861 			if (errno != EINTR)
862 				break;
863 			else
864 				continue;
865 		}
866 
867 		/* uoptimize */
868 		if (ndone == 0)
869 			continue;
870 
871 		/* iterate over the results */
872 		for (curev = pu->pu_evs; ndone--; curev++) {
873 			int what;
874 
875 #if 0
876 			/* get & possibly dispatch events from kernel */
877 			if (curev->ident == puffsfd) {
878 				if (puffs_req_handle(pgr, ppr, 0) == -1)
879 					goto out;
880 				continue;
881 			}
882 #endif
883 
884 			fio = (void *)curev->udata;
885 			if (__predict_true(fio))
886 				pfctrl = fio->fctrl;
887 			else
888 				pfctrl = NULL;
889 			if (curev->flags & EV_ERROR) {
890 				assert(curev->filter == EVFILT_WRITE);
891 				fio->stat &= ~FIO_WR;
892 
893 				/* XXX: how to know if it's a transient error */
894 				puffs__framev_writeclose(pu, fio,
895 				    (int)curev->data);
896 				puffs__framev_notify(fio, PUFFS_FBIO_ERROR);
897 				continue;
898 			}
899 
900 			what = 0;
901 			if (curev->filter == EVFILT_READ) {
902 				puffs__framev_input(pu, pfctrl, fio);
903 				what |= PUFFS_FBIO_READ;
904 			}
905 
906 			else if (curev->filter == EVFILT_WRITE) {
907 				puffs__framev_output(pu, pfctrl, fio);
908 				what |= PUFFS_FBIO_WRITE;
909 			}
910 
911 			else if (__predict_false(curev->filter==EVFILT_SIGNAL)){
912 				if ((pu->pu_state & PU_DONEXIT) == 0) {
913 					PU_SETSFLAG(pu, PU_DONEXIT);
914 					puffs_exit(pu, 0);
915 				}
916 			}
917 			if (what)
918 				puffs__framev_notify(fio, what);
919 		}
920 
921 		/*
922 		 * Really free fd's now that we don't have references
923 		 * to them.
924 		 */
925 		while ((fio = LIST_FIRST(&pu->pu_ios_rmlist)) != NULL) {
926 			LIST_REMOVE(fio, fio_entries);
927 			free(fio);
928 		}
929 	}
930 
931 	if (puffs__cc_restoremain(pu) == -1)
932 		warn("cannot restore main context.  impending doom");
933 }
934 int
935 puffs_mainloop(struct puffs_usermount *pu)
936 {
937 	struct puffs_fctrl_io *fio;
938 	struct puffs_cc *pcc;
939 	struct kevent *curev;
940 	size_t nevs;
941 	int sverrno, i;
942 
943 	assert(puffs_getstate(pu) >= PUFFS_STATE_RUNNING);
944 
945 	pu->pu_kq = kqueue();
946 	if (pu->pu_kq == -1)
947 		goto out;
948 	pu->pu_state |= PU_HASKQ;
949 
950 	puffs_setblockingmode(pu, PUFFSDEV_NONBLOCK);
951 	if (puffs__framev_addfd_ctrl(pu, puffs_getselectable(pu),
952 	    PUFFS_FBIO_READ | PUFFS_FBIO_WRITE,
953 	    &pu->pu_framectrl[PU_FRAMECTRL_FS]) == -1)
954 		goto out;
955 
956 	nevs = pu->pu_nevs + sigcatch;
957 	curev = realloc(pu->pu_evs, nevs * sizeof(struct kevent));
958 	if (curev == NULL)
959 		goto out;
960 	pu->pu_evs = curev;
961 	pu->pu_nevs = nevs;
962 
963 	LIST_FOREACH(fio, &pu->pu_ios, fio_entries) {
964 		EV_SET(curev, fio->io_fd, EVFILT_READ, EV_ADD,
965 		    0, 0, (uintptr_t)fio);
966 		curev++;
967 		EV_SET(curev, fio->io_fd, EVFILT_WRITE, EV_ADD | EV_DISABLE,
968 		    0, 0, (uintptr_t)fio);
969 		curev++;
970 	}
971 	for (i = 0; i < NSIG; i++) {
972 		if (sigs[i]) {
973 			EV_SET(curev, i, EVFILT_SIGNAL, EV_ADD | EV_ENABLE,
974 			    0, 0, 0);
975 			curev++;
976 		}
977 	}
978 	assert(curev - pu->pu_evs == (ssize_t)pu->pu_nevs);
979 	if (kevent(pu->pu_kq, pu->pu_evs, pu->pu_nevs, NULL, 0, NULL) == -1)
980 		goto out;
981 
982 	pu->pu_state |= PU_INLOOP;
983 
984 	/*
985 	 * Create alternate execution context and jump to it.  Note
986 	 * that we come "out" of savemain twice.  Where we come out
987 	 * of it depends on the architecture.  If the return address is
988 	 * stored on the stack, we jump out from puffs_cc_continue(),
989 	 * for a register return address from puffs__cc_savemain().
990 	 * PU_MAINRESTORE makes sure we DTRT in both cases.
991 	 */
992 	if (puffs__cc_create(pu, puffs__theloop, &pcc) == -1) {
993 		goto out;
994 	}
995 	if (puffs__cc_savemain(pu) == -1) {
996 		goto out;
997 	}
998 	if ((pu->pu_state & PU_MAINRESTORE) == 0)
999 		puffs_cc_continue(pcc);
1000 
1001 	finalpush(pu);
1002 	errno = 0;
1003 
1004  out:
1005 	/* store the real error for a while */
1006 	sverrno = errno;
1007 
1008 	errno = sverrno;
1009 	if (errno)
1010 		return -1;
1011 	else
1012 		return 0;
1013 }
1014