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