xref: /netbsd-src/sys/kern/uipc_usrreq.c (revision eb961d0e02b7a46a9acfa877b02df48df6637278)
1 /*	$NetBSD: uipc_usrreq.c,v 1.87 2006/03/01 02:06:11 christos Exp $	*/
2 
3 /*-
4  * Copyright (c) 1998, 2000, 2004 The NetBSD Foundation, Inc.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to The NetBSD Foundation
8  * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
9  * NASA Ames Research Center.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  * 3. All advertising materials mentioning features or use of this software
20  *    must display the following acknowledgement:
21  *	This product includes software developed by the NetBSD
22  *	Foundation, Inc. and its contributors.
23  * 4. Neither the name of The NetBSD Foundation nor the names of its
24  *    contributors may be used to endorse or promote products derived
25  *    from this software without specific prior written permission.
26  *
27  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
28  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
29  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
30  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
31  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
32  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
33  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
34  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
35  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
36  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
37  * POSSIBILITY OF SUCH DAMAGE.
38  */
39 
40 /*
41  * Copyright (c) 1982, 1986, 1989, 1991, 1993
42  *	The Regents of the University of California.  All rights reserved.
43  *
44  * Redistribution and use in source and binary forms, with or without
45  * modification, are permitted provided that the following conditions
46  * are met:
47  * 1. Redistributions of source code must retain the above copyright
48  *    notice, this list of conditions and the following disclaimer.
49  * 2. Redistributions in binary form must reproduce the above copyright
50  *    notice, this list of conditions and the following disclaimer in the
51  *    documentation and/or other materials provided with the distribution.
52  * 3. Neither the name of the University nor the names of its contributors
53  *    may be used to endorse or promote products derived from this software
54  *    without specific prior written permission.
55  *
56  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
57  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
58  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
59  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
60  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
61  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
62  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
63  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
64  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
65  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
66  * SUCH DAMAGE.
67  *
68  *	@(#)uipc_usrreq.c	8.9 (Berkeley) 5/14/95
69  */
70 
71 /*
72  * Copyright (c) 1997 Christopher G. Demetriou.  All rights reserved.
73  *
74  * Redistribution and use in source and binary forms, with or without
75  * modification, are permitted provided that the following conditions
76  * are met:
77  * 1. Redistributions of source code must retain the above copyright
78  *    notice, this list of conditions and the following disclaimer.
79  * 2. Redistributions in binary form must reproduce the above copyright
80  *    notice, this list of conditions and the following disclaimer in the
81  *    documentation and/or other materials provided with the distribution.
82  * 3. All advertising materials mentioning features or use of this software
83  *    must display the following acknowledgement:
84  *	This product includes software developed by the University of
85  *	California, Berkeley and its contributors.
86  * 4. Neither the name of the University nor the names of its contributors
87  *    may be used to endorse or promote products derived from this software
88  *    without specific prior written permission.
89  *
90  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
91  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
92  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
93  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
94  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
95  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
96  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
97  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
98  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
99  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
100  * SUCH DAMAGE.
101  *
102  *	@(#)uipc_usrreq.c	8.9 (Berkeley) 5/14/95
103  */
104 
105 #include <sys/cdefs.h>
106 __KERNEL_RCSID(0, "$NetBSD: uipc_usrreq.c,v 1.87 2006/03/01 02:06:11 christos Exp $");
107 
108 #include <sys/param.h>
109 #include <sys/systm.h>
110 #include <sys/proc.h>
111 #include <sys/filedesc.h>
112 #include <sys/domain.h>
113 #include <sys/protosw.h>
114 #include <sys/socket.h>
115 #include <sys/socketvar.h>
116 #include <sys/unpcb.h>
117 #include <sys/un.h>
118 #include <sys/namei.h>
119 #include <sys/vnode.h>
120 #include <sys/file.h>
121 #include <sys/stat.h>
122 #include <sys/mbuf.h>
123 
124 /*
125  * Unix communications domain.
126  *
127  * TODO:
128  *	SEQPACKET, RDM
129  *	rethink name space problems
130  *	need a proper out-of-band
131  */
132 const struct	sockaddr_un sun_noname = { sizeof(sun_noname), AF_LOCAL };
133 ino_t	unp_ino;			/* prototype for fake inode numbers */
134 
135 struct mbuf *unp_addsockcred(struct proc *, struct mbuf *);
136 
137 int
138 unp_output(struct mbuf *m, struct mbuf *control, struct unpcb *unp,
139 	struct proc *p)
140 {
141 	struct socket *so2;
142 	const struct sockaddr_un *sun;
143 
144 	so2 = unp->unp_conn->unp_socket;
145 	if (unp->unp_addr)
146 		sun = unp->unp_addr;
147 	else
148 		sun = &sun_noname;
149 	if (unp->unp_conn->unp_flags & UNP_WANTCRED)
150 		control = unp_addsockcred(p, control);
151 	if (sbappendaddr(&so2->so_rcv, (const struct sockaddr *)sun, m,
152 	    control) == 0) {
153 		m_freem(control);
154 		m_freem(m);
155 		so2->so_rcv.sb_overflowed++;
156 		return (ENOBUFS);
157 	} else {
158 		sorwakeup(so2);
159 		return (0);
160 	}
161 }
162 
163 void
164 unp_setsockaddr(struct unpcb *unp, struct mbuf *nam)
165 {
166 	const struct sockaddr_un *sun;
167 
168 	if (unp->unp_addr)
169 		sun = unp->unp_addr;
170 	else
171 		sun = &sun_noname;
172 	nam->m_len = sun->sun_len;
173 	if (nam->m_len > MLEN)
174 		MEXTMALLOC(nam, nam->m_len, M_WAITOK);
175 	memcpy(mtod(nam, caddr_t), sun, (size_t)nam->m_len);
176 }
177 
178 void
179 unp_setpeeraddr(struct unpcb *unp, struct mbuf *nam)
180 {
181 	const struct sockaddr_un *sun;
182 
183 	if (unp->unp_conn && unp->unp_conn->unp_addr)
184 		sun = unp->unp_conn->unp_addr;
185 	else
186 		sun = &sun_noname;
187 	nam->m_len = sun->sun_len;
188 	if (nam->m_len > MLEN)
189 		MEXTMALLOC(nam, nam->m_len, M_WAITOK);
190 	memcpy(mtod(nam, caddr_t), sun, (size_t)nam->m_len);
191 }
192 
193 /*ARGSUSED*/
194 int
195 uipc_usrreq(struct socket *so, int req, struct mbuf *m, struct mbuf *nam,
196 	struct mbuf *control, struct lwp *l)
197 {
198 	struct unpcb *unp = sotounpcb(so);
199 	struct socket *so2;
200 	struct proc *p;
201 	u_int newhiwat;
202 	int error = 0;
203 
204 	if (req == PRU_CONTROL)
205 		return (EOPNOTSUPP);
206 
207 #ifdef DIAGNOSTIC
208 	if (req != PRU_SEND && req != PRU_SENDOOB && control)
209 		panic("uipc_usrreq: unexpected control mbuf");
210 #endif
211 	p = l ? l->l_proc : NULL;
212 	if (unp == 0 && req != PRU_ATTACH) {
213 		error = EINVAL;
214 		goto release;
215 	}
216 
217 	switch (req) {
218 
219 	case PRU_ATTACH:
220 		if (unp != 0) {
221 			error = EISCONN;
222 			break;
223 		}
224 		error = unp_attach(so);
225 		break;
226 
227 	case PRU_DETACH:
228 		unp_detach(unp);
229 		break;
230 
231 	case PRU_BIND:
232 		error = unp_bind(unp, nam, l);
233 		break;
234 
235 	case PRU_LISTEN:
236 		if (unp->unp_vnode == 0)
237 			error = EINVAL;
238 		break;
239 
240 	case PRU_CONNECT:
241 		error = unp_connect(so, nam, l);
242 		break;
243 
244 	case PRU_CONNECT2:
245 		error = unp_connect2(so, (struct socket *)nam, PRU_CONNECT2);
246 		break;
247 
248 	case PRU_DISCONNECT:
249 		unp_disconnect(unp);
250 		break;
251 
252 	case PRU_ACCEPT:
253 		unp_setpeeraddr(unp, nam);
254 		/*
255 		 * Mark the initiating STREAM socket as connected *ONLY*
256 		 * after it's been accepted.  This prevents a client from
257 		 * overrunning a server and receiving ECONNREFUSED.
258 		 */
259 		if (unp->unp_conn != NULL &&
260 		    (unp->unp_conn->unp_socket->so_state & SS_ISCONNECTING))
261 			soisconnected(unp->unp_conn->unp_socket);
262 		break;
263 
264 	case PRU_SHUTDOWN:
265 		socantsendmore(so);
266 		unp_shutdown(unp);
267 		break;
268 
269 	case PRU_RCVD:
270 		switch (so->so_type) {
271 
272 		case SOCK_DGRAM:
273 			panic("uipc 1");
274 			/*NOTREACHED*/
275 
276 		case SOCK_STREAM:
277 #define	rcv (&so->so_rcv)
278 #define snd (&so2->so_snd)
279 			if (unp->unp_conn == 0)
280 				break;
281 			so2 = unp->unp_conn->unp_socket;
282 			/*
283 			 * Adjust backpressure on sender
284 			 * and wakeup any waiting to write.
285 			 */
286 			snd->sb_mbmax += unp->unp_mbcnt - rcv->sb_mbcnt;
287 			unp->unp_mbcnt = rcv->sb_mbcnt;
288 			newhiwat = snd->sb_hiwat + unp->unp_cc - rcv->sb_cc;
289 			(void)chgsbsize(so2->so_uidinfo,
290 			    &snd->sb_hiwat, newhiwat, RLIM_INFINITY);
291 			unp->unp_cc = rcv->sb_cc;
292 			sowwakeup(so2);
293 #undef snd
294 #undef rcv
295 			break;
296 
297 		default:
298 			panic("uipc 2");
299 		}
300 		break;
301 
302 	case PRU_SEND:
303 		/*
304 		 * Note: unp_internalize() rejects any control message
305 		 * other than SCM_RIGHTS, and only allows one.  This
306 		 * has the side-effect of preventing a caller from
307 		 * forging SCM_CREDS.
308 		 */
309 		if (control && (error = unp_internalize(control, l))) {
310 			goto die;
311 		}
312 		switch (so->so_type) {
313 
314 		case SOCK_DGRAM: {
315 			if (nam) {
316 				if ((so->so_state & SS_ISCONNECTED) != 0) {
317 					error = EISCONN;
318 					goto die;
319 				}
320 				error = unp_connect(so, nam, l);
321 				if (error) {
322 				die:
323 					m_freem(control);
324 					m_freem(m);
325 					break;
326 				}
327 			} else {
328 				if ((so->so_state & SS_ISCONNECTED) == 0) {
329 					error = ENOTCONN;
330 					goto die;
331 				}
332 			}
333 			error = unp_output(m, control, unp, p);
334 			if (nam)
335 				unp_disconnect(unp);
336 			break;
337 		}
338 
339 		case SOCK_STREAM:
340 #define	rcv (&so2->so_rcv)
341 #define	snd (&so->so_snd)
342 			if (unp->unp_conn == NULL) {
343 				error = ENOTCONN;
344 				break;
345 			}
346 			so2 = unp->unp_conn->unp_socket;
347 			if (unp->unp_conn->unp_flags & UNP_WANTCRED) {
348 				/*
349 				 * Credentials are passed only once on
350 				 * SOCK_STREAM.
351 				 */
352 				unp->unp_conn->unp_flags &= ~UNP_WANTCRED;
353 				control = unp_addsockcred(p, control);
354 			}
355 			/*
356 			 * Send to paired receive port, and then reduce
357 			 * send buffer hiwater marks to maintain backpressure.
358 			 * Wake up readers.
359 			 */
360 			if (control) {
361 				if (sbappendcontrol(rcv, m, control) == 0)
362 					m_freem(control);
363 			} else
364 				sbappend(rcv, m);
365 			snd->sb_mbmax -=
366 			    rcv->sb_mbcnt - unp->unp_conn->unp_mbcnt;
367 			unp->unp_conn->unp_mbcnt = rcv->sb_mbcnt;
368 			newhiwat = snd->sb_hiwat -
369 			    (rcv->sb_cc - unp->unp_conn->unp_cc);
370 			(void)chgsbsize(so->so_uidinfo,
371 			    &snd->sb_hiwat, newhiwat, RLIM_INFINITY);
372 			unp->unp_conn->unp_cc = rcv->sb_cc;
373 			sorwakeup(so2);
374 #undef snd
375 #undef rcv
376 			break;
377 
378 		default:
379 			panic("uipc 4");
380 		}
381 		break;
382 
383 	case PRU_ABORT:
384 		unp_drop(unp, ECONNABORTED);
385 
386 #ifdef DIAGNOSTIC
387 		if (so->so_pcb == 0)
388 			panic("uipc 5: drop killed pcb");
389 #endif
390 		unp_detach(unp);
391 		break;
392 
393 	case PRU_SENSE:
394 		((struct stat *) m)->st_blksize = so->so_snd.sb_hiwat;
395 		if (so->so_type == SOCK_STREAM && unp->unp_conn != 0) {
396 			so2 = unp->unp_conn->unp_socket;
397 			((struct stat *) m)->st_blksize += so2->so_rcv.sb_cc;
398 		}
399 		((struct stat *) m)->st_dev = NODEV;
400 		if (unp->unp_ino == 0)
401 			unp->unp_ino = unp_ino++;
402 		((struct stat *) m)->st_atimespec =
403 		    ((struct stat *) m)->st_mtimespec =
404 		    ((struct stat *) m)->st_ctimespec = unp->unp_ctime;
405 		((struct stat *) m)->st_ino = unp->unp_ino;
406 		return (0);
407 
408 	case PRU_RCVOOB:
409 		error = EOPNOTSUPP;
410 		break;
411 
412 	case PRU_SENDOOB:
413 		m_freem(control);
414 		m_freem(m);
415 		error = EOPNOTSUPP;
416 		break;
417 
418 	case PRU_SOCKADDR:
419 		unp_setsockaddr(unp, nam);
420 		break;
421 
422 	case PRU_PEERADDR:
423 		unp_setpeeraddr(unp, nam);
424 		break;
425 
426 	default:
427 		panic("piusrreq");
428 	}
429 
430 release:
431 	return (error);
432 }
433 
434 /*
435  * Unix domain socket option processing.
436  */
437 int
438 uipc_ctloutput(int op, struct socket *so, int level, int optname,
439 	struct mbuf **mp)
440 {
441 	struct unpcb *unp = sotounpcb(so);
442 	struct mbuf *m = *mp;
443 	int optval = 0, error = 0;
444 
445 	if (level != 0) {
446 		error = EINVAL;
447 		if (op == PRCO_SETOPT && m)
448 			(void) m_free(m);
449 	} else switch (op) {
450 
451 	case PRCO_SETOPT:
452 		switch (optname) {
453 		case LOCAL_CREDS:
454 		case LOCAL_CONNWAIT:
455 			if (m == NULL || m->m_len != sizeof(int))
456 				error = EINVAL;
457 			else {
458 				optval = *mtod(m, int *);
459 				switch (optname) {
460 #define	OPTSET(bit) \
461 	if (optval) \
462 		unp->unp_flags |= (bit); \
463 	else \
464 		unp->unp_flags &= ~(bit);
465 
466 				case LOCAL_CREDS:
467 					OPTSET(UNP_WANTCRED);
468 					break;
469 				case LOCAL_CONNWAIT:
470 					OPTSET(UNP_CONNWAIT);
471 					break;
472 				}
473 			}
474 			break;
475 #undef OPTSET
476 
477 		default:
478 			error = ENOPROTOOPT;
479 			break;
480 		}
481 		if (m)
482 			(void) m_free(m);
483 		break;
484 
485 	case PRCO_GETOPT:
486 		switch (optname) {
487 		case LOCAL_CREDS:
488 			*mp = m = m_get(M_WAIT, MT_SOOPTS);
489 			m->m_len = sizeof(int);
490 			switch (optname) {
491 
492 #define	OPTBIT(bit)	(unp->unp_flags & (bit) ? 1 : 0)
493 
494 			case LOCAL_CREDS:
495 				optval = OPTBIT(UNP_WANTCRED);
496 				break;
497 			}
498 			*mtod(m, int *) = optval;
499 			break;
500 #undef OPTBIT
501 
502 		default:
503 			error = ENOPROTOOPT;
504 			break;
505 		}
506 		break;
507 	}
508 	return (error);
509 }
510 
511 /*
512  * Both send and receive buffers are allocated PIPSIZ bytes of buffering
513  * for stream sockets, although the total for sender and receiver is
514  * actually only PIPSIZ.
515  * Datagram sockets really use the sendspace as the maximum datagram size,
516  * and don't really want to reserve the sendspace.  Their recvspace should
517  * be large enough for at least one max-size datagram plus address.
518  */
519 #define	PIPSIZ	4096
520 u_long	unpst_sendspace = PIPSIZ;
521 u_long	unpst_recvspace = PIPSIZ;
522 u_long	unpdg_sendspace = 2*1024;	/* really max datagram size */
523 u_long	unpdg_recvspace = 4*1024;
524 
525 int	unp_rights;			/* file descriptors in flight */
526 
527 int
528 unp_attach(struct socket *so)
529 {
530 	struct unpcb *unp;
531 	int error;
532 
533 	if (so->so_snd.sb_hiwat == 0 || so->so_rcv.sb_hiwat == 0) {
534 		switch (so->so_type) {
535 
536 		case SOCK_STREAM:
537 			error = soreserve(so, unpst_sendspace, unpst_recvspace);
538 			break;
539 
540 		case SOCK_DGRAM:
541 			error = soreserve(so, unpdg_sendspace, unpdg_recvspace);
542 			break;
543 
544 		default:
545 			panic("unp_attach");
546 		}
547 		if (error)
548 			return (error);
549 	}
550 	unp = malloc(sizeof(*unp), M_PCB, M_NOWAIT);
551 	if (unp == NULL)
552 		return (ENOBUFS);
553 	memset((caddr_t)unp, 0, sizeof(*unp));
554 	unp->unp_socket = so;
555 	so->so_pcb = unp;
556 	nanotime(&unp->unp_ctime);
557 	return (0);
558 }
559 
560 void
561 unp_detach(struct unpcb *unp)
562 {
563 
564 	if (unp->unp_vnode) {
565 		unp->unp_vnode->v_socket = 0;
566 		vrele(unp->unp_vnode);
567 		unp->unp_vnode = 0;
568 	}
569 	if (unp->unp_conn)
570 		unp_disconnect(unp);
571 	while (unp->unp_refs)
572 		unp_drop(unp->unp_refs, ECONNRESET);
573 	soisdisconnected(unp->unp_socket);
574 	unp->unp_socket->so_pcb = 0;
575 	if (unp->unp_addr)
576 		free(unp->unp_addr, M_SONAME);
577 	if (unp_rights) {
578 		/*
579 		 * Normally the receive buffer is flushed later,
580 		 * in sofree, but if our receive buffer holds references
581 		 * to descriptors that are now garbage, we will dispose
582 		 * of those descriptor references after the garbage collector
583 		 * gets them (resulting in a "panic: closef: count < 0").
584 		 */
585 		sorflush(unp->unp_socket);
586 		free(unp, M_PCB);
587 		unp_gc();
588 	} else
589 		free(unp, M_PCB);
590 }
591 
592 int
593 unp_bind(struct unpcb *unp, struct mbuf *nam, struct lwp *l)
594 {
595 	struct sockaddr_un *sun;
596 	struct vnode *vp;
597 	struct mount *mp;
598 	struct vattr vattr;
599 	size_t addrlen;
600 	struct proc *p;
601 	int error;
602 	struct nameidata nd;
603 
604 	if (unp->unp_vnode != 0)
605 		return (EINVAL);
606 
607 	p = l->l_proc;
608 	/*
609 	 * Allocate the new sockaddr.  We have to allocate one
610 	 * extra byte so that we can ensure that the pathname
611 	 * is nul-terminated.
612 	 */
613 	addrlen = nam->m_len + 1;
614 	sun = malloc(addrlen, M_SONAME, M_WAITOK);
615 	m_copydata(nam, 0, nam->m_len, (caddr_t)sun);
616 	*(((char *)sun) + nam->m_len) = '\0';
617 
618 restart:
619 	NDINIT(&nd, CREATE, FOLLOW | LOCKPARENT, UIO_SYSSPACE,
620 	    sun->sun_path, l);
621 
622 /* SHOULD BE ABLE TO ADOPT EXISTING AND wakeup() ALA FIFO's */
623 	if ((error = namei(&nd)) != 0)
624 		goto bad;
625 	vp = nd.ni_vp;
626 	if (vp != NULL || vn_start_write(nd.ni_dvp, &mp, V_NOWAIT) != 0) {
627 		VOP_ABORTOP(nd.ni_dvp, &nd.ni_cnd);
628 		if (nd.ni_dvp == vp)
629 			vrele(nd.ni_dvp);
630 		else
631 			vput(nd.ni_dvp);
632 		vrele(vp);
633 		if (vp != NULL) {
634 			error = EADDRINUSE;
635 			goto bad;
636 		}
637 		error = vn_start_write(NULL, &mp,
638 		    V_WAIT | V_SLEEPONLY | V_PCATCH);
639 		if (error)
640 			goto bad;
641 		goto restart;
642 	}
643 	VATTR_NULL(&vattr);
644 	vattr.va_type = VSOCK;
645 	vattr.va_mode = ACCESSPERMS & ~(p->p_cwdi->cwdi_cmask);
646 	VOP_LEASE(nd.ni_dvp, l, p->p_ucred, LEASE_WRITE);
647 	error = VOP_CREATE(nd.ni_dvp, &nd.ni_vp, &nd.ni_cnd, &vattr);
648 	vn_finished_write(mp, 0);
649 	if (error)
650 		goto bad;
651 	vp = nd.ni_vp;
652 	vp->v_socket = unp->unp_socket;
653 	unp->unp_vnode = vp;
654 	unp->unp_addrlen = addrlen;
655 	unp->unp_addr = sun;
656 	VOP_UNLOCK(vp, 0);
657 	return (0);
658 
659  bad:
660 	free(sun, M_SONAME);
661 	return (error);
662 }
663 
664 int
665 unp_connect(struct socket *so, struct mbuf *nam, struct lwp *l)
666 {
667 	struct sockaddr_un *sun;
668 	struct vnode *vp;
669 	struct socket *so2, *so3;
670 	struct unpcb *unp2, *unp3;
671 	size_t addrlen;
672 	int error;
673 	struct nameidata nd;
674 
675 	/*
676 	 * Allocate a temporary sockaddr.  We have to allocate one extra
677 	 * byte so that we can ensure that the pathname is nul-terminated.
678 	 * When we establish the connection, we copy the other PCB's
679 	 * sockaddr to our own.
680 	 */
681 	addrlen = nam->m_len + 1;
682 	sun = malloc(addrlen, M_SONAME, M_WAITOK);
683 	m_copydata(nam, 0, nam->m_len, (caddr_t)sun);
684 	*(((char *)sun) + nam->m_len) = '\0';
685 
686 	NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF, UIO_SYSSPACE, sun->sun_path, l);
687 
688 	if ((error = namei(&nd)) != 0)
689 		goto bad2;
690 	vp = nd.ni_vp;
691 	if (vp->v_type != VSOCK) {
692 		error = ENOTSOCK;
693 		goto bad;
694 	}
695 	if ((error = VOP_ACCESS(vp, VWRITE, l->l_proc->p_ucred, l)) != 0)
696 		goto bad;
697 	so2 = vp->v_socket;
698 	if (so2 == 0) {
699 		error = ECONNREFUSED;
700 		goto bad;
701 	}
702 	if (so->so_type != so2->so_type) {
703 		error = EPROTOTYPE;
704 		goto bad;
705 	}
706 	if (so->so_proto->pr_flags & PR_CONNREQUIRED) {
707 		if ((so2->so_options & SO_ACCEPTCONN) == 0 ||
708 		    (so3 = sonewconn(so2, 0)) == 0) {
709 			error = ECONNREFUSED;
710 			goto bad;
711 		}
712 		unp2 = sotounpcb(so2);
713 		unp3 = sotounpcb(so3);
714 		if (unp2->unp_addr) {
715 			unp3->unp_addr = malloc(unp2->unp_addrlen,
716 			    M_SONAME, M_WAITOK);
717 			memcpy(unp3->unp_addr, unp2->unp_addr,
718 			    unp2->unp_addrlen);
719 			unp3->unp_addrlen = unp2->unp_addrlen;
720 		}
721 		unp3->unp_flags = unp2->unp_flags;
722 		so2 = so3;
723 	}
724 	error = unp_connect2(so, so2, PRU_CONNECT);
725  bad:
726 	vput(vp);
727  bad2:
728 	free(sun, M_SONAME);
729 	return (error);
730 }
731 
732 int
733 unp_connect2(struct socket *so, struct socket *so2, int req)
734 {
735 	struct unpcb *unp = sotounpcb(so);
736 	struct unpcb *unp2;
737 
738 	if (so2->so_type != so->so_type)
739 		return (EPROTOTYPE);
740 	unp2 = sotounpcb(so2);
741 	unp->unp_conn = unp2;
742 	switch (so->so_type) {
743 
744 	case SOCK_DGRAM:
745 		unp->unp_nextref = unp2->unp_refs;
746 		unp2->unp_refs = unp;
747 		soisconnected(so);
748 		break;
749 
750 	case SOCK_STREAM:
751 		unp2->unp_conn = unp;
752 		if (req == PRU_CONNECT &&
753 		    ((unp->unp_flags | unp2->unp_flags) & UNP_CONNWAIT))
754 			soisconnecting(so);
755 		else
756 			soisconnected(so);
757 		soisconnected(so2);
758 		break;
759 
760 	default:
761 		panic("unp_connect2");
762 	}
763 	return (0);
764 }
765 
766 void
767 unp_disconnect(struct unpcb *unp)
768 {
769 	struct unpcb *unp2 = unp->unp_conn;
770 
771 	if (unp2 == 0)
772 		return;
773 	unp->unp_conn = 0;
774 	switch (unp->unp_socket->so_type) {
775 
776 	case SOCK_DGRAM:
777 		if (unp2->unp_refs == unp)
778 			unp2->unp_refs = unp->unp_nextref;
779 		else {
780 			unp2 = unp2->unp_refs;
781 			for (;;) {
782 				if (unp2 == 0)
783 					panic("unp_disconnect");
784 				if (unp2->unp_nextref == unp)
785 					break;
786 				unp2 = unp2->unp_nextref;
787 			}
788 			unp2->unp_nextref = unp->unp_nextref;
789 		}
790 		unp->unp_nextref = 0;
791 		unp->unp_socket->so_state &= ~SS_ISCONNECTED;
792 		break;
793 
794 	case SOCK_STREAM:
795 		soisdisconnected(unp->unp_socket);
796 		unp2->unp_conn = 0;
797 		soisdisconnected(unp2->unp_socket);
798 		break;
799 	}
800 }
801 
802 #ifdef notdef
803 unp_abort(struct unpcb *unp)
804 {
805 	unp_detach(unp);
806 }
807 #endif
808 
809 void
810 unp_shutdown(struct unpcb *unp)
811 {
812 	struct socket *so;
813 
814 	if (unp->unp_socket->so_type == SOCK_STREAM && unp->unp_conn &&
815 	    (so = unp->unp_conn->unp_socket))
816 		socantrcvmore(so);
817 }
818 
819 void
820 unp_drop(struct unpcb *unp, int errno)
821 {
822 	struct socket *so = unp->unp_socket;
823 
824 	so->so_error = errno;
825 	unp_disconnect(unp);
826 	if (so->so_head) {
827 		so->so_pcb = 0;
828 		sofree(so);
829 		if (unp->unp_addr)
830 			free(unp->unp_addr, M_SONAME);
831 		free(unp, M_PCB);
832 	}
833 }
834 
835 #ifdef notdef
836 unp_drain(void)
837 {
838 
839 }
840 #endif
841 
842 int
843 unp_externalize(struct mbuf *rights, struct lwp *l)
844 {
845 	struct cmsghdr *cm = mtod(rights, struct cmsghdr *);
846 	struct proc *p = l->l_proc;
847 	int i, *fdp;
848 	struct file **rp;
849 	struct file *fp;
850 	int nfds, error = 0;
851 
852 	nfds = (cm->cmsg_len - CMSG_ALIGN(sizeof(*cm))) /
853 	    sizeof(struct file *);
854 	rp = (struct file **)CMSG_DATA(cm);
855 
856 	fdp = malloc(nfds * sizeof(int), M_TEMP, M_WAITOK);
857 
858 	/* Make sure the recipient should be able to see the descriptors.. */
859 	if (p->p_cwdi->cwdi_rdir != NULL) {
860 		rp = (struct file **)CMSG_DATA(cm);
861 		for (i = 0; i < nfds; i++) {
862 			fp = *rp++;
863 			/*
864 			 * If we are in a chroot'ed directory, and
865 			 * someone wants to pass us a directory, make
866 			 * sure it's inside the subtree we're allowed
867 			 * to access.
868 			 */
869 			if (fp->f_type == DTYPE_VNODE) {
870 				struct vnode *vp = (struct vnode *)fp->f_data;
871 				if ((vp->v_type == VDIR) &&
872 				    !vn_isunder(vp, p->p_cwdi->cwdi_rdir, l)) {
873 					error = EPERM;
874 					break;
875 				}
876 			}
877 		}
878 	}
879 
880  restart:
881 	rp = (struct file **)CMSG_DATA(cm);
882 	if (error != 0) {
883 		for (i = 0; i < nfds; i++) {
884 			fp = *rp;
885 			/*
886 			 * zero the pointer before calling unp_discard,
887 			 * since it may end up in unp_gc()..
888 			 */
889 			*rp++ = 0;
890 			unp_discard(fp);
891 		}
892 		goto out;
893 	}
894 
895 	/*
896 	 * First loop -- allocate file descriptor table slots for the
897 	 * new descriptors.
898 	 */
899 	for (i = 0; i < nfds; i++) {
900 		fp = *rp++;
901 		if ((error = fdalloc(p, 0, &fdp[i])) != 0) {
902 			/*
903 			 * Back out what we've done so far.
904 			 */
905 			for (--i; i >= 0; i--)
906 				fdremove(p->p_fd, fdp[i]);
907 
908 			if (error == ENOSPC) {
909 				fdexpand(p);
910 				error = 0;
911 			} else {
912 				/*
913 				 * This is the error that has historically
914 				 * been returned, and some callers may
915 				 * expect it.
916 				 */
917 				error = EMSGSIZE;
918 			}
919 			goto restart;
920 		}
921 
922 		/*
923 		 * Make the slot reference the descriptor so that
924 		 * fdalloc() works properly.. We finalize it all
925 		 * in the loop below.
926 		 */
927 		p->p_fd->fd_ofiles[fdp[i]] = fp;
928 	}
929 
930 	/*
931 	 * Now that adding them has succeeded, update all of the
932 	 * descriptor passing state.
933 	 */
934 	rp = (struct file **)CMSG_DATA(cm);
935 	for (i = 0; i < nfds; i++) {
936 		fp = *rp++;
937 		fp->f_msgcount--;
938 		unp_rights--;
939 	}
940 
941 	/*
942 	 * Copy temporary array to message and adjust length, in case of
943 	 * transition from large struct file pointers to ints.
944 	 */
945 	memcpy(CMSG_DATA(cm), fdp, nfds * sizeof(int));
946 	cm->cmsg_len = CMSG_LEN(nfds * sizeof(int));
947 	rights->m_len = CMSG_SPACE(nfds * sizeof(int));
948  out:
949 	free(fdp, M_TEMP);
950 	return (error);
951 }
952 
953 int
954 unp_internalize(struct mbuf *control, struct lwp *l)
955 {
956 	struct proc *p = l->l_proc;
957 	struct filedesc *fdescp = p->p_fd;
958 	struct cmsghdr *newcm, *cm = mtod(control, struct cmsghdr *);
959 	struct file **rp, **files;
960 	struct file *fp;
961 	int i, fd, *fdp;
962 	int nfds;
963 	u_int neededspace;
964 
965 	/* Sanity check the control message header */
966 	if (cm->cmsg_type != SCM_RIGHTS || cm->cmsg_level != SOL_SOCKET ||
967 	    cm->cmsg_len != control->m_len)
968 		return (EINVAL);
969 
970 	/* Verify that the file descriptors are valid */
971 	nfds = (cm->cmsg_len - CMSG_ALIGN(sizeof(*cm))) / sizeof(int);
972 	fdp = (int *)CMSG_DATA(cm);
973 	for (i = 0; i < nfds; i++) {
974 		fd = *fdp++;
975 		if ((fp = fd_getfile(fdescp, fd)) == NULL)
976 			return (EBADF);
977 		simple_unlock(&fp->f_slock);
978 	}
979 
980 	/* Make sure we have room for the struct file pointers */
981 	neededspace = CMSG_SPACE(nfds * sizeof(struct file *)) -
982 	    control->m_len;
983 	if (neededspace > M_TRAILINGSPACE(control)) {
984 
985 		/* allocate new space and copy header into it */
986 		newcm = malloc(
987 		    CMSG_SPACE(nfds * sizeof(struct file *)),
988 		    M_MBUF, M_WAITOK);
989 		if (newcm == NULL)
990 			return (E2BIG);
991 		memcpy(newcm, cm, sizeof(struct cmsghdr));
992 		files = (struct file **)CMSG_DATA(newcm);
993 	} else {
994 		/* we can convert in-place */
995 		newcm = NULL;
996 		files = (struct file **)CMSG_DATA(cm);
997 	}
998 
999 	/*
1000 	 * Transform the file descriptors into struct file pointers, in
1001 	 * reverse order so that if pointers are bigger than ints, the
1002 	 * int won't get until we're done.
1003 	 */
1004 	fdp = (int *)CMSG_DATA(cm) + nfds - 1;
1005 	rp = files + nfds - 1;
1006 	for (i = 0; i < nfds; i++) {
1007 		fp = fdescp->fd_ofiles[*fdp--];
1008 		simple_lock(&fp->f_slock);
1009 #ifdef DIAGNOSTIC
1010 		if (fp->f_iflags & FIF_WANTCLOSE)
1011 			panic("unp_internalize: file already closed");
1012 #endif
1013 		*rp-- = fp;
1014 		fp->f_count++;
1015 		fp->f_msgcount++;
1016 		simple_unlock(&fp->f_slock);
1017 		unp_rights++;
1018 	}
1019 
1020 	if (newcm) {
1021 		if (control->m_flags & M_EXT)
1022 			MEXTREMOVE(control);
1023 		MEXTADD(control, newcm,
1024 		    CMSG_SPACE(nfds * sizeof(struct file *)),
1025 		    M_MBUF, NULL, NULL);
1026 		cm = newcm;
1027 	}
1028 
1029 	/* adjust message & mbuf to note amount of space actually used. */
1030 	cm->cmsg_len = CMSG_LEN(nfds * sizeof(struct file *));
1031 	control->m_len = CMSG_SPACE(nfds * sizeof(struct file *));
1032 
1033 	return (0);
1034 }
1035 
1036 struct mbuf *
1037 unp_addsockcred(struct proc *p, struct mbuf *control)
1038 {
1039 	struct cmsghdr *cmp;
1040 	struct sockcred *sc;
1041 	struct mbuf *m, *n;
1042 	int len, space, i;
1043 
1044 	len = CMSG_LEN(SOCKCREDSIZE(p->p_ucred->cr_ngroups));
1045 	space = CMSG_SPACE(SOCKCREDSIZE(p->p_ucred->cr_ngroups));
1046 
1047 	m = m_get(M_WAIT, MT_CONTROL);
1048 	if (space > MLEN) {
1049 		if (space > MCLBYTES)
1050 			MEXTMALLOC(m, space, M_WAITOK);
1051 		else
1052 			m_clget(m, M_WAIT);
1053 		if ((m->m_flags & M_EXT) == 0) {
1054 			m_free(m);
1055 			return (control);
1056 		}
1057 	}
1058 
1059 	m->m_len = space;
1060 	m->m_next = NULL;
1061 	cmp = mtod(m, struct cmsghdr *);
1062 	sc = (struct sockcred *)CMSG_DATA(cmp);
1063 	cmp->cmsg_len = len;
1064 	cmp->cmsg_level = SOL_SOCKET;
1065 	cmp->cmsg_type = SCM_CREDS;
1066 	sc->sc_uid = p->p_cred->p_ruid;
1067 	sc->sc_euid = p->p_ucred->cr_uid;
1068 	sc->sc_gid = p->p_cred->p_rgid;
1069 	sc->sc_egid = p->p_ucred->cr_gid;
1070 	sc->sc_ngroups = p->p_ucred->cr_ngroups;
1071 	for (i = 0; i < sc->sc_ngroups; i++)
1072 		sc->sc_groups[i] = p->p_ucred->cr_groups[i];
1073 
1074 	/*
1075 	 * If a control message already exists, append us to the end.
1076 	 */
1077 	if (control != NULL) {
1078 		for (n = control; n->m_next != NULL; n = n->m_next)
1079 			;
1080 		n->m_next = m;
1081 	} else
1082 		control = m;
1083 
1084 	return (control);
1085 }
1086 
1087 int	unp_defer, unp_gcing;
1088 extern	struct domain unixdomain;
1089 
1090 /*
1091  * Comment added long after the fact explaining what's going on here.
1092  * Do a mark-sweep GC of file descriptors on the system, to free up
1093  * any which are caught in flight to an about-to-be-closed socket.
1094  *
1095  * Traditional mark-sweep gc's start at the "root", and mark
1096  * everything reachable from the root (which, in our case would be the
1097  * process table).  The mark bits are cleared during the sweep.
1098  *
1099  * XXX For some inexplicable reason (perhaps because the file
1100  * descriptor tables used to live in the u area which could be swapped
1101  * out and thus hard to reach), we do multiple scans over the set of
1102  * descriptors, using use *two* mark bits per object (DEFER and MARK).
1103  * Whenever we find a descriptor which references other descriptors,
1104  * the ones it references are marked with both bits, and we iterate
1105  * over the whole file table until there are no more DEFER bits set.
1106  * We also make an extra pass *before* the GC to clear the mark bits,
1107  * which could have been cleared at almost no cost during the previous
1108  * sweep.
1109  *
1110  * XXX MP: this needs to run with locks such that no other thread of
1111  * control can create or destroy references to file descriptors. it
1112  * may be necessary to defer the GC until later (when the locking
1113  * situation is more hospitable); it may be necessary to push this
1114  * into a separate thread.
1115  */
1116 void
1117 unp_gc(void)
1118 {
1119 	struct file *fp, *nextfp;
1120 	struct socket *so, *so1;
1121 	struct file **extra_ref, **fpp;
1122 	int nunref, i;
1123 
1124 	if (unp_gcing)
1125 		return;
1126 	unp_gcing = 1;
1127 	unp_defer = 0;
1128 
1129 	/* Clear mark bits */
1130 	LIST_FOREACH(fp, &filehead, f_list)
1131 		fp->f_flag &= ~(FMARK|FDEFER);
1132 
1133 	/*
1134 	 * Iterate over the set of descriptors, marking ones believed
1135 	 * (based on refcount) to be referenced from a process, and
1136 	 * marking for rescan descriptors which are queued on a socket.
1137 	 */
1138 	do {
1139 		LIST_FOREACH(fp, &filehead, f_list) {
1140 			if (fp->f_flag & FDEFER) {
1141 				fp->f_flag &= ~FDEFER;
1142 				unp_defer--;
1143 #ifdef DIAGNOSTIC
1144 				if (fp->f_count == 0)
1145 					panic("unp_gc: deferred unreferenced socket");
1146 #endif
1147 			} else {
1148 				if (fp->f_count == 0)
1149 					continue;
1150 				if (fp->f_flag & FMARK)
1151 					continue;
1152 				if (fp->f_count == fp->f_msgcount)
1153 					continue;
1154 			}
1155 			fp->f_flag |= FMARK;
1156 
1157 			if (fp->f_type != DTYPE_SOCKET ||
1158 			    (so = (struct socket *)fp->f_data) == 0)
1159 				continue;
1160 			if (so->so_proto->pr_domain != &unixdomain ||
1161 			    (so->so_proto->pr_flags&PR_RIGHTS) == 0)
1162 				continue;
1163 #ifdef notdef
1164 			if (so->so_rcv.sb_flags & SB_LOCK) {
1165 				/*
1166 				 * This is problematical; it's not clear
1167 				 * we need to wait for the sockbuf to be
1168 				 * unlocked (on a uniprocessor, at least),
1169 				 * and it's also not clear what to do
1170 				 * if sbwait returns an error due to receipt
1171 				 * of a signal.  If sbwait does return
1172 				 * an error, we'll go into an infinite
1173 				 * loop.  Delete all of this for now.
1174 				 */
1175 				(void) sbwait(&so->so_rcv);
1176 				goto restart;
1177 			}
1178 #endif
1179 			unp_scan(so->so_rcv.sb_mb, unp_mark, 0);
1180 			/*
1181 			 * mark descriptors referenced from sockets queued on the accept queue as well.
1182 			 */
1183 			if (so->so_options & SO_ACCEPTCONN) {
1184 				TAILQ_FOREACH(so1, &so->so_q0, so_qe) {
1185 					unp_scan(so1->so_rcv.sb_mb, unp_mark, 0);
1186 				}
1187 				TAILQ_FOREACH(so1, &so->so_q, so_qe) {
1188 					unp_scan(so1->so_rcv.sb_mb, unp_mark, 0);
1189 				}
1190 			}
1191 
1192 		}
1193 	} while (unp_defer);
1194 	/*
1195 	 * Sweep pass.  Find unmarked descriptors, and free them.
1196 	 *
1197 	 * We grab an extra reference to each of the file table entries
1198 	 * that are not otherwise accessible and then free the rights
1199 	 * that are stored in messages on them.
1200 	 *
1201 	 * The bug in the original code is a little tricky, so I'll describe
1202 	 * what's wrong with it here.
1203 	 *
1204 	 * It is incorrect to simply unp_discard each entry for f_msgcount
1205 	 * times -- consider the case of sockets A and B that contain
1206 	 * references to each other.  On a last close of some other socket,
1207 	 * we trigger a gc since the number of outstanding rights (unp_rights)
1208 	 * is non-zero.  If during the sweep phase the gc code un_discards,
1209 	 * we end up doing a (full) closef on the descriptor.  A closef on A
1210 	 * results in the following chain.  Closef calls soo_close, which
1211 	 * calls soclose.   Soclose calls first (through the switch
1212 	 * uipc_usrreq) unp_detach, which re-invokes unp_gc.  Unp_gc simply
1213 	 * returns because the previous instance had set unp_gcing, and
1214 	 * we return all the way back to soclose, which marks the socket
1215 	 * with SS_NOFDREF, and then calls sofree.  Sofree calls sorflush
1216 	 * to free up the rights that are queued in messages on the socket A,
1217 	 * i.e., the reference on B.  The sorflush calls via the dom_dispose
1218 	 * switch unp_dispose, which unp_scans with unp_discard.  This second
1219 	 * instance of unp_discard just calls closef on B.
1220 	 *
1221 	 * Well, a similar chain occurs on B, resulting in a sorflush on B,
1222 	 * which results in another closef on A.  Unfortunately, A is already
1223 	 * being closed, and the descriptor has already been marked with
1224 	 * SS_NOFDREF, and soclose panics at this point.
1225 	 *
1226 	 * Here, we first take an extra reference to each inaccessible
1227 	 * descriptor.  Then, if the inaccessible descriptor is a
1228 	 * socket, we call sorflush in case it is a Unix domain
1229 	 * socket.  After we destroy all the rights carried in
1230 	 * messages, we do a last closef to get rid of our extra
1231 	 * reference.  This is the last close, and the unp_detach etc
1232 	 * will shut down the socket.
1233 	 *
1234 	 * 91/09/19, bsy@cs.cmu.edu
1235 	 */
1236 	extra_ref = malloc(nfiles * sizeof(struct file *), M_FILE, M_WAITOK);
1237 	for (nunref = 0, fp = LIST_FIRST(&filehead), fpp = extra_ref; fp != 0;
1238 	    fp = nextfp) {
1239 		nextfp = LIST_NEXT(fp, f_list);
1240 		simple_lock(&fp->f_slock);
1241 		if (fp->f_count != 0 &&
1242 		    fp->f_count == fp->f_msgcount && !(fp->f_flag & FMARK)) {
1243 			*fpp++ = fp;
1244 			nunref++;
1245 			fp->f_count++;
1246 		}
1247 		simple_unlock(&fp->f_slock);
1248 	}
1249 	for (i = nunref, fpp = extra_ref; --i >= 0; ++fpp) {
1250 		fp = *fpp;
1251 		simple_lock(&fp->f_slock);
1252 		FILE_USE(fp);
1253 		if (fp->f_type == DTYPE_SOCKET)
1254 			sorflush((struct socket *)fp->f_data);
1255 		FILE_UNUSE(fp, NULL);
1256 	}
1257 	for (i = nunref, fpp = extra_ref; --i >= 0; ++fpp) {
1258 		fp = *fpp;
1259 		simple_lock(&fp->f_slock);
1260 		FILE_USE(fp);
1261 		(void) closef(fp, (struct lwp *)0);
1262 	}
1263 	free((caddr_t)extra_ref, M_FILE);
1264 	unp_gcing = 0;
1265 }
1266 
1267 void
1268 unp_dispose(struct mbuf *m)
1269 {
1270 
1271 	if (m)
1272 		unp_scan(m, unp_discard, 1);
1273 }
1274 
1275 void
1276 unp_scan(struct mbuf *m0, void (*op)(struct file *), int discard)
1277 {
1278 	struct mbuf *m;
1279 	struct file **rp;
1280 	struct cmsghdr *cm;
1281 	int i;
1282 	int qfds;
1283 
1284 	while (m0) {
1285 		for (m = m0; m; m = m->m_next) {
1286 			if (m->m_type == MT_CONTROL &&
1287 			    m->m_len >= sizeof(*cm)) {
1288 				cm = mtod(m, struct cmsghdr *);
1289 				if (cm->cmsg_level != SOL_SOCKET ||
1290 				    cm->cmsg_type != SCM_RIGHTS)
1291 					continue;
1292 				qfds = (cm->cmsg_len - CMSG_ALIGN(sizeof(*cm)))
1293 				    / sizeof(struct file *);
1294 				rp = (struct file **)CMSG_DATA(cm);
1295 				for (i = 0; i < qfds; i++) {
1296 					struct file *fp = *rp;
1297 					if (discard)
1298 						*rp = 0;
1299 					(*op)(fp);
1300 					rp++;
1301 				}
1302 				break;		/* XXX, but saves time */
1303 			}
1304 		}
1305 		m0 = m0->m_nextpkt;
1306 	}
1307 }
1308 
1309 void
1310 unp_mark(struct file *fp)
1311 {
1312 	if (fp == NULL)
1313 		return;
1314 
1315 	if (fp->f_flag & FMARK)
1316 		return;
1317 
1318 	/* If we're already deferred, don't screw up the defer count */
1319 	if (fp->f_flag & FDEFER)
1320 		return;
1321 
1322 	/*
1323 	 * Minimize the number of deferrals...  Sockets are the only
1324 	 * type of descriptor which can hold references to another
1325 	 * descriptor, so just mark other descriptors, and defer
1326 	 * unmarked sockets for the next pass.
1327 	 */
1328 	if (fp->f_type == DTYPE_SOCKET) {
1329 		unp_defer++;
1330 		if (fp->f_count == 0)
1331 			panic("unp_mark: queued unref");
1332 		fp->f_flag |= FDEFER;
1333 	} else {
1334 		fp->f_flag |= FMARK;
1335 	}
1336 	return;
1337 }
1338 
1339 void
1340 unp_discard(struct file *fp)
1341 {
1342 	if (fp == NULL)
1343 		return;
1344 	simple_lock(&fp->f_slock);
1345 	fp->f_usecount++;	/* i.e. FILE_USE(fp) sans locking */
1346 	fp->f_msgcount--;
1347 	simple_unlock(&fp->f_slock);
1348 	unp_rights--;
1349 	(void) closef(fp, (struct lwp *)0);
1350 }
1351